Skip to main content

Posts

Processing ASP MVC Web API Requests in Multi-threaded JS Web Worker

Unlike an asynchronous Ajax call, HTML5 Web workers provide an opportunity to run a Multi-threaded JavaScript code in modern browsers that support them . Each worker spawns an isolated thread with dedicated JavaScript Event Loop, Stack and Heap memory. For example a regular Ajax Call to MVC Web API service call goes through the following asynchronous call cycle. The JavaScript Event Loop in this case could be interrupted by events that are being executed on the UI; for instance, a "window.alert", could possibly stop all scripts on the page from executing until a user responds. Replacing the Ajax Call with HTML5 web worker provides a great way to run long running scripts in separate threads so that asynchronous code execution is not interrupted by UI events. Here is the a JavaScript worker implementation of the same MVC Web API call using a JavaScript web worker. Despite the advantages of using a web worker, implementing one requires working with some constr...

Simple and reusable directive for making list elements draggable.

I was working on Angular lists and needed a easy to implement and reusable solution to make list items draggable . I chose to implement the solution as an Angular directive so that I can pass scope references to the new helper controller and execute ng-repeat, as needed, to recreate Dom elements. After adding the helper controller, I was able to make ng-repeat lists in my application draggable by simply adding a custom attribute and passing the Angular collection name. Here is a Plunkr demo  and full GitHub source code .

ASP.MVC Real-time data processing with Sharded RavenDB and SignalR

In a move that some call "Radical” The Weather Channel recently swapped their enterprise Oracle and MySql Databases for NoSQL  MongoDB .  One word that could describe the rapid adoption of NoSQL databases compared to relational once is “ sharding .” Unlike relational databases, NoSQL systems allow developers to be active participants in the data storage process by providing a way to create logic (sharding strategy) that outlines how and where data could be stored, resulting in better scalability and improved performance. RavenDB , an open source NoSQL system for .NET that is easy to deploy (both as a standalone/embedded system) for an ASP.MVC application. SingalR is a tool that one can use in a .NET environment to add real-time client-server processing in an application. SignalR allows a developer to broadcast messages to all (or some) clients from a centralized client and/or server call. I was looking for a quick data-sharding example with embedded Rave...

Miniprofiler and QUnit in ASP.MVC

Miniprofiler and QUnit are simple DLL, JS and CSS files that can be added to an ASP.MVC project to identify trouble spots in a project such as server side functions that run longer than anticipated or intermittent JS errors/warnings that show up in browsers' consoles. Miniprofiler - keeps track of the amount of time functions in an ASP.MVC source code take to execute and displays the results on a browser. I have found that functions that take longer to execute are good candidates for refactoring. To add Miniprofiler: Use Package Manager to add references to Miniprofiler in your project PM> Install-Package MiniProfiler Update Global.asax file as follows (this is for making the library available globally in your project) using StackExchange.Profiling; and protected void Application_BeginRequest() { if (Request.IsLocal) { MiniProfiler.Start(); } } protected void Application_EndRequest() { MiniProfiler.Stop(); } Add the following one li...

From your ASP App to the Compiler with Compilation Directives

