How to ignore comments when parsing xml in asp.net - asp.net

Seems like this should be easy, but I'm not finding a simple configuration setting. Basically I have a page that will be parsing xml files that may have some comment tags in them. I'm loading it as an xml doc and looping through a particular node of the document and I'm running into problems because it's counting the comment as a child node. Any way to tell asp.net not to look at comments other than writing my own check for <!-- ?

If you use XmlNode, then that has a NodeType property. Ignore the nodes where that has a value of "Comment".
An XNode has the same property.

Use XmlReaderSettings.IgnoreComments:
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.IgnoreComments = true;
using (XmlReader reader = XmlReader.Create("input.xml", readerSettings))
{
XmlDocument myData = new XmlDocument();
myData.Load(reader);
// etc...
}

Related

Extracting userid from Inbound headers

I have to read element from Inbound Header...
I am assigning inbound header using WCF.InboundHeaders to a string....
now my problem is my inbounde header is looking like this
InboundHeaders
<headers><s:userid xmlns:s="http://www.w3.org/2003/05/soap-envelope">testuser</s:userid>
<s:applicationid xmlns:s="http://www.w3.org/2003/05/soap-envelope">assistworkerweb</s:applicationid>
<a:Action s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">http://Request</a:Action><a:To s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
Now i need to extract user id from it ..how to extract user id from it..
You haven't mentioned where or how your string is stored (that is populated with your WCF.InboundHeaders), however I would use a simple fragment of XPath to extract the UserId. If you were extracting this using a C# helper, you could do something along the lines of (note, this is untested, however its pretty much there):
XmlDocument doc = new XmlDocument();
doc.Load([WCF.InboundHeaders Xml Fragment]);
// Create an XmlNamespaceManager to add 'soap-envelope' namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
// Select the UserId
XmlNode userId = doc.SelectSingleNode("/headers/s:userid", nsmgr);
Console.WriteLine(userId.InnerXml);
You may also want to serialize the Xml fragment into a .Net object and retrieve the UserId in that manner.

How can i extract XML and use it as a datasource?

I am using asp.net VB and I have an XML file containing a set of data, I would like to use it in something like a datalist and where usually you would use a database i would like to use the XML file to produce the information.
Does anyone know how to do this, i have read about transform files but surely i will format the information in the control?
The file has multiple records so in some cases i would need to perform queries on the information through the datasource.
I would maybe look into XML serialization and de-serialization. Using de-serialization you could read your XML into a List(T) object containing a list of your own class objects and use that as a data source for your application.
Heres a link that you may find useful:
http://msdn.microsoft.com/en-us/library/ms731073.aspx
Hope this helps.
Dim ds As New DataSet()
ds.ReadXml(MapPath("data.xml"))
First you have to parse the XML and store that into custom C# object or you can directly pass the XML to your stored procedure and do the codding there for saving it into DB.
Passing the xml to stored procedure and manipulating it there is bit difficult so what I suggest is to parse it in C# and then get a custom object. Once you get it you can do whatever you want to.
Below is the sample code that parse a XML file and generate a custom C# object from it.
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}

Retrieving a list of Tridion 2009 components with a specific value and schema without using search

I would like to create a .NET page residing on the CMS server that shows all components that are based on a specific Schema(tcm:3-3-8) and from a specific Publication(tcm:0-3-1) including BluePrinted and Localized items, but only if they have the value "http://www.google.com" for the field "URL" in that Schema.
Is this possible, without using the search service as this is rather slow and unreliable?
Your search might be slow because of not indexing the search collection.
You should do indexing the search collection on regular intervals for better and fast results.
That's an expensive operation to do because of the cost of opening each individual component to check the value of a field, but certainly do-able.
Get the schema object
Get a list of components that use this schema (WhereUsed on the schema with filter on ItemType = component)
Open each component and check the value for the field(s), add to a List<Component> if it matches
Display list (possibly using a ASP.NET GridView)
I have not had any chance to test it, but something like this
Common common = new Common();
TDSE tdse = new TDSE();
ListRowFilter ComponentFilter = tdse.CreateListRowFilter();
Schema schema = (Schema)common.getObject("tcm:126-238630-8", ItemType.ItemTypeSchema);
ComponentFilter.SetCondition("ItemType", ItemType.ItemTypeComponent);
ComponentFilter.SetCondition("Recursive", true);
XDocument doc = common.ReadXML(schema.Info.GetListUsingItems(ListColumnFilter.XMLListID, ComponentFilter));
List<Component> MatchedComponents = new List<Component>();
XmlNamespaceManager NS = new XmlNamespaceManager(new NameTable());
NS.AddNamespace("tcm", "http://www.tridion.com/ContentManager/5.0");
NS.AddNamespace("Content", "uuid:4432F3C3-9F3E-45E4-AE31-408C5C46E2BF");
foreach (XElement component in doc.XPathSelectElements("/tcm:ListUsingItems/tcm:Item", NS))
{
Component comp = common.getComponent(component.Attribute("ID").Value);
XDocument compDoc = common.ReadXML(comp.GetXML(XMLReadFilter.XMLReadData));
foreach (XElement compNode in compDoc.XPathSelectElements("/tcm:Component/tcm:Data/tcm:Content/Content:Content/Content:feederUrl", NS))
{
MatchedComponents.Add(comp);
}
}

