Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, July 20, 2020

What's Blazor WebAssembly and why should you care?


There was a peaceful time where web application development was simple. With ASP.NET, all we had to do was just open the IDE and drag UI elements from a toolbox to design a web page. Double-click on a button and we could write code in C# to be executed when that button was clicked, without needing to worry about how the web works. Needless to say, Microsoft devotees like me were living the dream. Well, JavaScript was still there, but it was the black sheep in the family, due to its amateurish design and issues with compatibility.  Nobody took it seriously unless they wanted some fancy animations. And then, someone saw it through and started standardizing it across browsers. It didn't take long for AJAX to come along and turn things upside down. We survived the first wave but when jQuery hit us, it hit us hard. Just when we were coping with the repercussions, a plethora of JavaScript-based SPA frameworks started to mushroom. All hell broke loose.


Does the above sound relatable? Well then guess what, Microsoft's Blazor WebAssembly is exactly what you've been dreaming of. Finally, a framework where you could forget about JavaScript and write client-side code in C# over WebAssembly. Sounds crazy right? But what on earth is WebAssembly anyway? It's another type of code that can be run on the JavaScript runtime which already comes built-in to browsers. WebAssembly in its purest form is not exactly readable. Hello, it's called Web *Assembly*! Ring any bells? But the thing is, you can convert code written in other languages to WebAssembly and make them run on the browser. That's how you get to write C# code instead of JavaScript. But wait, isn't C# compiled into IL and needs a .NET runtime? Well, how correct you are. That's why the Microsoft guys have ported the .NET runtime to WebAssembly which in turn runs your compiled code. Sweet!


I must mention that there is a different way to use Blazor on the server-side, having no dependency on WebAssembly whatsoever. It's called the 'Blazor Server' where the client-side becomes extremely lightweight and the plumbing happens via SignalR. But that's not everybody's cup of tea, at least not mine. And probably a topic for another day so don't get confused when I say 'Blazor', it's short for Blazor WebAssembly. Before you get all skeptical, Blazor WebAssembly is now production-ready and is officially released in May 2020. What's even better is that the 3rd party UI component builders like Telerik, DevExpress, Infragistics and the rest have already hopped in the bandwagon with their library counterparts for Blazor. It is open-source and free therefore it's receiving immense community support from around the world as a lot of additional component libraries, frameworks and whatnot are being created for Blazor as we speak. The ecosystem is booming and trust me it will be huge when .NET 5 hits the shores in November. So, this would be the best time to start investing, if you know what I mean.

Let's briefly look at a couple of things Blazor provides you out of the box. If you happen to create a Blazor app using the template which uses ASP.NET Core as the back-end, you can enable authorization with a single line of code. The authorization bearer tokens would be included in the request headers without you needing to do any manual work, thanks to the boilerplate code created by the project template. Localization is a similar cross-cutting concern but .NET has a proven way of nailing it for decades. Yes, you guessed it right, Resource Files FTW! You just have to wrap your string literals with @Localize[""] and the magic happens behind the scenes. The same goes for other i18n aspects like the number and date formats. .NET thread culture is set automatically to the browser's culture so there is very little left for you to do.



Interoperability with JavaScript is another cool feature that shouldn't go unnoticed. Blazor supports calling JavaScript from .NET and vice versa. It becomes quite handy when you want to reuse an existing JavaScript library without wanting to rewrite it in Blazor. Incidentally, you might also want to write your own piece of JavaScript code and make it available for Blazor. Whatever the requirement, it's a piece of cake to hook these two together. If you are conscious about offline support, you'll need to use IndexedDB, the NoSQL storage provided by the browser. And if you've already used it by any chance, you know its asynchronous API is a disaster to work with. But the good news is, there are NuGet packages already being built for Blazor which lets you consume it similar to EF, letting you only worry about the data and not how you store or retrieve it. 


One other great feature you get when developing with Blazor is full-stack debugging support in Visual Studio. For example, you can seamlessly put breakpoints in your server code, client code or even in JavaScript code which you interop with and simultaneously step through them in a single session. There are no messy debugger statements or switching between IDEs, just true full-stack debugging. And you can even do the same in Visual Studio Code. Since Blazor uses regular .NET assemblies on the client, code sharing becomes a breeze. How many times have you had to duplicate your DTOs in your server and client? Since it's all in .NET now, you can just define them in a shared library and refer it either from server or client, being totally oblivious to the fact that the latter runs on a browser.


There is more to Blazor apps like its ability to convert them into Progressive Web Apps and to be hosted as pure static sites. So it's definitely something you should try out to see where it stands in the crowd. And if you are a .NET enthusiast, it's undoubtedly a crucial skill set to add to your arsenal. It's already a game-changer and there is so much yet to come. Keep an eye out for stuff like Hot reloading, AoT compilation and CSS isolation when Blazor gets shipped with .NET 5. Visit https://blazor.net today and give it a try. The tables have started to turn, so grab your seat. It's now or never!



References:
  1. https://devblogs.microsoft.com/aspnet/blazor-webassembly-3-2-0-now-available/
  2. https://www.pluralsight.com/courses/web-assembly-big-picture
  3. https://dotnet.microsoft.com/apps/aspnet/web-apps/blazor
  4. https://youtu.be/My_XOzQWwc4


Wednesday, April 22, 2020

How to sort divs based on visitor's country


