Skip to main content

Rendering Dynamically JavaScript Files from Server Side Code

Today's RIA applications require us to build robots apps with minimal post-backs cycles, this requirement forces us to make an extensive use of JavaScript and technologies as AJAX.

Today I want to blog about "Rendering Dynamically JavaScript Files from Server Side Code", this is a very useful and elegant (and strangely not discussed enough) technique that can improve our RIA application architecture.

Good But Not Perfect

So let's try to describe a small task and it's solution to make a good picture about this strong technique.

You work on a "Rental Car" application that is in charge of keeping track of all rented cars and sends an email notification to the "Rental Car" company manager about cars that their rental period already exceeded.
As mentioned before, your app makes an extensive use of JavaScript and AJAX in order to improve users experience.
Now, let's also say that you need to read the SMTP configuration parameters, such as SMTP Host Name, user name, password and sender email address from your Web Config or from a Data Base.

You have several option to perform this task, but I will stick to the main ones:
  1. You can turn a blind eye, and make a small post-back to the server to help you with this.
  2. You can make a small AJAX call to your server side Business Logic Layer or Data Access Layer, "make them" retrieve the requested data from the Web Config file or Data Base and reply back to your browser a nice JSON object containing the requested data.
The second option in not so bad, but neither perfect, because you always need to perform AJAX calls and waste bandwidth.
Obviously you could improve your little piece of code so it will save the data in a JavaScript variable so you don't need to perform AJAX calls again and again, but you will still need to perform at least one AJAX call for every page refresh. Taking in consideration that in a big enterprise application you could reach situations where you waste dozens of AJAX calls for every page refresh. Its not a perfect idea.

The Elegant Solution

Let's think about a wonderful world where we could:
  1. Retrieve the SMTP data from our server side (Business Logic Layer or Data Access Layer) ones and preserve it even between post-backs
  2. Cache data in the client (browser)
  3. In conjunction with HTTP protocol (I will blog about this one...) we also could have a full control on the cache expiration date (i.e re call server via AJAX only next week or only when data was changed etc)
Nice ha? Yes We Can.

As you know when a page makes its way back to the client it contains HTML.
With a small effort we can make our server generate JavaScript files dynamically and make use of server side code to retrieve the SMTP data, without unnecessary post-backs and AJAX calls.

Let's Code

Here a simple ASP.NET standard page that is used to render HTML back to our browser:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ServerSideJS.WebForm1" %> 

<html xmlns="" >
<head runat="server">
</body> </html>
In order  to tell the server that instead we want to render some JavaScript code your page should look like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="js.aspx.cs" Inherits="ServerSideJS.js" ContentType="application/x-javascript" %>

Two important things to note:
  1. This file still has it's own server side although it generates JavaScript code, that means that some how we can use the power of server side C# / VB to generate those JavaScript lines
  2. ContentType="application/x-javascript" is the key of Rendering Dynamically JavaScript Files technique, this small piece of code tells the server side code to generate JavaScript instead of HTML
Let's see now how we can add C# server side code to generate JavaScript. For this sample your Web Config file should look something like this:


Our "ServerSide - JavaScript" contains a simple JSON object that will be filled by the C# code with the corresponding data:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="js.aspx.cs" Inherits="ServerSideJS.js" ContentType="application/x-javascript" %>

var SMTPData={
HostName:'<%= ConfigurationManager.AppSettings["HostName"].ToString()%>',
Password:'<%= ConfigurationManager.AppSettings["Password"].ToString()%>',
UserName:'<%= ConfigurationManager.AppSettings["UserName"].ToString()%>',
SenderEmail:'<%= ConfigurationManager.AppSettings["SenderEmail"].ToString()%>'

From our simple ASP.NET standard page we are able to write the following code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ServerSideJS.WebForm1" %>
<html xmlns="" >
<head runat="server">


<body onload="load()">
</body> </html>

The sample I just show you is very simple, but with a little imagination, instead of simply reading data from our Web Config we can think on more complex scenarios like retrieve data from data base or from a complex Business Logic method that returns list of items etc.


The Best

GetHashCode Hands-On Session

The following is a hands-on post meant to demonstrate how GetHashCode() and Equals() methods are used by .NET Framework under the hood. For the sake of simplicity I will refer to the popular hashed-base Dictionary type, although any other hash based structure will follow a similar behavior, if not the same one. After understanding this post you should be able to spot potential problematic behaviors and resolve them, prevent creation of unreachable items in dictionaries and improve CRUD actions performance on hash based structures. The TheoryGetHashCode() is used to create a unique integer identifier for objects/structs. The hashcode can be used for two purposes: Programmatically, by developers, to distinguish objects/structs form each other (NOTE: Not recommended when the default .NET implementation is used, as it's not guaranteed to preserve the same hash between .NET versions and platforms)Internally, by .NET Framework, when using the object/struct as a key in a hashed based l…

Closures in C# vs JavaScript -
Same But Different

Closure in a Nutshell Closures are a Software phenomenon which exist in several languages, in which methods declared inside other methods (nested methods), capture variables declared inside the outer methods. This behavior makes captured variables available even after the outer method's scope has vanished.

The following pseudo-code demonstrates the simplest sample:
Main() //* Program starts from here { Closures(); } AgeCalculator() { int myAge = 30; return() => { //* Returns the correct answer although AgeCalculator method Scope should have ordinarily disappear return myAge++; }; } Closures() { Func ageCalculator = AgeCalculator(); //* At this point AgeCalculator scopeid cleared, but the captured values keeps to live Log(ageCalculator()); //* Result: 30 Log(ageCalculator()); //* Result: 31 } JavaScript and C# are two languages that support…

SSL Distilled

A few days ago, my wife asked me: "why is it, sometimes when I access my web-mail account at work, I get a scary browser popup threatening and yelling at me that the site is dangerous and I should click 'OK'...?".
I am pretty sure this post will answer her question. SSL without Sweating Although SSL is very popular and well documented on many web articles, blogs, books & technical videos, when trying to really understand and assemble all the bits and bytes, you will probably find yourself breaking a sweat, because of the many misconceptions about this subjects. In this article I am going to give a brief top-to-bottom review of the must-know parts of SSL and try to re-explain the less familiar parts of this protocol. In order to make it easy for those of you that are familiar with SSL and only want to read the 'Hot' parts, I added an '*' as prefix to those points, so you guys can jump between them. …