Category Archives: Uncategorized

ASP.NET MVC Caching Dynamically generated JavaScript

One of the things you may occasionally have to do while using JavaScript is show dialogs and react to your users inputs. These could be in the form of alert boxes that are built into the language, growls, loading panels or even just a message added to an element. (Side note: The jQuery BlockUI plugin seems very promising).

The discerning user would realize that a website that targets a global audience has to be able to localize, globalize and internationalize to their language and a good starting place is to look at Scott Hanselman’s post on this very topic.

Globalization, Internationalization and Localization in ASP.NET MVC 3, JavaScript and jQuery – Part 1

One hacky way to get localized strings in JavaScript when they are in separate files is to have a localized file with all the localized text in it. Then based on the users language preference, load up the appropriate file and use the strings from there. But what if the strings come from a database and you need to generate this at runtime to be able to handle change without deployment again. Well here is how you can do it.

Read the article on JavaScriptView by elegantcode for more details. However, to summarize here are their steps:

  1. Create a controller method that return the view as a JavaScriptFileResult preferably in your home controller.
  2. Create a view that contains the localized strings in an array. I used a helper method to get the contents from the database dynamically. You may wish to add this to your home controllers view folder as well.
  3. Add a script block in the shared layout’s header to the URL for the JavaScript file.

All well and good. The file will now come down with the rest of the content as a JavaScript file and you can use the array of localized strings in your other JavaScript code.

BUT! The one problem you may notice is that the JavaScript source file is retrieved every time a request is made to the server. Thus you will need to cache it. To do so, we just need to add the OutputCacheAttribute onto the controller method that returns the JavaScript file.

[OutputCache(Location = System.Web.UI.OutputCacheLocation.ServerAndClient, Duration = 900, VaryByParam = "none")]

The only problem here is that the VaryByParam is set to none. That’s because we don’t have any parameters being passed into the method. This is a problem because two different requests can come in for varying locales and now the second one may get the cached value of the first one. Therefore, we need to pass in the locale as a parameter and then VaryByParam on that field. This will ensure that every locale has the file cached and changes made can go out without requiring a deployment of files to the server.

JsConstants

The script block in the _Layouts.cshtml file.

<script src="@Url.Content("~/Home/JsConstants?lcid=" + System.Threading.Thread.CurrentThread.CurrentCulture.LCID)" type="text/javascript"></script>

But of course, who wants to keep sending these Id’s over all the time for all our script files. So, the easiest way to do this would be to create an identifier that can be used to check language automatically. And then we can write, “lang” in the VaryByParam attribute option and remove the lcid parameter from JsConstants.

[OutputCache(Location = System.Web.UI.OutputCacheLocation.ServerAndClient, Duration = 900, VaryByParam = "lang")]

The code to make this work is as follows. [Sorry but I’m not quite sure where I found this gem from]

public override string GetVaryByCustomString(HttpContext context, string value)
{
	if (value.Equals("lang"))
	{
		return Thread.CurrentThread.CurrentUICulture.Name;
	}
	return base.GetVaryByCustomString(context,value);
}

fidllerJsConstants

As you can see from the image above, the first request for the JsConstants file containing the JavaScript returned 918bytes of data. Whereas, the subsequent call returned 0 bytes. The raw message returned reads as follows:

HTTP/1.1 304 Not Modified
Cache-Control: private, max-age=863
Expires: Sat, 03 Sep 2011 22:57:26 GMT
Last-Modified: Sat, 03 Sep 2011 22:42:26 GMT
Vary: *
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Sat, 03 Sep 2011 22:43:03 GMT

This indicates that we are able to cache the contents of the JavaScript file that was being generated dynamically and it will be refreshed after the Duration we set (900).

Happy Coding.

kick it on DotNetKicks.com

Advertisements

Been a while

Its been a while. Lot has happened personally which I won’t get into but suffice it to say, its been a while.

I’m hoping to build up my blog now so look for new stuff.

The Power to Change

I’m sure everyone has seen Obama’s speech but I just wanted to pass it on in case you hadn’t.
Kennedy, in his inauguration said, “My fellow citizens of the world, ask not what America will do for you, but what together we can do for the freedom of man.” Inspiring words to rally people to a greater cause. I believe that the boundaries we build around us in regards to nations, religion, race, social class are things that must be broken before we can look at ourselves with any sense of pride.
Today, Obama made me feel like that was indeed possible. We all think these thoughts, but to hear them echoed by someone who truly believes it and wants to make it happen, makes me feel like there is a chance of redemption in the catastrophy that is human history, my history, your history, our history.
Mahatma Gandhi, Martin Luther King, Nelson Mandela, Dalai Lama and Aung San Suu Kyi in my mind are the greatest heros to human kind. Their contributions to our lives is immeasurable and I cannot begin to comprehend the extent to which they sacrificed their own lives for the benefit of others, not just in the nations they helped change but throughout the world. I have never met these great people, I probably never will. But I want to thank them. I want to say that I believe in them and the causes they started.
Today, I am moved. I am in tears. I want change. I want every corner of every continent to be free, to hold life as precious, to believe in and act morally, to accept others regardless of race, religion, nationality, and the other boundaries we have built. I hold these truths to be self evident.
Tomorrow, I am back to myself, uncaring and unchanging, living the drab life of a Programmer…but silently weeping….for change.