Recently I've got an opportunity to participate in revamping our company's official website.

One of the suggestions that came up there was to sort the clients' testimonies according to their relevance. And how would you know that you may ask? Well, one way to infer that is by capturing the visitor's geolocation and arranging the testimonials so the closest would show up first. Time to get to work!

To get the visitor's geolocation, initially, I tried the following service:
https://www.geoplugin.com (BTW later I ended up using this instead)

Well, that was the easy part. You just include their script and call a method to get country information.

<html>
 <head>
  <script src="http://www.geoplugin.net/javascript.gp"></script>
 </head>
 <body>
  <script> 
    alert(geoplugin_countryName()); 
  </script>
 </body>
</html>


The hard part was rather to get the testimonies sorted. Here's what I did.

We have clients from europe, america, middleast and australia. If someone from Norway visits our site, testemonies by Norgegian clients should show up first, then may be Swidish ones and so on.









So it's not just sorting by one country. You need something like "ORDER BY this, this too, this as well" which should work up to many degrees. I was much more interested in writing the sorting algo, overlooking the mechanism to compute the order by sequence. So the order by sequence was merely hardcoded for each potential geographic:
let computeSortOrder = function(countryCode) {
 switch (countryCode) {
  case 'NO':
   return ['NO', 'SE'];
   break;
    
  case 'SE':
   return ['US', 'CA'];
   break;
    
  ...

  default:
   return [countryCode];
   break;
 }
}

Now we got ourselves an array of counties that we would like our testimonies to be recursively sorted. How would you implement that? Custom sort with recursion!




 1. let sortClients = function(sortOrder, containerId) { 
 2. let divs = $('#' + containerId).find('.testimony');
 3. let orderedDivs = divs.sort(
 4.  function(a, b) {
 6.   let index = 0;
 7.   return innersort();
 8.   function innersort() {
 9.    var matchA = getMatch(a);
10.    var matchB = getMatch(b);
11.    if (matchA && !matchB) {
12.     return -1;
13.    } else if (!matchA && matchB) {.
14.     return 1;
15.    } else if (!matchA && !matchB) {
16.     index++
17.     if (index < sortOrder.length) {
18.      return innersort();
19.     }
20.    }
21.    return 0;
22.   }
23.   function getMatch(item) {
24.    return $(item).data('country') === sortOrder[index];
25.   }
26.  });
27. $('#' + containerId).append(orderedDivs);
30. }
Let me explain. The "sortOrder" is the array of countries returned from my earlier (ugly) function. The "containerId" is the id of the div which encloses all testimonies. Each testimony div is tagged with a class called "testimony".





In line 2, we get hold of all testimony divs we are interested in sorting. From line 3, the custom sort starts.
Basically the sorting function takes two arguments, essentially two adjacent items in the unsorted array say a & b and returns an integer where a negative value means a < b, positive means a > b and 0 means a = b. It is repeated many times for many pairs until all the elements in the array are in sorted order. The algorithm used will depend on your browser's implementation of ECMAScript. Does anyone still remember how bubblesort works? :) Here's some headsup.



So here, the modification to the general sort is we do the matcing recursively for everything in our sortOrder array. In line 15, when we don't find a match for the currently sorted country, we try to find a match for the next potential country in line at the sortOrder array. And it's repeated till the array is exhausted. The beauty is, it's not depending on any fixed degree of sorting. You can pass in an array of all the countries in the world and still get your divs sorted accordingly.



Alright, I hope you got some idea of the code now. By the way, the "data('country')" is how I tagged a testimony to a country in its div. Example below.



<div class="testimony"  data-country='NO'>
 bla bla bla
 ...
</div>

That's all for now. Stay safe and don't forget to wash your hands! #covid19

Monday, August 11, 2014

Google Charts: How to change axis, legend styles beyond what is provided by the API

If you are familiar with Google Charts, you know that you need to pass a 'Configuration Options' object when drawing a chart. Properties of that object for bar charts are found here.

For a recent project I worked, I needed to show the axis and legend labels as 'clickable' links hence I needed to show the cursor as a 'hand/pointer' when hovered above them. But Google Charts API only provides a limited set of styling for axis and legend labels. More precisely it only supports color, fontName, fontSize, bold, italic & underline styles.

But after inspecting the generated HTML DOM for the charts, I figured out a simple way to manipulate the elements properties and change the styling the way you want.

I prefer jQuery so here goes how the vertical axis labels were manipulated:
 $('text[text-anchor=end]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the horizontal axis labels were manipulated:
 
 $('text[text-anchor=middle]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

Here's how the legend labels were manipulated:
 
 $('text[text-anchor=start]').each(
  function (index, value) {
   $(value).attr('cursor', 'pointer');
   ...
  });

If you are a plain JavaScript guy, here you go:
 
 var labels = document.querySelectorAll('text[text-anchor=end]');
 for (var i = 0; i < labels.length; i++) {
  labels[i].setAttribute('cursor', 'pointer');
  ...
 }

Make sure you understand that the above hacks basically set the styling to every matching element found on the page. So if you have multiple charts on the same page and you need styling done individually, you will have to check additional properties of those elements inside the loops to determine which chart they belong to.

If you need further clarification on this, post it as a comment :)

Arduino Line Following Robot: Cracking the shortest/fastest path on a grid with loops

I'm sure you've created a line following robot at some point, if you've been exposed to Arduino (or any other programmable elec...