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 Theory GetHashCode() 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 has

Design API for Multiple Different Clients

Today I want to talk about common design challenges related to architecture of robust APIs, designed to be consumed by multiple clients with different needs. Our use case is the following: We need to build a N-Tier Web REST/SOAP API that is supposed to read/write data from a DB, perform some processing on that data and expose those methods to our API consumers. In addition we have multiple different API clients each with different needs, meaning we can't just expose a rigid set of functions with a defined group of DTOs (Data Transfer Objects). DTO vs POCO Before start diving I want to explain shortly the difference between these two controversial concepts. DTO Objects that are designed to transfer data between edges (i.e. between processes, functions, server & clients etc'). Typically DTOs will contain only simple properties with no behavior. POCO Objects that are designed to reflect the internal business data model. For example if you have an eCommerce platform

Connect to Active Directory using DDC SDK

In this post, I will cover a new Open Source Java SDK designed to simplify communication with Active Directory for small, medium and large projects. DDC (Domain Directory Controller) is an SDK designed to simplify AD interaction for small, medium and large projects. DDC is a portable Java library provided with a friendly API, allowing you to quickly compose simple or complicated queries against AD's endpoints without any previous LDAP knowledge. I had the pleasure to develop this SDK along with my colleges at Imperva . Now Imperva decided to make it available publicly as an Open Source project . The article was published by officially Imperva, you can find the full article here .