The best JavaScript MVC framework

I’m a great believer in frameworks as they provide a SOLID and well tested infrastructure for you solutions. Modern web apps are base on a almost excessive amount of JavaScript on the client side and REST services on the server side. There are a lot of frameworks that support this and the challenge for developers is to figure out on which one to invest their time on. Even if  the teams behind the products encourage to mix these, the reality is that  doing so will only result in hacks – in other words the framework needs to be complete.

So, on what horse did I decide to bet on? The answer is AngularJS.
Why? Let me telly you:

  • It tells a lot about a framework if the most basic examples reveal many features but are also easy to understand
  • Unlike the jQuery+Knockout+whatever combos it provides a complete framework which not only guides developers to setup the app in a certain way but also supports testing by design
  • It is a product of a big company (Google) but unlike Kendo it is 100% free making it easy to to take into use and to find developers already familiar with it. Not to mention that it is actually possible to find reviews without any commercial BS.
  • Unlike e.g. Ember it is a mature framework with a good online documentation and active community.
  • It provides templating by allowing to extend the standard set of HTML/DOM elements with your own components. Personally I find this approach most intuitive and clear.
  • The apps are based on controllers, directives, filters and services. There is a inbuilt support for dependency injection.
  • Unlike Knockout there is no need to use special observable object types in your model to get the data binding to work.
  • The Chrome and Angular teams have worked together to provide a browser add-on to help debugging.
  • It has no (inbuilt jQuery lite) dependencies on other frameworks unlike backbone, ember and most others.

Time will show if my investment pays off 🙂

Worth reading:

SharePoint Web Part Basics

All web parts are based on the same basic ingredients. When I started developing on my first web parts I did some extra work to find out the best practices. This post is meant to work as a simple reference and to answer some of the questions I had when I first started.

What web parts events should I use?

There are many different opinions on this. This is mine:

  • Never put code in the constructor as it might be called even if the object is later never used
  • In the OnInit initialize any controllers etc. you might have
  • In the CreateChildControls method create your controls, but don’t populate them. Note that it is a common practice to define all the controls and the wepart layout in a separate control class to keep the web part clean.
  • In the OnPreRender load the data into the controls and setup any async task you might need (they will be executed next)

How to register JavaScript?

There are many ways to include JavaScript on a page, the right one depends on your need. To include a script to to be executed directly after page load use the RegisterStartupScript combined with the ExecuteOrDelayUntilScriptLoaded (SOD) or _spBodyOnLoadFunctionNames.push functions:

public static class SharePointScriptHelper
{
public static string ExecuteOrDelayUntilScriptLoaded(Control control, string script, string after)
{
string script = string.Format("ExecuteOrDelayUntilScriptLoaded(function(){{{0}}}, '{1}');", script, after);
ScriptManager.RegisterStartupScript(control.Page, typeof(Page), "Script_" + control.ID, script, true);
}
}
SharePointScriptHelper.ExecuteOrDelayUntilScriptLoaded(this, "alert('Hello world!');", "SP.js");

The first mentioned takes care of the correct load order of scripts.

To include e.g. a library that is not meant to be directly executed use e.g. the RegisterClientScriptInclude method:

ScriptManager.RegisterClientScriptInclude(this.Page, typeof(Page), "MyScriptNamespace", ScriptFileUrl);

The point in using the ScriptManager is to avoid having the same script included multiple times, hence the key parameter in e.g. RegisterclientScriptInclude. The class offers a lot of functions that are worth taking a closer look at.

Note that is is a good practice to wrap you scripts in a “class”/namespace to avoid e.g. function name collisions with other scripts.

To easily include the web part id in your inline scripts you can use the ReplaceTokens function of the web part class to do this. It will simply replace tokens like e.g. _WPID_ with the correct property values.

How to include CSS on a page?

CssRegistration css = new CssRegistration();
css.After = "corev4.css";
css.Name = Settings.StyleSheetFileUrl;
this.Controls.Add(css);

I have not yet had a chance to test SharePoint 2013 to see if it works to refer to the corev4.css also in that version.

Where to define configuration parameters?

The web part definition file (yourwebpart.webpart) is definitely the only correct place. This way they the properties are fully customizable by the site owners when necessary.

Never store passwords in any file as they belong in the secure store service. You can prevent property values from being exportable for a simple way of hiding them.

How should I define my layout?

The most flexible and powerful way is to use XSLT for the rendering. You can implement it your self or inherit the DataFormWebPart class.

Where should I put the CSS, image and other files?

Put them in the appropriate SharePoint mapped folders. Always create a sub folder for you web part and give it a unique name e.g. based on the namespace of the main class.

How to do logging and debug?

Use the inbuilt framework. The most elegant solution would be to write your own service class deriving from the SPDiagnosticsServiceBase but note that it will need to be registered at deployment time.

public static class SPDiagnosticsServiceExtension
{
public static void WriteTrace(this SPDiagnosticsService service, string message, string categoryName, TraceSeverity severity)
{
SPDiagnosticsCategory category = new SPDiagnosticsCategory(categoryName, TraceSeverity.Unexpected, EventSeverity.Information);
service.WriteTrace(0, category, severity, message);
}
}

Usage

SPDiagnosticsService.Local.WriteTrace(ex.ToString(), "Web Parts", TraceSeverity.Unexpected);

I strongly recommend enabling the Developer dashboard and using the SPMonitoredScope to help optimize the performance of your web part.

That’s all for now, more to to come later.

The evolution of web development

Now over 13 years back I worked as a professional web developer. In those times JavaSscript was just something used to validate forms and anything else (e.g. toggling the visibility of a element) was considered fancy and labeled as DHTML. Few weeks ago I got a email from a co-worker having problems with including inline JavaScript in a ASP.NET razor page – this got me on memory lane.

Back in the days the code to open a popup window could look like this

<p><a href="javascript:window.open('http://www.google.com','mypopup')">Open google!</a></p>

This not only displayes as a scary link in the browsers status bar but also is useless in browsers not running JavaScript. So quite quickly the developers shape up and started putting the code in a separate JS file and using the events available:

function popitup(url) {  window.open(url,'mypopup'); }
<a href="http://www.google.com" onclick="popitup(this.href);return false;">Open google!</a>

This was fine for many years. But then it became modern to write nonobtrusive code (keeping the scripting and visuals separate). Even if this in practice requires a lot more code frameworks like jQuery make it easy.

window.onload = function() {
var myPopupLink = document.getElementById('myPopupLink');
if(~myPopupLink) myPopupLink.onclick = function() { popitup(myPopupLink.href); return false; }
}
<a id="myPopupLink" href="http://www.google.com">Open google!</a>

What next?