My article on “Essential IT Admin skills for .NET Developers” is published on DNC .NET Magazine May 2013 issue.
Please subscribe to this FREE magazine at: http://www.dotnetcurry.com/magazine/
My article on “Essential IT Admin skills for .NET Developers” is published on DNC .NET Magazine May 2013 issue.
Please subscribe to this FREE magazine at: http://www.dotnetcurry.com/magazine/
Codeuml.com is a web based UML designer where you code the diagram using a special language and it generates the diagram on the fly. It is faster than using any visual designer where you have to drag & drop diagram elements and use mouse to connect them. Codeuml uses the open source plantuml engine to produce diagram from text. You can produce UML diagrams as fast as you can code.

This web application shows some interesting design and coding challenges. First, it shows you how to build a web based IDE like environment that mimics Windows 8 Metro UI. Second it shows how you can periodically collect data from the website, send to the server in the background asynchronously and get the result generated on the fly. Third and the most important, it shows how you can maintain a server side pool of very expensive resource that you cannot just create on every hit to the server and must have a finite pool that is shared by all your web users.

Read details about this from this CodeProject article:
When you use WCF services from Javascript, you have to generate the Javascript proxies by hitting the Service.svc/js. If you have five WCF services, then it means five javascripts to download. As browsers download javascripts synchronously, one after another, it adds latency to page load and slows down page rendering performance. Moreover, the same WCF service proxy is downloaded from every page, because the generated javascript file is not cached on browser. Here is a solution that will ensure the generated Javascript proxies are cached on browser and when there is a hit on the service, it will respond with HTTP 304 if the Service.svc file has not changed.
Here’s a Fiddler trace of a page that uses two WCF services.
You can see there are two /js hits and they are sequential. Every visit to the same page, even with the same browser session results in making those two hits to /js. Second time when the same page is browsed:
You can see everything else is cached, except the WCF javascript proxies. They are never cached because the WCF javascript proxy generator does not produce the necessary caching headers to cache the files on browser.
Here’s an HttpModule for IIS and IIS Express which will intercept calls to WCF service proxy. It first checks if the service is changed since the cached version on the browser. If it has not changed then it will return HTTP 304 and not go through the service proxy generation process. Thus it saves some CPU on server. But if the request is for the first time and there’s no cached copy on browser, it will deliver the proxy and also emit the proper cache headers to cache the response on browser.
http://www.codeproject.com/Articles/360437/Caching-WCF-javascript-proxy-on-browser
Don’t forget to vote.
Here’s the recent presentation made on LIDNUG on scaling ASP.NET websites from thousands to millions of users. The action starts at 0:02:05.
Here’re the slides.
Now you no longer pay me for Dropthings license instead you donate the money to a charity and I will give you the license. In case you don’t know what Dropthings is, it is a Web 2.0 Personalizable Dashboard framework that you can use to build Web 2.0 personalizable websites and enterprise dashboards. It is built using ASP.NET AJAX, jQuery, Silverlight, .NET 3.5, Entity Framework, SQL Server. It is in use in big companies like BT, Intel, Microsoft, Thomson Reuters; many government organizations like State Police, Canada Border Protection etc. Since it is a state of the art .NET 3.5 codebase, it is sometimes used as a starting point for an application with all the best practices already in place in order to build an N-tier web app using popular technologies, design patterns and testing methods. Dropthings helps you build web app utilizing extensive performance and scalability research that I have done to scale websites to millions of users. It also helps you build a codebase that is highly testable. It shows you how to test AJAX applications using automated test tools like WatiN. It has a business layer and a data access layer that is fully unit testable, nearly 100% test coverage and uses Inversion of Control pattern to the fullest.

