Sunday 25 October 2015

What's the difference between a ViewModel and Controller?

enter image description here
  • The ViewModel can be on the client side as well as server side. Wherever it may be, the sole purpose of viewmodel is to play the presentation data.
  • In MVC architecture Viewmodel is not mandatory but with out controller the request from the client cannot be processed.
  • Controller can be visualised as the main interface between client and server to get any response from the server. It processes the client request, fetches data from repository and then prepares the view data. Viewmodel can be visualised as view data processor/presenter thus an interface to manage the view more eloquently.
  • In the overall context of a web application we can say the controller is the application request handler whereas viewmodel is only the UI handler.

 

Thursday 3 September 2015

Compilation Error : The type 'ASP.global_asax' exists in both dlls


 Looking into this bin-folder you will probably see two files (an information I found here):
  • App_global.asax.dll
  • App_global.asax.compiled
Removing these resolves the error. The App_global.asax.dll is generated at runtime too which causes the problem. I am however still investigating how these files got there, so comments are definitely welcome!

Tuesday 28 July 2015

IIS 403 Error  when URL has '/' at the end

This error can be fixed by specifying a default document for the website. You'd need to have that default document configured in the website.



Double click the Default Document and there in click Add from the right hand side panel. Now browse to your default document(under the website). Restart the website or the application pool. And now you can browse the URL with /. 

Friday 3 July 2015

Promise & Deferred objects in JavaScript

Introduction

In the not too distant past the primary tool available to JavaScript programmers for handling asynchronous events was the callback.
A callback is a piece of executable code that is passed as an argument to other code, which is expected to call back ( execute ) the argument at some convenient time
— Wikipedia
In other words, a function can be passed as an argument to another function to be executed when it is called.
There’s nothing inherently wrong with callbacks, but depending on which environment we are programming in there are a number of options available for managing asynchronous events. In this post my goal is to examine one set of available tools: promise objects and deferred objects. In part I, we will cover theory and semantics and in part 2 we will look at the use.
One of the keys to effectively working with asynchronous events in JavaScript is understanding that the program continues execution even when it doesn’t have the value it needs for work that is in progress. Dealing with as yet unknown values from unfinished work can make working with asynchronous events in JavaScript challenging — especially when you’re first getting started.
A classic example of this would be an XMLHttpRequest ( Ajax ). Imagine we want to:
  • make an Ajax request to get some data
  • immediately do something with that data, and then
  • do other things
In our program we initiate our Ajax request. The request is made but unlike with synchronous events, execution of our program isn’t stopped while the server is responding, instead the program continues running. By the time we get the response data from our Ajax request, the program has already finished execution.

Promises & Deferreds: What are they?

Promises are a programming construct that have been around since 1976. In short:
  • a promise represents a value that is not yet known
  • a deferred represents work that is not yet finished
Considered from a high level, promises in JavaScript give us the ability to write asynchronous code in a parallel manner to synchronous code. Let’s start with a diagram to get an overview of the big picture before diving into the specifics.
Promises
A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value. Every deferred has a promise which functions as a proxy for the future result. While a promise is a value returned by an asynchronous function, a deferred can be resolved or rejected by it’s caller which separates the promise from the resolver. The promise itself can be given to any number of consumers and each will observe the resolution independently meanwhile the resolver / deferred can be given to any number of producers and the promise will be resolved by the one that first resolves it. From a semantic perspective this means that instead of calling a function ( callback ), we are able to return a value ( promise ).

Promises According to the Promise/A Proposal

The Promises /A Proposal suggests the following standard behavior and API regardless of implementation details.
A promise:
  • Represents the eventual value returned from the single completion of an operation
  • may be in one of 3 states: unfulfilled, fulfilled and failed and may only move from unfulfilled to either fulfilled or failed
  • has a function as a value for the property “then” ( which must return a promise )
  • Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise.
    then(fulfilledHandler, errorHandler, progressHandler)
  • The value that is returned from the callback handler is the fulfillment value for the returned promise
  • promise’s value MUST not be changed (avoids side effects from listeners creating unanticipated behavior)
In other words, stripping out some of the nuances for a moment:
A promise serves as a proxy for a future value, has 3 possible states and needs to have a function which adds handlers for it’s states: fulfilledHandler, errorHandler and progressHandler ( optional ) and returns a new promise (to allow chaining ) which will be resolved / rejected when the handler finishes executing.

The states and return value of a promise

A promise has 3 possible states: unfulfilled, fulfilled and failed.
  • unfulfilled: since a promise is a proxy for an unknown value it starts in an unfulfilled state
  • fulfilled: the promise is filled with the value it was waiting for
  • failed: if the promise was returned an exception, it is in the failed state.
A promise may only move from unfulfilled to either fulfilled or failed. Upon resolution or rejection, any observers are notified and passed the promise / value. Once the promise has been resolved or rejected neither it’s state or the resulting value can be modified.
Here is an example of what this looks like:
// Promise to be filled with future value
var futureValue = new Promise();

// .then() will return a new promise
var anotherFutureValue = futureValue.then();

// Promise state handlers ( must be a function ).
// The returned value of the fulfilled / failed handler will be the value of the promise.
futureValue.then({

    // Called if/when the promise is fulfilled
    fulfilledHandler: function() {},

    // Called if/when the promise fails
    errorHandler: function() {},

    // Called for progress events (not all implementations of promises have this)
    progressHandler: function() {}
});

Implementation differences & Performance

When choosing a promise library, there are a number of considerations to take into account. Not all implementations are created equal. They can differ in regards to what utilities are offered by the API, performance and even in behaviour.
Since the Promise/A proposal only outlines a proposal for the behaviour of promises and not implementation specifics, varying promise libraries have differing sets of features. All Promise/A compliant implementations have a .then() function but also have varying features in their API. Additionally, they are still able to exchange promises with each other. jQuery is the noticeable exception to the rule because its implementation of promises is not fully Promise/A compliant. The impact of this decision is documented here and discussed here. In Promise/A compliant libraries, a thrown exception is translated into a rejection and the errorHandler() is called with the exception. In jQuery’s implementation an uncaught exception will hault the program’s execution. As a result of the differing implementation, there are interoperability problems if working with libraries which return or expect Promise/A compliant promises.
One solution to this problem is to convert jQuery promises into Promise/A compliant promises with another promise library and then use the API from the compliant library.
For example:
when($.ajax()).then()
When reading through jQuery’s decision to stick with their implementation of promises, a mention of performance considerations piqued my curiosity and I decided to do a quick performance test. I used Benchmark.js and tested the results of creating and resolving a deferred object with a success handler in .then().
The results:
jQuery 91.6kbWhen.js 1.04kbQ.js 8.74kb
9,979 ops/sec ±10.22%96,225 ops/sec ±10.10%2,385 ops/sec ±3.42%
Note: minified with Closure compiler, not gzipped
After running these tests, I discovered a much more in-depth test-suite of promise libraries which reveals similar overall results.
The differences in performance may be negligible in a real application but in my Benchmark.js tests, when.js comes out as a clear winner. This combination of speed and the small size of the library make when.js a great choice when considering performance in the equation.
Clearly there are tradeoffs to consider when choosing a promise library. The answer to which library you should use depends on your specific use case and the needs of your project. Some implementations to start exploring are:
  • When.js: Fast, lightweight implementation that has a number of useful utilities and as of v2.0 has full support for asynchronous resolution.
  • Q.js: Runs in the browser or Node.js, offers a robust API and is fully Promise/A compliant.
  • RSVP: Barebones implementation that is fully Promise/A compliant.
  • jQuery: Not Promise/A compliant but is widely used. If you are already using jQuery in your project it’s easy to get started with and worth a look.

Angular JS ajaxComplete

I recently came across a problem where our ajaxComplete function wasn't being executed from jQuery after we started using Angular.  As it turns out (it was a bit of a "duh" moment) the issue was that when using Angular we were no longer using the jQuery ajax calls.  So the jQuery ajaxComplete function was never fired because no jQuery ajax calls were ever made.

That set me on a path of trying to figure out how to mimic the ajaxComplete behavior with Angular and this is what I came up with.  I haven't fully tested it, but wanted to put it up here before I forget so I can have a better starting point next time this comes up.

After the application has been created, configure the $httpProvider to have an intercept:

angularApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.interceptors.push(function ($q) {
        return {
            response: function (response) {
                return response;
            }
        };
    });
}
]);

This particular implementation won't do anything but act as a pass through, but it can be modified however necessary to meet your needs. 

Tuesday 30 June 2015

How to enable assembly bind failure logging (Fusion) in .NET


A good place to start your investigation into any failed binding is to use the "fuslogvw.exe" utility. This may give you the information you need related to the binding failure so that you don't have to go messing around with any registry values to turn binding logging on.
The utility should be in your Microsoft SDKs folder, which would be something like this, depending on your operating system: "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\FUSLOGVW.exe"
1) Run this utility (it has a GUI) and set the settings to "Log bind failures to disk".
2) Click "Delete all" to clear the list of any previous bind failures
3) Reproduce the binding failure in your application
4) In the utility, click Refresh. You should then see the bind failure logged in the list.
5) You can view information about the bind failure by selecting it in the list and clicking "View Log"
The first thing I look for is the path in which the application is looking for the assembly. You should also make sure the version number of the assembly in question is what you expect.

Friday 15 May 2015

Asp.Net MVC Design Pattern

Presentation <---> Business Logic <---> Data Access
Firstly, it's best to not think of the the app as "an MVC application". It's an application that uses the MVC pattern as its presentation component. Thinking about it this way will help you separate out your business logic concerns from your presentation concerns. Perhaps it's ok for small applications to pile everything down to database access into the MVC structure, but it'll quickly become untenable for a mid-to-large application.
MVC (Presentation)
In your app, the ASP.NET MVC component should deal with transforming business data for display purposes (Models), displaying the user interface (Views), and communication issues such as routing, authentication, authorization, request validation, response handling, and the like (Controllers). If you have code that does something else, then it doesn't belong in the MVC component.
Repository/ORM (Data Access)
Also in your app, the data access layer should be concerned with retrieving and storing persistent data. Commonly that's in the form of a relational database, but there are many other ways data can be persisted. If you have code that isn't reading or storing persistent data, then it doesn't belong in the data layer. Eric King's thoughts on the ORM/Repository discussion can explain that, I don't consider an ORM to be the same thing as a Repository, for several reasons.
Business Logic
So now you have your presentation layer (MVC), and your data layer (repository or ORM) ... Everything else is your business logic layer (BLL). All of your code that decides which data to retrieve, or performs complicated calculations, or makes business decisions, should be here. I usually organize my business logic in the form of 'services', which my presentation layer can call upon to do the work requested. All of my domain models exist here.