NVelocity not finding the template

I'm having some difficulty with using NVelocity in an ASP.NET MVC application. I'm using it as a way of generating emails.
As far as I can make out the details I'm passing are all correct, but it fails to load the template.
Here is the code:
private const string defaultTemplatePath = "Views\\EmailTemplates\\";
...
velocityEngine = new VelocityEngine();
basePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, defaultTemplatePath);
ExtendedProperties properties = new ExtendedProperties();
properties.Add(RuntimeConstants.RESOURCE_LOADER, "file");
properties.Add(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, basePath);
velocityEngine.Init(properties);
The basePath is the correct directory, I've pasted the value into explorer to ensure it is correct.
if (!velocityEngine.TemplateExists(name))
throw new InvalidOperationException(string.Format("Could not find a template named '{0}'", name));
Template result = velocityEngine.GetTemplate(name);
'name' above is a valid filename in the folder defined as basePath above. However, TemplateExists returns false. If I comment that conditional out and let it fail on the GetTemplate method call the stack trace looks like this:
at NVelocity.Runtime.Resource.ResourceManagerImpl.LoadResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.Resource.ResourceManagerImpl.GetResource(String resourceName, ResourceType resourceType, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name, String encoding)
at NVelocity.Runtime.RuntimeInstance.GetTemplate(String name)
at NVelocity.App.VelocityEngine.GetTemplate(String name)
...
I'm now at a bit of an impasse. I feel that the answer is blindingly obvious, but I just can't seem to see it at the moment.
Have you considered using Castle's NVelocityTemplateEngine?
Download from the "TemplateEngine Component 1.1 - September 29th, 2009" section and reference the following assemblies:
using Castle.Components.Common.TemplateEngine.NVelocityTemplateEngine;
using Castle.Components.Common.TemplateEngine;
Then you can simply call:
using (var writer = new StringWriter())
{
_templateEngine.Process(data, string.Empty, writer, _templateContents);
return writer.ToString();
}
Where:
_templateEngine is your NVelocityTemplateEngine
data is your Dictionary of information (I'm using a Dictionary to enable me to access objects by a key ($objectKeyName) in my template.
_templateContents is the actual template string itself.
I hope this is of help to you!
Just to add, you'll want to put that into a static method returning a string of course!
Had this issue recently - NVelocity needs to be initialised with the location of the template files. In this case mergeValues is an anonymous type so in my template I can just refer to $Values.SomeItem:
private string Merge(Object mergeValues)
{
var velocity = new VelocityEngine();
var props = new ExtendedProperties();
props.AddProperty("file.resource.loader.path", #"D:\Path\To\Templates");
velocity.Init(props);
var template = velocity.GetTemplate("MailTemplate.vm");
var context = new VelocityContext();
context.Put("Values", mergeValues);
using (var writer = new StringWriter())
{
template.Merge(context, writer);
return writer.ToString();
}
}
Try setting the file.resource.loader.path
http://weblogs.asp.net/george_v_reilly/archive/2007/03/06/img-srchttpwwwcodegenerationnetlogosnveloc.aspx
Okay - So I'm managed to get something working but it is a bit of a hack and isn't anywhere near a solution that I want, but it got something working.
Basically, I manually load in the template into a string then pass that string to the velocityEngine.Evaluate() method which writes the result into the the given StringWriter. The side effect of this is that the #parse instructions in the template don't work because it still cannot find the files.
using (StringWriter writer = new StringWriter())
{
velocityEngine.Evaluate(context, writer, templateName, template);
return writer.ToString();
}
In the code above templateName is irrelevant as it isn't used. template is the string that contains the entire template that has been pre-loaded from disk.
I'd still appreciate any better solutions as I really don't like this.
The tests are the ultimate authority:
http://fisheye2.atlassian.com/browse/castleproject/NVelocity/trunk/src/NVelocity.Tests/Test/ParserTest.cs?r=6005#l122
Or you could use the TemplateEngine component which is a thin wrapper around NVelocity that makes things easier.

Storing XSLT in SQL Server 2005 with xml type?

I have a lot of XSL files in my ASP.NET web app. A lot. I generate a bunch of AJAX HTML responses using this kind of generic transform method:
public void Transform(XmlDocument xml, string xslPath)
{
...
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(xslPath);
myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
}
I'd like to move the XSL definitions into SQL Server, using a column of type xml.
I would store an entire XSL file in a single row in SQL, and each XSL is self-contained (no imports). I would read out the XSL definition from SQL into my XslTransform object.
Something like this:
public void Transform(XmlDocument xml, string xslKey)
{
...
SqlCommand cmd = new SqlCommand("GetXslDefinition");
cmd.AddParameter("#xslKey", SqlDbType.VarChar).Value = xslKey;
// where the result set has a single column of XSL: "<xslt:stylesheet>..."
...
SqlDataReader dr = cmd.ExecuteReader();
if(dr.Read()) {
SqlXml xsl = dr.GetSqlXml(0);
XslTransform myXslTrans = new XslTransform();
myXslTrans.Load(xsl.CreateReader());
myXslTrans.Transform(xml,null, HttpContext.Current.Response.Output);
}
}
It seems like a straightforward way to:
add metadata to each XSL, like lastUsed, useCount, etc.
bulk update/search capabilities
prevent lots of disk access
avoid referencing relative paths and organizing files
allow XSL changes without redeploying (I could even write an admin page that selects/updates the XSL in the database)
Has anyone tried this before? Are there any caveats?
EDIT
Caveats that responders have listed:
disk access isn't guaranteed to diminish
this will break xsl:includes
The two big issues I can see are:
We use a lot of includes to ensure that we only do things once, storing the XSLT in the database would stop us from doing that.
It makes updating XSLs more interesting - we've been quite happy to dump new .xsl files into deployed sites without doing a full update of the site. For that matter we've got bits of code that look for client specific xsl in a folder and those bits of code can reach back up to common code (templates) in the root - so I'm not sure about the redeploy thing at all, but this will depend very much on the particular use case, yours is certainly different to ours.
In terms of disk access, hmm... the db still has to go access the disk to pull the data and if you're talking about caching then the db isn't a requirement for enabling caching.
Have to agree about the update/search options - you can do stuff with Powershell but that needs to be run on the server and that's not always a good idea.
Technically I can see no reason why not (excepting the wish to do includes as above) but practically it seems to be fairly balanced with good arguments either way.
I store XSLTs in a database in my application dbscript. (However I keep them in an NVARCHAR column, since it also runs on SQL Server 2000)
Since users are able to edit their XSLTs, I needed to write a custom validator which loads the text of TextBox in a .Net XslCompiledTransform object like this:
args.IsValid = true;
if (args.Value.Trim() == "")
return;
try
{
System.IO.TextReader rd = new System.IO.StringReader(args.Value);
System.Xml.XmlReader xrd = System.Xml.XmlReader.Create(rd);
System.Xml.Xsl.XslCompiledTransform xslt = new System.Xml.Xsl.XslCompiledTransform();
System.Xml.Xsl.XsltSettings xslts = new System.Xml.Xsl.XsltSettings(false, false);
xslt.Load(xrd, xslts, new System.Xml.XmlUrlResolver());
xrd.Close();
}
catch (Exception ex)
{
this.ErrorMessage = (string.IsNullOrEmpty(sErrorMessage) ? "" : (sErrorMessage + "<br/>") +
ex.Message);
if (ex.InnerException != null)
{
ex = ex.InnerException;
this.ErrorMessage += "<br />" + ex.Message;
}
args.IsValid = false;
}
As for your points:
file I/O will be replaced by database-generated disk I/O, so no gains there
deployment changes to providing an INSERT/UPDATE script containing the new data

Resources