Category Archives: C#

C#: Get URL of HTTP Redirect

This is one of those snippets that might be useful someday:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://this.domain.com/someThingThatRespondsWithRedirect");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
string redirectUrl = response.Headers.Get("Location"));

Typically browsers or the default http request class of your favorite programming language redirect you automatically in case they receive a HTTP Redirect status code. Typically that’s exactly what you want.
Last week however I ran into a situation in which I didn’t want the redirect to happen.
Since the code was written in VBScript / ASP, I first tried to accomplish it there. No chance. Good thing that I don’t have to rely entirely on VBScript. The C# WebRequest class has an attribute that allows to explicitly turn off the automatic redirect. You can read the Redirect-URL from the response header.

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in C# | Leave a comment

C#: Bug in Uri.IsWellFormedUriString?!

A few days ago I had to analyze a string, figure out whether it is a URI and if yes, then do something with parts of the URI, like the host, the pathname and the parameters. Since I was coding in C# I thought the Uri class would be just ideal for that.

So first I implemented this

Uri myUri;
try {
    myUri = new Uri(myUrlString);
} catch (UriFormatException) {
    // do something
}

Then however I realized that there is a function for testing the validity of a string:

Uri myUri;
if (Uri.IsWellFormedUriString(myUrlString)) {
    myUri = new Uri(myUrlString);
}

This is much nicer. I don’t like using exceptions to handle expected workflows. In this case the string can be a valid or invalid Uri, so really the if-then-else construction is nicer than the try-catch. The problem is that even though IsWellFormedUriString returns true you might not be able to create an Uri instance from it. Consider this small programm:

using System;
namespace DemoConsoleApp
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Uri myUri;
 
			string myUrl1 = "www.mydomain.de/test/file.aspx";
			string myUrl2 = "http://www.mydomain.de/test/file.aspx";
 
			Console.WriteLine(Uri.IsWellFormedUriString(myUrl1, UriKind.RelativeOrAbsolute));
			Console.WriteLine(Uri.IsWellFormedUriString(myUrl2 ,UriKind.RelativeOrAbsolute));
 
			try {
				myUri = new Uri(myUrl1);
			} catch (UriFormatException) {
				Console.WriteLine("Failed to create Uri from myUrl1");
			}
 
			try {
				myUri = new Uri(myUrl2);
			} catch (UriFormatException) {
				Console.WriteLine("Failed to create Uri from myUrl2");
			}
		}
	}
}

The output is :

True
True
Failed to create Uri from myUrl1

According to the documentation, the first call of Uri.IsWellFormedUriString should returns false. If it did this would be also consistent with the constructor, which fails for myUrl1.

By default, the string is considered well-formed in accordance with RFC 2396 and RFC 2732. If International Resource Identifiers (IRIs) or Internationalized Domain Name (IDN) parsing is enabled, the string is considered well-formed in accordance with RFC 3986 and RFC 3987.
The string is considered poorly formed, causing the method to return false, if any of the following conditions occur
[...]
The string represents a hierarchical absolute Uri and does not contain “://” – www.contoso.com/path/file

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in C# | 1 Comment

C#: Copy Node From a XmlDocument To Another

This is not rocket science, just a little problem I had a couple of days ago: How to copy a XML node from one XmlDocument to another.

My first approach:

1
2
3
4
5
6
7
8
9
10
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(@"<hello>
                         <world>Test</world>
		        </hello>");
 
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(@"<hello>
                      </hello>");
 
doc2.DocumentElement.AppendChild(doc1.SelectSingleNode("/Hello/World"));

If you run this code, you’ll get an exception:

Unhandled Exception: System.ArgumentException: The node to be inserted is from a different document context.
   at System.Xml.XmlNode.AppendChild(XmlNode newChild)

So, this is how you have to do it:

1
2
3
4
5
6
7
8
9
10
11
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(@"<hello>
                         <world>Test</world>
                       </hello>");
 
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(@"<hello>
                       </hello>");
 
XmlNode copiedNode = doc2.ImportNode(doc1.SelectSingleNode("/Hello/World"), true);
doc2.DocumentElement.AppendChild(copiedNode);

The magic method which needs to be used here is ImportNode

DeliciousTwitterFacebookLinkedInRedditSlashdotTechnorati FavoritesDiggShare
Posted in C# | 6 Comments