free html hit counter
Posted on: Saturday, 18 February 2017 by Rajiv Popat

There was a time when making IDE plugins for Visual Studio was for folks who specialized in art of writing plugins; i.e. folks like DevExpress and Jetbrains. With Visual Studio Code, writing extensions is no longer a mysterious black art. Even regular programmers like you and me can write extensions which solve our little specific problems.

My specific little problem? I hate having to type a semicolon and then hit enter on every line of code that I write. Specially when the IDE is auto-completing my brackets and quotes. For example when I write:

Console.WriteLine("Hello

If I have the C# plugin installed in VS Code, VS code understands my intent and completes the sentence by writing:

Console.WriteLine("Hello[my cursor is here]")

Notice my cursor position in the snippet above? At this point if I need to end the line I hit the right arrow key twice, then type semicolon and then hit enter to continue to the next line.

Technically, in the above example, if my IDE was really smart, I should just be able to type a semicolon where my cursor is, have the IDE understand my intent, move the semicolon to the end of the line and automatically move me to the next line so that I can continue coding.

It's just 4 keystrokes per-line (two right arrows, a semi-colon and an enter), but when you write hundreds of lines of code condensing 4 keystrokes to 1, adds up and goes a long way in making you productive. Actually, it's not so much about reducing the keystrokes as it is about being in the flow and rhythm.

At one point DevExpress CodeRush had this feature; and If I wrote:

Console.WriteLine("Hello;

CodeRush would intelligently complete this as:

Console.WriteLine("Hello");

It was a very fluid experience. I used to love that feature. When I moved to Linux and Visual Studio Code, I lost most plugins like Resharper and Coderush; but then other free Visual Studio Code plugins made up for most of what I loved between Resharper and CodeRush. However, I continued to miss the above feature where the IDE would automatically understand my intent and move my semicolons where they belong.

So, I decided to see how difficult it would be to write an extension which would:

  1. Automatically move the semi-colon to the end of the line even if you type it in between the line (except for special cases like a for-loop or a for-each loop).
  2. Automatically move you to the next line without having to explicitly hit enter.

It took me one day to write the extension. It took me one more day to brand it with a logo and documentation and publish it to Visual Studio Code Marketplace after releasing it on Github. Before I started this extension, I knew nothing about writing Visual Studio Code extensions. Not to mention that the entire development was done on a Linux Laptop. The code was written in type-script and I am not a java-script or typescript guru either.

I think a regular programmer like me being able to write a plugin of this sort, publish it live to a marketplace and have folks download over just a couple of days says more about Visual Studio Code's highly extendable design than it says about my talent. By far one of the more amazing editors / IDE's I've seen in my life.

Because I used an source code of an open source extension on the marketplace to learn how to get started with writing extensions, and I could see an ever growing community of open source extensions on the Visual Studio Code marketplace, I'm also publishing my code on github.

Go ahead and try it out. It has already had a couple of dozen downloads; makes me hugely productive as a programmer when I am inside Visual Studio Code above all keeps me in flow when I write code. I've been fully supporting this plugin and closing bugs as and when I find them or if and when they are reported.

It is called 'Autoend' and is available for free on the visual studio code marketplace.

If you do try it out please drop me your feedback / comments in the comment section of this post and if you find an issue you can always post it on github or you can always drop a line to contact@thousandtyone.com. Happy coding!

posted on Saturday, 18 February 2017 11:46:23 UTC by Rajiv Popat  #    Comments [0] Trackback
Posted on: Tuesday, 24 January 2017 by Rajiv Popat

I’ve always been both; a windows and an Ubuntu user. I’m not an OS zealot and I love both operating systems. My work machine runs on Windows and one of my two laptops at home has been on Ubuntu for a very long time. I love windows because it’s convenient. I love Linux because it’s powerful, seriously geeky and free. Which is why when .NET core team announced the ability to run on multiple platforms (including Windows and Linux), the announcement was like music to my ears. This meant that I could be on the OS of my choice (or fancy) and still do development on a language I love (C#).

I had already played around with using Visual Studio Code as a full-blown IDE and had realized that with the right plugins it’s possible to be fully productive on it. The only missing piece now, was SQL server for which I would always need windows. And then the SQL Server team announced that they’ve added support for multiple platforms as well and you can now run SQL Server on Linux.

This meant that I could now use Linux as my primary OS if I wanted; and that was an itch I really wanted to scratch. This of course, meant that it was time to test where Linux was as an operating system when it comes to being a primary operating system for me as a .NET developer. I’ve already had one laptop with only Ubuntu for ages but I just use that machine for surfing, browsing, watching YouTube and sometimes writing books or posts. Using Linux as a daily driver was going to be completely different. This time around, my goal was to find if I can use Linux as my primary operating system.

With this goal in mind, I decided to look at various Linux Distributions and pick one for my work life. This post is more of a running diary of my experience.

Since my organization wasn’t fully ready to move me to Linux (we’re an all windows shop), I decided to get Linux on a VM and spend most of my work hours there for a few days before jumping in fully. Given that I have 8 GB of Ram and over 200 gigs of disk space with an I5 processor I figured I can have substantial horse power in my VM to spend my work life inside the VM. And because this was going to be a work machine I wanted to try out distributions other than Ubuntu – which is what I’ve been using for years. Why? Because I wanted variety and spice in my life.

After looking at various Linux Distros these are what I short listed:

Mint Linux:

Apparently, this seems like the simplest version of Linux that you hop on to when you move on from the Windows world. Under the hood it’s Ubuntu but it looks and feels more like windows. Which is why a lot of windows users who move to Linux and are confused by Unity in Ubuntu like Mint better. For me, if I wanted an OS that looked and felt like Windows, I was already on Windows and I could just stick to it; so, Mint was not something that appealed to me.

Elementary OS:

I went and grabbed a copy of elementary OS and installed it on a Virtual Box VM only to realize that with 8 GB host, and 4 GB on the Virtual Box the OS was still slow and choppy. When I did that however I wasn’t aware how large an impact on performance small settings like enabling 3D acceleration and GPU allocation can have on the overall speed of Linux on a Virtual Machine, so in all likely-hood it wasn’t elementary OS that was an issue but probably bad configuration on my part.

I read a few posts mentioning that Elementary OS works much better with VMWare Player (which is a free product for trying out and personal use) than it does with Virtual Box so I tried it on VM-Player and it was better; but since this was meant to be a work VM, using VM-Player for work related VM’s wasn’t allowed by the VMWare license anyways. So, I dropped the idea and deleted the VM.

At the end of the day, if Mint looks like Windows, Elementary is inspired by Mac and if I loved Mac machines, I would get a Mac. So the choppy performance of Elementary on a Virtual Box and the fact that it’s inspired by Mac, ruled it out as a distribution that I would pick for myself at this point of time. There is a high chance I may have used it if the performance on Virtual Box would have been better and there is a good chance I’ll revisit Elementary sometime in the future because I genuinely liked and appreciated the user interface but for this evaluation I moved on to other distributions.

Fedora:

I grabbed a copy of Fedora and got it installed, up and running in no time. The Gnome based desktop is… for lack of a better word.. extremely classy. The OS was fast and slick and worked extremely well. I was about to settle down with Fedora, when I realized that the chrome installation that I had done on the OS just doesn’t work. No Errors. No warnings. Chrome just doesn’t start. Actually, chrome starts and then disappears. No Windows. No Screens. (I later encountered a similar issue on Ubuntu and fixed this by starting chrome without GPU and then disabling hardware acceleration using chrome settings. For more details on this fix see the ‘Chrome Blackouts’ on Ubuntu section of this post or read on).

I later moved on to .NET installation and realized that DotNetCore keeps giving an initialization error every time I try to do a “dotnet new”. The command fails with initialization errors. This is because Fedora 25 is not supported by DotNetCore. Turns out, there is a bug in .NET Core which makes it require version 52 of ICU Library and Fedora 25 has a higher version. Here is an unofficial fix but I wasn’t able to make it work; and after wasting hours on this I moved back to the familiarity of Ubuntu.

Ubuntu:

After having tried out three different Distributions I ran out of patience (and almost an entire day) and decided to eventually settle down with the known territory of Ubuntu. Unity is a controversial topic. Some folks love the UI, others can’t stand it. I personally have no issues with it since I’ve used Unity for months on my home laptop and am happy with it. But then having tried Fedora, I had also fallen in love with Gnome 3 and because this is Linux, I realized there was nothing stopping me from running Gnome 3 on Ubuntu. So I did just that and grabbed Gnome 3 on top of Ubuntu after I had installed base Ubuntu. Of course, I could have fetched Ubuntu Gnome directly but I like the manual way better because it lets me switch between Gnome 3 and Unity whenever I want to (or at each login!). I also love the Arc theme so I decided to grab that and install that using the Gnome tweak tool. Eventually however with Gnome 3, I settled for the default Adwaita theme.

Note: Version 16.10 of Ubuntu somehow doesn’t seem to play nice with VMWare Player on my machine, and causes Kernel panics and the famous ‘CPU has been disabled by the Guest OS’ error. However, it worked fine with Virtual Box which is nice because Virtual Box was my preference for virtualization to begin with.

Long story short, at this point, I had the familiarity of Ubuntu, and the newness of the Gnome 3 User Interface that I experienced with Fedora. The best of both worlds:

So I was on Ubuntu with Gnome 3, but I was still far away from making this machine my daily driver. There were multiple other hoops that I had to jump to make this machine usable as a daily driver.

Sound Card Issues:

With Ubuntu installed on my virtual machine; I realize that sound doesn’t work with Ubuntu on Virtual Box. Turns out, after a certain version, Virtual Box doesn’t seem to pick up the right sound card drivers to be used for host and guest operating systems and you need to pick them up manually. For me what worked was Windows Direct Sound on the host and Intel HD Audio on the guest operating system.

I then go to the sound settings of Ubuntu and crank up the volume to maximum value allowed. Actually, I crank it up to 140% of what’s allowed:

Sometimes when I want to sound to go louder I have to go to the terminal and crank up the sound even louder with aslamixer command:

And then the sound works fine. The next thing I was going to need if I was going to use this machine on a daily basis was a stable browser like Chrome.

Chrome Blackouts:

I go ahead and grab chrome and am just about ready to work; when I see a blank black screen each time I start chrome. To fix this I start chrome without a GPU using the command:

google-chrome -disable-gpu

From my terminal window and once chrome starts I disable “Use hardware acceleration when available” by going to Chrome Settings and then into Advanced Settings of Chrome.

Note: This same fix works on on Federo where the chrome window disappears after you click on the chrome icon.

Sluggish Speeds:

My Virtual box is now up and running; I have a browser and sound; but the performance is still sluggish. I crank up the GPU to 128 MB and select ‘Enable 3D Acceleration’ from the virtual box settings which considerably speeds up the virtual machine and makes it fast. I also grab CompizConfig Settings Manager so that I can tweak animations and I disable them to make my system move faster. This speeds up my Virtual Box considerably and makes it actually extremely usable.

But What About Email?

With the basic setup of the OS complete, my next concern is email. Because we use Office 365 at my organization and Exchange at my client’s organization, I needed something that works seamlessly with Exchange Web Services and while evolution comes pre-installed in Fedora, Unity comes preloaded with Thunderbird; which, based on what I’ve read doesn’t work with Exchange services as of this writing. So I grab a copy of Evolution in my Ubuntu and configure my Office 365 emails with it.

Configuring Office 365 emails was relatively easier, though Evolution does tend to loose your preconfigured account the first time you configure them. If that happens open your process monitor, kill all threads of evolution and start fresh and there is a high chance you might find your accounts back. I ended up creating the accounts thrice and then found them all when I killed the evolution threads and started evolution fresh. Then I deleted all of them and re-created a single fresh account. This was of course a one-time issue and things have been fine once the accounts are configured.

Configuring Office 365 accounts were easy. With on premise Exchange accounts however things get a little more complex to troubleshoot. Because my client uses NTML based authentication and Evolution detected that as Kerberos; I kept getting the following error message:

The reported error was "No response: SPNEGO cannot find mechanisms to negotiate".

Finding out what the issue here was mostly a hit and try exercise where I tried to use basic authentication and that didn’t work so I moved to NTLM and that worked.

Site Note: the lack of support for Exchange in mature email clients like Thunderbird and the fact that you have to shell out 10$ a year to get an Exchange plugin in Thunderbird is a little disheartening. I have no issues with paying developers for the hard work they put in, but paying to accomplish something as simple as checking email when your entire OS is open source (and free) and every other app on your machine is open source is, for lack of a better word… a little… ironic. So I decided to grab Evolution which supports Exchange free out of the box and battle out the issues. And it paid off. Evolution has been working well both with Office 365 email account and with Exchange email account and I am actually starting to like it a whole lot.

For those of you who haven’t used evolution, the only thing I missed, compared to outlook was free text search. Turns out, Evolution has a very powerful advanced search and you can also turn on expression based searches:

Visual Studio Code:

With everything else configured I set out to load Visual Studio Code (the primary reason why I started to spend a day on making myself a Linux Work VM). Getting Visual Studio Code itself is super easy. You just download the package and you install it using the Application Manager. However, when I start Visual Studio Code I get a blank black screen. This reminds me of the black window in chrome so I go ahead and look for a similar fix. You just start Code without the GPU:

code --disable-gpu

But because we cannot be doing this each time we add this as an alias in our ~/.bashrc file (or in my case I just add it to my ~/.bash_aliases file which bashrc file references which just helps keeps things clean):

alias code='code --disable-gpu'

Once you’ve added the line you need to close your terminal and start it afresh for the alias to kick in. Caveats? First, you can’t open Code from the Icon in Gnome. Second, you can’t do a “Code .” and expect “.” to represent the current folder you are in when working on the terminal. You need to open Visual Studio Code and then do a File / Open… which is not that bad.

Next I follow these instructions to install DotNetCore on Ubuntu 16.10. Then Install the usual plug-ins and I am in business:

And so, with the development environment in place we are now going to need a DB to work with.

SQL Server:

SQL Server installation was by far the smoothest. You just follow the instructions here and then you follow these instructions for installing the client tools. SQL Server claims to require 4 GB RAM but I barely notice any slowdowns post install and the DB has been running blazing fast. I’m actually really impressed with the DB performance thus far.

There are no UI tools like SSMS for SQL Server on Ubuntu so I grab the DBeaver and use that as a visual editor for DB design.

To be honest the performance of DBeaver in a Virtual Box with 4 GB of RAM is extremely sluggish and it tends to slow down the entire VM. At the danger of offending and triggering Eclipse fans, it’s a trend I’ve seen with a lot of other applications that are built on Eclipse. I then move to SquirreL SQL which is light weight but only provides query capabilities and no Drag and Drop DDL capabilities.

I’m still looking for a visual database development tool but for now, between the command line, SquirreL and DBeaver I should be good.

And A Shared Folder with the Host OS:

If you’re going to run in a VM Mode you will probably want a shared folder with the host OS which you can mount automatically so that anything you save there is also available when you are not using Ubuntu. I do that by sharing a specific folder on my host OS with Ubuntu using Virtual Box settings:

And then I run into permission issues where I cannot access this folder from Ubuntu which I solve by adding my current user to the vboxsf group.

And I’m set for now. All ready to take my newly created VM for a spin and because my VM is just 12 Gb, I decide to take a full backup of my VDI file instead of taking a snapshot. My entire disk file size after installing everything I need, is about 12 GB, so it’s still a file I can carry on a 16 GB drive.

My Overall Experience:

I’ve been a happy Linux user on and off on at-least one personal laptop for over 15 years and Linux has come a long way, but even today, every time I decide to spend a day with various Linux distributions to see where they are and play around with them or try to expand the scope of Linux in my life, I encounter some hurdles which I have to jump and I eventually end up learning new things. That is what makes me angry at Linux sometimes. It’s also what makes me love Linux most of the times. Let’s just say it’s a healthy relationship – the kind that you have with your friends, wife or your kids. :)

If you’re an average office user who is Installing Linux on a bare metal modern day laptop, Linux has indeed come a long way, is very usable and your learning curve might be minimum. You probably can get started almost as easily as you do with windows. But if you plan on using Linux as a primary work machine (especially in a Virtualized environment because your office is on windows) there is a high chance you’ll hit a few bumps but among the dozen odd distributions of Linux and a couple virtual machine solutions and a couple of dozen workaround, you should not take more than a couple of hours to be completely up and running and that (genuinely; without the slightest tone of sarcasm in my voice) is not such a bad thing at all.

My overall experience after spending a day playing with Linux with the idea of using it as my primary work environment is that it has come a long way and I encourage each one of you to try it for a month as a primary work OS; even if it happens to be on a VM! With Visual Studio Code, .NET and SQL Server all running on it, there should not be any reason why you aren’t taking Linux for a test drive.

On another different note, I am loving the new Microsoft for making things like this even possible. It takes a lot of courage for a company of Microsoft’s size to embrace a truly open world where everything they build from Development platforms to development tools and even databases run on multiple platforms.

Here is a big thumbs-up to both the DotNetCore team and the SQL Server team for embracing openness. When we have open choices like these for developers, everyone wins. I’m genuinely impressed with what I have experienced and I’ve been on this VM as my primary machine for a week and nothing has broken. Pure Awesomeness.

Update: After using the Virtual Machine for a few days I finally took the plunge and decided to move to Linux on my work machine. All the GPU issues I had to work around in this post are non-existent on a bare metal install and the same Ubuntu + Gnome combination has been working really well for me during the past few of days.

posted on Tuesday, 24 January 2017 12:06:23 UTC by Rajiv Popat  #    Comments [0] Trackback
Posted on: Tuesday, 01 November 2016 by Rajiv Popat

If you’re interested in and working with Javascript frameworks, you’ve probably heard of Aurelia by now. It’s a compelling competitor to frameworks like Angular and React.  While getting started with Aurelia itself seems pretty straight forward, getting Aurelia working with Type-Script and making it all work Visual Studio 2015 has it’s own share of hiccups.

The aurelia team provides starter projects that they call skeletons that you can download and get up and running really quickly. However when I tried using them, the skeletons seemed to have issues which were both time-consuming and frustrating to resolve. Even the skeleton that was supposed to run with .NET MVC (and had a “.sln” solution file) would not even compile without errors. And these skeletons come with a lot more than what you would like have when you are just trying to get an initial hold of Aurelia and type-script. This left me with no other options but to star fresh and create my own basic skeleton where I can try out different Aurelia features.

If you’ve tried to get started with Aurelia + Typescript and you are a .NET programmer who lives inside Visual Studio, the goal of this post is to get you up and running with Aurelia and Typescript inside Visual Studio 2015.

To being with you’re going to need Typescript working inside your Visual Studio 2015. The simplest way I’ve found to do this is, just un-install older versions of Visual Studio 2015 and install Visual Studio 2015 Update 3 from scratch. You could use that link, but then if you have an MSDN subscription you are better of downloading an offline ISO from there and using that, which is what I did.  Initially, I tried in place update of Visual Studio 2015, and the installer kept crashing for some reason (this of-course could be because of the fact that I was on a weak Wi-Fi).  The MSDN ISO (a 7 GB download) worked smoothly after an uninstall of my existing visual studio; followed by a fresh install.

With Visual Studio 2015 Update 3 (with Core 1) loaded, you’re also going to need Typescript support inside Visual Studio so your Typescript files are compiled and converted to JS files each time you save them. To do that you can grab the Visual Studio Typescript plugin from here and install that. You will also need Node Package Manager (NPM) working on your machine and the simplest way to do that is download and get  Node JS installed on your machine.

With that done we’re ready to start our first hello world project with Typescript + Aurelia.

As I said before, the easiest way to do this would have been to download and use the skeletons, but given that the skeleton’s provided by Aurelia team didn’t work for me;  I was left with no option but to build my Aurelia app from hand and get started. Honestly, building your first app by hand actually works out better because it gets you a fresh new insight into many underlying concepts that you will typically not have to pickup if you use a ready made skeleton instead.

Since we’re going to be working with Visual Studio 2015 as our IDE of choice, let’s go and create a blank ASP.NET Web Development project inside Visual Studio in a folder of your choice. Open the solution file and keep the solution open in Visual Studio as you proceed with the below.

Once the project is created start command prompt and go to the specific location where you created the project. Note: go inside the project folder (not the folder with contains the .sln file – but the one that has your web.config file.):

Once there start by typing in the following commands:

npm install jspm
jspm init

JSPM is the JavaScript Package Manager which let’s you fetch and use various  Javascript modules you will need to get started with Aurelia. In the above diagram we switch to the project folder (shown in the screenshot + code snippet),  do a NPM install of JSPM which fetches JSPM on your machine. Once there we initialize jspm in our project folder (jspm init) where it will create new project asking you basic questions:

We select the default answer by just hitting enter, except for picking the Transpiler, where we will use TypeScript instead of the default Transpiler JSPM uses (babel).

Once that is done we continue with rest of the defaults and finish our “jspm init”.  We then install the required underlying frameworks in our project by doing:

jspm install aurelia-framework aurelia-bootstrapper bootstrap

This should pull all files pertaining to Aurelia framework, the aurelia bootstrapper and the bootstrap framework (which are the very basic things we need to start a simple web application with Aurelia and Typescript). If all goes well your folder structure should look like this inside Visual Studio with “Show All Files” selected in Solution Explorer:

We now need to start writing code for our project. The first thing we do is right click the config.js file in the solution explorer and say “Include in Project”.

Once done we open the file and add the highlighted line :

This tells the Transpiler to look for code in the “src” folder. Of course we don’t have that folder in our solution so we create that by right click solution explorer and clicking create folder and adding the src folder. Now we have a place where we will write our Aurelia code. But any web-server that we will also use to host the code will need a startup file to begin running the application – which usually is index.html. So let’s code the following index.html by hand:

<!DOCTYPE html>
<html>
  <head>
    <title>Aurelia</title>
  </head>
  <body aurelia-app>
    <script src="jspm_packages/system.js"></script>
    <script src="config.js"></script>
    <script>
      System.import('aurelia-bootstrapper');
    </script>
  </body>
</html>

This is a simple standard index.html file most Aurelia applications will typically need. We are adding two JS files that aurelia needs. The first is system.js and the second is where our configuration is stored (config.js). We then use System.import (from system.js) to import the aurelia-bootstrapper.

Also note the “aurelia-app” tag in body. A few important pieces are getting connected in the above code and aurelia is using convention to connect the pieces. The index.html tells aurelia to use the config.js file. And as we’ve seen before, the line we added in config.js tells aurelia that the custom aurelia code would be in the “src” folder. The “aurelia-app” tells aurelia to be default look for “app.js” as an entry point. Note: we haven’t specified app.js – but the aureila-app tag itself (by convention) tells aurelia to use app.js by default. You can of-course override the convention but that’s for another post. Right now, let’s just create a app.js in the source folder.

We could drop an app.js file inside source, but remember we are planning on using TypeScript throughout the project, so instead of an app.js, we will use “app.ts”. We will work on the typescript file (app.ts) and let Visual Studio to generate the .js fie each time we save the “.ts” file. So let’s right click “src” folder and add a Typescript file and call it “app.ts”.  Because typescript provides added intelligence and compile time validations, it needs what we call typing files which allow visual studio to validate your TS code. Which is why Visual Studio will ask you this:

Going ahead we will grab out typing files manually so say no to the above for now and let’s proceed. We’re going to talk more about typings later in this post.

In your blank app.ts add the following lines:

export class App
{
    Message: string;
    constructor()
    {
        this.Message = 'Hello World';
    }
}

Note in the above code, we have a simple type-script class (this will translate to a JS function) and string Variable called Message. In the constructor we add a default value to the field. This app.ts, will get translated to app.js when we save it and will act as a view-model. Now that we have a “View Model” let’s go ahead and make a View. Aurelia view are simple HTML pages surrounded by a template tag. So inside “src” folder let’s add a new app.html and add the following lines:

<template>
    Message received from View-Model: ${Message}
</template>

The Message that we set in the View-Model should now flow to the view and when you compile and run the project at it’s root, you should now see:

Congratulations! You have your first Aurelia project with TypeScript running now. Now let’s do something more meaningful and try to create a screen to add customers to a List of Customers. To do that let’s start by making a Customer class by adding a “Customer.ts”. For now let’s modify the blank Customer Class so that it has a CustomerName attribute and looks like this:

export class Customer
{
    CustomerName: string;
    public constructor()
    {
    }
}

We will now need to go ahead and use the Customer inside app.ts and then create a function inside app.js that allows us to create a customer to the list of customers. To do that we modify our app.ts:

import { Customer } from './Customer';
export class App
{
    CurrentCustomer: Customer;
    Customers = new Array<Customer>();
  
    constructor()
    {
    }

    addCustomer()
    {
        if (this.CurrentCustomer)
        {
            this.Customers.push(this.CurrentCustomer);
            this.CurrentCustomer = new Customer();
        }
    }
}

In the above code we use Import to import the Customer class into our App class so that we can use it in our code. Then we create an array of Customers (which will hold a list of customers) and a specific Customer (which the user will add using the UI). The “addCustomer” method adds the current customer to the list. To put sense into all of this let’s create a UI front end which has a textbox, and button called “Add Customer” which adds the customer whose name you type in the textbox to a List of customers which is re-presented by a “UL”. The final view (index.html) looks like this:

<template>
    <form submit.trigger="addCustomer()">
        <input type="text" value.bind="CurrentCustomer.CustomerName" />
        <button type="submit">
            Add Customer
        </button>
        <ul>
            <li repeat.for="Customer of Customers">
                <span>
                    ${Customer.CustomerName}
                </span>
            </li>
        </ul>
    </form>
</template>

Notice that in the code above I have a form whose submit triggers the addCustomer method which we write in our View-Model. There is a textbox which we “bind” to the CustomerName of the Current Customer, which again is defined in our view model. We have a simple submit button and a UL where the LI’s repeat for every Customer in the “Customers” array which is defined in our ViewModel. The UI looks like this:

As we type the name of the customer and click the add button the customers get added to the list:

And we can do this with multiple customers:

The binding of the textbox with the CurrentCustomer.CustomerName ensures that the value passes from the view to the view-model. Each Time addCustomer is called, we create a new Customer object and hence the textbox blanks out after the existing customer is added to “Customers” array which is bound to the UL using a “repeat.for” loop.

So far so good. Everything we’ve done thus far, compiles, builds and runs.

However as you start going into deeper Aurelia, you will realize that you will need to use more complex concepts like Dependency injection (where you would like to inject services into your view-models). The start project we have created works but isn’t fully ready to handle imports because we have the typing files missing. Remember we said we’ll discuss typings later in this post? This is the part where we now need to address typings to move ahead.

To virtually use any advanced feature in aurelia you will have to import the aurelia framework in your code. For example if you want to use the dependency injection of aurelia, your code to do so would look like this:

import { inject } from 'aurelia-framework';

Put that code in your app.ts and you’ll immediately realize that visual studio starts complaining:

And this is because Visual Studio knows nothing about the Aurelia-framework even though we had done a “jspm install aurelia-framework” right when we started. We had done the install with the command prompt using jspm but visual studio (and typescript) still require typing files for aurelia framework before they let you import specific components of the framework inside your TS files.  The simplest way to grab Typing files is to add a “typings.json” file in your project root and add the following lines to it:

{
  "name": "AureliaHelloWorld",
  "dependencies": {
    "aurelia-binding": "github:aurelia/binding",
    "aurelia-bootstrapper": "github:aurelia/bootstrapper",
    "aurelia-dependency-injection": "github:aurelia/dependency-injection",
    "aurelia-event-aggregator": "github:aurelia/event-aggregator",
    "aurelia-fetch-client": "github:aurelia/fetch-client",
    "aurelia-framework": "github:aurelia/framework",
    "aurelia-history": "github:aurelia/history",
    "aurelia-history-browser": "github:aurelia/history-browser",
    "aurelia-loader": "github:aurelia/loader",
    "aurelia-logging": "github:aurelia/logging",
    "aurelia-logging-console": "github:aurelia/logging-console",
    "aurelia-metadata": "github:aurelia/metadata",
    "aurelia-pal": "github:aurelia/pal",
    "aurelia-pal-browser": "github:aurelia/pal-browser",
    "aurelia-path": "github:aurelia/path",
    "aurelia-polyfills": "github:aurelia/polyfills",
    "aurelia-route-recognizer": "github:aurelia/route-recognizer",
    "aurelia-router": "github:aurelia/router",
    "aurelia-task-queue": "github:aurelia/task-queue",
    "aurelia-templating": "github:aurelia/templating",
    "aurelia-templating-binding": "github:aurelia/templating-binding",
    "aurelia-templating-resources": "github:aurelia/templating-resources",
    "aurelia-templating-router": "github:aurelia/templating-router"
  },
  "globalDevDependencies": {
    "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
    "aurelia-protractor": "github:aurelia/typings/dist/aurelia-protractor.d.ts",
    "jasmine": "registry:dt/jasmine#2.2.0+20160505161446",
    "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
  },
  "globalDependencies": {
    "url":
"github:aurelia/fetch-client/doc/url.d.ts#bbe0777ef710d889a05759a65fa2c9c3865fc618",
    "whatwg-fetch": "registry:dt/whatwg-fetch#0.0.0+20160524142046"
  }
}

This will provide details of practically all aurelia typing files we are going to need for now and future. Once you have created this file and saved it go to command prompt, navigate to the folder that has the typings.json file (i.e. same folder as the one which holds your web.config) and type:

npm install typings –g

This will install the typings module globally. Now to grab relevant typing files based on your typings.json type:

typings install

Now we’ve fetched typing files but Visual Studio is still blissfully unaware about the fact that we’ve pulled the typings. You should also see the “typings” folder in your source explorer. However To make Visual Studio aware of the typings, we will need to add a typing definition file inside our source folder – the one which our Transpiler is watching. We can call this file anything as long as it has a “d.ts” extension but for now we’ll call “main.d.ts” and will place it inside the src folder. If you notice inside the typings folder you realize that is already has a typing definition file called “index.d.ts” – and it references all the necessary aurelia files;  so if our “main.d.ts” just references that file we should be done. Let’s go to our newly created blank “main.d.ts” (inside the src folder) and add this line:

/// <reference path="../typings/index.d.ts" />

With this done we now have the typings referenced properly and visual studio should stop throwing “cannot find module ‘aurelia-framework’.” error and that specific error should get fixed. However now when you fire a build you should see dozens of these two errors:

Build:Cannot find name 'Promise'.
Build:Cannot find name 'Map'.

This is because Aurelia typings internally use promise and collections. To fix this error we can use the Nuget package manager inside visual studio and install Typescript definition for ES6 promise and collections. The command to do that (inside Visual Studio Nu-get package manager) is:

Install-Package es6-promise.TypeScript.DefinitelyTyped

Install-Package es6-collections.TypeScript.DefinitelyTyped

Once you do that and once typings for promise and collections are installed your build should compile successfully. However, if you start using advanced features like dependency injection you will encounter some more build errors. For example, let’s modify your “app.ts” to use dependency injection:

import { Customer } from './Customer';
import { inject } from 'aurelia-framework';

@inject(Customer)
export class App
{
    CurrentCustomer: Customer;
    Customers = new Array<Customer>();
  
    constructor(injectedcustomer)
    {
           
    }

    addCustomer()
    {
        if (this.CurrentCustomer)
        {
            this.Customers.push(this.CurrentCustomer);
            this.CurrentCustomer = new Customer();
        }
    }
}

Notice the lines in bold which are using out of the box dependency injection of aurelia. In other words, aurelia automatically creates an object of Customer class and pushes it in the constructor. However the moment you actually do this and hit a build you should see compilation error:

Build:Experimental support for decorators is a feature that is subject
to change in a future release.

Set the 'experimentalDecorators' option to remove this warning.

To Overcome this error you will need add a new tsconfig.json in your project root and add the following lines to it:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules","jspm_packages"

  ]
}

