public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer) { _threadEntity = CurrentThreadEntity; _threadEntity.ControlIndex += 1; _index = Xy.Tools.Control.Tag.TransferValue("PageIndex", _index, CurrentPageClass); _size = Xy.Tools.Control.Tag.TransferValue("PageSize", _size, CurrentPageClass); _max = Xy.Tools.Control.Tag.TransferValue("PageMax", _max, CurrentPageClass); _count = Xy.Tools.Control.Tag.TransferValue("PageCount", _count, CurrentPageClass); if (_innerData == null || (!string.IsNullOrEmpty(_xsltstring) && _threadEntity.WebSetting.DebugMode)) { if (!string.IsNullOrEmpty(_xsltstring)) { using (System.IO.FileStream fs = new System.IO.FileStream(_threadEntity.WebSetting.XsltDir + _xsltstring, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) { _innerData.Write(sr.ReadToEnd()); sr.Close(); } fs.Close(); } } } HandleData(); System.Xml.XPath.XPathDocument xpathDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_datastring)); System.Xml.Xsl.XslCompiledTransform xsl = HandleXSLT(); ContentContainer.Write(Xy.Tools.IO.XML.TransfromXmlStringToHtml(xsl, xpathDoc)); _threadEntity.ControlIndex -= 1; }
// Function takes in a name of a FlowDocument XAML file and converts it into a FlowDocument object private FlowDocument ConvertXmlToFlowDocument(String FileName) { //Create an object representing the xml file System.Xml.XPath.XPathDocument originalXML = new System.Xml.XPath.XPathDocument(FileName); // Create an object representing the XSLT System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform(); xslt.Load("GenericToXaml.xslt"); // Create a memory stream to store the results of the XSLT MemoryStream memStream = new MemoryStream(); // Apply the XSLT transform xslt.Transform(originalXML, null, memStream); //Use this line for debugging your XSLT: //xslt.Transform(originalXML, new XmlTextWriter(Console.Out)); // Parse the new XAML in the memory stream and convert it into a FlowDocument object FlowDocument flowDocument = new FlowDocument(); memStream.Seek(0, SeekOrigin.Begin); flowDocument = (FlowDocument)System.Windows.Markup.XamlReader.Load(memStream); memStream.Close(); return flowDocument; }
protected void Calculate(object sender, EventArgs e) { try { var value = new System.Xml.XPath.XPathDocument (new System.IO.StringReader("<r/>")).CreateNavigator().Evaluate (string.Format("number({0})", new System.Text.RegularExpressions.Regex(@"([\+\-\*])") .Replace(txtResultado.Text, " ${1} ") .Replace("/", " div ") .Replace("%", " mod ") .Replace("x", " * "))).ToString(); if (value == "∞") { System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Não é possível dividir por zero.')", true); } else { txtResultado.Text = value; } } catch (System.Xml.XPath.XPathException) { System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Expressão inválida.')", true); } }
Digest.Model.WebReferenceUrl[] getWebReferenceUrls(DirectoryInfo folder, string currentPath) { string relPath = Path.Combine(currentPath, folder.Name); string url = string.Empty; List <Digest.Model.WebReferenceUrl> webReferenceUrls = new List <Digest.Model.WebReferenceUrl>(); FileInfo[] fileInfo = folder.GetFiles("*.discomap"); if (fileInfo != null && fileInfo.Length > 0) { System.Xml.XPath.XPathDocument xDoc = new System.Xml.XPath.XPathDocument(fileInfo[0].FullName); System.Xml.XPath.XPathNavigator xNav = xDoc.CreateNavigator(); string xpathExpression = @"DiscoveryClientResultsFile/Results/DiscoveryClientResult[@referenceType='System.Web.Services.Discovery.ContractReference']/@url"; System.Xml.XPath.XPathNodeIterator xIter = xNav.Select(xpathExpression); if (xIter.MoveNext()) { url = xIter.Current.TypedValue.ToString(); } } if (!string.IsNullOrEmpty(url)) { Digest.Model.WebReferenceUrl newWebReferenceUrl = new Digest.Model.WebReferenceUrl(); newWebReferenceUrl.RelPath = relPath; newWebReferenceUrl.UpdateFromURL = url; webReferenceUrls.Add(newWebReferenceUrl); } foreach (DirectoryInfo dirInfo in folder.GetDirectories()) { webReferenceUrls.AddRange(getWebReferenceUrls(dirInfo, relPath)); } return(webReferenceUrls.ToArray()); }
private bool ParseResponse() { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.StreamWriter writer = new System.IO.StreamWriter(stream); writer.Write(sResponse); writer.Flush(); stream.Position = 0; System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(stream); System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator(); String sValue = nav.SelectSingleNode("/node/isMaster/text()").Value; nav = null; doc = null; stream.Close(); stream = null; return(Boolean.Parse(sValue)); } catch (Exception ex) { Trace.TraceWarning("Exception: " + ex.Message + Environment.NewLine + "StackTrace: " + ex.StackTrace); return(false); } }
private void WriteXSLT(System.Xml.XPath.XPathDocument z, string stylesheet, string suffix) { System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform(true); transform.Load(System.IO.Path.Combine(mAssemblyLocation, stylesheet), null, mResolver); System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(FullPath(suffix), transform.OutputSettings); transform.Transform(z, writer); }
public static string TranslateCDAToMobileHTML(string sCDAData) { try { System.Xml.Xsl.XslCompiledTransform xslttransform = new System.Xml.Xsl.XslCompiledTransform(); System.IO.StreamReader oxsltstream = new System.IO.StreamReader(System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("MobileCDA.xslt")); System.Xml.XmlTextReader xtextreader = new System.Xml.XmlTextReader(oxsltstream); xslttransform.Load(xtextreader); System.Xml.XPath.XPathDocument xDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(sCDAData)); System.Xml.XmlWriterSettings xWriterSettings = new System.Xml.XmlWriterSettings(); xWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; StringBuilder sb = new StringBuilder(); xslttransform.Transform(xDoc, System.Xml.XmlWriter.Create(sb, xWriterSettings)); return(sb.ToString()); } catch (Exception ex) { throw new Exception("Exception in Sirona.Utilities.Translator.TranslateCDAToMobileHTML:\n" + ex.Message); } }
public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer) { _threadEntity = CurrentThreadEntity; _threadEntity.ControlIndex += 1; _dataBuilder.Init(_tagList); _datastring = _dataBuilder.HandleData(CurrentPageClass); HTMLContainer _temp = new HTMLContainer(ContentContainer.Encoding); if (!_xsltLoaded || _threadEntity.WebSetting.DebugMode) { _xsltCache = HandleXSLT(); } _xsltString = _xsltCache; _xsltString = _dataBuilder.InsertParameter(_xsltString); if (!string.IsNullOrEmpty(_xsltParameter)) { _xsltString = InsertParameter(_xsltString, CurrentPageClass); } _temp.Write(HandleHTML(_datastring, _xsltString)); if (_enableScript && _temp.Length > 0) { Control.ControlAnalyze _controls = new ControlAnalyze(CurrentThreadEntity, this.Map, true); _controls.SetContent(_temp.ToArray()); _controls.Analyze(); _temp.Clear(); _controls.Handle(CurrentPageClass, _temp); } ContentContainer.Write(_temp); _threadEntity.ControlIndex -= 1; }
public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer) { _threadEntity = CurrentThreadEntity; _threadEntity.ControlIndex += 1; _dataBuilder.Init(_tagList); _datastring = _dataBuilder.HandleData(CurrentPageClass); if (!_xsltLoaded || _threadEntity.WebSetting.DebugMode) { _xsltstring = HandleXSLT(); } HTMLContainer _temp = new HTMLContainer(ContentContainer.Encoding); _xsltstring = _dataBuilder.InsertParameter(_xsltstring); if (!string.IsNullOrEmpty(_xsltParameter)) { _xsltstring = InsertParameter(_xsltstring, CurrentPageClass); } _temp.Write(HandleHTML(_datastring, _xsltstring)); if (_enableScript && _temp.Length > 0) { Control.ControlAnalyze _controls = new ControlAnalyze(CurrentThreadEntity, this.Map, true); _controls.SetContent(_temp.ToArray()); _controls.Analyze(); _temp.Clear(); _controls.Handle(CurrentPageClass, _temp); } ContentContainer.Write(_temp); _threadEntity.ControlIndex -= 1; }
public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer) { _threadEntity = CurrentThreadEntity; _threadEntity.ControlIndex += 1; _index = Xy.Tools.Control.Tag.TransferValue("PageIndex", _index, CurrentPageClass); _size = Xy.Tools.Control.Tag.TransferValue("PageSize", _size, CurrentPageClass); _max = Xy.Tools.Control.Tag.TransferValue("PageMax", _max, CurrentPageClass); _count = Xy.Tools.Control.Tag.TransferValue("PageCount", _count, CurrentPageClass); if (_innerData == null || (!string.IsNullOrEmpty(_xsltstring) && _threadEntity.WebSetting.DebugMode)) { if (!string.IsNullOrEmpty(_xsltstring)) { using (System.IO.FileStream fs = new System.IO.FileStream(_threadEntity.WebSetting.XsltDir + _xsltstring, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) { _innerData.Write(sr.ReadToEnd()); sr.Close(); } fs.Close(); } } } HandleData(); System.Xml.XPath.XPathDocument xpathDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_datastring)); System.Xml.Xsl.XslCompiledTransform xsl = HandleXSLT(); ContentContainer.Write(Xy.Tools.IO.XML.TransfromXmlStringToHtml(xsl, xpathDoc)); _threadEntity.ControlIndex -= 1; }
public void OpenTypeMetadataTest() { using (TestWebRequest request = TestWebRequest.CreateForInProcess()) { request.DataServiceType = typeof(CustomRowBasedOpenTypesContext); request.RequestUriString = "/$metadata"; request.SendRequest(); using (Stream responseStream = request.GetResponseStream()) { var document = new System.Xml.XPath.XPathDocument(responseStream); // Ensure the OpenType attribute is there. var expression = System.Xml.XPath.XPathExpression.Compile("//csdl:EntityType[@OpenType]", TestUtil.TestNamespaceManager); var nodeIterator = document.CreateNavigator().Select(expression); int count = 0; while (nodeIterator.MoveNext()) { Assert.AreEqual("true", nodeIterator.Current.SelectSingleNode("@OpenType").Value); count++; } // The OpenType attribute is present at all levels of the type hierarchy; expect it on all types. Assert.AreEqual(3, count); } } }
public string GetHtml(string transform_path, string xml) { string xsltPath = Server.MapPath(transform_path) + "\\sdctemplate.xslt"; string csspath = Server.MapPath(transform_path) + "\\sdctemplate.css"; //3/10/2016 - change encoding to unicode System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.UnicodeEncoding.ASCII.GetBytes(xml)); System.Xml.XPath.XPathDocument document = new System.Xml.XPath.XPathDocument(stream); System.IO.StringWriter writer = new System.IO.StringWriter(); System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform(); System.Xml.Xsl.XsltSettings settings = new System.Xml.Xsl.XsltSettings(true, true); System.Xml.XmlSecureResolver resolver = new System.Xml.XmlSecureResolver(new System.Xml.XmlUrlResolver(), csspath); try { transform.Load(xsltPath, settings, resolver); transform.Transform(document, null, writer); } catch (Exception ex) { throw ex; } return(writer.ToString()); }
private static string extractMessage(string exceptionFile) { System.Text.StringBuilder retVal = new System.Text.StringBuilder(); try { System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(exceptionFile); System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator(); System.Xml.XPath.XPathNodeIterator iter = nav.Select(@"/*/ServiceException"); while (iter.MoveNext()) { if (retVal.Length > 0) { retVal.Append(System.Environment.NewLine); } System.Xml.XPath.XPathNodeIterator attIter = iter.Current.Select(@"/code|/Code|/CODE"); if (attIter.MoveNext()) { retVal.Append("(" + iter.Current.Value.Trim() + ") "); } retVal.Append(iter.Current.Value.Trim()); } } catch (System.Exception) { retVal.Append("Unable to extract the error description from the information returned by the WMS server."); } return(retVal.ToString()); }
private bool handleAction_Xsl(string data, string xsltToUse) { //if (this.tmWebServices.tmAuthentication.sessionID. UserRole.ReadArticles var xstlFile = context.Server.MapPath("\\xslt\\" + xsltToUse); if (xstlFile.fileExists()) { var guid = tmWebServices.getGuidForMapping(data); if (guid != Guid.Empty) { var xmlContent = tmWebServices.XmlDatabase_GetGuidanceItemXml(guid); //.add_Xslt(xsltToUse); if (xmlContent.valid()) { //var xslTransform = new System.Xml.Xsl.XslTransform(); var xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xslTransform.Load(xstlFile); var xmlReader = new System.Xml.XmlTextReader(new StringReader(xmlContent)); var xpathNavigator = new System.Xml.XPath.XPathDocument(xmlReader); var stringWriter = new StringWriter(); xslTransform.Transform(xpathNavigator, new System.Xml.Xsl.XsltArgumentList(), stringWriter); context.Response.ContentType = "text/html"; context.Response.Write(stringWriter.str()); return(true); } return(false); } return(transfer_ArticleViewer()); } return(false); }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public override void ReadXml(System.Xml.XmlReader reader) { string dirPath = reader.GetAttribute("DirectoryPath"); if (dirPath == null) { base.ReadXml(reader); } else { //PackageSource = source; PackageDirectory = dirPath; //m_packageDirectory = dirPath; var sourceSerializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(PackageSystem.PackageReference), null); System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader); var nav = doc.CreateNavigator(); var iter = nav.SelectSingleNode("/DirectoryPath/PackageReference"); if (iter == null) { throw new XmlSchemaException(); } PackageSource = (IPackageReference)sourceSerializer.Deserialize(iter.ReadSubtree()); } }
private Server server; // The Wms.Client.Server object associated with these capabilities. public Capabilities(string filePath, Server server) { // Constructor requires a path to an XML capabilities file, // and a reference to a Wms.Client.Server object. this.server = server; this.doc = new System.Xml.XPath.XPathDocument(filePath); }
public void handleAction_Xsl(string data, string xsltToUse) { //if (this.TmWebServices.tmAuthentication.sessionID. UserRole.ReadArticles var xstlFile = context.Server.MapPath("\\xslt\\" + xsltToUse); if (xstlFile.fileExists()) { var guid = tmWebServices.getGuidForMapping(data); if (guid != Guid.Empty) { var xmlContent = tmWebServices.XmlDatabase_GetGuidanceItemXml(guid); //.add_Xslt(xsltToUse); if (xmlContent.valid()) { //var xslTransform = new System.Xml.Xsl.XslTransform(); var xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xslTransform.Load(xstlFile); var xmlReader = new System.Xml.XmlTextReader(new StringReader(xmlContent)); var xpathNavigator = new System.Xml.XPath.XPathDocument(xmlReader); var stringWriter = new StringWriter(); xslTransform.Transform(xpathNavigator, new System.Xml.Xsl.XsltArgumentList(), stringWriter); context.Response.ContentType = "text/html"; context.Response.Write(stringWriter.str()); var article = tmWebServices.GetGuidanceItemById(guid); switch (xsltToUse) { case "Notepad_Edit.xslt": tmWebServices.RBAC_Demand_EditArticles(); // will trigger an Security exception if the user if not authorized tmWebServices.logUserActivity("Edit Article (Notepad)", "{0} ({1})".format(article.Metadata.Title, guid)); break; case "TeamMentor_Article.xslt": tmWebServices.logUserActivity("View Article (xslt)", "{0} ({1})".format(article.Metadata.Title, guid)); break; case "JsCreole_Article.xslt": tmWebServices.logUserActivity("View Article (wiki)", "{0} ({1})".format(article.Metadata.Title, guid)); break; default: tmWebServices.logUserActivity("View Article ({0})", "{1} ({2})".format(xsltToUse, data, xsltToUse)); break; } endResponse(); } } else { transfer_Request("articleViewer"); // will trigger exception } } }
private byte[] HandleHTML(System.Xml.XPath.XPathDocument DataString, string XsltString) { if (DataString != null) { System.Xml.Xsl.XslCompiledTransform xslTransform = Xy.Web.Cache.XslCompiledTransform.Get(XsltString, _enableCode, _enableCache); return(Xy.Tools.IO.XML.TransfromXmlStringToHtml(xslTransform, DataString)); } return(new byte[0]); }
public static byte[] TransfromXmlStringToHtml(string xsltpath, string XmlString) { System.IO.StringReader xml = new System.IO.StringReader(XmlString); System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(xml); System.Xml.Xsl.XslCompiledTransform xsl = new System.Xml.Xsl.XslCompiledTransform(); xsl.Load(xsltpath); return(TransfromXmlStringToHtml(xsl, xmlDoc)); }
public WeatherPoint GetCurrentWeather(string woeId) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://weather.yahooapis.com/forecastrss?w={0}&u=c", woeId)); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { var document = new System.Xml.XPath.XPathDocument(response.GetResponseStream()); var navigator = document.CreateNavigator(); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0"); var temperature = navigator.SelectSingleNode("rss/channel/item/yweather:condition/@temp", manager); var conditionCode = navigator.SelectSingleNode("rss/channel/item/yweather:condition/@code", manager); var windSpeed = navigator.SelectSingleNode("rss/channel/yweather:wind/@speed", manager); var windChill = navigator.SelectSingleNode("rss/channel/yweather:wind/@chill", manager); var windDirection = navigator.SelectSingleNode("rss/channel/yweather:wind/@direction", manager); var atmosphereHumidity = navigator.SelectSingleNode("rss/channel/yweather:atmosphere/@humidity", manager); var atmosphereVisibility = navigator.SelectSingleNode("rss/channel/yweather:atmosphere/@visibility", manager); var atmospherePressure = navigator.SelectSingleNode("rss/channel/yweather:atmosphere/@pressure", manager); //var atmosphereRising= navigator.SelectSingleNode("rss/channel/yweather:atmosphere/@rising", manager); var astronomySunrise = navigator.SelectSingleNode("rss/channel/yweather:astronomy/@sunrise", manager); var astronomySunset = navigator.SelectSingleNode("rss/channel/yweather:astronomy/@sunset", manager); var weatherPoint = new Common.Weather.WeatherPoint() { Timestamp = DateTime.Now, Weather = new Common.Weather.WeatherPointData() }; weatherPoint.Weather.Temperature = new Common.Weather.Temperature() { Celsius = decimal.Parse(temperature.Value, System.Globalization.NumberFormatInfo.InvariantInfo) }; if (conditionCode != null && !string.IsNullOrEmpty(conditionCode.Value)) { weatherPoint.Weather.Condition = GetWeatherCondition(conditionCode.Value); } if (windChill != null && !string.IsNullOrEmpty(windChill.Value)) { weatherPoint.Weather.WindChill = decimal.Parse(windChill.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } if (windSpeed != null && !string.IsNullOrEmpty(windSpeed.Value)) { weatherPoint.Weather.WindSpeed = decimal.Parse(windSpeed.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } if (windDirection != null && !string.IsNullOrEmpty(windDirection.Value)) { weatherPoint.Weather.WindDirection = decimal.Parse(windDirection.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } if (atmospherePressure != null && !string.IsNullOrEmpty(atmospherePressure.Value)) { weatherPoint.Weather.Pressure = decimal.Parse(atmospherePressure.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } if (atmosphereVisibility != null && !string.IsNullOrEmpty(atmosphereVisibility.Value)) { weatherPoint.Weather.Visibility = decimal.Parse(atmosphereVisibility.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } if (atmosphereHumidity != null && !string.IsNullOrEmpty(atmosphereHumidity.Value)) { weatherPoint.Weather.Humidity = decimal.Parse(atmosphereHumidity.Value, System.Globalization.NumberFormatInfo.InvariantInfo); } //TODO: Sunrise, Sunset return weatherPoint; } } catch (Exception ex) { return null; } }
static void Main(string[] args) { if (args.Length != 2) { args = new string[] { @"C5.dll", @"C5.xml" }; } { Timer timer = new Timer(); timer.snap(); DocNet doc = new DocNet(args[0], args[1], "C5"); XmlDocument merged = doc.GenerateDoc(); Console.Error.WriteLine("Time merge: {0} ms", timer.snap()); System.Xml.Xsl.XslCompiledTransform overview = new System.Xml.Xsl.XslCompiledTransform(); overview.Load(@"overview.xslt"); overview.Transform(merged, new XmlTextWriter(new StreamWriter(@"docbuild\contents.htm"))); Console.Error.WriteLine("Time, overview: {0} ms", timer.snap()); StringBuilder megaDoc = new StringBuilder(); using (XmlWriter writer = XmlWriter.Create(megaDoc)) { writer.WriteStartElement("hack"); System.Xml.Xsl.XslCompiledTransform trans = new System.Xml.Xsl.XslCompiledTransform(); trans.Load(@"trans.xslt"); trans.Transform(merged, writer); writer.WriteEndElement(); writer.Close(); } Console.Error.WriteLine("Time trans: {0} ms", timer.snap()); System.Xml.XPath.XPathDocument megaXml = new System.Xml.XPath.XPathDocument(XmlReader.Create(new StringReader(megaDoc.ToString()))); System.Xml.XPath.XPathNodeIterator nodes = megaXml.CreateNavigator().Select("/hack/*"); string docfn = null; foreach (System.Xml.XPath.XPathNavigator var in nodes) { if (var.Name == "filestart") { docfn = var.GetAttribute("name", ""); } if (var.Name == "html") { Console.Error.Write("."); XmlWriter w = new XmlTextWriter(new StreamWriter(@"docbuild\types\" + docfn)); var.WriteSubtree(w); w.Close(); } } Console.Error.WriteLine(); Console.Error.WriteLine("Time split: {0} ms", timer.snap()); } Console.Write("? "); Console.Read(); }
/// <summary> /// Converts the current reader value to an XPath Navigator and returns it /// </summary> /// <param name="reader"></param> /// <param name="requiredType"></param> /// <param name="settings"></param> /// <returns></returns> internal static object ToXPathNavigator(XmlReader reader, Type requiredType, PDFGeneratorSettings settings) { while (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.Comment) { reader.Read(); } XmlReader inner = reader.ReadSubtree(); System.Xml.XPath.XPathNavigator nav = new System.Xml.XPath.XPathDocument(inner).CreateNavigator(); return(nav); }
/// <summary> /// Makes an authenticated web service call that returns XML data and returns the result as an XPathDocument. /// </summary> /// <param name="wsAddress">Address of web service with parameters to call.</param> /// <returns></returns> public System.Xml.XPath.XPathDocument GetAuthenticatedServiceXPathDocument(System.Uri wsAddress) { System.Xml.XPath.XPathDocument result = null; using (System.IO.Stream dataStream = GetAuthenticatedServiceStream(wsAddress)) { // Read result into a XPathDocument result = new System.Xml.XPath.XPathDocument(dataStream); } return(result); }
static float Evaluate(string expression) { var doc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>")); var nav = doc.CreateNavigator(); var newString = expression; newString = (new System.Text.RegularExpressions.Regex(@"([\+\-\*])")).Replace(newString, " ${1} "); newString = newString.Replace("/", " div ").Replace("%", " mod "); var res = nav.Evaluate("number(" + newString + ")"); double d = (double)res; return((float)d); }
private Server server; // The Wms.Client.Server object associated with these capabilities. public Capabilities(string filePath, Server server) { // Constructor requires a path to an XML capabilities file, // and a reference to a Wms.Client.Server object. this.server = server; // Disable the XmlResolver since it fails if proxy authentication is required // when retreiving schemas listed in the Xml file var xmlReader = new System.Xml.XmlTextReader(filePath); xmlReader.XmlResolver = null; this.doc = new System.Xml.XPath.XPathDocument(xmlReader); }
//Constructor public ET_Client(NameValueCollection parameters = null) { //Get configuration file and set variables System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(@"FuelSDK_config.xml"); foreach (System.Xml.XPath.XPathNavigator child in doc.CreateNavigator().Select("configuration")) { appSignature = child.SelectSingleNode("appSignature").Value.ToString().Trim(); clientId = child.SelectSingleNode("clientId").Value.ToString().Trim(); clientSecret = child.SelectSingleNode("clientSecret").Value.ToString().Trim(); soapEndPoint = child.SelectSingleNode("soapEndPoint").Value.ToString().Trim(); } //If JWT URL Parameter Used if (parameters != null && parameters.AllKeys.Contains("jwt")) { string encodedJWT = parameters["jwt"].ToString().Trim(); String decodedJWT = JsonWebToken.Decode(encodedJWT, appSignature); JObject parsedJWT = JObject.Parse(decodedJWT); authToken = parsedJWT["request"]["user"]["oauthToken"].Value<string>().Trim(); authTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value<string>().Trim())); internalAuthToken = parsedJWT["request"]["user"]["internalOauthToken"].Value<string>().Trim(); refreshKey = parsedJWT["request"]["user"]["refreshToken"].Value<string>().Trim(); } else { refreshToken(); } // Find the appropriate endpoint for the acccount ET_Endpoint getSingleEndpoint = new ET_Endpoint(); getSingleEndpoint.AuthStub = this; getSingleEndpoint.Type = "soap"; GetReturn grSingleEndpoint = getSingleEndpoint.Get(); if (grSingleEndpoint.Status && grSingleEndpoint.Results.Length == 1){ soapEndPoint = ((ET_Endpoint)grSingleEndpoint.Results[0]).URL; } else { throw new Exception("Unable to determine stack using /platform/v1/endpoints: " + grSingleEndpoint.Message); } //Create the SOAP binding for call with Oauth. BasicHttpBinding binding = new BasicHttpBinding(); binding.Name = "UserNameSoapBinding"; binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential; binding.MaxReceivedMessageSize = 2147483647; soapclient = new SoapClient(binding, new EndpointAddress(new Uri(soapEndPoint))); soapclient.ClientCredentials.UserName.UserName = "******"; soapclient.ClientCredentials.UserName.Password = "******"; }
public string GetHtml(string xsltPath, string xml) { //3/10/2016 - change encoding to unicode System.IO.MemoryStream stream = new System.IO.MemoryStream(System.Text.UnicodeEncoding.ASCII.GetBytes(xml)); System.Xml.XPath.XPathDocument document = new System.Xml.XPath.XPathDocument(stream); System.IO.StringWriter writer = new System.IO.StringWriter(); System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform(); System.Xml.Xsl.XsltSettings settings = new System.Xml.Xsl.XsltSettings(true, true); System.Xml.XmlSecureResolver resolver = new System.Xml.XmlSecureResolver(new System.Xml.XmlUrlResolver(), Server.MapPath("Transforms/Ver3/sdctemplate.css")); transform.Load(xsltPath, settings, resolver); transform.Transform(document, null, writer); return(writer.ToString()); }
public static bool TryEvaluate(string expression, out float result) { var doc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>")); var nav = doc.CreateNavigator(); var newString = expression; //newString = (new System.Text.RegularExpressions.Regex(@"([\+\-\*])")).Replace(newString, " ${1} "); newString = newString.Replace("/", " div ").Replace("%", " mod "); try{ newString = nav.Evaluate("number(" + newString + ")").ToString(); }catch (Exception e) { result = 0; return(false); } return(float.TryParse(newString, out result)); }
/// <summary> /// Setup Message Content Query for filtering messages /// </summary> /// <param name="pContext"></param> /// <param name="pInMsg"></param> private void SetupMessageContentQuery(IPipelineContext pContext, ref IBaseMessage pInMsg) { //make sure the stream is seekable, otherwise, wrap it in seekable stream System.IO.Stream streamWrapper = pInMsg.BodyPart.GetOriginalDataStream(); if (!pInMsg.BodyPart.GetOriginalDataStream().CanSeek) { streamWrapper = new ReadOnlySeekableStream(pInMsg.BodyPart.GetOriginalDataStream()); pInMsg.BodyPart.Data = streamWrapper; pContext.ResourceTracker.AddResource(streamWrapper); } //clone the stream to prevent XPathNavigator closing the stream System.IO.Stream streamClone = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(new System.IO.StreamReader(streamWrapper).ReadToEnd())); streamClone.Seek(0, System.IO.SeekOrigin.Begin); System.Xml.XPath.XPathNavigator navigator = new System.Xml.XPath.XPathDocument(streamClone).CreateNavigator(); //perform the queries System.Xml.XPath.XPathExpression query = null; if (!string.IsNullOrEmpty(XPathQuery1)) { query = navigator.Compile(XPathQuery1); isQuery1FoundAndMatch = Convert.ToBoolean(navigator.Evaluate(query)); } if (!string.IsNullOrEmpty(XPathQuery2)) { query = navigator.Compile(XPathQuery2); isQuery2FoundAndMatch = Convert.ToBoolean(navigator.Evaluate(query)); } if (!string.IsNullOrEmpty(XPathQuery3)) { query = navigator.Compile(XPathQuery3); isQuery3FoundAndMatch = Convert.ToBoolean(navigator.Evaluate(query)); } if (!string.IsNullOrEmpty(XPathQuery4)) { query = navigator.Compile(XPathQuery4); isQuery4FoundAndMatch = Convert.ToBoolean(navigator.Evaluate(query)); } if (!string.IsNullOrEmpty(XPathQuery5)) { query = navigator.Compile(XPathQuery5); isQuery5FoundAndMatch = Convert.ToBoolean(navigator.Evaluate(query)); } streamWrapper.Seek(0, System.IO.SeekOrigin.Begin); pContext.ResourceTracker.AddResource(streamWrapper); }
public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { ProbeHistory probeHistory; if (_probeStates.TryGetValue(source, out probeHistory)) { string value = ""; try { using (System.IO.StringReader reader = new System.IO.StringReader(message)) { System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(reader); System.Xml.XPath.XPathNavigator xmlNav = xmlDoc.CreateNavigator(); if (eventType != TraceEventType.Critical) { value = xmlNav.SelectSingleNode("//Value").InnerXml; } } } catch (Exception) { } string eventMessage = message; try { using (System.IO.StringReader reader = new System.IO.StringReader(message)) { System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(reader); System.Xml.XPath.XPathNavigator xmlNav = xmlDoc.CreateNavigator(); eventMessage = xmlNav.SelectSingleNode("//Message").InnerXml; } } catch (Exception) { } ProbeState probeState = new ProbeState(); probeState.EventId = id; probeState.Message = eventMessage; probeState.Value = value; probeState.Timestamp = DateTime.Now.ToString("yyyy'-'MM'-'dd' 'HH':'mm':'ss"); probeState.Status = eventType.ToString(); AddProbeState(probeState, ref probeHistory); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddCors(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "csPlayground", Version = "v1" }); //c.EnableAnnotations(); //var filePath = Path.Combine(System.AppContext.BaseDirectory, "csPlayground.xml"); var document = new System.Xml.XPath.XPathDocument(Assembly.GetExecutingAssembly() .GetManifestResourceStream("csPlayground.csPlayground.xml")); c.IncludeXmlComments(() => document, true); }); }
/// <summary> /// 设置区域信息 /// </summary> /// <param name="cultureConfigFile">语言配置文件路径</param> public void SetCulture(string cultureConfigFile) { System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(ZeroConfigSystem.Instance.SysCultureFile); System.Xml.XPath.XPathNavigator navigator = doc.CreateNavigator(); bool enableSetCulture = false; if (navigator.SelectSingleNode("/CultureInfo/EnableSetCulture") != null) { string value = navigator.SelectSingleNode("/CultureInfo/EnableSetCulture").Value; if (!string.IsNullOrEmpty(value)) { enableSetCulture = value.Equals("1"); } } this.EnableSetLanguage = enableSetCulture; this.SystemDefaultCulture = "en-US"; if (navigator.SelectSingleNode("/CultureInfo/Culture") != null) { this.SystemDefaultCulture = navigator.SelectSingleNode("/CultureInfo/Culture").Value; if (string.IsNullOrEmpty(this.SystemDefaultCulture)) { this.SystemDefaultCulture = "en-US"; } } this.CurrentCulture = this.SystemDefaultCulture; this.IsCustomCulture = false; if (File.Exists(cultureConfigFile)) { string customCulture = IniFileHelper.ReadINIValue(cultureConfigFile, "Langauge", "Default"); if (!string.IsNullOrEmpty(customCulture)) { CurrentCulture = customCulture; } string enableCustomCulture = IniFileHelper.ReadINIValue(cultureConfigFile, "Langauge", "EnableCustomCulture"); if (!string.IsNullOrEmpty(enableCustomCulture)) { this.IsCustomCulture = enableCustomCulture.Equals("1"); } } SetCulture(CurrentCulture, this.IsCustomCulture); }
// Write the SMIL files from the Z composite document private void WriteSMILFiles(System.Xml.XPath.XPathDocument z) { System.Xml.Xsl.XslCompiledTransform smilXslt = new System.Xml.Xsl.XslCompiledTransform(true); smilXslt.Load(System.IO.Path.Combine(mAssemblyLocation, SMIL_XSLT), null, mResolver); System.Xml.XPath.XPathNavigator navigator = z.CreateNavigator(); System.Xml.XmlNamespaceManager nsmgr = new System.Xml.XmlNamespaceManager(navigator.NameTable); nsmgr.AddNamespace("smil", "http://www.w3.org/2001/SMIL20/"); System.Xml.XPath.XPathNodeIterator it = navigator.Select("/z/smil:smil/smil:body/smil:seq", nsmgr); while (it.MoveNext()) { System.Xml.Xsl.XsltArgumentList args = new System.Xml.Xsl.XsltArgumentList(); string id = it.Current.GetAttribute("id", ""); args.AddParam("id", "", id); System.Xml.XmlWriter smilFile = System.Xml.XmlWriter.Create(FullPath(".smil", id), smilXslt.OutputSettings); smilXslt.Transform(z, args, smilFile); } }
/// <summary> /// /// </summary> /// <param name="q"></param> /// <returns></returns> internal Song getOneSong(Queue q) { //get song from playlist String path = q.getPlaylistPath(); System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(path); System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator(); Random random = new Random(); int num = random.Next(0, q.getPlaylistLen()); String id = String.Format("{0:000000}", num); nav.MoveToId(id); Song newSong = new Song(nav.Value); doc = null; return(newSong); }
public List<WeatherPeriod> GetDailyForecastWeather(string woeId) { try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://weather.yahooapis.com/forecastrss?w={0}&u=c", woeId)); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { var document = new System.Xml.XPath.XPathDocument(response.GetResponseStream()); var navigator = document.CreateNavigator(); XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable); manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0"); var forecasts = navigator.Select("rss/channel/item/yweather:forecast", manager); var list = new List<Common.Weather.WeatherPeriod>(); foreach (System.Xml.XPath.XPathNavigator forecast in forecasts) { var weatherPeriod = new Common.Weather.WeatherPeriod() { Weather = new Common.Weather.WeatherPeriodData() }; var date = forecast.SelectSingleNode("@date", manager); var day = forecast.SelectSingleNode("@day", manager); var high = forecast.SelectSingleNode("@high", manager); var low = forecast.SelectSingleNode("@low", manager); var weatherCode = forecast.SelectSingleNode("@code", manager); weatherPeriod.Weather.MaxTemperature = new Common.Weather.Temperature() { Celsius = decimal.Parse(high.Value, System.Globalization.NumberFormatInfo.InvariantInfo) }; weatherPeriod.Weather.MinTemperature = new Common.Weather.Temperature() { Celsius = decimal.Parse(low.Value, System.Globalization.NumberFormatInfo.InvariantInfo) }; weatherPeriod.Weather.Condition = GetWeatherCondition(weatherCode.Value); //TODO: Tag bestimmen: DateTime dateTime; if (DateTime.TryParse(date.Value, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AssumeLocal, out dateTime)) { weatherPeriod.TimeFrom = dateTime; weatherPeriod.TimeTo = dateTime.AddDays(1); } //weatherInformation.DayOfWeek = day.Value; list.Add(weatherPeriod); } return list; } } catch (Exception ex) { return null; } }
public static RecentExperimentList LoadRecentExperimentListFromXML(string pFilepath) { RecentExperimentList list = new RecentExperimentList(); if (System.IO.File.Exists(pFilepath)) { try { System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(pFilepath); System.Xml.XPath.XPathNavigator nav = doc.CreateNavigator(); System.Xml.XPath.XPathNodeIterator itemIterator = nav.Select("/RecentExperiments/RecentExperimentItem"); int numItems = itemIterator.Count; string fullpath, time; while (itemIterator.MoveNext()) { fullpath = itemIterator.Current.GetAttribute("FullPath", String.Empty); time = itemIterator.Current.GetAttribute("LastAccessTime", String.Empty); RecentExperimentReference item = RecentExperimentReference.CreateRecentExperimentItem(fullpath, time); if (item != null) { list.AddLast(item); } } if (list.Count != numItems) { RecentExperimentsHelper.SaveRecentExperimentListToXML(list, pFilepath); } } catch (XmlException) { System.IO.File.Delete(pFilepath); list.Clear(); } } return list; }
public static string FormatXml(string transactionalXml) { transactionalXml = "<ROOT>" + transactionalXml + "</ROOT>"; XmlDocument xmlDoc = new XmlDocument(); Stream xmlStream; System.Xml.Xsl.XslCompiledTransform xsl = new System.Xml.Xsl.XslCompiledTransform(); ASCIIEncoding enc = new ASCIIEncoding(); StringWriter writer = new System.IO.StringWriter(); // Get Xsl xsl.Load(HttpContext.Current.Server.MapPath(@"\css\defaultss.xslt")); // Remove the utf encoding as it causes problems with the XPathDocument transactionalXml = transactionalXml.Replace("utf-32", ""); transactionalXml = transactionalXml.Replace("utf-16", ""); transactionalXml = transactionalXml.Replace("utf-8", ""); xmlDoc.LoadXml(transactionalXml); // Get the bytes xmlStream = new MemoryStream(enc.GetBytes(xmlDoc.OuterXml), true); // Load Xpath document System.Xml.XPath.XPathDocument xp = new System.Xml.XPath.XPathDocument(xmlStream); // Perform Transform xsl.Transform(xp, null, writer); return writer.ToString(); }
private bool handleAction_Xsl(string data, string xsltToUse) { //if (this.tmWebServices.tmAuthentication.sessionID. UserRole.ReadArticles var xstlFile = context.Server.MapPath("\\xslt\\" + xsltToUse); if (xstlFile.fileExists()) { var guid = tmWebServices.getGuidForMapping(data); if (guid != Guid.Empty) { var xmlContent = tmWebServices.XmlDatabase_GetGuidanceItemXml(guid); //.add_Xslt(xsltToUse); if (xmlContent.valid()) { //var xslTransform = new System.Xml.Xsl.XslTransform(); var xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xslTransform.Load(xstlFile); var xmlReader = new System.Xml.XmlTextReader(new StringReader(xmlContent)); var xpathNavigator = new System.Xml.XPath.XPathDocument(xmlReader); var stringWriter = new StringWriter(); xslTransform.Transform(xpathNavigator, new System.Xml.Xsl.XsltArgumentList(), stringWriter); context.Response.ContentType = "text/html"; context.Response.Write(stringWriter.str()); return true; } return false; } return transfer_ArticleViewer(); } return false; }
/// <summary> /// LoadDetailsFromConfigFile: /// Loads details from the config file. It populates the global variable cfProducts with /// product names. If the productName parameter is not empty and contains a valid product /// name, then the productDetails parameter is populated with the build information for /// the specified product. /// </summary> /// <param name="configFileName">[required, in] The path and filename of the config file</param> /// <param name="productName">[optional, in] The name of the product to be loaded</param> /// <param name="productDetails">[optional, out] Required only if productName is specified</param> /// <returns>A boolean value indicating if product names were successfully added to the /// cfProducts variable</returns> private bool LoadDetailsFromConfigFile(string configFileName, string productName, out ProductDetails productDetails) { productDetails = null; //Local variables bool hasMoreProducts = true; //Erase any previously loaded information cfProducts = null; XmlTextReader xmlReader = null; XmlValidatingReader validator = null; System.Xml.XPath.XPathDocument doc; System.Xml.XPath.XPathNavigator nav; try { xmlReader = new XmlTextReader(configFileName); validator = new XmlValidatingReader(xmlReader); validator.ValidationType = ValidationType.DTD; //Any errors will cause an XmlException to be thrown while (validator.Read()) { } doc = new System.Xml.XPath.XPathDocument(configFileName); nav = doc.CreateNavigator(); } catch (Exception) { if (xmlReader != null) xmlReader.Close(); if (validator != null) validator.Close(); return false; } #region Load PRODUCT names (and product details if specified) from the XML configuration file //Move to the SIBuilder Tag nav.MoveToFirstChild(); if (!nav.HasChildren) { //MessageBox.Show ("The configuration file does not contain any products that can be built", errorDialogCaption); xmlReader.Close(); validator.Close(); return false; } this.cfProducts = new ArrayList(); //Move to the first PRODUCT in the configuration file nav.MoveToFirstChild (); hasMoreProducts = true; while (hasMoreProducts) { this.cfProducts.Add (nav.GetAttribute ("Name", "")); //Check if the Name attribute was returned; if not declare config file corrupt if (this.cfProducts[this.cfProducts.Count - 1].ToString() == String.Empty) { this.cfProducts = null; xmlReader.Close(); validator.Close(); return false; } #region Load details of this product if requested by the user //Check if the user wants details about the current PRODUCT if ((productName != "") && (cfProducts[cfProducts.Count -1].ToString() == productName)) { productDetails = new ProductDetails(); //Add the product name productDetails.Name = productName; //Get the Versioning information productDetails.MajorVersion = nav.GetAttribute ("MajorVersion", ""); productDetails.MinorVersion = nav.GetAttribute ("MinorVersion", ""); productDetails.BuildNumber = nav.GetAttribute ("BuildNumber", ""); //Get the other product details if (nav.HasChildren) { nav.MoveToFirstChild(); bool moreProductDetails = true; bool moreChildren = true; while (moreProductDetails) { switch (nav.Name.ToUpper()) { case "SOURCECONTROL": //Move into the children of the SOURCECONTROL node moreChildren= nav.MoveToFirstChild(); if (!moreChildren) break; while (moreChildren) { if (productDetails.SourceControlInfo== null) productDetails.SourceControlInfo = new ArrayList(); SourceControlInfo scInfo = new SourceControlInfo(); scInfo.Executable = nav.Value; scInfo.Arguments = nav.GetAttribute ("Args", ""); productDetails.SourceControlInfo.Add (scInfo); moreChildren = nav.MoveToNext(); } //Move back to the SOURCECONTROL node nav.MoveToParent(); break; case "PATHS": //Move into the children of the PATHS node moreChildren = nav.MoveToFirstChild(); if (!moreChildren) break; while (moreChildren) { switch (nav.Name.ToUpper()) { case "BUILDS_LOCATION": productDetails.BuildsLocation = nav.Value; break; case "LOGS_LOCATION": productDetails.LogsLocation = nav.Value; break; case "DEVENV_FILE": productDetails.DevenvFile = nav.Value; break; case "INSTALLSHIELD_SCRIPT": productDetails.InstallShieldScript = nav.Value; break; case "INSTALLSHIELD_OUTPUT": productDetails.InstallShieldOutput = nav.Value; break; default: break; } moreChildren = nav.MoveToNext(); } //Move back to the PATHS node nav.MoveToParent(); break; case "BUILDMAIL": //Move to the children of the BUILDMAIL node moreChildren = nav.MoveToFirstChild(); if (!moreChildren) break; while (moreChildren) { switch (nav.Name.ToUpper()) { case "RECIPIENTS": productDetails.MailRecipients = nav.Value; break; case "MAILSENDER": productDetails.MailSenderAddress = nav.GetAttribute ("Address", ""); productDetails.MailServerAddress = nav.GetAttribute ("SmtpServer", ""); break; default: break; } moreChildren = nav.MoveToNext(); } //Move back to the BUILDMAIL node nav.MoveToParent(); break; case "BUILD_SOLUTIONS": //Move to the children of the BUILD_SOLUTIONS node moreChildren = nav.MoveToFirstChild(); if (!moreChildren) break; while (moreChildren) { switch (nav.Name.ToUpper()) { case "SOLUTION": if (productDetails.SolutionInfo == null) productDetails.SolutionInfo = new ArrayList(); SolutionInfo solInfo = new SolutionInfo(); solInfo.SolutionPath = nav.Value; solInfo.ProjectName = nav.GetAttribute ("Project", ""); solInfo.BuildConfig = nav.GetAttribute ("BuildConfig", ""); productDetails.SolutionInfo.Add (solInfo); break; default: break; } moreChildren = nav.MoveToNext(); } //Move back to the BUILD_SOLUTIONS node nav.MoveToParent(); break; default: break; } moreProductDetails = nav.MoveToNext(); } } } #endregion hasMoreProducts = nav.MoveToNext(); } #endregion xmlReader.Close(); validator.Close(); return true; }
public XPathOperator(string uri) { _XPathDoc = new System.Xml.XPath.XPathDocument(uri); }
Digest.Model.WebReferenceUrl[] getWebReferenceUrls(DirectoryInfo folder, string currentPath) { string relPath = Path.Combine(currentPath, folder.Name); string url = string.Empty; List<Digest.Model.WebReferenceUrl> webReferenceUrls = new List<Digest.Model.WebReferenceUrl>(); FileInfo[] fileInfo = folder.GetFiles("*.discomap"); if (fileInfo != null && fileInfo.Length > 0) { System.Xml.XPath.XPathDocument xDoc = new System.Xml.XPath.XPathDocument(fileInfo[0].FullName); System.Xml.XPath.XPathNavigator xNav = xDoc.CreateNavigator(); string xpathExpression = @"DiscoveryClientResultsFile/Results/DiscoveryClientResult[@referenceType='System.Web.Services.Discovery.ContractReference']/@url"; System.Xml.XPath.XPathNodeIterator xIter = xNav.Select(xpathExpression); if (xIter.MoveNext()) { url = xIter.Current.TypedValue.ToString(); } } if (!string.IsNullOrEmpty(url)) { Digest.Model.WebReferenceUrl newWebReferenceUrl = new Digest.Model.WebReferenceUrl(); newWebReferenceUrl.RelPath = relPath; newWebReferenceUrl.UpdateFromURL = url; webReferenceUrls.Add(newWebReferenceUrl); } foreach (DirectoryInfo dirInfo in folder.GetDirectories()) { webReferenceUrls.AddRange(getWebReferenceUrls(dirInfo, relPath)); } return webReferenceUrls.ToArray(); }
private void exportXmlToolStripMenuItem_Click(object sender, EventArgs e) { int licenseType = VirtPackage.LicDataLoadFromFile(null); if (licenseType < VirtPackage.LICENSETYPE_PRO) { MessageBox.Show("Insufficient license"); return; } // TODO: require password FolderBrowserDialog saveFileDialog = new FolderBrowserDialog(); saveFileDialog.ShowNewFolderButton = true; /*SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.AddExtension = true; saveFileDialog.Filter = "Cameyo Blueprint (*.xml)|*.xml"; saveFileDialog.DefaultExt = "xml";*/ if (saveFileDialog.ShowDialog() == DialogResult.OK) { string appID = virtPackage.GetProperty("AppID").Trim(); string outDir = Path.Combine(saveFileDialog.SelectedPath, appID + ".Blueprint"); if (Directory.Exists(outDir)) { if (MessageBox.Show(outDir + "\nalready exists. Continue?", "Confirm", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) return; } else { try { if (Directory.CreateDirectory(outDir) == null) throw new Exception("Cannot create directory " + outDir); } catch { MessageBox.Show("Cannot create directory: " + outDir); return; } } // Start by exporting package's properties using -ExportAllProperties string packageExeFile = virtPackage.openedFile; string propsFile = Path.Combine(outDir, "PropsTmp.xml"); int exitCode = -1; bool packagerOk = (ExecProg(PackagerExe(), String.Format("-Quiet \"-ExportAllProperties:{0}\" \"{1}\"", propsFile, packageExeFile), true, ref exitCode) && exitCode == 0); if (!packagerOk) { MessageBox.Show("ExportAllProperties failed: " + exitCode.ToString()); return; } // Complete XML with Files and Registry var writerSettings = new XmlWriterSettings(); writerSettings.OmitXmlDeclaration = true; writerSettings.Indent = true; writerSettings.Encoding = Encoding.Unicode; using (XmlWriter xmlOut = XmlWriter.Create(Path.Combine(outDir, appID + ".xml"), writerSettings)) { string outFilesDir = outDir; xmlOut.WriteStartDocument(); xmlOut.WriteStartElement("CameyoPkg"); // Read existing XML Properties/Property nodes xmlOut.WriteStartElement("Properties"); { var xd = new System.Xml.XPath.XPathDocument(propsFile); var navigator = xd.CreateNavigator(); var iterator = navigator.Select("//Properties/Property"); foreach (System.Xml.XPath.XPathNavigator n in iterator) { n.MoveToFirstAttribute(); var name = n.Name; var val = n.Value; xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString(name, val); xmlOut.WriteEndElement(); } } xmlOut.WriteEndElement(); /*var xmlReader = XmlReader.Create(propsFile); try { if (xmlReader.ReadToDescendant("Properties")) { while (xmlReader.Read()) { var str = xmlReader.Name; xmlOut.WriteNode(xmlReader, true); } } } catch (Exception ex) { MessageBox.Show("Error parsing exported properties' XML: " + ex.ToString()); return; } // Properties string autoLaunch = virtPackage.GetProperty("AutoLaunch"); xmlOut.WriteStartElement("Properties"); { xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("AppID", virtPackage.GetProperty("AppID")); xmlOut.WriteEndElement(); xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("Version", virtPackage.GetProperty("Version")); xmlOut.WriteEndElement(); xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("BaseDirName", virtPackage.GetProperty("BaseDirName")); xmlOut.WriteEndElement(); //xmlOut.WriteStartElement("Property"); //xmlOut.WriteAttributeString("IconFile", "Icon.exe"); //xmlOut.WriteEndElement(); xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("StopInheritance", virtPackage.GetProperty("StopInheritance")); xmlOut.WriteEndElement(); xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("BuildOutput", "[AppID].exe"); xmlOut.WriteEndElement(); // AutoLaunch if (!string.IsNullOrEmpty(autoLaunch)) { xmlOut.WriteStartElement("Property"); xmlOut.WriteAttributeString("AutoLaunch", autoLaunch); xmlOut.WriteEndElement(); } } xmlOut.WriteEndElement();*/ // AutoLaunch property -> autoLaunchFiles list var autoLaunchFiles = new List<string>(); /*todo:string[] autoLaunches = autoLaunch.Split(';'); foreach (string item in autoLaunches) { string[] elements = item.Split('>'); if (elements.Length > 0) autoLaunchFiles.Add(elements[0]); }*/ // FileSystem xmlOut.WriteStartElement("FileSystem"); if (fsFolderTree.Nodes.Count != 0 && fsFolderTree.Nodes[0].Nodes.Count != 0) { BlueprintFilesRecurse(xmlOut, fsFolderTree.Nodes[0].Nodes, outFilesDir); } xmlOut.WriteEndElement(); // Registry xmlOut.WriteStartElement("Registry"); if (regEditor.workKey == null) ThreadedRegLoad(); // If registry isn't loaded yet, load it now (synchronously) if (regEditor.workKey != null) BlueprintRegKeysRecurse(xmlOut, regEditor.workKey, "", ""); xmlOut.WriteEndElement(); // Sandbox /*xmlOut.WriteStartElement("Sandbox"); { xmlOut.WriteStartElement("FileSystem"); xmlOut.WriteAttributeString("access", "Full"); xmlOut.WriteEndElement(); xmlOut.WriteStartElement("Registry"); xmlOut.WriteAttributeString("access", "Full"); xmlOut.WriteEndElement(); } xmlOut.WriteEndElement();*/ xmlOut.WriteEndElement(); xmlOut.WriteEndDocument(); xmlOut.Flush(); xmlOut.Close(); try { File.Delete(propsFile); } catch { } MessageBox.Show("Created in:\n" + outDir); } } }
//private string PROFILE_RECEIVENOTIFICATION = "ReceiveNotification"; public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (name == null || name.Length == 0) name = "EucalyptoNotificationProvider"; base.Initialize(name, config); this.mProviderName = name; //Read the configurations string templatePath = ExtractConfigValue(config, "template", null); if (templatePath == null || templatePath.Length == 0) { throw new EucalyptoException("template cannot be empty."); } templatePath = PathHelper.LocateServerPath(templatePath); mTemplate = new System.Xml.XPath.XPathDocument(templatePath); Enabled = bool.Parse(ExtractConfigValue(config, "enabled", "true")); // Throw an exception if unrecognized attributes remain if (config.Count > 0) { string attr = config.GetKey(0); if (!String.IsNullOrEmpty(attr)) throw new System.Configuration.Provider.ProviderException("Unrecognized attribute: " + attr); } }
//Constructor public ET_Client(NameValueCollection parameters = null) { //Get configuration file and set variables System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(@"FuelSDK_config.xml"); foreach (System.Xml.XPath.XPathNavigator child in doc.CreateNavigator().Select("configuration")) { appSignature = child.SelectSingleNode("appSignature").Value.ToString().Trim(); clientId = child.SelectSingleNode("clientId").Value.ToString().Trim(); clientSecret = child.SelectSingleNode("clientSecret").Value.ToString().Trim(); soapEndPoint = child.SelectSingleNode("soapEndPoint").Value.ToString().Trim(); } //Create the SOAP binding for call with Oauth. BasicHttpBinding binding = new BasicHttpBinding(); binding.Name = "UserNameSoapBinding"; binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential; binding.MaxReceivedMessageSize = 2147483647; soapclient = new SoapClient(binding, new EndpointAddress(new Uri(soapEndPoint))); soapclient.ClientCredentials.UserName.UserName = "******"; soapclient.ClientCredentials.UserName.Password = "******"; //If JWT URL Parameter Used if (parameters != null && parameters.AllKeys.Contains("jwt")) { string encodedJWT = parameters["jwt"].ToString().Trim(); String decodedJWT = JsonWebToken.Decode(encodedJWT, appSignature); JObject parsedJWT = JObject.Parse(decodedJWT); authToken = parsedJWT["request"]["user"]["oauthToken"].Value<string>().Trim(); authTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value<string>().Trim())); internalAuthToken = parsedJWT["request"]["user"]["internalOauthToken"].Value<string>().Trim(); refreshKey = parsedJWT["request"]["user"]["refreshToken"].Value<string>().Trim(); } else { refreshToken(); } }
/// <summary> /// Attempts to get or update the user authentication credentials that are required for web service calls. /// </summary> /// <exception cref="AuthenticationException">The <see cref="Token"/> is not set or the authentication system returned an error. Check the ErrorCode property for details.</exception> public void UpdateCredentials() { System.Xml.XPath.XPathDocument xpDoc; System.Xml.XPath.XPathNavigator navigator; System.Xml.XPath.XPathNavigator node; if(this._token.Length == 0) { throw new AuthenticationException(Properties.Resources.ErrorTokenNotSet, AuthenticationErrorCode.TokenInvalid); } // Make a call to the authentication service to retrieve the WSSID and cookie try { // Clear current authentication details _wssId = ""; _cookies = ""; using (System.IO.Stream dataStream = GetServiceStream(GetTokenLogOnAddress(),false)) { xpDoc = new System.Xml.XPath.XPathDocument(dataStream); } // Attempt to select "/BBAuthTokenLoginResponse/Success" navigator = xpDoc.CreateNavigator(); node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Success"); if (node != null) { // Get cookies node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Success/Cookie"); if (node != null) { _cookies = node.Value; } if (_cookies.Length != 0) { _cookies = _cookies.Replace(";", ","); } else { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorCookieParse, AuthenticationErrorCode.Other); } // Get WSSID node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Success/WSSID"); if (node != null) { _wssId = node.Value; } else { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorWssIdNotSet, AuthenticationErrorCode.Other); } // Get timeout value of the cookie and WSSID int timeout = 0; node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Success/Timeout"); if (node != null) { try { // With .NET 2.0 we could use node.ValueAsInt timeout = int.Parse(node.Value, System.Globalization.CultureInfo.InvariantCulture); } catch (FormatException) { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorTimeoutParse, AuthenticationErrorCode.Other); } catch (OverflowException) { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorTimeoutParse, AuthenticationErrorCode.Other); } catch (InvalidCastException) { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorTimeoutParse, AuthenticationErrorCode.Other); } } else { // Raise custom error throw new AuthenticationException(Properties.Resources.ErrorTimeoutParse, AuthenticationErrorCode.Other); } _validUntil = DateTime.Now.AddSeconds(timeout); } else { AuthenticationErrorCode errorCode = AuthenticationErrorCode.Unknown; string errorCodeText = ""; string errorDesc = Properties.Resources.ErrorUnknown; node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Error"); if (node != null) { // Get error code node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Error/ErrorCode"); if (node != null) { errorCodeText = node.Value; } if (errorCodeText.Length != 0) { try { if (Enum.IsDefined(typeof(AuthenticationErrorCode), int.Parse(errorCodeText, System.Globalization.CultureInfo.InvariantCulture)) == true) { errorCode = (AuthenticationErrorCode)Enum.Parse(typeof(AuthenticationErrorCode), errorCodeText, true); } } catch (ArgumentException) { } catch (FormatException) { } } // Get error description node = SelectSingleNode(navigator, "/BBAuthTokenLoginResponse/Error/ErrorDescription"); if (node != null) { errorDesc = node.Value; } } // Raise error throw new AuthenticationException(errorDesc, errorCode); } } catch(System.Net.WebException wex) { // Try to retrieve more information about the network error string errorDesc = Properties.Resources.ErrorNetwork; System.Net.HttpWebResponse errorResponse = null; try { errorResponse = wex.Response as System.Net.HttpWebResponse; if (errorResponse != null) { errorDesc = errorResponse.StatusDescription + " (" + ((int)errorResponse.StatusCode).ToString(System.Globalization.CultureInfo.InvariantCulture) + ")"; } } catch { } finally { if (errorResponse != null) { errorResponse.Close(); } } // Raise error throw new AuthenticationException(errorDesc, wex, AuthenticationErrorCode.NetworkError); } }
/// <summary> /// Executes the Command and returns an XPathDocument /// </summary> /// <returns>An XPathDocument</returns> protected System.Xml.XPath.XPathDocument GetXPathDocument() { this.UseConnectionAndTransaction(DbConnection); try { DbConnection.Open(); System.Xml.XmlReader reader = ((System.Data.SqlClient.SqlCommand)(Command)).ExecuteXmlReader(); System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader); reader.Close(); return doc; } finally { DbConnection.Close(); } }
private void WriteHTMLOutput(Type type, object value, Stream writeStream) { StreamWriter writer = new StreamWriter(writeStream, Encoding.UTF8); writer.WriteLine("<html>"); writer.WriteLine("<head>"); writer.WriteLine(" <link href=\"/Content/fhir-html.css\" rel=\"stylesheet\"></link>"); writer.WriteLine("</head>"); writer.WriteLine("<body>"); if (type == typeof(OperationOutcome)) { OperationOutcome oo = (OperationOutcome)value; if (oo.Text != null) writer.Write(oo.Text.Div); } else if (type == typeof(Resource)) { if (value is Bundle) { Bundle resource = (Bundle)value; if (resource.SelfLink != null) { writer.WriteLine(String.Format("Searching: {0}<br/>", resource.SelfLink.OriginalString)); // Hl7.Fhir.Model.Parameters query = FhirParser.ParseQueryFromUriParameters(collection, parameters); NameValueCollection ps = resource.SelfLink.ParseQueryString(); if (ps.AllKeys.Contains(FhirParameter.SORT)) writer.WriteLine(String.Format(" Sort by: {0}<br/>", ps[FhirParameter.SORT])); if (ps.AllKeys.Contains(FhirParameter.SUMMARY)) writer.WriteLine(" Summary only<br/>"); if (ps.AllKeys.Contains(FhirParameter.COUNT)) writer.WriteLine(String.Format(" Count: {0}<br/>", ps[FhirParameter.COUNT])); if (ps.AllKeys.Contains(FhirParameter.SNAPSHOT_INDEX)) writer.WriteLine(String.Format(" From RowNum: {0}<br/>", ps[FhirParameter.SNAPSHOT_INDEX])); if (ps.AllKeys.Contains(FhirParameter.SINCE)) writer.WriteLine(String.Format(" Since: {0}<br/>", ps[FhirParameter.SINCE])); foreach (var item in ps.AllKeys.Where(k => !k.StartsWith("_"))) { if (ModelInfo.SearchParameters.Exists(s => s.Name == item)) { writer.WriteLine(String.Format(" {0}: {1}<br/>", item, ps[item])); //var parameters = transportContext..Request.TupledParameters(); //int pagesize = Request.GetIntParameter(FhirParameter.COUNT) ?? Const.DEFAULT_PAGE_SIZE; //bool summary = Request.GetBooleanParameter(FhirParameter.SUMMARY) ?? false; //string sortby = Request.GetParameter(FhirParameter.SORT); } else { writer.WriteLine(String.Format(" <i>{0}: {1} (excluded)</i><br/>", item, ps[item])); } } } if (resource.FirstLink != null) writer.WriteLine(String.Format("First Link: {0}<br/>", resource.FirstLink.OriginalString)); if (resource.PreviousLink != null) writer.WriteLine(String.Format("Previous Link: {0}<br/>", resource.PreviousLink.OriginalString)); if (resource.NextLink != null) writer.WriteLine(String.Format("Next Link: {0}<br/>", resource.NextLink.OriginalString)); if (resource.LastLink != null) writer.WriteLine(String.Format("Last Link: {0}<br/>", resource.LastLink.OriginalString)); // Write the other Bundle Header data writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">Type: {0}, {1} of {2}</span>", resource.Type.ToString(), resource.Entry.Count, resource.Total)); foreach (var item in resource.Entry) { //IKey key = item.ExtractKey(); writer.WriteLine("<div class=\"item-tile\">"); if (item.IsDeleted()) { if (item.Request != null) { string id = item.Request.Url; writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">{0}</span>", id)); } //if (item.Deleted.Instant.HasValue) // writer.WriteLine(String.Format("<i>Deleted: {0}</i><br/>", item.Deleted.Instant.Value.ToString())); writer.WriteLine("<hr/>"); writer.WriteLine("<b>DELETED</b><br/>"); } else if (item.Resource != null) { Key key = item.Resource.ExtractKey(); string visualurl = key.WithoutBase().ToUriString(); string realurl = key.ToUriString() + "?_format=html"; writer.WriteLine(String.Format("<a style=\"word-wrap: break-word; display:block;\" href=\"{0}\">{1}</a>", realurl, visualurl)); if (item.Resource.Meta != null && item.Resource.Meta.LastUpdated.HasValue) writer.WriteLine(String.Format("<i>Modified: {0}</i><br/>", item.Resource.Meta.LastUpdated.Value.ToString())); writer.WriteLine("<hr/>"); if (item.Resource is DomainResource) { if ((item.Resource as DomainResource).Text != null && !string.IsNullOrEmpty((item.Resource as DomainResource).Text.Div)) writer.Write((item.Resource as DomainResource).Text.Div); else writer.WriteLine(String.Format("Blank Text: {0}<br/>", item.Resource.ExtractKey().ToUriString())); } else { writer.WriteLine("This is not a domain resource"); } } writer.WriteLine("</div>"); } } else { DomainResource resource = (DomainResource)value; string org = resource.ResourceBase + "/" + resource.ResourceType.ToString() + "/" + resource.Id; // TODO: This is probably a bug in the service (Id is null can throw ResourceIdentity == null // reference ResourceIdentity : org = resource.ResourceIdentity().OriginalString; writer.WriteLine(String.Format("Retrieved: {0}<hr/>", org)); string text = (resource.Text != null) ? resource.Text.Div : null; writer.Write(text); writer.WriteLine("<hr/>"); bool summary = requestMessage.RequestSummary(); string xml = FhirSerializer.SerializeResourceToXml(resource, summary); System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(new StringReader(xml)); // And we also need an output writer System.IO.TextWriter output = new System.IO.StringWriter(new System.Text.StringBuilder()); // Now for a little magic // Create XML Reader with style-sheet System.Xml.XmlReader stylesheetReader = System.Xml.XmlReader.Create(new StringReader(Resources.RenderXMLasHTML)); System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xslTransform.Load(stylesheetReader); xslTransform.Transform(xmlDoc, null, output); writer.WriteLine(output.ToString()); } } writer.WriteLine("</body>"); writer.WriteLine("</html>"); writer.Flush(); }
/// <summary> /// Recursive function that finds and /// graphs Wikipedia links /// </summary> /// <param name="g">The graph</param> /// <param name="lookupValue">Name of orgin article</param> /// <param name="hops">How many degrees of separation from the original article</param> private void addLinks(Kitware.VTK.vtkMutableDirectedGraph g, string lookupValue, int hops) { vtkStringArray label = (vtkStringArray)g.GetVertexData().GetAbstractArray("label"); long parent = label.LookupValue(lookupValue); //if lookupValue is not in the graph add it if (parent < 0) { rotateLogo(); parent = g.AddVertex(); label.InsertNextValue(lookupValue); arrListSmall.Add(lookupValue); } //Parse Wikipedia for the lookupValue string underscores = lookupValue.Replace(' ', '_'); System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://en.wikipedia.org/wiki/Special:Export/" + underscores); webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.Accept = "text/xml"; try { System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse(); System.IO.Stream responseStream = webResponse.GetResponseStream(); System.Xml.XmlReader reader = new System.Xml.XmlTextReader(responseStream); String NS = "http://www.mediawiki.org/xml/export-0.4/"; System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader); reader.Close(); webResponse.Close(); System.Xml.XPath.XPathNavigator myXPahtNavigator = doc.CreateNavigator(); System.Xml.XPath.XPathNodeIterator nodesText = myXPahtNavigator.SelectDescendants("text", NS, false); String fullText = ""; //Parse the wiki page for links while (nodesText.MoveNext()) fullText += nodesText.Current.InnerXml + " "; System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(fullText, "\\[\\[.*?\\]\\]"); int max; try { max = System.Convert.ToInt32(toolStripTextBox2.Text); } catch (Exception) { max = -1; } int count = 0; while (m.Success && ((count < max) || (max < 0))) { String s = m.ToString(); int index = s.IndexOf('|'); String substring = ""; if (index > 0) { substring = s.Substring(2, index - 2); } else { substring = s.Substring(2, s.Length - 4); } //if the new substring is not already there add it long v = label.LookupValue(substring); if (v < 0) { rotateLogo(); v = g.AddVertex(); label.InsertNextValue(substring); arrListSmall.Add(substring); if (hops > 1) { addLinks(g, substring, hops - 1); } } else if (arrListSmall.IndexOf(substring) < 0) { arrListSmall.Add(substring); if (hops > 1) { addLinks(g, substring, hops - 1); } } //Make sure nothing is linked to twice by expanding the graph vtkAdjacentVertexIterator avi = vtkAdjacentVertexIterator.New(); g.GetAdjacentVertices((int)parent, avi); m = m.NextMatch(); ++count; while (avi.HasNext()) { long id = avi.Next(); if (id == v) { return; } } rotateLogo(); g.AddGraphEdge((int)parent, (int)v); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public override void NotifyTo(string email, string MailTemplatePath, Dictionary<string, string> parameters) { if (Enabled == false) return; //throw new Exception("The method or operation is not implemented."); String path = PathHelper.LocateServerPath(MailTemplatePath); mTemplate = new System.Xml.XPath.XPathDocument(path); if (string.IsNullOrEmpty(email)) throw new Exception("The Email could not be blank"); if (!AreValidEmails(ref email)) throw new Exception("The Email Address is not valid"); // Specify the message content. using (MailMessage message = CreateMailMessageFromTemplate(Template, email, parameters)) { //For now I don't use async method because I don't known exactly how to handle the message // dispose and for MSDN seems that you cannot execute 2 or more SendAsync without waiting that the first mail is completed //// Set the method that is called back when the send operation ends. //client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); //// The userState can be any object that allows your callback //// method to identify this send operation. //// For this example, the userToken is a string constant. //string userState = "Notification to " + user.Email + " subject: " + subject; //SmtpClient client = new SmtpClient(); //client.SendAsync(message, userState); try { SmtpClient client = new SmtpClient(); client.Send(message); } catch (Exception ex) { throw new SmtpNotificationException(email, ex); } } }
public string CreatePagination(int CurrentPage, int PageSize, int DataCount, int PageCount) { if (_type != PageDataType.DataTable && _type != PageDataType.Xml) { throw new Exception("only DataTable or XPathDocument can be create pagination"); } _pagination = string.Empty; if (PageCount % 2 == 0) { throw new Exception("PageCount should just odd"); } int PageMax = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(DataCount) / Convert.ToDecimal(PageSize))); int PageIndex = CurrentPage + 1; StringBuilder _tempsb = new StringBuilder(); int pagestart = PageIndex - Convert.ToInt32(Math.Floor(PageCount / 2f)); int pageend = PageIndex + Convert.ToInt32(Math.Floor(PageCount / 2f)); if (PageMax < 0) { throw new Exception("PageMax less the 0"); } else if (PageMax <= 1) { _pagination = "<Pages Max=\"1\" Current=\"1\"><Page Index=\"1\" /></Pages>"; } else if (PageMax <= PageCount) { pagestart = 1; pageend = PageMax; } else { int temp = 0; if (pagestart < 1) { temp = 1 - pagestart; pagestart = 1; pageend += temp; } if (pageend > PageMax) { temp = pageend - PageMax; pageend = PageMax; pagestart -= temp; } if (pagestart < 1) { pagestart = 1; } } if (string.IsNullOrEmpty(_pagination)) { _tempsb.Append(string.Format("<Pages Max=\"{0}\" Current=\"{1}\">", PageMax, PageIndex)); for (int i = pagestart; i <= pageend; i++) { _tempsb.Append(string.Format("<Page Index=\"{0}\" />", i)); } _tempsb.Append("</Pages>"); _pagination = _tempsb.ToString(); } if (_type == PageDataType.Xml && !_pageable) { System.Xml.XPath.XPathNavigator _xPathNavigator = _dataXml.CreateNavigator(); System.Xml.XmlDocument _xmlDocument = new System.Xml.XmlDocument(); _xmlDocument.LoadXml(_xPathNavigator.OuterXml); _xPathNavigator = _xmlDocument.CreateNavigator(); _xPathNavigator.MoveToFirstChild(); _xPathNavigator.AppendChild(_pagination); _dataXml = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_xPathNavigator.OuterXml)); } _pageable = true; return _pagination; }
private void lnkImportPwdKey_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var openFileDialog = new OpenFileDialog(); openFileDialog.InitialDirectory = Path.GetDirectoryName(virtPackage.openedFile); openFileDialog.Multiselect = false; openFileDialog.Filter = "Password key (*.PasswordKey.xml)|*.PasswordKey.xml|All files (*.*)|*.*"; openFileDialog.DefaultExt = "PasswordKey.xml"; if (openFileDialog.ShowDialog() != DialogResult.OK) return; var xd = new System.Xml.XPath.XPathDocument(openFileDialog.FileName); var navigator = xd.CreateNavigator(); var iterator = navigator.Select("//Properties/Property"); int foundProps = 0; foreach (System.Xml.XPath.XPathNavigator n in iterator) { n.MoveToFirstAttribute(); var name = n.Name; var val = n.Value; if (name == "EncryptionPwdKey" || name == "EncryptionPwdHash" || name == "EncryptionPwdSalt" || name == "EncryptionPwdIV") { virtPackage.SetProperty(name, val); foundProps++; } } if (foundProps == 4) // All expected properties were found { tbEncryptionPwd.Text = tbEncryptionPwdConfirm.Text = "[UNCHANGED]"; MessageBox.Show("Password key imported."); } else { MessageBox.Show("No password key found in this file."); } }
void Window1_Loaded(object sender, RoutedEventArgs e) { // Arena.instance.VerticalAlignment = VerticalAlignment.Stretch;// .sca .RenderTransform = new ScaleTransform(1.5, 1.5); // Arena.instance.HorizontalAlignment = HorizontalAlignment.Stretch;// .sca .RenderTransform = new ScaleTransform(1.5, 1.5); System.Xml.XPath.XPathDocument GameData = new System.Xml.XPath.XPathDocument(".\\GameData.xml"); System.Xml.XPath.XPathNavigator GameDataNav = GameData.CreateNavigator(); Arena.instance.BankBalance = double.Parse(GameDataNav.SelectSingleNode("/GameData/StartingCash").ToString()); Arena.instance.Lifes = 20; //GameDataNav.MoveToRoot(); //System.Xml.XPath.XPathNodeIterator dx = GameDataNav.Select("/GameData/TowerTypes/RadiatorTowers/RadiatorTower"); System.Xml.XPath.XPathNodeIterator dx = GameDataNav.Select("/GameData/TowerTypes/*/*/@Name"); //"/GameData/TowerTypes/*/*/@Price" while (dx.MoveNext()) { string q = dx.Current.ToString(); ListBoxItem x = new ListBoxItem(); x.Content = q; System.Xml.XPath.XPathNavigator n = GameData.CreateNavigator(); System.Xml.XPath.XPathNavigator o = n.SelectSingleNode("/GameData/TowerTypes/*/*[@Name='" + q + "']"); TowerData PTD; if (o.Name == "ProjectileTower") { PTD = new ProjectileTowerData(o); } else if (o.Name == "RadiatorTower") { PTD = new HeatTowerData(o); } else if (o.Name == "BeamTower") { PTD = new BeamTowerData(o); } else { PTD = new TowerData(o); } x.Tag = PTD; Window1.instance.Towers.Items.Add(x); } }
private string DoTransform(string XML, string XSL, System.Xml.Xsl.XsltArgumentList Params) { try { System.Xml.Xsl.XslTransform oXsl = new System.Xml.Xsl.XslTransform(); oXsl.Load(XSL); XmlTextReader oXR = new XmlTextReader(XML, XmlNodeType.Document, null); System.Xml.XPath.XPathDocument oXml = new System.Xml.XPath.XPathDocument(oXR); XmlUrlResolver oResolver = new XmlUrlResolver(); System.Text.StringBuilder oSB = new System.Text.StringBuilder(); System.IO.StringWriter oWriter = new System.IO.StringWriter(oSB, null); oXsl.Transform(oXml, Params, oWriter, oResolver); oWriter.Close(); return oSB.ToString(); } catch (Exception ex) { throw ex; } }
public void Serialize (System.IO.TextWriter writer) { DoapNs doap = new DoapNs (); RdfNs rdf = new RdfNs (); FoafNs foaf = new FoafNs (); StringWriter sw = new StringWriter (); XmlTextWriter w = new XmlTextWriter (sw); string[] urltypes = new string[] { "homepage", "mailing-list", "download-page", "download-mirror", "wiki", "bug-database", "screenshots" }; string[] literaltypes = new string[] { "created", "os", "programming-language" }; string[] peopletypes = new string [] { "maintainer", "developer", "documenter", "translator", "tester", "helper" }; w.WriteStartDocument (); w.WriteStartElement (null, "content", null); foreach (Node proj in model.GetSources (rdf ["type"], doap ["Project"])) { w.WriteStartElement (null, "project", null); Node name = model.GetTarget (proj, doap ["name"]); w.WriteStartElement ("name"); w.WriteString (name.Literal); w.WriteEndElement (); Node description = model.GetTarget (proj, doap ["description"]); w.WriteStartElement ("description"); w.WriteStartAttribute ("xml", "lang", null); w.WriteString (description.Language); w.WriteEndAttribute (); w.WriteString (description.Literal); w.WriteEndElement (); Node shortdesc = model.GetTarget (proj, doap ["shortdesc"]); w.WriteStartElement ("shortdesc"); w.WriteStartAttribute ("xml", "lang", null); w.WriteString (shortdesc.Language); w.WriteEndAttribute (); w.WriteString (shortdesc.Literal); w.WriteEndElement (); foreach (string p in urltypes) { Node r = model.GetTarget (proj, doap [p]); if (r != null) { w.WriteStartElement (p); w.WriteStartAttribute (null, "href", null); w.WriteString (r.Uri.ToString ()); w.WriteEndElement (); } } foreach (string p in literaltypes) { foreach (Node r in model.GetTargets (proj, doap [p])) { w.WriteStartElement (p); w.WriteString (r.Literal); w.WriteEndElement (); } } foreach (string p in peopletypes) { foreach (Node r in model.GetTargets (proj, doap [p])) { w.WriteStartElement ("person"); w.WriteStartAttribute (null, "role", null); w.WriteString (p); w.WriteEndAttribute (); Node n = model.GetTarget (r, foaf ["name"]); Node hp = model.GetTarget (r, foaf ["homepage"]); w.WriteStartAttribute (null, "name", null); w.WriteString (n.Literal); w.WriteEndAttribute (); if (hp != null) { w.WriteStartAttribute (null, "homepage", null); w.WriteString (hp.Uri.ToString ()); w.WriteEndAttribute (); } w.WriteEndElement (); w.WriteEndElement (); } } w.WriteEndElement (); } w.WriteEndDocument (); // now do XML transform System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument (new XmlTextReader (new StringReader (sw.ToString ()))); style.Transform (doc, null, writer, null); }
public void handleAction_Xsl(string data, string xsltToUse) { //if (this.TmWebServices.tmAuthentication.sessionID. UserRole.ReadArticles var xstlFile = context.Server.MapPath("\\xslt\\" + xsltToUse); if (xstlFile.fileExists()) { var guid = tmWebServices.getGuidForMapping(data); if (guid != Guid.Empty) { var xmlContent = tmWebServices.XmlDatabase_GetGuidanceItemXml(guid); //.add_Xslt(xsltToUse); if (xmlContent.valid()) { //var xslTransform = new System.Xml.Xsl.XslTransform(); var xslTransform = new System.Xml.Xsl.XslCompiledTransform(); xslTransform.Load(xstlFile); var xmlReader = new System.Xml.XmlTextReader(new StringReader(xmlContent)); var xpathNavigator = new System.Xml.XPath.XPathDocument(xmlReader); var stringWriter = new StringWriter(); xslTransform.Transform(xpathNavigator, new System.Xml.Xsl.XsltArgumentList(), stringWriter); context.Response.ContentType = "text/html"; context.Response.Write(stringWriter.str()); var article = tmWebServices.GetGuidanceItemById(guid); switch(xsltToUse) { case "Notepad_Edit.xslt": tmWebServices.RBAC_Demand_EditArticles(); // will trigger an Security exception if the user if not authorized tmWebServices.logUserActivity("Edit Article (Notepad)", "{0} ({1})".format(article.Metadata.Title, guid)); break; case "TeamMentor_Article.xslt": tmWebServices.logUserActivity("View Article (xslt)", "{0} ({1})".format(article.Metadata.Title, guid)); break; case "JsCreole_Article.xslt": tmWebServices.logUserActivity("View Article (wiki)", "{0} ({1})".format(article.Metadata.Title, guid)); break; default: tmWebServices.logUserActivity("View Article ({0})", "{1} ({2})".format(xsltToUse, data,xsltToUse)); break; } endResponse(); } } else transfer_Request("articleViewer"); // will trigger exception } }
public XPathOperator(System.Xml.XPath.XPathDocument xPathDoc) { _XPathDoc = xPathDoc; }
/// <summary> /// Makes an authenticated web service call that returns XML data and returns the result as an XPathDocument. /// </summary> /// <param name="wsAddress">Address of web service with parameters to call.</param> /// <returns></returns> public System.Xml.XPath.XPathDocument GetAuthenticatedServiceXPathDocument(System.Uri wsAddress) { System.Xml.XPath.XPathDocument result = null; using (System.IO.Stream dataStream = GetAuthenticatedServiceStream(wsAddress)) { // Read result into a XPathDocument result = new System.Xml.XPath.XPathDocument(dataStream); } return result; }
public PageDataItem(string name, System.Xml.XPath.XPathDocument dataXml) { _type = PageDataType.Xml; _name = name; _dataXml = dataXml; }
/// <summary> /// Executes the logic for this workflow activity /// </summary> protected override void InternalExecute() { string catNetPath; if (string.IsNullOrEmpty(this.CatNetPath.Get(this.ActivityContext))) { string programFilePath = Environment.GetEnvironmentVariable("ProgramFiles"); if (string.IsNullOrEmpty(programFilePath)) { this.LogBuildError("Failed to read a value from the ProgramFiles Environment Variable"); return; } if (System.IO.File.Exists(programFilePath + @"\Microsoft\CAT.NET\CATNetCmd.exe")) { catNetPath = programFilePath + @"\Microsoft\CAT.NET\CATNetCmd.exe"; } else { this.LogBuildError(string.Format(CultureInfo.CurrentCulture, "CATNetCmd.exe was not found in the default location. Use CATNetCmd to specify it. Searched at: {0}", programFilePath + @"\Microsoft\CAT.NET\")); return; } } else { catNetPath = this.CatNetPath.Get(this.ActivityContext); } string arguments = string.Empty; if (!string.IsNullOrEmpty(this.AssemblyDirectory.Get(this.ActivityContext))) { arguments += string.Format("/file:\"{0}\"", this.AssemblyDirectory.Get(this.ActivityContext)); } if (!string.IsNullOrEmpty(this.ConfigDirectory.Get(this.ActivityContext))) { arguments += string.Format(" /configdir:\"{0}\"", this.ConfigDirectory.Get(this.ActivityContext)); } if (!string.IsNullOrEmpty(this.Rules.Get(this.ActivityContext))) { arguments += string.Format(" /rules:\"{0}\"", this.Rules.Get(this.ActivityContext)); } if (!string.IsNullOrEmpty(this.Report.Get(this.ActivityContext))) { arguments += string.Format(" /report:\"{0}\"", this.Report.Get(this.ActivityContext)); } if (!string.IsNullOrEmpty(this.ReportXsl.Get(this.ActivityContext))) { arguments += string.Format(" /reportxsl:\"{0}\"", this.ReportXsl.Get(this.ActivityContext)); } if (!string.IsNullOrEmpty(this.ReportXslOutput.Get(this.ActivityContext))) { arguments += string.Format(" /reportxsloutput:\"{0}\"", this.ReportXslOutput.Get(this.ActivityContext)); } if (this.Verbose.Get(this.ActivityContext)) { arguments += " /verbose"; } using (Process proc = new Process()) { proc.StartInfo.FileName = catNetPath; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.Arguments = arguments; this.LogBuildMessage(string.Format("Running {0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments)); proc.Start(); string outputStream = proc.StandardOutput.ReadToEnd(); if (outputStream.Length > 0) { this.LogBuildMessage("****************************************************"); this.LogBuildMessage("Cat.Net Scan Started."); this.LogBuildMessage("****************************************************"); this.LogBuildMessage(outputStream); } string errorStream = proc.StandardError.ReadToEnd(); if (errorStream.Length > 0) { this.LogBuildError(errorStream); } proc.WaitForExit(); if (proc.ExitCode != 0) { // note the command line not seem to return errorlevels under normal usage, even if parameters are mistyped this.LogBuildError(string.Format("CAT.NET analysis exited with errorcode {0}", proc.ExitCode.ToString(CultureInfo.CurrentCulture))); this.AnalysisFailed.Set(this.ActivityContext, true); return; } // check for the number of issues var document = new System.Xml.XPath.XPathDocument(this.Report.Get(this.ActivityContext)); var nav = document.CreateNavigator(); var issueCount = (double)nav.Evaluate("sum(/Report/Rules/Rule/TotalResults)"); // this xpath should return a double if (issueCount != 0) { // note the command line not seem to return errorlevels under normal usage, even if parameters are mistyped this.LogBuildError(string.Format("CAT.NET analysis reported {0} issues, see logfile for details", issueCount)); this.AnalysisFailed.Set(this.ActivityContext, true); return; } } this.LogBuildMessage("CAT.NET analysis completed and reported no issues.", BuildMessageImportance.High); }
/// <summary> /// Generates an object from its XML representation. /// </summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param> public override void ReadXml(System.Xml.XmlReader reader) { string fileId = reader.GetAttribute("FileID"); if (fileId == null) { base.ReadXml(reader); } else { var sourceSerializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(PackageSystem.PackageReference), null); m_packageFile = fileId; System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader); var nav = doc.CreateNavigator(); var iter = nav.SelectSingleNode("/FilePath/PackageReference"); if(iter == null) throw new XmlSchemaException(); m_packageSource = (IPackageReference)sourceSerializer.Deserialize(iter.ReadSubtree()); } }