If you have some code that you want to run locally for testing, you can check current "Request" and look at methods like "Request.IsLocal" to conditionally include test modules. However, there are times you need to bypass the ASP.NET application life cycle and directly exclude or include a source code from compiling using compilation directives. Here is an example of a use case where you might need to bypass the application life cycle in order to run code during development. Consider a case where you need to include some JS and CSS styles, say, you have QUnit   files stashed somewhere in a folder of your app, during development. If you are working on an ASP.NET page, view or controller you can access incoming HTTP Request by using: var currentRequest = Request; or if you are accessing the "Request" object from a class that does not inherit from "Page" in ASP.NET or "ViewPage" in MVC (or any other object that has the current ...

Upgrading from Angular 1.0 to 1.2

One of the projects I recently worked on required an upgrade from Angular 1.0 to 1.2.  The upgrade was not a result of Angular 1.0 limitations (in terms business needs), version 1.0 works just fine; however, Angular 1.0 is an experimental release and chances of running into already known and less desirable issues was very likely without moving to a stable version of Angular. Here are the steps that I took to rewrite the application JS functions to work with Angular 1.2. Caveat:  Folks at Angular have migration guideline documentation here -  http://docs.angularjs.org/guide/migration  - the steps I outlined below only deal with updates to a specific application (Angular 1.0 running with WCF web services), you might want to review the migration guideline document if you run into any issues after your application upgrade. Steps Take the plunge  – remove references to Angular 1.0 and replace them with Angular 1.2. You will need two JS references for Angular ...

Pseduo-RegEx JQuery Selectors

More often than not I find myself using only few jQuery selectors to locate elements in DOM for event binding; however, jQuery also offers some powerful psedo-RegEx selectors for locating elements. Say, you have the following HTML5 markup: -------------------------------------------------- <!DOCTYPE HTML> < html lang = "en" > < head > < meta charset = "UTF-8" > < title > JQuery Selector </ title > </ head > < body > < article class = "post-article" > < header class = "article-header" > </ header > < p class = "article-content" > </ p > </ article > </ body > </ html > -------------------------------------------------- You can use the following selectors to locate the "article-header" element. 1- Using closest     $(".post-article").closest("header").fi...

Deffered Ajax calls in jQuery

One of the useful features of jQuery Ajax function is the ability daisy chain a series of JS calls using ".done" directive. If you have a series of web service calls and want them to execute in a certain predetermined order you can simply add your function to a jQuery $ajax call and use the ".done" helper to call a web service when another call completes. Here is a Plunker example: Here is a quick plunkr example code.

Turning WCF Service into .asmx for debugging

Even though .asmx web services are becoming dinosaurs of the new .NET world of WCF. I missed the simplicity of debugging code right in visual studio without: Creating a client to consume WCF service Attaching w3p.exe process and Adding break points  One quick solution: Turn WCF service into .asmx service with few lines of code, debug your code with asmx, and turn .asmx off during deployment.  Detail steps: 1- First take your WCF class and add WebService attribute to it Code Snippet /// <summary> /// Dual mode with .ASMX and WCF /// </summary> [ WebService (Namespace = "http://www.yourdomain.com/" )] 2- Then add WebMethod attribute to a function you want to expose in .asmx Code Snippet [ WebMethod ] public List < PageController . Page > DualFunction() { 3- Take the .svc file from your solution - copy and rename the copied file [YourOriginalWCFFile.asmx]. Open up the copied file and rename "ServiceHost...

.NET 4.0 Bundle of Joy

It use to be that you would have to summon the mighty powers of YUI compressor and roll out the red carpets of MSBuild to minify CSS and JS files in your ASP.NET and MVC applications.  With the introduction of bundling in System.Web.Optimization (now Microsoft.AspNet.Web.Optimization) you can skip the formalities and bundle your JS and CSS file without introducing additional dependencies. To use bundling in a .NET 4.0 app. 1- Create an App_Start folder in your solution (if you don't have one already) 2- Add a class in your App_Start folder for your bundles and create a function to call all your CSS and JS files. E.g. (BundleConfig.cs) Code Snippet using System.Web; using System.Web.Optimization;   namespace YourGlobalNameSpace {      public class BundleConfig     {          public static void RegisterBundles(BundleCollection bundles)     ...

Pre-fetching CDN calls

Pre-fetching has been around for  some time now  and is often used to load images and CSS files.  While your mileage may vary, you can also pre-fetch your CDN calls (e.g. Jquery) and make your apps a bit faster by loading scripts in the <head> section to load JS calls before your <script> get resolved by browsers. You can also CDN outage proof it (when it  rarely happens ) by having local JS libraries (for rainy days) using some quick jquery checks (based on code from + Hanselman ) Testing Without pre-fetch: Code Snippet < script src ="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></ script > < script >      if ( typeof jQuery == 'undefined' ) {         document.write(unescape( "%3Cscript src='[yourlocalbackupjqueryfile].js' type='text/javascript'%3E%3C/script%3E" ));     }      var startTime...

Disjoint queries in LINQ to SQL

I find LINQ to SQL expressions very useful when running queries against Entity Framework objects; however, running disjoint queries in LINQ (queries that require filtering one list and running the results against another) is not as simple using inner joins or correlated sub-queries [i.e.  in SQL "where [someID] not in ([some query])']. To run a disjoint query in LINQ to SQL you would have to write three separate queries. One with all data you need Code Snippet var myDataUniverse = from ent in [SomeEntity]                       select ent; another with items to exclude Code Snippet var myExcludedList = from ent in  [SomeEntity]                        // where some logic to filter excluded entities                    ...

A URL Inception: Sending Query String within a Query String

I came across a simple but interesting solution when working on a project that required sending query string that contains another query string (i.e. a URL Inception  :) ... ) First Pass: http://somedomain.com/someservice?query=http://anotherdomain.com/anotherservice?dream1=value1 Which works fine as long as you are sending a single query string. However, if you have additional query string your data breaks at the first ampersand of the second query string. i.e. http://somedomain.com/someservice?dream1=value1&dream2=http://anotherdomain.com/anotherservice?&subdream1=subdreamvalue1 will be interpreted as: after the URL is translated in a browser. The Solution: Using good old URL encoding . Changing the ampersand in the second query string to %26  fixes the issue. i.e. http://somedomain.com/someservice?dream1=value1&dream2=http://anotherdomain.com/anotherservice? %26 subdream1=subdreamvalue1 Will...

Optimizing ASP.NET/MVC 3.0 Site

I stumbled upon the Google Page Speed Insights tools  when testing ASP.MVC 3 site performance few days ago. After running the performance test, I found out that the web page I was testing has a performance index of 50% - i.e.things such as loading JS, CSS, and static files are taking away about half of the website loading time.  Here are some steps I took to optimize the site and recover much needed speed. Plan of Action 1- Enabling Gzip Compression Gzip  is a compression algorithm that is used by several web servers and browsers to send and receive compressed http responses. By default gzip is disabled on IIS (bummer ...). You could use IIS GUI to change the settings - but for those of you who are XML ninja's here are the few lines of code that will recover some speed for your .NET 4.0 /3.5 app running on IIS7. Code Snippet < system.webServer >    < urlCompression doStaticCompression = " true " doDynamicCompression = " true " /> ...