The experimentalDecorators value of true ensures decorators like inject are allowed. Exclude on node_modules and jspm_packages ensures that the typescript compiler excludes those when it fires a build. Fire a build now and your build should fire successfully.  Run your code and it should just as before because we aren’t doing anything in particular with dependency injection here. In fact it’s actually a bad example of dependency injection but I included it in this post because the post covers the setup of a starter project that let’s you try out and learn everything that aurelia has to offer while using it with Typescript, inside Visual Studio 2015, so adding a right “tsconfig.json” and getting the typings upfront is a good idea (even if you are not using dependency injection or other advanced aurelia concepts).

I honestly believe that while the aurelia team is doing an amazing job documentation and videos of aurelia itself, but mixing aurelia with type-script and getting it all to run on visual studio 2015 can turn out to be a bit daunting for someone who is starting out his aurelia + typescript journey because there is no single place to get started. It would be really nice to not have to go through so many steps to just set up a basic development project where you can try out and learn features aurelia (with Typescript) has to offer, while working inside visual studio.

I know you can create projects using Aurelia CLI tools but even those had the similar typings related issues that I highlighted in this post. And getting those to work was an equally daunting task. Now that I have been working in aurelia for a few days, I can take a skeleton and make that work too, but as far as I am concerned, the learning curve to get into aurelia itself has been much lower than the learning curve required to get into aurelia with typescript and get it all to work inside visual studio. All I can do is hope that the Aurelia team builds some more documentation around getting started with Aurelia + Typescript. In the meantime, this post you get you on your way.