What is Beautiful Code?

First, I must preface this by saying I haven’t read the book Beautiful Code. However, reading the book description under the section Editorial Reviews.

“The authors think aloud as they work through their project’s architecture, the tradeoffs made in its construction, and when it was important to break rules. Beautiful Code is an opportunity for master coders to tell their story.”

In my opinion, this does not make for Beautiful Code. Maybe Pragmatic Code, Convenient Code, Judicious Code but not Beautiful Code.

Chapter 1 talks about “A Regular Expression Matcher by Brian Kernighan…and a problem can lead to a concise and elegant solution.” Great! While I have no doubt that the author and others in the book are FAR FAR more intelligent and accomplished that I am, I must say that what you might consider beautiful might not be what I consider beautiful. For example, regex expressions. I point you to Scott Hanselman’s post on LINQ to Everything – LINQ to XSD adds more LINQiness . Here is some sample code from his blog.

public sealed class AmountType {    
[DebuggerBrowsable(DebuggerBrowsableState.Never)]    
public static Microsoft.Xml.Schema.Linq.SimpleTypeValidator TypeDefinition =
new Microsoft.Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String),
new Microsoft.Xml.Schema.Linq.RestrictionFacets(((Microsoft.Xml.Schema.Linq.RestrictionFlags)(46)), null, 0, 0, null, null, 32, null, null, 1,
new string[] { “^(([\+\-]?[0-9]*(([0-9][,\.]?)|([,\.][0-9]))[0-9]*))$”}, 0, XmlSchemaWhiteSpace.Collapse));    
private AmountType() {} }

This code may be very functional and to some very beautiful. However, to me Beautiful Code MUST be simple and readable, even by a Freshman Computer Science student. Look at the complexity and the change in thinking required to write Regex code. I have to get my thinking away from the programming language I am currently writing and context switch into the Regex language. Once I am done with the Regex I must switch back to the language and continue my work.

That brings me to another point. Why isn’t there a complete Regex library in the Microsoft Namespace. Things like validation for phone numbers based on region, validation for addresses, validation for email based on the RFC standard and other useful Regex . I understand that a lot of the regex created is custom but some of the most used regex is going to be the simple reusable stuff.

I came across this little gem from a blog called Alarming Development.
 

“O’Reilly just published Beautiful Code. I was invited to contribute, but I just could not go along with the premise. I disagree that beauty is a guiding principle of programming. Here is how I responded.

I am having trouble with this assignment. Telling an inspiring story about a beautiful design feels disingenuous. Yes, we all strive for beautiful code. But that is not what a talented young programmer needs to hear. I wish someone had instead warned me that programming is a desperate losing battle against the unconquerable complexity of code, and the treachery of requirements.”

Bravo. As always, I always want to “Ask Jeff” too. Jeff Atwood of Coding Horror had this to say:

“Unfortunately, Beautiful Code wasn’t nearly as enjoyable of a read as I had hoped it would be. It is by no means a bad book, but there’s something about it that’s not quite right.

Part of the problem is that it’s a compilation of disconnected essays, much like The Best Software Writing I.

I absolutely agree with the Jeff. (Yes I said the Jeff. Maybe it should say “The Jeff”) He goes on to say:

“But the code itself is not beautiful. The beauty of code lies in the architecture, the ideas, the grander algorithms and strategies that code represents.”

I agree with the first sentence However, I don’t think software architecture is beautiful. OH MY GOD! BLASPHEMY!! Yes I said it. Architecture is not beautiful. Think about it. If a problem is presented, each person tackling it will probably create different architecture for the same problem. Heck, the same person might do it differently each time based on things they learn from the previous attempt.

In my opinion the beauty lies in…….the problem! There is one unique problem and we have many way to solve it. The satisfaction gained from appreciating the problem, studying it and learning about it is beautiful. So the next time you come across the opportunity to solve a problem, savor the taste. I know I will.

Hello world!

Aboutdev has begun. Let the rejoicing begin.