<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Martin Normark's blog</title>
	
	<link>http://martinnormark.com</link>
	<description />
	<lastBuildDate>Thu, 05 Jan 2012 18:51:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/martinnormark" /><feedburner:info uri="martinnormark" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><image><link>http://creativecommons.org/licenses/by/3.0/</link><url>http://creativecommons.org/images/public/somerights20.gif</url><title>Some Rights Reserved</title></image><feedburner:emailServiceId>martinnormark</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>ASP.NET MVC 3 Windows Authentication problem – redirects to Account/Login</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/LMAmxoFfn7I/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login</link>
		<comments>http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login#comments</comments>
		<pubDate>Sun, 06 Nov 2011 15:45:19 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[quirks]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=342</guid>
		<description><![CDATA[ASP.NET MVC 3 has its quirkiness here and there. Sometimes it's a lack of support for something, and other times it's downright buggy. An issue I came across recently, is something to do with Windows Authentication. There's a lot of resource on &#8230; <p><a class="btn small" href="http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>ASP.NET MVC 3 has its quirkiness here and there. Sometimes it's a lack of support for something, and other times it's downright buggy.</p>
<p>An issue I came across recently, is something to do with Windows Authentication. There's a lot of resource on the web on how to run ASP.NET MVC with Windows Authentication. There's even a project template, the Intranet site, which ships with MVC 3. It should be a no-brainer!</p>
<p>The issue I came across, prevented ASP.NET from using Windows Authentication. Even though I had set authentication mode to Windows in Web.config:</p>
<pre><code>&lt;authentication mode="Windows" /&gt; </code>&lt;authorization&gt;
  &lt;deny users="?" /&gt;
&lt;/authorization&gt;</pre>
<p>And disabled anonymous authentication on the website in IIS - it always redirected all requests to <em>/Account/Login</em>, as if it was using some sort of default Forms Authentication.</p>
<p>This coursed a server error - the dreaded Yellow Screen of Death, since I didn't have a login form on my site, I had no controller/action for Account/Login.</p>
<h2>Known issue</h2>
<p>After searching the web for a while, I came across the <a href="http://www.asp.net/learn/whitepapers/mvc3-release-notes">release notes</a> on the ASP.NET MVC website. At the bottom, there's a section called '<a href="http://www.asp.net/learn/whitepapers/mvc3-release-notes#0.1__Toc274034230">Known issues</a>', and one of the last issues reads:</p>
<blockquote><p>There’s a known issue that causes Forms Authentication to always redirect unauthenticated users to ~/Account/Login, ignoring the forms authentication setting used in Web.config. The workaround is to add the following app setting.</p>
<pre>      &lt;add key="autoFormsAuthentication" value="false" /&gt;</pre>
</blockquote>
<p>And much to my disappointment, this didn't do the trick! Long story short, it turned out that I needed another setting as well, as pointed out in the comment of <a href="http://stackoverflow.com/questions/4078525/problem-exclusively-using-windows-authentication-in-asp-net-mvc-3-beta">this Stackoverflow question</a>:</p>
<pre>&lt;add key="enableSimpleMembership" value="false"/&gt;</pre>
<p>After adding the magic settings to my Web.config, everything worked as it should - and Windows Authentication on ASP.NET MVC <em>is</em> now a no-brainer!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/OT-HE5hq41mKqu4k79tYJXnu8bM/0/da"><img src="http://feedads.g.doubleclick.net/~a/OT-HE5hq41mKqu4k79tYJXnu8bM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/OT-HE5hq41mKqu4k79tYJXnu8bM/1/da"><img src="http://feedads.g.doubleclick.net/~a/OT-HE5hq41mKqu4k79tYJXnu8bM/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/LMAmxoFfn7I" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Make CSS inline in C# and ASP.NET using PreMailer.Net</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/XVxT5n7r1eE/move-css-inline-premailer-net</link>
		<comments>http://martinnormark.com/move-css-inline-premailer-net#comments</comments>
		<pubDate>Fri, 10 Jun 2011 09:58:55 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[E-mail]]></category>
		<category><![CDATA[HTML]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=251</guid>
		<description><![CDATA[Being able to make CSS inline is something you need all the time when sending HTML e-mails. HTML E-mails simply don't render perfectly in all e-mail clients if you don't make all your styles inline. Campaign Monitor introduced the ability &#8230; <p><a class="btn small" href="http://martinnormark.com/move-css-inline-premailer-net">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Being able to make CSS inline is something you need all the time when sending HTML e-mails. HTML E-mails simply don't render perfectly in all e-mail clients if you don't make all your styles inline.</p>
<p>Campaign Monitor introduced the <a href="http://www.campaignmonitor.com/blog/post/2406/huge-time-saver-automatic-inli/">ability to make CSS inline years ago</a>, and it just works. They use the <a href="https://github.com/alexdunae/premailer">premailer Ruby project</a> to do this, and it seems to work perfectly. You can edit your HTML e-mails using styles embedded inside the HTML document's &lt;head&gt; tag, and they automatically make the CSS inline on all elements that match your selectors.</p>
<p>At the end of my latest blog post on How to <a title="How to Send HTML E-mail from an ASP.NET MVC Controller" href="http://martinnormark.com/actionmailer-net-html-email">Send HTML E-mail from an ASP.NET MVC Controller</a>, I wrote that I'd like to combine the ActionMailer.Net library with the <a href="https://github.com/alexdunae/premailer">premailer Ruby project</a>, to be able to send great HTML e-mails from an application, that renders well in all e-mail clients.</p>
<p>I honestly didn't want to combine ASP.NET MVC with a Ruby project. I can't image all <a href="http://www.kevinblake.co.uk/executing-complete-ironruby-scripts-from-within-native-c-net/624/">the hacks necessary to make it work</a>. Eventually, I'd probably start a process from ASP.NET that<a href="http://stackoverflow.com/questions/2285288/calling-a-ruby-script-in-c"> runs the Ruby script</a> - but it's still a hack in my opinion.</p>
<p>That made me search the .Net community to see if I could find anything similar for .Net, but I didn't succeed. But instead I found two interesting things:</p>
<ul>
<li>A <a href="http://blog.dynamicprogrammer.com/2008/01/20/CSSParserClassInNET.aspx">CSS Parser for .NET</a> (by The Dynamic Programmer).</li>
<li>A <a href="http://code.google.com/p/fizzler/">.Net CSS Selector Engine</a>, called Fizzler.</li>
</ul>
<p>And that is exactly what it takes to make CSS inline. I added code to the CSS parser, so that it would merge the style block, if an element already had inline styles specified, and packed the two project into my own solution, called <a href="https://github.com/milkshakesoftware/PreMailer.Net">PreMailer.NET</a>.</p>
<p>It works like this:</p>
<pre class="prettyprint linenums">
string htmlSource = File.ReadAllText(@"C:\Workspace\testmail.html");
PreMailer pm = new PreMailer();
string premailedOutput = pm.MoveCssInline(htmlSource, false);
</pre>
<p>The premailedOutput variable contains e-mail mark-up ready to send.</p>
<p>For more information on how to create HTML E-mails, check out the <a href="http://htmlemailboilerplate.com/">HTML E-mail Boilerplate</a>, and Campaign Monitor's <a href="http://www.campaignmonitor.com/blog/tips-resources/">blog</a>, and <a href="http://www.campaignmonitor.com/resources/">resources</a> section.</p>
<div style="text-align: center;"><a title="Email Marketing" href="http://aweber.com/?377622"><br />
<img style="border: none;" src="http://www.aweber.com/banners/newsletter_design/468x60_an.gif" alt="Leave the Pain of Newsletter Design To Us - AWeber Email Marketing" /></a></div>

<p><a href="http://feedads.g.doubleclick.net/~a/y3NLOzhuLuioZA1HjybJj_PNT0c/0/da"><img src="http://feedads.g.doubleclick.net/~a/y3NLOzhuLuioZA1HjybJj_PNT0c/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/y3NLOzhuLuioZA1HjybJj_PNT0c/1/da"><img src="http://feedads.g.doubleclick.net/~a/y3NLOzhuLuioZA1HjybJj_PNT0c/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/XVxT5n7r1eE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/move-css-inline-premailer-net/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/move-css-inline-premailer-net?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>How to Send HTML E-mail from an ASP.NET MVC Controller</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/6v15F5nyzSQ/actionmailer-net-html-email</link>
		<comments>http://martinnormark.com/actionmailer-net-html-email#comments</comments>
		<pubDate>Sat, 02 Apr 2011 22:04:54 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[email]]></category>

		<guid isPermaLink="false">http://martinnormark.com/actionmailer-net-html-email</guid>
		<description><![CDATA[As I argued about a year ago, any modern piece of software needs to send e-mail. It needs to connect, and reach its users. Back then I showed how to send templated HTML e-mail, using the little known MailDefinition class &#8230; <p><a class="btn small" href="http://martinnormark.com/actionmailer-net-html-email">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>As I argued about a year ago, any <strong>modern piece of software needs </strong><a href="http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates"><strong>to send e-mail</strong></a>. It needs to connect, and reach its users. Back then I showed <a href="http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates">how to send templated HTML e-mail</a>, using the little known MailDefinition class in C#.</p>
<p>Today, there’s an even better approach. The main problem with the old solution, was that the templates were plain, old, flat and boring HTML templates. Any sort of dynamic content, were limited to what a simple replace could do.</p>
<p>The better approach that I’m using now, is the awesome <a href="https://bitbucket.org/swaj/actionmailer.net/wiki/Home">ActionMailer.NET</a> package. It’s right there within Visual Studio, if you have <a href="http://nuget.codeplex.com/">Nuget</a> – which I’m sure you do.</p>
<h2>Why is it better?</h2>
<p><a href="https://bitbucket.org/swaj/actionmailer.net/wiki/Home">ActionMailer.NET</a> is better, first of all because the templates for your e-mails are just <strong>regular ASP.NET MVC views</strong>. That means you can strongly type those view and supply it with a model. All the stuff you can do in an ASP.NET MVC View (Razor or WebForms – your choice) – you can now send via E-mail.</p>
<h2>It’s very easy to use</h2>
<p>You simply start by creating a new Controller in your ASP.NET MVC web application that will take care of sending all the e-mails. Along with the controller, you add a folder for the views.</p>
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> MailController : MailerBase
{
    <span class="kwrd">public</span> EmailResult VerificationEmail(User model)
    {
        To.Add(model.EmailAddress);
        From = <span class="str">&quot;Martin Normark &lt;mysite@email.com&gt;&quot;</span>;
        Subject = <span class="str">&quot;Welcome to My Blog!&quot;</span>;

        <span class="kwrd">return</span> Email(<span class="str">&quot;VerificationEmail&quot;</span>, model);
    }
}</pre>
<style type="text/css">
.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; }</style>
<p>Notice how you can set the from name, as well as the e-mail address. Neat stuff. If you want to do something just before or after an e-mail is sent, you can play around with the OnMailSending and OnMailSent by overriding the default implementation.</p>
<pre class="csharpcode"><span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnMailSending(MailSendingContext context)
{
    <span class="kwrd">base</span>.OnMailSending(context);
}

<span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> OnMailSent(System.Net.Mail.MailMessage mail)
{
    <span class="kwrd">base</span>.OnMailSent(mail);
}
<style type="text/css">.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; }
</style>
</pre>
<p>Maybe you want to save the e-mail in your database for future reference, logging etc.</p>
<p>One thing I’ll do one day, is combine this with the <a href="https://github.com/alexdunae/premailer">premailer Ruby project</a>, that optimizes your HTML e-mails for rendering in e-mail clients, by moving your CSS inline.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/KK_oKArmn2scza3B-fWNoT1XQ-A/0/da"><img src="http://feedads.g.doubleclick.net/~a/KK_oKArmn2scza3B-fWNoT1XQ-A/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/KK_oKArmn2scza3B-fWNoT1XQ-A/1/da"><img src="http://feedads.g.doubleclick.net/~a/KK_oKArmn2scza3B-fWNoT1XQ-A/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/6v15F5nyzSQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/actionmailer-net-html-email/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/actionmailer-net-html-email?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Serialize C# dynamic and Anonymous types to XML</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/8F-ng53Q8Dg/serialize-c-dynamic-and-anonymous-types-to-xml</link>
		<comments>http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml#comments</comments>
		<pubDate>Thu, 03 Feb 2011 16:50:06 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[anonymous type]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[serialize]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=171</guid>
		<description><![CDATA[Dynamic / Anonymous types in C# was a great improvement to the framework, made in version 3.0. I use it a lot when doing AJAX callbacks from JavaScript to ASP.NET MVC Controllers, not to forget the extensive use of anonymous &#8230; <p><a class="btn small" href="http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p><strong>Dynamic / Anonymous types in C#</strong> was a great improvement to the framework, made in version 3.0. I use it a lot when doing <strong>AJAX callbacks from JavaScript</strong> to ASP.NET MVC Controllers, not to forget the extensive use of anonymous types <strong>already used in ASP.NET MVC</strong>.</p>
<p>Then yesterday, one case where I absolutely needed to use anonymous types was in my application’s logging service. I want to be able to save behaviors/actions as well as errors. I have two separate tables, but both behaviors and errors can provide a <strong>set of details</strong>.  To do the actual logging, I call an implementation of this interface:</p>
<pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Defines methods for logging errors and behavior.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    [ServiceContract]
    <span class="kwrd">public</span> <span class="kwrd">interface</span> ILogService
    {
        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Logs the behavior with data.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name="applicationInstanceId"&gt;The application instance id.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="action"&gt;The action.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="logDate"&gt;The log date.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="userAgent"&gt;The user agent.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="behaviorData"&gt;The behavior data.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="source"&gt;The source.&lt;/param&gt;</span>
        [OperationContract]
        <span class="kwrd">void</span> LogBehaviorWithData(<span class="kwrd">int</span> applicationInstanceId, <span class="kwrd">string</span> action, DateTime logDate, <span class="kwrd">string</span> userAgent, <span class="kwrd">string</span> behaviorData, <span class="kwrd">string</span> source);

        <span class="rem">/// &lt;summary&gt;</span>
        <span class="rem">/// Logs the behavior.</span>
        <span class="rem">/// &lt;/summary&gt;</span>
        <span class="rem">/// &lt;param name="applicationInstanceId"&gt;The application instance id.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="action"&gt;The action.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="logDate"&gt;The log date.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="userAgent"&gt;The user agent.&lt;/param&gt;</span>
        <span class="rem">/// &lt;param name="source"&gt;The source.&lt;/param&gt;</span>
        [OperationContract]
        <span class="kwrd">void</span> LogBehavior(<span class="kwrd">int</span> applicationInstanceId, <span class="kwrd">string</span> action, DateTime logDate, <span class="kwrd">string</span> userAgent, <span class="kwrd">string</span> source);
    }</pre>
<p><!-- .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; } -->In the <strong>LogBehaviorWithData</strong> method, I wanted to specify <strong>behaviorData</strong> as <strong>XML</strong>, since the column in the database is an <strong>XML column</strong>. I do this, so that I’m able to query the table and using <strong>XPath</strong> to filter on behavior data.  That requires me to send XML to the method, and I don’t want to fool around manually with an <strong>XmlDocument</strong> or something similar.</p>
<p>I was looking around the internet for a way to <strong>serialize an anonymous type to XML</strong>, and came across a few questions on <a href="http://stackoverflow.com/">StackOverflow</a>. The <a href="http://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml">first one accepted there’s no way</a> to do that – even though there was <a href="http://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml/2404984#2404984">a fine answer</a> below, and <a href="http://stackoverflow.com/questions/3494605/is-there-any-way-to-xml-serialize-an-anonymous-type-in-net-using-c">the second didn’t provide a solution</a>.  I took the code provided by <a href="http://stackoverflow.com/users/89586/matthew-whited">Matthew Whited</a> in his <a href="http://stackoverflow.com/questions/2404685/can-i-serialize-anonymous-types-as-xml/2404984#2404984">excellent answer</a> (that I don’t believe is not the correct answer of the question).  It worked out of the box, except for Arrays, so that needed some extensions.</p>
<h2>How to use it</h2>
<p>It’s <strong>simply an </strong><a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx"><strong>Extension Method</strong></a> of the object type, <strong>called ToXml().</strong> And it is used like this:</p>
<pre class="csharpcode"><span class="kwrd">object</span> d = <span class="kwrd">new</span>
{
    Username = <span class="str">"martin"</span>,
    Roles = <span class="kwrd">new</span>[]
    {
        <span class="str">"Developer"</span>,
        <span class="str">"Administrator"</span>
    }
};

XElement xml = d.ToXml();
<span class="kwrd">string</span> xmlString = xml.ToString();</pre>
<p>The output is a <strong>beautifully formatted</strong> XML string:</p>
<pre class="csharpcode"><span class="kwrd">&lt;</span><span class="html">object</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Username</span><span class="kwrd">&gt;</span>martin<span class="kwrd">&lt;/</span><span class="html">Username</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;</span><span class="html">Roles</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">RolesChild</span><span class="kwrd">&gt;</span>Developer<span class="kwrd">&lt;/</span><span class="html">RolesChild</span><span class="kwrd">&gt;</span>
    <span class="kwrd">&lt;</span><span class="html">RolesChild</span><span class="kwrd">&gt;</span>Administrator<span class="kwrd">&lt;/</span><span class="html">RolesChild</span><span class="kwrd">&gt;</span>
  <span class="kwrd">&lt;/</span><span class="html">Roles</span><span class="kwrd">&gt;</span>
<span class="kwrd">&lt;/</span><span class="html">object</span><span class="kwrd">&gt;</span></pre>
<pre class="csharpcode"><span class="kwrd"> </span></pre>
<p>To make it more <strong>database friendly</strong>, you can <strong>omit the formatting</strong> by specifying <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.saveoptions.aspx">SaveOptions</a> in the ToString method call:</p>
<pre class="csharpcode"><span class="kwrd">string</span> xmlString = xml.ToString(SaveOptions.DisableFormatting);</pre>
<pre class="csharpcode"><!-- .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; } --></pre>
<h2>The actual code</h2>
<p>The actual code is quite simple, yet there’s some fiddling around with different types and such. I guess the <strong>name of child elements</strong> could also <strong>need some improvement</strong>, preferably changing the collection name to a<strong> singular representation</strong> and use that as the element name of its children.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Linq;
<span class="kwrd">using</span> System.Reflection;
<span class="kwrd">using</span> System.Xml;
<span class="kwrd">using</span> System.Xml.Linq;

<span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Extension methods for the dynamic object.</span>
<span class="rem">/// &lt;/summary&gt;</span>
<span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> DynamicHelper
{
    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Defines the simple types that is directly writeable to XML.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> <span class="kwrd">readonly</span> Type[] _writeTypes = <span class="kwrd">new</span>[] { <span class="kwrd">typeof</span>(<span class="kwrd">string</span>), <span class="kwrd">typeof</span>(DateTime), <span class="kwrd">typeof</span>(Enum), <span class="kwrd">typeof</span>(<span class="kwrd">decimal</span>), <span class="kwrd">typeof</span>(Guid) };

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Determines whether [is simple type] [the specified type].</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="type"&gt;The type to check.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;</span>
    <span class="rem">///     &lt;c&gt;true&lt;/c&gt; if [is simple type] [the specified type]; otherwise, &lt;c&gt;false&lt;/c&gt;.</span>
    <span class="rem">/// &lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> IsSimpleType(<span class="kwrd">this</span> Type type)
    {
        <span class="kwrd">return</span> type.IsPrimitive || _writeTypes.Contains(type);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Converts an anonymous type to an XElement.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="input"&gt;The input.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;Returns the object as it's XML representation in an XElement.&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> XElement ToXml(<span class="kwrd">this</span> <span class="kwrd">object</span> input)
    {
        <span class="kwrd">return</span> input.ToXml(<span class="kwrd">null</span>);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Converts an anonymous type to an XElement.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="input"&gt;The input.&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="element"&gt;The element name.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;Returns the object as it's XML representation in an XElement.&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> XElement ToXml(<span class="kwrd">this</span> <span class="kwrd">object</span> input, <span class="kwrd">string</span> element)
    {
        <span class="kwrd">if</span> (input == <span class="kwrd">null</span>)
        {
            <span class="kwrd">return</span> <span class="kwrd">null</span>;
        }

        <span class="kwrd">if</span> (String.IsNullOrEmpty(element))
        {
            element = <span class="str">"object"</span>;
        }

        element = XmlConvert.EncodeName(element);
        var ret = <span class="kwrd">new</span> XElement(element);

        <span class="kwrd">if</span> (input != <span class="kwrd">null</span>)
        {
            var type = input.GetType();
            var props = type.GetProperties();

            var elements = from prop <span class="kwrd">in</span> props
                                         let name = XmlConvert.EncodeName(prop.Name)
                                         let val = prop.PropertyType.IsArray ? <span class="str">"array"</span> : prop.GetValue(input, <span class="kwrd">null</span>)
                                         let <span class="kwrd">value</span> = prop.PropertyType.IsArray ? GetArrayElement(prop, (Array)prop.GetValue(input, <span class="kwrd">null</span>)) : (prop.PropertyType.IsSimpleType() ? <span class="kwrd">new</span> XElement(name, val) : val.ToXml(name))
                                         <span class="kwrd">where</span> <span class="kwrd">value</span> != <span class="kwrd">null</span>
                                         select <span class="kwrd">value</span>;

            ret.Add(elements);
        }

        <span class="kwrd">return</span> ret;
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Gets the array element.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="info"&gt;The property info.&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="input"&gt;The input object.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;Returns an XElement with the array collection as child elements.&lt;/returns&gt;</span>
    <span class="kwrd">private</span> <span class="kwrd">static</span> XElement GetArrayElement(PropertyInfo info, Array input)
    {
        var name = XmlConvert.EncodeName(info.Name);

        XElement rootElement = <span class="kwrd">new</span> XElement(name);

        var arrayCount = input.GetLength(0);

        <span class="kwrd">for</span> (<span class="kwrd">int</span> i = 0; i &lt; arrayCount; i++)
        {
            var val = input.GetValue(i);
            XElement childElement = val.GetType().IsSimpleType() ? <span class="kwrd">new</span> XElement(name + <span class="str">"Child"</span>, val) : val.ToXml();

            rootElement.Add(childElement);
        }

        <span class="kwrd">return</span> rootElement;
    }
}</pre>
<p>That way it is possible to serialize an anonymous type in C# to XML.</p>
<h2>Download</h2>
<p><a href="http://cid-146a3db7b364e824.office.live.com/self.aspx/Public/DynamicHelper.cs" target="_blank">Download the class from my SkyDrive</a>.</p>
<p><!-- .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; } --></p>

<p><a href="http://feedads.g.doubleclick.net/~a/_Hr6xgI-lR7RuraEr6wXGTujRJU/0/da"><img src="http://feedads.g.doubleclick.net/~a/_Hr6xgI-lR7RuraEr6wXGTujRJU/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/_Hr6xgI-lR7RuraEr6wXGTujRJU/1/da"><img src="http://feedads.g.doubleclick.net/~a/_Hr6xgI-lR7RuraEr6wXGTujRJU/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/8F-ng53Q8Dg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Making your ASP.NET Global Resource files work in JavaScript. IntelliSense included!</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/VGCMqH-idZM/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included</link>
		<comments>http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included#comments</comments>
		<pubDate>Mon, 15 Nov 2010 15:22:20 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Internationalization]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=56</guid>
		<description><![CDATA[Any modern web application needs localization! You simply can't ignore the huge amounts of people who doesn't speak your language, or whose native language is different from yours. You're probably using resource files (.resx) in .NET, but how do you &#8230; <p><a class="btn small" href="http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Any modern web application needs localization! You simply can't ignore the huge amounts of people who doesn't speak your language, or whose native language is different from yours.</p>
<p>You're probably using resource files (.resx) in .NET, but how do you go about getting values from your resource files in JavaScript?</p>
<p><a href="http://www.west-wind.com/Weblog/default.aspx">Rick Strahl</a> wrote a great <a href="http://www.west-wind.com/Weblog/posts/698097.aspx">blog post about an HttpHandler</a> that serves the content of your resource files in JavaScript. You basically add a script tag to your page that points to the HttpHandler, and the HttpHandler will produce the resources in JavaScript as an object with properties on it, like this:</p>
<blockquote><p>
[code lang="js"]var localRes = {<br />
    AreYouSureYouWantToRemoveValue: &quot;Sind Sie sicher dass Sie diesen Wert l\u00F6schen wollen?&quot;,<br />
    BackupComplete: &quot;Der Backup f\u00FChrte erfolgreich durch&quot;,<br />
    BackupFailed: &quot;Der Backup konnte nicht durchgef\u00FChrt werden&quot;,<br />
    BackupNotification: &quot;Diese Operation macht einen Backup von der Lokalisationtabelle. \nM\u00F6chten Sie fortfahren?&quot;,<br />
    Close: &quot;Schliessen&quot;,<br />
    FeatureDisabled: &quot;Diese Funktion ist nicht vorhanden im on-line Demo &quot;,<br />
    InvalidFileUploaded: &quot;Unzul\u00E4ssige Akten Format hochgeladen.&quot;,<br />
    InvalidResourceId: &quot;Unzul\u00E4ssige ResourceId&quot;,<br />
    Loading: &quot;Laden&quot;,<br />
    LocalizationTableCreated: &quot;Lokalisations Akte wurde erfolgreich erstellt.&quot;,<br />
    LocalizationTableNotCreated: &quot;Die Localizations Akte konnte nicht erstellt werden.&quot;<br />
};[/code]</p></blockquote>
<p>This is awesome! Now you can access your resource files from JavaScript. Though, I see a single improvement to be made. The thing I don't like about the HttpHandler approach, is that you don't get IntelliSense support in Visual Studio. So you have to browse your resource file and copy &amp; paste the resource key to your JavaScript files in order for this to work.</p>
<h2>Generate static JavaScript files on Post-build</h2>
<p>Instead of generating dynamic files at runtime, I prefer to generate static JavaScript files and then dynamically include the file of the current language on my pages. I do this by calling a Console Application I’ve written on the Post-build event of my ASP.NET (MVC) project, which you can set in the property pages of your project (By the way, did you know that you can open property pages of a project by double clicking the default Properties folder?):</p>
<p><a href="http://martinnormark.com/wp-content/uploads/2010/11/image1.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://martinnormark.com/wp-content/uploads/2010/11/image_thumb1.png" border="0" alt="image" width="634" height="490" /></a></p>
<p>What my JavascriptResxGenerator App does, is quite messy. But the essence of the App is, of course, to take a single (or several) .resx files and do the following:</p>
<p>1. Loop through all keys.</p>
<p>2. Make sure the key is not a <a href="http://javascript.about.com/library/blreserved.htm">JavaScript reserved word</a>.</p>
<p>3. Add the key and value to a dictionary (in JavaScript).</p>
<p>4. Write the file.</p>
<p>And for the default culture I generate a –vsdoc file, that I can use for Visual Studio IntelliSense.</p>
<h2>Using the JavaScript Resx Generator App</h2>
<p>My App supports a single file approach, and directory approach.</p>
<p><strong>Single file: </strong>JavascriptResxGenerator.exe C:\Folder\Text.resx C:\Output C:\Output\VsDoc MyApp.Namespace.Resources</p>
<p><strong>Directory: </strong>JavascriptResxGenerator.exe C:\Folder C:\Output C:\Output\VsDoc MyApp.Namespace.Resources</p>
<p>The MyApp.Namespace.Resources value, is the namespace your resource dictionary will get enclosed in.</p>
<p><a href="http://martinnormark.com/wp-content/uploads/2010/11/image2.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://martinnormark.com/wp-content/uploads/2010/11/image_thumb2.png" border="0" alt="image" width="634" height="294" /></a></p>
<h2>Embedding the file on your pages</h2>
<p>To include the JavaScript resource file in your page, you simply add a script include tag that points to the correct language. The App will respect the region token used in your Resx files. So if you have a file called Text.da.resx, the JavaScript file generated will include .da.resx at the end. It’s then up to you to add the correct logic to keep hold of the current language and specify the correct region token in order to include the correct JavaScript resource file.</p>
<h2>Download</h2>
<p>You can <a href="http://cid-146a3db7b364e824.office.live.com/self.aspx/Public/JavascriptResxGenerator.zip">download the App here</a>, as a ZIP file.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/5qqv7iZm93qoLkIiR6Ou7CmONHY/0/da"><img src="http://feedads.g.doubleclick.net/~a/5qqv7iZm93qoLkIiR6Ou7CmONHY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/5qqv7iZm93qoLkIiR6Ou7CmONHY/1/da"><img src="http://feedads.g.doubleclick.net/~a/5qqv7iZm93qoLkIiR6Ou7CmONHY/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/VGCMqH-idZM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Translate text in C#, using Google Translate, revisited</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/R01n4PViNOU/translate-text-in-c-using-google-translate-revisited</link>
		<comments>http://martinnormark.com/translate-text-in-c-using-google-translate-revisited#comments</comments>
		<pubDate>Mon, 25 Oct 2010 15:31:49 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Internationalization]]></category>
		<category><![CDATA[Google]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=131</guid>
		<description><![CDATA[A long time ago, I wrote a blog post about how to translate text in C# using Google Translate. Since then, an official AJAX API has been released, which is a much better solution. Reading the comments of the blog &#8230; <p><a class="btn small" href="http://martinnormark.com/translate-text-in-c-using-google-translate-revisited">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>A long time ago, I wrote a blog post about how to <a href="http://martinnormark.com/2009/03/12/translate-text-in-c-using-google-translate">translate text in C# using Google Translate</a>. Since then, an <strong>official AJAX API</strong> has been released, which is a much better solution. Reading the comments of the blog post indicates that the code was broken quite quickly!</p>
<p><a href="http://code.google.com/apis/ajaxlanguage/">Google’s AJAX Language API</a>, also includes functionality to detect language from a given string. All you can do on <a href="http://translate.google.com/">translate.google.com</a> you can do via the API. Reading the <a href="http://code.google.com/apis/ajaxlanguage/documentation/reference.html">class reference for the Translation API</a>, for <a href="http://code.google.com/apis/ajaxlanguage/documentation/reference.html#_intro_fonje">Flash and other Non-Javascript environments</a> gives us the information we need to perform <strong>translations from C#</strong>. Most important is the URL and the parameters required and accepted.</p>
<p>Another <strong>very important thing</strong> we can read in the documentation is this:</p>
<blockquote><p>Applications MUST always include a valid and accurate <a href="http://en.wikipedia.org/wiki/HTTP_referer">http referer header</a> in their requests</p></blockquote>
<p><strong>We must remember to add a valid referrer when making the actual call!</strong></p>
<h2>The response object</h2>
<p>Google’s AJAX Language APIs uses JSON, and returns a JSON object containing 3 properties:</p>
<ul>
<li>responseData</li>
<li>responseDetails</li>
<li>responseStatus</li>
</ul>
<p>This means we need to have some C# objects that we can use to deserialize the JSON returned from Google. I’m using a generic class called GoogleAjaxResponse&lt;T&gt;, with T being the specific class I want the JSON to be deserialized to.</p>
<pre class="csharp">using System.Runtime.Serialization;

namespace Milkshake.Integration.Google
{
	/// Defines a response from one of Google's AJAX APIs.
	/// The type of object, being returned.
	[DataContract]
	public class GoogleAjaxResponse&lt;T&gt;
	{
		///
		/// Gets or sets the response data.
		///
		///
		/// The responseData from Google AJAX API Call
		///
		/// The response data.
		[DataMember(Name = "responseData", Order = 0)]
		public T ResponseData { get; set; }
	}
}</pre>
<p>To deserialize the Translation specific JSON, I use the TranslationResponse class:</p>
<pre class="csharp">using System.Net;
using System.Runtime.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// Defines a response from the Google AJAX Translate API.
	[DataContract]
	public class TranslationResponse
	{
		/// Initializes a new instance of the  class.
		public TranslationResponse()
		{
			this.ResponseStatus = HttpStatusCode.OK;
		}

		/// Gets or sets the translated text.
		/// The translated text.
		[DataMember(Name = "translatedText", Order = 0)]
		public string TranslatedText { get; set; }

		/// Gets or sets the response details.
		/// The response details.
		[DataMember(Name = "responseDetails", Order = 1)]
		public object ResponseDetails { get; set; }

		/// Gets or sets the response status.
		/// The response status.
		[DataMember(Name = "responseStatus", Order = 2)]
		public HttpStatusCode ResponseStatus { get; set; }
	}
}</pre>
<h2>Calling the Google AJAX Translate API</h2>
<p>To make the actual call, we can use the <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx">HttpWebRequest</a> and <a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.aspx">HttpWebResponse</a> classes.</p>
<pre class="csharp">using System;
using System.Globalization;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;

namespace Milkshake.Integration.Google.Translate
{
	/// An API Client for the Google AJAX Translate API.
	public class TranslateApi
	{
		/// The JavaScript serializer
		private JavaScriptSerializer _Serializer = new JavaScriptSerializer();

		/// Translates the text.
<pre>		public string TranslateText(string inputText, string sourceLanguage, string destinationLanguage, string referrer, string apiKey)
		{
			string requestUrl = string.Format("http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&amp;q={0}&amp;langpair={1}|{2}&amp;key={3}", HttpUtility.UrlEncode(inputText), sourceLanguage.ToLowerInvariant(), destinationLanguage.ToLowerInvariant(), apiKey);

			try
			{
				using (HttpClient http = new HttpClient(requestUrl))
				{
					http.AddReferrer(referrer);
					http.ExecuteRequest();

					string responseJson = http.GetResponseString();

					GoogleAjaxResponse&lt;TranslationResponse&gt; translation = this._Serializer.Deserialize&lt;GoogleAjaxResponse&lt;TranslationResponse&gt;&gt;(responseJson);

					if (translation != null &amp;&amp; translation.ResponseData != null &amp;&amp; translation.ResponseData.ResponseStatus == HttpStatusCode.OK)
					{
						return translation.ResponseData.TranslatedText;
					}
					else
					{
						return String.Empty;
					}
				}
			}
			catch
			{
				return String.Empty;
			}
		}
<pre>	}
}</pre>
</pre>
</pre>
<h2>The response JSON and translated text</h2>
<p>Doing a simple test, I translate “Hello world” from English to Danish, and I can see that it works like a charm.</p>
<p><a href="http://martinnormark.com/wp-content/uploads/2010/10/image.png"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="image" src="http://martinnormark.com/wp-content/uploads/2010/10/image_thumb.png" border="0" alt="image" width="628" height="273" /></a></p>
<p>
<strong>Professional translations - even via API!</strong><br />
<a href="http://www.onehourtranslation.com/affiliate/martinnormark"><img src="http://www.onehourtranslation.com/public/images/banners/set2/translation-services-468x49.jpg" alt="translation agency" border="0"></a></p>

<p><a href="http://feedads.g.doubleclick.net/~a/ZHh16rI4dAYZIoGTjavRrrPI2E8/0/da"><img src="http://feedads.g.doubleclick.net/~a/ZHh16rI4dAYZIoGTjavRrrPI2E8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ZHh16rI4dAYZIoGTjavRrrPI2E8/1/da"><img src="http://feedads.g.doubleclick.net/~a/ZHh16rI4dAYZIoGTjavRrrPI2E8/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/R01n4PViNOU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/translate-text-in-c-using-google-translate-revisited/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/translate-text-in-c-using-google-translate-revisited?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>The (almost) Ultimate Developer PC 2.0</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/9wRl-_TgRGA/the-almost-ultimate-developer-pc-2-0</link>
		<comments>http://martinnormark.com/the-almost-ultimate-developer-pc-2-0#comments</comments>
		<pubDate>Sat, 31 Jul 2010 08:59:00 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[Hardware]]></category>

		<guid isPermaLink="false">http://martinnormark.com/2010/07/31/the-almost-ultimate-developer-pc-2-0</guid>
		<description><![CDATA[There’s a lot of talk on Twitter and blogs about The Ultimate Developer PC 2.0. The Ultimate Developer PC, was something started three years ago by Scott Hanselman and Jeff Atwood, when Scott wanted a new machine and went for &#8230; <p><a class="btn small" href="http://martinnormark.com/the-almost-ultimate-developer-pc-2-0">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>There’s a lot of </span><a href="http://search.twitter.com/search?q=&amp;ands=Ultimate+Developer+PC+2.0&amp;phrase=&amp;ors=&amp;nots=&amp;tag=&amp;lang=all&amp;from=&amp;to=&amp;ref=&amp;near=&amp;within=15&amp;units=mi&amp;since=&amp;until=2010-07-31&amp;rpp=15">talk on Twitter</a> and blogs about <a href="http://www.hanselman.com/blog/UltimateDeveloperPC20Part1BuildingAWEI79AndRFCForBuildingAGOMGodsOwnMachine.aspx">The</a> <a href="http://www.hanselman.com/blog/UltimateDeveloperPC20Part2UPDATEAndPODCASTOnBuildingAWEI79AndRFCForBuildingAGOMGodsOwnMachine.aspx">Ultimate</a> <a href="http://www.hanselman.com/blog/UltimateDeveloperPC20Part3UPDATEOnBuildingAWEI79AndRFCForBuildingAGOMGodsOwnMachine.aspx">Developer</a> <a href="http://10rem.net/blog/2010/07/28/the-ultimate-developer-machine-20">PC</a> <a href="http://10rem.net/blog/2010/07/30/last-nights-ultimate-pc-live-bench-build">2.0</a>. The Ultimate Developer PC, was something started three years ago by <a href="http://twitter.com/shanselman">Scott Hanselman</a> and <a href="http://twitter.com/codinghorror">Jeff Atwood</a>, when Scott wanted a new machine and went for the best of the best. <a href="http://www.codinghorror.com/blog/2007/07/building-a-pc-part-i.html">Jeff Atwood came up with</a> his take, known as <a href="http://www.hanselman.com/blog/TheCodingHorrorUltimateDeveloperRigThrowdownPart2.aspx">The Coding Horror Ultimate Developer Rig</a>.</p>
<p>The same story goes for The Ultimate Developer PC 2.0, only that now it’s Scott Hanselman and Pete Brown building their new machines with an obession of having to achieve a 7.9 score on the Windows Experience Index (WEI).</p>
<p>Back in August 2007 with The Ultimate Developer PC 1.0, Scott Hanselman <a href="http://www.hanselman.com/blog/GoneQuadDay0WithTheUltimateDeveloperPC.aspx">achieved a WEI of 5.8</a>. I guess what started the 7.9 WEI obsession, is the <a href="http://weishare.cloudapp.net/">WEI Share</a> website where you can show off your score, and throw down your parts list. Great idea.</p>
<h2>Is it worth spending $3,168, to get WEI 7.9?</h2>
<p>Looking at Scott Hanselman’s</span> purchase, it totals $3,168. That’s a lot, but if you do get value for money – that is awesome. I have no problem with that!</p>
<p>But how much value are you really getting for the last $1,000? Could you make a PC that was almost as powerful for $2,000?</p>
<p>I built my machine back in <strong>November 2009</strong>. I had one goal: To built a kick ass machine, that didn’t break the bank completely. I’m not a gamer. I have an XBOX 360 for that. I do pick up a game occasionally, though, Starcraft 2 is in my thoughts – but I resist. Modern Warfare 2 has been lying on my PC unopened for almost two months now.</p>
<p>The video card must be able to power up my <a href="http://accessories.us.dell.com/sna/products/Displays/productdetail.aspx?c=us&amp;l=en&amp;s=dhs&amp;cs=19&amp;sku=223-4890">Dell 30” primary monitor</a>, and my <a href="http://accessories.us.dell.com/sna/products/Displays/productdetail.aspx?c=us&amp;l=en&amp;s=dhs&amp;cs=19&amp;sku=320-8277">Dell 24” secondary monitor</a>, without long wait times for repainting and such.</p>
<p>Here goes my parts lists including the current price found at NewEgg.com:</p>
<ul>
<li>Case: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16811129061&amp;Tpk=antec%20p183">Antec P183 Aluminum</a>.<br />
$154.99</li>
<li>PSU: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16817139005&amp;cm_re=corsair_650-_-17-139-005-_-Product">CORSAIR CMPSU-650TX 650W</a><br />
$89.99</li>
<li>Motherboard: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16813188049&amp;Tpk=evga%20x58%20sli%20le">EVGA X58 SLI LE</a><br />
$199.99</li>
<li>CPU: Intel Core i7 Quad Processor i7-920 (not on NewEgg today)<br />
Price back then: ~$300</li>
<li>Cooler: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16835242001&amp;Tpk=megahalems">Prolimatech Megahalems Rev.B</a><br />
$62.00</li>
<li>Memory: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16820145292&amp;cm_re=Corsair_Dominator_ddr3_6GB-_-20-145-292-_-Product">CORSAIR DOMINATOR-GT 6GB (3 x 2GB) 240-Pin DDR3 SDRAM DDR3 1866</a><br />
$229.99</li>
<li>SSD: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16820167017&amp;cm_re=intel_ssd-_-20-167-017-_-Product">Intel X25-M Mainstream SSDSA2M160G2XXX 2.5" 160GB SATA II MLC</a><br />
$424.99</li>
<li>Video card: <a href="http://www.newegg.com/Product/Product.aspx?Item=N82E16814150436&amp;Tpk=xfx%20hd%204870">XFX Radeon HD 4870 1GB</a><br />
$144.99</li>
</ul>
<p><span style="font-size: small;"><strong>That totals</strong></span>: <span style="font-size: large;"><strong><span style="text-decoration: underline;">$1,606.99</span></strong></span> – nearly half the price compared to Scott’s purchase.</p>
<h2>Yeah – but what about the WEI score?</h2>
<p>Remember the point of The Ultimate Developer PC 2.0 was to get a 7.9 WEI score? That cost $3,168?</p>
<p>So, what score does a machine for half the price get on the Windows Experience Index:</p>
<p><a href="http://martinnormark.com/wp-content/uploads/2010/07/image.png"><img class="wlDisabledImage" style="display: inline; border: 0px;" title="image" src="http://martinnormark.com/wp-content/uploads/2010/07/image_thumb.png" border="0" alt="image" width="615" height="500" /></a></p>
<h2>What about gaming?</h2>
<p>I mentioned earlier, that Modern Warfare 2 has been lying on my case for 2 months. Not anymore, I installed it to see how well this machine would do. Remember, it's a &lt;$150 video card, and I'm still able to spin up MW2 in 2560 x 1600 with full details enabled. I recorded a video on my phone, and uploaded it to YouTube. Check it out here:</p>
<p><a href="http://www.youtube.com/watch?v=_s-gBpJk6n8">www.youtube.com/watch?v=_s-gBpJk6n8</a></p>
<h2>Conclusion</h2>
<p>I think that is a pretty good achievement. And remember that these parts are from November 2009! I didn’t pick the newest parts at that time, basically because I think you get a lot more value for money by picking parts that has been released for a month or two.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/ioGHbMU5pjQpYLTrQehanQHUvi8/0/da"><img src="http://feedads.g.doubleclick.net/~a/ioGHbMU5pjQpYLTrQehanQHUvi8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ioGHbMU5pjQpYLTrQehanQHUvi8/1/da"><img src="http://feedads.g.doubleclick.net/~a/ioGHbMU5pjQpYLTrQehanQHUvi8/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/9wRl-_TgRGA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/the-almost-ultimate-developer-pc-2-0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/the-almost-ultimate-developer-pc-2-0?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Generate HTML e-mail body in C# using templates</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/TB_y2Nun28g/generate-html-e-mail-body-in-c-using-templates</link>
		<comments>http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates#comments</comments>
		<pubDate>Sat, 13 Mar 2010 23:42:00 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Hidden features of .NET]]></category>

		<guid isPermaLink="false">/post/Generate-HTML-e-mail-body-in-C-using-templates.aspx</guid>
		<description><![CDATA[Almost a year ago, I answered a question on StackOverflow, about if there’s a better way to generate HTML e-mails in C# than using a StringBuilder and just appending strings one by one. I think that any modern piece of &#8230; <p><a class="btn small" href="http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Almost a year ago, I <a href="http://stackoverflow.com/questions/886728/generating-html-email-body-in-c/886750#886750">answered</a> a <a href="http://stackoverflow.com/questions/886728/generating-html-email-body-in-c">question</a> on <a href="http://stackoverflow.com/">StackOverflow</a>, about if there’s a <a href="http://stackoverflow.com/questions/886728/generating-html-email-body-in-c/886750#886750">better way to generate HTML e-mails in C#</a> than using a <a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder(VS.100).aspx">StringBuilder</a> and just appending strings one by one.</p>
<p>I think that any modern piece of software today, needs to send e-mail. Whether it being password recovery e-mails, rich reports, newsletters or anything else – being able to easily see and customize the look and feel of your e-mails is vital.</p>
<p>So, the worst way I could think of is having your HTML hidden away in some StringBuilder.Append() hell. The best solution (in my opinion) would be, if you could have plain old HTML files with parameters like &lt;#FirstName#&gt; so you could dynamically replace those at runtime.</p>
<h1>The MailDefinition class</h1>
<p>Luckily, there’s a class for that! If you read the comments on my answer on <a href="http://stackoverflow.com/">StackOverflow</a>, you’ll notice that none of them was familiar with that class and it came as a bit of a surprise. It did for me too, I actually wrote my own “<a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition(VS.100).aspx">MailDefinition</a>” class that did just about the same thing. A complete waste of time, and it only tells me that us, developers, are sometimes too trigger happy on the keyboard instead of doing some research first. A quick search in the <a href="http://msdn.microsoft.com/en-us/library/ms229335(VS.100).aspx">MSDN documentation</a> would have saved me some work here and there.</p>
<p>Using the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition(VS.100).aspx">MailDefinition</a> class is pretty straight forward. You use the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition(VS.100).aspx">MailDefinition</a> class to create an instance of <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage(VS.100).aspx">MailMessage</a>, which you can send straightaway:</p>
<pre name="code" class="csharp">
MailDefinition md = new MailDefinition();
md.From = "test@domain.com";
md.IsBodyHtml = true;
md.Subject = "Test of MailDefinition";

ListDictionary replacements = new ListDictionary();
replacements.Add("<%Name%>", "Martin");
replacements.Add("<%Country%>", "Denmark");

string body = "<html><head></head><body>
<div>Hello <b><%Name%></b>

You're from <%Country%>.</div>

</body></html>";

MailMessage msg = md.CreateMailMessage("you@anywhere.com", replacements, body, new System.Web.UI.Control());
</pre>
<p>Instead of having the HTML inside the code, you could easily have it in your database or as a file on the computer. That will also enable you to edit the look and feel of the HTML template at any time, without having to rebuild and deploy your application.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition(VS.100).aspx">MailDefinition</a> is located in the <strong>System.Web assembly</strong>, so don’t forget to add reference to that from your project.</p>

<p><a href="http://feedads.g.doubleclick.net/~a/_4eQSKbuXB3QTZyjAf8U0PZoEcQ/0/da"><img src="http://feedads.g.doubleclick.net/~a/_4eQSKbuXB3QTZyjAf8U0PZoEcQ/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/_4eQSKbuXB3QTZyjAf8U0PZoEcQ/1/da"><img src="http://feedads.g.doubleclick.net/~a/_4eQSKbuXB3QTZyjAf8U0PZoEcQ/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/TB_y2Nun28g" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>IISAPP equivalent in IIS 7 and beyond</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/MENMxgY8lR4/iisapp-equivalent-in-iis-7-and-beyond</link>
		<comments>http://martinnormark.com/iisapp-equivalent-in-iis-7-and-beyond#comments</comments>
		<pubDate>Mon, 08 Mar 2010 23:53:00 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[IIS7]]></category>

		<guid isPermaLink="false">/post/IISAPP-equivalent-in-IIS-7-and-beyond.aspx</guid>
		<description><![CDATA[If there’s one change I hate about IIS 7 and beyond, it is the lack of the very useful IISAPP script that was present on IIS 6 installations. Run it from a command prompt, and you will see a list &#8230; <p><a class="btn small" href="http://martinnormark.com/iisapp-equivalent-in-iis-7-and-beyond">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>If there’s one change I hate about IIS 7 and beyond, it is the lack of the very useful IISAPP script that was present on IIS 6 installations.</p>
<p>Run it from a command prompt, and you will see a list of all running worker processes, the process id and the application pool name the process is serving. Very useful if you need to shut down a single site.</p>
<p>As I mentioned, that script was removed in IIS 7 and beyond. I find myself constantly running IISAPP without any luck several times a week, and I’ve decided that this is a habit that I cannot leave behind.</p>
<p>So, to solve the problem I’ve created a small .bat file called <strong>iisapp.bat</strong> and copied it to the C:\Windows\System32 folder. The content of the iisapp.bat file is just a single line, that does exactly the same as the old IISAPP did – just using the new APPCMD in IIS 7 instead:</p>
<blockquote>
<pre class="csharpcode">%SystemRoot%\System32\inetsrv\<strong>appcmd list wp</strong></pre>
</blockquote>
<p>Now I can call IISAPP and see a list of running applications:</p>
<p><a href="http://martinnormark.com/wp-content/uploads/2010/03/iisapp-list-iis7.jpg"><img class="alignnone size-full wp-image-271" title="IIS App List IIS 7" src="http://martinnormark.com/wp-content/uploads/2010/03/iisapp-list-iis7.jpg" alt="IIS Application list in IIS 7" width="590" height="298" /></a></p>
<p>And now my day got a whole lot better. Since the BAT file was copied to the System32 folder, there's no need to add anything to the PATH environment variable. This will work from any command prompt - just type <strong>iisapp</strong> and hit Enter.</p>
<div style="float: right;">
<iframe src="http://rcm.amazon.com/e/cm?lt1=_blank&#038;bc1=FFFFFF&#038;IS1=1&#038;nou=1&#038;bg1=FFFFFF&#038;fc1=000000&#038;lc1=0000FF&#038;t=martnormsblog-20&#038;o=1&#038;p=8&#038;l=as1&#038;m=amazon&#038;f=ifr&#038;ref=tf_til&#038;asins=0470152532" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe>
</div>
<h3>The Integrated Programming model in IIS 7</h3>
<p>IIS 7 comes with a bunch of improvements for developers. You can do a whole lot of exciting things even from web.config, but also from code.</p>
<p>To take advantage of the powerful integrated programming model, you need to set your application pool to use the Integrated pipeline mode. There's no limit to what you can do.</p>
<p>I found a lot of great stuff in the book called <a href="http://www.amazon.com/gp/product/0470152532/ref=as_li_tf_tl?ie=UTF8&#038;tag=martnormsblog-20&#038;linkCode=as2&#038;camp=217145&#038;creative=399381&#038;creativeASIN=0470152532">Professional IIS 7 and ASP.NET Integrated Programming</a><img src="http://www.assoc-amazon.com/e/ir?t=martnormsblog-20&#038;l=as2&#038;o=1&#038;a=0470152532&#038;camp=217145&#038;creative=399381" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> and learned a lot of useful stuff.</p>
<p>IIS 7 (or 7.5) is still the preferred way to develop, test and deploy ASP.NET applications, and as a developer you must stay up-to-date on what your tools and framework has to offer!</p>

<p><a href="http://feedads.g.doubleclick.net/~a/UtRPQ8hDe6VPlATd_s3xTf4BFhE/0/da"><img src="http://feedads.g.doubleclick.net/~a/UtRPQ8hDe6VPlATd_s3xTf4BFhE/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/UtRPQ8hDe6VPlATd_s3xTf4BFhE/1/da"><img src="http://feedads.g.doubleclick.net/~a/UtRPQ8hDe6VPlATd_s3xTf4BFhE/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/MENMxgY8lR4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/iisapp-equivalent-in-iis-7-and-beyond/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/iisapp-equivalent-in-iis-7-and-beyond?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
		<item>
		<title>Unit test for verifying references from DataAnnotation validation to the ErrorMessageResourceName value</title>
		<link>http://feedproxy.google.com/~r/martinnormark/~3/eQFhFQRjzTo/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value</link>
		<comments>http://martinnormark.com/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value#comments</comments>
		<pubDate>Thu, 04 Mar 2010 17:52:00 +0000</pubDate>
		<dc:creator>Martin H. Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Internationalization]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">/post/Unit-test-for-verifying-references-from-DataAnnotation-validation-to-the-ErrorMessageResourceName-value.aspx</guid>
		<description><![CDATA[I love the new model validation features in System.ComponentModel.DataAnnotations. One thing I don’t like though, is that the ErrorMessageResourceName is loosely typed. The ErrorMessageResourceType, however, is a System.Type which will be strongly typed by assigning its value using the typeof(Namespace.ResourceSetType) &#8230; <p><a class="btn small" href="http://martinnormark.com/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>I love the new model validation features in System.ComponentModel.DataAnnotations. One thing I don’t like though, is that the ErrorMessageResourceName is loosely typed. The ErrorMessageResourceType, however, is a System.Type which will be strongly typed by assigning its value using the typeof(Namespace.ResourceSetType) method.</p>
<p>Since there’s no build-breaking reference between a resource file and the value of the ErrorMessageResourceName on all classes where you use it, I thought it would be cool to have a unit test that verifies the existence of all referenced resource keys.</p>
<p>Remember to add a reference to System.ComponentModel.DataAnnotations.</p>
<h2>Code</h2>
<pre class="csharpcode"><span class="rem">/// &lt;summary&gt;</span>
<span class="rem">/// Verifies that all properties that are decorated with validation data-annotations, refers to </span>
<span class="rem">/// an existing resource. This will make sure, that missing resources are not referenced.</span>
<span class="rem">/// &lt;/summary&gt;</span>
[TestMethod]
<span class="kwrd">public</span> <span class="kwrd">void</span> All_Properties_With_Validation_Annotations_Must_Refer_To_Existing_Resource()
{
    Assembly assembly = Assembly.Load(<span class="kwrd">new</span> AssemblyName(<span class="str">"MyApp.Model.Namespace"</span>));
    var types = assembly.GetTypes().Where&lt;Type&gt;(t =&gt; t.IsClass &amp;&amp; !t.IsAbstract);

    <span class="kwrd">foreach</span> (var type <span class="kwrd">in</span> types)
    {
        var properties = type.GetProperties();

        <span class="kwrd">foreach</span> (PropertyInfo property <span class="kwrd">in</span> properties)
        {
            var attributes = property.GetCustomAttributes(<span class="kwrd">true</span>);

            <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> attributes)
            {
                <span class="kwrd">if</span> (item <span class="kwrd">is</span> ValidationAttribute)
                {
                    ValidationAttribute val = item <span class="kwrd">as</span> ValidationAttribute;

                    Assert.IsNotNull(val);

                    <span class="kwrd">if</span> (val.ErrorMessageResourceType != <span class="kwrd">null</span>)
                    {
                        Assert.AreNotEqual(String.Empty, val.ErrorMessageResourceName,
                            String.Format(<span class="str">@"Validation Error Resource specified on property:
                        {0}.{1} is empty!"</span>, type.ToString(), property.Name));

                        <span class="kwrd">try</span>
                        {
                            ResourceManager rm = <span class="kwrd">new</span> ResourceManager(val.ErrorMessageResourceType);
                            <span class="kwrd">string</span> resourceValue = rm.GetString(val.ErrorMessageResourceName);
                            Assert.IsFalse(String.IsNullOrEmpty(resourceValue),
                                String.Format(<span class="str">@"The value of the Validation Error Resource specified on property:
                            {0}.{1} is empty!"</span>, type.ToString(), property.Name));
                        }
                        <span class="kwrd">catch</span> (MissingManifestResourceException)
                        {
                            Assert.Fail(String.Format(<span class="str">@"Validation Error Resource specified on property:
                            {0}.{1} could not be found!"</span>, type.ToString(), property.Name));
                        }
                    }
                }
            }
        }
    }
}</pre>
<p><!-- .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; } --></p>

<p><a href="http://feedads.g.doubleclick.net/~a/9Ww5tVQwbPVIEFTtZ1Doz8IjtUc/0/da"><img src="http://feedads.g.doubleclick.net/~a/9Ww5tVQwbPVIEFTtZ1Doz8IjtUc/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/9Ww5tVQwbPVIEFTtZ1Doz8IjtUc/1/da"><img src="http://feedads.g.doubleclick.net/~a/9Ww5tVQwbPVIEFTtZ1Doz8IjtUc/1/di" border="0" ismap="true"></img></a></p><img src="http://feeds.feedburner.com/~r/martinnormark/~4/eQFhFQRjzTo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	<feedburner:origLink>http://martinnormark.com/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=rss</feedburner:origLink></item>
	</channel>
</rss>