posted on Tuesday, 01 November 2016 16:03:18 UTC by Rajiv Popat  #    Comments [1] Trackback
Posted on: Saturday, 08 October 2016 by Rajiv Popat

There have been a lot of conversations around IoT lately. As someone who has done his major in accounting and as someone who builds business and financial applications for a living, I had a lot of excitement and some reservations about starting on my IoT journey. I mean I am just a regular nerd without any electronics background. Should I be playing with Microcontrollers and live current? After a few weeks, I’m happy to announce that the journey has been fun and I think it has been a journey worth sharing with you.

The basic underlying idea is to control things over the internet and hence the need for a programmable chip or a microcontroller - a small tiny independent board with a programmable chip that can run code in an infinite loop. The code controls the chip and the chip controls the devices or things it is connected to.

The “control” in the microcontroller can be as simple as turning a LED on / off or something as complex as building a smart home, with lights, fans, entertainment systems and water pumps controlled using your code.

Most articles and you-tube IoT examples out there are either way too complex involving complex circuits and code, or way too simplistic and impractical where someone shows you how to make a LED blink  with your code; which fortunately is a good start; but unfortunately does not allow you to anything practical with your microcontroller, which then puts your micro-controller in the same category as your gym membership - something you own but don’t actually use.

My goal with this series of posts, is to get started on IoT and provide enough insight on the topic to enable you to build something real and practical with it. The goal is also to take you to a point where IoT goes from yet another buzzword that electronics guys should be concerned about, to a practical, real, affordable and simple tool that you can use to build useful projects with.

