Tag: Front End
JavaScript frameworks explained to an ASP.NET dev

JavaScript frameworks explained to an ASP.NET dev

For most of my career I've been an ASP.NET dev and a JavaScript dev. If I was going to say I was more of an expert in one of them it would be the .NET side of things but I've never really lost touch with JavaScript.

Right now I think it's fair to say technologies in the world are starting to shift how we build websites, with JavaScript frameworks reaching a point with features like static site generation where they actually now offer a decent performance incentive to use them. At some point Blazor may get to a point where it reverses this, but right now there's a compelling argument to move.

For a ASP.NET dev this can be a daunting task. You might be thinking of trying out a headless CMS with a JavaScript front end, but just take a look at this screen grab from Prismic's sdk list.

There's 7 different JavaScript based SDK's listed there! Over half of the total and none of them are that Angular thing you had heard about. Where do you start?

Lets compare to .NET

Well recently I've been updating my JS skills again trying out some of the frameworks I hadn't used before, so I thought I'd share some learnings. The good news is as always it's not really as different as it first seems. To take some of the pain out of understanding what all these frameworks are I thought it would be good to try and relate them back to .NET and what the almost equivalent is.

Assembly Code

No not actual assembler but what does our code actually compile to. In the .NET world we have CIL (Common Intermediate Language), previously known as MSIL (Microsoft Intermediate Language) that our C#, F#, VB etc all compile down to before then being converted to the correct machine code for where they run.

In the front end world think of JavaScript being a bit like this (apart from the fact you actually write JavaScript and we don't write CIL).

View Engine

To render views into HTML, in the ASP.NET world we have Razor, but not just Razor. We also have WebForm, Brail, Bellevue, NDjango (see more here), it just happens that we mostly just use Razor.

I see the equivalents of these being ReactJS, VueJS and Angular. Its not an exact match as they also aren't exact equivalents or each other, but they're largely your functionality that will take a model and turn it into HTML.

Web Application Framework

The problem with the name framework is it applies to basically anything, but this is what I'm going with for describing ASP.NET MVC/ASP.NET Razor Pages/Web Forms, you know all those things built on-top of .NET that make it a website rather than a desktop app. They do things like routing, organising our files into controller and view folders, know how to respond to http requests etc.

Here we have Next.js, Nuxt.js and maybe Gatsby. The link between these and View Engine is a bit stronger than the ASP.NET MVC world as you essentially have a one to one mapping Next.js -> React, Nuxt.js -> Vue but they are what adds routing, static site generation and organization to your code.

Lower Level Framework

Now this one could be wrong :)

In .NET we have different version of the framework. e.g. .NET Framework /3.5/4, .NET Core, .NET 5, Mono. On the front end side they have Node.

Languages

In .NET we have choices including C#, F#, VB among other.

JavaScript has JavaScript (which I know I said was assembly), TypeScript, Coffee Script maybe more.

Not so daunting

There's probably a bunch of flaws with my comparison list and reasons people can point out why things I've said are the same are in fact different, but my point was really to show that while .NET may appear as one button on a SDK list alongside 7 JavaScript based SDK's its not that different. Out of the 7 Node is based on JavaScript. Vue and React are based on Node, and Next/Gatsby/Nuxt are based on Vue/React. There just isn't the same concept of all of it being built by one company or one particular combination being dominant in the same way that ASP.NET MVC + C# + Razor has been for the last generation of .NET websites.

Bundling and Minification with Sitecore

There's various ways to add bundling and minification to a site, but one of the easiest is to use Microsoft's support from the Microsoft.AspNet.Web.Optimization package. This implementation has some great features including:

  • Automatically create the bundles and minify them as files are changed
  • Create unique urls to each version of a bundle to force browser refreshing of the file
  • Debug mode which outputs links to the raw files rather than the bundled minified version

The functionality is also fully compatible with Sitecore. To use it in your Sitecore solution follow these steps:

1. Add Microsoft.AspNet.Web.Optimization to your project from NuGet. This is the package from Microsoft that contains the functionality to do bundling and minification

 

