<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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"
>

<channel>
	<title>Martin Normark&#039;s blog &#187; C#</title>
	<atom:link href="http://martinnormark.com/category/c/feed" rel="self" type="application/rss+xml" />
	<link>http://martinnormark.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 21:06:09 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</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" />
		<item>
		<title>Make CSS inline in C# and ASP.NET using PreMailer.Net</title>
		<link>http://martinnormark.com/move-css-inline-premailer-net?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/move-css-inline-premailer-net/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Serialize C# dynamic and Anonymous types to XML</title>
		<link>http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/serialize-c-dynamic-and-anonymous-types-to-xml/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Making your ASP.NET Global Resource files work in JavaScript. IntelliSense included!</title>
		<link>http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/making-your-asp-net-global-resource-files-work-in-javascript-intellisense-included/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Translate text in C#, using Google Translate, revisited</title>
		<link>http://martinnormark.com/translate-text-in-c-using-google-translate-revisited?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/translate-text-in-c-using-google-translate-revisited/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Generate HTML e-mail body in C# using templates</title>
		<link>http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/generate-html-e-mail-body-in-c-using-templates/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Unit test for verifying references from DataAnnotation validation to the ErrorMessageResourceName value</title>
		<link>http://martinnormark.com/unit-test-for-verifying-references-from-dataannotation-validation-to-the-errormessageresourcename-value?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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>
]]></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>
	</item>
		<item>
		<title>Multiple SSL certificates on IIS using host headers</title>
		<link>http://martinnormark.com/multiple-ssl-certificates-on-iis-using-host-headers?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/multiple-ssl-certificates-on-iis-using-host-headers#comments</comments>
		<pubDate>Thu, 04 Mar 2010 00:35:00 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[IIS7]]></category>

		<guid isPermaLink="false">/post/Multiple-SSL-certificates-on-IIS-using-host-headers.aspx</guid>
		<description><![CDATA[In IIS SSL sites have seemed to be limited to only one site per network interface, since you (from IIS Manager) cannot specify a host header binding on the HTTPS protocol. It turns out, that it is only a limitation &#8230; <p><a class="btn small" href="http://martinnormark.com/multiple-ssl-certificates-on-iis-using-host-headers">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>In IIS SSL sites have seemed to be limited to only one site per network interface, since you (from IIS Manager) cannot specify a host header binding on the HTTPS protocol.</p>
<p>It turns out, that it is only a limitation in the UI. So to have e.g. two sites with their own dedicated SSL certificate we need to add a host header binding on port 443 from either appcmd, managed code or by editing the applicationHosts.config file.</p>
<p>I like managed code the most, so I’ve written a small method in C# that does the trick. You need to have two SSL certificates named <a href="http://www.ssl1.com">www.ssl1.com</a> and <a href="http://www.ssl2.com">www.ssl2.com</a> installed on the machine. I just created a self signed certificate for both of them using the IIS Manager.</p>
<pre class="csharpcode"><span class="kwrd">using</span> System.Security.Cryptography.X509Certificates;
<span class="kwrd">using</span> Microsoft.Web.Administration;

<span class="kwrd">namespace</span> IisSsl
{
    <span class="kwrd">class</span> Program
    {
        <span class="kwrd">static</span> <span class="kwrd">void</span> Main(<span class="kwrd">string</span>[] args)
        {
            <span class="kwrd">using</span> (ServerManager _serverManager = <span class="kwrd">new</span> ServerManager())
            {
                <span class="kwrd">string</span> siteName = <span class="str">"SSL2"</span>;
                <span class="kwrd">string</span> certName = <span class="str">"www.ssl2.com"</span>;

                X509Store store = <span class="kwrd">new</span> X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);

                X509Certificate2 certificate = store.Certificates[0];

                Site site = _serverManager.Sites[siteName];

                <span class="kwrd">if</span> (site != <span class="kwrd">null</span>)
                {
                    site.Bindings.Add(<span class="str">"*:443:"</span> + certName,
                        certificate.GetCertHash(), store.Name);
                }
                store.Close();

                _serverManager.CommitChanges();
            }
        }
    }
}</pre>
<p>Remember to add a reference to C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll in order to use the ServerManager class.</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/multiple-ssl-certificates-on-iis-using-host-headers/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Search Twitter from C# using LINQ to XML</title>
		<link>http://martinnormark.com/search-twitter-from-c-using-linq-to-xml?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/search-twitter-from-c-using-linq-to-xml#comments</comments>
		<pubDate>Mon, 16 Mar 2009 21:28:08 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">/post/Search-Twitter-from-C-using-LINQ-to-XML.aspx</guid>
		<description><![CDATA[In some applications, it could be cool to have a feature that enabled the user to quickly get a glimpse of what people are saying on Twitter about the user or their product, service, company etc. For instance, a service &#8230; <p><a class="btn small" href="http://martinnormark.com/search-twitter-from-c-using-linq-to-xml">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>In some applications, it could be cool to have a feature that enabled the user to quickly get a glimpse of what people are saying on <a href="http://twitter.com/">Twitter</a> about the user or their product, service, company etc.</p>
<p>For instance, a service like <a href="http://getsatisfaction.com">GetSatisfaction.com</a> has a feature just like that. They call it <a href="http://getsatisfaction.com/dell/overheard">Overheard</a>, and this is what it looks like:</p>
<p><a href="http://www.martinnormark.com/image.axd?picture=overheard.jpg"><img style="display: inline; border: 0px;" title="overheard" src="http://www.martinnormark.com/image.axd?picture=overheard_thumb.jpg" border="0" alt="overheard" width="621" height="513" /></a></p>
<p>There’s nothing like Twitter to give you feedback. I think <a href="http://mediatemple.net/">MediaTemple</a> felt the <a href="http://search.twitter.com/search?q=+mediatemple+since%3A2009-02-26+until%3A2009-02-28">effect of unhappy customers on Twitter</a> when their servers broke down, and stayed there for more than two days!</p>
<p>Anyway. I wanted to search from C#, and get back a DataTable. Here’s how it’s done:</p>
<pre class="csharpcode">    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Searches Twitter for the specified query.</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="query"&gt;The query.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;Returns the search results as a DataTable&lt;/returns&gt;</span>
    <span class="kwrd">public</span> DataTable Search(<span class="kwrd">string</span> query)
    {
      DataTable dt = <span class="kwrd">new</span> DataTable();
      dt.Columns.Add(<span class="str">"text"</span>);
      dt.Columns.Add(<span class="str">"html"</span>);
      dt.Columns.Add(<span class="str">"pubdate"</span>);
      dt.Columns.Add(<span class="str">"id"</span>);
      dt.Columns.Add(<span class="str">"link"</span>);
      dt.Columns.Add(<span class="str">"authorname"</span>);
      dt.Columns.Add(<span class="str">"authorlink"</span>);

      XDocument tweetResults = XDocument.Load(String.Format(</pre>
<pre class="csharpcode">      <span class="str">"http://search.twitter.com/search.atom?q={0}"</span>, HttpUtility.UrlEncode(query)));</pre>
<pre class="csharpcode">      XNamespace atomNS = <span class="str">"http://www.w3.org/2005/Atom"</span>;
      var q = from tweet <span class="kwrd">in</span> tweetResults.Descendants(atomNS + <span class="str">"entry"</span>)
              select <span class="kwrd">new</span>
              {
                Text = (<span class="kwrd">string</span>)tweet.Element(atomNS + <span class="str">"title"</span>),
                Html = (<span class="kwrd">string</span>)tweet.Element(atomNS + <span class="str">"content"</span>),
                DatePublished = DateTime.Parse((<span class="kwrd">string</span>)tweet.Element(atomNS + <span class="str">"published"</span>)),
                Id = (<span class="kwrd">string</span>)tweet.Element(atomNS + <span class="str">"id"</span>),
                Link = (<span class="kwrd">string</span>)tweet.Elements(atomNS + <span class="str">"link"</span>)
                .Where(link =&gt; (<span class="kwrd">string</span>)link.Attribute(<span class="str">"rel"</span>) == <span class="str">"alternate"</span>)
                .Select(link =&gt; (<span class="kwrd">string</span>)link.Attribute(<span class="str">"href"</span>))
                .First(),
                Author = (from author <span class="kwrd">in</span> tweet.Descendants(atomNS + <span class="str">"author"</span>)
                          select <span class="kwrd">new</span>
                          {
                            Name = (<span class="kwrd">string</span>)author.Element(atomNS + <span class="str">"name"</span>),
                            Uri = (<span class="kwrd">string</span>)author.Element(atomNS + <span class="str">"uri"</span>),
                          }).First()
              };

      <span class="kwrd">foreach</span> (var item <span class="kwrd">in</span> q)
      {
        dt.Rows.Add(item.Text, item.Html, item.DatePublished, item.Id, item.Link,</pre>
<pre class="csharpcode">                    item.Author.Name, item.Author.Uri);
      }

      <span class="kwrd">return</span> dt;
    }</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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/search-twitter-from-c-using-linq-to-xml/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Automatically translate Global and Local Resource (resx) files</title>
		<link>http://martinnormark.com/automatically-translate-global-and-local-resource-resx-files?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/automatically-translate-global-and-local-resource-resx-files#comments</comments>
		<pubDate>Fri, 13 Mar 2009 22:31:14 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Internationalization]]></category>

		<guid isPermaLink="false">/post/Automatically-translate-Global-and-Local-Resource-(resx)-files.aspx</guid>
		<description><![CDATA[Yesterday, I blogged about how you can use Google Translate to translate a string in C#. To make it more useful than just a simple translator, and because I need to translate some Global Resource files for an E-commerce website &#8230; <p><a class="btn small" href="http://martinnormark.com/automatically-translate-global-and-local-resource-resx-files">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Yesterday, I blogged about how you can <a href="http://martinnormark.com/post/Translate-text-in-C-using-Google-Translate.aspx">use Google Translate to translate a string in C#</a>. To make it more useful than just a simple translator, and because I need to translate some Global Resource files for an E-commerce website that I’m working on, I wanted to create a small Windows Application in C# that could read a Global Resource file (.resx) and translate it into a selected language using the <a href="http://martinnormark.com/post/Translate-text-in-C-using-Google-Translate.aspx">method for translating a word in C#</a> that i blogged about yesterday.</p>
<p><a href="http://www.martinnormark.com/image.axd?picture=image.png"><img style="display: inline; border-width: 0px;" title="image" src="http://www.martinnormark.com/image.axd?picture=image_thumb.png" border="0" alt="image" width="451" height="166" /></a></p>
<p>This is how it looks so far. You simply select the resource file you want to translate. Select the current language of the resource file in the middle box, and select the language you want to translate it to in the last box. Click <strong>Translate</strong> at it should work. The new resource file will be saved in the same location as the application itself.</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/automatically-translate-global-and-local-resource-resx-files/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Translate text in C#, using Google Translate</title>
		<link>http://martinnormark.com/translate-text-in-c-using-google-translate?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/translate-text-in-c-using-google-translate#comments</comments>
		<pubDate>Thu, 12 Mar 2009 00:14:26 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">/post/Translate-text-in-C-using-Google-Translate.aspx</guid>
		<description><![CDATA[*** This post is no longer up-to-date. Take a look at my new post, revisiting how to tranlate text in C# using Google Translate *** Sometimes, it would be great to be able to translate a text from e.g. English &#8230; <p><a class="btn small" href="http://martinnormark.com/translate-text-in-c-using-google-translate">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>*** This post is <strong>no longer up-to-date</strong>. Take a look at my new post, revisiting how to <a href="http://martinnormark.com/2010/10/25/translate-text-in-c-using-google-translate-revisited">tranlate text in C# using Google Translate</a> ***</p>
<p>Sometimes, it would be great to be able to translate a text from e.g. English to Danish directly from C#. This could be useful when you want to translate a <a href="http://msdn.microsoft.com/en-us/library/ekyft91f(VS.80).aspx">Resource file</a> into another language.</p>
<p><a href="http://translate.google.com/">Google Translate</a> is awesome. There’s also <a href="http://www.windowslivetranslator.com/">Windows Live Translator</a>, but Microsoft are far behind Google (also) in this game.</p>
<p>Code:</p>
<pre class="csharpcode"><span class="kwrd">using</span> System;
<span class="kwrd">using</span> System.Net;
<span class="kwrd">using</span> System.Text;
<span class="kwrd">using</span> System.Text.RegularExpressions;

<span class="kwrd">namespace</span> Utilities
{
  <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">class</span> Translator
  {
    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Translates the text.</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="languagePair"&gt;The language pair.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> TranslateText(<span class="kwrd">string</span> input, <span class="kwrd">string</span> languagePair)
    {
      <span class="kwrd">return</span> TranslateText(input, languagePair, System.Text.Encoding.UTF7);
    }

    <span class="rem">/// &lt;summary&gt;</span>
    <span class="rem">/// Translate Text using Google Translate</span>
    <span class="rem">/// &lt;/summary&gt;</span>
    <span class="rem">/// &lt;param name="input"&gt;The string you want translated&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="languagePair"&gt;2 letter Language Pair, delimited by "|". </span>
    <span class="rem">/// e.g. "en|da" language pair means to translate from English to Danish&lt;/param&gt;</span>
    <span class="rem">/// &lt;param name="encoding"&gt;The encoding.&lt;/param&gt;</span>
    <span class="rem">/// &lt;returns&gt;Translated to String&lt;/returns&gt;</span>
    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">string</span> TranslateText(<span class="kwrd">string</span> input, <span class="kwrd">string</span> languagePair, Encoding encoding)
    {
      <span class="kwrd">string</span> url = String.Format(<span class="str">"http://www.google.com/translate_t?hl=en&amp;ie=UTF8&amp;text={0}&amp;langpair={1}"</span>, input, languagePair);

      <span class="kwrd">string</span> result = String.Empty;

      <span class="kwrd">using</span> (WebClient webClient = <span class="kwrd">new</span> WebClient())
      {
        webClient.Encoding = encoding;
        result = webClient.DownloadString(url);
      }

      Match m = Regex.Match(result, <span class="str">"(?&lt;=&lt;div id=result_box dir=\"ltr\"&gt;)(.*?)(?=&lt;/div&gt;)"</span>);

      <span class="kwrd">if</span> (m.Success)
        result = m.Value;

      <span class="kwrd">return</span> result;
    }
  }
}</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>The translated string is fetched by the RegEx close to the bottom. This could of course change, and you have to keep it up to date.</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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/translate-text-in-c-using-google-translate/feed</wfw:commentRss>
		<slash:comments>10</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
	</channel>
</rss>

