Certification 70-486: Developing ASP.NET MVC 4 Web Applications

Last week, I took the exam for Microsoft Certification 70-486: Developing ASP.NET MVC 4 Web Applications and passed successfully and scored 831. This was my first exam after almost two years. Although, the exam format and questions’ style did not differ, I certainly noticed some differences.

The number of questions were 45, and the questions were spread in proportion:

22 general questions
23 questions in 3 different scenarios

The test included 3 different scenarios to analyze, and it required a good amount of time to spend on reading code and business requirements of the scenarios in order to be able to answer the questions. Although the scenarios were quite different, it was very easy to mix the requirements, so a good focus had to be put to remember the requirements of each scenario.

The questions were practical, but not easy. They were focused on details of specific features. I was introduced with good amount of questions regarding session management, especially in distributed environments, security implementation, debugging, azure deployment, and related to controller implementation.

To anyone who is preparing to take the exam, my recommendation is to put a focus on the topics above mentioned.

I hope this helps.

AngularJS at its simplest form

AngularJS is a very hot topic nowadays amongst web developers. It seems to be having a

AngularJS

AngularJS

momentum and as such getting high attention and interest. Being an extensible javascript framework and excellent framework for developing Single Page Applications (SPA), it is feature rich and evolving very fast.

As learning such a huge and fast growing framework could seem to be hard at the beginning, I will try to take a very simple form of it, and try to explain how can we create an AngularJS SPA at its simplest form. For the sake of demonstration, I will create a web page which displays basic contacts of famous web developers.

AngularJS is a Model-View-Controller framework, where Model serves the data, Controller takes the data from Model and delivers to View, and View displays the data. As we want to display some data, we need all three of the components. We have our contacts, which is our Model, then we need a Controller which will deliver the contacts’ list to the View, and we need a View to display the contacts’ list.

Before we start to create components, we need to define the Angular module which will form the base of our SPA, and it is done through this line of code:

var angularEg = angular.module('angularEg', []);

A new module is defined using angular.module. The first argument defines the name of the module, and the second argument specifies other required modules. We will leave it as an empty array as we have no dependency on other modules for this example. Although the second argument is optional, it has a significant meaning. If not specified, angular will look for an existing module with the name specified at the first argument, otherwise if specified a new module will be created.

Lets create now the components one by one.

Model

Our contact card will display contact’s name,  country, and his web page URL, so we need an object which will hold these data. Our model will look like this:


{
name: "Scott Hanselman",
country: "USA",
web: "http://www.hanselman.com"
}

This represents a single contact, and our Model will contain an array of such objects.

Controller

The controller in our case has only one duty, to make the data available to the view, so lets first define the controller using this code:

angularEg.controller('myContacts', function($scope){

});

The first argument to controller creation is the name of the controller, which in this case will be ‘myContacts’ and the second argument is the controller implementation. The $scope variable is the connection between the Controller and the View, and it is used to pass information from Controller to the View. The controller can get the data from model in various ways like loading data from a file, from an internal/external web service, etc. To keep it simple, I will hard code the data inside the controller.

angularEg.controller('myContacts', function($scope){

$scope.contacts = [{
name: "Arian Celina",
country: "Republic of Kosova",
web: "http://18.197.31.180"
}]
});

The controller is ready, lets continue with the view.

View

Our view will be a standard html page which displays the above specified information in div blocks. There are three things we need to do in view in order to bind the information from controller.

1. We need to specify that the view is for the angular module we have created and we do this by putting ng-app attribute in html tag

<html ng-app="angularEg">

2. We need to specify which part of this view is bound to which controller, and we do this by attaching ng-controller directive to the relevant container, in this case I will do it in body. This can be done in a granular level such as a specific div, or a global level such as body.

<body ng-controller="myContacts">

3. We need to display the contacts. There is a directive in AngularJS specifically to display collection of data such as arrays, and it is ng-repeat. I will repeat contacts and display them in this way:

<div class="w-row" ng-repeat="contact in contacts">

<div class="contact-brief">
<h2 class="contact-name">{{contact.name}}</h2>
<div class="contact-info">Country: {{contact.country}}</div>
<div class="contact-info">Web: {{contact.web}}</div>
</div>

</div>

The ng-repeat directive iterates through collection of contacts which he gets from the controller “myController” (remember, we defined variable contacts in $scope). A local variable contact is defined inside ng-repeat, this gives us the opportunity to access the object in iteration and access its properties and then the data binding is done by specifying the property and enclosing it with double brackets like {{contact.name}} (the handlebars syntax).