You can find details about the Project here: http://code.google.com/p/dropthings/
There are two codeproject articles that show you how it was built, tested, deployed and the production challenges I had to overcome scaling this to millions of requests per day:
Build Google IG like Portal in 7 days
Web 2.0 AJAX Portal using jQuery, ASP.NET 3.5, Silverlight, Linq to SQL, WF and Unity
Finally, there’s a book on it, that takes you from the initial idea to design, coding, testing, all the way to purchasing right production hardware, deployment and production troubleshooting. It is a complete end-to-end guide for a developer/startup CTO to take an idea from design to VC funded successful startup used by millions. I have captured many experiences I have learnt from my startup years at Pageflakes that I co-founded and was the founding CTO.
Building a Web 2.0 Portal with ASP.NET 3.5 from O‘Reilly.
Let’s build great web apps and save the world at the same time!
Microsoft Research arranged MVP Open Day 2011 at Cambridge on Oct 14, 2011. Beautiful university, made me feel like giving up my job and going back to study. Amazing research work going there, highly thought provoking. The session on DNA programming was out of the world. The most surprising thing I learnt that a 10cm long DNA strand can hold 10TB worth digitally encoded data and cells are thousand times more robust computing system than silicon based chips. Moreover, cells are self-powered, super energy efficient micro processors, hundred years ahead of Intel processors.
Can’t wait for the day when we will be able to use C# to program DNA:
protected void CancerCell_Found(object body, CellEventArgs e) { this.Attack(e.TargetCell); }
Here’s my presentation slide. Nothing NDA or DNA in this, feel free to distribute.
ASP.NET generates some large cookies if you are using ASP.NET membership provider. Especially if you are using the Anonymous provider, then a typical site will send the following cookies to every request when a user is logged in, whether the request is to a dynamic page or to any static resource:
.DBANON=w3kYczsH8Wvzs6MgryS4JYEF0N-8ZR6aLRSTU9KwVaGaydD6WwUHD7X9tN8vBgjgzKf3r3SJHusTYFjU85y
YfnunyCeuExcZs895JK9Fk1HS68ksGwm3QpxnRZvpDBAfJKEUKee2OTlND0gi43qwwtIPLeY1;
ASP.NET_SessionId=bmnbp155wilotk45gjhitoqg; DBAUTH12=2A848A8C200CB0E8E05C6EBA8059A0DBA228FC5F6EDD29401C249D2
37812344C15B3C5C57D6B776037FAA8F14017880E57BDC14A7963C58B0A0B30229
AF0123A6DF56601D814E75525E7DCA9AD4A0EF200832B39A1F35A5111092F0805B
0A8CD3D2FD5E3AB6176893D86AFBEB68F7EA42BE61E89537DEAA3279F3B576D0C
44BA00B9FA1D9DD3EE985F37B0A5A134ADC0EA9C548D
There are 517 bytes of worthless data being sent to every css, js and images from the browser to your webserver!
You might think 517 bytes is peanut. Do the math:
Here’s how to prevent this:
www.yoursite.com then map static.yoursite.com to it. <link>, <script>, <img> css url(…) and prefix each resource with http://static.yoursite.com Global.asax and in the EndRequest do this trick:
HttpContext context = HttpContext.Current;
if (context.Request.Url.ToString.StartsWith("http://static.yoursite.com")
{
List<string> cookiesToClear = new List<string>();
foreach (string cookieName in context.Request.Cookies)
{
HttpCookie cookie = context.Request.Cookies[cookieName];
cookiesToClear.Add(cookie.Name);
}
foreach (string name in cookiesToClear)
{
HttpCookie cookie = new HttpCookie(name, string.Empty);
cookie.Expires = DateTime.Today.AddYears(-1);
context.Response.Cookies.Set(cookie);
}
}
This code reads all the cookies it receives from request and expires them so that browser does not send those cookies again. If by any chance ASP.NET cookies get injected into the static.yoursite.com domain, this code will take care of removing them.
A truly RESTful API means you have unique URLs to uniquely represent entities and collections, and there is no verb/action on the URL. You cannot have URL like /Customers/Create or /Customers/John/Update, /Customers/John/Delete where the action is part of the URL that represents the entity. An URL can only represent the state of an entity, like /Customers/John represents the state of John, a customer, and allow GET, POST, PUT, DELETE on that very URL to perform CRUD operations. Same goes for a collection where /Customers returns list of customers and a POST to that URL adds new customer(s). Usually we create separate controllers to deal with API part of the website but I will show you how you can create both RESTful website and API using the same controller code working over the exact same URL that a browser can use to browse through the website and a client application can perform CRUD operations on the entities.
I have tried Scott Gu’s examples on creating RESTful routes, this MSDN Magazine article, Phil Haack’s REST SDK for ASP.NET MVC, and various other examples. But they have all made the same classic mistake – the action is part of the URL. You have to have URLs like http://localhost:8082/MovieApp/Home/Edit/5?format=Xml to edit a certain entity and define the format eg xml, that you need to support. They aren’t truly RESTful since the URL does not uniquely represent the state of an entity. The action is part of the URL. When you put the action on the URL, then it is straightforward to do it using ASP.NET MVC. Only when you take the action out of the URL and you have to support CRUD over the same URL, using three different formats – html, xml and json, it becomes tricky and you need some custom filters to do the job. It’s not very tricky though, you just need to keep in mind your controller actions are serving multiple formats and design your website in a certain way that makes it API friendly. You make the website URLs look like API URL.
The example code has a library of ActionFilterAttribute and ValurProvider that make it possible to serve and accept html, json and xml over the same URL. A regular browser gets html output, an AJAX call expecting json gets json response and an XmlHttp call gets xml response.
You might ask why not use WCF REST SDK? The idea is to reuse the same logic to retrieve models and emit html, json, xml all from the same code so that we do not have to duplicate logic in the website and then in the API. If we use WCF REST SDK, you have to create a WCF API layer that replicates the model handling logic in the controllers.
The example shown here offers the following RESTful URLs:
All these URLs support GET, POST, PUT, DELETE. Users can browse to these URLs and get html page rendered. Client apps can make AJAX calls to these URLs to perform CRUD on these. Thus making a truly RESTful API and website.
They also support verbs over POST in case you don’t have PUT, DELETE allowed on your webserver or through firewalls. They are usually disabled by default in most webservers and firewalls due to security common practices. In that case you can use POST and pass the verb as query string. For ex, /Customers/C0001?verb=Delete to delete the customer. This does not break the RESTfulness since the URL /Customers/C0001 is still uniquely identifying the entity. You are passing additional context on the URL. Query strings are also used to do filtering, sorting operations on REST URLs. For ex, /Customers?filter=John&sort=Location&limit=100 tells the server to return a filtered, sorted, and paged collection of customers.
Read my CodeProject article for details:
http://www.codeproject.com/KB/aspnet/aspnet_mvc_restapi.aspx
The source code is available here:
http://code.msdn.microsoft.com/Build-truly-RESTful-API-194a6253
Enjoy!
When you update javascript or css files that are already cached in users’ browsers, most likely many users won’t get that for some time because of the caching at the browser or intermediate proxy(s). You need some way to force browser and proxy(s) to download latest files. There’s no way to do that effectively across all browsers and proxies from the webserver by manipulating cache headers unless you change the file name or you change the URL of the files by introducing some unique query string so that browsers/proxies interpret them as new files. Most web developers use the query string approach and use a version suffix to send the new file to the browser. For example,
<script src="someJs.js?v=1001" ></script> <link href="someCss.css?v=2001"></link>
In order to do this, developers have to go to all the html, aspx, ascx, master pages, find all references to static files that are changed, and then increase the version number. If you forget to do this on some page, that page may break because browser uses old cached script. So, it requires a lot of regression test effort to find out whether changing some css or js breaks something anywhere in the entire website.
Another approach is to run some build script that scans all files and updates the reference to the javascript and css files in each and every page in the website. But this approach does not work on dynamic pages where the javascript and css references are added at run-time, say using ScriptManager.
If you have no way to know what javascript and css will get added to the page at run-time, the only option is to analyze the page output at runtime and then change the javascript, css references on the fly.
Here’s an HttpFilter that can do that for you. This filter intercepts any ASPX hit and then it automatically appends the last modification date time of javascript and css files inside the emitted html. It does so without storing the whole generated html in memory nor doing any string operation because that will cause high memory and CPU consumption on webserver under high load. The code works with character buffers and response streams directly so that it’s as fast as possible. I have done enough load test to ensure even if you hit an aspx page million times per hour, it won’t add more than 50ms delay over each page response time.
First, you add set the filter called StaticContentFilter in the Global.asax file’s Application_BeginRequest event handler:
Response.Filter = new Dropthings.Web.Util.StaticContentFilter(
Response,
relativePath =>
{
if (Context.Cache[physicalPath] == null)
{
var physicalPath = Server.MapPath(relativePath);
var version = "?v=" +
new System.IO.FileInfo(physicalPath).LastWriteTime
.ToString("yyyyMMddhhmmss");
Context.Cache.Add(physicalPath, version, null,
DateTime.Now.AddMinutes(1), TimeSpan.Zero,
CacheItemPriority.Normal, null);
Context.Cache[physicalPath] = version;
return version;
}
else
{
return Context.Cache[physicalPath] as string;
}
},
"http://images.mydomain.com/",
"http://scripts.mydomain.com/",
"http://styles.mydomain.com/",
baseUrl,
applicationPath,
folderPath);
}
The only tricky part here is the delegate that is fired whenever the filter detects a script or css link and it asks you to return the version for the file. Whatever you return gets appended right after the original URL of the script or css. So, here the delegate is producing the version as “?v=yyyyMMddhhmmss” using the file’s last modified date time. It’s also caching the version for the file to make sure it does not make a File I/O request on each and every page view in order to get the file’s last modified date time.
For example, the following scripts and css in the html snippet:
<script type="text/javascript" src="scripts/jquery-1.4.1.min.js" ></script> <script type="text/javascript" src="scripts/TestScript.js" ></script> <link href="Styles/Stylesheet.css" rel="stylesheet" type="text/css" />
It will get emitted as:
<script type="text/javascript" src="scripts/jquery-1.4.1.min.js?v=20100319021342" ></script> <script type="text/javascript" src="scripts/TestScript.js?v=20110522074353" ></script> <link href="Styles/Stylesheet.css?v=20110522074829" rel="stylesheet" type="text/css" />
As you see there’s a query string generated with each of the file’s last modified date time. Good thing is you don’t have to worry about generating a sequential version number after changing a file. it will take the last modified date, which will change only when a file is changed.
The HttpFilter I will show you here can not only append version suffix, it can also prepend anything you want to add on image, css and link URLs. You can use this feature to load images from a different domain, or load scripts from a different domain and benefit from the parallel loading feature of browsers and increase the page load performance. For example, the following tags can have any URL prepended to them:
<script src="some.js" ></script> <link href="some.css" /> <img src="some.png" />
They can be emitted as:
<script src="http://javascripts.mydomain.com/some.js" ></script> <link href="http://styles.mydomain.com/some.css" /> <img src="http://images.mydomain.com/some.png" />
Loading javascripts, css and images from different domain can significantly improve your page load time since browsers can load only two files from a domain at a time. If you load javascripts, css and images from different subdomains and the page itself on www subdomain, you can load 8 files in parallel instead of only 2 files in parallel.
Read here to learn how this works:
http://www.codeproject.com/KB/aspnet/autojscssversion.aspx
Appreciate your feedback.
When you deploy incremental changes on a production server, which is running and live all the time, you some times see error messages like “Compiler Error Message: The Type ‘XXX’ exists in both…”. Sometimes you find Application_Start event not firing although you shipped a new class, dll or web.config. Sometimes you find static variables not getting initialized and so on. There are so many weird things happen on webservers when you incrementally deploy changes to the server and the server has been up and running for several weeks. So, I came up with a full proof house keeping steps that we always do whenever we deploy some incremental change to our websites. These steps ensure that the web sites are properly recycled , cached are cleared, all the data stored at Application level is initialized.
First of all you should have multiple web servers behind a load balancer. This way you can take one server out of the production traffic, do your deployment and house keeping tasks like restarting IIS, and then put it back. Then you can do it for the second server and so on. This ensures there’s no outage for customer. If you can do it reasonable fast, hopefully customers won’t notice discrepancy between the servers some having new code and some having old code. You should only do this when your changes aren’t drastic. For ex, you aren’t delivering a complete revamped UI. In that case, some users hitting server1 with latest UI will suddenly get a completely different experience and then on next page refresh, they might hit server2 with old code and get a totally different experience. This works for incremental non-dramatic changes only.
During deployment you should follow these steps:
That’s it. It should give you a clean deployment and prevent unexpected errors. You should print these steps and hang on the desk of your deployment guys so that they never forget during deployment pressure.
Doing all these steps manually is risky. Under deployment time pressure, your production guys can make mistakes and screw up a server for good. So, I always prefer having a batch file that takes a server out and makes it ready for deploying code and then after the deployment is done, use another batch file to put the server back into load balancer traffic rotation after the server is warmed up.
Generally load balancers are configured to hit some page on your website and keep the server alive if that page returns a HTTP 200. If not, it assumes the server is dead and takes it our of rotation. For ex, say you have an alive.txt file on your website which is what load balancer is keeping an eye on. If it’s gone, the server is put out of the rotation. In that case, you can create some batch files that will take the server out, wait for couple of seconds to ensure the in-flight requests complete and then stop IIS, delete temporary ASP.NET files and make server ready to deploy stuff. Something like this:
serverout.bat ===================== Ren alive.txt dead.txt typeperf "ASP.NET Applications(__Total__)Requests Executing" -sc 30 iisreset /stop rmdir /q /s "C:WINDOWSMicrosoft.NETFramework64v1.1.4322Temporary ASP.NET Files" rmdir /q /s "C:WINDOWSMicrosoft.NETFramework64v2.0.50727Temporary ASP.NET Files" md "C:WINDOWSMicrosoft.NETFramework64v1.1.4322Temporary ASP.NET Files" md "C:WINDOWSMicrosoft.NETFramework64v2.0.50727Temporary ASP.NET Files" xcacls "C:WINDOWSMicrosoft.NETFramework64v1.1.4322Temporary ASP.NET Files" /E /G MYMACHINEIIS_WPG:F /Q xcacls "C:WINDOWSMicrosoft.NETFramework64v2.0.50727Temporary ASP.NET Files" /E /G MYMACHINEIIS_WPG:F /Q
Similarly you should have a batch file that starts IIS, warms up some pages, and then puts the server back into load balancer.
serverin.bat ============ SET TINYGET=C:Program Files (x86)IIS ResourcesTinyGettinyget.exe iisreset /start"%TINYGET%" -srv:localhost -uri:http://localhost/ -status:200 ren dead.txt alive.txt typeperf "ASP.NET Applications(__Total__)Requests Executing" -sc 30
Always try to automate this kind of admin chores. It’s difficult to do it right all the time manually under deployment pressure.