<?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</title>
	<atom:link href="http://martinnormark.com/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>Unit Testing ASP.NET MVC Controller Action contains specific ActionFilter Attributes</title>
		<link>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter#comments</comments>
		<pubDate>Tue, 15 May 2012 21:06:09 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Unit testing]]></category>
		<category><![CDATA[ActionFilters]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=424</guid>
		<description><![CDATA[ActionFilters in ASP.NET MVC are great. You can now easily share logic between controllers without having to inherit from a base controller, that does the common work. I have a content heavy application that supports a set of layouts. Each layout &#8230; <p><a class="btn small" href="http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/dd410209.aspx">ActionFilters</a> in ASP.NET MVC are great.</p>
<p>You can now easily share logic between controllers without having to inherit from a base controller, that does the common work.</p>
<p>I have a content heavy application that supports a set of layouts. Each layout is rendered by setting the Layout view dynamically, which I do from an ActionFilter. My ActionFilter is fully tested, but when you delegate work to an ActionFilter, you should write a test that ensures the filter is defined on the action.</p>
<p>Not surprisingly, this is very simple and relies on reflection (Download from Gist: <a href="https://gist.github.com/2605628">https://gist.github.com/2605628</a>):</p>
<pre class="prettyprint">/// &lt;summary&gt;
/// Verifies the controller action, contains an attribute of the specified attributeType.
/// &lt;/summary&gt;
/// &lt;param name="controller"&gt;The controller.&lt;/param&gt;
/// &lt;param name="action"&gt;The action method.&lt;/param&gt;
/// &lt;param name="attributeType"&gt;Type of the attribute to look for.&lt;/param&gt;
/// &lt;returns&gt;Returns true if the attribute was present on the action. Otherwise false.&lt;/returns&gt;
public static bool VerifyControllerActionAttribute(this Controller controller, Func&lt;ActionResult&gt; action, Type attributeType)
{
    MethodInfo methodInfo = action.Method;
    object[] attributes = methodInfo.GetCustomAttributes(attributeType, true);
    return attributes.Any(a =&gt; a.GetType() == attributeType);
}</pre>
<p>And the usage looks like this:</p>
<pre class="prettyprint">[TestMethod]
public void Index_ContainsTemplateLayoutAttribute()
{
    HomeController controller = new HomeController();
    bool containsAttribute = controller.VerifyControllerActionAttribute(controller.Index, typeof(TemplateLayoutAttribute));
    Assert.IsTrue(containsAttribute);
}</pre>
<p>Need an introduction? Watch a video about <a href="http://vimeo.com/32617893">unit testing ASP.NET and MVC based web apps</a> on Vimeo, published by Typemock.</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/unit-testing-asp-net-mvc-controller-action-contains-actionfilter/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>Make features obvious &#8212; forcing usage is even better</title>
		<link>http://martinnormark.com/make-features-obvious-forcing-usage?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/make-features-obvious-forcing-usage#comments</comments>
		<pubDate>Fri, 11 May 2012 11:20:13 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[Software]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[feature]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=421</guid>
		<description><![CDATA[When creating software, make your features obvious. A long time ago, Facebook introduced friendlists - a feature where you can group friends by any name you want. Along comes Google+, and have a feature called circles that, unlike Facebook's lists, &#8230; <p><a class="btn small" href="http://martinnormark.com/make-features-obvious-forcing-usage">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>When creating software, make your features obvious.</p>
<div>A long time ago, Facebook introduced friendlists - a feature where you can group friends by any name you want.</div>
<div></div>
<div>Along comes Google+, and have a feature called circles that, unlike Facebook's lists, are very obvious and an integral part of the design and workflow for when adding friends. All over the press, this is the feature they <a href="http://www.huffingtonpost.com/dave-taylor/why-google-plus-circles-facebook_b_888074.html">focus </a>on claiming it has an advantage over Facebook. It seems as if they don't know about the lists feature of Facebook, which makes it very important to focus on the features you need and make them obvious.</div>
<div></div>
<div>People use what they can see, and what they're forced to use.</div>
<div></div>
<div>It also makes you think about the countless times, when someone says "I hate the bla bla bla" - and most technical minded people just says, "you can turn it off". This is a typical response, but the problem might be that the <strong>defaults are incorrect</strong>.</div>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/make-features-obvious-forcing-usage/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>ASP.NET MVC Localize Numeric (data-val-number) Validation</title>
		<link>http://martinnormark.com/asp-net-mvc-localize-numeric-data-val-number-validation?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/asp-net-mvc-localize-numeric-data-val-number-validation#comments</comments>
		<pubDate>Sat, 05 May 2012 11:08:31 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=349</guid>
		<description><![CDATA[Another buggy experience in ASP.NET MVC. This has to do with validation, more specifically numeric validation. Whenever you have a numeric property on your view models, ASP.NET MVC automatically adds some implicit validation to ensure that whatever entered in fact is a numeric value. &#8230; <p><a class="btn small" href="http://martinnormark.com/asp-net-mvc-localize-numeric-data-val-number-validation">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Another buggy experience in ASP.NET MVC. This has to do with validation, more specifically numeric validation. Whenever you have a numeric property on your view models, ASP.NET MVC automatically adds some implicit validation to ensure that whatever entered in fact is a numeric value.</p>
<p>Might be good in most cases, but here's the problem. The validation mechanism writes the error messages in english. So for any app that targets a non-english audience, this needs to be changes.</p>
<p>But that's easier said than done. The code in ASP.NET MVC that generates the error message for the implicit numeric validator, looks like this:</p>
<pre class="prettyprint">private static string MakeErrorString(string displayName) {
  // use CurrentCulture since this message is intended for the site visitor
  return String.Format(CultureInfo.CurrentCulture, MvcResources.ClientDataTypeModelValidatorProvider_FieldMustBeNumeric, displayName);
}</pre>
<p>To make matter worse, this is a method from an internal, sealed class. They didn't want you to change this.</p>
<p>The only option is to remove the validator, and get rid of the implicit validation. To be honest, I prefer to take care of validation myself, through data annotations on my view models. I don't like when too much gets done implicitly. I want to be in control, and I want to know what is going on.</p>
<p>You can remove the validator in Global.asax:</p>
<pre class="prettyprint">foreach (ModelValidatorProvider prov in ModelValidatorProviders.Providers) {
  if (prov.GetType().Equals(typeof(ClientDataTypeModelValidatorProvider))) {
    ModelValidatorProviders.Providers.Remove(prov);
    break;
  }
}</pre>
<p>If you'd like to keep the numeric validation, but be able to override the error message, there's a great way to <a href="http://jwwishart.blogspot.com/2011/03/custom-server-and-client-side-required.html">roll your own ClientDataTypeModelValidatorProvider</a> that does this the right way.</p>
<h2>Things will get better</h2>
<p>I was browsing through the source code of ASP.NET MVC 4, and found <a href="http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/06f52b894414#src%2fSystem.Web.Mvc%2fClientDataTypeModelValidatorProvider.cs">a changeset</a> that looks like will fix this issue. In short, it will be possible to define your own <a href="http://msdn.microsoft.com/en-us/library/system.web.http.validation.providers.clientdatatypemodelvalidatorprovider.resourceclasskey(v=vs.108).aspx">ResourceClassKey</a>, and the MVC framework will use that before using default error messages. Nice!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/asp-net-mvc-localize-numeric-data-val-number-validation/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>10 Ways to (re) Structure JavaScript</title>
		<link>http://martinnormark.com/10-ways-structure-javascript?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/10-ways-structure-javascript#comments</comments>
		<pubDate>Tue, 03 Apr 2012 14:23:34 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Maintainability]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=351</guid>
		<description><![CDATA[Structuring JavaScript can be a job in itself if you don't look out. I was attending the virtual jQuery Summit 2011, and one of the talks were called 'Structuring Your DOM-based Application' by Garann Means. Her talk really took me back to &#8230; <p><a class="btn small" href="http://martinnormark.com/10-ways-structure-javascript">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>Structuring JavaScript can be a job in itself if you don't look out. I was attending the virtual jQuery Summit 2011, and one of the talks were called '<a href="http://speakerdeck.com/u/garann/p/sneaking-structure-into-your-dom-based-application">Structuring Your DOM-based Application</a>' by <a href="http://twitter.com/#!/garannm">Garann Means</a>. Her talk really took me back to the days of fighting un-structured JavaScript.</p>
<p>I was working on a code base that had been maintained by a handful of different developers, each with different skills, ideas and disciplin. Web development, and especially JavaScript requires a lot of disciplin in order to keep the code clean and structured, and that just wasn't the case at that time.</p>
<p>While I was watching Garann's talk, I constantly thought of all the problems we had and what we eventually did to solve our issues and take control of our JavaScript.</p>
<p>This is is my 10 ideas on ways to (re) structure JavaScript, get it under control, get rid of legacy code and improve the quality of a code base.</p>
<h2>1. Move all JavaScript code into js files</h2>
<p>While this should be obvious for all of us, it's just something I constantly see people don't do. Instead of having these nice js files, JavaScript is thrown into view files.</p>
<p>First of all, this means that the same code is delivered to the client everytime a page is requested. Depending on the amount of JavaScript tucked into the view, this can easily add up to hundreds of kilobytes which slows down your sites load time. With JS files, you can easily cache those files on the client, save bandwidth and increase the speed of your site.</p>
<p>Secondly, it makes the JavaScript much more difficult to maintain. You basically can't find what you're looking for, it's hard to have shared and general purpose functions that you can use from several views and you declare everything in <a href="http://yuiblog.com/blog/2006/06/01/global-domination/">the global scope</a>.</p>
<h2>2. Use closures, to avoid working in the global scope</h2>
<blockquote><p>JavaScript's <a href="http://yuiblog.com/blog/2006/06/01/global-domination/">biggest problem</a> is its dependence on global variables, particularly implied global variables. If a variable is not explicitly declared (usually with the <code>var</code> statement), then JavaScript assumes that the variable was global. This can mask misspelled names and other problems.</p>
<p><em>Douglas Crockford, <a href="http://www.jslint.com/lint.html">http://www.jslint.com/lint.html</a> - (Global Variables paragraph)</em></p></blockquote>
<p>To solve this problem, we need to wrap all of our code in closures.</p>
<p>A closure changes the context your code is executed within, to be inside the closure and not in the global scope. This means that all your functions and variables inside your closure is not available for others, outside the closure unless you explicitly expose them.</p>
<p>A closure is often referred to as an Immediately Invoked Function Expression (IFFE), and it is pretty much a function that acts as a wrapper around your code:</p>
<pre class="prettyprint">(function () {
  // your code here
})();</pre>
<p>Read more about <a href="http://tech.myemma.com/iifes-javascript-control-variable-scope/">closures and IIFE's here</a>.</p>
<h2>3. Improve jQuery selectors</h2>
<p><a href="http://api.jquery.com/category/selectors/">jQuery selectors</a> are very powerful. It's dead easy to write selectors that gets a bunch of elements in the DOM, and they can easily get pretty advanced.</p>
<p>This can have an impact on the performance of your code. Running in the browser, the efficiency of your code has a direct impact on the user's experience.</p>
<p>Since <code>getElementsByClassName</code> is not implemented by all browsers, the ones that don't have it will suffer when you query the DOM by class class name.</p>
<p>That means you can speed up your jQuery selectors by <a href="http://stackoverflow.com/questions/46214/good-ways-to-improve-jquery-selector-performance">specifying the tag name</a> before the class name:</p>
<p>BAD: <code>$(".price-label")</code></p>
<p>GOOD: <code>$("span.price-label")</code></p>
<p>You can also improve performance by limiting the context in which you select. You do that by specifying a second parameter to the selector which could be a container element that you're working inside:</p>
<pre class="prettyprint">var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);</pre>
<h2>4. Cache elements, instead of selecting from the DOM</h2>
<p>Using jQuery to select elements from the DOM is expensive. Some selectors are more expensive than others, but if you're going to use the same element multiple times in a functions, you're better off storing it in a local variable instead of selecting it every time.</p>
<p>When you select an element like this: <code>$(".price-label")</code> it's like having a huge swimming pool (the DOM), and telling your little brother (jQuery) to jump in and find all USD coins in there. And if you do the same on the next line of code, he has to jump in again, swim around the pool looking for USD coins.</p>
<p>And if the pool is junked up with loads of coins in other currencies, he has to look at each end everyone of them to determine whether or not it is a USD coin.</p>
<p>Some browser has a native function called <code>getElementsByClassName</code>, as opposed to <code>getElementsByTagName</code>. That does speed up the above example a little, but it is still much more effective to <a href="http://www.jeremyckahn.com/blog/?p=11">cache the element in a local</a> variable.</p>
<p>It's just a matter of saving an element to a local variable, and the use that in the rest of you code:</p>
<pre>var productDetailsDiv = $("div.product-details");
var priceLabel = $("span.price-label", productDetailsDiv);</pre>
<h2>5. Get rid of HTML in JavaScript</h2>
<p>Just like JavaScript should not be added to your HTML pages, HTML should not be generated inside JavaScript by concatenating strings.</p>
<p><a href="http://viget.com/extend/benchmarking-javascript-templating-libraries">Client side template libraries</a> are getting more and more popular, so utilize the <a href="http://stackoverflow.com/questions/4912586/explanation-of-script-type-text-template-script">&lt;script type="text/template"&gt;&lt;/script&gt;</a> and embed your client side view templates there.</p>
<p>Or even better. Pre-compile your client side views into JavaScript using something like <a href="http://twitter.github.com/hogan.js/">HoganJS</a>, place the code in a separate file and embed that. Not only will the footprint be smaller, but you also get caching and you speed things up since they're already compiled!</p>
<h2>6. Upgrade jQuery</h2>
<p>This should be a no-brainer. But code-bases get stuck on old versions for a variety of reasons. Maybe you rely on a plugin that doesn't work with the latest version, or you use lots of deprecated stuff that would take ages to rewrite.</p>
<p>Plugins that are stuck on older version, and are not compatible with future versions must die! You should not hold yourself hostage due to a plugin - get rid of it, fix the error, rewrite the plugin yourself and host it on Github. Never get stuck!</p>
<p>Same for deprecated code. It's a huge warning signal and you need to react!</p>
<p>In general, stay up to date on the project. New concepts, bug fixes and performance improvements are added all the times. Subscribe to their blog, read the <a href="http://docs.jquery.com/Downloading_jQuery#Current_Release">release notes</a> everytime they release a new version to get familiar with the new stuff.</p>
<h2>7. Teach your colleagues</h2>
<p>It is widely misunderstood, but a lot of developers tend to think of JavaScript as a language you don't have to learn, in order to write and maintain it. I don't know of any other language where this is the case, but loads of developers just think of JavaScript as "not real code" that "just lives in the browser", and more or less "doesn't matter".</p>
<p>This is one of the many reasons why JavaScript gets out of control. Too many incompetent developers are writing it, and it's a tough job to get it under control if you're the only true JavaScript developer where you work.</p>
<p>First of all, tell your colleagues to watch <a href="http://www.youtube.com/watch?v=hQVTIJBZook">JavaScript - The Good Parts</a> by <a href="http://www.crockford.com/">Douglas Crockford</a>. This touches on what's great and what's bad in JavaScript, and any developer that don't really know the language will realize that they're doing a lot of stuff wrong.</p>
<p>If you have to write JavaScript - man up and learn the language.</p>
<h2>8. Combine, compress and cache your JavaScript.</h2>
<p>In order to increase the performance of any website, <a href="http://developer.yahoo.com/performance/rules.html#num_http">minimizing the amount of files</a> the browser needs to download, and minimizing the size of each file is vital.</p>
<p>First of all, install <a href="http://developer.yahoo.com/yslow/">YSlow </a>in your browser and start examining what you have to improve.</p>
<p>If you haven't optimized for fewer HTTP request, you'll notice that's the top thing YSlow tells you to do. Find inspiration and guidance on how to <a href="http://www.hanselman.com/blog/TheImportanceAndEaseOfMinifyingYourCSSAndJavaScriptAndOptimizingPNGsForYourBlogOrWebsite.aspx">minify and optimize JavaScript and CSS files</a>. It's easy.</p>
<p>Next up is caching. First thing on this list, suggests that you should move JavaScript into js files. And this is why: Having js files, that is embedded on a page makes it really easy to cache on the client. Most webservers already sends out proper HTTP headers to allow static files, such as JavaScript to be cached on the client.</p>
<p>What you have to make sure, is that you're able to bust the cache. Either use <a href="http://www.web-caching.com/mnot_tutorial/how.html">expiration headers</a>, or add a version indicator to the URL of the file. Next time you deploy, increase that number to make it a new URL.</p>
<h2>9. Use a Content Delivery Network - CDN</h2>
<p>If you have lots of traffic, from all over the world. You can benefit from hosting your JavaScript files on a Content Delivery Network. With all the new cloud hosting companies out there, this has become exceptionally cheap.</p>
<p>For jQuery and other common libraries, you can also use the <a href="http://docs.jquery.com/Downloading_jQuery#CDN_Hosted_jQuery">CDN hosted files</a> provided by jQuery, Google or Microsoft.</p>
<h2>10. Write JavaScript Unit Tests</h2>
<p>Some people would probably say this should not be the last thing to do. But I think you need all the low-hanging fruits, that you can accomplish before you start dramatically changing the way you go about writing JavaScript. And unit testing JavaScript is going to do that.</p>
<p>There are several good unit testing libraries for JavaScript. The more popular are <a href="http://docs.jquery.com/QUnit">QUnit</a> and <a href="http://pivotal.github.com/jasmine/">Jasmine</a>.</p>
<h2>Conclusion</h2>
<p>There's a lot of things you can do to re-structure and get control of JavaScript. One thing is for sure. If you do nothing, things will get messy.</p>
<p>This was my take on what can be done, things I've done in the past with great success.</p>
<p>What do you think is missing, what have you done that greatly improved the quality of your JavaScript code-base?</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/10-ways-structure-javascript/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>JavaScript Bundling Issues When Using Unfinished Closures</title>
		<link>http://martinnormark.com/javascript-bundling-issues-closures?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/javascript-bundling-issues-closures#comments</comments>
		<pubDate>Thu, 22 Mar 2012 20:12:10 +0000</pubDate>
		<dc:creator>Martin Normark</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Closures]]></category>

		<guid isPermaLink="false">http://martinnormark.com/?p=396</guid>
		<description><![CDATA[We all know it's a good idea to bundle JavaScript files into as few script includes as possible to minimize HTTP request. And - we all know you should write your code inside closures, to avoid the biggest problem of &#8230; <p><a class="btn small" href="http://martinnormark.com/javascript-bundling-issues-closures">Continue reading <span class="meta-nav">&#8594;</span></a></p>]]></description>
			<content:encoded><![CDATA[<p>We all know it's a good idea to bundle JavaScript files into as few script includes as possible to <a href="http://developer.yahoo.com/performance/rules.html#num_http">minimize HTTP request</a>.</p>
<p>And - we all know you should write your <a href="http://reallifejs.com/the-meat/getting-closure/im-still-using-that/">code inside closures</a>, to avoid the biggest problem of JavaScript: its dependence on <a href="http://yuiblog.com/blog/2006/06/01/global-domination/">global variables</a>!</p>
<p>But what happens when those two things don't work together?</p>
<p>For me, they didn't play nice with each other today. Whenever I bundled my JavaScript files i got an <code>Uncaught TypeError: undefined is not a function</code>.</p>
<p>Consider this code:</p>
<pre class="prettyprint">/****** a-file.js ******/
!function($) {
  // Code here
}(window.jQuery)

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");
})(window.jQuery);​</pre>
<p>The error occurred on the first line, inside the closure in another-file.js. Take a look at <a href="http://jsfiddle.net/martinnormark/HGBrR/4/">this jsFiddle</a>.</p>
<p>Since the result of the first closure is true, the above code will evaluate as this:</p>
<pre class="prettyprint">/****** a-file.js ******/
true

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");
})(window.jQuery);​</pre>
<p>The only thing missing, is a semicolon to finish off the first closure (updated, and <a href="http://jsfiddle.net/martinnormark/HGBrR/6/">working jsFiddle</a>):</p>
<pre class="prettyprint">/****** a-file.js ******/
!function($) {
  // Code here
}(window.jQuery);

/****** another-file.js ******/
(function ($) {
  $("#hello").text("World!");   
})(window.jQuery);​</pre>
<p>Now, this is a trivial thing to get right, if you were only dealing with your own code base. But with loads of plugins, external libraries and such - you can only pray for the best!</p>
<p>In my case, the script that were causing the error was <a href="http://twitter.github.com/bootstrap/">Twitter Bootstrap</a> scripts. They were all missing the semi-colon in version 2.0, the<a href="https://github.com/twitter/bootstrap/issues/1836"> issue was submitted</a> a month ago, and later <a href="https://github.com/twitter/bootstrap/commit/6e77c9d1233c1621deeaa2dd00e6eca3fd618610">fixed</a>...</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/javascript-bundling-issues-closures/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<item>
		<title>ASP.NET MVC 3 Windows Authentication problem &#8211; redirects to Account/Login</title>
		<link>http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</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 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 class="prettyprint">&lt;authentication mode="Windows" /&gt;
&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>
]]></content:encoded>
			<wfw:commentRss>http://martinnormark.com/asp-net-mvc-3-windows-authentication-problem-redirects-to-account-login/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
	<creativeCommons:license>http://creativecommons.org/licenses/by/3.0/</creativeCommons:license>
	</item>
		<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>How to Send HTML E-mail from an ASP.NET MVC Controller</title>
		<link>http://martinnormark.com/actionmailer-net-html-email?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rss</link>
		<comments>http://martinnormark.com/actionmailer-net-html-email#comments</comments>
		<pubDate>Sat, 02 Apr 2011 22:04:54 +0000</pubDate>
		<dc:creator>Martin 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>
]]></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>
	</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>
	</channel>
</rss>