AngularJS will iterate over the array $scope.contacts and add the above specified div to the DOM for every element in the array.

The resulting app can be seen online on http://18.197.31.180/angularexample/index.html. Feel free to get the code from GitHub and play with it.

 

There is life beyond jQuery

I am a huge fan of jQuery library. For years, jQuery has been my ultimate tool for client side development, and I have used it in any web project I have undertaken. Few weeks ago, I took a project to develop a simple brochure style web site, which had to display a couple of static data, and I decided it to be a Single Page Application (SPA) for the sake of the simplicity and reuse of the page templates.

At the beginning, my idea was to do the dom manipulation with jQuery and templating using jsRender library, but during the planning phase, I thought I should take into consideration using a SPA framework or library. I did a little research on the web, consulted a friend of mine, and then shortened my list to DurandalJS and AngularJS. After giving a quick try to each of them, I decided to go with AngularJS.

Using HTML templates for pages and binding data to the templates was dead simple in AngularJS. The biggest implementation challenge on the project was the internationalization, as the site is multilingual in four different languages. With the help of Angular translate module I managed to translate the labels very easily, and by extracting the language using route params I made the app to decide on the language of controler. The app worked like a charm.

On overall, I managed to finish the whole project within three working days and the most interesting part for me was that I managed to do it without using jQuery at all. Ever since I have started to use jQuery, this is the first project that I have finished without using jQuery. I still think that jQuery is an amazing library and I will continue using it in the future, but there is one other thing, that certainly, I will start using more and more AngluarJS as well.

Multiplatform development with Phonegap

It has been a while not being active in blogging. I have been engaged in a project developing mobile applications for a tourism project in Kosovo. The project entailed development of three mobile applications for the needs of the project in three major platforms, iOS, Android, and Windows Mobile.

As the requirements were to develop the very same functionality and look in all platforms, the first thing that came to my mind was to use in HTML5, CSS3, and JavaScript combination. I would share the same code and design in three different platforms and finish the project in a faster time.  After a short analysis and readings, I came to decision to use jQuery mobile and PhoneGap. Now that everything is finished, I would like to describe my experience here so you can make a better judgement when you start your own project.

Goods

The initial start of the project was a fairytale. I managed to customize the jQuery mobile theme and adjust the design as needed and created the prototype within a week. It was a nice piece which satisfied the needs of my client. I used the PhoneGap build which made my job easier. There was no need to install anything and was using a text editor to write HTML + CSS + JavaScript code.

PhoneGap is an excellent tool to build non-native applications in an amazingly fast way. Our application was a basic brochure which did not require a native experience and HTML5 app was doing a great job.

Leverage existing knowledge

Leveraging existing knowledge was the main motivation behind going non-native development. My experience in designing and developing web applications was a great help in immediately starting to develop the applications.

Shared functionality

Although I managed to port around 70% of the functionality in all three platforms, the idea of write once run anywhere is a fallacy. I faced the most problems when porting to Windows Phone. The browser was not rendering well the look and feel and had to do some custom tricks to adopt. Also there was a bug with back button event in jQuery mobile which was not reacting well to Windows Phone back button event. Apple iOS and Android platforms were working fine with minimal differences.

Easier maintenance

Maintenance is a huge cost factor in the lifecycle of an application, and mobile applications make no exception on this. Having the same codebase made changes easier and faster. After deploying the first version, we saw the need to some updates, and having to touch same JavaScript or HTML code made propagation of changes to other platforms a matter of copy – paste.

Bads

After putting some images to the application, the application soon passed the size of 35 megs. PhoneGap build does not support applications larger than 15 MB. As my app was larger I had to build them locally. This required separate installations of mobile development platforms and the PhoneGap build itself, and required to have a Windows PC and Mac computer.

Some performance issues

PhoneGap and jQuery mobile is a good combination, but, there are some performance implications though. It is not hard to notice some latencies on clicks. There are some performance improvement tips and tricks out there, but you have to do a little research and customizations to achieve a desired performance level.

Overall opinion

In general, my experience developing these applications was OK. I managed to create three applications within a month and a half, which deadline, I’m sure I would not be able to meet if I would have chosen to develop in native platforms. Depending on the requirements, if there is no need for a very fast application, such as games or any real time communication application, I would recommend  PhoneGap. When it comes to jQuery mobile, on my next project I will test another framework first and then post my recommendation 🙂

JSONP request to your WebAPI service

A day ago, I was trying to prepare a demo on how simple it is to make a cross domain AJAX request to a web service, and display the JSON result in a friendly HTML div using jQuery AJAX method.

