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.

Social Innovation Camp Kosovo

Last weekend, I had the pleasure and opportunity, to be mentoring for the second Social Innovation Camp Kosovo, together with Dan McQuillan, Fisnik Ismaili, Laura HahnPeter Manning, and Josh Harvey .

 

During a 48 hours challenge, six groups of young Kosovars tried to make reality the idea they had proposed, which intended to make a social impact in Kosovo. After 48 hours of hard work and fun, teams came up with the prototypes of their ideas, went out to test their prototypes with other people, and then presented their prototype together with the impressions gathered outside, in front of the independent judge panel.

After all the fun and hard work, three teams excelled and won prices to continue forward their ideas. The winners were:

  • Eventor – A project which intends to put together events and scholarships for Kosovars, and make them available for students and others to get informed.
  • KapLexo – An idea around book exchanging for second hand books, while making also possible for people to review, comment, meet and discuss, about the books they like and have read.
  • ParkingLot – An idea which intends to make free parking slots in maps (web and mobile) through social participation.

Personally, I would like to thank UNICEF Innovation Labs Kosovo for making this event possible, which creates opportunities for young people to start new projects which could have positive impact in Kosovo.

My productivity apps

As for most of us, time is the most precious and scarce resource we have. I am passionate about organizing my time, but I would say that would not be easy without using some very good apps.

Daily tasks

Organizing daily tasks is a crucial activity towards increasing the productivity during the day. My daily tasks do cover all major activities I should perform during the day. As such, I need something which could give me a way to track the activities, track what’s done and what’s pending, as well as separate tasks based on relativity. My favorite app for this is Wunderlist. It is present in all major mobile platforms, as a Windows app as well as from a good web access. It has features like creating lists of tasks, setting reminders, due dates, sub-tasks, and notes on tasks.

Development tasks

When organizing my development tasks, I do use Trello. It offers to create boards of cards, where in a card you can write a simple description, or a detailed checklist of tasks, set due dates, attach files, comment, and share it with others. You can create mini boards within a board, which could make easy to represent the development stages, and move cards from stage to stage to help agile development.

Time tracking

When we work on projects, it is often required to track how much time we spent on a specific project, or a task, I do use Toggl. It is a very simple tool, which is focused on time tracking. It can help also if you use productivity methodologies such as Pomodoro.

Using these apps, I do manage my day to day activities, and would recommend to anyone.

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.

My impressions on 70-480 certification

In my last post, I gave some details about the Microsoft’s campaign on 70-480 Programming in HTML5 with JavaScript and CSS3 certification. As many out there, I decided to benefit from this offer as well as challenge my knowledge a little, and took the test today. Fortunately, I did pass the certification. In this post, I would like to share with you my impressions on 70-480 certification exam.

This certification was recently introduced by Microsoft, with the new MCSD line of certifications. It counts as a credit towards two MCSD lines: Web applications and Windows Store Apps using HTML5. As such, it is an important exam for those who do want to certify their knolwedge in Web front end development as well as developing windows HTML5 apps using JavaScript and CSS3.

The title of the exam, and the skills measured might make you think, this is a pure Web Development certification, and might disorient your expectations, as it did to me :). I also had another miscalculation. As I have several years of experience in web development, I thought that there is no need to learn much about this. But, there was a difference between what I use daily and what I was going to be tested on.

One of the two main topics on questions I faced (which counted more than 10% of total questions) were about making AJAX requests, and manipulating DOM. On my daily job, I use jQuery to perform these tasks, and rarely touch pure JavaScript functions to do this. As the exam was to cover the web path as well as Windows store app development path, questions were generic, without using libraries such as jQuery. This was a part, I did not take care much, however, now that I passed the exam, I learned a lot about this part too, and this is the benefit of getting certified.

Apart of these details, the questions in the test, were mainly focused on data validation, making client side requests to WCF web services, manipulating DOM, creating and using Web Workers, inheritance in JavaScript, layout formating using CSS3, and new HTML5 elements.

So, my advice to those preparing for the test: prepare to be tested on pure JavaScript, HTML5, and CSS3. Forget about libraries you use on your daily programming. Good luck.

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.