In the first post we’ll cover some very basic concepts around the Arduino chipset (which is the micro-controller we are going to use for our IoT experiments) and write some basic code that runs on the chipset.

In the posts that follow we will attach some interesting modules to Arduino and write code to control these modules. Going ahead, we’ll get these modules and the microcontroller connected to your home Wifi and we’ll show you how you can control the microcontroller (and the modules connected to it) over the internet; and we’ll finally move on to working with real live electrical devices like, light bulbs and fans and control those with code.

All circuits we build in the process will be open sourced. All code we write in this process will also be on open sourced and  will be posted here on this blog for you to use.

When I started with my IoT journey a few weeks ago, I knew nothing about physics (or electronics) other than some basics I had picked up in high school, most of which I had never paid any attention to or had forgotten over time. Long story short, I’m just a regular nerd who writes business applications / CRUD screens for a living  and hence the series of these posts doesn’t require you to know physics or electronics to start. You will need to go out and buy a couple of cheap gadgets if you want to try some of these examples yourself but your overall investment will be less than 25 dollars.

And as a final disclaimer, I have never officially studied electronics so everything I write about here, is just a regular nerd trying to connect wires and have some fun. If something explodes (or if you cook a chipset or two) the responsibility is all yours!

Sounds good? Let's begin.

To start playing around with IoT we’re going to write code that controls devices so you’ll have to shell out some money and buy some basic devices. Even though there are platforms like the raspberry pi which make IoT much simpler, let’s start with buying a much cheaper micro controller which actually gets you a deeper understanding of the circuits you will be making, will make a smaller hole in your pocket and will help you stay away from having to run and entire Linux clone on your microprocessor like Raspberry Pi does.