I created a simple WebAPI controller, which had a method which returns a IEnumerable<MyObject> of a list of objects, and published it to a Windows Azure Cloud Service. The Web Service was working like a charm.

When I created the jQuery code, which was as simple as this

$(function () {
var url = "http://webprogramming.cloudapp.net/api/Kompanite?callback=?"

$.getJSON(url, function (data) {
$.each(data, function (index) {
//place info in a div
});
});
});

and was supposed to work smoothly. But, as opposed to a working code, I started to receive no results. I started to catch ajax errors, and saw that the callback function was not being called. After three hours of research, I came through this “JSONP with ASP.NET WebAPI” StackOverflow question, which explained everything. The answer was that, by default, the result of WebAPI was not prepared to deal with callback required for JSONP. You need to have a special JsonMediaTypeFormatter which can handle this kind of situation. After I copied/pasted the formatter class from the answer, and cofigured it in Global.asax’s Application_Start() method through this line:

config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

the jQuery code started to work like a charm. So… if you fall into a similar situation, please make sure you implement your own JsonMediaTypeFormatter to support JSONP calls to your web service.

ASP.NET 4.5 & Security Exception

Lately, while trying to put in live a web application to my GoDaddy hosting account, I started to face some errors which were not present at my local development machine. I was receiving Security Exception with a generic error stating no much information to lead me to the correct cause of the error. Then I remembered that GoDadddy has set its security level to Medium Trust. After solving this problem, I thought it would be good to share this so here is my post regarding ASP.NET 4.5 Security Exception.

In order to simulate the environment, I added the following line to my web config file:

<trust level="Medium" />

Immediately, I started to receive the very same error locally. After trying few possible solutions, removed some libraries I was using, I was still receiving the very same error with slight  changes in the stack trace, but still no help.

==============================================================================

Security Exception

Description: The application attempted to perform an operation not allowed by the security policy.  To grant this application the required permission please contact your system administrator or change the application’s trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type ‘System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089’ failed.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

==============================================================================

Then I decided to test my solution in an environment with .NET 4.0 (not 4.5 as in my current development machine), and… voi·là, the application was working like a charm.

So, the first time, I really had problem with a library which was not able to perform under medium trust, however, what really mislead me was the Security Exception thrown by .NET 4.5 under medium trust. After a short research, I discovered that this is an issue to many developers and libraries such as DNN, and some others. I hope Microsoft will soon address this.

So  you who use Visual Studio 2012, if you receive Security Exception under medium trust, please try to run your application in an environment with .NET 4.0 to test if the problem is with the .NET itself.

Hope this helps.

Programming in HTML5 with JavaScript and CSS3 – 70-480 Microsoft Certification

Programming in HTML5 with JavaScript and CSS3 (70-480) certification, is the entry point towards the new line of Microsoft Certified Solution Developer Web applications certification. Currently, there is a special offer for this exam, and it is offered for free. The voucher can be taken from here. This special offer also includes video training for this exam from Microsoft Virtual Academy.

The exam is prepared to test your knowledge on topics related to HTML5 (semantic structures, new HTML5 elements, data validation, etc.), CSS3 (selectors, layout management, box properties, animation, etc.), and JavaScript (DOM manipulation, events, exception handling, callbacks, etc.). Details about skills measured can be found on this link.

The knowledge gained from this training, can be used to develop web applications as well as Window Store apps.

What are you waiting for… Get certified 🙂

Optimizing ASP.NET web pages

With increasing usage of mobile devices for browsing the web, optimization of web pages has become a topic of utmost importance. Perhaps, this post is nothing more than stating the obvious, as techniques to be mentioned here are very well known for quite some time, yet, pretty often ignored or dismissed, leaving web pages bad performance.

In this post, I am going to describe some of the well known techniques for web page optimization and how they can be leveraged in ASP.NET web pages/applications. This post will cover:

  • Javascript/CSS placements
  • Bundling & Minification
  • Caching
  • Image optimization
  • Gzip compression
  • Number of requests
  • CDN

Let’s get deeper into the topic.

JavaScript and CSS placement

It is often encountered that developers leave all CSS links and JavaScript (JS) references at the Head section of a page. Interpretation of the HTML code by the browser goes in a sequential way, so the browser downloads resources as they come, and until resource in the queue is downloaded, it stops downloading other resources if they are at the same host. As such, when source hits JS reference, it will block loading further until these JS files are downloaded. In most cases, JS files contain code related to functionality, and it is acceptable that functionality not to be available until the whole site is loaded.
Whilst, CSS files are required for proper appearance of the site. This suggests us, that CSS files usually have a higher priority for loading than JS files. As such, if we leave all CSS links at head section, and move all JS references at the bottom of the page, right before the body end tag, we will make the page appear before the whole site is loaded, thus giving a faster load time impression.

E.g.


<html lang="en">
<head>
<link type="text/css" reference="stylesheet" src="~/styles/style1.css"/>
<link type="text/css" reference="stylesheet" src="~/styles/style2.css"/>
<link type="text/css" reference="stylesheet" src="~/styles/style3.css"/>
</head>
<body>
...
</body>
</html>

Bundling & Minification

Bundling is a technique used to collect all CSS files into one CSS file, and all JS files into a one JS file. ASP.NET as of version 4.5 has bundling and minification functionality included. Older versions can get System.WebOptimization packag by downloading it from NuGet.

When you create a new MVC 4 web application from Visual Studio, you get bundling and minification set up by default. Bundling and minification code can be found in App_Start folder within the solution, in BundleConfig.cs file. Here you may add files to be bundled and minified one by one by registering them with their relative path like this:

bundles.Add(new ScriptBundle("~/bundles/libs").Include("~/Scripts/libs/jQuery.js"));

This code creates a virtual path “~/bundles/libs” and includes JavaScript file jQuery.js. You can include as many files as you wish, and they will be bundled in the order you have included them. You can also specify a pattern to include such as "~/Scripts/libs/*.js" and this will include all JavaScript files in that folder. In the case of pattern, files will be loaded alphabetically, with consideration of known libriaries, such as jquery will be loaded before your custom libraries, and before jquery.UI.

It is important to note that, bundling and minification will happen only when the application is on “Release” solution configuration. When in debug mode, bundling and minification will not happen.

Caching

Caching is a technique used to create a temporary faster storage of commonly used content. Caching can be done on two levels:

  • Server side
  • Client side

When done server side, we load commonly used content to memory, and serve from that place instead of other sources such as HDD, DB, etc. ASP.NET provides support for server side caching through HttpContext.Current.Cache. However, server side cache helps with dynamic content. On the other side, a good part of web page load comes from static content such as JavaScript/CSS files, images, etc. Static content can be cached on client side. By this, we tell the browser what content can be saved locally for some time, and until that date is expired, the browser should not ask the server for that content. We can influence client caching through using a Manifest file or by saying the IIS to write caching headers on responses for static content. This can be done by adding this code in Web.config file.


<system.webServer>
<staticContent>
<clientCache cacheControlMaxAge="365:00:00" cacheControlMode="UseMaxAge"/>
</staticContent>
</system.webServer>

This will tell the client to cache static content for a year from the date of request.

Image optimization

Optimizing images is a crucial point on web optimization. Most of the sites today have a lot of images, and by optimizing them a lot of page load size can be saved. Images can be optimized by using a image editing software. From Visual Studio, an extension called Image Optimizer can be used to optimize images.

Image optimizer extension for Visual Studio

This extension will allow you to right click an image, or an image folder and select Optimize images option, and it will do the optimization for you.

Gzip compression

Gzip compression is a server side functionality for compressing the content sent to a client. By default, compression is enabled from IIS7.5 and above. If compression is enabled on web server, then we can influence this behavior from web config by specifying this:

<system.webServer>
<urlCompression doDynamicCompression=”true”
doStaticCompression=”true”
dynamicCompressionBeforeCache=”true”/>
</system.webServer>

If values are specified to false, then this will stop compression.

If you are using IIS Express, then you can activate compression by executing this command from iis express folder

appcmd set config -section:urlCompression /doDynamicCompression:true

Number of requests

By HTTP specification, the browser should download at most 2 resources in parallel from the same host. Most browsers comply with this, or up to 4 parallel downloads. This means, if there is a high number of requests to retrieve the whole site, the page load time will be slow.

This bottleneck can be addressed in different ways. Bundling & minification is one way to decrease the number of requests. CSS Sprites as well as embedding small background images to CSS also will help on this. One other way to help this is by putting resources in different hosts. Even subdomains will help on this, for e.g. putting images, scripts, and css on different subdomains like this:

images.host.com
scripts.host.com
css.host.com

will make the browser believe it is downloading files from different resources and throw more threads for parallel downloads.

Content Delivery Networks (CDNs)

CDN is a way to optimize a web page as well as save bandwidth at the same time. Most common libraries used, one of them being jQuery, are hosted by CDN providers such as Microsoft, Google, etc. You can even use custom CDNs such as Akamai and host your content.

