Archive

Archive for February, 2014

How to validate string.format within Visual Studio

February 28, 2014 Leave a comment

 

In writing code we use string.format a lot to create strings for error reporting or sending to the screen. Some of these will only ever get created if an error occurs so they become difficult to test to make sure the don’t throw an error. Take the following example

The following code would fail at runtime but is fine in the compiler

string.Format("{0} This is valid but will error {1}", this.siteURL);

So how do we catch these. Well we all use the code analysis tools built into visual studio. Don’t we?

 

Well this has a nice test case that will catch and highlight this problem.

 

Run code analysis on your project Alt+F11 or select “Run Code Analysis on …” from the Analyse menu.

 

Then once this has finished you can search for issue CA2241. This will show any and all string.formats that would fail at run time.

 

It would be nice if the compiler caught these but this is still a good approach.

Categories: work Tags:

Infopath Namespace manager creation code

February 18, 2014 Leave a comment

I have had to create some code this week that reads the xml created by InfoPath. I then found that if you try and xpath on something you get a null return until the namespace manager has all of the correct entries. In the past I have created these manually but after a bit of google fo I have come up with the below piece of code. It takes an XMLDocument that you have created based on the form file (or any XML document really) and returns you a newly created namespace manager that can be used along side you xpath queries to get the data you want.

 

 

public static XmlNamespaceManager GetNameSpaceManager(XmlDocument xmlDoc)
{
XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
foreach (XmlAttribute att in xmlDoc.DocumentElement.Attributes)
{
if (att.Prefix == "xmlns")
{
ns.AddNamespace(att.LocalName, att.Value);
}
}
return ns;
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Categories: work Tags: