public void Load(String fromPath) { var xmlDocument = new XmlDocument(); xmlDocument.Load(fromPath); loadFile = xmlDocument.ToXDocument(); Practice.ClearCurrent(); PreloadAllEntityGroups(); LoadPracticeSettings(); LoadSlides(); LoadObjects(); LoadActions(); }
private static void Insert() { string url = "http://www.moneytrackin.com/api/rest/insertTransaction?project=&description=lorem+ipsum&amount=-123&date=2013-04-20&tags=food"; bool success = false; string errorMessage = String.Empty; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Headers.Add("Authorization", "Basic yourkeygoeshere"); try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { string xmlResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { xmlResponse = reader.ReadToEnd(); } var doc = new XmlDocument(); doc.LoadXml(xmlResponse); var xdoc = doc.ToXDocument(); var code = (string)xdoc.Root.Attribute("code"); var query = from c in xdoc.Descendants("error") select new { ErrorMessage = (string)c.Value }; success = code.ToLower() == "done"; errorMessage = query.FirstOrDefault() != null ? query.FirstOrDefault().ErrorMessage : "Undefined error."; } //_logger.InfoFormat("Sent email for request commitment ID {0}", commitment.Id); } catch (WebException ex) { //_logger.Error(String.Format("Email for request commitment ID {0} could not be sent.", commitment.Id), ex); success = false; } Console.WriteLine("Success: {0}. Error Message: {1}", success, errorMessage); }
public XmlDocument UpdateMessageForProductionGateway(XmlDocument govTalkMessage) { var xd = govTalkMessage.ToXDocument(); var ns = XNamespace.Get("http://www.govtalk.gov.uk/CM/envelope"); if (xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTimestamp") != null) xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTimestamp").Remove(); if (xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTest") != null) xd.Element(ns + "GovTalkMessage").Element(ns + "Header").Element(ns + "MessageDetails").Element(ns + "GatewayTest").Remove(); govTalkMessage = xd.ToXmlDocument(); return govTalkMessage; }
public XmlDocument UpdateMessageForLocalTest(XmlDocument govtalkmessage) { #region DontDoThis // DeSerialize XmlDocument govTalkMessage // Change properties // Serialize GovTalkMessage //GovTalkMessage govTalkMessage = XmlSerializationHelpers.DeserializeMessage(govtalkmessage); //govTalkMessage.Header.MessageDetails.GatewayTest = "1"; //govTalkMessage.Header.MessageDetails.GatewayTimestampSpecified = true; //govTalkMessage.Header.MessageDetails.GatewayTimestamp = DateTime.Now; // OK, so using this method to re-serialize specifically adds the \t whitespace // Therefore possibly making any previously added IRmark incorrect. // Avoid deserializing Body here ... // govtalkmessage = XmlSerializationHelpers.SerializeGovTalkMessage(govTalkMessage); #endregion DontDoThis // XmlDocument to XDocument // Add the elements // XDocument to XmlDocument XNamespace GovTalk = "http://www.govtalk.gov.uk/CM/envelope"; XElement GatewayTest = new XElement(GovTalk + "GatewayTest", "1"); XElement GatewayTimestamp = new XElement(GovTalk + "GatewayTimestamp", DateTime.Now); XmlDocument ModifiedGovTalkMessage = new XmlDocument(); ModifiedGovTalkMessage.PreserveWhitespace = true; XDocument InProcessXDocument = govtalkmessage.ToXDocument(); InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest); InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTimestamp); ModifiedGovTalkMessage = InProcessXDocument.ToXmlDocument(); return ModifiedGovTalkMessage; }
public XmlDocument UpdateMessageForDevGatewayTest(XmlDocument govtalkmessage) { XNamespace GovTalk = "http://www.govtalk.gov.uk/CM/envelope"; XElement GatewayTest = new XElement(GovTalk + "GatewayTest", "1"); XmlDocument ModifiedGovTalkMessage = new XmlDocument(); ModifiedGovTalkMessage.PreserveWhitespace = true; XDocument InProcessXDocument = govtalkmessage.ToXDocument(); if (InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest") == null) InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest); else if (InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest").Value == "0") { InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Element(GovTalk + "GatewayTest").Remove(); InProcessXDocument.Root.Element(GovTalk + "Header").Element(GovTalk + "MessageDetails").Add(GatewayTest); } ModifiedGovTalkMessage = InProcessXDocument.ToXmlDocument(); return ModifiedGovTalkMessage; }
static void TestReadListResponse() { IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository(); loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService()); LogProviderContext.Current = loggingService; string filename = @"C:\Temp\LocalDataRequestMessage_2014_10_16_10_33_50.xml"; XmlDocument listResponse = new XmlDocument(); listResponse.Load(filename); IMessageReader reader = new DefaultMessageReader(loggingService, configurationRepository, listResponse.ToXDocument()); reader.ReadMessage(); string[] results = reader.GetMessageResults<string[]>(); string qualifier = reader.GetQualifier(); string function = reader.GetFunction(); DataTable listResults = reader.GetMessageResults<DataTable>(); GovTalkMessage message = reader.Message(); Console.WriteLine("Message from {0}", message.Header.MessageDetails.ResponseEndPoint.Value.ToString()); }
/// <summary> /// Demonstrate using the message reader strategies to get results from a message reply /// </summary> /// <param name="loggingService"></param> /// <param name="messageToRead"></param> static void DemonstrateReadMessage(ILoggingService loggingService, XmlDocument messageToRead) { // Set up a message reading strategy IMessageReader messageReader = new DefaultMessageReader(loggingService, configurationRepository, messageToRead.ToXDocument()); messageReader.ReadMessage(); // We don't know what we've got back from the Gateway, but all replies are GovTalkMessages if(messageReader.HasErrors()) { //There are errors in the results file so we can deal with them // Get a DataTable of the results and have a look at that DataTable errorTable = messageReader.GetMessageResults<DataTable>(); // Or set up an error return strategy and do something with that IErrorReturnCalculator errorCalculator = new DefaultErrorReturnCalculator(); GovTalkMessageGovTalkDetailsError error = messageReader.GetMessageResults<GovTalkMessageGovTalkDetailsError>(); Console.WriteLine(errorCalculator.CalculateErrorReturn(error)); if(error.Number == "3001") { ErrorResponse errResponse = messageReader.GetMessageResults<ErrorResponse>(); } } else { // It's either an acknowledgement so we need to get the poll interval and URL, or a response. string[] results = messageReader.GetMessageResults<string[]>(); foreach(var result in results) { Console.WriteLine(result); } if(messageReader.GetQualifier() == "response") { string body = messageReader.GetBodyType(); if(body != null) { DataTable responseTable = messageReader.GetMessageResults<DataTable>(); LocalHelp.ConsolePrintDataTable(responseTable); } else { Console.WriteLine("No body content"); } } } GovTalkMessageFileName ReplyNamer = new GovTalkMessageFileName.FileNameBuilder() .AddLogger(loggingService) .AddConfigurationRepository(configurationRepository) .AddMessageIntention("ReplyMessage") .AddCorrelationId(messageReader.GetCorrelationId()) .AddFilePath(@"C:\Temp\") .BuildFileName(); string replyFileName = ReplyNamer.ToString(); messageToRead.Save(replyFileName); }
public static void TestReadSuccessResponse() { IConfigurationRepository configurationRepository = new ConfigFileConfigurationRepository(); ILoggingService loggingService = new Log4NetLoggingService(configurationRepository, new ThreadContextService()); XmlDocument successResponse = new XmlDocument(); successResponse.Load(@"C:\Temp\success_response_78503626913182048.xml"); ReadResponseStrategy reader = new ReadResponseStrategy(loggingService, configurationRepository); if (reader.IsMatch(successResponse.ToXDocument())) { SuccessResponse success = reader.GetBody<SuccessResponse>(); } }
internal virtual XDocument ConvertXmlDocumentToXDocument(XmlDocument xmlDocument) { XDocument xDoc = null; try { xDoc = xmlDocument.ToXDocument(); if (xDoc.Root == null) { return null; } } catch (Exception ex) { Log.Error(ex); } return xDoc; }
/// <summary> /// 根据Xml元素重新加载结点 /// </summary> /// <param name="desPos">结点坐标</param> /// <param name="xmlStr">xml字符串</param> public void LoadNode(Coord desPos, string xmlStr) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xmlStr); XElement xmlNode = xmlDocument.ToXDocument().Root; ElementNode node = ElementNode.GetNode(xmlNode); CopyNode(node, desPos); }
public IEnumerable<Transacction> GetTransactions(DateTime from, DateTime to) { // get settings from config file // make request to mtrackin's api // convert request to IEnumerable<Transacction> and return it. string url = String.Format("http://www.moneytrackin.com/api/rest/listTransactions?project=&startDate={0:yyyy-MM-dd}&endDate={1:yyyy-MM-dd}", from, to); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Headers.Add("Authorization", String.Format("Basic {0}", ConfigurationManager.AppSettings["ApiAuthorizationKey"])); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { string xmlResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { xmlResponse = reader.ReadToEnd(); xmlResponse = xmlResponse.Replace("result", "transactions"); } var doc = new XmlDocument(); doc.LoadXml(xmlResponse); var xdoc = doc.ToXDocument(); var query = from c in xdoc.Descendants("transaction") select new Transacction { ID = (long)c.Attribute("id"), Description = (string)c.Element("description"), Date = (DateTime)c.Element("date"), Amount = (decimal)c.Element("amount"), Tags = c.Descendants("tags").Select(x => x.Element("tag").Value).ToList() }; return query.ToList(); } }
/// <summary> /// Получаем контент сообщения об ошибке /// </summary> /// <param name="doc"></param> /// <returns>Информацию об ошибке</returns> public VKErrorInfo GetErrorContent(XmlDocument doc) { XDocument xDoc = doc.ToXDocument(); if (xDoc != null) { VKErrorInfo errors = new VKErrorInfo(); errors.ErrorCode = Convert.ToInt32(xDoc.Element("error").Element("error_code").Value); errors.ErrorMessage = xDoc.Element("error").Element("error_msg").Value; errors.ErrorParams = (from item in xDoc.Element("error").Element("request_params").Elements() where item.Name == "param" select new VKErrorParams() { Key = item.Element("key").Value, Value = item.Element("value").Value }).ToList(); return errors; } return null; }
public static void Main() { XmlDocument doc = new XmlDocument(); string filename = "../../catalog.xml"; doc.Load(filename); XmlNodeList nodes = LoadNodesStandard(doc); //XmlNodeList nodes = LoadNodesUsingXPath(doc); Console.WriteLine(value: "Album artists:"); Console.WriteLine(new string(c: '=', count: 40)); RenderAlbumArtists(nodes); // Remove expensive albums IEnumerable<XmlNode> expensiveAlbums = from XmlNode node in nodes where int.Parse(node["price"].InnerText) > 20 select node; foreach (XmlNode album in expensiveAlbums) { doc.DocumentElement.RemoveChild(album); } doc.Save(filename); Console.WriteLine(value: "\nAfter removal of expensive albums:"); Console.WriteLine(new string(c: '=', count: 40)); RenderAlbumArtists(LoadNodesUsingXPath(doc)); // Album songs Console.WriteLine(value: "\nAlbum songs:"); Console.WriteLine(new string(c: '=', count: 40)); using (XmlReader reader = XmlReader.Create(filename)) { while (reader.Read()) { if (reader.Name == "title") { Console.WriteLine(reader.ReadInnerXml()); } } } // Album songs using LINQ Console.WriteLine(value: "\nAlbum songs using LINQ:"); Console.WriteLine(new string(c: '=', count: 40)); IEnumerable<string> titles = from XmlNode node in nodes from XmlNode x in node["songs"] select x["title"].InnerText; foreach (var title in titles) { Console.WriteLine(title); } // Read person.txt and create person.xml string[] personData = File.ReadAllText(path: "../../person.txt").Split(separator: new char[] { '\n' }); var root = new XElement(name: "person", content: new object[] { new XElement(name: "name", content: personData[0]), new XElement(name: "address", content: personData[1]), new XElement(name: "phone", content: personData[2]) }); using (XmlWriter writer = XmlWriter.Create(outputFileName: "../../person.xml")) { root.WriteTo(writer); } Console.WriteLine(value: "\nperson.xml created successfully:"); Console.WriteLine(new string(c: '=', count: 40)); // Write to albums.xml var totalAlbums = new XElement("albums"); using (XmlReader reader = XmlReader.Create(filename)) { using (XmlWriter writer = XmlWriter.Create(outputFileName: "../../albums.xml")) { while (reader.Read()) { if (reader.Name == "album") { XmlNode albumNode = doc.ReadNode(reader); totalAlbums.Add(new XElement(name: "album", content: new object[] { new object[] { new XElement(name: "name", content: albumNode["name"].InnerText), new XElement(name: "artist", content: albumNode["artist"].InnerText) } })); } } totalAlbums.WriteTo(writer); } } Console.WriteLine(value: "\nalbums.xml created - filtered the albums info"); Console.WriteLine(new string(c: '=', count: 40)); // Iterate through the project dir var dirPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\..\\..\\"); var projectRoot = new XElement(name: "dir", content: new object[] { new XAttribute(name: "type", value: "root"), new XAttribute(name: "name", value: dirPath.Name) }); XElement result = WalkDirectoryTree(dirPath, root); using (XmlWriter writer = XmlWriter.Create(outputFileName: "../../directories.xml")) { result.WriteTo(writer); } Console.WriteLine(value: "\ndirectories.xml created - iterated through project dir"); Console.WriteLine(new string(c: '=', count: 40)); // Extract albums prices < 5 years ago Console.WriteLine(value: "\nAlbums prices < 5 years ago using xPath"); Console.WriteLine(new string(c: '=', count: 40)); XmlNodeList albums = LoadNodesUsingXPath(doc); int currentYear = DateTime.Now.Year; foreach (XmlNode node in albums) { if (currentYear - int.Parse(node["year"].InnerText) <= 5) { Console.WriteLine($"{node["name"].InnerText} - {node["year"].InnerText}"); } } Console.WriteLine(value: "\nAlbums prices < 5 years ago using LINQ"); Console.WriteLine(new string(c: '=', count: 40)); (from XmlNode node in doc.DocumentElement.ChildNodes where currentYear - int.Parse(node["year"].InnerText) <= 5 select node) .ToList() .ForEach((n) => Console.WriteLine($"{n["name"].InnerText} - {n["year"].InnerText}")); // Apply xslt styles var transformer = new XslCompiledTransform(); transformer.Load(stylesheetUri: "../../catalog.xslt"); transformer.Transform(filename, resultsFile: "../../catalog.html"); Console.WriteLine(value: "\ncatalog.html created - XSLT styles applied"); Console.WriteLine(new string(c: '=', count: 40)); // xsd against xml validation Console.WriteLine(value: "\nxsd against xml validation"); Console.WriteLine(new string(c: '=', count: 40)); string xsdMarkup = File.ReadAllText(path: "../../catalog.xsd"); var schemas = new XmlSchemaSet(); schemas.Add(targetNamespace: "", schemaDocument: XmlReader.Create(new StringReader(xsdMarkup))); Console.WriteLine(value: "Validating catalog.xml"); bool error = false; doc.ToXDocument().Validate(schemas, (o, e) => { Console.WriteLine(format: "{0}", arg0: e.Message); error = true; }); Console.WriteLine(error ? "not successful" : "successful"); Console.WriteLine(value: "Validating an empty xml document"); error = false; new XDocument( new XElement(name: "Root", content: new object[] { new XElement(name: "Child1", content: "content1"), new XElement(name: "Child2", content: "content2") })) .Validate(schemas, (o, e) => { Console.WriteLine(format: "{0}", arg0: e.Message); error = true; }); Console.WriteLine(error ? "not successful" : "successful"); }
/// <summary> /// Reads gpx data from the stream, parses it, and saves to the data store for the specified user. /// </summary> /// <param name="inputStream"> /// The input stream. /// </param> /// <param name="fileName"> /// The file name. /// </param> /// <param name="forceName"> /// If parameter is false, the program will try to extract the name from the uploaded file. Otherwise it will use the value from fileName parameter. /// </param> /// <returns> /// True if the opreation completed successfully. False otherwise. /// </returns> public bool ImportRoute(Stream inputStream, string fileName, bool forceName) { int result; var xDocument = new XmlDocument(); using (var xReader = new StreamReader(inputStream)) { xDocument.Load(xReader); var newRoute = _xmlParser.ConvertXmlDocumentToRoute(xDocument.ToXDocument(), forceName); if (forceName) { newRoute.Name = fileName; } else if (newRoute.Name == null) { newRoute.Name = fileName; } newRoute.UserId = _userId; result = _routesRepository.Save(newRoute); } return result > -1; }
public static void TestDecompressMessage(XmlDocument compressedXmlDocument) { string contents = CommonUtilityHelper.DecompressData(compressedXmlDocument.XmlToBytes()); XmlDocument decompressedDocument = new XmlDocument(); decompressedDocument.LoadXml(contents); DefaultMessageReader reader = new DefaultMessageReader(loggingService, configurationRepository, decompressedDocument.ToXDocument()); string[] results = reader.GetMessageResults<string[]>(); Console.WriteLine(reader.GetQualifier()); }
private static void Run() { string url = "http://www.moneytrackin.com/api/rest/listTransactions?project=&startDate=2011-11-01&endDate=2011-11-30"; bool success = false; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Headers.Add("Authorization", "Basic yourkeygoeshere"); try { using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { success = response.StatusCode == HttpStatusCode.OK; string xmlResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { xmlResponse = reader.ReadToEnd(); xmlResponse = xmlResponse.Replace("result", "transactions"); } var doc = new XmlDocument(); doc.LoadXml(xmlResponse); var xdoc = doc.ToXDocument(); var query = from c in xdoc.Descendants("transaction") select new Transacction { ID = (long)c.Attribute("id"), Description = (string)c.Element("description"), Date = (DateTime)c.Element("date"), Amount = (decimal)c.Element("amount"), Tags = c.Descendants("tags").Select(x => x.Element("tag").Value).ToList() }; } //_logger.InfoFormat("Sent email for request commitment ID {0}", commitment.Id); } catch (WebException ex) { //_logger.Error(String.Format("Email for request commitment ID {0} could not be sent.", commitment.Id), ex); success = false; } }
public bool DeleteTransaction(long transactionID, out string errorMessage) { string url = String.Format("http://www.moneytrackin.com/api/rest/deleteTransaction?transactionID={0}", transactionID); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; request.Headers.Add("Authorization", String.Format("Basic {0}", ConfigurationManager.AppSettings["ApiAuthorizationKey"])); bool success = false; errorMessage = null; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { string xmlResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { xmlResponse = reader.ReadToEnd(); } var doc = new XmlDocument(); doc.LoadXml(xmlResponse); var xdoc = doc.ToXDocument(); var code = (string)xdoc.Root.Attribute("code"); var query = from c in xdoc.Descendants("error") select new { ErrorMessage = (string)c.Value }; success = code.ToLower() == "done"; errorMessage = query.FirstOrDefault() != null ? query.FirstOrDefault().ErrorMessage : "Undefined error."; } return success; }