} // end:Constructor() public ejpXpsDocument(Stream data, string path, bool isExternalToAssignment, Guid parentStudyId) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Information, "Creating new Document", "Creating ejp wrapper for xps document with path: " + path); this._isExternalToAssignment = isExternalToAssignment; this._xpsDocumentPath = path; this._packageUri = new Uri(path, UriKind.Absolute); data.Seek(0, SeekOrigin.Begin); this._xpsPackage = Package.Open(data, FileMode.Open, FileAccess.ReadWrite); try { PackageStore.AddPackage(this._packageUri, this._xpsPackage); this._xpsDocument = new XpsDocument(this._xpsPackage, CompressionOption.Maximum, path); this.GetFixedDocumentSequenceUri(); } catch (Exception ex) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Error, "Failed to create Xps Document Instance", "\nPath: " + path + "\nIs External To Assignment: " + isExternalToAssignment.ToString() + "\nError: " + ex.Message); throw; } } // end:Constructor()
} // end:Constructor() #endregion #region Public Methods /// <summary> /// Update the file package reference that this XpsDocument /// is loaded from. /// </summary> public void UpdatePackageReference(Stream data, string path) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Information, "Updating Package Reference", "\nPath: " + path); this._xpsDocumentPath = path; this._packageUri = new Uri(path, UriKind.Absolute); data.Seek(0, SeekOrigin.Begin); this._xpsPackage = Package.Open(data, FileMode.Open, FileAccess.ReadWrite); try { PackageStore.AddPackage(this._packageUri, this._xpsPackage); this._xpsDocument = new XpsDocument(this._xpsPackage, CompressionOption.Maximum, path); this.GetFixedDocumentSequenceUri(); } catch (Exception ex) { SiliconStudio.DebugManagers.DebugReporter.Report( SiliconStudio.DebugManagers.MessageType.Error, "Failed to Update Package Reference", "\nPath: " + path + "\nError: " + ex.Message); throw; } }
public static XpsDocument GetXpsDocument(FlowDocument document) { //Uri DocumentUri = new Uri("pack://currentTicket_" + new Random().Next(1000).ToString() + ".xps"); Uri docUri = new Uri("pack://tempTicket.xps"); var ms = new MemoryStream(); { Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); PackageStore.RemovePackage(docUri); PackageStore.AddPackage(docUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, docUri.AbsoluteUri); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator docPage = ((IDocumentPaginatorSource)document).DocumentPaginator; //docPage.PageSize = new System.Windows.Size(PageWidth, PageHeight); //docPage.PageSize = new System.Windows.Size(document.PageWidth, document.PageHeight); rsm.SaveAsXaml(docPage); return(xpsDocument); } }
public static FixedDocumentSequence PaintDrawingVisual(DrawingVisual drawingVisual, PageMediaSize pageMediaSize) { FixedDocumentSequence document = null; using (var xpsStream = new MemoryStream()) { using (var package = Package.Open(xpsStream, FileMode.Create, FileAccess.ReadWrite)) { var packageUriString = "memorystream://data.xps"; var packageUri = new Uri(packageUriString); PackageStore.AddPackage(packageUri, package); var xpsDocument = new XpsDocument(package, CompressionOption.Maximum, packageUriString); var writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); var printTicket = new PrintTicket(); printTicket.PageMediaSize = pageMediaSize; writer.Write(drawingVisual, printTicket); document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); PackageStore.RemovePackage(packageUri); } } return(document); }
/// <summary> /// Loads xaml content from a WPF package. /// </summary> /// <param name="stream"> /// Stream that must be accessible for reading and structured as /// a WPF container: part XamlEntryPart is expected as one of /// its entry parts. /// </param> /// <returns> /// Returns a xaml element loaded from the entry part of the package. /// </returns> /// <exception cref="ArgumentNullException"> /// Throws parsing exception when the xaml content does not comply with the xaml schema. /// </exception> /// <exception cref="ArgumentException"> /// Throws validation exception when the package is not well structured. /// </exception> /// <exception cref="Exception"> /// Throws uri exception when the pachageBaseUri is not correct absolute uri. /// </exception> /// <remarks> /// USED IN LEXICON VIA REFLECTION /// </remarks> internal static object LoadElement(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } object xamlObject; try { WpfPayload wpfPayload = WpfPayload.OpenWpfPayload(stream); // Now load the package using (wpfPayload.Package) { // Validate WPF paypoad and get its entry part PackagePart xamlEntryPart = wpfPayload.ValidatePayload(); // Define a unique uri for this instance of PWF payload. // Uniqueness is required to make sure that cached images are not mixed up. int newWpfPayoutCount = Interlocked.Increment(ref _wpfPayloadCount); Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package // Set this temporary uri as a base uri for xaml parser ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; // Call xaml parser xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); } } catch (XamlParseException e) { // Incase of xaml parsing or package structure failure // we return null. Invariant.Assert(e != null); //to make compiler happy about not using a variable e. This variable is useful in debugging process though - to see a reason of a parsing failure xamlObject = null; } catch (System.IO.FileFormatException) { xamlObject = null; } catch (System.IO.FileLoadException) { xamlObject = null; } catch (System.OutOfMemoryException) { xamlObject = null; } return(xamlObject); }
public void LoadXps() { MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); try { //构造一个基于内存的xps document PackageStore.RemovePackage(DocumentUri); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); //将flow document写入基于内存的xps document中去 XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator); //获取这个基于内存的xps document的fixed document docViewer.Document = xpsDocument.GetFixedDocumentSequence(); //关闭基于内存的xps document xpsDocument.Close(); } catch (Exception ex) { MessageBox.Show("异常(LoadXps):\n" + ex.Message); } }
public ejpXpsDocument(string path, string title, bool isExternalToAssignment, Guid xpsDocumentId, Guid parentStudyId) { this._isExternalToAssignment = isExternalToAssignment; if (!File.Exists(path)) { throw new IOException(Application.Current.Resources["EX_Fnf_XPSNotFound"] as string); //Properties.Resources.EX_Fnf_XPSNotFound); } this._xpsDocumentPath = path; this._packageUri = new Uri(path, UriKind.Absolute); try { this._xpsDocument = new XpsDocument(path, FileAccess.ReadWrite); FileInfo fi = new FileInfo(path); this._xpsDocument.CoreDocumentProperties.Title = title; this._xpsDocument.CoreDocumentProperties.Identifier = xpsDocumentId.ToString(); this._xpsPackage = PackageStore.GetPackage(this._packageUri); if ((this._xpsPackage == null) || (this._xpsDocument == null)) { throw new Exception(Application.Current.Resources["EX_Fnf_XPSNotFound"] as string); //Properties.Resources.EX_Fnf_XPSNotFound); } this.GetFixedDocumentSequenceUri(); } catch (Exception) { } } // end:Constructor()
private void OnWindowUnloaded(object sender, RoutedEventArgs e) { try { docViewer.Document = null; if (_xpsDocument != null) { _xpsDocument.Close(); _xpsDocument = null; } if (_xpsDocPackage != null) { _xpsDocPackage.Close(); _xpsDocPackage = null; } if (!string.IsNullOrWhiteSpace(_fileName)) { PackageStore.RemovePackage(new Uri(_fileName)); } } catch { } }
static int _wpfPayloadCount; // used to disambiguate between all acts of loading from different WPF payloads. internal static object LoadElement(Stream stream) { Package package = Package.Open(stream, FileMode.Open, FileAccess.Read); WpfPayload wpfPayload = new WpfPayload(package); PackagePart xamlEntryPart = wpfPayload.GetWpfEntryPart(); int newWpfPayoutCount = _wpfPayloadCount++; Uri payloadUri = new Uri("payload://wpf" + newWpfPayoutCount, UriKind.Absolute); Uri entryPartUri = PackUriHelper.Create(payloadUri, xamlEntryPart.Uri); // gives an absolute uri of the entry part Uri packageUri = PackUriHelper.GetPackageUri(entryPartUri); // extracts package uri from combined package+part uri PackageStore.AddPackage(packageUri, wpfPayload.Package); // Register the package ParserContext parserContext = new ParserContext(); parserContext.BaseUri = entryPartUri; object xamlObject = XamlReader.Load(xamlEntryPart.GetStream(), parserContext); // Remove the temporary uri from the PackageStore PackageStore.RemovePackage(packageUri); return(xamlObject); }
private void DownloadXpsDoc(Uri theUri, string Name) { System.Net.WebClient client = new WebClient(); try { //Download the document byte[] XpsBytes = client.DownloadData(theUri); MemoryStream xpsStream = new MemoryStream(XpsBytes); Package package = Package.Open(xpsStream); //Create URI for the package Uri packageUri = new Uri(theUri.ToString()); //Need to add the Package to the PackageStore PackageStore.AddPackage(packageUri, package); //Create instance of XpsDocument XpsDocument document = new XpsDocument(package, CompressionOption.Maximum, theUri.ToString()); //Do the operation on document here //Here I am viewing the document in the DocViewer FixedDocumentSequence fixedDocumentSequence = document.GetFixedDocumentSequence(); //To view in the DocViewer DocReader.Document = fixedDocumentSequence as IDocumentPaginatorSource; //Remember to keep the Package object in PackageStore until all operations complete on document. //Remove the package from store PackageStore.RemovePackage(packageUri); //Close the Document document.Close(); } catch (XamlParseException ex) { MessageBox.Show(ex.Message, "XamlParseException", MessageBoxButton.OK); } }
SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] // arguments are validated public void ProcessPageLoad(HttpResponse response, PackageStore packageStore, TryGetViewInfo TryGetViewInfo, TryGetAttemptInfo TryGetAttemptInfo, ProcessViewRequest ProcessViewRequest, RegisterError RegisterError, string submitPageLinkText) { FramesetUtil.ValidateNonNullParameter("packageStore", packageStore); FramesetUtil.ValidateNonNullParameter("TryGetViewInfo", TryGetViewInfo); FramesetUtil.ValidateNonNullParameter("TryGetAttemptInfo", TryGetAttemptInfo); FramesetUtil.ValidateNonNullParameter("RegisterError", RegisterError); m_response = response; m_submitPageLinkText = submitPageLinkText; AttemptItemIdentifier attemptId; SessionView view; if (!TryGetViewInfo(true, out view)) return; // This is an attempt-based session if (!TryGetAttemptInfo(true, out attemptId)) { return; } m_session = new StoredLearningSession(view, new AttemptItemIdentifier(attemptId), packageStore); // If user cannot access the session, then remove the reference to the session. if (!ProcessViewRequest(view, m_session)) m_session = null; }
private async void DisplayFile(string file) { string rawXamlText; using (StreamReader streamReader = File.OpenText(file)) { rawXamlText = streamReader.ReadToEnd(); } var flowDocument = XamlReader.Load(new XmlTextReader(new StringReader(rawXamlText))) as FlowDocument; DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator; Package package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite); var packUri = new Uri("pack://temp.xps"); PackageStore.RemovePackage(packUri); PackageStore.AddPackage(packUri, package); var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString()); XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator); FixedDocument fixedDocument = xps.GetFixedDocumentSequence().References[0].GetDocument(true); await Dispatcher.BeginInvoke( new Action(() => { documentViewer.Document = fixedDocument; documentViewer.Zoom = 125; })); }
public static void SaveToPdf(this FlowDocument flowDoc, string filename) { MemoryStream xamlStream = new MemoryStream(); XamlWriter.Save(flowDoc, xamlStream); File.WriteAllBytes("d:\\file.xaml", xamlStream.ToArray()); IDocumentPaginatorSource text = flowDoc as IDocumentPaginatorSource; xamlStream.Close(); MemoryStream memoryStream = new MemoryStream(); Package pkg = Package.Open(memoryStream, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://temp.xps"; PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); DocumentPaginator pgn = text.DocumentPaginator; rsm.SaveAsXaml(pgn); MemoryStream xpsStream = new MemoryStream(); var writer = new XpsSerializerFactory().CreateSerializerWriter(xpsStream); writer.Write(doc.GetFixedDocumentSequence()); MemoryStream outStream = new MemoryStream(); NiXPS.Converter.XpsToPdf(xpsStream, outStream); File.WriteAllBytes("file.pdf", outStream.ToArray()); }
public IEnumerable <Bitmap> ToBitmap(Parameters parameters) { var pages = new List <Bitmap>(); var thread = new Thread(() => { const string inMemoryPackageName = "memorystream://inmemory.xps"; var packageUri = new Uri(inMemoryPackageName); using (var package = Package.Open(_xpsDocumentInMemoryStream)) { PackageStore.AddPackage(packageUri, package); _xpsDocument = new XpsDocument(package, CompressionOption.Normal, inMemoryPackageName); _xpsDocumentPaginator = _xpsDocument.GetFixedDocumentSequence().DocumentPaginator; for (var docPageNumber = 0; docPageNumber < PageCount; docPageNumber++) { pages.Add(ProcessPage(parameters, docPageNumber)); } PackageStore.RemovePackage(packageUri); _xpsDocument.Close(); _xpsDocument = null; } }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); thread.Join(); return(pages); }
private void ButtonClickToParse(object sender, RoutedEventArgs e) { documentMenu.Visibility = Visibility.Visible; tableHistoryMenu.Visibility = Visibility.Collapsed; var fixedDocument = new FixedDocument(); var pageContent = new PageContent(); var fixedPage = new FixedPage(); DataGrid dataGrid = new DataGrid(); using (ShopContext shopContext = new ShopContext()) { dataGrid.ItemsSource = shopContext.HistoryBuy.ToList(); } fixedPage.Children.Add(dataGrid); pageContent.Child = fixedPage; fixedDocument.Pages.Add(pageContent); var stream = new MemoryStream(); var uri = new Uri("pack://document.xps"); var package = Package.Open(stream, FileMode.Create, FileAccess.ReadWrite); PackageStore.AddPackage(uri, package); var xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri); var docWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); docWriter.Write(fixedDocument); documentViewer.Document = xpsDoc.GetFixedDocumentSequence(); }
/// <summary> /// Helper method to create page header or footer from flow document template /// </summary> /// <param name="data">enumerable report data</param> /// <returns></returns> /// <exception cref="ArgumentNullException">data</exception> public XpsDocument CreateXpsDocument(IEnumerable <ReportData> data) { if (data == null) { throw new ArgumentNullException("data"); } int count = 0; ReportData firstData = null; foreach (ReportData rd in data) { if (firstData == null) { firstData = rd; } count++; } if (count == 1) { return(CreateXpsDocument(firstData)); // we have only one ReportData object -> use the normal ReportPaginator instead } MemoryStream ms = new MemoryStream(); Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://report.xps"; PackageStore.RemovePackage(new Uri(pack)); PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, CompressionOption.NotCompressed, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)CreateFlowDocument()).DocumentPaginator; MultipleReportPaginator rp = new MultipleReportPaginator(this, data); rsm.SaveAsXaml(rp); return(doc); }
private void cmdShowFlow_Click(object sender, RoutedEventArgs e) { // Load the XPS content into memory. MemoryStream ms = new MemoryStream(); Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); Uri DocumentUri = new Uri("pack://InMemoryDocument.xps"); PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri); // Load the XPS content into a temporary file (alternative approach). //if (File.Exists("test2.xps")) File.Delete("test2.xps"); // XpsDocument xpsDocument = new XpsDocument("test2.xps", FileAccess.ReadWrite); using (FileStream fs = File.Open("FlowDocument1.xaml", FileMode.Open)) { FlowDocument doc = (FlowDocument)XamlReader.Load(fs); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)doc).DocumentPaginator); // Display the new XPS document in a viewer. docViewer.Document = xpsDocument.GetFixedDocumentSequence(); xpsDocument.Close(); } }
public void SaveAs() { //SiliconStudio.DebugManagers.DebugReporter.Report( // SiliconStudio.DebugManagers.MessageType.Information, // "EjpLib - ejpAssignment", // "Saving Assignment As" + // "\nTitle: " + this.MetaData.Title + // "\nPath: " + this._filePackagePath); //holds the uris to the Xps packages before they are updated in the //save as operation. 080405 //here we also need to update the km entities parent doc ID link. List <Uri> oldPackageStoreUris = new List <Uri>(); foreach (ejpStudy study in this._studies) { foreach (ejpXpsDocument xpsD in study.XpsDocuments) { oldPackageStoreUris.Add(xpsD.PackageUri); xpsD.XpsDocument.CoreDocumentProperties.Identifier = Helpers.IdManipulation.GetNewGuid().ToString(); } } EjpLib.AssignmentOperations.LocalAssignmentFileOperations.SaveAssignmentAs(this); //remove all the old PackageUris from the Store. 080405 foreach (Uri puri in oldPackageStoreUris) { PackageStore.RemovePackage(puri); } this.IsPersisted = true; }
/// <summary> /// Helper method to create page header or footer from flow document template /// </summary> /// <param name="data">enumerable report data</param> /// <param name="fileName">file to save XPS to</param> /// <returns></returns> public XpsDocument CreateXpsDocument(IEnumerable <ReportData> data, string fileName) { if (data == null) { throw new ArgumentNullException("data"); } int count = 0; ReportData firstData = null; foreach (ReportData rd in data) { if (firstData == null) { firstData = rd; } count++; } if (count == 1) { return(CreateXpsDocument(firstData)); // we have only one ReportData object -> use the normal ReportPaginator instead } Package pkg = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite); string pack = "pack://report.xps"; PackageStore.RemovePackage(new Uri(pack)); PackageStore.AddPackage(new Uri(pack), pkg); XpsDocument doc = new XpsDocument(pkg, _xpsCompressionOption, pack); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); MultipleReportPaginator rp = new MultipleReportPaginator(this, data); rsm.SaveAsXaml(rp); rsm.Commit(); pkg.Close(); return(new XpsDocument(fileName, FileAccess.Read)); }
/// <summary> /// Helper method to create page header o footer from flow document template /// </summary> /// <param name="fd"></param> /// <param name="pageDef"></param> /// <returns></returns> public static XpsDocument CreateXpsDocument(FlowDocument fd, PageDefinition pageDef) { const string pack = "pack://report.xps"; //var ms = new MemoryStream(); //Package pkg = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); //PackageStore.RemovePackage(new Uri(pack)); //PackageStore.AddPackage(new Uri(pack), pkg); //var doc = new XpsDocument(pkg, CompressionOption.SuperFast, pack); //var rsm = new XpsSerializationManager(new XpsPackagingPolicy(doc), false); //DocumentPaginator paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator; //var rp = new ReportPaginator(paginator, new Size(96/2.54*21, 96/2.54*28.7), pageDef);//PrintHelper.GetPageSize() //rsm.SaveAsXaml(rp); //return doc; var ms = new MemoryStream(); var package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); var doc = new XpsDocument(package, CompressionOption.SuperFast, pack); PackageStore.AddPackage(new Uri(pack), package); DocumentPaginator paginator = ((IDocumentPaginatorSource)fd).DocumentPaginator; XpsDocument.CreateXpsDocumentWriter(doc).Write(paginator); //ReplacePngsWithJpegs(package); //var fixedDoc = doc.GetFixedDocumentSequence(); //fixedDoc.DocumentPaginator.PageSize = GetPaperSize(reportPaperSize); return(doc); }
private static Uri GetStructureUriFromRelationship(Uri contentUri, string relationshipName) { Uri result = null; if (contentUri != null && relationshipName != null) { Uri partUri = PackUriHelper.GetPartUri(contentUri); if (partUri != null) { Uri packageUri = PackUriHelper.GetPackageUri(contentUri); Package package = PreloadedPackages.GetPackage(packageUri); if (package == null && SecurityHelper.CheckEnvironmentPermission()) { package = PackageStore.GetPackage(packageUri); } if (package != null) { PackagePart part = package.GetPart(partUri); PackageRelationshipCollection relationshipsByType = part.GetRelationshipsByType(relationshipName); Uri uri = null; foreach (PackageRelationship packageRelationship in relationshipsByType) { uri = PackUriHelper.ResolvePartUri(partUri, packageRelationship.TargetUri); } if (uri != null) { result = PackUriHelper.Create(packageUri, uri); } } } } return(result); }
}// end:OnClose() // --------------------------- CloseDocument -------------------------- /// <summary> /// Closes the document currently displayed in /// the DocumentViewer control.</summary> public void CloseDocument() { // Shut down the annotationsHelper. _annotHelper.StopAnnotations(); // Remove the document from the DocumentViewer control. docViewer.Document = null; // If the package is open, close it. if (_xpsPackage != null) { _xpsPackage.Close(); _xpsPackage = null; } if (_packageUri != null) { PackageStore.RemovePackage(_packageUri); } // Disable document-related selections when there's no document. menuFileClose.IsEnabled = false; menuFilePrint.IsEnabled = false; menuViewAnnotations.IsEnabled = false; menuViewIncreaseZoom.IsEnabled = false; menuViewDecreaseZoom.IsEnabled = false; }// end:CloseDocument
public void SaveAs(bool UpdatePackageStore) { //Updated to take a bool to determine if the package store should be updated 081128 //holds the uris to the Xps packages before they are updated in the //save as operation. 080405 //here we also need to update the km entities parent doc ID link. List <Uri> oldPackageStoreUris = new List <Uri>(); foreach (ejpStudy study in this._studies) { foreach (ejpXpsDocument xpsD in study.XpsDocuments) { oldPackageStoreUris.Add(xpsD.PackageUri); xpsD.XpsDocument.CoreDocumentProperties.Identifier = Helpers.IdManipulation.GetNewGuid().ToString(); } } EjpLib.AssignmentOperations.LocalAssignmentFileOperations.SaveAssignmentAs(this); //remove all the old PackageUris from the Store. 080405 if (UpdatePackageStore) { foreach (Uri puri in oldPackageStoreUris) { PackageStore.RemovePackage(puri); } } this.IsPersisted = true; }
public static void PrintXps(FlowDocument document, bool printDirect = true) { try { Uri DocumentUri = new Uri("pack://currentTicket.xps"); var ms = new MemoryStream(); { using (Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite)) { PackageStore.AddPackage(DocumentUri, package); XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, DocumentUri.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument); writer.Write(((IDocumentPaginatorSource)document).DocumentPaginator); if (printDirect) { PrintXpsToPrinter(xpsDocument); } PackageStore.RemovePackage(DocumentUri); xpsDocument.Close(); package.Close(); } } } catch (Exception ex) { // log the exceptions LogService.Error("Print Error", ex); } }
// Print Preview public void PrintPreview(FixedDocument fixeddocument, CancellationToken ct) { // Was cancellation already requested? if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } MemoryStream ms = new MemoryStream(); using (Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite)) { Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u, p); XpsDocument doc = new XpsDocument(p, CompressionOption.Maximum, u.AbsoluteUri); XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); //writer.Write(fixeddocument.DocumentPaginator); Dispatcher.Invoke(new Action <DocumentPaginator>(writer.Write), fixeddocument.DocumentPaginator); FixedDocumentSequence fixedDocumentSequence = doc.GetFixedDocumentSequence(); var previewWindow = new PrintPreview(fixedDocumentSequence); Action closeAction = () => previewWindow.Close(); ct.Register(() => previewWindow.Dispatcher.Invoke(closeAction) ); previewWindow.ShowDialog(); PackageStore.RemovePackage(u); doc.Close(); } }
private void Page_Loaded(object sender, RoutedEventArgs e) { // Getting a Stream out of the Resource file, strDocument string strDocument = "View.Help.legendgenerator_english.xps"; string strSchemaPath = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + "." + strDocument; Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(strSchemaPath); // Getting the length of the Stream we just obtained int length = (int)stream.Length; // Setting up a new MemoryStream and Byte Array MemoryStream ms = new MemoryStream(); ms.Capacity = (int)length; byte[] buffer = new byte[length]; // Copying the Stream to the Byte Array (Buffer) stream.Read(buffer, 0, length); // Copying the Byte Array (Buffer) to the MemoryStream ms.Write(buffer, 0, length); // Setting up a new Package based on the MemoryStream Package pkg = Package.Open(ms); // Putting together a Uri for the Package using the document name (strDocument) string strMemoryPackageName = string.Format("memorystream://{0}.xps", "legendgenerator_english.xps"); Uri packageUri = new Uri(strMemoryPackageName); // Adding the Package to PackageStore using the Uri if (PackageStore.GetPackage(packageUri) == null) { PackageStore.AddPackage(packageUri, pkg); } // Finally, putting together the XpsDocument doc = new XpsDocument(pkg, CompressionOption.Maximum, strMemoryPackageName); // Feeding the DocumentViewer, which was declared at Design Time as a variable called "viewer" documentViewer1.Document = doc.GetFixedDocumentSequence(); documentViewer1.FitToWidth(); documentViewer1.FitToHeight(); }
/// <summary> /// CHOOSING PRINT TO PAPER OR PRINT TO WINDOWS /// </summary> /// <param name="doc"></param> private void PrintToReal(FlowDocument doc) { // Create IDocumentPaginatorSource from FlowDocument IDocumentPaginatorSource idpSource = doc; if (!isShowReview) { // Call PrintDocument method to send document to printer printDlg.PrintDocument(idpSource.DocumentPaginator, "bill printing"); } else { // convert FlowDocument to FixedDocument var paginator = idpSource.DocumentPaginator; var package = Package.Open(new MemoryStream(), FileMode.Create, FileAccess.ReadWrite); var packUri = new Uri("pack://temp.xps"); PackageStore.RemovePackage(packUri); PackageStore.AddPackage(packUri, package); var xps = new XpsDocument(package, CompressionOption.NotCompressed, packUri.ToString()); XpsDocument.CreateXpsDocumentWriter(xps).Write(paginator); FixedDocument fdoc = xps.GetFixedDocumentSequence().References[0].GetDocument(true); DocumentViewer previewWindow = new DocumentViewer { Document = fdoc }; Window printpriview = new Window(); printpriview.Content = previewWindow; printpriview.Title = "Print Preview"; printpriview.Show(); } }
private void OnWindowClosing(object sender, CancelEventArgs e) { try { docViewer.Document = null; if (_xpsDocument != null) { _xpsDocument.Close(); _xpsDocument = null; } if (_xpsDocPackage != null) { _xpsDocPackage.Close(); _xpsDocPackage = null; } if (!String.IsNullOrEmpty(_fileName)) { PackageStore.RemovePackage(new Uri(_fileName)); } } catch { } }
private void ShowPrintPreview() { // We have to clone the FlowDocument before we use different pagination settings for the export. RichTextDocument document = (RichTextDocument)fileService.ActiveDocument; FlowDocument clone = document.CloneContent(); clone.ColumnWidth = double.PositiveInfinity; // Create a package for the XPS document MemoryStream packageStream = new MemoryStream(); package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite); // Create a XPS document with the path "pack://temp.xps" PackageStore.AddPackage(new Uri(PackagePath), package); xpsDocument = new XpsDocument(package, CompressionOption.SuperFast, PackagePath); // Serialize the XPS document XpsSerializationManager serializer = new XpsSerializationManager(new XpsPackagingPolicy(xpsDocument), false); DocumentPaginator paginator = ((IDocumentPaginatorSource)clone).DocumentPaginator; serializer.SaveAsXaml(paginator); // Get the fixed document sequence FixedDocumentSequence documentSequence = xpsDocument.GetFixedDocumentSequence(); // Create and show the print preview view PrintPreviewViewModel printPreviewViewModel = printPreviewViewModelFactory.CreateExport().Value; printPreviewViewModel.Document = documentSequence; previousView = shellViewModel.ContentView; shellViewModel.ContentView = printPreviewViewModel.View; shellViewModel.IsPrintPreviewVisible = true; printPreviewCommand.RaiseCanExecuteChanged(); }
}// end:OnClose() // --------------------------- CloseDocument -------------------------- /// <summary> /// Closes the document currently displayed in /// the DocumentViewer control.</summary> public void CloseDocument() { // Remove the document from the DocumentViewer control. docViewer.Document = null; // If the package is open, close it. if (_xpsPackage != null) { _xpsPackage.Close(); _xpsPackage = null; } if (_packageUri != null) PackageStore.RemovePackage(_packageUri); // Disable document-related selections when there's no document. menuFileClose.IsEnabled = false; menuFilePrint.IsEnabled = false; menuViewIncreaseZoom.IsEnabled = false; menuViewDecreaseZoom.IsEnabled = false; WriteStatus("Closed '" + _xpsDocumentName + "'"); WritePrompt( "Click 'File | Open...' to select a file to open and view."); // Close the XrML file. CloseXrML(); }// end:CloseDocument
}// end:OnClose() // --------------------------- CloseDocument -------------------------- /// <summary> /// Closes the document currently displayed in /// the DocumentViewer control.</summary> public void CloseDocument() { if (_xpsFile != null) { ShowStatus("Closing '" + Filename(_xpsFile) + "'"); DocViewer.Document = null; _xpsFile = null; } // If the package is open, close it. if (_xpsPackage != null) { _xpsPackage.Close(); _xpsPackage = null; } // The package is closed, remove it from the store. if (_packageUri != null) { PackageStore.RemovePackage(_packageUri); _packageUri = null; } // Disable document-related selections when there's no document. menuFileClose.IsEnabled = false; menuFilePrint.IsEnabled = false; menuViewIncreaseZoom.IsEnabled = false; menuViewDecreaseZoom.IsEnabled = false; this.Title = "RightsManagedPackageViewer SDK Sample"; ShowPrompt( "Click 'File | Open...' to select a file to open and view."); rightsBlock.Text = ""; }// end:CloseDocument
// it's not worth changing this now public void ProcessPageLoad( PackageStore packageStore, bool firstRendering, // frameset is being initialized bool isPostBack, // page was posted TryGetViewInfo tryGetViewInfo, TryGetAttemptInfo tryGetAttemptInfo, TryGetActivityInfo tryGetActivityInfo, GetResourcePath getResourcePath, AppendContentFrameDetails appendContentFrameDetails, UpdateRenderContext updateRenderContext, ProcessPostedData processPostedData, ProcessViewRequest processViewRequest, ProcessPostedDataComplete processPostedDataComplete, RegisterError registerError, GetErrorInfo getErrorInfo, GetFramesetMsg getFramesetMsg) { this.RegisterError = registerError; this.UpdateRenderContext = updateRenderContext; this.GetErrorInfo = getErrorInfo; this.AppendContentFrameDetails = appendContentFrameDetails; this.GetFramesetMsg = getFramesetMsg; this.mIsPostedPage = isPostBack; // If this is the first time the page is being rendered, just show 'please wait' and return. if (firstRendering) { // Initial page rendering, show "please wait" WritePleaseWaitToResponse(this.Response); this.Response.End(); return; } SessionView view; // Get View information. It determines what else to look for. if (!tryGetViewInfo(true, out view)) { return; } // There is something to display, so process the request... AttemptItemIdentifier attemptId; if (!tryGetAttemptInfo(true, out attemptId)) { return; } StoredLearningSession slsSession = new StoredLearningSession(view, attemptId, packageStore); if (!processViewRequest(view, slsSession)) { return; } this.Session = slsSession; if (slsSession.View == SessionView.Execute) { // Check if the session can be executed... if (slsSession.AttemptStatus != AttemptStatus.Active) { this.RegisterError( this.GetFramesetMsg(FramesetStringId.CannotDisplayContentTitle), this.GetFramesetMsg(FramesetStringId.SessionIsNotActiveMsg), false); return; } if (!slsSession.CurrentActivityIsActive) { this.RegisterError( this.GetFramesetMsg(FramesetStringId.SelectActivityTitleHtml), this.GetFramesetMsg(FramesetStringId.SelectActivityMessageHtml), true); return; } } else if (slsSession.View == SessionView.Review) { // Get information about which activity to review, then make that the current activity. long activityId = -1; // make compiler happy if (!tryGetActivityInfo(true, out activityId)) { return; } // Move to the requested activity. Under normal conditions, this should always succeed, since the frameset should be // giving this page a valid activity id. MoveToActivity(slsSession, activityId); } else if (slsSession.View == SessionView.RandomAccess) { // Get information about which activity to edit, then make that the current activity. long activityId = -1; // make compiler happy if (!tryGetActivityInfo(true, out activityId)) { return; } // Move to the requested activity. Under normal conditions, this should always succeed, since the frameset should be // giving this page a valid activity id. MoveToActivity(slsSession, activityId); } if (isPostBack /* && !SessionEnded */) { // Process information from posted content if (!this.SessionIsReadOnly) { HttpFileCollection files = this.Request.Files; int numFiles = files.Count; Dictionary<string, HttpPostedFile> newFileCollection = new Dictionary<string, HttpPostedFile>(numFiles); // Allow the application to process the form data if (!processPostedData(slsSession, this.Request, newFileCollection)) { return; } // Allow MLC to process the form data this.Session.ProcessFormData(this.Request.Form, newFileCollection); // Allow application to do final processing after all posted data is processed. processPostedDataComplete(this.Session); // If there was an error in processing form data, end the processing. This allows, for instance, to // save the data, display an error and not have commands (such as 'move to next activity') executed. if (this.HasError) { this.Session.CommitChanges(); return; } } // Issue with Review view: where to get activity id? From URL or posted data? // Find out what the commands are and do them. ICollection<CommandInfo> commands = this.GetCommands(); foreach (CommandInfo cmdInfo in commands) { switch (cmdInfo.Command) { case Commands.DoNext: { // When leaving a current activity, we must allow navigation requests the SCO has made to be // executed. If that results in changing the current activity, then do not also ask for another // move. if (!ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToNextValid()) { MoveToNextActivity(this.Session); this.ActivityHasChanged = true; } } else { this.ActivityHasChanged = true; } if (!this.ActivityHasChanged) { // Moving to the next activity is not valid. this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToNextFailedHtml), this.ThemeFolderPath), true); } } break; case Commands.DoPrevious: { if (!ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToPreviousValid()) { MoveToPreviousActivity(this.Session); this.ActivityHasChanged = true; } } else { this.ActivityHasChanged = true; } if (!this.ActivityHasChanged) { // Moving to the previous activity is not valid. this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToPreviousFailedHtml), this.ThemeFolderPath), true); } } break; case Commands.DoChoice: case Commands.DoTocChoice: { // These commands are used to navigate to activities, and to navigate to the final 'submit' page. // In SCORM content, these commands do different things. In LRM content (which is what we are // in, since this is the posted page), they have identical effects. // First check whether this is a request for the submit page or an activity. string cmdData = cmdInfo.CommandData; if (string.CompareOrdinal(cmdData, SubmitId) == 0) { // Requesting submit page. Do not change the current activity, but mark it as changed so that // it appears to the user that it has changed. this.ActivityHasChanged = true; string title = this.GetFramesetMsg(FramesetStringId.SubmitPageTitleHtml); string message; string saveBtn = this.GetFramesetMsg(FramesetStringId.SubmitPageSaveButtonHtml); if (this.Session.HasCurrentActivity) { message = this.GetFramesetMsg(FramesetStringId.SubmitPageMessageHtml); } else { message = this.GetFramesetMsg(FramesetStringId.SubmitPageMessageNoCurrentActivityHtml); } this.WriteSubmitPage(title, message, saveBtn); } else { long activityId; if (long.TryParse(cmdData, out activityId)) { // If the requested activity is the current activity, then do not do the navigation. // We skip it because moving to the activity basically exits the current attempt and creates // a new one. That new one also increments the attempt count. If we don't do the move, we // pretend it was done. This will force the content frame to be reloaded with the current // activity. if (this.IsCurrentActiveActivity(activityId)) { this.ActivityHasChanged = true; } else { if (!ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToActivityValid(activityId)) { MoveToActivity(this.Session, activityId); this.ActivityHasChanged = true; } } else { this.ActivityHasChanged = true; } } } } if (!this.ActivityHasChanged) { // Moving to the selected activity is not valid. this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToActivityFailedHtml), this.ThemeFolderPath), true); } } break; case Commands.DoSave: { // Do nothing. The information will be saved since the page was posted. } break; case Commands.DoSubmit: { if (this.Session.View == SessionView.Execute) { ProcessNavigationRequests(this.Session); this.Session.Exit(); } this.ActivityHasChanged = true; } break; } } } // If an error has been registered (and it's not the submit // page rendering), don't attempt to render the content. if (this.HasError && !this.SubmitPageDisplayed) { if (!this.SessionIsReadOnly) { this.Session.CommitChanges(); } return; } // There was no error, so go ahead and render the content from the package. // If the current activity has changed in the processing of this page, then render the current activity's resource. // Otherwise, ask the application which resource to read. if (this.ActivityHasChanged) { // If the activity has changed, we render the content page without rendering the content. The page will then // reload the content frame with the new activity. if (!this.SessionIsReadOnly) { this.Session.CommitChanges(); } } else { // Render the requested file in the current activity. this.RenderPackageContent(getResourcePath()); // If there was no error, end the response. Otherwise, we wait and render the error on the page. if (!this.HasError) { this.Response.End(); } } }
// it's not worth changing this now public void ProcessPageLoad( PackageStore packageStore, GetSessionTitle getSessionTitle, TryGetViewInfo tryGetViewInfo, TryGetAttemptInfo tryGetAttemptInfo, AppendContentFrameDetails appendContentFrameDetails, RegisterError registerError, GetErrorInfo getErrorInfo, ProcessSessionEnd processSessionEnd, ProcessViewRequest processViewRequest, GetFramesetMsg getFramesetMsg, // messages that appear that are unique to different framesets bool isPostBack) { try { this.RegisterError = registerError; this.GetErrorInfo = getErrorInfo; this.AppendContentFrameDetails = appendContentFrameDetails; this.GetFramesetMsg = getFramesetMsg; this.mGetSessionTitle = getSessionTitle; this.mIsPostedPage = isPostBack; AttemptItemIdentifier attemptId; SessionView view; this.LoadContentFrame = true; this.ActivityHasChanged = false; if (!tryGetViewInfo(false, out view)) { this.WriteError( ResHelper.GetMessage(Localization.GetMessage("FRM_ViewNotSupportedMsg"))); return; } switch (view) { case SessionView.Execute: { if (!tryGetAttemptInfo(false, out attemptId)) { return; } this.Session = new StoredLearningSession(view, attemptId, packageStore); if (!processViewRequest(view, this.Session)) { return; } // If the session has ended, allow the application to deal with it. processSessionEnd(this.Session, ref this.mSessionEndedMsgTitle, ref this.mSessionEndedMsg); } break; case SessionView.Review: { if (!tryGetAttemptInfo(false, out attemptId)) { return; } this.Session = new StoredLearningSession(view, attemptId, packageStore); // Do not set logging options in review view. if (!processViewRequest(view, this.Session)) { return; } } break; case SessionView.RandomAccess: { // Note: RandomAccess is not supported in BWP, however that would have been caught before // displaying this frame. if (!tryGetAttemptInfo(false, out attemptId)) { return; } this.Session = new StoredLearningSession(view, attemptId, packageStore); // Do not set logging options in random access view. if (!processViewRequest(view, this.Session)) { return; } // Move to the first activity with a resource. MoveToNextActivity(this.Session); } break; default: this.WriteError( ResHelper.GetMessage( Localization.GetMessage("FRM_ViewNotSupportedMsg"))); return; } // If the page is posted, process posted data. Remember that all posted data should be considered hostile! // Note that if the session has already ended, then none of the posted data is saved or processed. if (isPostBack && !this.SessionIsEnded) { // Process any datamodel changes before doing any navigation. This does not save any data. this.ProcessDataModelValues( this.Request.Form[HiddenFieldNames.DataModel], this.Request.Form[HiddenFieldNames.ObjectiveIdMap]); // Assume we do not have to reload the content frame this.ActivityHasChanged = false; this.LoadContentFrame = false; // if the view requires more data, get it if ((this.Session.View == SessionView.Review) || (this.Session.View == SessionView.RandomAccess)) { // Get the current activity from the posted data and set the session to that activity string strActivityId = this.Request.Form[HiddenFieldNames.ActivityId]; long activityId; if (string.IsNullOrEmpty(strActivityId) || !long.TryParse(strActivityId, out activityId)) { this.WriteError( ResHelper.GetMessage( Localization.GetMessage("HID_InvalidActivityId"), strActivityId)); } else { MoveToActivity(this.Session, activityId); } } // Find out what the commands are and do them. this.mSaveOnly = true; ICollection<CommandInfo> commands = this.GetCommands(); foreach (CommandInfo cmdInfo in commands) { switch (cmdInfo.Command) { case Commands.DoNext: { if (!this.Session.HasCurrentActivity || !ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToNextValid()) { MoveToNextActivity(this.Session); this.ActivityHasChanged = true; this.LoadContentFrame = true; } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; continue; } } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; } if (!this.ActivityHasChanged) { // Moving to the next activity is not valid. It's possible that when the current // activity was unloaded, it exited or suspended itself. If that's the case, we // try to reactivate it. Note this causes the attempt count on the activity to // increment, so on "poorly" written content, the user may not see their data // anymore. this.ActivateCurrentActivity(); this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToNextFailedHtml), this.ThemeFolderPath), true); } this.mSaveOnly = false; } break; case Commands.DoPrevious: { if (!this.Session.HasCurrentActivity || !ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToPreviousValid()) { MoveToPreviousActivity(this.Session); this.ActivityHasChanged = true; this.LoadContentFrame = true; } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; continue; } } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; } if (!this.ActivityHasChanged) { // Moving to the previous activity is not valid. It's possible that when the current // activity was unloaded, it exited or suspended itself. If that's the case, we // try to reactivate it. Note this causes the attempt count on the activity to // increment, so on "poorly" written content, the user may not see their data // anymore. this.ActivateCurrentActivity(); this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToPreviousFailedHtml), this.ThemeFolderPath), true); } this.mSaveOnly = false; } break; case Commands.DoChoice: { // This command is used to navigate to activities, primarily from either within a link in an // error page, or the submit page returning to the current activity. This command does not // create a new attempt if the requested activity is already the current activity. // Requesting to move to a specific activity. The cmdData will include a numeric activity id. string cmdData = cmdInfo.CommandData; long activityId; if (long.TryParse(cmdData, out activityId)) { // If the requested activity is the current activity, then do not do the navigation. // We skip it because moving to the activity basically exits the current attempt and creates // a new one and in this case, that is not the desired behavior. // That new one also increments the attempt count. If we don't do the move, we // pretend it was done. This will force the content frame to be reloaded with the current // activity. if (this.IsCurrentActiveActivity(activityId)) { this.ActivityHasChanged = true; this.LoadContentFrame = true; } else { // If there is no current activity, or if any navigation requests did not // result in a move, then continue with the choice. if (!this.Session.HasCurrentActivity || !ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToActivityValid(activityId)) { MoveToActivity(this.Session, activityId); this.ActivityHasChanged = true; this.LoadContentFrame = true; } } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; } } } if (!this.ActivityHasChanged) { // Moving to the selected activity is not valid. It's possible that when the current // activity was unloaded, it exited or suspended itself. If that's the case, we // try to reactivate it. Note this causes the attempt count on the activity to // increment, so on "poorly" written content, the user may not see their data // anymore. this.ActivateCurrentActivity(); this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToActivityFailedHtml), this.ThemeFolderPath), true); } this.mSaveOnly = false; } break; case Commands.DoTocChoice: { // This command is used to navigate to activities in response to a user selecting a node // in the TOC. In this case, even if the current activity is the activity that is requested, // then a MoveToActivity() is requested. This will cause the attempt count on the activity // to be incremented and the RTE to be reinitialized. This may be a surprise to the user, but // is a requirement of the SCORM 2004 conformance tests. // If the selected page is the submit page (either in Execute or RandomAccess views), then // display the message and don't ask the session to move to a new activity. string cmdData = cmdInfo.CommandData; if (string.CompareOrdinal(cmdData, SubmitId) == 0) { // Requesting submit page. Do not change the current activity, but mark it as changed so that // it appears to the user that it has changed. this.ActivityHasChanged = true; this.LoadContentFrame = true; string title = this.GetFramesetMsg(FramesetStringId.SubmitPageTitleHtml); string message; string saveBtn = this.GetFramesetMsg(FramesetStringId.SubmitPageSaveButtonHtml); if (this.Session.HasCurrentActivity) { message = this.GetFramesetMsg(FramesetStringId.SubmitPageMessageHtml); } else { message = this.GetFramesetMsg( FramesetStringId.SubmitPageMessageNoCurrentActivityHtml); } this.WriteSubmitPage(title, message, saveBtn); } else { // Requesting to move to a specific activity. The cmdData will include a numeric activity id. long activityId; if (long.TryParse(cmdData, out activityId)) { // If there is no current activity, or if any navigation requests did not // result in a move, then continue with the choice. if (!this.Session.HasCurrentActivity || !ProcessNavigationRequests(this.Session)) { if (this.Session.IsMoveToActivityValid(activityId)) { MoveToActivity(this.Session, activityId); this.ActivityHasChanged = true; this.LoadContentFrame = true; } } else { this.ActivityHasChanged = true; this.LoadContentFrame = true; } } } if (!this.ActivityHasChanged) { // Moving to the selected activity is not valid. It's possible that when the current // activity was unloaded, it exited or suspended itself. If that's the case, we // try to reactivate it. Note this causes the attempt count on the activity to // increment, so on "poorly" written content, the user may not see their data // anymore. this.ActivateCurrentActivity(); this.WriteError( ResHelper.Format( this.GetFramesetMsg(FramesetStringId.MoveToActivityFailedHtml), this.ThemeFolderPath), true); } this.mSaveOnly = false; } break; case Commands.DoIsChoiceValid: { string activityKey = cmdInfo.CommandData; bool isValid = false; if (!string.IsNullOrEmpty(activityKey)) { isValid = this.Session.IsMoveToActivityValid(activityKey); } this.mIsNavValidResponse = new IsNavValidResponseData( Commands.DoIsChoiceValid, activityKey, isValid); this.mSaveOnly = false; } break; case Commands.DoIsNavigationValid: { string navCommand = cmdInfo.CommandData; if (!string.IsNullOrEmpty(navCommand)) { bool isValid = false; if (navCommand == Commands.DoNext) { isValid = this.Session.IsMoveToNextValid(); } else if (navCommand == Commands.DoPrevious) { isValid = this.Session.IsMoveToPreviousValid(); } this.mIsNavValidResponse = new IsNavValidResponseData( Commands.DoIsNavigationValid, navCommand, isValid); } this.mSaveOnly = false; } break; case Commands.DoSave: { // Do nothing. The information will be saved since the page was posted. } break; case Commands.DoTerminate: { // end the current activity try { if (this.Session.View == SessionView.Execute) { // Keep track of state before calling ProcessNavigationRequests so that we can // detect if the call changes it in a way that requires reloading the content frame. long activityBeforeNavigation = this.Session.CurrentActivityId; int activityAttemptCount = this.Session.CurrentActivityDataModel.ActivityAttemptCount; LearningSession session = this.Session; if (session.HasCurrentActivity) { session.ProcessNavigationRequests(); } // The activity has changed if... // ... the session now does not have a current activity (since it did before we did the ProcessNavRequests call, OR // ... the session's current activity is not activity anymore (since it was before the call), OR // ... the session's activity id has changed // ... the session's activity id has not changed, but the attempt count has if (!session.HasCurrentActivity) { this.ActivityHasChanged = true; this.LoadContentFrame = true; } else if ((session.View == SessionView.Execute) && (!this.Session.CurrentActivityIsActive)) { // In Execute view, it started as active or would have thrown an exception. this.ActivityHasChanged = true; // do not load content frame, as that causes messages to flash while switching activities this.LoadContentFrame = false; } else if (activityBeforeNavigation != session.CurrentActivityId) { // The current activity has changed. this.ActivityHasChanged = true; this.LoadContentFrame = true; } else if ((activityBeforeNavigation == session.CurrentActivityId) && (activityAttemptCount != session.CurrentActivityDataModel.ActivityAttemptCount)) { // The activity has not changed, but the attempt count has. this.ActivityHasChanged = true; this.LoadContentFrame = true; } else { // In all other cases, it has not changed this.ActivityHasChanged = false; this.LoadContentFrame = false; } } else if ((this.Session.View == SessionView.Review) || (this.Session.View == SessionView.RandomAccess)) { // The activity has changed simply by calling this. This allows the client RTE to reinitialize and behave // as if navigation has happened. this.ActivityHasChanged = true; this.LoadContentFrame = true; } } catch (SequencingException ex) { this.WriteError( ResHelper.GetMessage( Localization.GetMessage("HID_TerminateFailed"), HttpUtility.HtmlEncode(ex.Message))); } this.mSaveOnly = false; } break; case Commands.DoSubmit: { // Submit the attempt -- meaning, do an ExitAll if (this.Session.View == SessionView.Execute) { if (this.Session.HasCurrentActivity) { ProcessNavigationRequests(this.Session); } this.Session.Exit(); } else if (this.Session.View == SessionView.RandomAccess) { // This may also be a request to end grading (for SLK), in which case // we just set a flag, get the right strings to display and call it done this.SessionIsEnded = true; processSessionEnd( this.Session, ref this.mSessionEndedMsgTitle, ref this.mSessionEndedMsg); } this.ActivityHasChanged = true; this.LoadContentFrame = true; this.mSaveOnly = false; } break; } } } else { // Is this the first page load, as part of frameset? (Some hidden values are only rendered in this case.) string param = this.Request.QueryString[FramesetQueryParameter.Init]; if (!string.IsNullOrEmpty(param)) { this.mIsFramesetInitialization = true; } } // If this was not simply a save operation and there is no current activity, then display a message // asking the user to select one. if (!this.mSaveOnly && !this.Session.HasCurrentActivity) { this.RegisterError( this.GetFramesetMsg(FramesetStringId.SelectActivityTitleHtml), this.GetFramesetMsg(FramesetStringId.SelectActivityMessageHtml), true); } // In Execute view, ProcessSessionEnd may write to the database and change state of data related to the attempt. // Therefore, session changes must be written in the same transation as the session end changes. TransactionOptions transactionOptions = new TransactionOptions(); transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable; using (LearningStoreTransactionScope scope = new LearningStoreTransactionScope(transactionOptions)) { if (!this.SessionIsReadOnly) { // Save all changes this.Session.CommitChanges(); } if (this.Session.View == SessionView.Execute) { // 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. Allow the application to process this, since the messages are // different. processSessionEnd(this.Session, ref this.mSessionEndedMsgTitle, ref this.mSessionEndedMsg); } // finish the transaction scope.Complete(); } this.InitHiddenControlInfo(); this.mPageLoadSuccessful = true; } catch (ThreadAbortException) { // Do nothing -- thread is leaving. throw; } catch (Exception) { this.mPageLoadSuccessful = false; throw; } }
[SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] // parameters are validated public void ProcessPageLoad(PackageStore packageStore, TryGetViewInfo TryGetViewInfo, TryGetAttemptInfo TryGetAttemptInfo, ProcessViewRequest ProcessViewRequest) { // These should never be a problem, however fxcop complains about them. FramesetUtil.ValidateNonNullParameter("TryGetViewInfo", TryGetViewInfo); FramesetUtil.ValidateNonNullParameter("TryGetAttemptInfo", TryGetAttemptInfo); FramesetUtil.ValidateNonNullParameter("ProcessViewRequest", ProcessViewRequest); FramesetUtil.ValidateNonNullParameter("packageStore", packageStore); // Session information that may be required SessionView view; AttemptItemIdentifier attemptId; // not required for all views // Get View information. It determines what else to look for. if (!TryGetViewInfo(true, out view)) return; // Based on View, request other information switch (view) { case SessionView.Execute: { // AttemptId is required if (!TryGetAttemptInfo(true, out attemptId)) return; // Create the session m_session = new StoredLearningSession(view, attemptId, packageStore); StoredLearningSession slsSession = m_session as StoredLearningSession; if (!ProcessViewRequest(SessionView.Execute, slsSession)) { if (slsSession.AttemptStatus == AttemptStatus.Completed) { } return; } // If the attempt id appeared valid (that is, it was numeric), but does not represent a valid // attempt, the call to access AttemptStatus on the session will trigger an InvalidOperationException // containing a message for the user that the attempt id was not valid. switch (slsSession.AttemptStatus) { case AttemptStatus.Abandoned: { // Can't do execute view on abandoned sessions. The application should have handled this // in the ProcessViewRequest. return; } case AttemptStatus.Active: { // Check if it's started. If not, try starting it and forcing selection of a current activity. if (!slsSession.HasCurrentActivity) { try { slsSession.Start(false); slsSession.CommitChanges(); } catch (SequencingException) { // Intentionally ignored. This means it was either already started or could not // select an activity. In either case, just let the content frame ask the user to // deal with selecting an activity. } } else { // If the current activity is not active, then it's possible the frameset was removed from the // user and the content suspended the current activity. In that case, we do this little trick // and try suspending all the activities and then resuming them. The resume will simply resume // all the activities between the current activity and the root. Other suspended activities // will not be affected. if (!slsSession.CurrentActivityIsActive) { slsSession.Suspend(); slsSession.Resume(); slsSession.CommitChanges(); } } } break; case AttemptStatus.Completed: { // Can't do execute view on completed sessions. The application should have handled this in the // ProcessViewRequest. return; } case AttemptStatus.Suspended: { // Resume it slsSession.Resume(); slsSession.CommitChanges(); } break; default: break; } } break; case SessionView.RandomAccess: { // AttemptId is required if (!TryGetAttemptInfo(true, out attemptId)) return; StoredLearningSession slsSession = new StoredLearningSession(SessionView.RandomAccess, attemptId, packageStore); m_session = slsSession; if (!ProcessViewRequest(SessionView.RandomAccess, slsSession )) return; // Move to the first activity with a resource. PostableFrameHelper.MoveToNextActivity(m_session); } break; case SessionView.Review: { // AttemptId is required if (!TryGetAttemptInfo(true, out attemptId)) return; // Create the session StoredLearningSession slsSession = new StoredLearningSession(view, attemptId, packageStore); m_session = slsSession; if (!ProcessViewRequest(SessionView.Review, m_session)) return; // Access a property. If the user doesn't have permission, this will throw exception if (m_session.HasCurrentActivity) { // This is good. The 'if' statement is here to make compiler happy. } } break; } }