protected void Button1_Click(object sender, EventArgs e) { XsltArgumentList argsList = new XsltArgumentList(); argsList.AddParam("calories", "", TextBox1.Text); Xml1.TransformArgumentList = argsList; Xml1.Visible = true; }
public static string Transform(string xsltFile, string xml, XsltArgumentList xslArg) { string result = ""; try { XslCompiledTransform xslt = new XslCompiledTransform(); xslt.Load(xsltFile); // XmlWriterSettings.OmitXmlDeclaration XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(new StringReader(xml)); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; using (StringWriter sw = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sw, settings)) { xslt.Transform(xmlDoc, xslArg, writer); } sw.Flush(); result = sw.ToString(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return result; }
public static object GetData(StageParams config) { XmlDocument input = Util.Validate<XmlDocument>( config.data, "XSLTStage" ); string xslPath = config.context.Server.MapPath( config.map ); if (!File.Exists(xslPath)) throw new FileLoadException(String.Format("Style sheet {0} is not found", xslPath)); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(xslPath, new XsltSettings(false, true), new XmlUrlResolver()); XsltArgumentList al = new XsltArgumentList(); int index = 0; foreach (XmlNode node in config.stage) if ( node.Attributes["type"] != null ) al.AddParam( node.Name, "", config.allParams[index++]); if (!config.last) { MemoryStream output = new MemoryStream(); transform.Transform(input, al, output); return output; } else { transform.Transform(input, al, config.outputStream); return null; } }
internal XmlQueryContext(XmlQueryRuntime runtime, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules) { this.runtime = runtime; this.dataSources = dataSources; this.dataSourceCache = new Hashtable(); this.argList = argList; this.wsRules = wsRules; if (defaultDataSource is XmlReader) { this.readerSettings = new QueryReaderSettings((XmlReader) defaultDataSource); } else { // Consider allowing users to set DefaultReaderSettings in XsltArgumentList // readerSettings = argList.DefaultReaderSettings; this.readerSettings = new QueryReaderSettings(new NameTable()); } if (defaultDataSource is string) { // Load the default document from a Uri this.defaultDataSource = GetDataSource(defaultDataSource as string, null); if (this.defaultDataSource == null) throw new XslTransformException(Res.XmlIl_UnknownDocument, defaultDataSource as string); } else if (defaultDataSource != null) { this.defaultDataSource = ConstructDocument(defaultDataSource, null, null); } }
public XsltArgumentList ToXsltArgumentList() { XsltArgumentList result = new XsltArgumentList(); for(int i=0; i<mKeys.Count; i++){ result.AddParam((string)mKeys[i], "", (string)mVals[i]); } return result; }
protected void imgSearchIcon_Click(object sender, ImageClickEventArgs e) { string helpCultureName = _cultureCookie != null ? _cultureCookie.Value : string.Empty; string rootUrl = HelpSiteMapProvider.GetProviderRootUrlByCultureName(helpCultureName); string contentIndexName = "HelpContentIndex:" + rootUrl; ContentIndex myContentIndex = null; ContentSearchResult mySearchResult = null; XmlDocument doc = new XmlDocument(); XslCompiledTransform xslt = new XslCompiledTransform(); XsltArgumentList xsltArgs = new XsltArgumentList(); StringWriter xsltResult = null; string exprPageTitle = @"(?si)(?:(?<=<meta\s*name\s*=\s*(?:""|')menuText(?:""|')\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")[^>]*>)|(?<=<meta\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")\s*name\s*=\s*(?:""|')menuText(?:""|')\s*[^>]*>))"; if (txtSearch.Text.Length > 0) { try { myContentIndex = Application[contentIndexName] as ContentIndex; if (myContentIndex == null) { myContentIndex = new ContentIndex(Page.MapPath(rootUrl), exprPageTitle); Application[contentIndexName] = myContentIndex; } mySearchResult = myContentIndex.Search(txtSearch.Text); doc.LoadXml(mySearchResult.ToXml()); xslt.Load(Server.MapPath("css/searchResult.xsl")); xsltArgs.AddParam("hrefPrefix", string.Empty, Request.Url.GetLeftPart(System.UriPartial.Path) + "?page=Help&content="); xsltArgs.AddParam("relativeURL", string.Empty, rootUrl); xsltArgs.AddParam("mappedURL", string.Empty, Page.MapPath(rootUrl)); xsltResult = new StringWriter(); xslt.Transform(doc, xsltArgs, xsltResult); litMainContent.Text = xsltResult.ToString(); } catch (XmlException xmlEx) { if (xmlEx.Message.ToLowerInvariant().Contains("root")) { //Missing root element. litMainContent.Text = String.Format(GetLocalResourceObject("NoContentFound").ToString(), txtSearch.Text); } else { litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), xmlEx.Message); } } catch (Exception ex) { litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), ex.Message); } finally { if (xsltResult != null) xsltResult.Close(); } } }
public static void Transform(string sXmlPath, string sXslPath) { try { XPathDocument myXPathDoc = new XPathDocument(sXmlPath); XslCompiledTransform myXslTrans = new XslCompiledTransform(); myXslTrans.Load(sXslPath); XsltArgumentList xslArgs = new XsltArgumentList(); Utils classPtr = new Utils(); xslArgs.AddExtensionObject("urn:util", classPtr); XmlTextWriter myWriter = new XmlTextWriter("result.xml", null); myXslTrans.Transform(myXPathDoc, xslArgs, myWriter); myWriter.Close(); } catch (Exception e) { Console.WriteLine("Exception: {0}", e.ToString()); } }
private void ProcessMenuRequest() { Ektron.Cms.ContentAPI myContent = new Ektron.Cms.ContentAPI(); Ektron.Cms.CommonApi AppUI = new Ektron.Cms.CommonApi(); Ektron.Cms.API.User.User myUser = new Ektron.Cms.API.User.User(); long contentId = Convert.ToInt64(Request.QueryString["contentId"]); int languageId = -1; long taxonomyOverrideId = 0; if (Request.QueryString["dmsLanguageId"] != null) { if (Request.QueryString["dmsLanguageId"] != String.Empty) { languageId = Convert.ToInt32(Request.QueryString["dmsLanguageId"]); if (languageId == Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED || languageId == Ektron.Cms.Common.EkConstants.ALL_CONTENT_LANGUAGES) { languageId = AppUI.DefaultContentLanguage; } AppUI.ContentLanguage = languageId; myContent.ContentLanguage = languageId; } } //createIeSpecificMenu is an argument passed to the constructor of the DMSMenuContentAPI class //This arg tells DMSMenuContentAPI whether or not to include the IE specific functionality //namely, this funcitonality is the office-specific stuff (Edit In Microsoft Office, View in Microsoft Office). Boolean createIeSpecificMenu = false; if (Request.QueryString["createIeSpecificMenu"] != String.Empty) { createIeSpecificMenu = Convert.ToBoolean(Request.QueryString["createIeSpecificMenu"]); } string dmsMenuType = String.Empty; string dmsMenuSubtype = String.Empty; long communityGroupID = 0; if (!String.IsNullOrEmpty(Request.QueryString["communityDocuments"])) { // Dms community menus may carry additional data (i.e. group id). string[] splitDmsMenuTypeInfo = Request.QueryString["communityDocuments"].Split( new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries); dmsMenuType = splitDmsMenuTypeInfo[0]; if (splitDmsMenuTypeInfo.Length == 2) { long.TryParse(splitDmsMenuTypeInfo[1], out communityGroupID); } } Ektron.Cms.ContentData myContentData = new Ektron.Cms.ContentData(); Ektron.Cms.API.Content.Content apiCont = new Ektron.Cms.API.Content.Content(); Ektron.Cms.ContentStateData stateData = apiCont.GetContentState(contentId); if (stateData.Status == "A") myContentData = apiCont.GetContent(contentId, Ektron.Cms.ContentAPI.ContentResultType.Published); else myContentData = apiCont.GetContent(contentId, Ektron.Cms.ContentAPI.ContentResultType.Staged); string dmsMenuGuid; XsltArgumentList myDMSMenuArguments = new XsltArgumentList(); Ektron.Cms.Workarea.Dms.DmsMenu myDMSMenu; if (dmsMenuType != "") { bool queryDynamicContentBox = false; string controlID = String.Empty; if (Request.QueryString["dynamicContentBox"] != null) { queryDynamicContentBox = Convert.ToBoolean(Request.QueryString["DynamicContentBox"]); if (dmsMenuType.ToLower() == "communityuser" || dmsMenuType.ToLower() == "communitygroup" && EkConstants.IsAssetContentType(myContentData.ContType, true) && myContentData.ContType !=(int) EkEnumeration.CMSContentType.Multimedia) { if (myContentData.AssetData != null && !EkFunctions.IsImage("." + myContentData.AssetData.FileExtension) && myContentData.Type !=(int) EkEnumeration.CMSContentType.Multimedia) { queryDynamicContentBox = false; } } myDMSMenuArguments.AddParam("dynamicContentBox", String.Empty, queryDynamicContentBox); } if (Request.QueryString["dmsEktControlID"] != null) { controlID = Request.QueryString["dmsEktControlID"].ToString(); myDMSMenuArguments.AddParam("dmsEktControlID", String.Empty, controlID); } if (Request.QueryString["taxonomyOverrideId"] != null) { taxonomyOverrideId = Convert.ToInt64(Request.QueryString["taxonomyOverrideId"]); } } if (Request.QueryString["dmsMenuGuid"] != null) { dmsMenuGuid = Request.QueryString["dmsMenuGuid"].ToString(); myDMSMenuArguments.AddParam("dmsMenuGuid", String.Empty, dmsMenuGuid); } Boolean IsPhotoGallery = true; if (Request.QueryString["dmsMenuSubtype"] != null) { dmsMenuSubtype = Request.QueryString["dmsMenuSubtype"].ToString(); myDMSMenuArguments.AddParam("dmsMenuSubtype", String.Empty, dmsMenuSubtype); IsPhotoGallery = (dmsMenuSubtype == "photo"); } string fromPage = String.Empty; if (Request.QueryString["fromPage"] != null) { fromPage = Request.QueryString["fromPage"].ToString(); myDMSMenuArguments.AddParam("fromPage", String.Empty, fromPage); } switch (dmsMenuType.ToLower()) { case "taxonomy": //Taxonomy Implementation //Use Taxnonomy constructor overload //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId) if (Request.QueryString["communityGroupid"] != null) { long.TryParse(Request.QueryString["communityGroupid"].ToString(), out communityGroupID); } myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Taxonomy, contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type, createIeSpecificMenu, taxonomyOverrideId, communityGroupID); break; case "communityuser": //Community User Implementation //Use Community User constructor overload //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, Boolean isPhotoGallery) myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.CommunityUser, contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type, createIeSpecificMenu, IsPhotoGallery); break; case "communitygroup": //Community Group Implementation //Use Community Group constructor overload //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId, int communityGroupId, Boolean isPhotoGallery) myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.CommunityGroup, contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type, createIeSpecificMenu, taxonomyOverrideId, communityGroupID, IsPhotoGallery, fromPage); break; case "favorites": //Favorites Menu Implementation //Use Favorites constructor overload //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId, int communityGroupId, Boolean isPhotoGallery) myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Favorites, contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type, createIeSpecificMenu, taxonomyOverrideId, communityGroupID, IsPhotoGallery, fromPage); break; case "workarea": default: //Workarea Implementation //Use Workarea constructor overload //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu) myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Workarea, contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type, createIeSpecificMenu, fromPage); break; } DMSMenu.Text = myDMSMenu.GetDmsMenu(myDMSMenuArguments); }
public static MvcHtmlString RenderXslt(string xslPath, string xmlString, List<KeyValuePair<string, string>> parameters = null) { string xsltResult = string.Empty; try { // XML Settings XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.XmlResolver = null; xmlSettings.IgnoreComments = true; xmlSettings.DtdProcessing = DtdProcessing.Ignore; xmlSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xmlSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // XSLT Settings XmlReaderSettings xsltSettings = new XmlReaderSettings(); xsltSettings.XmlResolver = null; xsltSettings.DtdProcessing = DtdProcessing.Ignore; xsltSettings.ValidationType = ValidationType.None; // Attaches an action to the valiation event handler. This will write out error messages in the Output pane. #if DEBUG xsltSettings.ValidationEventHandler += (sender, e) => { Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message)); }; #endif // Init params XsltArgumentList xslArgs = new XsltArgumentList(); if (parameters != null) { foreach (KeyValuePair<string, string> param in parameters) xslArgs.AddParam(param.Key, string.Empty, param.Value); } // Load XML using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), xmlSettings)) { // Load XSL XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion using (XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings)) { XslCompiledTransform xsltDoc = new XslCompiledTransform(); xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver()); // Transform using (var sw = new UTF8StringWriter()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = Encoding.UTF8; settings.OmitXmlDeclaration = true; using (var xw = XmlWriter.Create(sw, settings)) { xsltDoc.Transform(reader, xslArgs, sw); } xsltResult = sw.ToString(); } } } } catch { } // custom error handling here // Return result return MvcHtmlString.Create(xsltResult); }
public void Transform(System.Xml.XPath.IXPathNavigable input, XsltArgumentList arguments, System.IO.Stream results) { }
private string Transform(string xml, string xsl, XsltArgumentList argsList) { XDocument selectedXml = XDocument.Parse(xml); XslCompiledTransform xmlTransform = new XslCompiledTransform(); StringBuilder htmlOutput = new StringBuilder(); XmlWriter writer = XmlWriter.Create(htmlOutput); xmlTransform.Load(xsl); xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer); return htmlOutput.ToString(); }
private static void Main2() { if (opts.dumptemplate) { DumpTemplate(); return; } if (opts.source == null || opts.source == "" || opts.dest == null || opts.dest == "") throw new ApplicationException("The source and dest options must be specified."); Directory.CreateDirectory(opts.dest); // Load the stylesheets, overview.xml, and resolver XslTransform overviewxsl = LoadTransform("overview.xsl"); XslTransform stylesheet = LoadTransform("stylesheet.xsl"); XslTransform template; if (opts.template == null) { template = LoadTransform("defaulttemplate.xsl"); } else { try { XmlDocument templatexsl = new XmlDocument(); templatexsl.Load(opts.template); template = new XslTransform(); template.Load(templatexsl); } catch (Exception e) { throw new ApplicationException("There was an error loading " + opts.template, e); } } XmlDocument overview = new XmlDocument(); overview.Load(opts.source + "/index.xml"); ArrayList extensions = GetExtensionMethods (overview); // Create the master page XsltArgumentList overviewargs = new XsltArgumentList(); overviewargs.AddParam("ext", "", opts.ext); overviewargs.AddParam("basepath", "", "./"); Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template); overviewargs.RemoveParam("basepath", ""); overviewargs.AddParam("basepath", "", "../"); // Create the namespace & type pages XsltArgumentList typeargs = new XsltArgumentList(); typeargs.AddParam("ext", "", opts.ext); typeargs.AddParam("basepath", "", "../"); foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace")) { string nsname = ns.GetAttribute("Name"); if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + ".")) continue; System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname); if (!d.Exists) d.Create(); // Create the NS page overviewargs.AddParam("namespace", "", nsname); Generate(overview, overviewxsl, overviewargs, opts.dest + "/" + nsname + "/index." + opts.ext, template); overviewargs.RemoveParam("namespace", ""); foreach (XmlElement ty in ns.SelectNodes("Type")) { string typefilebase = ty.GetAttribute("Name"); string typename = ty.GetAttribute("DisplayName"); if (typename.Length == 0) typename = typefilebase; if (opts.onlytype != null && !(nsname + "." + typename).StartsWith(opts.onlytype)) continue; string typefile = opts.source + "/" + nsname + "/" + typefilebase + ".xml"; if (!File.Exists(typefile)) continue; XmlDocument typexml = new XmlDocument(); typexml.Load(typefile); if (extensions != null) { DocLoader loader = CreateDocLoader (overview); XmlDocUtils.AddExtensionMethods (typexml, extensions, loader); } Console.WriteLine(nsname + "." + typename); Generate(typexml, stylesheet, typeargs, opts.dest + "/" + nsname + "/" + typefilebase + "." + opts.ext, template); } } }
public void Transform(System.Xml.XmlReader input, XsltArgumentList arguments, System.IO.Stream results) { }
private QueryReaderSettings readerSettings; // If we create reader out of stream we will use these settings /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryContext(XmlQueryRuntime runtime, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, WhitespaceRuleLookup wsRules) { this.runtime = runtime; this.dataSources = dataSources; this.dataSourceCache = new Hashtable(); this.argList = argList; this.wsRules = wsRules; if (defaultDataSource is XmlReader) { this.readerSettings = new QueryReaderSettings((XmlReader)defaultDataSource); } else { this.readerSettings = new QueryReaderSettings(new NameTable()); } if (defaultDataSource is string) { // Load the default document from a Uri this.defaultDataSource = GetDataSource(defaultDataSource as string, null); if (this.defaultDataSource == null) { throw new XslTransformException(Res.XmlIl_UnknownDocument, defaultDataSource as string); } } else if (defaultDataSource != null) { this.defaultDataSource = ConstructDocument(defaultDataSource, null, null); } }
public void Transform(System.Xml.XPath.XPathNavigator input, XsltArgumentList args, System.Xml.XmlWriter output) { }
static IMessage MakeMessageInternal(TextMessageCapture capture, XmlFormatInfo formatInfo, IRegex bodyRe, ref IMatch bodyReMatch, MessagesBuilderCallback callback, XsltArgumentList transformArgs, DateTime sourceTime, ITimeOffsets timeOffsets) { for (; ;) { StringBuilder messageBuf = new StringBuilder(); messageBuf.AppendFormat("<root {0}>", formatInfo.NSDeclaration.ToString()); messageBuf.Append(capture.HeaderBuffer, capture.HeaderMatch.Index, capture.HeaderMatch.Length); if (bodyRe != null) { if (!bodyRe.Match(capture.BodyBuffer, capture.BodyIndex, capture.BodyLength, ref bodyReMatch)) { return(null); } messageBuf.Append(capture.BodyBuffer, bodyReMatch.Index, bodyReMatch.Length); } else { messageBuf.Append(capture.BodyBuffer, capture.BodyIndex, capture.BodyLength); } messageBuf.Append("</root>"); callback.SetCurrentPosition(capture.BeginPosition, capture.EndPosition); //this.owner.xslExt.SetSourceTime(this.owner.MediaLastModified); todo? string messageStr = messageBuf.ToString(); using (FactoryWriter factoryWriter = new FactoryWriter(callback, timeOffsets)) using (XmlReader xmlReader = XmlReader.Create(new StringReader(messageStr), xmlReaderSettings)) { try { if (formatInfo.IsNativeFormat) { factoryWriter.WriteNode(xmlReader, false); } else { formatInfo.Transform.Transform(xmlReader, transformArgs, factoryWriter); } } catch (XmlException) { if (capture.IsLastMessage) { // There might be incomplete XML at the end of the stream. Ignore it. return(null); } else { // Try to parse the next messsage if it's not the end of the stream continue; } } var ret = factoryWriter.GetOutput(); if (ret == null) { throw new XsltException( "Normalization XSLT produced no output"); } if (formatInfo.ViewOptions.RawViewAllowed) { ret.SetRawText(StringSlice.Concat(capture.MessageHeaderSlice, capture.MessageBodySlice).Trim()); } if (formatInfo.ViewOptions.WrapLineLength.HasValue) { ret.WrapsTexts(formatInfo.ViewOptions.WrapLineLength.Value); } return(ret); } } }
public void Transform(ProgressState progressState) { _progressState = progressState; using (Stream outputStream = File.Create(OutputFilePath)) { var inputDocument = new XmlDocument { PreserveWhitespace = true }; inputDocument.Load(_inputFilePath); var transform = new XslCompiledTransform(); try { //all this just to allow a DTD statement in the source xslt var readerSettings = new XmlReaderSettings { DtdProcessing = DtdProcessing.Parse }; _progressState.StatusLabel = "Preparing..."; using (Stream stream = _xsltStream) { using (XmlReader xsltReader = XmlReader.Create(stream, readerSettings)) { XsltSettings settings = new XsltSettings(true, true); transform.Load(xsltReader, settings, new XmlUrlResolver()); xsltReader.Close(); } stream.Close(); } _progressState.StatusLabel = "Processing..."; int entriesCount = 1; XmlNodeList nodeCountList = inputDocument.SelectNodes(_xpathToCountSteps); if (nodeCountList != null) { entriesCount = nodeCountList.Count; } _progressState.TotalNumberOfSteps = entriesCount; if (_xsltArguments == null) { _xsltArguments = new XsltArgumentList(); } _xsltArguments.XsltMessageEncountered += OnXsltMessageEncountered; transform.Transform(inputDocument, _xsltArguments, outputStream); outputStream.Close(); //let the next guy get at the file Debug.Assert(_progressState.NumberOfStepsCompleted <= entriesCount, "Should use up more than we reserved for ourselves"); _progressState.NumberOfStepsCompleted = entriesCount; _progressState.State = ProgressState.StateValue.Finished; } catch (CancelingException) //not an error { _progressState.State = ProgressState.StateValue.Finished; } catch (Exception err) { //currently, error reporter can choke because this is //being called from a non sta thread. //so let's leave it to the progress dialog to report the error // Reporting.ErrorReporter.ReportException(args,null, false); _progressState.ExceptionThatWasEncountered = err; _progressState.WriteToLog(err.Message); _progressState.State = ProgressState.StateValue.StoppedWithError; } #if NET461 finally { _progressState.StatusLabel = "Cleaning up..."; transform.TemporaryFiles?.Delete(); } #endif } }
/// <summary> /// Метод запускает задание выгрузки файловового контента в исходящую папку /// </summary> public void Execute() { _log.Info( string.Format( "Запуск задания... Key: {0}, Storage: '{1}', SnapshotType: '{2}', Change Type: '{3}', Destination: '{4}', Package Size: {5}", Key, StorageName, SnapshotType, ChangeType, Destination, PackageSize)); // Проверка на доступность объекта if (Enabled) { try { // Определение TempPath var _tempPath = ConfigurationManager.AppSettings.Get("ECR.ChangeManager.TempPath"); if (_tempPath.Length == 0) { _tempPath = Path.GetTempPath(); } // Определение значения переменной-флага создания журналов отправки var _writeSJ = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("ECR.ChangeManager.WriteSJ")); Debug("Копирование в целевую папку..."); // Проверка наличия файлов <file_name>.ecrchg$ в temp var di = new DirectoryInfo(_tempPath); // ... основной поток данных var _files = di.GetFiles(ChangeType + "_*_" + StorageName + ".xml.ecrchg$"); if (_files.Length > 0) { for (var i = 0; i < _files.Length; i++) { File.Copy(_tempPath + _files[i].Name, Destination + _files[i].Name.Replace(".ecrchg$", string.Empty), true); Debug(string.Format("Файл '{0}' скопирован в папку '{1}'", _files[i].Name.Replace(".ecrchg$", string.Empty), Destination)); File.Delete(_tempPath + _files[i].Name); Debug(string.Format("Файл '{0}' удален", _files[i].Name.Replace(".ecrchg$", string.Empty))); } } // ... журналы отправок if (_writeSJ) { // "otSendingJournal_ECR_{0}_{1}.xml.ecrchg$" _files = di.GetFiles("otSendingJournal_ECR_*_" + StorageName + ".xml.ecrchg$"); if (_files.Length > 0) { for (var i = 0; i < _files.Length; i++) { File.Copy(_tempPath + _files[i].Name, DestinationSj + _files[i].Name.Replace(".ecrchg$", string.Empty), true); Debug(string.Format("Файл '{0}' скопирован в папку '{1}'", _files[i].Name.Replace(".ecrchg$", string.Empty), Destination)); File.Delete(_tempPath + _files[i].Name); Debug(string.Format("Файл '{0}' удален", _files[i].Name.Replace(".ecrchg$", string.Empty))); } } } // Определяем строку соединения с базой данных ECR_Storage<i> по имени хранилища StorageName Debug("Определение строки соединения с базой данных ECR_Storage..."); var _storageCnnStr = GetConnectionString(StorageName); Debug("Создание пакета xml..."); // Snapshot type switch (SnapshotType) { // changeset case "changes": using (var _conn = new SqlConnection(_storageCnnStr)) { using (var _cmd = new SqlCommand()) { _conn.Open(); try { Debug("Определение параметров создания пакета..."); _cmd.Connection = _conn; _cmd.CommandTimeout = CommandTimeout; _cmd.CommandType = CommandType.StoredProcedure; switch (ChangeType) { case "otContentEntity": _cmd.CommandText = "[ecr].[CollectEntityChanges_Xml]"; break; case "otContentView": _cmd.CommandText = "[ecr].[CollectViewChanges_Xml]"; break; } _cmd.Parameters.AddWithValue("Count", PackageSize); var _packageId = _cmd.Parameters.Add("@PackageID", SqlDbType.Int); _packageId.Direction = ParameterDirection.Output; var _outXml = _cmd.Parameters.Add("@OutXml", SqlDbType.Xml); _outXml.Direction = ParameterDirection.Output; _outXml.Size = Convert.ToInt32(ConfigurationManager.AppSettings.Get("ECR.ChangeManager.MaxOutputFileSize")); // Имя основного файла var _xmlFilename = string.Format("{0}_{1}_{2}.xml.ecrchg$", ChangeType, _packageId.Value, StorageName); // Имя файла для журнала отчета var _xmlSjFilename = string.Format("otSendingJournal_ECR_{0}_{1}.xml.ecrchg$", _packageId.Value, StorageName); Debug("Запуск хранимой процедуры создания пакета..."); _cmd.ExecuteNonQuery(); Debug("Запись данных пакета в файл xml..."); // Формирование основного файла using (var _writer = new XmlTextWriter(_tempPath + _xmlFilename, Encoding.Default)) { try { _writer.Formatting = Formatting.None; _writer.WriteRaw(_outXml.Value.ToString()); _writer.Flush(); } finally { _writer.Close(); } } Debug("Создание основного файла пакета xml завершено успешно"); #region Writing Sending Journals // Пишем файл журнала отправок if (_writeSJ) { Debug("Создание файла журнала отправок..."); // Константа xslt-преобразования для получения файла журнала отправок const string xsltScript = @"<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>" + " <xsl:output method='xml' version='1.0' encoding='UTF-8' indent='yes'/>" + " <xsl:param name='mID'></xsl:param>" + " <xsl:param name='origFN'></xsl:param>" + " <xsl:template match='/'>" + " <!--Describe message's root element-->" + " <xsl:element name='Message'>" + " <xsl:attribute name='MessageId'><xsl:value-of select='$mID'></xsl:value-of></xsl:attribute>" + " <xsl:attribute name='MessageCreationTime'><xsl:value-of select='//Message/@MessageCreationTime'/></xsl:attribute>" + " <xsl:attribute name='ObjectOwner'><xsl:text>ECR</xsl:text></xsl:attribute>" + " <xsl:attribute name='ObjectType'><xsl:text>otSendingJournal</xsl:text></xsl:attribute>" + " <xsl:attribute name='OriginFileName'><xsl:value-of select='$origFN'></xsl:value-of></xsl:attribute>" + " <!--Describe object's header element-->" + " <xsl:element name='Object'>" + " <xsl:attribute name='MessageId'><xsl:value-of select='//Message/@MessageId'/></xsl:attribute>" + " <xsl:attribute name='MessagePackageCount'><xsl:value-of select='//Message/@MessagePackageCount'/></xsl:attribute>" + " <xsl:attribute name='MessagePackageNumber'><xsl:value-of select='//Message/@MessagePackageNumber'/></xsl:attribute>" + " <xsl:attribute name='MessageCreationTime'><xsl:value-of select='//Message/@MessageCreationTime'/></xsl:attribute>" + " </xsl:element>" + " </xsl:element>" + " </xsl:template>" + "</xsl:stylesheet>"; using (var _writer = new XmlTextWriter(_tempPath + _xmlSjFilename, Encoding.Default)) { try { // Схема трансформации #pragma warning disable 618,612 var _xslt = new XslTransform(); #pragma warning restore 618,612 _xslt.Load(new XPathDocument(new StringReader(xsltScript))); // Основной файл var _xmlSj = new XmlDocument(); _xmlSj.LoadXml(_outXml.Value.ToString()); // Добиваем нужными параметрами var _argList = new XsltArgumentList(); _argList.AddParam("mID", "", Guid.NewGuid()); _argList.AddParam("origFN", "", _xmlSjFilename); // Выполняем трансформацию _xslt.Transform(_xmlSj, _argList, _writer); _writer.Formatting = Formatting.None; _writer.Flush(); } finally { _writer.Close(); } } Debug("Создание файла журнала отправок завершено успешно"); } #endregion _log.Info( string.Format( "Создание файла пакета xml выполнено успешно. Файл: '{0}', PackageId: {1}", _xmlFilename, _packageId.Value)); break; } finally { if (_conn.State != ConnectionState.Closed) { _conn.Close(); } } } } // full snapshot - standart case "all": break; default: throw new Exception(string.Format("Некорректное значение параметра 'SnapshotType': '{0}'", SnapshotType)); } _log.Info(string.Format("Задание выполнено успешно, key: '{0}'", Key)); } catch (SqlException e) { if (e.Number == 50000) { _log.Info(string.Format("Предупреждение при выполнении задания, key: '{0}'", Key), e); } else { _log.Error(string.Format("Ошибка выполнения задания, key: '{0}'", Key), e); } return; } catch (Exception e) { _log.Error(string.Format("Ошибка выполнения задания, key: '{0}'", Key), e); } } else { // Если объект недоступен, то пишем в лог и выходим _log.Warn(string.Format("Задание: {0} заблокировано. Задание неактивно либо доступ запрещен", Key)); } }
/// <summary> /// Creates an instance of the given type from the specified Internet resource. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="type">The requested type.</param> /// <returns>An newly created instance.</returns> public object CreateInstance(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, Type type) { return(CreateInstance(htmlUrl, xsltUrl, xsltArgs, type, null)); }
/// <summary> /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation. /// </summary> /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp".</param> /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param> /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param> /// <param name="writer">The XmlTextWriter to which you want to save.</param> public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer) { LoadHtmlAsXml(htmlUrl, xsltUrl, xsltArgs, writer, null); }
public System.Xml.XmlReader Transform(System.Xml.XPath.IXPathNavigable input, XsltArgumentList args, System.Xml.XmlResolver resolver) { }
/// <summary> /// Gets the value of the variable specified /// </summary> /// <param name="xsltContext">Context in which this variable is used</param> /// <returns>Value of the variable</returns> public object Evaluate(XsltContext xsltContext) { XsltArgumentList args = ((ExtendedXPathFunctions)xsltContext).ArgumentList; return(args.GetParam(Name, "")); }
public void Transform(System.Xml.XPath.IXPathNavigable input, XsltArgumentList args, System.Xml.XmlWriter output, System.Xml.XmlResolver resolver) { }
/// <summary> /// Constructor /// </summary> /// <param name="nametable"></param> /// <param name="Args"></param> public ExtendedXPathFunctions(NameTable nametable, XsltArgumentList Args) : base(nametable) { ArgumentList = Args; }
/// <summary> /// Transforms the <see cref="XmlDocument"/>. /// </summary> /// <param name="document">The document to be transformed.</param> /// <returns>Returns the resulting <see cref="XmlDocument"/>.</returns> public XmlDocument Transform(XmlDocument document) { XslTransform xslt = new XslTransform(); XsltArgumentList args = new XsltArgumentList(); if (HttpContext.Current == null) { xslt.Load(System.IO.Path.Combine(basePath,this.Type) + ".xslt"); } else { xslt.Load(HttpContext.Current.Server.MapPath(this.Type + ".xslt")); foreach (string key in HttpContext.Current.Request.Params.AllKeys) { try { args.AddParam(key, String.Empty, HttpContext.Current.Request.Params[key]); } catch (Exception ex) { } } } MemoryStream ms = new MemoryStream(); xslt.Transform(document, args, ms); XmlDocument output = new XmlDocument(); output.LoadXml(System.Text.Encoding.ASCII.GetString(ms.ToArray())); return output; }
public bool Generate() { if(!this.isInitialized) { if(!System.IO.File.Exists(PathHelpMe)) { throw new Exception("Did not find the input xml file. passed was: " + PathHelpMe); } if(!System.IO.File.Exists(PathTreeXsl)) { throw new Exception("Did not find the tree xsl file. passed was: " + PathTreeXsl); } if(!System.IO.File.Exists(PathPagesXsl)) { throw new Exception("Did not find the pages xsl file. passed was: " + PathPagesXsl); } init(); } System.IO.StringWriter stringWriter = new System.IO.StringWriter(CultureInfo.CurrentCulture); System.Xml.XmlDocument xmlPages = new System.Xml.XmlDocument(); System.Xml.XmlNodeList pageNodes; string fileName = ""; string title=""; System.Xml.Xsl.XsltArgumentList args = new XsltArgumentList(); if(this.IsHtmlOutput) { // this makes the tree... #if (DOT_NET_VERSION_10) xslTree.Transform(this.PathHelpMe, this.PathOut + "\\tree.htm"); #else xslTree.Transform(this.PathHelpMe, this.PathOut + "\\tree.htm", null); #endif args.AddParam("ShowSyncTree","","true"); } else { args.AddParam("ShowSyncTree","","false"); } // this makes the html pages in one big xml file... #if (DOT_NET_VERSION_10) xslPages.Transform(this.xmlHelpMe, args, stringWriter); #else xslPages.Transform(this.xmlHelpMe, args, stringWriter, null); #endif // save a page for each page in the pages.xml... xmlPages.LoadXml(stringWriter.ToString()); pageNodes = xmlPages.SelectNodes("/root/page"); // for the index (only used if IsHtmlOutput is true) string innerText = ""; System.Xml.XmlDocument xmlIndex = new System.Xml.XmlDocument(); System.Xml.XmlElement elem; System.Xml.XmlCDataSection cdata; xmlIndex.LoadXml("<root/>"); for(int i=0;i<pageNodes.Count;i++) { // make and save an htm for each page... fileName = pageNodes[i].SelectSingleNode("@name").Value; title = pageNodes[i].SelectSingleNode("@title").Value; System.IO.StreamWriter streamWriter = System.IO.File.CreateText(this.PathOut + "\\" + fileName); streamWriter.Write("<html xmlns:v=\"urn:schemas-microsoft-com:vml\">" + pageNodes[i].SelectSingleNode("html").InnerXml + "</html>"); streamWriter.Close(); if(this.IsHtmlOutput) { // have to do this replace cuz we don't want // their ]]> (if one is present) to break our cdata section... innerText = pageNodes[i].InnerText.Replace("]]>","]]"); elem = xmlIndex.CreateElement("page"); cdata = xmlIndex.CreateCDataSection(innerText); elem.SetAttribute("title",title); elem.SetAttribute("name",fileName); elem.AppendChild(cdata); // add this page to the index... xmlIndex.DocumentElement.AppendChild(elem); } } if(this.IsHtmlOutput) { xmlIndex.Save(this.PathOut + "\\indexText.xml"); } return true; }
/// <summary> /// Transform XML from a file and write to file /// </summary> /// <param name="xct">Object</param> /// <param name="infilename">Path to XML file</param> /// <param name="arguments">Arguments for XSLT</param> /// <param name="outfilename">Path to output file</param> public static void TransformFileToFile(this XslCompiledTransform xct, string infilename, XsltArgumentList arguments, string outfilename) { File.WriteAllText(outfilename, xct.TransformFileToString(infilename, arguments), Encoding.UTF8); }
internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { Debug.Assert(data != null); string[] names = data.Names; Int32Pair[] filters = data.Filters; WhitespaceRuleLookup wsRules; int i; // Early-Bound Library Objects wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; _ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); _xsltLib = null; _earlyInfo = data.EarlyBound; _earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null; // Global variables and parameters _globalNames = data.GlobalNames; _globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null; // Names _nameTableQuery = _ctxt.QueryNameTable; _atomizedNames = null; if (names != null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = _ctxt.DefaultNameTable; _atomizedNames = new string[names.Length]; if (nameTableDefault != _nameTableQuery && nameTableDefault != null) { // Ensure that atomized names from the default data source are added to the // name table used in this query for (i = 0; i < names.Length; i++) { string name = nameTableDefault.Get(names[i]); _atomizedNames[i] = _nameTableQuery.Add(name ?? names[i]); } } else { // Enter names into nametable used in this query for (i = 0; i < names.Length; i++) { _atomizedNames[i] = _nameTableQuery.Add(names[i]); } } } // Name filters _filters = null; if (filters != null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. _filters = new XmlNavigatorFilter[filters.Length]; for (i = 0; i < filters.Length; i++) { _filters[i] = XmlNavNameFilter.Create(_atomizedNames[filters[i].Left], _atomizedNames[filters[i].Right]); } } // Prefix maping lists _prefixMappingsList = data.PrefixMappingsList; // Xml types _types = data.Types; // Xml collations _collations = data.Collations; // Document ordering _docOrderCmp = new DocumentOrderComparer(); // Indexes _indexes = null; // Output construction _stkOutput = new Stack <XmlQueryOutput>(16); _output = new XmlQueryOutput(this, seqWrt); }
public void Transform(string inputUri, XsltArgumentList arguments, System.IO.TextWriter results) { }
/// <summary> /// Transform xml data based on xslt stylesheet, then save the results to a string writer. /// </summary> /// <param name="xmlInput">The xml to transform.</param> /// <param name="xslTransform">The loaded xslt stylesheet.</param> /// <param name="xsltArguments">Xslt arguments for this transform, such as extension objects.</param> /// <returns></returns> public static StringWriter Transform(XmlReader xmlInput, XslCompiledTransform xslTransform, XsltArgumentList xsltArguments) { // Create StringWriter to store results. StringWriter results = new StringWriter(); // Transform data using xslt stylesheet. xslTransform.Transform(xmlInput, xsltArguments, results); return(results); }
//----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryRuntime(XmlILCommand cmd, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { Debug.Assert(cmd != null, "Command object must be non-null"); string[] names = cmd.Names; Int32Pair[] filters = cmd.Filters; WhitespaceRuleLookup wsRules; int i; this.cmd = cmd; // Early-Bound Library Objects wsRules = (cmd.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(cmd.WhitespaceRules) : null; this.ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); this.xsltLib = null; this.earlyInfo = cmd.EarlyBound; this.earlyObjects = (this.earlyInfo != null) ? new object[earlyInfo.Length] : null; // Global variables and parameters this.globalNames = cmd.GlobalNames; this.globalValues = (this.globalNames != null) ? new object[this.globalNames.Length] : null; // Names this.nameTableQuery = this.ctxt.QueryNameTable; this.atomizedNames = null; if (names != null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = ctxt.DefaultNameTable; this.atomizedNames = new string[names.Length]; if (nameTableDefault != this.nameTableQuery && nameTableDefault != null) { // Ensure that atomized names from the default data source are added to the // name table used in this query for (i = 0; i < names.Length; i++) { string name = nameTableDefault.Get(names[i]); this.atomizedNames[i] = this.nameTableQuery.Add(name ?? names[i]); } } else { // Enter names into nametable used in this query for (i = 0; i < names.Length; i++) this.atomizedNames[i] = this.nameTableQuery.Add(names[i]); } } // Name filters this.filters = null; if (filters != null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. this.filters = new XmlNavigatorFilter[filters.Length]; for (i = 0; i < filters.Length; i++) this.filters[i] = XmlNavNameFilter.Create(this.atomizedNames[filters[i].Left], this.atomizedNames[filters[i].Right]); } // Prefix maping lists this.prefixMappingsList = cmd.PrefixMappingsList; // Xml types this.types = cmd.Types; // Xml collations this.collations = cmd.Collations; // Document ordering this.docOrderCmp = new DocumentOrderComparer(); // Indexes this.indexes = null; // Output construction this.stkOutput = new Stack<XmlQueryOutput>(16); this.output = new XmlQueryOutput(this, seqWrt); }
private void DrawProfilesModule() { XsltArgumentList args = new XsltArgumentList(); long offset = 0; long perpage = 0; long totalcount = 0; long totalpageremainder = 0; long totalpages = 0; long startrecord = 0; long page = 0; string searchfor = ""; string classgroupuri = ""; string classuri = ""; string fname = ""; string lname = ""; string institution = ""; string department = ""; string division = ""; string sort = ""; string sortdirection = ""; string searchrequest = ""; XmlDocument xmlsearchrequest; xmlsearchrequest = new XmlDocument(); Int16 showcolumns = 0; string otherfilters = ""; string institutionallexcept = string.Empty; string departmentallexcept = string.Empty; string divisionallexcept = string.Empty; string exactphrase = "false"; // UCSF default value to allow old Mini Search to work string searchtype = ""; Search.Utilities.DataIO data = new Profiles.Search.Utilities.DataIO(); if (String.IsNullOrEmpty(Request.QueryString["searchrequest"]) == false) { searchrequest = data.DecryptRequest(Request.QueryString["searchrequest"]); xmlsearchrequest.LoadXml(searchrequest); } else if (string.IsNullOrEmpty(base.MasterPage.SearchRequest) == false) { searchrequest = data.DecryptRequest(base.MasterPage.SearchRequest); xmlsearchrequest.LoadXml(searchrequest); } if (String.IsNullOrEmpty(Request.QueryString["searchtype"]) == false) { searchtype = Request.QueryString["searchtype"]; } else if (String.IsNullOrEmpty(Request.Form["searchtype"]) == false) { searchtype = Request.Form["searchtype"]; } if (String.IsNullOrEmpty(Request.QueryString["searchfor"]) == false) { searchfor = Request.QueryString["searchfor"]; //exactphrase = Request.QueryString["exactphrase"]; This is causing a bug. We test and set this if present later in this block anyway } else if (String.IsNullOrEmpty(Request.Form["txtSearchFor"]) == false) { searchfor = Request.Form["txtSearchFor"]; } else if (xmlsearchrequest.ChildNodes.Count > 0) { try { searchfor = xmlsearchrequest.SelectSingleNode("SearchOptions/MatchOptions/SearchString").InnerText; } catch (Exception) { // Do nothing, leave searchfor = null } } if (searchfor == null) { searchfor = string.Empty; } if (String.IsNullOrEmpty(Request.QueryString["lname"]) == false) { lname = Request.QueryString["lname"]; } else { lname = Request.Form["txtLname"]; } if (lname == null) { lname = string.Empty; } if (String.IsNullOrEmpty(Request.QueryString["fname"]) == false) { fname = Request.QueryString["fname"]; } else { fname = Request.Form["txtFname"]; } if (fname == null) { fname = string.Empty; } if (String.IsNullOrEmpty(Request.QueryString["institution"]) == false) { institution = Request.QueryString["institution"]; } if (String.IsNullOrEmpty(Request.QueryString["department"]) == false) { department = Request.QueryString["department"]; } if (String.IsNullOrEmpty(Request.QueryString["division"]) == false) { division = Request.QueryString["division"]; } if (String.IsNullOrEmpty(Request.QueryString["perpage"]) == false) { perpage = Convert.ToInt64(Request.QueryString["perpage"]); if (!(perpage > 0)) { perpage = 15; } //if (String.IsNullOrEmpty(Request.QueryString["perpage"])==false) // perpage = Convert.ToInt64(Request.QueryString["perpage"]); //else // perpage = 15; } else { perpage = 15; //default } if (String.IsNullOrEmpty(Request.QueryString["offset"]) == false) { offset = Convert.ToInt64(Request.QueryString["offset"]); //if (Request.QueryString["offset"] != string.Empty) // offset = Convert.ToInt64(Request.QueryString["offset"]); //else // offset = 0; } else { offset = 0; } if (String.IsNullOrEmpty(Request.QueryString["page"]) == false) { page = Convert.ToInt64(Request.QueryString["page"]); if (!(page > 0)) { page = 1; } //if (Request.QueryString["page"] != string.Empty) // page = Convert.ToInt64(Request.QueryString["page"]); //else // page = 1; } else { page = 1; } if (String.IsNullOrEmpty(Request.QueryString["classgroupuri"]) == false) { classgroupuri = HttpUtility.UrlDecode(Request.QueryString["classgroupuri"]); } else { classgroupuri = HttpUtility.UrlDecode(Request.Form["classgroupuri"]); } if (classgroupuri != null) { if (classgroupuri.Contains("!")) { classgroupuri = classgroupuri.Replace('!', '#'); } } else { classgroupuri = string.Empty; } if (String.IsNullOrEmpty(Request.QueryString["classuri"]) == false) { classuri = HttpUtility.UrlDecode(Request.QueryString["classuri"]); } else { classuri = HttpUtility.UrlDecode(Request.Form["classuri"]); } if (classuri != null) { if (classuri.Contains("!")) { classuri = classuri.Replace('!', '#'); } } else { classuri = string.Empty; } if (String.IsNullOrEmpty(Request.QueryString["sortby"]) == false) { sort = Request.QueryString["sortby"]; } if (String.IsNullOrEmpty(Request.QueryString["sortdirection"]) == false) { sortdirection = Request.QueryString["sortdirection"]; } if (String.IsNullOrEmpty(Request.QueryString["showcolumns"]) == false) { showcolumns = Convert.ToInt16(Request.QueryString["showcolumns"]); } else { showcolumns = 1; } if (String.IsNullOrEmpty(Request.QueryString["otherfilters"]) == false) { otherfilters = Request.QueryString["otherfilters"]; } if (String.IsNullOrEmpty(Request.QueryString["institutionallexcept"]) == false) { institutionallexcept = Request.QueryString["institutionallexcept"]; } if (String.IsNullOrEmpty(Request.QueryString["departmentallexcept"]) == false) { departmentallexcept = Request.QueryString["departmentallexcept"]; } if (String.IsNullOrEmpty(Request.QueryString["divisionallexcept"]) == false) { divisionallexcept = Request.QueryString["divisionallexcept"]; } if (String.IsNullOrEmpty(Request.QueryString["exactphrase"]) == false) { exactphrase = Request.QueryString["exactphrase"]; } try { totalcount = data.GetTotalSearchConnections(this.SearchData, base.Namespaces); if (page < 0) { page = 1; } totalpages = Math.DivRem(totalcount, Convert.ToInt64(perpage), out totalpageremainder); if (totalpageremainder > 0) { totalpages = totalpages + 1; } if (page > totalpages) { page = totalpages; } startrecord = ((Convert.ToInt32(page) * Convert.ToInt32(perpage)) + 1) - Convert.ToInt32(perpage); if (startrecord < 0) { startrecord = 1; } if (searchrequest.Trim() != string.Empty) { searchrequest = data.EncryptRequest(searchrequest); } List <GenericListItem> g = new List <GenericListItem>(); g = data.GetListOfFilters(); if (otherfilters.IsNullOrEmpty() && base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description/vivo:overview/SearchOptions/MatchOptions/SearchFiltersList/SearchFilter[@Property='http://profiles.catalyst.harvard.edu/ontology/prns#hasPersonFilter']", base.Namespaces) != null) { string s = string.Empty; foreach (XmlNode x in base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description/vivo:overview/SearchOptions/MatchOptions/SearchFiltersList/SearchFilter[@Property='http://profiles.catalyst.harvard.edu/ontology/prns#hasPersonFilter']", base.Namespaces)) { s = data.GetConvertedURIListItem(g, x.InnerText); otherfilters += "," + s; } } switch (searchtype.ToLower()) { case "everything": xmlsearchrequest = data.SearchRequest(searchfor, exactphrase, classgroupuri, classuri, perpage.ToString(), (startrecord - 1).ToString()); break; default: xmlsearchrequest = data.SearchRequest(searchfor, exactphrase, fname, lname, institution, institutionallexcept, department, departmentallexcept, division, divisionallexcept, "http://xmlns.com/foaf/0.1/Person", perpage.ToString(), (startrecord - 1).ToString(), sort, sortdirection, otherfilters, "", ref searchrequest); break; } this.SearchData = data.Search(xmlsearchrequest, false); this.SearchRequest = data.EncryptRequest(xmlsearchrequest.OuterXml); base.MasterPage.SearchRequest = this.SearchRequest; base.MasterPage.RDFData = this.SearchData; base.MasterPage.RDFNamespaces = this.Namespaces; // only shows these if we are not doing an everything search, or we are looking at people in the everything search if (!"everything".Equals(searchtype.ToLower()) || "http://profiles.catalyst.harvard.edu/ontology/prns#ClassGroupPeople".Equals(classgroupuri)) { new ORNGSearchRPCService(Page, this.SearchData, xmlsearchrequest, this.Namespaces); } } catch (DisallowedSearchException se) { litEverythingResults.Text = se.Message; return; } catch (Exception ex) { ex = ex; DebugLogging.Log("ERROR" + ex.Message); //for now just flip it back to the defaults. This is if someone keys some funky divide by zero stuff in the URL // to try and break the system. startrecord = 1; perpage = 15; } args.AddParam("root", "", Root.Domain); args.AddParam("perpage", "", perpage); args.AddParam("offset", "", offset); args.AddParam("totalpages", "", totalpages); args.AddParam("page", "", page); args.AddParam("searchfor", "", searchfor); args.AddParam("exactphrase", "", exactphrase); args.AddParam("classGrpURIpassedin", "", classgroupuri); args.AddParam("classURIpassedin", "", classuri); args.AddParam("searchrequest", "", this.SearchRequest); switch (searchtype.ToLower()) { case "everything": litEverythingResults.Text = XslHelper.TransformInMemory(Server.MapPath("~/Search/Modules/SearchResults/EverythingResults.xslt"), args, this.SearchData.OuterXml); break; case "people": args.AddParam("showcolumns", "", showcolumns.ToString()); if ((showcolumns & 1) == 1) { args.AddParam("institution", "", "true"); } else { args.AddParam("institution", "", "false"); } if ((showcolumns & 2) == 2) { args.AddParam("department", "", "true"); } else { args.AddParam("department", "", "false"); } if ((showcolumns & 8) == 8) { args.AddParam("facrank", "", "true"); } else { args.AddParam("facrank", "", "false"); } //Profiles.Search.Utilities.DataIO dropdowns = new Profiles.Search.Utilities.DataIO(); if (Convert.ToBoolean(ConfigurationSettings.AppSettings["ShowInstitutions"]) == true) { args.AddParam("ShowInstitutions", "", "true"); } else { args.AddParam("ShowInstitutions", "", "false"); } if (Convert.ToBoolean(ConfigurationSettings.AppSettings["ShowDepartments"]) == true) { args.AddParam("ShowDepartments", "", "true"); } else { args.AddParam("ShowDepartments", "", "false"); } //Faculty Rank always shows args.AddParam("ShowFacRank", "", "true"); args.AddParam("currentsort", "", sort); args.AddParam("currentsortdirection", "", sortdirection); if (base.BaseData.SelectNodes("rdf:RDF/rdf:Description/vivo:overview/SearchDetails/SearchPhraseList", base.Namespaces).Count > 0) { args.AddParam("why", "", true); } else { args.AddParam("why", "", false); } litEverythingResults.Text = HttpUtility.HtmlDecode(XslHelper.TransformInMemory(Server.MapPath("~/Search/Modules/SearchResults/PeopleResults.xslt"), args, this.SearchData.OuterXml)); break; } }
public static Stream XslTransform(string resource, Stream input, params DictionaryEntry[] entries) { int t1 = Environment.TickCount; Stream s = Util.GetEmbeddedResourceStream(resource); int t2 = Environment.TickCount; XPathDocument d = new XPathDocument(s); Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "new XPathDocument(1) t={0}", Environment.TickCount - t2)); int t3 = Environment.TickCount; var xslc = new XslCompiledTransform(); // Using the Trusted Xslt is fine as the style sheet comes from our own assemblies. // This is similar to the prior this.GetType().Assembly/Evidence method that was used in the now depricated XslTransform. xslc.Load(d, XsltSettings.TrustedXslt, s_resolver); Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform.Load t={0}", Environment.TickCount - t3)); // Need to copy input stream because XmlReader will close it, // causing errors for later callers that access the same stream var clonedInput = new MemoryStream(); Util.CopyStream(input, clonedInput); int t4 = Environment.TickCount; XmlReader xml = XmlReader.Create(clonedInput); Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "new XmlReader(2) t={0}", Environment.TickCount - t4)); XsltArgumentList args = null; if (entries.Length > 0) { args = new XsltArgumentList(); foreach (DictionaryEntry entry in entries) { string key = entry.Key.ToString(); object val = entry.Value.ToString(); args.AddParam(key, "", val); Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "arg: key='{0}' value='{1}'", key, val.ToString())); } } var m = new MemoryStream(); var w = new XmlTextWriter(m, Encoding.UTF8); w.WriteStartDocument(); int t5 = Environment.TickCount; xslc.Transform(xml, args, w, s_resolver); Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform.Transform t={0}", Environment.TickCount - t4)); w.WriteEndDocument(); w.Flush(); m.Position = 0; Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform(\"{0}\") t={1}", resource, Environment.TickCount - t1)); return(m); }
/// <summary> /// This is used to transform a *.topic file into a *.html file using /// an XSLT transformation based on the presentation style. /// </summary> /// <param name="sourceFile">The source topic filename</param> private void XslTransform(string sourceFile) { TocEntry tocInfo; XmlReader reader = null; XmlWriter writer = null; XsltSettings settings; XmlReaderSettings readerSettings; XmlWriterSettings writerSettings; Encoding enc = Encoding.Default; FileItemCollection transforms; string content; string sourceStylesheet, destFile = Path.ChangeExtension(sourceFile, ".html"); try { readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; readerSettings.CloseInput = true; // Create the transform on first use if (xslTransform == null) { transforms = new FileItemCollection(project, BuildAction.TopicTransform); if (transforms.Count != 0) { if (transforms.Count > 1) { this.ReportWarning("BE0011", "Multiple topic " + "transformations found. Using '{0}'", transforms[0].FullPath); } sourceStylesheet = transforms[0].FullPath; } else { sourceStylesheet = templateFolder + presentationParam + ".xsl"; } xslStylesheet = workingFolder + Path.GetFileName(sourceStylesheet); tocInfo = BuildProcess.GetTocInfo(sourceStylesheet); // The stylesheet may contain shared content items so we // must resolve it this way rather than using // TransformTemplate. this.ResolveLinksAndCopy(sourceStylesheet, xslStylesheet, tocInfo); xslTransform = new XslCompiledTransform(); settings = new XsltSettings(true, true); xslArguments = new XsltArgumentList(); xslTransform.Load(XmlReader.Create(xslStylesheet, readerSettings), settings, new XmlUrlResolver()); } this.ReportProgress("Applying XSL transformation '{0}' to '{1}'.", xslStylesheet, sourceFile); reader = XmlReader.Create(sourceFile, readerSettings); writerSettings = xslTransform.OutputSettings.Clone(); writerSettings.CloseOutput = true; writerSettings.Indent = false; writer = XmlWriter.Create(destFile, writerSettings); xslArguments.Clear(); xslArguments.AddParam("pathToRoot", String.Empty, pathToRoot); xslTransform.Transform(reader, xslArguments, writer); } catch (Exception ex) { throw new BuilderException("BE0017", String.Format( CultureInfo.InvariantCulture, "Unexpected error " + "using '{0}' to transform additional content file '{1}' " + "to '{2}'. The error is: {3}\r\n{4}", xslStylesheet, sourceFile, destFile, ex.Message, (ex.InnerException == null) ? String.Empty : ex.InnerException.Message)); } finally { if (reader != null) { reader.Close(); } if (writer != null) { writer.Flush(); writer.Close(); } } // The source topic file is deleted as the transformed file // takes its place. File.Delete(sourceFile); // <span> and <script> tags cannot be self-closing if empty. // The template may contain them correctly but when written out // as XML, they get converted to self-closing tags which breaks // them. To fix them, convert them to full start and close tags. content = BuildProcess.ReadWithEncoding(destFile, ref enc); content = reSpanScript.Replace(content, "<$1$2></$1>"); // An XSL transform might have added tags and include items that // need replacing so run it through those options if needed. tocInfo = BuildProcess.GetTocInfo(destFile); // Expand <code> tags if necessary if (tocInfo.HasCodeBlocks) { content = reCodeBlock.Replace(content, codeBlockMatchEval); } // Colorize <pre> tags if necessary if (tocInfo.NeedsColorizing || tocInfo.HasCodeBlocks) { // Initialize code colorizer on first use if (codeColorizer == null) { codeColorizer = new CodeColorizer(shfbFolder + @"Colorizer\highlight.xml", shfbFolder + @"Colorizer\highlight.xsl"); } // Set the path the "Copy" image codeColorizer.CopyImageUrl = pathToRoot + "icons/CopyCode.gif"; // Colorize it and replace the "Copy" literal text with the // shared content include item so that it gets localized. content = codeColorizer.ProcessAndHighlightText(content); content = content.Replace(codeColorizer.CopyText + "</span", "<include item=\"copyCode\"/></span"); tocInfo.HasProjectTags = true; } // Use a regular expression to find and replace all tags with // cref attributes with a link to the help file content. This // needs to happen after the code block processing as they // may contain <see> tags that need to be resolved. if (tocInfo.HasLinks || tocInfo.HasCodeBlocks) { content = reResolveLinks.Replace(content, linkMatchEval); } // Replace project option tags with project option values if (tocInfo.HasProjectTags) { // Project tags can be nested while (reProjectTags.IsMatch(content)) { content = reProjectTags.Replace(content, fieldMatchEval); } // Shared content items can be nested while (reSharedContent.IsMatch(content)) { content = reSharedContent.Replace(content, contentMatchEval); } } // Write the file back out with the appropriate encoding using (StreamWriter sw = new StreamWriter(destFile, false, enc)) { sw.Write(content); } }
public static string Transform(string input, PipelineCommand command, ExecutionLog log) { var xml = string.Empty; var xsl = command.GetArgument("xslt"); // This adds an extension object for XSL transforms var arguments = new XsltArgumentList(); arguments.AddExtensionObject("http://denina", new XsltExtensions()); // Do we want to pass in a custom extension object? if (Pipeline.IsSetGlobally(XSLT_ARGUMENT_VARIABLE_NAME)) { var namespaceName = "ext"; var className = Pipeline.GetGlobalVariable(XSLT_ARGUMENT_VARIABLE_NAME).ToString(); // If they want to specify a custom namespace via "=", split and reassign the namespace and class names. if (className.Contains('=')) { namespaceName = className.Split('=').First(); className = className.Split('=').Last(); } // Try to get the object ObjectHandle extensionObject; try { extensionObject = Activator.CreateInstance(className.Split(',').Last(), className.Split(',').First()); } catch (Exception e) { throw new DeninaException(String.Format("Unable to load XsltExtension object \"{0}\"", className), e); } arguments.AddExtensionObject(String.Concat("http://", namespaceName), extensionObject.Unwrap()); } // If there are two arguments, assume the second is XML if (command.HasArgument("xml")) { xml = command.GetArgument("xml"); } else { // Otherwise, the XML is the input xml = input; } // Set some basic parameters for our XML reading... var settings = new XmlReaderSettings() { IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true }; // Form the XML doc from the input XmlReader xmlReader; try { xmlReader = XmlReader.Create(new StringReader(xml), settings); } catch (Exception e) { throw new DeninaException("Error parsing XML.", e); } // Form the XSL from the first argument XslCompiledTransform transform; try { transform = new XslCompiledTransform(); transform.Load(XmlReader.Create(new StringReader(xsl), settings)); } catch (Exception e) { throw new DeninaException("Error parsing XSL.", e); } // Do the transform (we're passing in an empty XsltArgumentList as a placeholder, in case we want to do something with it later...) var writer = new StringWriter(); try { transform.Transform(xmlReader, arguments, writer); } catch (Exception e) { throw new DeninaException("Error performing XSLT transform.", e); } return(writer.ToString().Replace("\u00A0", " ")); // This is a bit of a hack. We're replacing NO BREAK SPACE with a regular space. There has to be a way to fix this in the XSLT output. }
//===================================================================== /// <summary> /// Main program entry point /// </summary> /// <param name="args">Command line arguments</param> /// <returns>Zero on success or non-zero on failure</returns> public static int Main(string[] args) { ConsoleApplication.WriteBanner(); // Specify options OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new ListOption("xsl", "Specify one or more XSL transform files.", "xsltPath") { RequiredMessage = "Specify at least one XSL transform file" }, new ListOption("arg", "Specify arguments.", "name=value"), new StringOption("out", "Specify an output file. If unspecified, output goes to the " + "console.", "outputFilePath"), new SwitchOption("w", "Do not ignore insignificant whitespace. By default " + "insignificant whitespace is ignored.") }; // Process options ParseArgumentsResult results = options.ParseArguments(args); if (results.Options["?"].IsPresent) { Console.WriteLine("XslTransform [options] xml_file"); options.WriteOptionSummary(Console.Out); return(1); } // Check for invalid options if (!results.Success) { results.WriteParseErrors(Console.Out); return(1); } // Check for missing or extra input files if (results.UnusedArguments.Count != 1) { Console.WriteLine("Specify one input XML input file."); return(1); } // Set whitespace setting bool ignoreWhitespace = !results.Options["w"].IsPresent; // Load transforms string[] transformFiles = (string[])results.Options["xsl"].Value; XslCompiledTransform[] transforms = new XslCompiledTransform[transformFiles.Length]; for (int i = 0; i < transformFiles.Length; i++) { string transformFile = Environment.ExpandEnvironmentVariables(transformFiles[i]); transforms[i] = new XslCompiledTransform(); XsltSettings transformSettings = new XsltSettings(true, true); try { transforms[i].Load(transformFile, transformSettings, new XmlUrlResolver()); } catch (IOException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " + "loaded. The error is: {1}", transformFile, e.Message); return(1); } catch (UnauthorizedAccessException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' could not be " + "loaded. The error is: {1}", transformFile, e.Message); return(1); } catch (XsltException e) { if (e.InnerException != null) { ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " + "not valid. The error is: {1}", transformFile, e.InnerException.Message); } else { ConsoleApplication.WriteMessage(LogLevel.Error, "The transformation file '{0}' is " + "not valid. The error is: {1}", transformFile, e.Message); } return(1); } catch (XmlException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The transform file '{0}' is not " + "well-formed. The error is: {1}", transformFile, e.Message); return(1); } } // Compose the arguments XsltArgumentList arguments = new XsltArgumentList(); if (results.Options["arg"].IsPresent) { string[] nameValueStrings = (string[])results.Options["arg"].Value; foreach (string nameValueString in nameValueStrings) { string[] nameValuePair = nameValueString.Split('='); if (nameValuePair.Length != 2) { continue; } arguments.AddParam(nameValuePair[0], String.Empty, nameValuePair[1]); } } string input = Environment.ExpandEnvironmentVariables(results.UnusedArguments[0]); // Prepare the reader XmlReaderSettings readerSettings = new XmlReaderSettings { IgnoreWhitespace = ignoreWhitespace, CloseInput = true }; // Do each transform for (int i = 0; i < transforms.Length; i++) { ConsoleApplication.WriteMessage(LogLevel.Info, "Applying XSL transformation '{0}'.", transformFiles[i]); // Get the transform XslCompiledTransform transform = transforms[i]; // Figure out where to put the output string output; if (i < transforms.Length - 1) { try { output = Path.GetTempFileName(); File.SetAttributes(output, FileAttributes.Temporary); } catch (IOException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while attempting " + "to create a temporary file. The error message is: {0}", e.Message); return(1); } } else if (results.Options["out"].IsPresent) { output = Environment.ExpandEnvironmentVariables((string)results.Options["out"].Value); } else { output = null; } // Create a reader Stream readStream; try { readStream = File.Open(input, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); } catch (IOException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " + "loaded. The error is: {1}", input, e.Message); return(1); } catch (UnauthorizedAccessException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' could not be " + "loaded. The error is: {1}", input, e.Message); return(1); } using (XmlReader reader = XmlReader.Create(readStream, readerSettings)) { // Create a writer Stream outputStream; if (output == null) { outputStream = Console.OpenStandardOutput(); } else { try { outputStream = File.Open(output, FileMode.Create, FileAccess.Write, FileShare.Read | FileShare.Delete); } catch (IOException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " + "be created. The error is: {1}", output, e.Message); return(1); } catch (UnauthorizedAccessException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The output file '{0}' could not " + "be created. The error is: {1}", output, e.Message); return(1); } } // Transform the file using (XmlWriter writer = XmlWriter.Create(outputStream, transform.OutputSettings)) { try { transform.Transform(reader, arguments, writer); } catch (TargetInvocationException e) { // If performing the Add Filenames transform and using GUID naming, the MD5 hashing // algorithm can be blocked if the FIPS policy is enabled. In such cases, tell the // user to switch to Member Name or Hashed Member Name as the naming method. This is // rare and using the alternate naming method is easier than replacing the MD5 // hashing which would be a significant breaking change. Exception fipsEx = e; while (fipsEx != null) { if (fipsEx is InvalidOperationException && fipsEx.Message.IndexOf(" FIPS ", StringComparison.Ordinal) != -1) { break; } fipsEx = fipsEx.InnerException; } if (fipsEx == null) { throw; } ConsoleApplication.WriteMessage(LogLevel.Error, "The FIPS validated cryptographic " + "algorithms policy appears to be enabled. This prevents the MD5 hashing algorithm " + "from being used to generate GUID topic filenames. Change the project's Naming " + "Method property to either Member Name or Hashed Member Name which do not rely " + "on the MD5 hashing algorithm."); return(1); } catch (XsltException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred during the " + "transformation. The error message is: {0}", (e.InnerException == null) ? e.Message : e.InnerException.Message); return(1); } catch (XmlException e) { ConsoleApplication.WriteMessage(LogLevel.Error, "The input file '{0}' is not " + "well-formed. The error is: {1}", input, e.Message); return(1); } } // If not using the console, close the output file or we sometimes get "file in use" errors // if we're quick enough and the garbage collector hasn't taken care of it. if (output != null) { outputStream.Close(); } } // If the last input was a temp file, delete it if (i > 0) { try { File.Delete(input); } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " + "be deleted. The error message is: {1}", input, ioEx.Message); } catch (UnauthorizedAccessException uaEx) { // !EFW - Virus scanners can sometimes cause an unauthorized access exception too ConsoleApplication.WriteMessage(LogLevel.Warn, "The temporary file '{0}' could not " + "be deleted. The error message is: {1}", input, uaEx.Message); } } // The last output file is the next input file input = output; if (Canceled) { ConsoleApplication.WriteMessage(LogLevel.Error, "XslTransform task canceled"); break; } } return(Canceled ? 1 : 0); }
public void Transform(System.Xml.XPath.XPathNavigator input, XsltArgumentList args, System.IO.TextWriter output, System.Xml.XmlResolver resolver) { }
protected override void ExecuteTask() { // ensure base directory is set, even if fileset was not initialized // from XML if (InFiles.BaseDirectory == null) { InFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory); } StringCollection srcFiles = null; if (SrcFile != null) { srcFiles = new StringCollection(); srcFiles.Add(SrcFile.FullName); } else if (InFiles.FileNames.Count > 0) { if (OutputFile != null) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1148")), Location); } srcFiles = InFiles.FileNames; } if (srcFiles == null || srcFiles.Count == 0) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1147")), Location); } if (XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); if (!fileInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), fileInfo.FullName), Location); } } else { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(XsltFile); if (Proxy != null) { request.Proxy = Proxy.GetWebProxy(); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (response.StatusCode != HttpStatusCode.OK) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1149"), XsltFile), Location); } } foreach (string srcFile in srcFiles) { string destFile = null; if (OutputFile != null) { destFile = OutputFile.FullName; } if (String.IsNullOrEmpty(destFile)) { // TODO: use System.IO.Path (gs) // append extension if necessary string ext = Extension.IndexOf(".") > -1 ? Extension : "." + Extension; int extPos = srcFile.LastIndexOf('.'); if (extPos == -1) { destFile = srcFile + ext; } else { destFile = srcFile.Substring(0, extPos) + ext; } destFile = Path.GetFileName(destFile); } FileInfo srcInfo = new FileInfo(srcFile); FileInfo destInfo = new FileInfo(Path.GetFullPath(Path.Combine( DestDir.FullName, destFile))); if (!srcInfo.Exists) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1150"), srcInfo.FullName), Location); } bool destOutdated = !destInfo.Exists || srcInfo.LastWriteTime > destInfo.LastWriteTime; if (!destOutdated && XsltFile.IsFile) { FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); destOutdated |= fileInfo.LastWriteTime > destInfo.LastWriteTime; } if (destOutdated) { XmlReader xmlReader = null; XmlReader xslReader = null; TextWriter writer = null; try { // store current directory string originalCurrentDirectory = Directory.GetCurrentDirectory(); // initialize XPath document holding input XML XPathDocument xml = null; try { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly Directory.SetCurrentDirectory(srcInfo.DirectoryName); // load the xml that needs to be transformed Log(Level.Verbose, "Loading XML file '{0}'.", srcInfo.FullName); xmlReader = CreateXmlReader(new Uri(srcInfo.FullName)); xml = new XPathDocument(xmlReader); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } // initialize xslt parameters XsltArgumentList xsltArgs = new XsltArgumentList(); // set the xslt parameters foreach (XsltParameter parameter in Parameters) { if (IfDefined && !UnlessDefined) { xsltArgs.AddParam(parameter.ParameterName, parameter.NamespaceUri, parameter.Value); } } // create extension objects foreach (XsltExtensionObject extensionObject in ExtensionObjects) { if (extensionObject.IfDefined && !extensionObject.UnlessDefined) { object extensionInstance = extensionObject.CreateInstance(); xsltArgs.AddExtensionObject(extensionObject.NamespaceUri, extensionInstance); } } try { if (XsltFile.IsFile) { // change current directory to directory containing // XSLT file, to allow includes to be resolved // correctly FileInfo fileInfo = new FileInfo(XsltFile.LocalPath); Directory.SetCurrentDirectory(fileInfo.DirectoryName); } // load the stylesheet Log(Level.Verbose, "Loading stylesheet '{0}'.", XsltFile); xslReader = CreateXmlReader(XsltFile); // create writer for the destination xml writer = CreateWriter(destInfo.FullName); // do the actual transformation Log(Level.Info, "Processing '{0}' to '{1}'.", srcInfo.FullName, destInfo.FullName); XslCompiledTransform xslt = new XslCompiledTransform(); string xslEngineName = xslt.GetType().Name; Log(Level.Verbose, "Using {0} to load '{1}'.", xslEngineName, XsltFile); xslt.Load(xslReader, new XsltSettings { EnableDocumentFunction = true, EnableScript = true }, new XmlUrlResolver()); Log(Level.Verbose, "Using {0} to process '{1}' to '{2}'.", xslEngineName, srcInfo.FullName, destInfo.FullName); xslt.Transform(xml, xsltArgs, writer); } finally { // restore original current directory Directory.SetCurrentDirectory(originalCurrentDirectory); } } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA1151"), srcInfo.FullName, XsltFile), Location, ex); } finally { // ensure file handles are closed if (xmlReader != null) { xmlReader.Close(); } if (xslReader != null) { xslReader.Close(); } if (writer != null) { writer.Close(); } } } } }
public void Transform(System.Xml.XPath.IXPathNavigable input, XsltArgumentList args, System.IO.TextWriter output) { }
public void Transform(string modelFilePath) { StreamReader sr; string foDoc; MemoryStream ms = new MemoryStream(); XmlResolver resolver = new XmlUrlResolver(); resolver.Credentials = CredentialCache.DefaultCredentials; XmlTextReader doc = new XmlTextReader(modelFilePath); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(this.stylesheetFilesPath + Path.DirectorySeparatorChar + "PdfRtfExport.xsl", null, resolver); XsltArgumentList al = new XsltArgumentList(); AssemblyName an = this.GetType().Assembly.GetName(); al.AddParam("version", "", an.Version.ToString(3)); al.AddParam("outputType", "", "withLink"); al.AddParam("description", "", this.localizer.GetValue("Globals", "Description")); al.AddParam("notes", "", this.localizer.GetValue("Globals", "Notes")); al.AddParam("relatedDocs", "", this.localizer.GetValue("Globals", "RelatedDocuments")); al.AddParam("model", "", this.localizer.GetValue("Globals", "Model")); al.AddParam("actor", "", this.localizer.GetValue("Globals", "Actor")); al.AddParam("goals", "", this.localizer.GetValue("Globals", "Goals")); al.AddParam("useCase", "", this.localizer.GetValue("Globals", "UseCase")); al.AddParam("package", "", this.localizer.GetValue("Globals", "Package")); al.AddParam("actors", "", this.localizer.GetValue("Globals", "Actors")); al.AddParam("useCases", "", this.localizer.GetValue("Globals", "UseCases")); al.AddParam("packages", "", this.localizer.GetValue("Globals", "Packages")); al.AddParam("summary", "", this.localizer.GetValue("Globals", "Summary")); al.AddParam("glossary", "", this.localizer.GetValue("Globals", "Glossary")); al.AddParam("glossaryItem", "", this.localizer.GetValue("Globals", "GlossaryItem")); al.AddParam("stakeholders", "", this.localizer.GetValue("Globals", "Stakeholders")); al.AddParam("stakeholder", "", this.localizer.GetValue("Globals", "Stakeholder")); al.AddParam("preconditions", "", this.localizer.GetValue("Globals", "Preconditions")); al.AddParam("postconditions", "", this.localizer.GetValue("Globals", "Postconditions")); al.AddParam("openIssues", "", this.localizer.GetValue("Globals", "OpenIssues")); al.AddParam("flowOfEvents", "", this.localizer.GetValue("Globals", "FlowOfEvents")); al.AddParam("prose", "", this.localizer.GetValue("Globals", "Prose")); al.AddParam("details", "", this.localizer.GetValue("Globals", "Details")); al.AddParam("priority", "", this.localizer.GetValue("Globals", "Priority")); al.AddParam("status", "", this.localizer.GetValue("Globals", "Status")); al.AddParam("level", "", this.localizer.GetValue("Globals", "Level")); al.AddParam("complexity", "", this.localizer.GetValue("Globals", "Complexity")); al.AddParam("implementation", "", this.localizer.GetValue("Globals", "Implementation")); al.AddParam("assignedTo", "", this.localizer.GetValue("Globals", "AssignedTo")); al.AddParam("release", "", this.localizer.GetValue("Globals", "Release")); al.AddParam("activeActors", "", this.localizer.GetValue("Globals", "ActiveActors")); al.AddParam("primary", "", this.localizer.GetValue("Globals", "Primary")); al.AddParam("history", "", this.localizer.GetValue("Globals", "History")); al.AddParam("statusNodeSet", "", this.localizer.GetNodeSet("cmbStatus", "Item")); al.AddParam("levelNodeSet", "", this.localizer.GetNodeSet("cmbLevel", "Item")); al.AddParam("complexityNodeSet", "", this.localizer.GetNodeSet("cmbComplexity", "Item")); al.AddParam("implementationNodeSet", "", this.localizer.GetNodeSet("cmbImplementation", "Item")); al.AddParam("historyTypeNodeSet", "", this.localizer.GetNodeSet("HistoryType", "Item")); al.AddParam("eventTypeNodeSet", "", this.localizer.GetNodeSet("cmbTriggerEvent", "Item")); al.AddParam("triggerEvent", "", this.localizer.GetValue("Globals", "TriggerEvent")); al.AddParam("triggerDescription", "", this.localizer.GetValue("Globals", "TriggerDescription")); al.AddParam("categoryNodeSet", "", this.localizer.GetNodeSet("cmbCategory", "Item")); al.AddParam("importanceNodeSet", "", this.localizer.GetNodeSet("cmbImportance", "Item")); al.AddParam("acceptanceNodeSet", "", this.localizer.GetNodeSet("cmbAcceptanceStatus", "Item")); al.AddParam("proposedBy", "", this.localizer.GetValue("Globals", "ProposedBy")); al.AddParam("benefitTo", "", this.localizer.GetValue("Globals", "BenefitTo")); al.AddParam("category", "", this.localizer.GetValue("Globals", "Category")); al.AddParam("importance", "", this.localizer.GetValue("Globals", "Importance")); al.AddParam("acceptance", "", this.localizer.GetValue("Globals", "Acceptance")); al.AddParam("mappedUCs", "", this.localizer.GetValue("Globals", "MappedUCs")); al.AddParam("requirements", "", this.localizer.GetValue("Globals", "Requirements")); al.AddParam("author", "", this.localizer.GetValue("Globals", "Author")); al.AddParam("company", "", this.localizer.GetValue("Globals", "Company")); al.AddParam("creationDate", "", this.localizer.GetValue("Globals", "CreationDate")); al.AddParam("exportPrintDate", "", this.localizer.GetValue("Globals", "ExportPrintDate")); al.AddParam("now", "", Convert.ToString(DateTime.Now, DateTimeFormatInfo.InvariantInfo)); transform.Transform(doc, al, new XmlTextWriter(ms, Encoding.UTF8), resolver); ms.Position = 0; sr = new StreamReader(ms, Encoding.UTF8); foDoc = sr.ReadToEnd(); sr.Close(); ms.Close(); doc.Close(); this.XmlToPdf(foDoc, this.pdfFilesPath); }
public System.Xml.XmlReader Transform(System.Xml.XPath.XPathNavigator input, XsltArgumentList args) { }
protected override void DoUofToOoxMainTransform(string inputFile, string outputFile, string resourceDir) { XmlUrlResolver resourceResolver; XPathDocument xslDoc; XmlReaderSettings xrs = new XmlReaderSettings(); XmlReader source = null; XmlWriter writer = null; try { //xrs.ProhibitDtd = true; string xslLocation = TranslatorConstants.UOFToOOX_XSL; if (outputFile == null) { xslLocation = TranslatorConstants.UOFToOOX_COMPUTE_SIZE_XSL; } if (resourceDir == null) { resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(), this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + TranslatorConstants.UOFToOOX_WORD_LOCATION); xslDoc = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream(xslLocation)); xrs.XmlResolver = resourceResolver; source = XmlReader.Create(inputFile); } else { resourceResolver = new XmlUrlResolver(); xslDoc = new XPathDocument(resourceDir + "/" + xslLocation); source = XmlReader.Create(resourceDir + "/" + TranslatorConstants.SOURCE_XML, xrs); } XslCompiledTransform xslt = new XslCompiledTransform(); XsltSettings settings = new XsltSettings(true, false); xslt.Load(xslDoc, settings, resourceResolver); XsltArgumentList parameters = new XsltArgumentList(); parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack); if (outputFile != null) { parameters.AddParam("outputFile", "", outputFile); writer = new OoxZipWriter(inputFile); // writer = new UofZipWriter(inputFile); } else { writer = new XmlTextWriter(new StringWriter()); } xslt.Transform(source, parameters, writer); mainOutput = outputFile; } finally { if (writer != null) { writer.Close(); } if (source != null) { source.Close(); } } }
// // Construction // public Processor( XPathNavigator doc, XsltArgumentList args, XmlResolver resolver, Stylesheet stylesheet, List<TheQuery> queryStore, RootAction rootAction, IXsltDebugger debugger ) { this.stylesheet = stylesheet; this.queryStore = queryStore; this.rootAction = rootAction; this.queryList = new Query[queryStore.Count]; { for(int i = 0; i < queryStore.Count; i ++) { queryList[i] = Query.Clone(queryStore[i].CompiledQuery.QueryTree); } } this.xsm = new StateMachine(); this.document = doc; this.builder = null; this.actionStack = new HWStack(StackIncrement); this.output = this.rootAction.Output; this.permissions = this.rootAction.permissions; this.resolver = resolver ?? XmlNullResolver.Singleton; this.args = args ?? new XsltArgumentList(); this.debugger = debugger; if (this.debugger != null) { this.debuggerStack = new HWStack(StackIncrement, /*limit:*/1000); templateLookup = new TemplateLookupActionDbg(); } // Clone the compile-time KeyList if (this.rootAction.KeyList != null) { this.keyList = new Key[this.rootAction.KeyList.Count]; for (int i = 0; i < this.keyList.Length; i ++) { this.keyList[i] = this.rootAction.KeyList[i].Clone(); } } this.scriptExtensions = new Hashtable(this.stylesheet.ScriptObjectTypes.Count); { foreach(DictionaryEntry entry in this.stylesheet.ScriptObjectTypes) { string namespaceUri = (string)entry.Key; if (GetExtensionObject(namespaceUri) != null) { throw XsltException.Create(Res.Xslt_ScriptDub, namespaceUri); } scriptExtensions.Add(namespaceUri, Activator.CreateInstance((Type)entry.Value, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, null, null)); } } this.PushActionFrame(this.rootAction, /*nodeSet:*/null); }
protected void btnUpload_Click(object sender, EventArgs e) { trResults.Visible = true; string errors = ""; if (fuFile.HasFile) { HttpPostedFile PostedFile = fuFile.PostedFile; if (!PostedFile.FileName.EndsWith("xls", StringComparison.InvariantCultureIgnoreCase) && !PostedFile.FileName.EndsWith("xml", StringComparison.InvariantCultureIgnoreCase) && !PostedFile.FileName.EndsWith("csv", StringComparison.InvariantCultureIgnoreCase) && PostedFile.FileName.Trim() != "") { errors = String.Format(AppLogic.GetString("admin.importProductPricing.InvalidFileType", SkinID, LocaleSetting), CommonLogic.IIF(PostedFile.ContentLength == 0, AppLogic.GetString("admin.common.FileContentsWereEmpty", SkinID, LocaleSetting), AppLogic.GetString("admin.common.CommaDelimitedFilesPrompt", SkinID, LocaleSetting))); } else { if ((AppLogic.ProductIsMLExpress() || AppLogic.ProductIsMLX()) && PostedFile.FileName.EndsWith("xml", StringComparison.InvariantCultureIgnoreCase)) { //not supported in Incartia errors = AppLogic.GetString("admin.importProductPricing.XMLNotSupported", SkinID, LocaleSetting); } else { string filename = System.Guid.NewGuid().ToString(); string FullFilePath = CommonLogic.SafeMapPath("../images") + "\\" + filename + PostedFile.FileName.ToLowerInvariant().Substring(PostedFile.FileName.LastIndexOf('.')); string xml = String.Empty; PostedFile.SaveAs(FullFilePath); StreamReader sr = new StreamReader(FullFilePath); string filecontent = sr.ReadToEnd(); sr.Close(); if (PostedFile.FileName.EndsWith("csv", StringComparison.InvariantCultureIgnoreCase)) { xml = "<productlist>"; string[] rows = filecontent.Split(Environment.NewLine.ToCharArray()); for (int i = 1; i < rows.Length; i++) { if (rows[i].Length > 0) { xml += "<productvariant>"; string delim = ","; string[] cols = rows[i].Split(delim.ToCharArray()); xml += "<ProductID>" + cols[0] + "</ProductID>"; xml += "<VariantID>" + cols[1] + "</VariantID>"; xml += "<KitItemID>" + cols[2] + "</KitItemID>"; xml += "<Name>" + cols[3] + "</Name>"; xml += "<KitGroup>" + cols[4] + "</KitGroup>"; xml += "<SKU>" + cols[5] + "</SKU>"; xml += "<SKUSuffix>" + cols[7] + "</SKUSuffix>"; xml += "<ManufacturerPartNumber>" + cols[6] + "</ManufacturerPartNumber>"; xml += "<Cost>" + cols[8] + "</Cost>"; xml += "<MSRP>" + cols[9] + "</MSRP>"; xml += "<Price>" + cols[10] + "</Price>"; xml += "<SalePrice>" + cols[11] + "</SalePrice>"; xml += "<Inventory>" + cols[12] + "</Inventory>"; xml += "</productvariant>"; } } xml += "</productlist>"; } else if (PostedFile.FileName.EndsWith("xls", StringComparison.InvariantCultureIgnoreCase)) { xml = Import.ConvertPricingFileToXml(FullFilePath); XslCompiledTransform xForm = new XslCompiledTransform(); xForm.Load(CommonLogic.SafeMapPath("XmlPackages/ExcelPricingImport.xslt")); Localization ExtObj = new Localization(); XsltArgumentList m_TransformArgumentList = new XsltArgumentList(); m_TransformArgumentList.AddExtensionObject("urn:aspdnsf", ExtObj); XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(xml); StringWriter xsw = new StringWriter(); xForm.Transform(xdoc, m_TransformArgumentList, xsw); xml = xsw.ToString(); } else { xml = filecontent; } File.Delete(FullFilePath); errors = AppLogic.ImportProductList(xml); } } } else { errors = (AppLogic.GetString("admin.importProductPricing.NothingToImport", SkinID, LocaleSetting)); } if (errors.Length == 0) { ltResult.Text = (AppLogic.GetString("admin.importProductPricing.ImportOK", SkinID, LocaleSetting)); } else { ltResult.Text = (String.Format(AppLogic.GetString("admin.importProductPricing.ImportError", SkinID, LocaleSetting), errors)); } }
private static void Generate(XmlDocument source, XslTransform transform, XsltArgumentList args, string output, XslTransform template) { using (TextWriter textwriter = new StreamWriter(new FileStream(output, FileMode.Create))) { XmlTextWriter writer = new XmlTextWriter(textwriter); writer.Formatting = Formatting.Indented; writer.Indentation = 2; writer.IndentChar = ' '; try { XmlDocument intermediate = new XmlDocument(); intermediate.PreserveWhitespace = true; intermediate.Load(transform.Transform(source, args, new ManifestResourceResolver(opts.source))); template.Transform(intermediate, new XsltArgumentList(), new XhtmlWriter (writer), null); } catch (Exception e) { throw new ApplicationException("An error occured while generating " + output, e); } } }
public override void DataBind() { // Get the report for this module if (!this.ValidateDataSource() || !this.ValidateResults()) { this.litContent.Visible = false; } else { this.litContent.Visible = true; // Get the extension objects IEnumerable<ExtensionObjectInfo> extensionObjects = ReportsController.GetXsltExtensionObjects(this.TabModuleId); var argList = new XsltArgumentList(); foreach (var extensionObject in extensionObjects) { object obj = this.CreateExtensionObject(extensionObject.ClrType); if (obj != null) { argList.AddExtensionObject(extensionObject.XmlNamespace, obj); } } // Get the Xslt Url var sXsl = SettingsUtil.GetDictionarySetting(this.Report.VisualizerSettings, ReportsConstants.SETTING_Xslt_TransformFile, string.Empty); if (string.IsNullOrEmpty(sXsl)) { return; } if (sXsl.ToLower().StartsWith("fileid=")) { sXsl = Utilities.MapFileIdPath(this.ParentModule.PortalSettings, sXsl); } else if (!sXsl.ToLower().StartsWith("http")) { sXsl = Path.Combine(this.ParentModule.PortalSettings.HomeDirectoryMapPath, sXsl.Replace("/", "\\")); } if (string.IsNullOrEmpty(sXsl)) { return; } // Serialize the results to Xml var sbSource = new StringBuilder(); using (var srcWriter = new StringWriter(sbSource)) { this.ReportResults.WriteXml(srcWriter); } // Load the Transform and transform the Xml var sbDest = new StringBuilder(); var xform = new XslCompiledTransform(); using (var destWriter = new XmlTextWriter(new StringWriter(sbDest))) { xform.Load(sXsl); xform.Transform(new XPathDocument(new StringReader(sbSource.ToString())), argList, destWriter); } var objSec = new PortalSecurity(); this.litContent.Text = objSec.InputFilter(sbDest.ToString(), PortalSecurity.FilterFlag.NoScripting); } base.DataBind(); }
/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { // set current directory so paths are relative to this page location Environment.CurrentDirectory = this.Server.MapPath(this.TemplateSourceDirectory); // set localized Page Title this.PageTitle = General.GetString("TAB_TITLE_RAINBOW_HELP", "Rainbow Help", this); // add the Help css this.ClearCssFileList(); this.RegisterCssFile("help", "css/help.css"); this.RegisterCssFile("menu", "css/mainmenu.css"); if (!this.IsAdditionalMetaElementRegistered("ie7")) { string _ie7 = string.Empty; string _ie7Part = string.Empty; foreach (string _script in Ie7Script.Split(new char[] { ';' })) { _ie7Part = Path.WebPathCombine(Path.ApplicationRoot, _script); _ie7Part = string.Format("<!--[if lt IE 7]><script src=\"{0}\" type=\"text/javascript\"></script><![endif]-->", _ie7Part); _ie7 += _ie7Part + "\n"; } this.RegisterAdditionalMetaElement("ie7", _ie7); } string loc = string.Empty; string src = string.Empty; string xslt = string.Empty; CultureInfo lang = this.portalSettings.PortalContentLanguage; CultureInfo defaultLang = this.portalSettings.PortalContentLanguage; //jes1111 - CultureInfo fallbackLang = new CultureInfo(ConfigurationSettings.AppSettings["DefaultLanguage"]); CultureInfo fallbackLang = new CultureInfo(Config.DefaultLanguage); XslTransform xt; // grab the QueryString NameValueCollection qs = Request.QueryString; // Read Location if (qs["loc"] != null && qs["loc"].Length != 0) { loc = qs["loc"]; } else { loc = defaultLocation; } // Read Source if (qs["src"] != null && qs["src"].Length != 0) { src = qs["src"]; } else { src = defaultSource; } // Read Culture if (qs["lang"] != null && qs["lang"].Length != 0) { try{ lang = new CultureInfo(qs["lang"], false); } catch {} } // Read XSLT Stylesheet if (qs["xslt"] != null && qs["xslt"].Length != 0 && File.Exists(qs["xslt"]) ) { xslt = qs["xslt"]; } else { xslt = defaultXslt; } // create language sequence ArrayList langSequence = new ArrayList(7); langSequence.Add(lang); if (!lang.Equals(defaultLang)) { langSequence.Add(defaultLang); } if (!defaultLang.Equals(fallbackLang)) { langSequence.Add(fallbackLang); } langSequence.Add(new CultureInfo(string.Empty)); // create file sequence ArrayList fileSequence = new ArrayList(2); fileSequence.Add(Path.WebPathCombine(loc, src)); fileSequence.Add(Path.WebPathCombine(defaultLocation, defaultSource)); string filePath = string.Empty; bool found = false; bool asRequested = true; string languageReturned = string.Empty; // find a file foreach (string _file in fileSequence) { foreach (CultureInfo _language in langSequence) { filePath = string.Concat(_file, ".", _language.Name, sourceExtension); filePath = filePath.Replace("..", "."); if (File.Exists(filePath)) { languageReturned = _language.Name; found = true; break; } if (_language.TwoLetterISOLanguageName.ToLower().Equals("en")) { filePath = string.Concat(_file, sourceExtension); } else { filePath = string.Concat(_file, ".", _language.TwoLetterISOLanguageName, sourceExtension); } filePath = filePath.Replace("..", "."); if (File.Exists(filePath)) { languageReturned = _language.TwoLetterISOLanguageName; found = true; break; } } if (found) { break; } else { asRequested = false; } } // if we found something to display if (found) { // get the Transformer string transformerCacheKey = string.Concat(cacheKeyRoot, "_", xslt); if (Context.Cache[transformerCacheKey] == null) { try { xt = new XslTransform(); xslt = this.Server.MapPath(xslt); XmlUrlResolver xr = new XmlUrlResolver(); xt.Load(xslt, xr); Context.Cache.Insert(transformerCacheKey, xt, new CacheDependency(xslt)); } catch (Exception ex) { Rainbow.Framework.ErrorHandler.Publish(Rainbow.Framework.LogLevel.Error, "Failed in Help Transformer load - message was: " + ex.Message); throw new Exception("Failed in Help Transformer load - message was: " + ex.Message); } } else { xt = (XslTransform)Context.Cache[transformerCacheKey]; } // create the ArgList XsltArgumentList xa = new XsltArgumentList(); XslHelper xh = new XslHelper(); xa.AddExtensionObject("urn:rainbow", xh); xa.AddParam("LanguageRequested", string.Empty, lang.Name); xa.AddParam("LanguageReturned", string.Empty, languageReturned); xa.AddParam("AsRequested", string.Empty, asRequested.ToString()); //string rootFolder = Rainbow.Framework.Settings.Path.ApplicationRoot + "/rb_documentation/"; //xa.AddParam("Location",string.Empty,rootFolder + loc); xa.AddParam("Location", string.Empty, loc); xa.AddParam("Title", string.Empty, this.PageTitle); string tocFile = string.Concat(loc.Substring(0, loc.IndexOf("/")), "/map.", languageReturned, sourceExtension); tocFile = tocFile.Replace("..", "."); tocFile = string.Concat("../", tocFile); xa.AddParam("TOCfile", string.Empty, tocFile); xa.AddParam("Viewer", string.Empty, this.Request.Url.AbsolutePath); xa.AddParam("myRoot", string.Empty, loc.Substring(0, loc.IndexOf("/"))); // load up the Xml control myXml.DocumentSource = filePath; myXml.Transform = xt; myXml.TransformArgumentList = xa; } else { using (Localize errorMsg = new Localize()) { errorMsg.TextKey = "HELP_VIEWER_ERROR"; errorMsg.Text = "Sorry - no help available"; using (HtmlGenericControl container = new HtmlGenericControl("div")) { container.Attributes.Add("style", "padding:3em;font-size:1.2em;text-align:center"); container.Controls.Add(errorMsg); this.ContentHolder.Controls.Add(container); } } } }
public void DrawProfilesModule() { DateTime d = DateTime.Now; //If your module performs a data request, based on the DataURI parameter then call ReLoadBaseData base.GetDataByURI(); List <CloudItem> weights = new List <CloudItem>(); double firsttwenty = 0.0; double lasttwenty = 0.0; string cloudweightnode = string.Empty; string networklistnode = string.Empty; string itemurl = string.Empty; string itemurltext = string.Empty; string itemtext = string.Empty; cloudweightnode = base.GetModuleParamString("CloudWeightNode"); networklistnode = base.GetModuleParamString("NetworkListNode"); itemurl = base.GetModuleParamString("ItemURL"); itemurltext = base.GetModuleParamString("ItemURLText"); itemtext = base.GetModuleParamString("ItemText"); if (base.BaseData.SelectNodes(networklistnode, base.Namespaces) != null && cloudweightnode != string.Empty) { if (cloudweightnode != string.Empty) { var items = from XmlNode networknode in base.BaseData.SelectNodes(networklistnode, base.Namespaces) select new { weight = Convert.ToDouble(networknode.SelectSingleNode(cloudweightnode, base.Namespaces).InnerText), value = networknode.SelectSingleNode("./rdf:object/@rdf:resource", this.Namespaces).Value }; foreach (var i in items) { weights.Add(new CloudItem(i.weight, i.value)); } //foreach (XmlNode networknode in base.BaseData.SelectNodes(networklistnode, base.Namespaces)) //{ // weight = Convert.ToDouble(networknode.SelectSingleNode(cloudweightnode, base.Namespaces).InnerText); // weights.Add(new CloudItem(weight, networknode.SelectSingleNode("./rdf:object/@rdf:resource", this.Namespaces).Value)); //} } weights = weights.OrderByDescending(clouditem => clouditem.Weight).ToList(); firsttwenty = weights.Count * .2; lasttwenty = weights.Count * .8; int cnt = 0; foreach (CloudItem ci in weights) { if (cnt > firsttwenty && cnt < lasttwenty) { ci.Rank = "med"; } if (cnt < firsttwenty) { ci.Rank = "big"; } if (cnt > lasttwenty) { ci.Rank = "small"; } cnt++; } } XmlDocument document = new XmlDocument(); System.Text.StringBuilder documentdata = new System.Text.StringBuilder(); documentdata.Append("<ListView"); documentdata.Append(" Columns=\""); documentdata.Append(base.GetModuleParamString("Columns")); documentdata.Append("\""); if (base.GetModuleParamString("BulletType") != string.Empty) { documentdata.Append(" Bullet=\""); documentdata.Append(base.GetModuleParamString("BulletType")); documentdata.Append("\""); } documentdata.Append(" InfoCaption=\""); documentdata.Append(base.GetModuleParamString("InfoCaption")); documentdata.Append("\""); documentdata.Append(" Description=\""); documentdata.Append(base.GetModuleParamString("Description")); documentdata.Append("\">"); string item = string.Empty; if (base.BaseData.SelectNodes(networklistnode, base.Namespaces) != null) { var items = from XmlNode networknode in base.BaseData.SelectNodes(networklistnode, base.Namespaces) select new { itemurl = CustomParse.Parse(itemurl, networknode, base.Namespaces), item = CustomParse.Parse(itemtext, networknode, base.Namespaces), weight = GetCloudRank(networknode.SelectSingleNode("./rdf:object/@rdf:resource", base.Namespaces).InnerText, weights), connectiondetails = networknode.SelectSingleNode("prns:hasConnectionDetails/@rdf:resource", base.Namespaces), sortorder = networknode.SelectSingleNode("prns:sortOrder", base.Namespaces), itemxpath = CustomParse.Parse(itemurltext, networknode, base.Namespaces) }; List <string> orngCallbackItems = new List <string>(); foreach (var i in items) { //foreach (XmlNode networknode in base.BaseData.SelectNodes(networklistnode, base.Namespaces)) //{ documentdata.Append("<Item"); if (itemurl != string.Empty) { orngCallbackItems.Add(i.itemurl); documentdata.Append(" ItemURL=\""); documentdata.Append(i.itemurl); documentdata.Append("\""); if (cloudweightnode != string.Empty) { documentdata.Append(" Weight=\""); documentdata.Append(i.weight); documentdata.Append("\""); } if (i.connectiondetails != null) { if (base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[@rdf:about='" + i.connectiondetails.InnerText + "']/prns:isAlsoCoAuthor", base.Namespaces) != null) { documentdata.Append(" CoAuthor=\""); documentdata.Append(base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[@rdf:about='" + i.connectiondetails.InnerText + "']/prns:isAlsoCoAuthor", base.Namespaces).InnerText); documentdata.Append("\""); } if (i.sortorder != null) { documentdata.Append(" sortOrder=\""); documentdata.Append(i.sortorder.InnerText); documentdata.Append("\""); } } string itemxpath = i.itemxpath; if (itemxpath != string.Empty) { item = base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[@rdf:about= '" + itemxpath + "']/rdfs:label", base.Namespaces).InnerText; } documentdata.Append(" ItemURLText=\""); documentdata.Append(item.Replace("\"", "'")); documentdata.Append("\""); } documentdata.Append(">"); documentdata.Append(i.item); documentdata.Append("</Item>"); } new ORNGNetworkListRPCService(Page, orngCallbackItems); } documentdata.Append("</ListView>"); document.LoadXml(documentdata.ToString().Replace("&", "&")); XsltArgumentList args = new XsltArgumentList(); string xmlbuffer; if (base.GetModuleParamString("SortBy").Equals("Weight")) { xmlbuffer = XslHelper.TransformInMemory(Server.MapPath("~/Profile/Modules/NetworkList/SortIntermediateByWeight.xslt"), args, document.OuterXml); } else { xmlbuffer = XslHelper.TransformInMemory(Server.MapPath("~/Profile/Modules/NetworkList/SortIntermediate.xslt"), args, document.OuterXml); } litListView.Text = XslHelper.TransformInMemory(Server.MapPath("~/Profile/Modules/NetworkList/NetworkList.xslt"), args, xmlbuffer); Framework.Utilities.DebugLogging.Log("Network List MODULE end Milliseconds:" + (DateTime.Now - d).TotalSeconds); }
public void Transform(System.Xml.XmlReader input, XsltArgumentList arguments, System.IO.TextWriter results) { }
/// <summary> /// Builds the documentation. /// </summary> public override void Build(NDoc.Core.Project project) { int buildStepProgress = 0; OnDocBuildingStep(buildStepProgress, "Initializing..."); _resourceDirectory = Path.Combine(Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), "NDoc"), "NAnt"); // get assembly in which documenter is defined Assembly assembly = this.GetType().Module.Assembly; // write xslt files to resource directory EmbeddedResources.WriteEmbeddedResources(assembly, "Documenter.xslt", Path.Combine(_resourceDirectory, "xslt")); // create the html output directories try { Directory.CreateDirectory(OutputDirectory); Directory.CreateDirectory(Path.Combine(OutputDirectory, "elements")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "functions")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "types")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "tasks")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "enums")); Directory.CreateDirectory(Path.Combine(OutputDirectory, "filters")); } catch (Exception ex) { throw new DocumenterException("The output directories could not" + " be created.", ex); } buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Merging XML documentation..."); // load the stylesheets that will convert the master xml into html pages MakeTransforms(); // will hold the file name containing the NDoc generated XML string tempFile = null; try { // determine temporary file name tempFile = Path.GetTempFileName(); // create the master XML document MakeXmlFile(project, tempFile); // create a xml document that will be transformed using xslt using (FileStream fs = new FileStream(tempFile, FileMode.Open, FileAccess.Read, FileShare.Read)) { _xmlDocumentation = new XmlDocument(); _xmlDocumentation.Load(fs); } } finally { // ensure temporary file is removed if (tempFile != null) { File.Delete(tempFile); } } // build the file mapping buildStepProgress += 15; OnDocBuildingStep(buildStepProgress, "Building mapping..."); // create arguments for nant index page transform XsltArgumentList indexArguments = CreateXsltArgumentList(); // add extension object for NAnt utilities NAntXsltUtilities indexUtilities = NAntXsltUtilities.CreateInstance( _xmlDocumentation, (NAntDocumenterConfig)Config); // add extension object to Xslt arguments indexArguments.AddExtensionObject("urn:NAntUtil", indexUtilities); buildStepProgress += 15; OnDocBuildingStep(buildStepProgress, "Creating Task Index Page..."); // transform nant task index page transform TransformAndWriteResult(_xsltTaskIndex, indexArguments, "tasks/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Creating Type Index Page..."); // transform nant type index page transform TransformAndWriteResult(_xsltTypeIndex, indexArguments, "types/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Creating Filter Index Page..."); // transform nant type index page transform TransformAndWriteResult(_xsltFilterIndex, indexArguments, "filters/index.html"); OnDocBuildingStep(buildStepProgress, "Creating Function Index Page..."); // transform nant function index page transform TransformAndWriteResult(_xsltFunctionIndex, indexArguments, "functions/index.html"); buildStepProgress += 10; OnDocBuildingStep(buildStepProgress, "Generating Task Documents..."); // generate a page for each marked task XmlNodeList typeNodes = _xmlDocumentation.SelectNodes("//class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]"); foreach (XmlNode typeNode in typeNodes) { ElementDocType elementDocType = indexUtilities.GetElementDocType(typeNode); DocumentType(typeNode, elementDocType, indexUtilities); } OnDocBuildingStep(buildStepProgress, "Generating Function Documents..."); // generate a page for each function - TODO - change the XPath expression to select more functions XmlNodeList functionNodes = _xmlDocumentation.SelectNodes("//method[attribute/@name = 'NAnt.Core.Attributes.FunctionAttribute' and ancestor::class[starts-with(substring(@id, 3, string-length(@id) - 2), '" + NamespaceFilter + "')]]"); foreach (XmlElement function in functionNodes) { DocumentFunction(function, indexUtilities); } OnDocBuildingStep(100, "Complete"); }
public void Transform(System.Xml.XmlReader input, XsltArgumentList arguments, System.Xml.XmlWriter results, System.Xml.XmlResolver documentResolver) { }
internal static void TransformXml(AbsolutePath sourceXmlPath, AbsolutePath xsltPath, AbsolutePath outputFilePath, XsltArgumentList arguments = null) { Normal($"Transforming with '{xsltPath}'."); var transformation = new XslCompiledTransform(); transformation.Load(xsltPath); using (var streamWriter = new StreamWriter(outputFilePath)) { transformation.Transform(sourceXmlPath, arguments, streamWriter); } Normal($"Transformation completed. Output file: '{outputFilePath}'."); }
public void Transform(string inputUri, XsltArgumentList arguments, System.IO.Stream results) { }
static void Main() { // // assumes directory structure: // // ofx/ <--- OFX's read from // - ofxfile1.ofx // - ofxfile2.ofx // - ... // - ofxfileN.ofx // csv/ <--- CSV outputs to // - csvfile1.csv // - csvfile2.csv // - ... // - csvfileN.csv // var assemblyFileName = new FileInfo(Assembly.GetEntryAssembly().Location); var ofxPath = Path.Combine(assemblyFileName.Directory.FullName, "ofx"); var csvPath = Path.Combine(assemblyFileName.Directory.FullName, "csv"); var transform = new XslCompiledTransform(); // load XSLT from assembly manifest resource using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(OFXLoader.Program), "Extractor.xslt")) { transform.Load(XmlReader.Create(stream)); } // create CSV output file using (var ext = new Ext(Path.Combine(csvPath, String.Format("output_{0:yyyyMMdd}.csv", DateTime.Today)))) { var args = new XsltArgumentList(); args.AddExtensionObject("uri:extension", ext); var srcDir = new DirectoryInfo(ofxPath); using (var results = new XmlTextWriter(new MemoryStream(), Encoding.UTF8)) { // read in OFX files foreach (var file in srcDir.GetFiles("*.ofx")) { Console.WriteLine(file.Name); var sb = new StringBuilder(); // load the file; may start with OFX header, so read to the start of the XML using (var stream = File.OpenText(file.FullName)) { // some OFX file has non-XML content at the top of the file // ignore lines until line starting with "<OFX>" // then load the content as XML var inContent = false; var line = stream.ReadLine(); while (line != null) { if (inContent) { sb.Append(line); } else if (line.StartsWith("<OFX>")) { inContent = true; sb.Append(line); } line = stream.ReadLine(); } } var dataFile = new XPathDocument(new StringReader(sb.ToString())); transform.Transform(dataFile.CreateNavigator(), args, results); } } } }
private XElement UpdateTreeView(XElement functionMarkupContainer) { // TODO: Do some compiled xslt caching XElement treeInput = CopyWithId(functionMarkupContainer); treeInput.Add(GetFunctionDescriptionElements(functionMarkupContainer)); if (_state.AllowSelectingInputParameters) { CollapseGetInputParamaterFunctionCalls(treeInput, InputParameterNodeIDs); } // treeInput.Save(Request.MapPath("out.tmp.xml")); string xslFilePath = Request.MapPath("functioneditortree.xslt"); XslCompiledTransform transform = GetTransformation(xslFilePath); var xsltTransformArguments = new XsltArgumentList(); xsltTransformArguments.AddExtensionObject(XsltExtensionObjectNamespace, new TreeRenderingXsltExtensionObject(TreePathToIdMapping)); xsltTransformArguments.AddParam("SelectedId", string.Empty, SelectedNode.IsNullOrEmpty() ? string.Empty : TreePathToIdMapping[SelectedNode]); XDocument transformedDoc = new XDocument(); using (XmlWriter writer = transformedDoc.CreateWriter()) { transform.Transform(treeInput.CreateReader(), xsltTransformArguments, writer); } WriteTo(transformedDoc, this.TreePlaceholder); return treeInput; }
/// <summary> /// Render the specified report definition with the specified view /// </summary> public virtual Stream Render(BiReportDefinition reportDefinition, string viewName, IDictionary <string, object> parameters) { foreach (var pol in reportDefinition.MetaData.Demands ?? new List <string>()) { ApplicationServiceContext.Current.GetService <IPolicyEnforcementService>().Demand(pol); } // Get the view var view = string.IsNullOrEmpty(viewName) ? reportDefinition.Views.First() : reportDefinition.Views.FirstOrDefault(o => o.Name == viewName); if (view == null) { throw new KeyNotFoundException($"Report view {viewName} does not exist in {reportDefinition.Id}"); } // Demand permission to render // Start a new root context var context = new RootRenderContext(reportDefinition, viewName, parameters, this.m_configuration?.MaxBiResultSetSize); try { using (var tempMs = new MemoryStream()) { using (var xw = XmlWriter.Create(tempMs, new XmlWriterSettings() { CloseOutput = false, #if DEBUG Indent = true, NewLineOnAttributes = true #else Indent = false, OmitXmlDeclaration = true #endif })) ReportViewUtil.Write(xw, view.Body, context); tempMs.Seek(0, SeekOrigin.Begin); var retVal = new MemoryStream(); XsltArgumentList args = new XsltArgumentList(); args.AddParam("current-date", String.Empty, DateTime.Now.ToString("o")); using (var xr = XmlReader.Create(tempMs)) { if (this.m_isText) { using (var xw = new StreamWriter(retVal, Encoding.UTF8, 1024, true)) this.m_xsl.Transform(xr, null, xw); } else { using (var xw = XmlWriter.Create(retVal, new XmlWriterSettings() { Indent = true, OmitXmlDeclaration = false })) this.m_xsl.Transform(xr, xw); } } retVal.Seek(0, SeekOrigin.Begin); return(retVal); }
protected void Page_Load(object sender, EventArgs e) { int DBNId; string ResponseFormat, SDMXFormat, Indicator, Area, TimePeriod, Source, Language, DataResponse,Title, Footnote; XmlDocument QueryDocument, ResponseDocument; bool IsGroupBy=false; DBNId = 0; ResponseFormat = string.Empty; SDMXFormat = string.Empty; Indicator = string.Empty; Area = string.Empty; TimePeriod = string.Empty; Source = string.Empty; Language = string.Empty; DataResponse = string.Empty; Title = string.Empty; Footnote = string.Empty; QueryDocument = new XmlDocument(); ResponseDocument = new XmlDocument(); foreach (string QSComponent in Request.QueryString.Keys) { switch (QSComponent) { case Constants.WSQueryStrings.p: if (this.Context.Request.QueryString[Constants.WSQueryStrings.p] != null && !string.IsNullOrEmpty(this.Context.Request.QueryString[Constants.WSQueryStrings.p]) && int.TryParse(this.Context.Request.QueryString[Constants.WSQueryStrings.p], out DBNId)) { this.DIConnection = Global.GetDbConnection(DBNId); this.DIQueries = new DIQueries(this.DIConnection.DIDataSetDefault(), this.DIConnection.DILanguageCodeDefault(this.DIConnection.DIDataSetDefault())); } else { Global.GetAppSetting(); DBNId = Convert.ToInt32(Global.GetDefaultDbNId()); this.DIConnection = Global.GetDbConnection(Convert.ToInt32(Global.GetDefaultDbNId())); this.DIQueries = new DIQueries(this.DIConnection.DIDataSetDefault(), this.DIConnection.DILanguageCodeDefault(this.DIConnection.DIDataSetDefault())); } break; case Constants.WSQueryStrings.ResponseFormat: if (Request.QueryString[Constants.WSQueryStrings.ResponseFormat] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.ResponseFormat].ToString())) { ResponseFormat = Request.QueryString[Constants.WSQueryStrings.ResponseFormat].ToString(); } else { ResponseFormat = Constants.WSQueryStrings.ResponseFormatTypes.SDMX; } break; case Constants.WSQueryStrings.SDMXFormat: if (Request.QueryString[Constants.WSQueryStrings.SDMXFormat] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.SDMXFormat].ToString())) { SDMXFormat = Request.QueryString[Constants.WSQueryStrings.SDMXFormat].ToString(); } else { SDMXFormat = Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecificTS; } break; case DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id: if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id].ToString())) { Indicator = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id].ToString(); } break; case DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id: if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id].ToString())) { Area = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id].ToString(); } break; case DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id: if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id].ToString())) { TimePeriod = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id].ToString(); } break; case DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id: if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id].ToString())) { Source = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id].ToString(); } break; case Constants.WSQueryStrings.Language: if (Request.QueryString[Constants.WSQueryStrings.Language] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.Language].ToString())) { Language = Request.QueryString[Constants.WSQueryStrings.Language].ToString(); } break; case Constants.WSQueryStrings.GroupByIndicator: if(!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.GroupByIndicator])) { IsGroupBy = Convert.ToBoolean(Request.QueryString[Constants.WSQueryStrings.GroupByIndicator]); } break; case Constants.WSQueryStrings.Title: if (!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.Title])) { Title = Convert.ToString(Request.QueryString[Constants.WSQueryStrings.Title]); } break; case Constants.WSQueryStrings.FootNote: if (!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.FootNote])) { Footnote = Convert.ToString(Request.QueryString[Constants.WSQueryStrings.FootNote]); } break; default: break; } } if (!string.IsNullOrEmpty(ResponseFormat)) { switch (ResponseFormat) { case Constants.WSQueryStrings.ResponseFormatTypes.SDMX: QueryDocument = GetQueryXML(ResponseFormat, SDMXFormat, Indicator, Area, TimePeriod, Source, Language); if (!string.IsNullOrEmpty(SDMXFormat)) { switch (SDMXFormat) { case Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecificTS: ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries); break; case Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecific: ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecific, DIConnection, DIQueries); break; case Constants.WSQueryStrings.SDMXFormatTypes.GenericTS: ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.GenericTS, DIConnection, DIQueries); break; case Constants.WSQueryStrings.SDMXFormatTypes.Generic: ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.Generic, DIConnection, DIQueries); break; default: break; } } else { ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries); } Response.Write(ResponseDocument.OuterXml); break; case Constants.WSQueryStrings.ResponseFormatTypes.JSON: QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language); Response.Write(DATAUtility.Get_Data(QueryDocument, DataTypes.JSON, DIConnection, DIQueries)); break; case Constants.WSQueryStrings.ResponseFormatTypes.XML: QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language); Response.Write(DATAUtility.Get_Data(QueryDocument, DataTypes.XML, DIConnection, DIQueries)); break; case Constants.WSQueryStrings.ResponseFormatTypes.TABLE: string BaseUrl = HttpContext.Current.Request.Url.OriginalString.Split(new string[] { "?" }, StringSplitOptions.None)[0]; int index = BaseUrl.IndexOf("libraries"); string XsltUrl = string.Empty; if (IsGroupBy) { XsltUrl = BaseUrl.Substring(0, index) + "stock/xslt/HTTPRequest_XMLResponse - INDGrp.xslt"; //XsltUrl = "../../stock/xslt/HTTPRequest_XMLResponse - INDGrp.xslt"; } else { XsltUrl = BaseUrl.Substring(0, index) + "stock/xslt/HTTPRequest_XMLResponse.xslt"; //XsltUrl = "../../stock/xslt/HTTPRequest_XMLResponse.xslt"; } BaseUrl = BaseUrl.Substring(0,index-1); //string PItext = "type='application/xml' href='" + XsltUrl + "'"; QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language); string XmlStr = DATAUtility.Get_Data(QueryDocument, DataTypes.XML, DIConnection, DIQueries); // DataTable DT = new DataTable(); // DT.ReadXml(new StringReader(XmlStr)); XsltArgumentList ArguList = new XsltArgumentList(); ArguList.AddParam("Title_Text","",Title); ArguList.AddParam("Footnote_Text", "", Footnote); ArguList.AddParam("BaseUrl", "", BaseUrl); XmlStr = this.Transform(XmlStr, XsltUrl, ArguList); XmlStr = XmlStr.Substring(XmlStr.IndexOf("<html>")); //XmlDocument FormattedXml = new XmlDocument(); //FormattedXml.LoadXml(XmlStr); //XmlProcessingInstruction XSLTTag = FormattedXml.CreateProcessingInstruction("xml-stylesheet", PItext); //FormattedXml.InsertBefore(XSLTTag, FormattedXml.SelectSingleNode("Root")); Response.ClearHeaders(); //Response.AddHeader("content-type", "application/xml"); //Response.Write(FormattedXml.InnerXml); Response.Write(XmlStr); break; default: break; } } else { QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language); ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries); } }
//----------------------------------------------- // Constructors //----------------------------------------------- /// <summary> /// This constructor is internal so that external users cannot construct it (and therefore we do not have to test it separately). /// </summary> internal XmlQueryRuntime(XmlQueryStaticData data, object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt) { Debug.Assert(data != null); string[] names = data.Names; Int32Pair[] filters = data.Filters; WhitespaceRuleLookup wsRules; int i; // Early-Bound Library Objects wsRules = (data.WhitespaceRules != null && data.WhitespaceRules.Count != 0) ? new WhitespaceRuleLookup(data.WhitespaceRules) : null; _ctxt = new XmlQueryContext(this, defaultDataSource, dataSources, argList, wsRules); _xsltLib = null; _earlyInfo = data.EarlyBound; _earlyObjects = (_earlyInfo != null) ? new object[_earlyInfo.Length] : null; // Global variables and parameters _globalNames = data.GlobalNames; _globalValues = (_globalNames != null) ? new object[_globalNames.Length] : null; // Names _nameTableQuery = _ctxt.QueryNameTable; _atomizedNames = null; if (names != null) { // Atomize all names in "nameTableQuery". Use names from the default data source's // name table when possible. XmlNameTable nameTableDefault = _ctxt.DefaultNameTable; _atomizedNames = new string[names.Length]; if (nameTableDefault != _nameTableQuery && nameTableDefault != null) { // Ensure that atomized names from the default data source are added to the // name table used in this query for (i = 0; i < names.Length; i++) { string name = nameTableDefault.Get(names[i]); _atomizedNames[i] = _nameTableQuery.Add(name ?? names[i]); } } else { // Enter names into nametable used in this query for (i = 0; i < names.Length; i++) _atomizedNames[i] = _nameTableQuery.Add(names[i]); } } // Name filters _filters = null; if (filters != null) { // Construct name filters. Each pair of integers in the filters[] array specifies the // (localName, namespaceUri) of the NameFilter to be created. _filters = new XmlNavigatorFilter[filters.Length]; for (i = 0; i < filters.Length; i++) _filters[i] = XmlNavNameFilter.Create(_atomizedNames[filters[i].Left], _atomizedNames[filters[i].Right]); } // Prefix maping lists _prefixMappingsList = data.PrefixMappingsList; // Xml types _types = data.Types; // Xml collations _collations = data.Collations; // Document ordering _docOrderCmp = new DocumentOrderComparer(); // Indexes _indexes = null; // Output construction _stkOutput = new Stack<XmlQueryOutput>(16); _output = new XmlQueryOutput(this, seqWrt); }
private void DocumentType(XmlNode typeNode, ElementDocType docType, NAntXsltUtilities utilities) { if (typeNode == null) { throw new ArgumentNullException("typeNode"); } if (docType == ElementDocType.None || docType == ElementDocType.FunctionSet) { // we don't need to document this type return; } string classID = typeNode.Attributes["id"].Value; if (!classID.Substring(2).StartsWith(NamespaceFilter)) { // we don't need to types in this namespace return; } string filename = utilities.GetFileNameForType(typeNode, false); if (filename == null) { // we should never get here, but just in case ... return; } if (_writtenFiles.ContainsValue(classID)) { return; } else { _writtenFiles.Add(filename, classID); } // create arguments for nant task page transform (valid args are class-id, refType, imagePath, relPathAdjust) XsltArgumentList arguments = CreateXsltArgumentList(); arguments.AddParam("class-id", String.Empty, classID); string refTypeString; switch (docType) { case ElementDocType.DataTypeElement: refTypeString = "Type"; break; case ElementDocType.Element: refTypeString = "Element"; break; case ElementDocType.Task: refTypeString = "Task"; break; case ElementDocType.Enum: refTypeString = "Enum"; break; case ElementDocType.Filter: refTypeString = "Filter"; break; default: refTypeString = "Other?"; break; } arguments.AddParam("refType", string.Empty, refTypeString); // add extension object to Xslt arguments arguments.AddExtensionObject("urn:NAntUtil", utilities); // Process all sub-elements and generate docs for them. :) // Just look for properties with attributes to narrow down the foreach loop. // (This is a restriction of NAnt.Core.Attributes.BuildElementAttribute) foreach (XmlNode propertyNode in typeNode.SelectNodes("property[attribute]")) { //get the xml element string elementName = utilities.GetElementNameForProperty(propertyNode); if (elementName != null) { // try to get attribute info if it is an array/collection. // strip the array brakets "[]" to get the type string elementType = "T:" + propertyNode.Attributes["type"].Value.Replace("[]", ""); // check whether property is an element array XmlNode nestedElementNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementArrayAttribute).FullName + "']"); if (nestedElementNode == null) { // check whether property is an element collection nestedElementNode = propertyNode.SelectSingleNode("attribute[@name='" + typeof(BuildElementCollectionAttribute).FullName + "']"); } // if property is either array or collection type element if (nestedElementNode != null) { // select the item type in the collection XmlAttribute elementTypeAttribute = _xmlDocumentation.SelectSingleNode("//class[@id='" + elementType + "']/method[@name='Add']/parameter/@type") as XmlAttribute; if (elementTypeAttribute != null) { // get type of collection elements elementType = "T:" + elementTypeAttribute.Value; } // if it contains a ElementType attribute then it is an array or collection // if it is a collection, then we care about the child type. XmlNode explicitElementType = propertyNode.SelectSingleNode("attribute/property[@ElementType]"); if (explicitElementType != null) { // ndoc is inconsistent about how classes are named. elementType = explicitElementType.Attributes["value"].Value.Replace("+", "."); } } XmlNode elementTypeNode = utilities.GetTypeNodeByID(elementType); if (elementTypeNode != null) { ElementDocType elementDocType = utilities.GetElementDocType(elementTypeNode); if (elementDocType != ElementDocType.None) { DocumentType(elementTypeNode, elementDocType, utilities); } } } } // create the page TransformAndWriteResult(_xsltTypeDoc, arguments, filename); }
void ProcessDirectories(List <string> sourceDirectories) { if (sourceDirectories.Count == 0 || opts.dest == null || opts.dest == "") { throw new ApplicationException("The source and dest options must be specified."); } Directory.CreateDirectory(opts.dest); // Load the stylesheets, overview.xml, and resolver XslTransform overviewxsl = LoadTransform("overview.xsl", sourceDirectories); XslTransform stylesheet = LoadTransform("stylesheet.xsl", sourceDirectories); XslTransform template; if (opts.template == null) { template = LoadTransform("defaulttemplate.xsl", sourceDirectories); } else { try { XmlDocument templatexsl = new XmlDocument(); templatexsl.Load(opts.template); template = new XslTransform(); template.Load(templatexsl); } catch (Exception e) { throw new ApplicationException("There was an error loading " + opts.template, e); } } XmlDocument overview = GetOverview(sourceDirectories); ArrayList extensions = GetExtensionMethods(overview); // Create the master page XsltArgumentList overviewargs = new XsltArgumentList(); var regenIndex = ShouldRegenIndexes(opts, overview, sourceDirectories); if (regenIndex) { overviewargs.AddParam("ext", "", opts.ext); overviewargs.AddParam("basepath", "", "./"); Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template, sourceDirectories); overviewargs.RemoveParam("basepath", ""); } overviewargs.AddParam("basepath", "", "../"); overviewargs.AddParam("Index", "", overview.CreateNavigator()); // Create the namespace & type pages XsltArgumentList typeargs = new XsltArgumentList(); typeargs.AddParam("ext", "", opts.ext); typeargs.AddParam("basepath", "", "../"); typeargs.AddParam("Index", "", overview.CreateNavigator()); foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace")) { string nsname = ns.GetAttribute("Name"); if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + ".")) { continue; } System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname); if (!d.Exists) { d.Create(); } // Create the NS page string nsDest = opts.dest + "/" + nsname + "/index." + opts.ext; if (regenIndex) { overviewargs.AddParam("namespace", "", nsname); Generate(overview, overviewxsl, overviewargs, nsDest, template, sourceDirectories); overviewargs.RemoveParam("namespace", ""); } foreach (XmlElement ty in ns.SelectNodes("Type")) { string typename, typefile, destfile; GetTypePaths(opts, ty, out typename, out typefile, out destfile); if (DestinationIsNewer(typefile, destfile)) { // target already exists, and is newer. why regenerate? continue; } XmlDocument typexml = new XmlDocument(); typexml.Load(typefile); PreserveMembersInVersions(typexml); if (extensions != null) { DocLoader loader = CreateDocLoader(overview); XmlDocUtils.AddExtensionMethods(typexml, extensions, loader); } Console.WriteLine(nsname + "." + typename); Generate(typexml, stylesheet, typeargs, destfile, template, sourceDirectories); } } }