CDNs will optimize content download from a geographically close location to the requester. This will also benefit from the fact that the browser will see a different host from your side, and will throw another thread for downloading content from CDN.

The techniques mentioned in this post are by no means all what can be done to optimize ASP.NET web pages. There are many other techniques with more specific usage and help optimization of web pages.

Train yourself on ASP.NET web development

I have always been supporter of the formal education as a primary way of one’s intellectual forming. However, there are times you need a quick push on a topic you have no experience, or formal education. If this is your case, then here is my advice.

You need to have a curriculum to support your knowledge development, instead of trying to grasp the topic from blog posts and internet pages. As humans tend to learn visually faster than by reading, starting with video training would be a better choice.

Pluralsight is a video training provider for developer topics with videos prepared by some of the most known authors and industry experts of software development community. From the range of the courses offered, here is a learning path I would suggest, from the range of training provided from Pluralsight.

Lets start progressively, from basics to more advanced topics, so here are the courses in this order:

  1. HTML Fundamentals
  2. HTML5 Fundamentals
  3. Using HTML5 and CSS3
  4. JavaScript Fundamentals
  5. Structuring JavaScript Code
  6. jQuery Fundamentals
  7. A Web developer’s guide to images
  8. ASP.NET MVC4 Fundamentals
  9. Building Applications with ASP.NET MVC 4
  10. Building ASP.NET MVC Apps with EF Code First, HTML5, and jQuery
  11. Web performance
  12. Scrum Fundamentals

This curricula is prepared in a way so you will progressively develop yourself to be a web developer. First, you will start with HTML, then continue with HTML5, the hot topic of our time, and proceed further with mixing HTML5 and CSS3 to create modern sites. After that, the curricula continues with JavaScript, the ultimate language of browsers, to continue with a guide to images,  and then further advance with server side programming using ASP.NET MVC framework. At the end, course finishes with Web performance topic to create optimal fast loading sites, and Scrum fundamentals, to develop a structured software development process. 

If you follow this path, my suggestion is that you allow yourself at least two months, if not more, to go through these courses.

I would like to hear your opinion, especially about the results if you have followed this learning path.

Zen Coding

Zen Coding is a plugin for HTML, XML, XSL, CSS fast code editing which could be used in different text editing software and/or IDEs. Recently, through the Web Essentials VS Extension, Zen coding is also available in Visual Studio. This functionality is activated by pressing TAB key right after you write the zen code.

Zen coding has a specific syntax, and the code is created by combining html tags and ‘zen code operators’. These operators include :

Operator Operation
# Create ID attribute
> Child element
. CSS style
* Mutiplication of elements
[] Custom attribute
+ Sibling element
^ Climbs one hierarchy level up

Let’s demonstrate these by examples.

Specifying the ID

If we want to create a div element which has an id named container, then we would write

div#container and when we press TAB, and the result will be <div id="container"></div>

Creating child elements

If we want to create nested elements, then we would use greater then (>) symbol to specify nested elements. Writing ul>li produces

<ul>
<li></li>
</ul>

with proper indentation.

Adding CSS class to element(s)

The dot symbol will add css class to an element. Modifying the last example code to ul#menu>li.menuItem will produce

<ul id="menu">
<li class="menuItem"></li>
</ul>

Creating many elements

If we want to create more than one element of the same type, then we will use multiplier (*) operator. If we write ul#menu>li.menuItem*5 the result will be

<ul id="menu">
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
<li class="menuItem"></li>
</ul>

Creating custom attributes

In some cases, there is a need for custom attributes (e.g. new html data-dash attributes). Let us modify our last example so it includes a data-value attribute. If we write ul#menu>li[data-value].menuItem*5 and press TAB, the result will be


<ul id="menu">
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
<li data-value="" class="menuItem"></li>
</ul>

We can even give a default value to the attribute by changing attribute section to [data-value=val].

Creating sibling elements

Let us create a div for search with an id equal to ‘search’ and two input elements inside, one textbox and one search button. Our zen code would look like this:

div#search>input[type=text]+input[type=submit,value=search]

and it will produce

<div id="search">
<input type="text" value="" />
<input type="submit" value="search" />
</div>

Level up

The caret operator (^) enables us to go one level up in hierarchy. E.g.

Code div#container>div#element1^div#element2 will produce this HTML

<div id="container">
<div id="element1"></div>
</div>
<div id="element2"></div>

This is it folks. I hope you like it.