Search Results

Search found 314 results on 13 pages for 'xmldocument'.

Page 3/13 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Creating an XmlNode/XmlElement in C# without an XmlDocument?

    - by Michael Stum
    I have a simple class that essentially just holds some values. I have overridden the ToString() method to return a nice string representation. Now, I want to create a ToXml() method, that will return something like this: <Song> <Artist>Bla</Artist> <Title>Foo</Title> </Song> Of course, I could just use a StringBuilder here, but I would like to return an XmlNode or XmlElement, to be used with XmlDocument.AppendChild. I do not seem to be able to create an XmlElement other than calling XmlDocument.CreateElement, so I wonder if I have just overlooked anything, or if I really either have to pass in either a XmlDocument or ref XmlElement to work with, or have the function return a String that contains the XML I want?

    Read the article

  • How to parse json string to dataset in C#

    - by Samir R. Bhogayta
    // Serialization of DataSet to json string StringWriter sw = new StringWriter(); versionUpGetData.WriteXml(sw, XmlWriteMode.WriteSchema); XmlDocument xd = new XmlDocument(); xd.LoadXml(sw.ToString()); String jsonText = JsonConvert.SerializeXmlNode(xd); File.WriteAllText(“d:/datasetJson.txt”,jsonText); //Deserialization of Json String to DataSet XmlDocument xd1 = new XmlDocument(); xd1 = (XmlDocument)JsonConvert.DeserializeXmlNode(jsonText); DataSet jsonDataSet = new DataSet(); jsonDataSet.ReadXml(new XmlNodeReader(xd1));

    Read the article

  • Trying to parse xml, but xmldocument.loadxml() is trying to download?

    - by maxp
    I have a string input that i do not know whether or not is valid xml. I think the simplest aprroach is to wrap new XmlDocument().LoadXml(strINPUT); In a try/catch. The problem im facing is, sometimes strINPUT is an html file, if the header of this file contains <!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd""> <html xml:lang=""en-GB"" xmlns=""http://www.w3.org/1999/xhtml"" lang=""en-GB""> ...like many do, it actually tries to make a connection to the w3.org url, which i really dont want it doing. Anyone know if its possible to just parse the string without trying to be clever and checking external urls? Failing that is there an alternative to xmldocument?

    Read the article

  • Managing common code on Windows 7 (.NET) and Windows 8 (WinRT)

    - by ryanabr
    Recent announcements regarding Windows Phone 8 and the fact that it will have the WinRT behind it might make some of this less painful but I  discovered the "XmlDocument" object is in a new location in WinRT and is almost the same as it's brother in .NET System.Xml.XmlDocument (.NET) Windows.Data.Xml.Dom.XmlDocument (WinRT) The problem I am trying to solve is how to work with both types in the code that performs the same task on both Windows Phone 7 and Windows 8 platforms. The first thing I did was define my own XmlNode and XmlNodeList classes that wrap the actual Microsoft objects so that by using the "#if" compiler directive either work with the WinRT version of the type, or the .NET version from the calling code easily. public class XmlNode     { #if WIN8         public Windows.Data.Xml.Dom.IXmlNode Node { get; set; }         public XmlNode(Windows.Data.Xml.Dom.IXmlNode xmlNode)         {             Node = xmlNode;         } #endif #if !WIN8 public System.Xml.XmlNode Node { get; set ; } public XmlNode(System.Xml.XmlNode xmlNode)         {             Node = xmlNode;         } #endif     } public class XmlNodeList     { #if WIN8         public Windows.Data.Xml.Dom.XmlNodeList List { get; set; }         public int Count {get {return (int)List.Count;}}         public XmlNodeList(Windows.Data.Xml.Dom.XmlNodeList list)         {             List = list;         } #endif #if !WIN8 public System.Xml.XmlNodeList List { get; set ; } public int Count { get { return List.Count;}} public XmlNodeList(System.Xml.XmlNodeList list)         {             List = list;        } #endif     } From there I can then use my XmlNode and XmlNodeList in the calling code with out having to clutter the code with all of the additional #if switches. The challenge after this was the code that worked directly with the XMLDocument object needed to be seperate on both platforms since the method for populating the XmlDocument object is completly different on both platforms. To solve this issue. I made partial classes, one partial class for .NET and one for WinRT. Both projects have Links to the Partial Class that contains the code that is the same for the majority of the class, and the partial class contains the code that is unique to the version of the XmlDocument. The files with the little arrow in the lower left corner denotes 'linked files' and are shared in multiple projects but only exist in one location in source control. You can see that the _Win7 partial class is included directly in the project since it include code that is only for the .NET platform, where as it's cousin the _Win8 (not pictured above) has all of the code specific to the _Win8 platform. In the _Win7 partial class is this code: public partial class WUndergroundViewModel     { public static WUndergroundData GetWeatherData( double lat, double lng)         { WUndergroundData data = new WUndergroundData();             System.Net. WebClient c = new System.Net. WebClient(); string req = "http://api.wunderground.com/api/xxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); XmlDocument doc = new XmlDocument();             doc.Load(c.OpenRead(req)); foreach (XmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.Node.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break ; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break ; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation" )),data); break ;                 }             } return data;         }     } in _win8 partial class is this code: public partial class WUndergroundViewModel     { public async static Task< WUndergroundData > GetWeatherData(double lat, double lng)         { WUndergroundData data = new WUndergroundData (); HttpClient c = new HttpClient (); string req = "http://api.wunderground.com/api/xxxx/yesterday/conditions/forecast/q/[LAT],[LNG].xml" ;             req = req.Replace( "[LAT]" , lat.ToString());             req = req.Replace( "[LNG]" , lng.ToString()); HttpResponseMessage msg = await c.GetAsync(req); string stream = await msg.Content.ReadAsStringAsync(); XmlDocument doc = new XmlDocument ();             doc.LoadXml(stream, null); foreach ( IXmlNode item in doc.SelectNodes("/response/features/feature" ))             { switch (item.InnerText)                 { case "yesterday" :                         ParseForecast( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/txt_forecast/forecastdays/forecastday" )), new FishingControls.XmlNodeList (doc.SelectNodes( "/response/forecast/simpleforecast/forecastdays/forecastday" )), data); break; case "conditions" :                         ParseCurrent( new FishingControls.XmlNode (doc.SelectSingleNode("/response/current_observation" )), data); break; case "forecast" :                         ParseYesterday( new FishingControls.XmlNodeList (doc.SelectNodes( "/response/history/observations/observation")), data); break;                 }             } return data;         }     } Summary: This method allows me to have common 'business' code for both platforms that is pretty clean, and I manage the technology differences separately. Thank you tostringtheory for your suggestion, I was considering that approach.

    Read the article

  • How can I copy an XmlNode from one XmlDocument to another?

    - by Chris Wenham
    I'm building a tool that authors/edits XML files, and I want to be able to populate it with template fragments defined in another XML file. For example, the tool has an "Add FooBarBaz Element" button that adds a element to the new document being created, and I want to add FooBarBaz by copying it from a template. Or let's say this is my template file: <Templates> <FooBarBaz Attribute="Value"> <ChildElement/> </FooBarBaz> </Templates> I can then grab a template fragment with .GetElementsByTagName("FooBarBaz"), and I'd like to be able to inject it into the new document with something like .AppendChild(templateNode). But the problem is that an XmlNode cannot be copied from one XmlDocument to another, even if you use .Clone() or .CloneNode(), because AppendChild() throws an exception saying that the template element belongs to another context. Is there an easy way to copy a System.Xml.XmlNode between System.Xml.XmlDocuments?

    Read the article

  • OutOfMemoryException in Microsoft WSE 3.0 Diagnostics.TraceInputFilter

    - by Michael Freidgeim
    We are still using Microsoft WSE 3.0 and on test server started to get   Event Type:        Error Event Source:    Microsoft WSE 3.0 WSE054: An error occurred during the operation of the TraceInputFilter: System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.    at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)    at System.Text.StringBuilder.GetThreadSafeString(IntPtr& tid)    at System.Text.StringBuilder.set_Length(Int32 value)    at System.Xml.BufferBuilder.Clear()    at System.Xml.BufferBuilder.set_Length(Int32 value)    at System.Xml.XmlTextReaderImpl.ParseText()    at System.Xml.XmlTextReaderImpl.ParseElementContent()    at System.Xml.XmlTextReaderImpl.Read()    at System.Xml.XmlLoader.LoadNode(Boolean skipOverWhitespace)    at System.Xml.XmlLoader.LoadDocSequence(XmlDocument parentDoc)    at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)    at System.Xml.XmlDocument.Load(XmlReader reader)    at System.Xml.XmlDocument.Load(Stream inStream)    at Microsoft.Web.Services3.Diagnostics.TraceInputFilter.OpenLoadExistingFile(String path)    at Microsoft.Web.Services3.Diagnostics.TraceInputFilter.Load(String path)    at Microsoft.Web.Services3.Diagnostics.TraceInputFilter.TraceMessage(String messageId, Collection`1 traceEntries).   After investigation it was found, that the problem related to trace files, that become too big. When they were deleted and new files were created, error gone.

    Read the article

  • Calling a .NET C# class from XSLT

    - by HanSolo
    If you've ever worked with XSLT, you'd know that it's pretty limited when it comes to its programming capabilities. Try writing a for loop in XSLT and you'd know what I mean. XSLT is not designed to be a programming language so you should never put too much programming logic in your XSLT. That code can be a pain to write and maintain and so it should be avoided at all costs. Keep your xslt simple and put any complex logic that your xslt transformation requires in a class. Here is how you can create a helper class and call that from your xslt. For example, this is my helper class:  public class XsltHelper     {         public string GetStringHash(string originalString)         {             return originalString.GetHashCode().ToString();         }     }   And this is my xslt file(notice the namespace declaration that references the helper class): <?xml version="1.0" encoding="UTF-8" ?> <xsl:stylesheet  xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:ext="http://MyNamespace">     <xsl:output method="text" indent="yes" omit-xml-declaration="yes"/>     <xsl:template  match="/">The hash code of "<xsl:value-of select="stringList/string1" />" is "<xsl:value-of select="ext:GetStringHash(stringList/string1)" />".     </xsl:template> </xsl:stylesheet>   Here is how you can include the helper class as part of the transformation: string xml = "<stringList><string1>test</string1></stringList>";             XmlDocument xmlDocument = new XmlDocument();             xmlDocument.LoadXml(xml);               XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();             xslCompiledTransform.Load("XSLTFile1.xslt");               XsltArgumentList xsltArgs = new XsltArgumentList();                        xsltArgs.AddExtensionObject("http://MyNamespace", Activator.CreateInstance(typeof(XsltHelper)));               using (FileStream fileStream = new FileStream("TransformResults.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))             {                 // transform the xml and output to the output file ...                 xslCompiledTransform.Transform(xmlDocument, xsltArgs, fileStream);                            }

    Read the article

  • What's the best way to move "a child up" in a C# XmlDocument?

    - by Mike
    Hi everyone, Given an xml structure like this: <garage> <car>Firebird</car> <car>Altima</car> <car>Prius</car> </garage> I want to "move" the Prius node "one level up" so it appears above the Altima node. Here's the final structure I want: <garage> <car>Firebird</car> <car>Prius</car> <car>Altima</car> </garage> So given the C# code: XmlNode priusNode = GetReferenceToPriusNode() What's the best way to cause the priusNode to "move up" one place in the garage's child list? Thanks! -Mike

    Read the article

  • What's the best way to move "a child up" in a .NET XmlDocument?

    - by Mike
    Given an XML structure like this: <garage> <car>Firebird</car> <car>Altima</car> <car>Prius</car> </garage> I want to "move" the Prius node "one level up" so it appears above the Altima node. Here's the final structure I want: <garage> <car>Firebird</car> <car>Prius</car> <car>Altima</car> </garage> So given the C# code: XmlNode priusNode = GetReferenceToPriusNode() What's the best way to cause the priusNode to "move up" one place in the garage's child list?

    Read the article

  • Parse an XML file

    - by karan@dotnet
    The following code shows a simple method of parsing through an XML file/string. We can get the parent name, child name, attributes etc from the XML. The namespace System.Xml would be the only additional namespace that we would be using. string myXMl = "<Employees>" + "<Employee ID='1' Name='John Mayer'" + "Address='12th Street'" + "City='New York' Zip='10004'>" + "</Employee>" + "</Employees>"; XmlDocument xDoc = new XmlDocument();xDoc.LoadXml(myXMl);XmlNodeList xNodeList = xDoc.SelectNodes("Employees/child::node()");foreach (XmlNode xNode in xNodeList){ if (xNode.Name == "Employee") { string ID = xNode.Attributes["ID"].Value; //Outputs: 1 string Name = xNode.Attributes["Name"].Value;//Outputs: John Mayer string Address = xNode.Attributes["Address"].Value;//Outputs: 12th Street string City = xNode.Attributes["City"].Value;//Outputs: New York string Zip = xNode.Attributes["Zip"].Value; //Outputs: 10004 }} Lets look at another XML: string myXMl = "<root>" + "<parent1>..some data</parent1>" + "<parent2>" + "<Child1 id='1' name='Adam'>data1</Child1>" + "<Child2 id='2' name='Stanley'>data2</Child2>" + "</parent2>" + "</root>"; XmlDocument xDoc = new XmlDocument();xDoc.LoadXml(myXMl);XmlNodeList xNodeList = xDoc.SelectNodes("root/child::node()"); //Traverse the entire XML nodes.foreach (XmlNode xNode in xNodeList) { //Looks for any particular nodes if (xNode.Name == "parent1") { //some traversing.... } if (xNode.Name == "parent2") { //If the parent node has child nodes then //traverse the child nodes foreach (XmlNode xNode1 in xNode.ChildNodes) { string childNodeName = xNode1.Name; //Ouputs: Child1 string childNodeData = xNode1.InnerText; //Outputs: data1 //Loop through each attribute of the child nodes foreach (XmlAttribute xAtt in xNode1.Attributes) { string attrName = xAtt.Name; //Outputs: id string attrValue = xAtt.Value; //Outputs: 1 } } }}  

    Read the article

  • Twitter API Voting System

    - by Richard Jones
    So I blatantly got this idea from the MIX 10 event. At MIX they held a rockband talent competition type thing (I’m not quite sure of all the details).    But the interesting part for me is how they collected votes. They used Twitter (what else, when you have a few thousand geeks available to you). The basic idea was that you tweeted your vote with a # tag, i.e #ROCKBANDVOTE vote Richard How cool….    So the question is how do you write something to collate and count all the votes?   Time to press the magic Visual Studio new Project button… Twitter has a really nice API that can be invoked from .NET.   This is the snippet of code that will search for any given phrase i.e #ROCKBANDVOTE   public static XmlDocument GetSearchResults(string searchfor) { return GetSearchResults(searchfor, ""); }   public static XmlDocument GetSearchResults(string searchfor, string sinceid) { XmlDocument retdoc = new XmlDocument();   try { string url = "http://search.twitter.com/search.atom?&q=" + searchfor; if (sinceid.Length > 0) url += "since_id=" + sinceid; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; WebResponse res = request.GetResponse(); retdoc.Load(res.GetResponseStream()); res.Close();   } catch { } return retdoc; } } I’ve got two overloads, that optionally let you pass in the last ID to look for as well as what you want to search for. Note that Twitter rate limits the amount of requests you can send,  see http://apiwiki.twitter.com/Rate-limiting So realistically I wanted my app to run every hour or so and only pull out results that haven’t been received before (hence the overload to pass in the sinceid parameter). I’ll post the code when finished that parses the returned XML.

    Read the article

  • How to add new filters to CAML queries in SharePoint 2007

    - by uruit
      Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:0cm; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} One flexibility SharePoint has is CAML (Collaborative Application Markup Language). CAML it’s a markup language like html that allows developers to do queries against SharePoint lists, it’s syntax is very easy to understand and it allows to add logical conditions like Where, Contains, And, Or, etc, just like a SQL Query. For one of our projects we have the need to do a filter on SharePoint views, the problem here is that the view it’s a list containing a CAML Query with the filters the view may have, so in order to filter the view that’s already been filtered before, we need to append our filters to the existing CAML Query. That’s not a trivial task because the where statement in a CAML Query it’s like this: <Where>   <And>     <Filter1 />     <Filter2 />   </And> </Where> If we want to add a new logical operator, like an OR it’s not just as simple as to append the OR expression like the following example: <Where>   <And>     <Filter1 />     <Filter2 />   </And>   <Or>     <Filter3 />   </Or> </Where> But instead the correct query would be: <Where>   <Or>     <And>       <Filter1 />       <Filter2 />     </And>     <Filter3 />   </Or> </Where> Notice that the <Filter# /> tags are for explanation purpose only. In order to solve this problem we created a simple component, it has a method that receives the current query (could be an empty query also) and appends the expression you want to that query. Example: string currentQuery = @“ <Where>    <And>     <Contains><FieldRef Name='Title' /><Value Type='Text'>A</Value></Contains>     <Contains><FieldRef Name='Title' /><Value Type='Text'>B</Value></Contains>   </And> </Where>”; currentQuery = CAMLQueryBuilder.AppendQuery(     currentQuery,     “<Contains><FieldRef Name='Title' /><Value Type='Text'>C</Value></Contains>”,     CAMLQueryBuilder.Operators.Or); The fist parameter this function receives it’s the actual query, the second it’s the filter you want to add, and the third it’s the logical operator, so basically in this query we want all the items that the title contains: the character A and B or the ones that contains the character C. The result query is: <Where>   <Or>      <And>       <Contains><FieldRef Name='Title' /><Value Type='Text'>A</Value></Contains>       <Contains><FieldRef Name='Title' /><Value Type='Text'>B</Value></Contains>     </And>     <Contains><FieldRef Name='Title' /><Value Type='Text'>C</Value></Contains>   </Or> </Where>             The code:   First of all we have an enumerator inside the CAMLQueryBuilder class that has the two possible Options And, Or. public enum Operators { And, Or }   Then we have the main method that’s the one that performs the append of the filters. public static string AppendQuery(string containerQuery, string logicalExpression, Operators logicalOperator){   In this method the first we do is create a new XmlDocument and wrap the current query (that may be empty) with a “<Query></Query>” tag, because the query that comes with the view doesn’t have a root element and the XmlDocument must be a well formatted xml.   XmlDocument queryDoc = new XmlDocument(); queryDoc.LoadXml("<Query>" + containerQuery + "</Query>");   The next step is to create a new XmlDocument containing the logical expression that has the filter needed.   XmlDocument logicalExpressionDoc = new XmlDocument(); logicalExpressionDoc.LoadXml("<root>" + logicalExpression + "</root>"); In these next four lines we extract the expression from the recently created XmlDocument and create an XmlElement.                  XmlElement expressionElTemp = (XmlElement)logicalExpressionDoc.SelectSingleNode("/root/*"); XmlElement expressionEl = queryDoc.CreateElement(expressionElTemp.Name); expressionEl.InnerXml = expressionElTemp.InnerXml;   Below are the main steps in the component logic. The first “if” checks if the actual query doesn’t contains a “Where” clause. In case there’s no “Where” we add it and append the expression.   In case that there’s already a “Where” clause, we get the entire statement that’s inside the “Where” and reorder the query removing and appending elements to form the correct query, that will finally filter the list.   XmlElement whereEl; if (!containerQuery.Contains("Where")) { queryDoc.FirstChild.AppendChild(queryDoc.CreateElement("Where")); queryDoc.SelectSingleNode("/Query/Where").AppendChild(expressionEl); } else { whereEl = (XmlElement)queryDoc.SelectSingleNode("/Query/Where"); if (!containerQuery.Contains("<And>") &&                 !containerQuery.Contains("<Or>"))        {              XmlElement operatorEl = queryDoc.CreateElement(GetName(logicalOperator)); XmlElement existingExpression = (XmlElement)whereEl.SelectSingleNode("/Query/Where/*"); whereEl.RemoveChild(existingExpression);                 operatorEl.AppendChild(existingExpression);               operatorEl.AppendChild(expressionEl);                 whereEl.AppendChild(operatorEl);        }        else        {              XmlElement operatorEl = queryDoc.CreateElement(GetName(logicalOperator)); XmlElement existingOperator = (XmlElement)whereEl.SelectSingleNode("/Query/Where/*");                 whereEl.RemoveChild(existingOperator);               operatorEl.AppendChild(existingOperator);               operatorEl.AppendChild(expressionEl);                 whereEl.AppendChild(operatorEl);         }  }  return queryDoc.FirstChild.InnerXml }     Finally the GetName method converts the Enum option to his string equivalent.   private static string GetName(Operators logicalOperator) {       return Enum.GetName(typeof(Operators), logicalOperator); }        This component helped our team a lot using SharePoint 2007 and modifying the queries, but now in SharePoint 2010; that wouldn’t be needed because of the incorporation of LINQ to SharePoint. This new feature enables the developers to do typed queries against SharePoint lists without the need of writing any CAML code.   Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-fareast-language:EN-US;} Post written by Sebastian Rodriguez - Portals and Collaboration Solutions @ UruIT  

    Read the article

  • How to add new filters to CAML queries in SharePoint 2007

    - by uruit
    Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:0cm; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} One flexibility SharePoint has is CAML (Collaborative Application Markup Language). CAML it’s a markup language like html that allows developers to do queries against SharePoint lists, it’s syntax is very easy to understand and it allows to add logical conditions like Where, Contains, And, Or, etc, just like a SQL Query. For one of our projects we have the need to do a filter on SharePoint views, the problem here is that the view it’s a list containing a CAML Query with the filters the view may have, so in order to filter the view that’s already been filtered before, we need to append our filters to the existing CAML Query. That’s not a trivial task because the where statement in a CAML Query it’s like this: <Where>   <And>     <Filter1 />     <Filter2 />   </And> </Where> If we want to add a new logical operator, like an OR it’s not just as simple as to append the OR expression like the following example: <Where>   <And>     <Filter1 />     <Filter2 />   </And>   <Or>     <Filter3 />   </Or> </Where> But instead the correct query would be: <Where>   <Or>     <And>       <Filter1 />       <Filter2 />     </And>     <Filter3 />   </Or> </Where> Notice that the <Filter# /> tags are for explanation purpose only. In order to solve this problem we created a simple component, it has a method that receives the current query (could be an empty query also) and appends the expression you want to that query. Example: string currentQuery = @“ <Where>    <And>     <Contains><FieldRef Name='Title' /><Value Type='Text'>A</Value></Contains>     <Contains><FieldRef Name='Title' /><Value Type='Text'>B</Value></Contains>   </And> </Where>”; currentQuery = CAMLQueryBuilder.AppendQuery(     currentQuery,     “<Contains><FieldRef Name='Title' /><Value Type='Text'>C</Value></Contains>”,     CAMLQueryBuilder.Operators.Or); The fist parameter this function receives it’s the actual query, the second it’s the filter you want to add, and the third it’s the logical operator, so basically in this query we want all the items that the title contains: the character A and B or the ones that contains the character C. The result query is: <Where>   <Or>      <And>       <Contains><FieldRef Name='Title' /><Value Type='Text'>A</Value></Contains>       <Contains><FieldRef Name='Title' /><Value Type='Text'>B</Value></Contains>     </And>     <Contains><FieldRef Name='Title' /><Value Type='Text'>C</Value></Contains>   </Or> </Where>     The code:   First of all we have an enumerator inside the CAMLQueryBuilder class that has the two possible Options And, Or. public enum Operators { And, Or }   Then we have the main method that’s the one that performs the append of the filters. public static string AppendQuery(string containerQuery, string logicalExpression, Operators logicalOperator){   In this method the first we do is create a new XmlDocument and wrap the current query (that may be empty) with a “<Query></Query>” tag, because the query that comes with the view doesn’t have a root element and the XmlDocument must be a well formatted xml.   XmlDocument queryDoc = new XmlDocument(); queryDoc.LoadXml("<Query>" + containerQuery + "</Query>");   The next step is to create a new XmlDocument containing the logical expression that has the filter needed.   XmlDocument logicalExpressionDoc = new XmlDocument(); logicalExpressionDoc.LoadXml("<root>" + logicalExpression + "</root>"); In these next four lines we extract the expression from the recently created XmlDocument and create an XmlElement.                  XmlElement expressionElTemp = (XmlElement)logicalExpressionDoc.SelectSingleNode("/root/*"); XmlElement expressionEl = queryDoc.CreateElement(expressionElTemp.Name); expressionEl.InnerXml = expressionElTemp.InnerXml;   Below are the main steps in the component logic. The first “if” checks if the actual query doesn’t contains a “Where” clause. In case there’s no “Where” we add it and append the expression.   In case that there’s already a “Where” clause, we get the entire statement that’s inside the “Where” and reorder the query removing and appending elements to form the correct query, that will finally filter the list.   XmlElement whereEl; if (!containerQuery.Contains("Where")) { queryDoc.FirstChild.AppendChild(queryDoc.CreateElement("Where")); queryDoc.SelectSingleNode("/Query/Where").AppendChild(expressionEl); } else { whereEl = (XmlElement)queryDoc.SelectSingleNode("/Query/Where"); if (!containerQuery.Contains("<And>") &&                 !containerQuery.Contains("<Or>"))        {              XmlElement operatorEl = queryDoc.CreateElement(GetName(logicalOperator)); XmlElement existingExpression = (XmlElement)whereEl.SelectSingleNode("/Query/Where/*"); whereEl.RemoveChild(existingExpression);                 operatorEl.AppendChild(existingExpression);               operatorEl.AppendChild(expressionEl);                 whereEl.AppendChild(operatorEl);        }        else        {              XmlElement operatorEl = queryDoc.CreateElement(GetName(logicalOperator)); XmlElement existingOperator = (XmlElement)whereEl.SelectSingleNode("/Query/Where/*");                 whereEl.RemoveChild(existingOperator);               operatorEl.AppendChild(existingOperator);               operatorEl.AppendChild(expressionEl);                 whereEl.AppendChild(operatorEl);         }  }  return queryDoc.FirstChild.InnerXml }     Finally the GetName method converts the Enum option to his string equivalent.   private static string GetName(Operators logicalOperator) {       return Enum.GetName(typeof(Operators), logicalOperator); }        Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:0cm; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin-top:0cm; mso-para-margin-right:0cm; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0cm; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi;} This component helped our team a lot using SharePoint 2007 and modifying the queries, but now in SharePoint 2010; that wouldn’t be needed because of the incorporation of LINQ to SharePoint. This new feature enables the developers to do typed queries against SharePoint lists without the need of writing any CAML code.  But there is still much development to the 2007 version, so I hope this information is useful for other members.  Post Normal 0 21 false false false ES-UY X-NONE X-NONE /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:"Times New Roman"; mso-bidi-theme-font:minor-bidi; mso-fareast-language:EN-US;} written by Sebastian Rodriguez - Portals and Collaboration Solutions @ UruIT

    Read the article

  • Deploying a SharePoint 2007 theme using Features

    - by Kelly Jones
    I recently had a requirement to update the branding on an existing Windows SharePoint Services (WSS version 3.0) site.  I needed to update the theme, along with the master page.  An additional requirement is that my client likes to have all changes bundled up in SharePoint solutions.  This makes it much easier to move code from dev to test to prod and more importantly, makes it easier to undo code migrations if any issues would arise (I agree with this approach). Updating the theme was easy enough.  I created a new theme, along with a two new features.  The first feature, scoped at the farm level, deploys the theme, adding it to the spthemes.xml file (in the 12 hive –> \Template\layouts\1033 folder).  Here’s the method that I call from the feature activated event: private static void AddThemeToSpThemes(string id, string name, string description, string thumbnail, string preview, SPFeatureReceiverProperties properties) { XmlDocument spThemes = new XmlDocument(); //use GetGenericSetupPath to find the 12 hive folder string spThemesPath = SPUtility.GetGenericSetupPath(@"TEMPLATE\LAYOUTS\1033\spThemes.xml"); //load the spthemes file into our xmldocument, since it is just xml spThemes.Load(spThemesPath); XmlNode root = spThemes.DocumentElement; //search the themes file to see if our theme is already added bool found = false; foreach (XmlNode node in root.ChildNodes) { foreach (XmlNode prop in node.ChildNodes) { if (prop.Name.Equals("TemplateID")) { if (prop.InnerText.Equals(id)) { found = true; break; } } } if (found) { break; } } if (!found) //theme not found, so add it { //This is what we need to add: // <Templates> // <TemplateID>ThemeName</TemplateID> // <DisplayName>Theme Display Name</DisplayName> // <Description>My theme description</Description> // <Thumbnail>images/mythemethumb.gif</Thumbnail> // <Preview>images/mythemepreview.gif</Preview> // </Templates> StringBuilder sb = new StringBuilder(); sb.Append("<Templates><TemplateID>"); sb.Append(id); sb.Append("</TemplateID><DisplayName>"); sb.Append(name); sb.Append("</DisplayName><Description>"); sb.Append(description); sb.Append("</Description><Thumbnail>"); sb.Append(thumbnail); sb.Append("</Thumbnail><Preview>"); sb.Append(preview); sb.Append("</Preview></Templates>"); root.CreateNavigator().AppendChild(sb.ToString()); spThemes.Save(spThemesPath); } } Just as important, is the code that removes the theme when the feature is deactivated: private static void RemoveThemeFromSpThemes(string id) { XmlDocument spThemes = new XmlDocument(); string spThemesPath = HostingEnvironment.MapPath("/_layouts/") + @"1033\spThemes.xml"; spThemes.Load(spThemesPath); XmlNode root = spThemes.DocumentElement; foreach (XmlNode node in root.ChildNodes) { foreach (XmlNode prop in node.ChildNodes) { if (prop.Name.Equals("TemplateID")) { if (prop.InnerText.Equals(id)) { root.RemoveChild(node); spThemes.Save(spThemesPath); break; } } } } } So, that takes care of deploying the theme.  In order to apply the theme to the web, my activate feature method looks like this: public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb curweb = (SPWeb)properties.Feature.Parent) { curweb.ApplyTheme("myThemeName"); curweb.Update(); } } Deactivating is just as simple: public override void FeatureDeactivating(SPFeatureReceiverProperties properties) { using (SPWeb curweb = (SPWeb)properties.Feature.Parent) { curweb.ApplyTheme("none"); curweb.Update(); } } Ok, that’s the code necessary to deploy, apply, un-apply, and retract the theme.  Also, the solution (WSP file) contains the actual theme files. SO, next is the master page, which I’ll cover in my next blog post.

    Read the article

  • Parsing concatenated, non-delimited XML messages from TCP-stream using C#

    - by thaller
    I am trying to parse XML messages which are send to my C# application over TCP. Unfortunately, the protocol can not be changed and the XML messages are not delimited and no length prefix is used. Moreover the character encoding is not fixed but each message starts with an XML declaration <?xml>. The question is, how can i read one XML message at a time, using C#. Up to now, I tried to read the data from the TCP stream into a byte array and use it through a MemoryStream. The problem is, the buffer might contain more than one XML messages or the first message may be incomplete. In these cases, I get an exception when trying to parse it with XmlReader.Read or XmlDocument.Load, but unfortunately the XmlException does not really allow me to distinguish the problem (except parsing the localized error string). I tried using XmlReader.Read and count the number of Element and EndElement nodes. That way I know when I am finished reading the first, entire XML message. However, there are several problems. If the buffer does not yet contain the entire message, how can I distinguish the XmlException from an actually invalid, non-well-formed message? In other words, if an exception is thrown before reading the first root EndElement, how can I decide whether to abort the connection with error, or to collect more bytes from the TCP stream? If no exception occurs, the XmlReader is positioned at the start of the root EndElement. Casting the XmlReader to IXmlLineInfo gives me the current LineNumber and LinePosition, however it is not straight forward to get the byte position where the EndElement really ends. In order to do that, I would have to convert the byte array into a string (with the encoding specified in the XML declaration), seek to LineNumber,LinePosition and convert that back to the byte offset. I try to do that with StreamReader.ReadLine, but the stream reader gives no public access to the current byte position. All this seams very inelegant and non robust. I wonder if you have ideas for a better solution. Thank you. EDIT: I looked around and think that the situation is as follows (I might be wrong, corrections are welcome): I found no method so that the XmlReader can continue parsing a second XML message (at least not, if the second message has an XmlDeclaration). XmlTextReader.ResetState could do something similar, but for that I would have to assume the same encoding for all messages. Therefor I could not connect the XmlReader directly to the TcpStream. After closing the XmlReader, the buffer is not positioned at the readers last position. So it is not possible to close the reader and use a new one to continue with the next message. I guess the reason for this is, that the reader could not successfully seek on every possible input stream. When XmlReader throws an exception it can not be determined whether it happened because of an premature EOF or because of a non-wellformed XML. XmlReader.EOF is not set in case of an exception. As workaround I derived my own MemoryBuffer, which returns the very last byte as a single byte. This way I know that the XmlReader was really interested in the last byte and the following exception is likely due to a truncated message (this is kinda sloppy, in that it might not detect every non-wellformed message. However, after appending more bytes to the buffer, sooner or later the error will be detected. I could cast my XmlReader to the IXmlLineInfo interface, which gives access to the LineNumber and the LinePosition of the current node. So after reading the first message I remember these positions and use it to truncate the buffer. Here comes the really sloppy part, because I have to use the character encoding to get the byte position. I am sure you could find test cases for the code below where it breaks (e.g. internal elements with mixed encoding). But up to now it worked for all my tests. The parser class follows here -- may it be useful (I know, its very far from perfect...) class XmlParser { private byte[] buffer = new byte[0]; public int Length { get { return buffer.Length; } } // Append new binary data to the internal data buffer... public XmlParser Append(byte[] buffer2) { if (buffer2 != null && buffer2.Length > 0) { // I know, its not an efficient way to do this. // The EofMemoryStream should handle a List<byte[]> ... byte[] new_buffer = new byte[buffer.Length + buffer2.Length]; buffer.CopyTo(new_buffer, 0); buffer2.CopyTo(new_buffer, buffer.Length); buffer = new_buffer; } return this; } // MemoryStream which returns the last byte of the buffer individually, // so that we know that the buffering XmlReader really locked at the last // byte of the stream. // Moreover there is an EOF marker. private class EofMemoryStream: Stream { public bool EOF { get; private set; } private MemoryStream mem_; public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override bool CanRead { get { return true; } } public override long Length { get { return mem_.Length; } } public override long Position { get { return mem_.Position; } set { throw new NotSupportedException(); } } public override void Flush() { mem_.Flush(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { count = Math.Min(count, Math.Max(1, (int)(Length - Position - 1))); int nread = mem_.Read(buffer, offset, count); if (nread == 0) { EOF = true; } return nread; } public EofMemoryStream(byte[] buffer) { mem_ = new MemoryStream(buffer, false); EOF = false; } protected override void Dispose(bool disposing) { mem_.Dispose(); } } // Parses the first xml message from the stream. // If the first message is not yet complete, it returns null. // If the buffer contains non-wellformed xml, it ~should~ throw an exception. // After reading an xml message, it pops the data from the byte array. public Message deserialize() { if (buffer.Length == 0) { return null; } Message message = null; Encoding encoding = Message.default_encoding; //string xml = encoding.GetString(buffer); using (EofMemoryStream sbuffer = new EofMemoryStream (buffer)) { XmlDocument xmlDocument = null; XmlReaderSettings settings = new XmlReaderSettings(); int LineNumber = -1; int LinePosition = -1; bool truncate_buffer = false; using (XmlReader xmlReader = XmlReader.Create(sbuffer, settings)) { try { // Read to the first node (skipping over some element-types. // Don't use MoveToContent here, because it would skip the // XmlDeclaration too... while (xmlReader.Read() && (xmlReader.NodeType==XmlNodeType.Whitespace || xmlReader.NodeType==XmlNodeType.Comment)) { }; // Check for XML declaration. // If the message has an XmlDeclaration, extract the encoding. switch (xmlReader.NodeType) { case XmlNodeType.XmlDeclaration: while (xmlReader.MoveToNextAttribute()) { if (xmlReader.Name == "encoding") { encoding = Encoding.GetEncoding(xmlReader.Value); } } xmlReader.MoveToContent(); xmlReader.Read(); break; } // Move to the first element. xmlReader.MoveToContent(); // Read the entire document. xmlDocument = new XmlDocument(); xmlDocument.Load(xmlReader.ReadSubtree()); } catch (XmlException e) { // The parsing of the xml failed. If the XmlReader did // not yet look at the last byte, it is assumed that the // XML is invalid and the exception is re-thrown. if (sbuffer.EOF) { return null; } throw e; } { // Try to serialize an internal data structure using XmlSerializer. Type type = null; try { type = Type.GetType("my.namespace." + xmlDocument.DocumentElement.Name); } catch (Exception e) { // No specialized data container for this class found... } if (type == null) { message = new Message(); } else { // TODO: reuse the serializer... System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(type); message = (Message)ser.Deserialize(new XmlNodeReader(xmlDocument)); } message.doc = xmlDocument; } // At this point, the first XML message was sucessfully parsed. // Remember the lineposition of the current end element. IXmlLineInfo xmlLineInfo = xmlReader as IXmlLineInfo; if (xmlLineInfo != null && xmlLineInfo.HasLineInfo()) { LineNumber = xmlLineInfo.LineNumber; LinePosition = xmlLineInfo.LinePosition; } // Try to read the rest of the buffer. // If an exception is thrown, another xml message appears. // This way the xml parser could tell us that the message is finished here. // This would be prefered as truncating the buffer using the line info is sloppy. try { while (xmlReader.Read()) { } } catch { // There comes a second message. Needs workaround for trunkating. truncate_buffer = true; } } if (truncate_buffer) { if (LineNumber < 0) { throw new Exception("LineNumber not given. Cannot truncate xml buffer"); } // Convert the buffer to a string using the encoding found before // (or the default encoding). string s = encoding.GetString(buffer); // Seek to the line. int char_index = 0; while (--LineNumber > 0) { // Recognize \r , \n , \r\n as newlines... char_index = s.IndexOfAny(new char[] {'\r', '\n'}, char_index); // char_index should not be -1 because LineNumber>0, otherwise an RangeException is // thrown, which is appropriate. char_index++; if (s[char_index-1]=='\r' && s.Length>char_index && s[char_index]=='\n') { char_index++; } } char_index += LinePosition - 1; var rgx = new System.Text.RegularExpressions.Regex(xmlDocument.DocumentElement.Name + "[ \r\n\t]*\\>"); System.Text.RegularExpressions.Match match = rgx.Match(s, char_index); if (!match.Success || match.Index != char_index) { throw new Exception("could not find EndElement to truncate the xml buffer."); } char_index += match.Value.Length; // Convert the character offset back to the byte offset (for the given encoding). int line1_boffset = encoding.GetByteCount(s.Substring(0, char_index)); // remove the bytes from the buffer. buffer = buffer.Skip(line1_boffset).ToArray(); } else { buffer = new byte[0]; } } return message; } }

    Read the article

  • How to debug jQuery ajax POST to .NET webservice

    - by Nick
    Hey all. I have a web service that I have published locally. I wrote an HTML page to test the web service. The webservice is expecting a string that will be XML. When I debug the web service from within VS everything works great. I can use FireBug and see that my web service is indeed being hit by they AJAX call. After deploying the web service locally to IIS it does not appear to be working. I need to know the best way to trouble shoot this problem. My AJAX js looks like this: function postSummaryXml(data) { $.ajax({ type: 'POST', url: 'http://localhost/collection/services/datacollector.asmx/SaveSummaryDisplayData', data: { xml: data }, error: function(result) { alert(result); }, success: function(result) { alert(result); } }); The web method looks like so: [WebMethod] public string SaveSummaryDisplayData(string xml) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); XmlParser parser = new XmlParser(xmlDocument); IModel repository = new Repository(); if(repository.AddRecord("TestData",parser.TestValues)) { return "true"; } return "false"; } } I added the return string to the web method in an attempt to ensure that the web-service is really hit from the ajax. The problem is this: In FF the 'Success' function is always called yet the result is always 'NULL'. And the web method does not appear to have worked (no data saved). In IE the 'Error' function is called and the response is server error: 500. I think (believe it or not) IE is giving me a more accurate indication that something is wrong but I cannnot determine what the issue is. Can someone please suggest how I should expose the specific server error message? Thanks for the help!

    Read the article

  • XML Serialize and Deserialize Problem XML Structure

    - by Ph.E
    Camarades, I'm having the following problem. Caught a list Struct, Serialize (Valid W3C) and send to a WebService. In the WebService I receive, transform to a string, valid by the W3C and then Deserializer, but when I try to run it, always occurs error, saying that some objects were not closed. Any help? Sent Code: #region ListToXML private XmlDocument ListToXMLDocument(object __Lista) { XmlDocument _ListToXMLDocument = new XmlDocument(); try { XmlDocument _XMLDoc = new XmlDocument(); MemoryStream _StreamMem = new MemoryStream(); XmlSerializer _XMLSerial = new XmlSerializer(__Lista.GetType()); StreamWriter _StreamWriter = new StreamWriter(_StreamMem, Encoding.UTF8); _XMLSerial.Serialize(_StreamWriter, __Lista); _StreamMem.Position = 0; _XMLDoc.Load(_StreamMem); if (_XMLDoc.ChildNodes.Count > 0) _ListToXMLDocument = _XMLDoc; } catch (Exception __Excp) { new uException(__Excp).GerarLogErro(CtNomeBiblioteca); } return _ListToXMLDocument; } #endregion Receive Code: #region XMLDocumentToTypedList private List<T> XMLDocumentToTypedList<T>(string __XMLDocument) { List<T> _XMLDocumentToTypedList = new List<T>(); try { XmlSerializer _XMLSerial = new XmlSerializer(typeof(List<T>)); MemoryStream _MemStream = new MemoryStream(); StreamWriter _StreamWriter = new StreamWriter(_MemStream, Encoding.UTF8); _StreamWriter.Write(__XMLDocument); _MemStream.Position = 0; _XMLDocumentToTypedList = (List<T>)_XMLSerial.Deserialize(_MemStream); return _XMLDocumentToTypedList; } catch (Exception _Ex) { new uException(_Ex).GerarLogErro(CtNomeBiblioteca); throw _Ex; } } #endregion

    Read the article

  • Reading RSS feeds --> not consistent

    - by DEE
    Hi There, i am trying to read the RSS feed by loading it to xmldocument some thing like xmlTextReader = new XmlTextReader(url); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlTextReader); some times the loading to xml document succeeds and some times it fails . the url i am using is http://rss.nzherald.co.nz/rss/xml/nzhrsscid%5F000000004.xml what could be the probelm, is it like the RSS is not updated properly..? any suggestions/comments Regards DEE

    Read the article

  • XmlException - inserting attribute gives "unexpected token" exception

    - by Anders Svensson
    Hi, I have an XmlDocument object in C# that I transform, using XslTransform, to html. In the stylesheet I insert an id attribute in a span tag, taking the id from an element in the XmlDocument. Here is the template for the element: <xsl:template match="word"> <span> <xsl:attribute name="id"><xsl:value-of select="@id"></xsl:value-of></xsl:attribute> <xsl:apply-templates/> </span> </xsl:template> But then I want to process the result document as an xhtml document (using the XmlDocument dom). So I'm taking a selected element in the html, creating a range out of it, and try to load the element using XmlLoad(): wordElem.LoadXml(range.htmlText); But this gives me the following exception: "'598' is an unexpected token. The expected token is '"' or '''. Line 1, position 10." And if I move the cursor over the range.htmlText, I see the tags for the element, and the "id" shows without quotes, which confuses me (i.e.SPAN id=598 instead of SPAN id="598"). To confuse the matter further, if I insert a blank space or something like that in the value of the id in the stylesheet, it works fine, i.e.: <span> <xsl:attribute name="id"><xsl:text> </xsl:text> <xsl:value-of select="@id"></xsl:value-of></xsl:attribute> <xsl:apply-templates/> </span> (Notice the whitespace in the xsl:text element). Now if I move the cursor over the range.htmlText, I see an id with quotes as usual in attributes (and as it shows if I open the html file in notepad or something). What is going on here? Why can't I insert an attribute this way and have a result that is acceptable as xhtml for XmlDocument to read? I feel I am missing something fundamental, but all this surprises me, since I do this sort of transformations using xsl:attribute to insert attributes all the time for other types of xsl transformations. Why doesn't XmlDocument accept this value? By the way, it doesn't matter if it is an id attribute. i have tried with the "class" attribute, "style" etc, and also using literal values such as "style" and setting the value to "color:red" and so on. The compiler always complains it is an unvalid token, and does not include quotes for the value unless there is a whitespace or something else in there (linebreaks etc.). I hope I have provided enough information. Any help will be greatly appreciated. Basically, what I want to accomplish is set an id in a span element in html, select a word in a webbrowser control with this document loaded, and get the id attribute out of the selected element. I've accomplished everything, and can actually do what I want, but only if I use regex e.g. to get the attribute value, and I want to be able to use XmlDocument instead to simply get the value out of the attribute directly. I'm sure I'm missing something simple, but if so please tell me. Regards, Anders

    Read the article

  • Understanding Visitor Pattern

    - by Nezreli
    I have a hierarchy of classes that represents GUI controls. Something like this: Control-ContainerControl-Form I have to implement a series of algoritms that work with objects doing various stuff and I'm thinking that Visitor pattern would be the cleanest solution. Let take for example an algorithm which creates a Xml representaion of a hierarchy of objects. Using 'classic' approach I would do this: public abstract class Control { public virtual XmlElement ToXML(XmlDocument document) { XmlElement xml = document.CreateElement(this.GetType().Name); // Create element, fill it with attributes declared with control return xml; } } public abstract class ContainerControl : Control { public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Use forech to fill XmlElement with child XmlElements return xml; } } public class Form : ContainerControl { public override XmlElement ToXML(XmlDocument document) { XmlElement xml = base.ToXML(document); // Fill remaining elements declared in Form class return xml; } } But I'm not sure how to do this with visitor pattern. This is the basic implementation: public class ToXmlVisitor : IVisitor { public void Visit(Form form) { } } Since even the abstract classes help with implementation I'm not sure how to do that properly in ToXmlVisitor. Perhaps there is a better solution to this problem. The reason that I'm considering Visitor pattern is that some algorithms will need references not available in project where the classes are implemented and there is a number of different algorithms so I'm avoiding large classes. Any thoughts are welcome.

    Read the article

  • XAML | When used XamlReader.Parse, not able to refer the items using the LogicalTreeHelper/VisualTre

    - by Roopesh
    Hi, I am setting the dynamic xaml (I am reading the xaml from the DB) for the content of a tab using the below statement. Tab.Content = XamlReader.Parse(xaml, ctx) After setting the content, if I try getting the children using the VisualTreeHelper, but I am not able to get. How ever I dont have this issue when I construct the xaml statically. Here is the code to reading the xaml. Dim XmlDocument = New XmlDataDocument() Dim IID As String = Nothing Dim xaml As String = Nothing Dim Tab As New TabItem Dim TempPanel As XmlNode = Nothing 'Tab.Height = 0 Try XmlDocument.Load(Directory.GetCurrentDirectory & "\Xml\AppFile.xml") pXmlDoc = XmlDocument xaml = XmlDocument.SelectSingleNode("//Grid").OuterXml Dim AsmName As String = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name Dim ctx As ParserContext = New ParserContext() ' New ParserContext() ctx.XamlTypeMapper = New XamlTypeMapper(New String() {AsmName}) ctx.XamlTypeMapper.AddMappingProcessingInstruction("src", "WpfToolkitDataGridTester", AsmName) ctx.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation") ctx.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml") ctx.XmlnsDictionary.Add("src", "clr-namespace:WpfToolkitDataGridTester;assembly=" + AsmName) Tab.Name = "Tab" & Grid1Tab.Items.Count + 1 Tab.Header = "AppFile-1" Tab.BorderThickness = New Thickness(0) Tab.IsSelected = True Tab.Content = XamlReader.Parse(xaml, ctx) Grid1Tab.Items.Add(Tab) Return True Catch ex As Exception Throw End Try Here is the code to access the item after constructing the XAML. For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(myVisual) - 1 Dim childVisual As Visual = CType(VisualTreeHelper.GetChild(myVisual, i), Visual) Select Case childVisual.DependencyObjectType.Name Case "ComboBox" AddHandler CType(childVisual, ComboBox).SelectionChanged, AddressOf ComboBox_SelectChanged Case "CheckBox" AddHandler CType(childVisual, CheckBox).Checked, AddressOf CheckBoxClicked AddHandler CType(childVisual, CheckBox).Unchecked, AddressOf CheckBoxClicked Case "RadioButton" AddHandler CType(childVisual, RadioButton).Checked, AddressOf CheckBoxClicked Case "TabControl" For Each item As System.Windows.Controls.TabItem In CType(childVisual, TabControl).Items EnumVisual(item.Content) Next End Select EnumVisual(childVisual) Next i any help is highly appreciated. Thanks,

    Read the article

  • Is there a way to create a SyndicationFeed from a String?

    - by Roberto Bonini
    Hi, I'm trying to recreate a SyndicationFeed object (System.ServiceModel.Syndication) from XML data that has been stored locally. If I were working with XMLDocument, this would be easy.I'd call LoadXml(string). The SyndicationFeed will only load from an XMLReader. The XMLReader will only take a Stream or another XMLReader or a TextReader. Since XMLDocument will load a string, I've tried to do this as follows (in the form of a Extension Method): public static SyndicationFeed ToSyndicationFeed(this XmlDocument document) { Stream thestream = Stream.Null; XmlWriter thewriter = XmlWriter.Create(thestream); document.WriteTo(thewriter); thewriter.Flush(); XmlReader thereader = XmlReader.Create(thestream); SyndicationFeed thefeed = SyndicationFeed.Load(thereader); return thefeed; } I can't get this to work. The Stream is always empty even though the XMLDocument is populated with the Feed to be loaded into the SyndicationFeed. Any help or pointers you can give would be most helpful. Thanks, Roberto

    Read the article

  • Calling a Stored Procedure using C# with XML Datatype

    - by Lakeshore
    I am simply trying to call a store procedure (SQL Server 2008) using C# and passing XMLDocument to a store procedure parameter that takes a SqlDbType.Xml data type. I am getting error: Failed to convert parameter value from a XmlDocument to a String. Below is code sample. How do you pass an XML Document to a store procedure that is expecting an XML datatype? Thanks. XmlDocument doc = new XmlDocument(); //Load the the document with the last book node. XmlTextReader reader = new XmlTextReader(@"C:\temp\" + uploadFileName); reader.Read(); // load reader doc.Load(reader); connection.Open(); SqlCommand cmd = new SqlCommand("UploadXMLDoc", connection); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@Year", SqlDbType.Int); cmd.Parameters["@Year"].Value = iYear; cmd.Parameters.Add("@Quarter", SqlDbType.Int); cmd.Parameters["@Quarter"].Value = iQuarter; cmd.Parameters.Add("@CompanyID", SqlDbType.Int); cmd.Parameters["@CompanyID"].Value = iOrganizationID; cmd.Parameters.Add("@FileType", SqlDbType.VarChar); cmd.Parameters["@FileType"].Value = "Replace"; cmd.Parameters.Add("@FileContent", SqlDbType.Xml); cmd.Parameters["@FileContent"].Value = doc; cmd.Parameters.Add("@FileName", SqlDbType.VarChar); cmd.Parameters["@FileName"].Value = uploadFileName; cmd.Parameters.Add("@Description", SqlDbType.VarChar); cmd.Parameters["@Description"].Value = lblDocDesc.Text; cmd.Parameters.Add("@Success", SqlDbType.Bit); cmd.Parameters["@Success"].Value = false; cmd.Parameters.Add("@AddBy", SqlDbType.VarChar); cmd.Parameters["@AddBy"].Value = Page.User.Identity.Name; cmd.ExecuteNonQuery(); connection.Close();

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >