/// <summary>See <see cref="Page.Render"/>.</summary> protected override void Render(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "1"); writer.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); using (new HtmlBlock(HtmlTextWriterTag.Table, 0, writer)) { using (new HtmlBlock(HtmlTextWriterTag.Tr, 0, writer)) { using (GetTd(writer)) { using (GetAnchor(writer)) { using (GetImage(writer)) { } } } using (GetTd(writer)) { using (GetAnchor(writer)) { writer.Write(SlkUtilities.GetHtmlEncodedText(Text)); } } } } }
void WriteFrame(HtmlTextWriter htmlTextWriter, string url, string nameQualifier, bool fullWidth) { bool isIpad = SlkUtilities.IsIpad(); htmlTextWriter.Write("<iframe "); if (fullWidth) { if (isIpad == false) { htmlTextWriter.Write("width=\"100%\" "); } } else { htmlTextWriter.Write(" style=\"width :"); htmlTextWriter.Write(SummaryWidth.ToString(CultureInfo.InvariantCulture)); htmlTextWriter.Write("\" "); } if (isIpad == false) { htmlTextWriter.Write(" height=\"100%\" "); } htmlTextWriter.Write(" frameborder=\"0\" src=\""); htmlTextWriter.Write(url); htmlTextWriter.Write("\" name=\""); htmlTextWriter.Write(frameId); htmlTextWriter.Write(nameQualifier); htmlTextWriter.Write("\"></iframe>"); }
private void SetUpDisplayValues(LearnerAssignmentState learnerAssignmentStatus) { lblTitle.Text = Server.HtmlEncode(AssignmentProperties.Title); lblDescription.Text = SlkUtilities.ClickifyLinks(SlkUtilities.GetCrlfHtmlEncodedText(AssignmentProperties.Description)); SetUpAssignmentSiteLink(); SetUpScoreAndGradeDisplayValues(learnerAssignmentStatus); SPTimeZone timeZone = SPWeb.RegionalSettings.TimeZone; lblStartValue.Text = FormatDateForDisplay(timeZone.UTCToLocalTime(AssignmentProperties.StartDate)); if (AssignmentProperties.DueDate.HasValue) { lblDueValue.Text = FormatDateForDisplay(timeZone.UTCToLocalTime(AssignmentProperties.DueDate.Value)); } if (LearnerAssignmentProperties.InstructorComments.Length != 0) { lblCommentsValue.Text = SlkUtilities.GetCrlfHtmlEncodedText(LearnerAssignmentProperties.InstructorComments); } else { tgrComments.Visible = false; } lblStatusValue.Text = Server.HtmlEncode(SlkUtilities.GetLearnerAssignmentState(learnerAssignmentStatus)); DisplayCustomProperties(); DisplayMixes(); }
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> /// Write the html for the table of contents to the response. /// </summary> /// <returns></returns> public void WriteToc() { SlkUtilities.RetryOnDeadlock(delegate() { // This accesses the database to get the list of nodes m_tocHelper.TocElementsHtml(Request, AssignmentView.Grading.ToString()); }); }
[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> /// Initialize the SlkError Object with passed errorType and errorText. /// </summary> internal SlkError(ErrorType errorType, string errorText) { // Initialize Object if ErrorText is not null or empty. if (!String.IsNullOrEmpty(SlkUtilities.Trim(errorText))) { m_errorType = errorType; m_errorText = errorText; } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); try { SetResourceText(); LoadGradingList(); if (!pageHasErrors) { if (SPWeb.ID != AssignmentProperties.SPWebGuid) { Response.Redirect(SlkUtilities.UrlCombine(SPWeb.Url, Request.Path + "?" + Request.QueryString.ToString())); } AddReactivationCheck(); lblTitle.Text = Server.HtmlEncode(AssignmentProperties.Title); lblDescription.Text = SlkUtilities.ClickifyLinks(Server.HtmlEncode(AssignmentProperties.Description).Replace("\r\n", "<br />\r\n")); if (AssignmentProperties.PointsPossible.HasValue) { lblPointsValue.Text = AssignmentProperties.PointsPossible.Value.ToString(Constants.RoundTrip, NumberFormatInfo); } SPTimeZone timeZone = SPWeb.RegionalSettings.TimeZone; lblStartValue.Text = FormatDateForDisplay(timeZone.UTCToLocalTime(AssignmentProperties.StartDate)); if (AssignmentProperties.DueDate.HasValue) { lblDueValue.Text = FormatDateForDisplay(timeZone.UTCToLocalTime(AssignmentProperties.DueDate.Value)); } tblAutoReturn.Visible = AssignmentProperties.AutoReturn; tblAnswers.Visible = AssignmentProperties.ShowAnswersToLearners; tgrAutoReturn.Visible = tblAutoReturn.Visible || tblAnswers.Visible; } } catch (ThreadAbortException) { // make sure this exception isn't caught throw; } catch (Exception ex) { contentPanel.Visible = false; errorBanner.AddException(SlkStore, ex); } }
void WriteSummary(HtmlTextWriter htmlTextWriter, string urlQueryString) { htmlTextWriter.Write("<td height=\"100%\" style=\"height:100%; width :"); htmlTextWriter.Write(SummaryWidth.ToString(CultureInfo.InvariantCulture)); htmlTextWriter.Write("\">"); // Get the ServerRelativeUrl for QueryResultPage string urlString = SlkUtilities.UrlCombine(SPWeb.ServerRelativeUrl, Constants.SlkUrlPath, Constants.QuerySetPage); //Append the QueryString Values urlString += urlQueryString; WriteFrame(htmlTextWriter, urlString.ToString(), "_AlwpQuerySummary", false); htmlTextWriter.Write("</td>"); }
private void ShowLearnerComments() { if (string.IsNullOrEmpty(LearnerAssignmentProperties.LearnerComments) == false) { tgrLearnerComments.Visible = true; lblLearnerCommentsValue.Visible = true; LearnerComments.Visible = false; lblLearnerCommentsValue.Text = SlkUtilities.GetCrlfHtmlEncodedText(LearnerAssignmentProperties.LearnerComments); } else { tgrLearnerComments.Visible = false; lblLearnerCommentsValue.Visible = false; LearnerComments.Visible = false; } }
/// <summary> /// writes the exeception to the event Log and outs the SlkError Object. /// </summary> /// <param name="store">The ISlkStore to write exceptions to.</param> /// <param name="ex">Exception</param> /// <returns></returns> public static SlkError WriteException(ISlkStore store, Exception ex) { SlkError slkError = null; //Check for Exception Type. For all Handled Exceptions //Add the Exception Message in Error //Or Add the Standard Error Message and //log the exception in EventLog. if (ex is SafeToDisplayException || ex is UserNotFoundException || ex is SlkNotConfiguredException || ex is NotAnInstructorException) { slkError = new SlkError(ErrorType.Error, SlkUtilities.GetHtmlEncodedText(ex.Message)); } else if (ex is UnauthorizedAccessException || ex is LearningStoreSecurityException) { slkError = new SlkError(ErrorType.Error, SlkUtilities.GetHtmlEncodedText(SlkCulture.GetResources().AccessDenied)); } else { //Set the Standard Error text SlkCulture culture = new SlkCulture(); string errorText = culture.Resources.SlkGenericError; SqlException sqlEx = ex as SqlException; if (sqlEx != null) { //check whether deadlock occured if (sqlEx.Number == 1205) { errorText = culture.Resources.SlkExWorkFlowSqlDeadLockError; } } //log the exception in EventLog. if (store != null) { store.LogException(ex); } slkError = new SlkError(ErrorType.Error, SlkUtilities.GetHtmlEncodedText(errorText)); } return(slkError); }
/// <summary> /// Control Render Method /// </summary> /// <param name="writer"></param> protected override void Render(HtmlTextWriter writer) { //Renders the Validation Error Message on Top of the Control. if (!IsValid) { if (!String.IsNullOrEmpty(SlkUtilities.Trim(this.ErrorMessage))) { Label lblErrorText = new Label(); lblErrorText.Text = SlkUtilities.GetHtmlEncodedText(this.ErrorMessage); lblErrorText.CssClass = "ms-formvalidation"; using (new HtmlBlock(HtmlTextWriterTag.Div, 0, writer)) { lblErrorText.RenderControl(writer); } } } //Render the CheckBox List RenderCustomCheckBox(writer); }
/// <summary> /// Checks for deadlock and writes the SqlExeception to the event Log and outs the SlkError Object. /// </summary> /// <param name="store">The ISlkStore to log exceptions.</param> /// <param name="sqlEx">SqlException</param> /// <returns></returns> internal static SlkError WriteException(ISlkStore store, SqlException sqlEx) { //Set the Standard Error text SlkCulture culture = new SlkCulture(); string errorText = culture.Resources.SlkGenericError; //check whether deadlock occured if (sqlEx.Number == 1205) { errorText = culture.Resources.SlkExAlwpSqlDeadLockError; } //Slk Error with Generic or dead lock error message. errorText = Constants.Space + SlkUtilities.GetHtmlEncodedText(errorText); //log the exception store.LogException(sqlEx); //Add the Error to Error Collection. return(new SlkError(ErrorType.Error, errorText)); }
private string GenerateRedirectUrl() { string redirectUrl; bool fromLobbyPage = (Request.QueryString["fl"] == "true"); if (fromLobbyPage) { string baseUrl = SlkUtilities.UrlCombine(SPWeb.ServerRelativeUrl, Constants.SlkUrlPath, "Lobby.aspx"); redirectUrl = string.Format("{0}?{1}={2}&{3}={4}", baseUrl, FramesetQueryParameter.LearnerAssignmentId, LearnerAssignmentGuid.ToString(), QueryStringKeys.Source, RawSourceUrl); } else { // From ALWP, return there redirectUrl = SourceUrl; if (string.IsNullOrEmpty(redirectUrl)) { redirectUrl = SPWeb.Url; } } return(redirectUrl); }
private void SetUpAssignmentSiteLink() { // for the assignment site, if the user doesn't have permission to view it // we'll catch the exception and hide the row bool previousValue = SPSecurity.CatchAccessDeniedException; SPSecurity.CatchAccessDeniedException = false; try { using (SPSite assignmentSite = new SPSite(AssignmentProperties.SPSiteGuid, SPContext.Current.Site.Zone)) { using (SPWeb assignmentWeb = assignmentSite.OpenWeb(AssignmentProperties.SPWebGuid)) { // If the assignment is in a different SPWeb redirect to it. if (SPWeb.ID != assignmentWeb.ID) { Response.Redirect(SlkUtilities.UrlCombine(assignmentWeb.Url, Request.Path + "?" + Request.QueryString.ToString())); } lnkSite.Text = Server.HtmlEncode(assignmentWeb.Title); lnkSite.NavigateUrl = assignmentWeb.ServerRelativeUrl; } } } catch (UnauthorizedAccessException) { lblSiteValue.Text = PageCulture.Resources.LobbyInvalidSite; lblSiteValue.Visible = true; } catch (FileNotFoundException) { lblSiteValue.Text = PageCulture.Resources.LobbyInvalidSite; lblSiteValue.Visible = true; } finally { SPSecurity.CatchAccessDeniedException = previousValue; } }
void AssignToSelf(bool useReferrerSource) { try { string source = null; if (useReferrerSource) { source = Request.UrlReferrer.ToString(); } else { source = SourceHidden.Value; } Guid learnerAssignmentGuidId = AssignmentProperties.CreateSelfAssignment(SlkStore, SPWeb, package.Location, OrganizationIndex); string url = SlkUtilities.UrlCombine(SPWeb.ServerRelativeUrl, Constants.SlkUrlPath, "Lobby.aspx"); url = String.Format(CultureInfo.InvariantCulture, "{0}?{1}={2}&{3}={4}", url, FramesetQueryParameter.LearnerAssignmentId, learnerAssignmentGuidId.ToString(), "Source", System.Web.HttpUtility.UrlEncode(source)); Response.Redirect(url, 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 (SafeToDisplayException e) { errorBanner.Clear(); errorBanner.AddError(ErrorType.Error, e.Message); } catch (Exception ex) { contentPanel.Visible = false; errorBanner.AddException(SlkStore, ex); } }
protected void slkButtonEdit_Click(object sender, EventArgs e) { try { SaveGradingList(SaveAction.SaveOnly); string url = SlkUtilities.UrlCombine(SPWeb.ServerRelativeUrl, Constants.SlkUrlPath, "AssignmentProperties.aspx"); url = String.Format(CultureInfo.InvariantCulture, "{0}?AssignmentId={1}", url, AssignmentId.ToString()); Response.Redirect(url, 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 ex) { pageHasErrors = true; errorBanner.AddException(SlkStore, ex); } }
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> /// Validates the required attributes to render AssignmentListWebPart /// Throws SafeToDisplayException If not Valid. /// </summary> private void ValidateAlwpProperties() { //Check for Current User and QuerySet Values if (SPWeb.CurrentUser == null) { throw new UserNotFoundException(culture.Resources.SlkExUserNotFound); } if (String.IsNullOrEmpty(SlkUtilities.Trim(QuerySetOverride)) == false) { // set <querySetDef> to the QuerySetDefinition named <querySetName> QuerySetDefinition querySetDef = SlkStore.Settings.FindQuerySetDefinition(QuerySetOverride, true); if (querySetDef == null) { throw new SafeToDisplayException(culture.Resources.AlwpQuerySetNotFound, QuerySetOverride); } else { defaultQueryName = querySetDef.DefaultQueryName; } } }
/// <summary> /// Check the Current User Role and Set the /// Default QuerySet accrodingly /// </summary> private void DefaultQuerySetIfRequired() { //Override the QuerySet depends on the weppart property selection and role. if (String.IsNullOrEmpty(SlkUtilities.Trim(QuerySetOverride))) { //Defaluted to Default LearnerQuerySet For all, but instructor and observer. QuerySetOverride = Constants.DefaultLearnerQuerySet; //// check for the role and assign the query set if (SlkStore.IsObserver(SPWeb)) { QuerySetOverride = Constants.DefaultObserverQuerySet; } else if (SlkStore.IsInstructor(SPWeb)) { QuerySetOverride = Constants.DefaultInstructorQuerySet; } else if (SlkStore.IsLearner(SPWeb)) { QuerySetOverride = Constants.DefaultLearnerQuerySet; } } }
private void DisplayMixes() { const string officeMixHost = "mix.office.com"; const string swayHost = "sway.com"; if (SlkUtilities.ContainsString(AssignmentProperties.Description, officeMixHost) || SlkUtilities.ContainsString(AssignmentProperties.Description, swayHost)) { MatchCollection links = SlkUtilities.FindLinks(AssignmentProperties.Description); foreach (Match match in links) { if (SlkUtilities.ContainsString(match.Value, officeMixHost)) { // It is a link to an Office Mix string embedUrl = SlkUtilities.GenerateMixUrl(match.Value); AddMix(embedUrl); } else if (SlkUtilities.ContainsString(match.Value, swayHost)) { string embedUrl = SlkUtilities.GenerateSwayUrl(match.Value); AddSway(embedUrl); } } } }
public void UpdateRenderContext(RenderContext context, StringBuilder scriptBlock, LearningSession session) { // Set values other than OutputStream and RelativePath context.EmbeddedUIResourcePath = new Uri(SlkEmbeddedUIPath, "Images/"); SetMimeTypeMapping(context.MimeTypeMapping); SetIisCompatibilityModeExtensions(context.IisCompatibilityModeExtensions); // If this is not the primary resource, nothing else matters. if (scriptBlock == null) { return; } LearnerAssignmentProperties la = GetLearnerAssignment(); switch (AssignmentView) { case AssignmentView.Execute: { context.ShowCorrectAnswers = false; context.ShowReviewerInformation = false; } break; case AssignmentView.StudentReview: { context.ShowCorrectAnswers = la.Assignment.ShowAnswersToLearners; context.ShowReviewerInformation = false; } break; case AssignmentView.InstructorReview: { context.ShowCorrectAnswers = true; context.ShowReviewerInformation = true; } break; case AssignmentView.Grading: { context.ShowCorrectAnswers = true; context.ShowReviewerInformation = true; } break; } // Update hidden controls and script to include assignment information if there is script // information to be written. Only write script in LRM content. if ((scriptBlock != null) && (session.CurrentActivityResourceType == ResourceType.Lrm)) { WriteSlkMgrInit(scriptBlock); scriptBlock.AppendLine("slkMgr = Slk_GetSlkManager();"); context.FormHiddenControls.Add(HiddenFieldNames.LearnerAssignmentId, FramesetUtil.GetStringInvariant(la.LearnerAssignmentId.GetKey())); scriptBlock.AppendFormat("slkMgr.LearnerAssignmentId = document.getElementById({0}).value;\r\n", JScriptString.QuoteString(HiddenFieldNames.LearnerAssignmentId, false)); context.FormHiddenControls.Add(HiddenFieldNames.LearnerAssignmentStatus, SlkUtilities.GetLearnerAssignmentState(la.Status)); scriptBlock.AppendFormat("slkMgr.Status = document.getElementById({0}).value;\r\n", JScriptString.QuoteString(HiddenFieldNames.LearnerAssignmentStatus, false)); // Set the change in final points. This can only happen in grading. if (AssignmentView == AssignmentView.Grading) { string finalPointsValue = "null"; float? finalPoints = la.FinalPoints; if (finalPoints != null) { // FinalPoints is invariant culture finalPointsValue = Convert.ToString(finalPoints.Value, CultureInfo.InvariantCulture.NumberFormat); } scriptBlock.AppendFormat("slkMgr.FinalPoints = {0};\r\n", finalPointsValue); } // Send information about total points (ie, computed points on the client). if (session != null) { if (session.TotalPoints != null) { // TotalPoints is passed in current culture, as a string JScriptString totalPointsValue = JScriptString.QuoteString(Convert.ToString(session.TotalPoints, CultureInfo.CurrentCulture.NumberFormat), false); scriptBlock.AppendFormat("slkMgr.ComputedPoints = {0};\r\n", totalPointsValue); } else { scriptBlock.Append("slkMgr.ComputedPoints = \"\";\r\n"); } if (session.SuccessStatus != SuccessStatus.Unknown) { scriptBlock.AppendFormat("slkMgr.PassFail = {0};\r\n", JScriptString.QuoteString(((session.SuccessStatus == SuccessStatus.Passed) ? "passed" : "failed"), false)); } } } }
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()); } }
/// <summary> /// Adds the SlkError to the Error Collection /// and makes the Error Banner visible in the Page. /// ErrorText Will be HtmlEncoded. /// </summary> /// <param name="errorType">ErrorType</param> /// <param name="errorText">Plain Error Text to be displayed</param> internal void AddError(ErrorType errorType, String errorText) { //adds the Error to the Error Collection AddHtmlErrorText(errorType, SlkUtilities.GetHtmlEncodedText(errorText)); }
/// <summary> /// Render the Custom made CheckboxControl parses the content of /// List Items and Render the Items /// </summary> /// <param name="htmlTextWriter">HtmlTextWriter</param> protected void RenderCustomCheckBox(HtmlTextWriter htmlTextWriter) { htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Cellpadding, "0"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Cellspacing, "0"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Class, "UserGenericText"); using (new HtmlBlock(HtmlTextWriterTag.Table, 1, htmlTextWriter)) { if (!String.IsNullOrEmpty(SlkUtilities.Trim(this.HeaderText))) { using (new HtmlBlock(HtmlTextWriterTag.Tr, 1, htmlTextWriter)) { htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Colspan, "2"); using (new HtmlBlock(HtmlTextWriterTag.Td, 1, htmlTextWriter)) { LiteralControl ltrl = new LiteralControl(SlkUtilities.GetHtmlEncodedText(this.HeaderText)); ltrl.RenderControl(htmlTextWriter); } } } //for each item in the collection of SlkCheckBoxItem objects render //Checkbox and Associated label Control. foreach (SlkCheckBoxItem item in this.Items) { using (new HtmlBlock(HtmlTextWriterTag.Tr, 1, htmlTextWriter)) { CheckBox checkBox = ControlToRepeat; htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Width, "1%"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Valign, "top"); using (new HtmlBlock(HtmlTextWriterTag.Td, 1, htmlTextWriter)) { checkBox.ID = item.Value; checkBox.ToolTip = item.ToolTip; checkBox.Checked = item.Selected; if (this.HasAttributes) { foreach (string text1 in this.Attributes.Keys) { checkBox.Attributes[text1] = this.Attributes[text1]; } } checkBox.RenderControl(htmlTextWriter); } htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Width, "100%"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Valign, "top"); htmlTextWriter.AddAttribute(HtmlTextWriterAttribute.Style, "border-top: none; padding-top:2px"); using (new HtmlBlock(HtmlTextWriterTag.Td, 1, htmlTextWriter)) { Label label = ControlToAssociate; label.ToolTip = item.ToolTip; label.Text = item.Text; label.AssociatedControlID = item.Value; label.RenderControl(htmlTextWriter); } } } } }
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] // exceptions caught, added to event log protected void Page_Load(object sender, EventArgs e) { try { SlkUtilities.RetryOnDeadlock(delegate() { //Initialize data that may need to be reset on retry Response.Clear(); ClearError(); m_sessionEnded = false; m_hiddenHelper = new HiddenHelper(Request, Response, SlkEmbeddedUIPath); m_hiddenHelper.ProcessPageLoad(SlkStore.PackageStore, GetSessionTitle, TryGetSessionView, TryGetAttemptId, AppendContentFrameDetails, RegisterError, GetErrorInfo, ProcessSessionEnd, ProcessViewRequest, GetMessage, IsPostBack); // Send assignment information to client. If the session has ended, then force a reload of the current // assignment properties. Otherwise, the cached value will have required info so no need to re-query database. LearnerAssignmentProperties la = GetLearnerAssignment(SessionEnded); // Add assignment information to the hidden controls HiddenControlInfo hiddenCtrlInfo = new HiddenControlInfo(); hiddenCtrlInfo.Id = new PlainTextString(HiddenFieldNames.LearnerAssignmentId); hiddenCtrlInfo.Value = new PlainTextString(FramesetUtil.GetStringInvariant(la.LearnerAssignmentId.GetKey())); hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString(ResHelper.Format("slkMgr.LearnerAssignmentId = document.getElementById({0}).value;", JScriptString.QuoteString(HiddenFieldNames.LearnerAssignmentId, false))); m_hiddenHelper.HiddenControls.Add(hiddenCtrlInfo); // Learner assignment status ('not started', 'in progress', etc) hiddenCtrlInfo = new HiddenControlInfo(); hiddenCtrlInfo.Id = new PlainTextString(HiddenFieldNames.LearnerAssignmentStatus); hiddenCtrlInfo.Value = new PlainTextString(SlkUtilities.GetLearnerAssignmentState(la.Status)); hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString(ResHelper.Format("slkMgr.Status = document.getElementById({0}).value;", JScriptString.QuoteString(HiddenFieldNames.LearnerAssignmentStatus, false))); m_hiddenHelper.HiddenControls.Add(hiddenCtrlInfo); hiddenCtrlInfo = new HiddenControlInfo(); if (la.FinalPoints != null) { // finalPoints is passed in invariant culture, as a float hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString(ResHelper.Format("slkMgr.FinalPoints = {0};", Convert.ToString(la.FinalPoints, CultureInfo.InvariantCulture.NumberFormat))); } else { hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString("slkMgr.FinalPoints = null;"); } m_hiddenHelper.HiddenControls.Add(hiddenCtrlInfo); // Send information about total points (ie, computed points on the client). This is called 'graded score' in // grading page. LearningSession session = m_hiddenHelper.Session; if (session != null) { hiddenCtrlInfo = new HiddenControlInfo(); if (session.TotalPoints != null) { // TotalPoints is passed in current culture, as a string JScriptString totalPointsValue = JScriptString.QuoteString(Convert.ToString(session.TotalPoints, CultureInfo.CurrentCulture.NumberFormat), false); hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString(ResHelper.Format("slkMgr.ComputedPoints = {0};", totalPointsValue)); } else { hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString("slkMgr.ComputedPoints = \"\";"); } m_hiddenHelper.HiddenControls.Add(hiddenCtrlInfo); if (session.SuccessStatus != SuccessStatus.Unknown) { hiddenCtrlInfo = new HiddenControlInfo(); hiddenCtrlInfo.FrameManagerInitializationScript = new JScriptString(ResHelper.Format("slkMgr.PassFail = {0};\r\n", JScriptString.QuoteString(((session.SuccessStatus == SuccessStatus.Passed) ? "passed" : "failed"), false))); m_hiddenHelper.HiddenControls.Add(hiddenCtrlInfo); } } }); } catch (Exception ex) { ClearError(); // 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> /// Process the posted data before it is saved by the shared code. This allows checking the file attachments /// and making sure they meet the requirements of the SlkSettings. /// </summary> public bool ProcessPostedData(LearningSession session, HttpRequest request, Dictionary <string, HttpPostedFile> files) { // Save initial value of FinalPoints m_initialTotalPoints = session.TotalPoints; // Check the files for validity and fill in the output collection HttpFileCollection attachedFiles = Request.Files; int numFilesAttached = attachedFiles.Count; if (numFilesAttached > 0) { // Check if posted data meets requirements in SlkSettings. Additionally, check if there are files // that refer to files that do not exist (i.e. have 0 length). int maxKb = SlkStore.Settings.MaxAttachmentKilobytes; ICollection <string> attachmentTypes = SlkStore.Settings.ApprovedAttachmentTypes; List <string> invalidFileAttachments = new List <string>(numFilesAttached); List <string> invalidFileSize = new List <string>(numFilesAttached); List <string> filesDontExist = new List <string>(numFilesAttached); // Keep track of whether there is at least bool hasInvalidFileAttachment = false; bool hasInvalidFileSize = false; bool fileExists = true; // Go through posted files and test if they meet requirements foreach (string fileKey in attachedFiles) { HttpPostedFile file = attachedFiles[fileKey]; bool fileIsValid = true; // is this file a valid file attachment? string filename = file.FileName; // If the filename is empty, the file wasn't actually attached. if (!String.IsNullOrEmpty(filename)) { if (file.ContentLength == 0) { filesDontExist.Add(filename); fileExists = false; fileIsValid = false; } else if ((file.ContentLength / 1024) > maxKb) { invalidFileSize.Add(filename); hasInvalidFileSize = true; fileIsValid = false; } if (!attachmentTypes.Contains(Path.GetExtension(filename))) { invalidFileAttachments.Add(filename); hasInvalidFileAttachment = true; fileIsValid = false; } } // else: The file was valid on a previous posting, so consider it valid here if (fileIsValid) { // Add it to the returned list of valid files files.Add(fileKey, file); } } // if any of the posted files are invalid, then we need to write the message if (hasInvalidFileSize || hasInvalidFileAttachment || !fileExists) { StringBuilder message = new StringBuilder(1000); if (hasInvalidFileAttachment) { message.Append(ResHelper.GetMessage(SlkFrameset.CON_InvalidFileExtensionMsgHtml)); message.Append("<br><br><ul>"); foreach (string filename in invalidFileAttachments) { message.AppendFormat("<li>{0}</li>", SlkUtilities.GetHtmlEncodedText(filename)); } message.Append("</ul>"); } if (hasInvalidFileSize) { message.AppendFormat(ResHelper.GetMessage(SlkFrameset.CON_MaxFileSizeExceededMsgHtml, Convert.ToString(maxKb, CultureInfo.CurrentCulture.NumberFormat))); message.Append("<br><br><ul>"); foreach (string filename in invalidFileSize) { message.AppendFormat("<li>{0}</li>", SlkUtilities.GetHtmlEncodedText(filename)); } message.Append("</ul>"); } if (!fileExists) { message.AppendFormat(SlkFrameset.CON_FilesDontExistHtml); message.Append("<br><br><ul>"); foreach (string filename in filesDontExist) { message.AppendFormat("<li>{0}</li>", SlkUtilities.GetHtmlEncodedText(filename)); } message.Append("</ul>"); } // If one of the cases that relates to SLK settings is true, then tell user that there are settings // that affect the error if (hasInvalidFileSize || hasInvalidFileAttachment) { message.AppendFormat(CultureInfo.InvariantCulture, "{0}<br><br>", ResHelper.GetMessage(SlkFrameset.CON_InvalidFileAttachmentMsgHtml)); } message.Append(FramesetResources.CON_FileAttachmentErrorEndHtml); // Add information for the 'Continue' link JScriptString js = new JScriptString(ResHelper.FormatInvariant("API_GetFramesetManager().DoChoice(\"{0}\");", FramesetUtil.GetStringInvariant(session.CurrentActivityId))); message.AppendFormat(CultureInfo.InvariantCulture, "<br><br><a href='{0}' >{1}</a>", js.ToJavascriptProtocol(), HttpUtility.HtmlEncode(FramesetResources.HID_ReloadCurrentContent)); RegisterError(SlkFrameset.CON_InvalidFileAttachmentTitleHtml, message.ToString(), false); } } return(true); }
[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(); } }
SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] // parameter is validated public void ProcessSessionEnd(LearningSession session, ref string messageTitle, ref string message) { FramesetUtil.ValidateNonNullParameter("session", session); // If we have already been here, then there is nothing more to do. if (SessionEnded) { return; } LearnerAssignmentProperties la = GetLearnerAssignment(); // Session ending results in message shown to the user. if (session.View == SessionView.Execute) { StoredLearningSession slsSession = session as StoredLearningSession; if (slsSession != null) { // The rollup and/or sequencing process may have changed the state of the attempt. If so, there are some cases // that cannot continue so show an error message. switch (slsSession.AttemptStatus) { case AttemptStatus.Abandoned: messageTitle = SlkFrameset.HID_SessionAbandonedTitle; message = SlkFrameset.HID_ExecuteViewAbandonedSessionMsg; SessionEnded = true; break; case AttemptStatus.Completed: messageTitle = SlkFrameset.HID_SessionCompletedTitle; message = SlkFrameset.HID_ExecuteViewCompletedSessionMsg; SessionEnded = true; break; case AttemptStatus.Suspended: messageTitle = SlkFrameset.HID_SessionSuspendedTitle; message = SlkFrameset.HID_ExecuteViewSuspendedSessionMsg; // Do not set SessionEnded -- the session being suspended does not warrant ending the learner assignment break; } } if (SessionEnded) { // Call FinishLearnerAssignment since the attempt has already been completed. SlkStore.FinishLearnerAssignment(LearnerAssignmentGuidId); } } else if (session.View == SessionView.RandomAccess) { messageTitle = SlkFrameset.HID_GradingFinishedTitle; message = SlkFrameset.HID_GradingFinishedMessage; StringBuilder sb = new StringBuilder(1000); sb.Append(message); sb.Append("<br><script>"); // Write the assignment status to slkFrameMgr WriteSlkMgrInit(sb); sb.AppendLine("slkMgr = Slk_GetSlkManager();"); sb.AppendFormat("slkMgr.LearnerAssignmentId = {0};\r\n", JScriptString.QuoteString(FramesetUtil.GetStringInvariant(la.LearnerAssignmentId.GetKey()), false)); sb.AppendFormat("slkMgr.Status = {0};\r\n", JScriptString.QuoteString(SlkUtilities.GetLearnerAssignmentState(la.Status), false)); if (AssignmentView == AssignmentView.Grading) { string finalPointsValue = "null"; float? finalPoints = la.FinalPoints; if (finalPoints != null) { finalPointsValue = Convert.ToString(finalPoints.Value, CultureInfo.InvariantCulture.NumberFormat); } sb.AppendFormat("slkMgr.FinalPoints = {0};\r\n", finalPointsValue); } // Send information about total points (ie, computed points on the client). if (session != null) { if (session.TotalPoints != null) { sb.AppendFormat("slkMgr.ComputedPoints = {0};\r\n", JScriptString.QuoteString(Convert.ToString(session.TotalPoints, CultureInfo.CurrentCulture.NumberFormat), false)); } else { sb.AppendFormat("slkMgr.ComputedPoints = \"\";\r\n"); } if (session.SuccessStatus != SuccessStatus.Unknown) { sb.AppendFormat("slkMgr.PassFail = {0};\r\n", JScriptString.QuoteString(((session.SuccessStatus == SuccessStatus.Passed) ? "passed" : "failed"), false)); } } } }