2. Create your CSS and Javascript bundles. Where you put the logic for this is up to you but it will need to run when the application starts. Outside of Sitecore my main development is on bespoke ASP.NET MVC and Web API projects so I like to organise startup scripts into an App_Start folder and reference it from the Application_Start event in the global ascx file.

If you are running a Sitecore instance with multiple sites or if you do not have direct access to the production config files, it may be better to keep the logic separate and use a pipeline to create the bundles.

My bundle definitions would look something like this

1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Web;
5using System.Web.Optimization;
6
7public class BundleConfig
8{
9 public static void RegisterBundles(BundleCollection bundles)
10 {
11 bundles.Add(new ScriptBundle("~/bundles/scripts").Include(
12 "~/Scripts/jquery-{version}.js",
13 "~/Scripts/bootstrap.js"));
14
15 bundles.Add(new StyleBundle("~/bundles/css").Include(
16 "~/Content/bootstrap.css",
17 "~/css/site.css"));
18 }
19}

And in my Global.asax.cs file I would have some logic like this to call the other function

1protected void Application_Start(object sender, EventArgs e)
2{
3 BundleConfig.RegisterBundles(System.Web.Optimization.BundleTable.Bundles);
4}

3. Replace your Javascript/CSS references in your layout or rendering files with a call to render the bundle

Webforms

1<%: System.Web.Optimization.Scripts.Render("~/bundles/scripts") %>
2<%: System.Web.Optimization.Styles.Render("~/bundles/css") %>

MVC

1@Scripts.Render("~/bundles/scripts")
2@Styles.Render("~/bundles/css")

4. In your web.config file there are a couple of changes needed to get things to work.

First you need to set an ignore url prefix to stop Sitecore trying to resolve the URL to the bundle. In this example mine is called bundles (note: you should add the prefix the what is already in your config file. e.g. |/bundles)

1<!-- IGNORE URLS
2 Set IgnoreUrlPrefixes to a '|' separated list of url prefixes that should not be
3 regarded and processed as friendly urls (ie. forms etc.)
4-->
5<setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/bundles" />
6

Next a dependant assembly binding needs to be set up for Web Grease. Without it you will see an error about the Web Grease version number

1<dependentAssembly>
2 <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
3 <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
4</dependentAssembly>

If you have done this and are still getting a version number error check the assembly binding tag. Older versions of Sitecore have the applies to property set which may be only applying the bindings to .Net 2 and you may be using .Net 4.

1<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v2.0.50727">

5. If you are using IIS7 you will also need to make a change in your web.config file

1<system.webServer>
2 <modules runAllManagedModulesForAllRequests="true">
3 </modules>
4</system.webServer>

6. Publish your changes into your Sitecore site. Depending if you have compilation mode set to debug or not you will now either have a bundle reference for all your JavaScript and CSS or the individual file references.

Responsive Images in Sitecore

By default, when you add an image to a page in Sitecore using the <sc:Image > control it will render height and width attributes on the resulting html. These are based on the images dimensions or any height and width properties you may have set server side.

The benefit of doing this is that when the browser renders the page, it already knows what space the image will take up before the image has loaded. This reduces the number of repaints the browser has to make and ultimately speeds up the page rendering time. If the height and width weren't specified then a repaint would happen after the image was loaded as the size would now be known.

However this can cause an issue when you are producing a responsive site that changes its layout based on the size of a device or width of a browser window. Because responsive design is done though CSS media tags the server does not know what the height and width of the image will be, unfortunately there's also no built in way to tell Sitecore to stop rendering the height and width tags. Not very good when you want to size your image to 100% width of an area that can change size.

The solution is to create a Pipeline. Pipelines are Sitecore's way of enabling you change how Sitecore works and their not overly complex to implement.

To create a pipeline that will affect the way an Image field is rendered your first need to create a GetImageFieldValueResponsive class as follows. The name of the class can be anything you want but I've called it GetImageFieldValueResponsive as it will be called after Sitecores GetImageFieldValue class.