Here are a few things you may want to go out and buy if you want to follow along:

  1. An Arduino UNO chipset - You can buy the original one or a cheap clone. I got one from amazon at about 7$.
  2. A Breadboard - so that you can connect wires and devices together without needing soldering equipment. I got mine from amazon at about 2$.
  3. Some jumper wires - so that you can connect devices on your Arduino and your breadboard. I picked up a neat set of male-to-male, male-to-female and female-to-female at Amazon. Cost of the whole kit? About 2$.
  4. A Few LEDs (and a few resistors) - which is the very first thing we will control with our code. You can also grab some resistors at 150 for just 1$ and a few LEDs for 3$.
  5. An ultrasonic transmitter - we will not be using it in the first demo, but we will need this in the third post, so it may be a good idea to get everything you will need in one shot. I picked up mine at 2$.
  6. A Wi-Fi module - that will eventually let you get connected to the internet over your home Wi-Fi connection and let you control the Arduino over an internet connection. Price? About 3$. Again, not something we will use in the first post, but something that we will use pretty soon.
  7. A Relay - that will let us control real live current / devices using our Arduino - we’re not going to use this for the next couple of posts but at 2$ a piece it’s something you may also want to order along with everything else mentioned above.

In under 25$ you have all you need to work on some meaningful IOT experiments and try out a few things.

We’ll get started with Arduino itself in this post and make it control a basic on-board LED light before we do some more interesting things with it. I do realize this example is highly non-practical but it is really simple, gets you used to the Arduino IDE and gets you familiar with the environment. So, let’s get started by making a LED blink, but before that lets begin by knowing our Microcontroller.

You can read article after after to understand the Arduino, but to start messing around with it, all you need to know is that is has 2 power output pins (using which connected devices can draw power) - one is a 3.3V power output pin, the other  a 5V power output pin. Apart from the power pins it also has ground pins labelled “GND” and all circuits that you make will usually end / complete with the ground pin. Put simply, your wiring will start with the power pin and end in the ground pin, and you will control everything else that’s in between (i.e. everything that’s connected to your IO pins).

Depending on the device you are connecting to your Arduino you can decide the power output you want to use. Most devices will have specs which will tell you how much power they expect. Exercise some common sense when you pick the power pin - for example, don’t connect your jumper wire to a 5V pin when the device you are connecting expects 3.3V - if you do there is a high chance you will cook your device.

Apart from the two power pins there are also some digital pins where you write a high or a low. Think of writing a “high” as turning a switch on and think of writing a “low” signal as turning the switch off. Out of all these pins, pin 13 is special because it has an in-built LED (light) attached to it that you can control with your code.

To write code we’re going to get the Arduino studio, which you can download from here and install using a simple installer. Once done, you connect your Arduino to the USB port of your laptop (which is one of the sources from which Arduino gets it’s power). Of course Arduino itself, can also work without a machine and you can hook it up with a battery or direct power, but for now since we will be uploading our code from our machine to the chip, it makes sense to have it connected with our laptop using the USB port.

Once connected go to your Arduino studio and pick the right port your Arduino is connected to. Usually the IDE automatically detects this but if it doesn’t you can try different ports and try to upload your code on each one till it succeeds. All code that typically runs on the microcontroller is referred to as a sketch and each sketch has a loop, which keeps on running as soon as the sketch is uploaded and the microcontroller is powered on.

An empty sketch looks like this.

Setup function is where you write code that runs only once. Anything you write in in “loop” runs in an infinite loop while the microcontroller is powered and on.

Now it’s time to connect the dots and assemble everything we’ve read thus far. Remember when we were talking about writing highs (which is same as turning the pin on) and lows(which is same as turning the pin off)? We know pin 13 has an in-built LED (light) and if we can write a high to pin 13, it should turn the switch on and the LED should glow. If we then write a low to the same pin the LED should shut off. If we do that in a loop function and wait 5 seconds between the on and the off, we should have an LED that keeps on blinking every five seconds the moment you power on the microcontroller. Simple enough? That’s exactly what we are doing in the code below:

int InBuiltLedPin = 13;

void setup() {
  // Let's set Pin 13 as Output Pin
  // Which means we will write high's and low's to it.
  pinMode(InBuiltLedPin, OUTPUT);
}

void loop() {
  // Turn on the Pin (and LED on board)
  digitalWrite(InBuiltLedPin, HIGH);
  // Wait for 5 Seconds
  delay (5000);
  // Turn off the Pin (and LED on board)
  digitalWrite(InBuiltLedPin, LOW);
  // Wait for another 5 seconds.
  delay (5000);
}

Verify your sketch (which is the same as compiling your code):

And once verified, upload your sketch on your Microcontroller:

And if all has gone fine you should see your Microcontroller LED blink on in five seconds (notice the Red LED next to pin 13 light up in the below picture):

And off in another five seconds:

Of course, this will continue in a loop till you switch off the microcontroller by pulling the USB cable off, or till you upload a new sketch.

And with that, you have just controlled an onboard LED with your code. In the next post, we will attach an external LED to the Arduino using a breadboard and try and change the same code slightly to make that LED blink. If you’ve never worked on electronics before the next post will introduce you to a lot of basic concepts like breadboards and resistors. And from there we’ll be ready to build some real life projects. So stay tuned for the next post.

posted on Saturday, 08 October 2016 18:33:14 UTC by Rajiv Popat  #    Comments [0] Trackback