public void Diagnosis_SDataCode_Should_Be_An_Enum_Test() { var diagnosis = new Diagnosis { SDataCode = DiagnosisCode.ApplicationDiagnosis, ApplicationCode = "Application error" }; string xml; using (var textWriter = new StringWriter()) using (var xmlWriter = new XmlTextWriter(textWriter)) { diagnosis.WriteTo(xmlWriter, null); xml = textWriter.ToString(); } XPathNavigator nav; using (var textReader = new StringReader(xml)) using (var xmlReader = new XmlTextReader(textReader)) { nav = new XPathDocument(xmlReader).CreateNavigator(); } var node = nav.SelectSingleNode("diagnosis/sdataCode"); Assert.IsNotNull(node); Assert.AreEqual("ApplicationDiagnosis", node.Value); node = nav.SelectSingleNode("diagnosis/applicationCode"); Assert.IsNotNull(node); Assert.AreEqual("Application error", node.Value); }
public void Write_Element_Then_Complex_Type_Then_List_Type_Test() { var schema = new SDataSchema("http://schemas.sage.com/crmErp/2008") { Types = { new SDataSchemaResourceType("tradingAccount") } }; XPathNavigator nav; using (var stream = new MemoryStream()) { schema.Write(stream); stream.Seek(0, SeekOrigin.Begin); #if NET_2_0 || NET_3_5 nav = new XPathDocument(stream).CreateNavigator(); #else nav = XDocument.Load(stream).CreateNavigator(); #endif } var mgr = new XmlNamespaceManager(nav.NameTable); mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); var resource = nav.SelectSingleNode("xs:schema/xs:element[@name='tradingAccount']", mgr); Assert.That(resource, Is.Not.Null); Assert.That(nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--type']", mgr), Is.Not.Null); Assert.That(nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--list']", mgr), Is.Not.Null); }
protected override IEnumerable <CommandResponse> Execute() { string[] args = this.Arguments.ToArray(); string username; if (args.Length > 0 && args[0] != string.Empty) { username = string.Join(" ", args); } else { username = this.User.Nickname; } var queryParameters = new NameValueCollection { { "action", "stats" }, { "user", username } }; Stream httpResponseData; try { httpResponseData = this.webServiceClient.DoApiCall( queryParameters, "https://accounts.wmflabs.org/api.php", this.botConfiguration.UserAgent); } catch (WebException e) { this.Logger.Warn("Error getting remote data", e); return(new[] { new CommandResponse { Message = e.Message } }); } var nav = new XPathDocument(httpResponseData).CreateNavigator(); var isMissing = nav.SelectSingleNode("//user/@missing") != null; if (isMissing) { return(this.responder.Respond("accountcreations.no-such-user", this.CommandSource, username)); } object[] messageParams = { username, // username nav.SelectSingleNode("//user/@status").Value, // accesslevel nav.SelectSingleNode("//user/@lastactive").Value, nav.SelectSingleNode("//user/@welcome_template").Value == string.Empty ? "disabled" : "enabled", nav.SelectSingleNode("//user/@onwikiname").Value }; return(this.responder.Respond("accountcreations.command.stats", this.CommandSource, messageParams)); }
public Definitions(string definitionFile) { using (XmlReader reader = XmlReader.Create(definitionFile)) { XPathNavigator navigator = new XPathDocument(reader).CreateNavigator(); bool caseSensitive = XmlConvert.ToBoolean(navigator.SelectSingleNode("/NxDSL-Defs").GetAttribute("caseSensitive", "")); XPathNodeIterator atomPatterns = navigator.SelectDescendants("AtomPattern", "", false); while (atomPatterns.MoveNext()) { XPathNavigator atomPattern = atomPatterns.Current; RegexOptions options = RegexOptions.Compiled; if (!caseSensitive) { options |= RegexOptions.IgnoreCase; } Regex regex = new Regex("^\\s*" + atomPattern.GetAttribute("regex", "") + "$", options); definitions.Add(regex, atomPattern.InnerXml); } } }
private void ValidateSetup() { using (var stringReader = new StringReader(new TTransform().XmlContent)) using (var xmlReader = XmlReader.Create(stringReader, new XmlReaderSettings { XmlResolver = null })) { var navigator = new XPathDocument(xmlReader).CreateNavigator(); var output = navigator.SelectSingleNode("/xsl:stylesheet/xsl:output/@method", navigator.GetNamespaceManager().AddNamespaces <TTransform>()); if (output != null && !output.Value.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException($"Transform produces a {output.Value} output and not an XML one."); } } switch (ContentProcessing) { case XmlSchemaContentProcessing.None: case XmlSchemaContentProcessing.Skip: break; case XmlSchemaContentProcessing.Lax: case XmlSchemaContentProcessing.Strict: if (!Schemas.Any()) { throw new InvalidOperationException("At least one XML Schema to which the output must conform to must be setup."); } break; } }
public void Write_Tracking_Test() { var tracking = new Tracking { Phase = "Archiving FY 2007", PhaseDetail = "Compressing file archive.dat", Progress = 12M, ElapsedSeconds = 95M, RemainingSeconds = 568M, PollingMillis = 500 }; XPathNavigator nav; using (var stream = new MemoryStream()) { new XmlContentHandler().WriteTo(tracking, stream); stream.Seek(0, SeekOrigin.Begin); #if NET_2_0 || NET_3_5 nav = new XPathDocument(stream).CreateNavigator(); #else nav = XDocument.Load(stream).CreateNavigator(); #endif } var mgr = new XmlNamespaceManager(nav.NameTable); mgr.AddNamespace("sdata", "http://schemas.sage.com/sdata/2008/1"); var node = nav.SelectSingleNode("sdata:tracking", mgr); Assert.That(node, Is.Not.Null); Assert.That(node.SelectSingleNode("sdata:phase", mgr).Value, Is.EqualTo("Archiving FY 2007")); Assert.That(node.SelectSingleNode("sdata:phaseDetail", mgr).Value, Is.EqualTo("Compressing file archive.dat")); Assert.That(node.SelectSingleNode("sdata:progress", mgr).Value, Is.EqualTo("12")); Assert.That(node.SelectSingleNode("sdata:elapsedSeconds", mgr).Value, Is.EqualTo("95")); Assert.That(node.SelectSingleNode("sdata:remainingSeconds", mgr).Value, Is.EqualTo("568")); Assert.That(node.SelectSingleNode("sdata:pollingMillis", mgr).Value, Is.EqualTo("500")); }
public void dlLinks_ItemCommand(object source, DataListCommandEventArgs e) { string mode = e.CommandName; string id = e.CommandArgument.ToString(); if (mode == "Delete") { EditXml(mode, id); } else //Editing { ViewState["EditMode"] = mode; XPathNavigator nav = new XPathDocument(_XmlPath).CreateNavigator(); nav.MoveToFirstChild(); XPathNavigator node = nav.SelectSingleNode("link[@id='" + id + "']"); if (node != null) { this.lblID.Text = id; this.txtName.Text = node.GetAttribute("name", String.Empty); this.txtURL.Text = node.GetAttribute("href", String.Empty); } else { this.lblOutput.Text = "Unable to find node."; } } }
private string GetAdfsSAMLTokenWinAuth() { // makes a seurity token request to the corporate ADFS proxy integrated auth endpoint. // If the user is logged on to a machine joined to the corporate domain with her Windows credentials and connected // to the corporate network Kerberos automatically takes care of authenticating the security token // request to ADFS. // The logon token is used to talk to MSO STS to get an O365 service token that can then be used to sign into SPO. string samlAssertion = null; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(this.adfsIntegratedAuthUrl); request.UseDefaultCredentials = true; // use the default credentials so Kerberos can take care of authenticating our request byte[] responseData = HttpHelper.SendHttpRequest( this.adfsIntegratedAuthUrl, "GET", null, "text/html; charset=utf-8", request); if (responseData != null) { try { StreamReader sr = new StreamReader(new MemoryStream(responseData), Encoding.GetEncoding("utf-8")); XPathNavigator nav = new XPathDocument(sr).CreateNavigator(); XPathNavigator wresult = nav.SelectSingleNode("/html/body/form/input[@name='wresult']"); if (wresult != null) { string RequestSecurityTokenResponseText = wresult.GetAttribute("value", ""); sr = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(RequestSecurityTokenResponseText))); nav = new XPathDocument(sr).CreateNavigator(); XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); nsMgr.AddNamespace("t", "http://schemas.xmlsoap.org/ws/2005/02/trust"); XPathNavigator requestedSecurityToken = nav.SelectSingleNode("//t:RequestedSecurityToken", nsMgr); // Ensure whitespace is reserved XmlDocument doc = new XmlDocument(); doc.LoadXml(requestedSecurityToken.InnerXml); doc.PreserveWhitespace = true; samlAssertion = doc.InnerXml; } } catch { // we failed to sign the user using integrated Windows Auth } } return(samlAssertion); }
public XmlReader GetRegistryItemsForCriteria(int registryId, int startRow, int pageSize, params string[] searchCriteria) { StringBuilder sbXpath = new StringBuilder(); IDataReader idr = DatabaseFactory.CreateDatabase().ExecuteReader("Rejestry.pobierzDaneRejestru", registryId); if (!idr.Read()) { return(null); } string definicja = idr["definicja"].ToString(); idr.Close(); XPathNavigator xpnDef = new XPathDocument(new StringReader(definicja)).CreateNavigator(); XPathNodeIterator xpiDef = xpnDef.Select("/definicjaRejestru/wyszukiwanie/kryterium"); sbXpath.Append("/pozycje/pozycja"); while (xpiDef.MoveNext()) { if (searchCriteria[xpiDef.CurrentPosition - 1].Length > 0) { if (sbXpath.Length > 16) { sbXpath.Append(" and "); } else { sbXpath.Append("["); } sbXpath.AppendFormat(xpiDef.Current.SelectSingleNode("@xpath").Value, String.Format("\"{0}\"", searchCriteria[xpiDef.CurrentPosition - 1])); } } if (sbXpath.Length > 16) { sbXpath.Append("]"); } string xpathExpression = sbXpath.ToString(); int totalRows; XPathNavigator xpn = new XPathDocument(GetRegistryItems(new Guid(Membership.GetUser().ProviderUserKey.ToString()), registryId, startRow, pageSize, out totalRows)).CreateNavigator(); XPathNodeIterator xpi = xpn.Select(xpathExpression); StringBuilder sbOut = new StringBuilder(); sbOut.Append("<pozycje>"); sbOut.Append(xpnDef.SelectSingleNode("/definicjaRejestru/pola").OuterXml);//dodane aby byla spojna struktura xml-a while (xpi.MoveNext()) { sbOut.Append(xpi.Current.OuterXml); } sbOut.Append("</pozycje>"); return(XmlReader.Create(new StringReader(sbOut.ToString()))); // zamykany }
/// <summary> /// A navigator from an Xml and XPath /// </summary> /// <param name="xml"></param> /// <param name="xpath"></param> /// <returns></returns> private XPathNavigator FromXPath(string xml, string xpath) { var nav = new XPathDocument( new StringReader(xml) ).CreateNavigator(); var nsm = NamespacesOfDom(xml); return(nav.SelectSingleNode(xpath, nsm)); }
public void ProcessInstructions(KissTransactionMode mode) { string path, branchId; byte[] sdData; XPathNavigator instruction; StandingData standingData; var filter = new List <string>(); var neighborhood = new Neighborhood(_sql); var neighborhoodClients = neighborhood.GetAllClients().ToArray(); foreach (var id in StandingData.RetrieveInstructionAll(_sql)) { using (var sr = new StringReader(StandingData.RetrieveInstruction(_sql, long.Parse(id)))) { instruction = new XPathDocument(sr).CreateNavigator(); path = instruction.SelectSingleNode("//StandingData/@Path").Value; branchId = instruction.SelectSingleNode("//StandingData/@BranchId").Value; Array.Sort(neighborhoodClients); foreach (XPathNavigator clientId in instruction.Select("//Client/@Id")) { if (Array.BinarySearch(neighborhoodClients, clientId.Value) >= 0) { filter.Add(clientId.Value); } } if (branchId == neighborhood.GetLocalBranch() && filter.Count > 0) { sdData = DownloadStandingData(path); standingData = new StandingData(_sql, long.Parse(id), _msmqCapacity, sdData); standingData.Distribute(mode, filter.ToArray()); } } } }
private void ValidateSetup() { using (var sr = new StringReader(new TTransform().XmlContent)) { var navigator = new XPathDocument(sr).CreateNavigator(); var output = navigator.SelectSingleNode("/xsl:stylesheet/xsl:output/@method", navigator.GetNamespaceManager().AddNamespaces <TTransform>()); if (output != null && output.Value.Equals("xml", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("Transform produces an XML output and not a text one."); } } }
private string GetAdfsSAMLTokenUsernamePassword() { // makes a seurity token request to the corporate ADFS proxy usernamemixed endpoint using // the user's corporate credentials. The logon token is used to talk to MSO STS to get // an O365 service token that can then be used to sign into SPO. string samlAssertion = null; // the corporate ADFS proxy endpoint that issues SAML seurity tokens given username/password credentials string stsUsernameMixedUrl = String.Format("https://{0}/adfs/services/trust/2005/usernamemixed/", adfsAuthUrl.Host); // generate the WS-Trust security token request SOAP message passing in the user's corporate credentials // and the site we want access to. We send the token request to the corporate ADFS proxy usernamemixed endpoint. byte[] requestBody = Encoding.UTF8.GetBytes(ParameterizeSoapRequestTokenMsgWithUsernamePassword( "urn:federation:MicrosoftOnline", // we are requesting a logon token to talk to the Microsoft Federation Gateway this.username, this.password, stsUsernameMixedUrl)); try { Uri stsUrl = new Uri(stsUsernameMixedUrl); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(stsUrl); byte[] responseData = HttpHelper.SendHttpRequest( stsUrl, "POST", requestBody, "application/soap+xml; charset=utf-8", request, null); if (responseData != null) { StreamReader sr = new StreamReader(new MemoryStream(responseData), Encoding.GetEncoding("utf-8")); XPathNavigator nav = new XPathDocument(sr).CreateNavigator(); XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); nsMgr.AddNamespace("t", "http://schemas.xmlsoap.org/ws/2005/02/trust"); XPathNavigator requestedSecurityToken = nav.SelectSingleNode("//t:RequestedSecurityToken", nsMgr); // Ensure whitespace is reserved XmlDocument doc = new XmlDocument(); doc.LoadXml(requestedSecurityToken.InnerXml); doc.PreserveWhitespace = true; samlAssertion = doc.InnerXml; } } catch { // we failed to sign the user using corporate credentials } return(samlAssertion); }
/// <summary> /// Starts a Kalonline Server, with following actions /// - Configure NHibernate (ORM) /// - Load Maps /// - Start ClientHandling thread /// </summary> public Server() { /// /// Load Server Config /// if (File.Exists("Config.xml")) { XPathNavigator config = new XPathDocument("Config.xml").CreateNavigator(); PORT = Int32.Parse(config.SelectSingleNode("config/port").Value); } else { ServerConsole.WriteLine(Color.Red, "Could not find Config.xml, aborting startup."); return; } /// /// Configure NHibernate /// ServerConsole.WriteLine(Color.Blue, "- [Configuring Database]"); Configuration cfg = new Configuration(); cfg.AddAssembly("Emulator"); Factory = cfg.BuildSessionFactory(); /// /// Load Maps /// ServerConsole.WriteLine(Color.Blue, "- [Loading Maps]"); World.LoadMaps(); /// /// Load NPCs /// ServerConsole.WriteLine(Color.Blue, "- [Loading NPCs]"); World.LoadNPCs(); if (World.done) { /// /// Start the server /// processConnectionsThread = new Thread( new ThreadStart(Server.ProcessConnections) ); processConnectionsThread.Start(); ServerThinker.Start(); ServerConsole.WriteLine("Server Started"); } }
private void MessengerOnMessageReceived(string sender, string message) { Logger.LogNotice($"Message received from '{sender}': {message}"); try { using (var reader = new StringReader(message)) { var nav = new XPathDocument(reader).CreateNavigator(); var peerUri = nav.SelectSingleNode(PeerIdExpr)?.Value; var note = nav.SelectSingleNode(NoteExpr)?.Value ?? string.Empty; var statusName = nav.SelectSingleNode(StatusNameExpr)?.LocalName; if (statusName == null) { throw new InvalidOperationException("StatusName is not provided cannot be parsed"); } if (peerUri == null || PeerRegex.Match(peerUri).Groups["peerId"].Value != PluginManager.Core.Sip.Account.UserName) { throw new InvalidOperationException("Peer URI is not provided or cannot be parsed"); } if (_criteriaFunc(statusName)) { PluginManager.ExecuteAction(_targetActionCode, _targetPluginId, note); } } } catch (InvalidOperationException e) { Logger.LogWarn(e, "Required data missing"); } catch (Exception e) { Logger.LogWarn(e, "Unable to parse message as Presence/XML"); } }
public void Write_Enum_Schema_Types_Support_List_Types_Test() { var schema = new SDataSchema { Types = { new SDataSchemaEnumType("test") { BaseType = XmlTypeCode.String, ListName = "test--list", ListItemName = "test" } } }; XPathNavigator nav; using (var stream = new MemoryStream()) { schema.Write(stream); stream.Seek(0, SeekOrigin.Begin); #if NET_2_0 || NET_3_5 nav = new XPathDocument(stream).CreateNavigator(); #else nav = XDocument.Load(stream).CreateNavigator(); #endif } var mgr = new XmlNamespaceManager(nav.NameTable); mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); var type = nav.SelectSingleNode("xs:schema/xs:simpleType[@name='test--enum']", mgr); Assume.That(type, Is.Not.Null); var list = nav.SelectSingleNode("xs:schema/xs:complexType[@name='test--list']", mgr); Assert.That(list, Is.Not.Null); Assert.That(list.SelectSingleNode("xs:sequence/xs:element[@name='test']", mgr), Is.Not.Null); }
public static void Read(string filepath, ProjectManager projects, ReferenceTable references, IdTable ids) { var xml = new XPathDocument(filepath).CreateNavigator(); var project = new Project(); var pnode = xml.SelectSingleNode("/Project"); ids[project] = new Guid(pnode.GetAttribute("id", "")); AssignProperties(pnode, project, references); references.Update(ids); // force Project.Property assignment var aci = pnode.Select("Assignments/FlatAssignmentCollection"); while (aci.MoveNext()) { var acnode = aci.Current; var flatid = acnode.SelectSingleNode("Flat").Value; var collection = project.Assignments.First(ac => ids[ac.Flat].ToString() == flatid); ids[collection] = new Guid(acnode.GetAttribute("id", "")); AssignProperties(acnode, collection, references); var ai = acnode.Select("FlatAssignment"); while (ai.MoveNext()) { var anode = ai.Current; var a = new FlatAssignment(project); ids[a] = new Guid(anode.GetAttribute("id", "")); AssignProperties(anode, a, references); collection.Add(a); } } references.Update(ids); // force Assignments for CostOptions generation var ci = pnode.Select("Costs/Cost"); while (ci.MoveNext()) { var cnode = ci.Current; var c = project.CreateCost(); ids[c] = new Guid(cnode.GetAttribute("id", "")); AssignProperties(cnode, c, references); var oi = cnode.Select("Options/CostOptions"); while (oi.MoveNext()) { var onode = oi.Current; var lesseeid = onode.SelectSingleNode("Lessee").Value; var option = c.Options.First(o => ids[o.Lessee].ToString() == lesseeid); ids[option] = new Guid(onode.GetAttribute("id", "")); AssignProperties(onode, option, references); } } projects.Add(project); }
protected virtual void ConfirmResult(BusinessRulesBase rules, JArray addresses) { foreach (JToken address in addresses) { if (((string)(address["components"]["country"])) == "US") { // try enhancing address by verifying it with USPS var serialNo = ((string)(ApplicationServicesBase.Settings("server.geocoding.usps.serialNo"))); var userName = ((string)(ApplicationServicesBase.Settings("server.geocoding.usps.userName"))); var password = ((string)(ApplicationServicesBase.Settings("server.geocoding.usps.password"))); var address1 = ((string)(address["address1"])); if (!(string.IsNullOrEmpty(userName)) && !(string.IsNullOrEmpty(address1))) { var uspsRequest = new StringBuilder("<VERIFYADDRESS><COMMAND>ZIP1</COMMAND>"); uspsRequest.AppendFormat("<SERIALNO>{0}</SERIALNO>", serialNo); uspsRequest.AppendFormat("<USER>{0}</USER>", userName); uspsRequest.AppendFormat("<PASSWORD>{0}</PASSWORD>", password); uspsRequest.Append("<ADDRESS0></ADDRESS0>"); uspsRequest.AppendFormat("<ADDRESS1>{0}</ADDRESS1>", address1); uspsRequest.AppendFormat("<ADDRESS2>{0}</ADDRESS2>", address["address2"]); uspsRequest.AppendFormat("<ADDRESS3>{0},{1},{2}</ADDRESS3>", address["city"], address["region"], address["postalcode"]); uspsRequest.Append("</VERIFYADDRESS>"); using (var client = new WebClient()) { var uspsResponseText = client.DownloadString(("http://www.dial-a-zip.com/XML-Dial-A-ZIP/DAZService.asmx/MethodZIPValidate?input=" + "" + HttpUtility.UrlEncode(uspsRequest.ToString()))); var uspsResponse = new XPathDocument(new StringReader(uspsResponseText)).CreateNavigator().SelectSingleNode("/Dial-A-ZIP_Response"); if (uspsResponse != null) { address["address1"] = uspsResponse.SelectSingleNode("AddrLine1").Value; address["address2"] = uspsResponse.SelectSingleNode("AddrLine2").Value; address["city"] = uspsResponse.SelectSingleNode("City").Value; address["region"] = uspsResponse.SelectSingleNode("State").Value; address["postalcode"] = (uspsResponse.SelectSingleNode("ZIP5").Value + ("-" + uspsResponse.SelectSingleNode("Plus4").Value)); address["components"]["postalcode"] = uspsResponse.SelectSingleNode("ZIP5").Value; address["components"]["postalcodesuffix"] = uspsResponse.SelectSingleNode("Plus4").Value; address["country"] = address["country"].ToString().ToUpper(); } } } } } }
public void Scan(string path, IdTable ids) { foreach (var filepath in Directory.EnumerateFiles(path, "*.xml")) { var xml = new XPathDocument(filepath).CreateNavigator(); var node = xml.SelectSingleNode("/Project"); if (node != null) { var project = new Project(); var refs = new ReferenceTable(); Xml.AssignProperties(node, project, refs); refs.Update(ids); var timespan = project.StartDate.ToShortDateString() + " bis " + project.StartDate.AddYears(1).ToShortDateString(); Add(new ProjectInfo(project.Name, project.Property.Name, timespan, filepath)); } } }
private void ProcessWorker1ResponseQueueMessage(IModel channel, BasicDeliverEventArgs ea) { XPathNavigator navResponse = null; using (MemoryStream ms = new MemoryStream(ea.Body)) { navResponse = new XPathDocument(ms).CreateNavigator(); } Guid jobId = Guid.Parse(ea.BasicProperties.CorrelationId); JobA job = null; job = m_jobs_JobA.Where(j => j.JobId == jobId).FirstOrDefault(); if (null == job) { m_log.WarnFormat("Received a Worker1 response for an unrecognized job, job_id: {0}. Ignoring...", jobId); return; } if (JobAState.Done == job.State) { m_log.WarnFormat("Received a Worker1 response for a completed job, job_id: {0}. Ignoring...", jobId); return; } // Get status from Worker1 response message bool status = bool.Parse(navResponse.SelectSingleNode("/job/status").Value); switch (status) { case false: job.Fire(JobATrigger.Worker1Error); break; case true: job.Fire(JobATrigger.Worker1Complete); break; } // Acknowledge the message was processed channel.BasicAck( deliveryTag: ea.DeliveryTag, multiple: false); }
public void Write_Unknown_Test() { const string xml = @"<dummy/>"; XPathNavigator nav; using (var stream = new MemoryStream()) { new XmlContentHandler().WriteTo(xml, stream); stream.Seek(0, SeekOrigin.Begin); #if NET_2_0 || NET_3_5 nav = new XPathDocument(stream).CreateNavigator(); #else nav = XDocument.Load(stream).CreateNavigator(); #endif } var node = nav.SelectSingleNode("dummy"); Assert.That(node, Is.Not.Null); Assert.That(node.IsEmptyElement, Is.True); }
private bool ValidApplication() { /* http://api.geonames.org/timezone?lat=-34.60&lng=-58.38&username=consulgroup*/ // CLAVE CSX343GSDG var httpWebRequest = (HttpWebRequest)WebRequest.Create(" http://api.geonames.org/timezone?lat=-34.60&lng=-58.38&username=consulgroup"); httpWebRequest.UserAgent = ".NET Framework Test Client"; httpWebRequest.Accept = "text/html"; httpWebRequest.Method = "GET"; //this is the default behavior // execute the request var response = (HttpWebResponse)httpWebRequest.GetResponse(); // we will read data via the response stream var resStream = response.GetResponseStream(); var date = String.Empty; using (var reader = new StreamReader(resStream, Encoding.UTF8)) { var nav = new XPathDocument(reader).CreateNavigator(); date = nav.SelectSingleNode("//time").InnerXml.Split(' ')[0].Replace("-", "").Substring(0, 6); // date = reader.ReadToEnd().Substring(0, 7).Replace("-", ""); } if (date != DateTime.Now.ToString("yyyyMM")) { return(false); } var keys = ConfigurationManager.AppSettings["KEY"]; var today = DateTime.Now.ToString("yyyyMM"); var operador = ConfigurationManager.AppSettings["Operador"]; var hashedKey = GetHashString(today + operador); // TODO: Validar con web service de hora. if (!keys.Contains(hashedKey)) { return(false); } return(true); }
/* * Format of request queue message: * <job job_id="{GUID}"> * <pauseForSeconds>{numberOfSecondsToDoWork}</pauseForSeconds> * </job> * * Format of response queue message: * <job job_id="{GUID}"> * <status>{bool: 0: false, 1: true}</status> * </job> */ internal static JobA FromQueueMessage(IModel channel, byte[] messageBody) { XPathNavigator nav = null; using (MemoryStream ms = new MemoryStream(messageBody)) { nav = new XPathDocument(ms).CreateNavigator(); } JobA job = new JobA(); job.Channel = channel; job.State = JobAState.Begin; job.JobXml = nav.InnerXml; job.JobId = Guid.NewGuid(); job.StartTime = DateTime.UtcNow; job.NumSecondsToWork = int.Parse(nav.SelectSingleNode("/job/pauseForSeconds").Value); job.FullPathAndFilenameToSerializedJob = Path.Combine( Environment.CurrentDirectory, "serialized-jobs", job.JobId.ToString() + ".xml"); return(job); }
public void Write_Properties_Without_Types_Specified_Test() { var schema = new SDataSchema("http://schemas.sage.com/crmErp/2008") { Types = { new SDataSchemaComplexType("tradingAccount") { Properties = { new SDataSchemaValueProperty("active") } } } }; XPathNavigator nav; using (var stream = new MemoryStream()) { schema.Write(stream); stream.Seek(0, SeekOrigin.Begin); #if NET_2_0 || NET_3_5 nav = new XPathDocument(stream).CreateNavigator(); #else nav = XDocument.Load(stream).CreateNavigator(); #endif } var mgr = new XmlNamespaceManager(nav.NameTable); mgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); var resource = nav.SelectSingleNode("xs:schema/xs:complexType[@name='tradingAccount--type']", mgr); Assert.That(resource, Is.Not.Null); Assert.That(resource.Select("xs:all/xs:element", mgr).Count, Is.EqualTo(1)); var property = resource.SelectSingleNode("xs:all/xs:element", mgr); Assert.That(property, Is.Not.Null); Assert.That(property.SelectSingleNode("@name").Value, Is.EqualTo("active")); Assert.That(property.SelectSingleNode("@type"), Is.Null); }
public string Invoke(string xmlDocument, string xpath, string expectedValue) { using (var reader = new MemoryStream(Encoding.UTF8.GetBytes(xmlDocument))) { try { var navigation = new XPathDocument(reader).CreateNavigator(); var value = navigation.SelectSingleNode(xpath).Value; if (value != expectedValue) { throw new AssertionException(value, expectedValue, WebDrivers.Default); } } catch (XmlException e) { throw new XmlParseException(xmlDocument, e.Message); } } return("true"); }
private void GetMessages() { ConnectionFactory factory = new ConnectionFactory(); factory.HostName = RabbitMQConfig.HOSTNAME; factory.VirtualHost = RabbitMQConfig.VIRTUAL_HOST; factory.UserName = RabbitMQConfig.USERNAME; factory.Password = RabbitMQConfig.PASSWORD; // In the event of network connection failure, // attempt network recovery every 5 seconds factory.AutomaticRecoveryEnabled = false; //factory.NetworkRecoveryInterval = TimeSpan.FromSeconds(5); while (true) { try { using (IConnection connection = factory.CreateConnection()) using (IModel channel = connection.CreateModel()) { channel.QueueDeclare( queue: RabbitMQConfig.WORKER1_REQUEST_QUEUE_NAME, durable: true, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos( prefetchCount: 1, prefetchSize: 0, global: false); QueueingBasicConsumer consumer = new QueueingBasicConsumer(channel); channel.BasicConsume(RabbitMQConfig.WORKER1_REQUEST_QUEUE_NAME, false, consumer); while (connection != null && connection.IsOpen && channel != null && channel.IsOpen) { m_log.Debug("Waiting for messages..."); BasicDeliverEventArgs ea = null; if (consumer.Queue.Dequeue(int.Parse(RabbitMQConfig.QUEUE_TIMEOUT), out ea)) { // Parse message int numSecondsToWork = 0; Guid jobId = Guid.Empty; XPathNavigator nav = null; using (MemoryStream ms = new MemoryStream(ea.Body)) { nav = new XPathDocument(ms).CreateNavigator(); jobId = Guid.Parse(nav.SelectSingleNode("/job/@job_id").Value); numSecondsToWork = int.Parse(nav.SelectSingleNode("/job/pauseForSeconds").Value); m_log.DebugFormat("Received message, job_id: {0}, workForSeconds: {1}.", jobId.ToString(), numSecondsToWork); } // Do work and get success status bool isWorkSuccess = DoWork(jobId, numSecondsToWork); // Send status message to reply-to address with success/failure of work SendResponseMessage(channel, ea.BasicProperties.ReplyToAddress, ea.BasicProperties.CorrelationId, jobId, isWorkSuccess); // Acknowledge request message - all work has been successfully completed channel.BasicAck(ea.DeliveryTag, false); m_log.Debug("Sent request message acknowledgement."); } } consumer = null; } } catch (RabbitMQ.Client.Exceptions.BrokerUnreachableException) { m_log.Error("Could not connect to the message queue service. Will attempt to connect indefinitely..."); Thread.Sleep(2000); } catch (Exception ex) { if (ex is EndOfStreamException || ex is RabbitMQ.Client.Exceptions.OperationInterruptedException) { m_log.Error("Connection to the message queue service was lost."); } else { m_log.Error(ex); } } } }
private SamlSecurityToken GetMsoStsSAMLToken() { // Makes a request that conforms with the WS-Trust standard to // Microsoft Online Services Security Token Service to get a SAML // security token back so we can then use it to sign the user to SPO SamlSecurityToken samlST = new SamlSecurityToken(); byte[] saml11RTBytes = null; string logonToken = null; // find out whether the user's domain is a federated domain this.adfsAuthUrl = GetAdfsAuthUrl(); // get logon token using windows integrated auth when the user is connected to the corporate network if (this.adfsAuthUrl != null && this.useIntegratedWindowsAuth) { UriBuilder ub = new UriBuilder(); ub.Scheme = this.adfsAuthUrl.Scheme; ub.Host = this.adfsAuthUrl.Host; ub.Path = string.Format("{0}auth/integrated/", this.adfsAuthUrl.LocalPath); // specify in the query string we want a logon token to present to the Microsoft Federation Gateway // for the corresponding user ub.Query = String.Format("{0}&wa=wsignin1.0&wtrealm=urn:federation:MicrosoftOnline", this.adfsAuthUrl.Query.Remove(0, 1)). Replace("&username="******"&username={0}", this.username)); this.adfsIntegratedAuthUrl = ub.Uri; // get the logon token from the corporate ADFS using Windows Integrated Auth logonToken = GetAdfsSAMLTokenWinAuth(); if (!string.IsNullOrEmpty(logonToken)) { // generate the WS-Trust security token request SOAP message passing in the logon token we got from the corporate ADFS // and the site we want access to saml11RTBytes = Encoding.UTF8.GetBytes(ParameterizeSoapRequestTokenMsgWithAssertion( this.spSiteUrl.ToString(), logonToken, msoStsUrl)); } } // get logon token using the user's corporate credentials. Likely when not connected to the corporate network if (logonToken == null && this.adfsAuthUrl != null && !string.IsNullOrEmpty(password)) { logonToken = GetAdfsSAMLTokenUsernamePassword(); // get the logon token from the corporate ADFS proxy usernamemixed enpoint if (logonToken != null) { // generate the WS-Trust security token request SOAP message passing in the logon token we got from the corporate ADFS // and the site we want access to saml11RTBytes = Encoding.UTF8.GetBytes(ParameterizeSoapRequestTokenMsgWithAssertion( this.spSiteUrl.ToString(), logonToken, msoStsUrl)); } } if (logonToken == null && this.adfsAuthUrl == null && !string.IsNullOrEmpty(password)) // login with O365 credentials. Not a federated login. { // generate the WS-Trust security token request SOAP message passing in the user's credentials and the site we want access to saml11RTBytes = Encoding.UTF8.GetBytes(ParameterizeSoapRequestTokenMsgWithUsernamePassword( this.spSiteUrl.ToString(), this.username, this.password, msoStsUrl)); } if (saml11RTBytes != null) { Uri MsoSTSUri = new Uri(msoStsUrl); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(MsoSTSUri); byte[] responseData = HttpHelper.SendHttpRequest( MsoSTSUri, "POST", saml11RTBytes, "application/soap+xml; charset=utf-8", request, null); StreamReader sr = new StreamReader(new MemoryStream(responseData), Encoding.GetEncoding("utf-8")); XPathNavigator nav = new XPathDocument(sr).CreateNavigator(); XmlNamespaceManager nsMgr = new XmlNamespaceManager(nav.NameTable); nsMgr.AddNamespace("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); XPathNavigator binarySecurityToken = nav.SelectSingleNode("//wsse:BinarySecurityToken", nsMgr); if (binarySecurityToken != null) { string binaryST = binarySecurityToken.InnerXml; nsMgr.AddNamespace("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); XPathNavigator expires = nav.SelectSingleNode("//wsu:Expires", nsMgr); if (!String.IsNullOrEmpty(binarySecurityToken.InnerXml) && !String.IsNullOrEmpty(expires.InnerXml)) { samlST.Token = Encoding.UTF8.GetBytes(binarySecurityToken.InnerXml); samlST.Expires = DateTime.Parse(expires.InnerXml); } } else { // We didn't get security token } } return(samlST); }
// Methods public static int Main(string[] args) { XPathDocument document; ConsoleApplication.WriteBanner(); OptionCollection options = new OptionCollection { new SwitchOption("?", "Show this help page."), new StringOption("config", "Specify a configuration file.", "versionCatalog"), new StringOption("out", "Specify an output file containing version information.", "outputFile"), new BooleanOption("rip", "Specify whether to rip old APIs which are not supported by the " + "latest versions.") }; ParseArgumentsResult result = options.ParseArguments(args); if (result.Options["?"].IsPresent) { Console.WriteLine("VersionBuilder [options]"); options.WriteOptionSummary(Console.Out); return(0); } if (!result.Success) { result.WriteParseErrors(Console.Out); return(1); } if (result.UnusedArguments.Count != 0) { Console.WriteLine("No non-option arguments are supported."); return(1); } if (!result.Options["config"].IsPresent) { ConsoleApplication.WriteMessage(LogLevel.Error, "You must specify a version catalog file."); return(1); } bool rip = true; if (result.Options["rip"].IsPresent && !((bool)result.Options["rip"].Value)) { rip = false; } string uri = (string)result.Options["config"].Value; try { document = new XPathDocument(uri); } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while accessing the version catalog file '{0}'. The error message " + "is: {1}", uri, ioEx.Message)); return(1); } catch (XmlException xmlEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "The version catalog file '{0}' is not well-formed. The error message is: {1}", uri, xmlEx.Message)); return(1); } XPathNavigator navigator = document.CreateNavigator().SelectSingleNode("versions"); XPathExpression expr = XPathExpression.Compile("string(ancestor::versions/@name)"); List <VersionInfo> allVersions = new List <VersionInfo>(); List <string> latestVersions = new List <string>(); foreach (XPathNavigator navigator2 in document.CreateNavigator().Select("versions//version[@file]")) { string group = (string)navigator2.Evaluate(expr); string attribute = navigator2.GetAttribute("name", String.Empty); if (string.IsNullOrEmpty(attribute)) { ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a name attribute."); } string name = navigator2.GetAttribute("file", String.Empty); if (String.IsNullOrEmpty(attribute)) { ConsoleApplication.WriteMessage(LogLevel.Error, "Every version element must have a file attribute."); } name = Environment.ExpandEnvironmentVariables(name); VersionInfo item = new VersionInfo(attribute, group, name); allVersions.Add(item); } string str5 = String.Empty; foreach (VersionInfo info2 in allVersions) { if (info2.Group != str5) { latestVersions.Add(info2.Name); str5 = info2.Group; } } if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } XmlReaderSettings settings = new XmlReaderSettings { IgnoreWhitespace = true }; XmlWriterSettings settings2 = new XmlWriterSettings { Indent = true }; Dictionary <string, List <KeyValuePair <string, string> > > versionIndex = new Dictionary <string, List <KeyValuePair <string, string> > >(); Dictionary <string, Dictionary <string, ElementInfo> > dictionary2 = new Dictionary <string, Dictionary <string, ElementInfo> >(); XPathExpression expression2 = XPathExpression.Compile("string(/api/@id)"); XPathExpression expression4 = XPathExpression.Compile("/api/elements/element"); XPathExpression expression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.ObsoleteAttribute']]"); XPathExpression extensionAttributeExpression = XPathExpression.Compile("/api/attributes/attribute[type[@api='T:System.Runtime.CompilerServices.ExtensionAttribute']]"); XPathExpression extensionFirstParameterExpression = XPathExpression.Compile("/api/parameters/parameter[1]/*"); XPathExpression specialization = XPathExpression.Compile("./specialization"); XPathExpression templates = XPathExpression.Compile("./template[boolean(@index) and starts-with(@api, 'M:')]"); XPathExpression skipFirstParam = XPathExpression.Compile("./parameter[position()>1]"); XPathExpression expression6 = XPathExpression.Compile("boolean(argument[type[@api='T:System.Boolean'] and value[.='True']])"); XPathExpression apiChild = XPathExpression.Compile("./api"); foreach (VersionInfo info3 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Indexing version '{0}' using file '{1}'.", info3.Name, info3.File)); try { XmlReader reader = XmlReader.Create(info3.File, settings); try { reader.MoveToContent(); while (reader.Read()) { if ((reader.NodeType == XmlNodeType.Element) && (reader.LocalName == "api")) { string key = String.Empty; List <KeyValuePair <string, string> > list3 = null; string str7 = String.Empty; Dictionary <string, ElementInfo> dictionary3 = null; XmlReader reader2 = reader.ReadSubtree(); XPathNavigator navigator3 = new XPathDocument(reader2).CreateNavigator(); key = (string)navigator3.Evaluate(expression2); if (!versionIndex.TryGetValue(key, out list3)) { list3 = new List <KeyValuePair <string, string> >(); versionIndex.Add(key, list3); } if (!dictionary2.TryGetValue(key, out dictionary3)) { dictionary3 = new Dictionary <string, ElementInfo>(); dictionary2.Add(key, dictionary3); } foreach (XPathNavigator navigator4 in navigator3.Select(expression4)) { ElementInfo info4; string str8 = navigator4.GetAttribute("api", String.Empty); if (!dictionary3.TryGetValue(str8, out info4)) { XPathNavigator elementNode = null; if ((navigator4.SelectSingleNode("*") != null) || (navigator4.SelectChildren(XPathNodeType.Attribute).Count > 1)) { elementNode = navigator4; } info4 = new ElementInfo(info3.Group, info3.Name, elementNode); dictionary3.Add(str8, info4); continue; } if (!info4.Versions.ContainsKey(info3.Group)) { info4.Versions.Add(info3.Group, info3.Name); } } XPathNavigator navigator6 = navigator3.SelectSingleNode(expression); if (navigator6 != null) { str7 = ((bool)navigator6.Evaluate(expression6)) ? "error" : "warning"; } if (key.StartsWith("M:", StringComparison.Ordinal)) { // Only check for extension methods when this is actually a method in question var navigator7 = navigator3.SelectSingleNode(extensionAttributeExpression); if (navigator7 != null) { // Check first parameter var navigator8 = navigator3.SelectSingleNode(extensionFirstParameterExpression); if (navigator8 != null) { // Get type node var typeID = navigator8.GetAttribute("api", String.Empty); if (navigator8.LocalName == "type") { var specNode = navigator8.SelectSingleNode(specialization); if (specNode == null || specNode.SelectChildren(XPathNodeType.Element).Count == specNode.Select(templates).Count) { // Either non-generic type or all type parameters are from within this method Dictionary <String, XPathNavigator> extMethods; if (!extensionMethods.TryGetValue(typeID, out extMethods)) { extMethods = new Dictionary <String, XPathNavigator>(); extensionMethods.Add(typeID, extMethods); } if (!extMethods.ContainsKey(key)) { extMethods.Add(key, navigator3.SelectSingleNode(apiChild)); } } } else { // TODO extension methods for generic parameters... } } } } list3.Add(new KeyValuePair <string, string>(info3.Name, str7)); str7 = String.Empty; reader2.Close(); } } } finally { reader.Close(); } continue; } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "An error occurred while accessing the input file '{0}'. The error message is: {1}", info3.File, ioEx.Message)); return(1); } catch (XmlException xmlEx) { ConsoleApplication.WriteMessage(LogLevel.Error, String.Format(CultureInfo.CurrentCulture, "The input file '{0}' is not well-formed. The error message is: {1}", info3.File, xmlEx.Message)); return(1); } } if (rip) { RemoveOldApis(versionIndex, latestVersions); } ConsoleApplication.WriteMessage(LogLevel.Info, String.Format(CultureInfo.CurrentCulture, "Indexed {0} entities in {1} versions.", versionIndex.Count, allVersions.Count)); try { XmlWriter writer; if (result.Options["out"].IsPresent) { writer = XmlWriter.Create((string)result.Options["out"].Value, settings2); } else { writer = XmlWriter.Create(Console.Out, settings2); } try { writer.WriteStartDocument(); writer.WriteStartElement("reflection"); writer.WriteStartElement("assemblies"); Dictionary <string, object> dictionary4 = new Dictionary <string, object>(); foreach (VersionInfo info5 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } using (XmlReader reader3 = XmlReader.Create(info5.File, settings)) { reader3.MoveToContent(); while (reader3.Read()) { if ((reader3.NodeType == XmlNodeType.Element) && (reader3.LocalName == "assembly")) { string str9 = reader3.GetAttribute("name"); if (!dictionary4.ContainsKey(str9)) { XmlReader reader4 = reader3.ReadSubtree(); writer.WriteNode(reader4, false); reader4.Close(); dictionary4.Add(str9, null); } } } } } writer.WriteEndElement(); writer.WriteStartElement("apis"); var readElements = new HashSet <String>(); foreach (VersionInfo info6 in allVersions) { if (Cancel) { ConsoleApplication.WriteMessage(LogLevel.Info, "VersionBuilder canceled"); return(1); } XmlReader reader5 = XmlReader.Create(info6.File, settings); reader5.MoveToContent(); while (reader5.Read()) { if ((reader5.NodeType == XmlNodeType.Element) && (reader5.LocalName == "api")) { string str10 = reader5.GetAttribute("id"); if (versionIndex.ContainsKey(str10)) { List <KeyValuePair <string, string> > versions = versionIndex[str10]; KeyValuePair <string, string> pair = versions[0]; if (info6.Name == pair.Key) { writer.WriteStartElement("api"); writer.WriteAttributeString("id", str10); XmlReader reader6 = reader5.ReadSubtree(); reader6.MoveToContent(); reader6.ReadStartElement(); Dictionary <String, XPathNavigator> eElems; var hasExtensionMethods = extensionMethods.TryGetValue(str10, out eElems); if (hasExtensionMethods) { readElements.Clear(); readElements.UnionWith(extensionMethods[str10].Keys); } while (!reader6.EOF) { if ((reader6.NodeType == XmlNodeType.Element) && (reader6.LocalName == "elements")) { Dictionary <string, ElementInfo> dictionary5 = dictionary2[str10]; Dictionary <string, object> dictionary6 = new Dictionary <string, object>(); writer.WriteStartElement("elements"); XmlReader reader7 = reader6.ReadSubtree(); foreach (XPathNavigator navigator8 in new XPathDocument(reader7).CreateNavigator().Select("elements/element")) { string str11 = navigator8.GetAttribute("api", String.Empty); dictionary6[str11] = null; writer.WriteStartElement("element"); writer.WriteAttributeString("api", str11); if (hasExtensionMethods) { readElements.Remove(str11); } foreach (string str12 in dictionary5[str11].Versions.Keys) { writer.WriteAttributeString(str12, dictionary5[str11].Versions[str12]); } foreach (XPathNavigator navigator9 in navigator8.Select("@*")) { if (navigator9.LocalName != "api") { writer.WriteAttributeString(navigator9.LocalName, navigator9.Value); } } foreach (XPathNavigator navigator10 in navigator8.Select("*")) { writer.WriteNode(navigator10, false); } writer.WriteEndElement(); } reader7.Close(); if (dictionary6.Count != dictionary5.Count) { foreach (string str13 in dictionary5.Keys) { if (dictionary6.ContainsKey(str13) || (rip && !IsLatestElement(dictionary5[str13].Versions.Values, latestVersions))) { continue; } writer.WriteStartElement("element"); writer.WriteAttributeString("api", str13); if (hasExtensionMethods) { readElements.Remove(str13); } foreach (string str14 in dictionary5[str13].Versions.Keys) { writer.WriteAttributeString(str14, dictionary5[str13].Versions[str14]); } if (dictionary5[str13].ElementNode != null) { foreach (XPathNavigator navigator11 in dictionary5[str13].ElementNode.Select("@*")) { if (navigator11.LocalName != "api") { writer.WriteAttributeString(navigator11.LocalName, navigator11.Value); } } foreach (XPathNavigator navigator12 in dictionary5[str13].ElementNode.Select("*")) { writer.WriteNode(navigator12, false); } } writer.WriteEndElement(); } } if (hasExtensionMethods) { foreach (var eMethodID in readElements) { writer.WriteStartElement("element"); writer.WriteAttributeString("api", eMethodID); writer.WriteAttributeString("source", "extension"); foreach (XPathNavigator extMember in eElems[eMethodID].SelectChildren(XPathNodeType.Element)) { switch (extMember.LocalName) { case "apidata": writer.WriteStartElement("apidata"); foreach (XPathNavigator apidataAttr in extMember.Select("@*")) { writer.WriteAttributeString(apidataAttr.LocalName, apidataAttr.Value); } writer.WriteAttributeString("subsubgroup", "extension"); foreach (XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute)) { writer.WriteNode(child, false); } writer.WriteEndElement(); break; case "parameters": var noParamsWritten = true; foreach (XPathNavigator eParam in extMember.Select(skipFirstParam)) { if (noParamsWritten) { writer.WriteStartElement("parameters"); noParamsWritten = false; } writer.WriteNode(eParam, false); } if (!noParamsWritten) { writer.WriteEndElement(); } break; case "memberdata": writer.WriteStartElement("memberdata"); foreach (XPathNavigator mDataAttr in extMember.Select("@*")) { if (mDataAttr.LocalName != "static") { writer.WriteAttributeString(mDataAttr.LocalName, mDataAttr.Value); } } foreach (XPathNavigator child in extMember.SelectChildren(XPathNodeType.All & ~XPathNodeType.Attribute)) { writer.WriteNode(child, false); } writer.WriteEndElement(); break; case "attributes": break; default: writer.WriteNode(extMember, false); break; } } writer.WriteEndElement(); } } writer.WriteEndElement(); reader6.Read(); } else if (reader6.NodeType == XmlNodeType.Element) { writer.WriteNode(reader6, false); } else { reader6.Read(); } } reader6.Close(); writer.WriteStartElement("versions"); foreach (XPathNavigator navigator13 in navigator.SelectChildren(XPathNodeType.Element)) { WriteVersionTree(versions, navigator13, writer); } writer.WriteEndElement(); writer.WriteEndElement(); } } } } reader5.Close(); } writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); } finally { writer.Close(); } } catch (IOException ioEx) { ConsoleApplication.WriteMessage(LogLevel.Error, "An error occurred while generating the " + "output file. The error message is: {0}", ioEx.Message); return(1); } return(0); }
/// <inheritdoc /> public override void Apply(XmlDocument document, string key) { currentKey = key; XPathNavigator targetDoc = document.CreateNavigator(); foreach (CopySet copySet in copySets) { XPathExpression targetExpression = copySet.GetTargetExpression(targetDoc, key); // get the target nodes in the document XPathNavigator targetNode = targetDoc.SelectSingleNode(targetExpression); while (targetNode != null) { string targetId = targetNode.Value; int pound = (String.IsNullOrEmpty(targetId)) ? -1 : targetId.IndexOf('#'); string bkeyword = (pound == -1) ? "" : targetId.Substring(pound + 1); if (bkeyword.Length == 0) { base.WriteMessage(key, MessageLevel.Warn, "Invalid id '{0}' in topic '{1}'.", targetId, currentKey); // delete this target and get the next target node targetNode.DeleteSelf(); targetNode = targetDoc.SelectSingleNode(targetExpression); continue; } List <string> idList; if (!bKeywordMap.TryGetValue(bkeyword, out idList)) { base.WriteMessage(key, MessageLevel.Warn, "B-keyword not found '{0}' in topic '{1}'.", targetId, currentKey); // delete this target and get the next target node targetNode.DeleteSelf(); targetNode = targetDoc.SelectSingleNode(targetExpression); continue; } if (idList.Count > 1) { Console.Write(""); } // create a 'tasks' node to replace the target XPathNavigator tasksNode = document.CreateElement("tasks").CreateNavigator(); tasksNode.CreateAttribute(string.Empty, "bkeyword", string.Empty, bkeyword); foreach (string topicId in idList) { //create a task node for this source topic XPathNavigator taskNode = document.CreateElement("task").CreateNavigator(); taskNode.CreateAttribute(string.Empty, "topicId", string.Empty, topicId); // get the source document for the topic id string filepath; if (!index.TryGetValue(topicId, out filepath)) { base.WriteMessage(key, MessageLevel.Warn, "No file found for topicId '{0}' for " + "B-keyword '{1}'. Source topic: '{2}'.", topicId, bkeyword, currentKey); continue; } XPathNavigator sourceDoc = new XPathDocument(filepath).CreateNavigator(); XPathNavigator sourceNode = sourceDoc.SelectSingleNode(valueQuery); if (sourceNode == null) { continue; } XPathNodeIterator sources = sourceNode.Select(copySet.SourceExpression); // append the source nodes to the target node if (sources.Count > 0) { foreach (XPathNavigator source in sources) { taskNode.AppendChild(source); } } tasksNode.AppendChild(taskNode); } targetNode.ReplaceSelf(tasksNode); // get the next target node targetNode = targetDoc.SelectSingleNode(targetExpression); } } }
protected override Dictionary <string, (Cipher cipher, byte[] data)> GetSessionKeys(ZipFile zipFile, string originalFilePath) { XPathNavigator navigator; using (var s = new MemoryStream()) { zipFile["META-INF/rights.xml"].Extract(s); s.Seek(0, SeekOrigin.Begin); navigator = new XPathDocument(s).CreateNavigator(); } var nsm = new XmlNamespaceManager(navigator.NameTable); nsm.AddNamespace("a", "http://ns.adobe.com/adept"); nsm.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#"); var node = navigator.SelectSingleNode("//a:encryptedKey[1]", nsm); if (node == null) { throw new InvalidOperationException("Can't find session key."); } var base64Key = node.Value; var contentKey = Convert.FromBase64String(base64Key); var possibleKeys = new List <byte[]>(); foreach (var masterKey in MasterKeys) { var rsa = GetRsaEngine(masterKey); var bookkey = rsa.ProcessBlock(contentKey, 0, contentKey.Length); //Padded as per RSAES-PKCS1-v1_5 if (bookkey[bookkey.Length - 17] == 0x00) { possibleKeys.Add(bookkey.Copy(bookkey.Length - 16)); } } if (possibleKeys.Count == 0) { throw new InvalidOperationException("Problem decrypting session key"); } using (var s = new MemoryStream()) { zipFile["META-INF/encryption.xml"].Extract(s); s.Seek(0, SeekOrigin.Begin); navigator = new XPathDocument(s).CreateNavigator(); } var contentLinks = navigator.Select("//e:EncryptedData", nsm); var result = new Dictionary <string, (Cipher cipher, byte[] data)>(contentLinks.Count); foreach (XPathNavigator link in contentLinks) { var em = link.SelectSingleNode("./e:EncryptionMethod/@Algorithm", nsm).Value; var path = link.SelectSingleNode("./e:CipherData/e:CipherReference/@URI", nsm).Value; var cipher = GetCipher(em); if (cipher == Cipher.Unknown) { throw new InvalidOperationException("This ebook is using unsupported encryption method: " + em); } result[path] = (cipher, possibleKeys[0]);