1namespace SitecoreCustomization.Pipelines.RenderField
2{
3 public class GetImageFieldValueResponsive
4 {
5 public void Process(RenderFieldArgs args)
6 {
7 if (args.FieldTypeKey != "image")
8 return;
9 if (args.Parameters.ContainsKey("responsive"))
10 {
11 string imageTag = args.Result.FirstPart;
12 imageTag = Regex.Replace(imageTag, @"(&lt;img[^&gt;]*?)\s+height\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
13 imageTag = Regex.Replace(imageTag, @"(&lt;img[^&gt;]*?)\s+width\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
14 imageTag = Regex.Replace(imageTag, @"(&lt;img[^&gt;]*?)\s+responsive\s*=\s*\S+", "$1", RegexOptions.IgnoreCase);
15 args.Result.FirstPart = imageTag;
16
17 }
18 }
19 }
20}

The process function in the class is what will get called as the control is rendered. First it will check that the field type is an image and then will look to see if there is a parameter called responsive. This will allow us to control when Sitecore should output height and width tags and when it shouldn't. Lastly some Regex is used to remove the height, width and responsive properties from the image tag that will already have been generated by this point.

Next we need to tell Sitecore to start using this pipeline. We do this by creating a RenderField.config file and placing it in the App_Config\Include folder of your Sitecore solution.

1<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
2 <sitecore>
3 <pipelines>
4 <renderField>
5 <processor
6 patch:after="*[@type='Sitecore.Pipelines.RenderField.GetImageFieldValue, Sitecore.Kernel']"
7 type="SitecoreCustomization.Pipelines.RenderField.GetImageFieldValueResponsive, DLLNameOfWhereYouCreatedTheClass"/>
8 </renderField>
9 </pipelines>
10 </sitecore>
11</configuration>

Lastly your control will need to have an attribute to say it should be responsive. For an xslt rendering your code will look like this:

1<sc:image field="Image" responsive="1" />

And for an ascx sublayout it will look like this:

1<sc:Image runat="server" Field="Image" Parameters="responsive=1" />

UI resources for developers

Having a good UI is possibly one of the most important aspects of any development. It doesn't matter how perfectly the code executes, if the thing looks awful people won't use it. But it is an area that a lot of developers struggle with.

There have always been things like website skins that you can buy, but I've never been a huge fan of these. It's always seemed odd that you can use an open source CMS for free that has had hundreds of man hours put into it, but a decent skin would cost you £100, and even then would still need a lot of work doing on it.

Thankfully there are some free resources that not only help with the css and making a site responsive, but they also include some fairly decent fonts and layouts.

 

Bootstrap

Bootstrap is possibly the most popular css framework for building sites with right now. Even Microsoft have adopted it into all the templates that ship with Visual Studio 2013.

One of the main things Bootstrap gives you is a standard set of css classes for doing things like grids and responsive layouts. When people start using a common set of classes to achieve the same thing, things get a lot more compatible and you can already see that starting to happen with Bootstrap.

Bootstraps grid system works on having the illusion that your page is divided up into 12 columns. You then have a set of classes to assign to a div that contain a number, that number is how many columns the div should span over. A bit like a colspan on a table.

These grids are responsive though so as your page shrinks down to a tablet and mobile size it will automatically recognise that the columns won't fit horizontally and start rearranging them underneath each other.

As a starting point Bootstrap also has some templates of common layouts to get you started.

Bootstrap also has default classes for forms, form fields, headings and lists that will give your site an initial face lift.

 

Foundation

Foundation in many ways is very similar to Bootstrap. It also has a grid system for layouts and also helps with making a site responsive. There are also default styles for headings, lists and forms but they have also taken things a step further and started to encroach on jQuery UI's territory with things like tabs and dialog windows.

I haven't heard of as much industry support but there site is full of documentation and videos on how to use the framework.

 

Pure

Another CSS framework with yet another grid system. Pure appears to be much simpler than the first two and offers many of the same features. Their site has some good templates that in some ways cover more scenarios that Bootstraps. Personally out of the three I would go with Bootstrap as it appears to have a much higher adoption.

 

Normalize

If the CSS frameworks seem a little overkill for what you're after have a look at Normalize. The concept is simple, by including this CSS file in your site as the first CSS file it will overwrite all the default browser styles to create consistency and something that looks a little nicer.

There's been many incidents where I've seen CSS produced that includes a style for every single html element try overcome the differences on browsers, which is a good idea (this is basically what normalize does except someone's written it for you), but the styles have all been set to the same thing which is generally margin:0, padding:0. On some elements this is fine, on lists though, not so much.

Another option I've seen is to define a style on *.* which is equally as bad.

 

Fit Text

Like it or not people are accessing sites from all kinds of devices these days with all kinds of screen sizes. If your site doesn't scale then you're going to lose visitors. One issue you will ultimately face at some point is font sizes. These can easily be changed using media queries but another option is to use FitText.

FitText is a really simple bit of JavaScript that will scale your text to fit its containing element. You do have to call a function for each element you want to scale, and it does only work on the width rather than taking the height into account. But it is very cool. Just make sure you have a look at the code because it's so small this isn't something you will want in a separate JS file.

jQuery ajax

If you want to dynamically load content into your page chances are your going to need to do some sort of request to a server in the background. The simplest way of doing this is to use jQuery's ajax function.

Here's an example of a GET request and a POST request:

1$.ajax({
2 type: "POST", // Set the HTTP type to POST
3 url: "/serviceurl.aspx", // URL of the service
4 data: "{data: [{"Field1": 1}] }", // Data to be posted to the service
5 processData: false, // If set to true the data will be processed and turned into a query string
6 success: (function (result) {
7 // Result of the service call
8 }),
9 error: (function (jqXHR, textStatus, errorThrown) {
10 alert(errorThrown);
11 })
12});
13
14$.ajax({
15 type: "GET", // Set the HTTP type to GET
16 url: "/serviceurl.aspx", // URL of the service
17 dataType: "jsonp", // Set what type of data you want back
18 success: (function (result) {
19 // Function that will be called on success
20 })
21});

HTML5 Series - Web Storage

One of the best benefits of HTML5 particularly for Web Apps is the ability to store data locally within the users browser. This means in many places you can speed your Web App up by fetching data once and then retrieving it locally in the future, rather than going back to a server each time.

There are 2 types of storage available localStorage and sessionStorage. The simple difference is that localStorage doesn't expire while sessionStorage expires at the end of the users session.

Both types store data in a key/value list and could not be simpler:

1// local storage
2localStorage.variableName = value;
3
4// session storage
5sessionStorage.variableName = value;

One thing to note though is you can only store text. If you want to store something more complex the simple solution is to convert it to and from JSON. E.g.

1var myColours = [ 'red', 'blue', 'green', 'yellow'];
2
3// Save to local storage
4localStorage.colours = JSON.stringify(myColours)
5
6// Retrieve from local storage
7var retrievedColorus = JSON.parse(localStorage.colours);

HTML5 Series - Error Handling

One thing you can say for certain about writing code is at some point your going to write something that error's. It may be picked up in code reviews, or by a tester, and then fixed but for certain as you are human at some point you will make a mistake. What's important though is what happens after the mistake.

If your a C# developer then good news JavaScript has the same try, catch, finally functionality that C# has and it works in the same way.

Wrap you code that could error with a try statement and curly braces and following it add in a catch statement with the code that you want to execute in the event of an error. Finally if you want some code to execute either way after both, place this in the finally block.

1try
2{
3 functionThatDoesntExists();
4}
5catch (err)
6{
7 alert(err.message);
8}
9finally
10{
11 //Code to execute at the end
12}

Notice the catch section is passed a parameter and I am then alerting a property of this called message. The error parameter can be useful for debugging what actually went wrong and contains a few other parameters.

  • Description
  • Message
  • Name
  • Number
  • Stack

Sometimes you may also want to cause an error to be thrown. You may be asking why, but consider people calling your functions may in-fact pass values that are not valid. You could detect this and throw an error containing some useful information before there incorrect parameter values causes your code to error and a less helpful message given.

1var err = new Error(1, "Oh dear, that's not going to work"); // First parameter is the error number, second is the message
2throw err;

HTML5 Series - Grid

There was a time when an HTML page layout mainly consisted of tables, and lots of them. Tables went inside other tables and complex layouts were achieved through the use of colspans and rowspans. The only problem though was it was a mess.

By using tables the HTML mark-up was dictating the design/layout of the page and if you ever wanted to change anything it was a huge task to undertake. Since then the world has moved on and now most webpages consist mainly of div's. But what if you did want to quite a rigid layout with columns and rows?

HTML5 introduces the Grid style through CSS. Your page can still consist mainly of div's (or anything for that matter), but in your css you set a display property of grid (for now in IE it's -ms-grid). You can then specify a grid-columns and grid-rows property to create a grid within your div.

Child items can be placed in grid cells through grid-row and grid-column properties in the CSS, and if you want something to span more than one cell you can use grid-row-span or grid-column-span.

If you've done any XMAL programming (WPF/Silverlight/Win8/Windows Phone) then this should all sound very similar to XMAL's Grid control.

The example below creates something like this:

1<style>
2 /* Set a grid with 3 columns and 2 rows */
3 div {
4 display: -ms-grid;
5 -ms-grid-columns:200px 200px 200px;
6 -ms-grid-rows:200px 200px;
7 }
8
9 /* Position the child div's in the grid */
10 div:nth-child(1) {
11 -ms-grid-row: 1;
12 -ms-grid-column: 1;
13 }
14 div:nth-child(2) {
15 -ms-grid-row: 2;
16 -ms-grid-column: 1;
17 }
18 div:nth-child(3) {
19 -ms-grid-row: 1;
20 -ms-grid-column: 2;
21 -ms-grid-row-span:2; /* The middle cell spans 2 rows */
22 }
23 div:nth-child(4) {
24 -ms-grid-row: 1;
25 -ms-grid-column: 3;
26 }
27 div:nth-child(5) {
28 -ms-grid-row: 2;
29 -ms-grid-column: 3;
30 }
31
32 /* Add a border to the cells */
33 div>div {
34 border: solid 1px black;
35 }
36</style>
37<div class="myGrid">
38 <div></div>
39 <div></div>
40 <div></div>
41 <div></div>
42 <div></div>
43</div>

It's also worth noting that the column/row sizes can be specified using fractions rather than fixed sizes. e.g. The following will produce a grid 600px wide where the middle column is twice the width of the other 2.

1<style>
2 /* Set a grid with 3 columns and 2 rows */
3 div {
4 display: -ms-grid;
5 width:600px;
6 -ms-grid-columns:1fr 2fr 1fr;
7 -ms-grid-rows:200px 200px;
8 }
9</style>

For another great example check out this hands on page from Microsoft Hands on: CSS3 Grid

HTML5 Series - Fonts

It's an all to common story, designer designs a website hands it to a developer who then goes, "what kind of font is that?" and get's the response of some completely unheard of name. The developer then try's to explain what a web safe font is and they agree to use Arial.

With CSS3 custom fonts are now a reality. On the item you are styling you still set the font family in the same way but additionally in your CSS you specify a @font-face rule so the browser can find out what the font is. The @font-face rule should specify a name and the src of the font. e.g.

1@font-face {
2 font-family: myFont;
3 src: url('myFontFileName.ttf');
4}

One point to note different browsers support different font type. Luckily though you can specify multiple sources for your font.

HTML5 Series - Video

Like Audio embedding Video in an HTML5 web page is really simple to do and has a very similar syntax.

The video tag can contain multiple source tags to specify videos in different formats as not all browsers support the same ones, and some text to be displayed if the browser does not support any. The video tag can also have a controls element specified to instruct the browser to display controls for the playback.

1<video controls>
2 <source src="URL of video.mp4" type="video/mp4">
3 <source src="URL of alternate video.ogg" type="video/ogg">
4 Your browser doesn't support viodes
5</video>

You can also set the following tags:

autoplay - Specifies that the video should begin playback immediately

loop - Sets the video to repeat

muted - Mutes the audio on playback

poster - Specifies an image to be shown what the video is downloading

preload - Specifies if an how the video should be loaded when the page loads

It is also possible to control a videos playback through JavaScript. You can reload the element, play and pause that track.

1var v = document.getElementById("myVideo");
2v.play();
3v.pause();
4v.load();