private void Init() { try { string basepath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Replace("file:///", "").Replace("/", @"\"); basepath = System.IO.Path.GetDirectoryName(basepath) + @"\"; GameCatalogSerializer gcs = new GameCatalogSerializer(); System.Xml.XmlDocument doc = gcs.Serialize(games); System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator(); System.Xml.Xsl.XslTransform xt = new System.Xml.Xsl.XslTransform(); System.Xml.XmlResolver res = new System.Xml.XmlUrlResolver(); System.IO.StringWriter writer = new System.IO.StringWriter(); System.Xml.Xsl.XsltArgumentList args = new System.Xml.Xsl.XsltArgumentList(); System.Xml.XmlNameTable xnt = new System.Xml.NameTable(); System.Xml.XmlReader xslt = new System.Xml.XmlTextReader(new System.IO.StreamReader(basepath + "GameList.xslt"), xnt); xt.Load(xslt, res, new System.Security.Policy.Evidence()); xt.Transform(nav, args, writer, res); string html = writer.ToString(); WriteHTML(html); } catch (Exception ex) { string error = "There was an error generating HTML"; Exception xe = ex; while (xe != null) { error += "<p><b>" + xe.Message + "</b><br><pre>" + xe.StackTrace + "</pre></p>\r\n"; } WriteHTML(error); } }
public void RunXslTransformCommand() { if (string.IsNullOrEmpty(stylesheetFileName)) { stylesheetFileName = XmlEditorService.BrowseForStylesheetFile(); if (string.IsNullOrEmpty(stylesheetFileName)) { return; } } using (IProgressMonitor monitor = XmlEditorService.GetMonitor()) { try { string xsltContent; try { xsltContent = GetFileContent(stylesheetFileName); } catch (System.IO.IOException) { monitor.ReportError( GettextCatalog.GetString("Error reading file '{0}'.", stylesheetFileName), null); return; } System.Xml.Xsl.XslTransform xslt = XmlEditorService.ValidateStylesheet(monitor, xsltContent, stylesheetFileName); if (xslt == null) { return; } XmlDocument doc = XmlEditorService.ValidateXml(monitor, Editor.Text, FileName); if (doc == null) { return; } string newFileName = XmlEditorService.GenerateFileName(FileName, "-transformed{0}.xml"); monitor.BeginTask(GettextCatalog.GetString("Executing transform..."), 1); using (XmlTextWriter output = XmlEditorService.CreateXmlTextWriter(Document)) { xslt.Transform(doc, null, output); IdeApp.Workbench.NewDocument( newFileName, "application/xml", output.ToString()); } monitor.ReportSuccess(GettextCatalog.GetString("Transform completed.")); monitor.EndTask(); } catch (Exception ex) { string msg = GettextCatalog.GetString("Could not run transform."); monitor.ReportError(msg, ex); monitor.EndTask(); } } }
/// <summary> /// The custom tab that displays the 'Add Course', 'Delete Course', etc. items also /// has an optional FEED tag, which will cause it to try to pick up an updated /// copy, if available, from the user's APPDATA\Microsoft\VisualStudio\7.1\Academic /// folder. This function updates that file, and should be called whenever either /// script or addin code update the list of courses on disk. /// </summary> public bool RegenerateUserCustomTab(bool noCoursesRemaining) { try { System.Xml.Xsl.XslTransform transformer; System.Xml.XmlTextReader xslReader; Microsoft.Win32.RegistryKey key; string coursesXMLFile, userTabFile, strDestinationDirectory, registryRoot, emptyTabFile; // Create a cached copy of assignments.xml and put it in the right spot key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(Constants.KeyName); strDestinationDirectory = key.GetValue(Constants.ValueName) + Constants.ApplicationPath; coursesXMLFile = strDestinationDirectory + Constants.ManagedCoursesFileName; userTabFile = strDestinationDirectory + Constants.UserTabFile; if (noCoursesRemaining) { // Copy the default tab. registryRoot = m_applicationObject.RegistryRoot; key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(registryRoot); emptyTabFile = key.GetValue(Constants.InstallationDirValueName) + Constants.VisualStudioHTMLDir; emptyTabFile += m_applicationObject.LocaleID.ToString() + "\\"; emptyTabFile += Constants.VisualStudioCourseManagementTabDir; if (System.IO.File.Exists(userTabFile)) { System.IO.File.Delete(userTabFile); } System.IO.File.Copy(emptyTabFile, userTabFile); } else { // Apply an XSL transform to the courses.xml file. xslReader = new System.Xml.XmlTextReader(AssignmentManager.ClientUI.AMResources.GetLocalizedString("XSLCustomTab"), System.Xml.XmlNodeType.Document, null); transformer = new System.Xml.Xsl.XslTransform(); transformer.Load(xslReader); if (System.IO.File.Exists(userTabFile)) { System.IO.File.Delete(userTabFile); } transformer.Transform(coursesXMLFile, userTabFile); } } catch (System.Exception) { return(false); } return(true); }
public static void GenerateXMLViaXSLT(string xsltFileName, System.Xml.XmlDocument xmlMetaData, string outputFile, string outputType, ExtObject[] extObjects, params Param[] @params) { System.Xml.Xsl.XslTransform xslt = new System.Xml.Xsl.XslTransform(); System.Xml.XPath.XPathNavigator xNav; System.Xml.XmlTextWriter XMLWriter = null; System.Xml.Xsl.XsltArgumentList args = new System.Xml.Xsl.XsltArgumentList(); try { if (xmlMetaData == null) { xmlMetaData = new System.Xml.XmlDocument(); } foreach (Param param in @params) { args.AddParam(param.Name, "", param.Value); } if (extObjects == null) { // No problem, just skip } else { foreach (ExtObject extObject in extObjects) { System.Reflection.ConstructorInfo constructorInfo = ((System.Type)(extObject.value)).GetConstructor(null); object obj = constructorInfo.Invoke(null); args.AddExtensionObject(extObject.NameSpaceURI, obj); } } AddStandardExtension(args); xNav = xmlMetaData.CreateNavigator(); XMLWriter = new System.Xml.XmlTextWriter(outputFile, System.Text.Encoding.UTF8); xslt.Load(xsltFileName); xslt.Transform(xNav, args, XMLWriter, null); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw; } finally { if (XMLWriter != null) { XMLWriter.Flush(); XMLWriter.Close(); } } }
private static void GenerateXSLTToStream(System.Xml.Xsl.XslTransform xsltTransform, System.Xml.XPath.XPathNavigator xNavMetaData, System.IO.Stream stream, string outputType, ExtObject[] extObjects, params Param[] @params) { System.IO.StreamWriter streamWriter = null; System.Xml.XmlTextWriter xmlWriter = null; System.Xml.Xsl.XsltArgumentList args = new System.Xml.Xsl.XsltArgumentList(); try { if (@params != null) { foreach (Param param in @params) { args.AddParam(param.Name, "", param.Value); } } if (extObjects == null) { // No problem, just skip } else { foreach (ExtObject extObject in extObjects) { System.Reflection.ConstructorInfo constructorInfo = ((System.Type)(extObject.value)).GetConstructor(Type.EmptyTypes); object obj = constructorInfo.Invoke(null); args.AddExtensionObject(extObject.NameSpaceURI, obj); } } AddStandardExtension(args); streamWriter = new System.IO.StreamWriter(stream); xsltTransform.Transform(xNavMetaData, args, streamWriter, null); } catch (System.Exception ex) { System.Diagnostics.Debug.WriteLine(ex); throw; } finally { if (streamWriter != null) { streamWriter.Flush(); } if (xmlWriter != null) { xmlWriter.Flush(); } } }
public string TransformXML(string xml, string xsl) { System.IO.StringReader stringReader = null; System.Xml.Xsl.XslTransform xslTransform = null; System.Xml.XmlTextReader xmlTextReader = null; System.IO.MemoryStream xmlTextWriterStream = null; System.Xml.XmlTextWriter xmlTextWriter = null; System.Xml.XmlDocument xmlDocument = null; System.IO.StreamReader streamReader = null; System.Security.Policy.Evidence evidence = null; try { stringReader = new System.IO.StringReader(xsl); xslTransform = new System.Xml.Xsl.XslTransform(); xmlTextReader = new System.Xml.XmlTextReader(stringReader); xmlTextWriterStream = new System.IO.MemoryStream(); xmlTextWriter = new System.Xml.XmlTextWriter(xmlTextWriterStream, System.Text.Encoding.Default); xmlDocument = new System.Xml.XmlDocument(); evidence = new System.Security.Policy.Evidence(); evidence.AddAssembly(this); xmlDocument.LoadXml(xml); xslTransform.Load(xmlTextReader, null, evidence); xslTransform.Transform(xmlDocument, null, xmlTextWriter, null); xmlTextWriter.Flush(); xmlTextWriterStream.Position = 0; streamReader = new System.IO.StreamReader(xmlTextWriterStream); return(streamReader.ReadToEnd()); } catch (Exception exc) { LogEvent(exc.Source, "TransformXML()", exc.ToString(), 4); return(""); } finally { streamReader.Close(); xmlTextWriter.Close(); xmlTextWriterStream.Close(); xmlTextReader.Close(); stringReader.Close(); GC.Collect(); } }
private string DoTransform(string XML, string XSL, System.Xml.Xsl.XsltArgumentList Params) { try { System.Xml.Xsl.XslTransform oXsl = new System.Xml.Xsl.XslTransform(); oXsl.Load(XSL); XmlTextReader oXR = new XmlTextReader(XML, XmlNodeType.Document, null); System.Xml.XPath.XPathDocument oXml = new System.Xml.XPath.XPathDocument(oXR); XmlUrlResolver oResolver = new XmlUrlResolver(); System.Text.StringBuilder oSB = new System.Text.StringBuilder(); System.IO.StringWriter oWriter = new System.IO.StringWriter(oSB, null); oXsl.Transform(oXml, Params, oWriter, oResolver); oWriter.Close(); return(oSB.ToString()); } catch (Exception ex) { throw ex; } }
private Boolean GenerarCadenaOriginalCFDI(String XML, out List <String> Errores, bool Local = false) { Boolean Resultado = false; _cadenaoriginal = String.Empty; Errores = new List <string>(); try { String ArchivoXSLT = (Local? "\\cadenaoriginal_3_3Local.xslt" : "\\cadenaoriginal_3_3.xslt"); if (System.IO.File.Exists(PosicionEsquema + ArchivoXSLT)) { System.IO.StringReader XmlSR = new System.IO.StringReader(XML); System.Xml.XPath.XPathDocument DocXml = new System.Xml.XPath.XPathDocument(XmlSR); System.Xml.Xsl.XslTransform elXSLt = new System.Xml.Xsl.XslTransform(); elXSLt.Load(PosicionEsquema + ArchivoXSLT); System.IO.Stream str = new System.IO.MemoryStream(); elXSLt.Transform(DocXml, null, str); str.Position = 0; System.IO.StreamReader reader = new System.IO.StreamReader(str); _cadenaoriginal = reader.ReadToEnd(); Resultado = true; reader.Close(); } else { //cErrores ErrT = new cErrores(1061); Errores.Add("No se encontro el archivo " + PosicionEsquema + ArchivoXSLT); } } catch (Exception e) { Errores.Add(e.Message); } return(Resultado); }
protected void Page_Load(object sender, EventArgs e) { main.SetPageType(Main.PageType.Content); ControlGenerator.AddScriptControl(Page.Master.Page.Header.Controls, "/Scripts/ResizeBrowseUtils.js"); ControlGenerator.AddScriptControl(Page.Master.Page.Header.Controls, "/Scripts/jquery-1.2.6.min.js"); ControlGenerator.AddAttributesAndPreserveExisting(main.Body, "onload", "ResizeContentPanel('browseContentPanel', 258);ResizeBrowseDivs();"); ControlGenerator.AddAttributesAndPreserveExisting(main.Body, "onresize", "ResizeContentPanel('browseContentPanel', 258);ResizeBrowseDivs();"); Data.PageSummaryView ps = null; CustomGenericList <Data.Item> items = null; CustomGenericList <Data.Creator> creators = null; CustomGenericList <Data.TitleTag> titleTags = null; CustomGenericList <Data.Title_TitleIdentifier> titleIdentifiers = null; CustomGenericList <Data.TitleAssociation> titleAssociations = null; Data.Title title = null; bool showData = false; int titleId = 0; if (Request["titleid"] != null) { if (!int.TryParse(Request.QueryString["titleid"], out titleId)) { // Request seems to have included a MARCBibID instead of a TitleId Data.PageSummaryView psBib = bhlProvider.PageTitleSummarySelectByBibID(Request.QueryString["titleid"].ToString()); if (psBib != null) { titleId = psBib.TitleID; } } showData = true; } if (!showData && Request.QueryString["oclc"] != null) { // Get the title id associated with the OCLC identifier Data.Title_TitleIdentifier titleTitleId = bhlProvider.Title_TitleIdentifierSelectByIdentifierValue(Request.QueryString["oclc"].ToString()); if (titleTitleId != null) { titleId = titleTitleId.TitleID; } showData = true; } if (showData) { hidTitleID.Value = titleId.ToString(); // Check to make sure this title hasn't been replaced. If it has, redirect // to the appropriate titleid. title = bhlProvider.TitleSelect(titleId); if (title.RedirectTitleID != null) { Response.Redirect("/bibliography/" + title.RedirectTitleID.ToString()); Response.End(); } // Set the title for the COinS COinSControl1.TitleID = titleId; ps = bhlProvider.PageTitleSummarySelectByTitleId(titleId); if (ps == null) { Response.Redirect("/TitleNotFound.aspx"); Response.End(); } Barcode = ps.BarCode; creators = bhlProvider.CreatorSelectByTitleId(titleId); items = bhlProvider.ItemSelectByTitleId(titleId); titleTags = bhlProvider.TitleTagSelectTagTextByTitleId(titleId); titleIdentifiers = bhlProvider.Title_TitleIdentifierSelectByTitleID(titleId); titleAssociations = bhlProvider.TitleAssociationSelectByTitleId(titleId, true); if (titleAssociations.Count == 0) { associationsDiv.Visible = false; } else { associationsDiv.Visible = true; associationsRepeater.DataSource = titleAssociations; associationsRepeater.DataBind(); } foreach (Data.Item item in items) { // Populate empty volume descriptions with default text if (item.Volume == String.Empty || item.Volume == null) { if (items.Count == 1) { item.Volume = "View Book"; } if (items.Count > 1) { item.Volume = "(no volume description)"; } } // Make sure all Botanicus PDFs actually exist. Remove the DownloadUrl for any that do not. if (item.DownloadUrl != String.Empty && item.ItemSourceID == 2) { // This is kludgy... should find a better way to do this String pdfLocation = item.DownloadUrl.Replace("http://www.botanicus.org/", "\\\\server\\").Replace('/', '\\'); if (new BHLProvider().GetFileAccessProvider(ConfigurationManager.AppSettings["UseRemoteFileAccessProvider"] == "true").FileExists(pdfLocation)) { item.DownloadUrl = ConfigurationManager.AppSettings["PdfAuthUrl"] != null?String.Format(ConfigurationManager.AppSettings["PdfAuthUrl"], item.BarCode) : String.Empty; } else { item.DownloadUrl = String.Empty; } } } // Look for an OCLC identifier (use the first one... might need to account for multiple at some point) bool oclcFound = false; foreach (Data.Title_TitleIdentifier titleIdentifier in titleIdentifiers) { if (String.Compare(titleIdentifier.IdentifierName, "OCLC", StringComparison.CurrentCultureIgnoreCase) == 0) { localLibraryLink.NavigateUrl += "wcpa/oclc/"; if (titleIdentifier.IdentifierValue.ToLower().StartsWith("ocm")) { //strip the "ocm" from the beginning of the value. localLibraryLink.NavigateUrl += titleIdentifier.IdentifierValue.Substring(3); } else { localLibraryLink.NavigateUrl += titleIdentifier.IdentifierValue; } oclcFound = true; break; } } if (!oclcFound) { string truncatedTitle = ""; if (title.FullTitle.Length > 220) { truncatedTitle = title.FullTitle.Substring(0, 220); truncatedTitle = truncatedTitle.Substring(0, truncatedTitle.LastIndexOf(" ")); } else { truncatedTitle = title.FullTitle; } localLibraryLink.NavigateUrl += "search?q=" + truncatedTitle.Replace(" ", "+") + "&qt=owc_search"; } Master.Page.Title = "Biodiversity Heritage Library: Information about '" + ps.FullTitle + "'"; //descriptionLiteral.Text = title.TitleDescription; publicationInfoLiteral.Text = title.PublicationDetails; fullTitleLiteral.Text = title.FullTitle + " " + (title.PartNumber ?? "") + " " + (title.PartName ?? ""); if (title.CallNumber == null || title.CallNumber.Length == 0) { callNumberPanel.Visible = false; } else { callNumberLiteral.Text = title.CallNumber; } if (titleTags == null || titleTags.Count == 0) { subjectPanel.Visible = false; } else { int k = titleTags.Count - 1; int i = 0; StringBuilder sb = new StringBuilder(); foreach (Data.TitleTag titleTag in titleTags) { sb.Append("<a href='/subject/"); sb.Append(Server.UrlEncode(titleTag.TagText)); sb.Append("'>"); sb.Append(titleTag.TagText); sb.Append("</a>"); if (i + 1 <= k) { sb.Append(", "); } i++; } subjectLiteral.Text = sb.ToString(); } itemRepeater.DataSource = items; itemRepeater.DataBind(); CustomGenericList <Data.Creator> authors = new CustomGenericList <Data.Creator>(); CustomGenericList <Data.Creator> additionalAuthors = new CustomGenericList <Data.Creator>(); foreach (Data.Creator creator in creators) { if (creator.CreatorRoleTypeForTitle >= 1 && creator.CreatorRoleTypeForTitle <= 3) { authors.Add(creator); } else { additionalAuthors.Add(creator); } } authorsRepeater.DataSource = authors; authorsRepeater.DataBind(); additionalAuthorsRepeater.DataSource = additionalAuthors; additionalAuthorsRepeater.DataBind(); //Data.Institution institution = bhlProvider.InstitutionSelectByItemID( ps.ItemID ); //if ( institution != null ) //{ // if ( institution.InstitutionUrl != null && institution.InstitutionUrl.Trim().Length > 0 ) // { // HyperLink link = new HyperLink(); // link.Text = institution.InstitutionName; // link.NavigateUrl = institution.InstitutionUrl; // link.Target = "_blank"; // attributionPlaceHolder.Controls.Add( link ); // } // else // { // Literal literal = new Literal(); // literal.Text = institution.InstitutionName; // attributionPlaceHolder.Controls.Add( literal ); // } //} if (Helper.IsAdmin(Request)) { editTitleLink.NavigateUrl = "/Admin/TitleEdit.aspx?id=" + titleId.ToString(); } else { editTitleLink.Visible = false; } // Get the full MARC details bool marcFound = false; String filepath = ps.MarcXmlLocation; bool test = (ConfigurationManager.AppSettings["UseRemoteFileAccessProvider"] == "true"); if (new BHLProvider().GetFileAccessProvider(ConfigurationManager.AppSettings["UseRemoteFileAccessProvider"] == "true").FileExists(filepath)) { marcFound = true; } else { // File not found in primary location, so look in alternate location (Botanicus files in alt location) filepath = ps.MarcXmlAltLocation; if (new BHLProvider().GetFileAccessProvider(ConfigurationManager.AppSettings["UseRemoteFileAccessProvider"] == "true").FileExists(filepath)) { marcFound = true; } } if (marcFound) { string marcXML = new BHLProvider().GetFileAccessProvider(ConfigurationManager.AppSettings["UseRemoteFileAccessProvider"] == "true").GetFileText(filepath); XmlDocument xml = new XmlDocument(); StringReader reader = new StringReader(marcXML); xml.Load(reader); // Set up the XSL resolver that we'll use to extract the text from the xml XmlUrlResolver resolver = new XmlUrlResolver(); resolver.Credentials = System.Net.CredentialCache.DefaultCredentials; System.Xml.Xsl.XslTransform xslTransform = new System.Xml.Xsl.XslTransform(); // Format the MARC XML into a "readable" format xslTransform.Load(Request.PhysicalApplicationPath + "xsl\\MARC21transformEnglish.xsl", resolver); StringWriter output = new StringWriter(); xslTransform.Transform(xml, null, output, resolver); litExpanded.Text = output.ToString(); // Format the MARC XML into a "flat" MARC format xslTransform.Load(Request.PhysicalApplicationPath + "xsl\\MARC21transformMARC.xsl", resolver); output = new StringWriter(); xslTransform.Transform(xml, null, output, resolver); litMarc.Text = output.ToString(); viewcontrol.Visible = true; } else { viewcontrolnomarc.Visible = true; } // Get the BibTex citations for this title try { hypBibTex.NavigateUrl += title.TitleID.ToString(); litBibTeX.Text = bhlProvider.TitleBibTeXGetCitationStringForTitleID(title.TitleID).Replace("\n", "<br>").Replace("\r", "<br>"); } catch { hypBibTex.Visible = false; litBibTeX.Text = "Error retrieving BibTex citations for this title."; } // Get the EndNote citation for this title try { hypEndNote.NavigateUrl += title.TitleID.ToString(); litEndNote.Text = bhlProvider.TitleEndNoteGetCitationStringForTitleID(title.TitleID, ConfigurationManager.AppSettings["ItemPageUrl"].ToString()).Replace("\n", "<br>").Replace("\r", "<br>"); } catch { hypEndNote.Visible = false; litEndNote.Text = "Error retrieving EndNote citations for this title."; } } }
private bool handleAction_Xsl(string data, string xsltToUse) { //if (this.tmWebServices.tmAuthentication.sessionID. UserRole.ReadArticles var xstlFile = context.Server.MapPath("\\xslt\\" + xsltToUse); if (xstlFile.fileExists()) { var guid = tmWebServices.getGuidForMapping(data); if (guid != Guid.Empty) { var xmlContent = tmWebServices.XmlDatabase_GetGuidanceItemXml(guid); //.add_Xslt(xsltToUse); if (xmlContent.valid()) { var xslTransform = new System.Xml.Xsl.XslTransform(); xslTransform.Load(xstlFile); var xmlReader = new System.Xml.XmlTextReader(new StringReader(xmlContent)); var xpathNavigator = new System.Xml.XPath.XPathDocument(xmlReader); var stringWriter = new StringWriter(); xslTransform.Transform(xpathNavigator, new System.Xml.Xsl.XsltArgumentList(), stringWriter); context.Response.ContentType = "text/html"; context.Response.Write(stringWriter.str()); return true; } return false; } return transfer_ArticleViewer(); } return false; }
private string DoTransform(string XML, string XSL, System.Xml.Xsl.XsltArgumentList Params) { try { System.Xml.Xsl.XslTransform oXsl = new System.Xml.Xsl.XslTransform(); oXsl.Load(XSL); XmlTextReader oXR = new XmlTextReader(XML, XmlNodeType.Document, null); System.Xml.XPath.XPathDocument oXml = new System.Xml.XPath.XPathDocument(oXR); XmlUrlResolver oResolver = new XmlUrlResolver(); System.Text.StringBuilder oSB = new System.Text.StringBuilder(); System.IO.StringWriter oWriter = new System.IO.StringWriter(oSB, null); oXsl.Transform(oXml, Params, oWriter, oResolver); oWriter.Close(); return oSB.ToString(); } catch (Exception ex) { throw ex; } }