Monday, April 30, 2018

Copying data to memory with JavaScript and jQuery

How to copying data to memory with JavaScript and jQuery? Read and understand.

A nice feature to have in your site is the ability of letting users copy certain pieces of data to the memory. This is useful for example to copying things such as Ids, phone numbers, urls or connection strings. Stuff that's complicated to type or very error prone.

Turns out that a simple solution can be achieved using JavaScript and jQuery. Let's see how.

A Simpler Approach

Here's how I approached it:

1. add a class to show a copy icon whenever you hover a DOM element:

Ex. class="icon-clipboard"

2. add a css class to identify what you want to copy:

Ex. class="copyableTemplate"

3. add the data to copy using the "data-clipboard" attribute:

Ex. data-clipboard=""

4. handle the click event on the copy icon and get the data associated to it:

Ex. $('body').on('click', 'div.icon-clipboard', function() { })

5. copy to memory using the browser's api:

Ex. document.execCommand('copy');

Source Code:

See Also

Monday, April 23, 2018

Testing JavaScript on ASP.NET Core Applications

On this post, let's take an in-depth look on how to test JavaScript using ASP.NET Core.
We've been discussing .NET on this blog for some time. On this post let's addres how can we can run JavaScript tests against your ASP.NET Core web application. If you're new to JavaScript tests, please check this link for a nice intro on JavaScript testing using existing testing frameworks.

This is a long post, so please grab some coffee and read on. 😊

Introducing Chutzpah

My solution of choice for running JavaScript in .NET Core applications is Chutzpah, an open source JavaScript test runner that integrates well with Visual Studio, Visual Studio Code and the .NET stack. But Chutzpah is not a testing framework itself. It is a test runner. That said, you'll also need to choose a JavaScript testing framework. Since I've been using the Jasmine for some time and I like it, I will use it on this demo. Note that Chutzpah is unopinionated and allows you to run unit tests using other frameworks such as QUnit, and Mocha. Choose what works best for you.

Writing Jasmine Tests

Without further ado, let's jump into an example. For starters, this is what a simple Jasmine test looks like:
Don't worry about that code yet. We will cover it in detail below.

Testing JavaScript in ASP.NET Core

Now let's create a new ASP.NET Core web app and configure it to use Chutzpah and Jasmine. Basically what we will do is:
  1. create a new core web app
  2. add Jasmine as a NuGet package
  3. add you JavaScript files
  4. test them =)

Step 1.1: Create a new Asp.Net Core web app

Open your Visual Studio -> New Project -> select ASP.Net Core Web Application and enter a name. Then, select "Web Application" from the popup box:

Step 1.2: Add the Jasmine NuGet Package

Right click your web project -> References -> Manage NuGet packages. On that window (I'm using VS2017) type jasmine, click install.

Step 1.3: Add your JavaScript files

For simplicity, I'll add a simple "mathhelper.js" script that will be tested:

Step 1.4: Add your Jasmine JavaScript test file

Now, follow the same process and add your test file. I called mine "mathhelper.js"

Good. Now it's time to install Chutzpah and run your tests directly from Visual Studio and from the command line if you want to.

Running tests with Chutzpah in Visual Studio

To complete this step we need to:
  1. Add Chutzpah as a referenced NuGet package;
  2. Install the Chutzpah extension in Visual Studio

Step 2.1: Add Chutzpah as a referenced NuGet package

Search for "chutzpah" in the NuGet search window and add it as a reference to your project.

Step 2.2: Install the Chutzpah extension in Visual Studio

In order to make Visual Studio recognize our tests we then need to install the Chutzpah extension by doing Tools -> Extensions and Updates. After typing "chutzpah" in the search box I get:
Click Download and restart your Visual Studio. When you're back, open the Tests Window (Test -> Windows -> Test Explorer) and you should see our test there:

Running the tests in Visual Studio

Now, from Visual Studio I can run my test as a regular unit test. I will simulate a quick TDD here by making the test fail:
Now, go ahead and fix it. You'll see that if the test's correct, Visual Studio will show it green!

Debugging the tests in Visual Studio

Note that Visual Studio and Chutzpah together can bring us great benefits like debugging our JavaScript unit tests. Here's it on my machine:

Running JavaScript tests in the console

Because Chutzpah uses the PhantomJS headless browser to run your tests, the nicest thing we can do is to be able to run JavaScript tests in the console. Why is that good? Because we can then integrate the tests in our IDE/build process and gain speed and quality by doing that. And the key to that happen is the Chutzpah console tool.

The Chutzpah console tool

Remember that previously we installed the Chutzpah NuGet package? Because .Net Core stores all Nuget packages on "~/.nuget/packages" as previously described on this blog, on my Windows machine I can access it on:

Please note how many options we have available. This post only scratches the surface!

Running my tests in the console

So, in order to run our tests in the console, just invoke the chutzpah.console.exe and point to the current folder. That executable will search for JavaScript tests and run them reporting a summary in the end:


I'm a big fan of automated tests. I have written thousands of them in my career and recommend everyone to do the same. The more tests we have, the easier it gets to improve/refactor/extend the code base and, with confidence! On that context, JavaScript tests are extremely important. Especially because JavaScript is an interpreted language and you won't know something is broken until you run that code what's both expensive and highly risky. TypeScript solves some of those issues by transpiling your JavaScript but that does not guarantee that your logic is flawless.

All that said, my recommendation is adding automated testing to your CI/CD services to make your team more confident and increase your overall quality. We can and should integrate test runs in our release pipeline we can gain a lot of productivity and quality by doing that and the console tool is the key to do that integration.

Source Code

The source code for this post is available on my GitHub.


See Also

Monday, April 16, 2018

How to render ASP.NET views in the backend

Did you know that we have an elegant approach to generate views with ASP.NET and ASP.NET Core? Read to understand.

It's possible that your backend runs on a different server than your web server. What would you do if you have to render certain views or even send emails on your backend (ex. reset password token) but don't have access to the MVC framework from it?


An elegant solution would be using RazorTemplates. RazorTemplates is an open source templating engine based on Microsoft's Razor parsing engine. The library allows building razor templates outside ASP.NET MVC Projects including in our own backends. It solves that common use case where we need to email users from our backends.

For reference, the github page is located here.

Using RazorTemplates

Add a reference to your project

The first thing you need to do is to add a reference to the RazorTemplates nuget package to your solution:
Project -> Manage Nuget Packages -> search for "RazorTemplates":

Create your view

Once added, it's time to create your views. Simply create a csthml in your non-web project as you would create any other file type, suffixing it with cshtml.

Note that here my model is dynamic so I'm not required to have a strongly typed model.

Set the custom tool property

Because you want to use your view server side, you need to have a C# file to reference it. To make that happen, you need to configure Visual Studio to to scaffold the C# code for you. To do so: click on your recently added file and press F4 to display the Properties Window, then set the custom tool property to "RazorGenerator":

Render the view in the backend using C#

Then, to have your template generated, you just need to call RazorTemplate's TransformText method. After the above code is run, TransformText returns you a string with the rendered content. You can then email that string or create fancy reports from your backend.

RazorTemplates and ASP.NET Core

To Asp.Net core users, Microsoft just released a similar approach to Razor UI in class libraries. We will explore that feature in the blog in the future.

Final Thoughts

While ASP.NET Core provides server-side view generation, none exists for ASP.NET. Since one of the most common scenarios developers encounter is emailing users from the backend, an elegant solution would be using the aforementioned RazorTemplates nuget package.

See Also

Monday, April 9, 2018

Skill Up: A Software Developer's Guide to Life and Career

A book every software developer should read.

I just finished reading the book Skill Up: A Software Developer's Guide to Life and Career by Jordan Hudgens.

If you are currently working as a developer (all levels), freelancer (or contractor) and/or want to build up on your career skills, you should read it. Here's the book description:
This unique book provides you with a wealth of tips, tricks, best practices, and answers to the day-to-day questions that programmers face in their careers. It is split into three parts: Coder Skills, Freelancer Skills, and Career Skills, providing the knowledge you need to get ahead in programming.

Tips for Developers

Here's a couple of quotes targeting developers that I enjoyed in the book:
  • Excellence is as straightforward as focused practice. Don't believe on the myth of genius developers;
  • When your working on something hard or are learning something new, remove any and all potential distractions, limiting the slot to around two hours.
  • Deep work is the ability to focus without distraction on a demanding task. 
  • A Research from about task-switching shows that it takes, on average, 23 minutes and 15 seconds to get fully back on task after being distracted. Keep focused!
  • Set small goals, you're less likely to put it off.
  • To think about the new concept instead of rushing through it. 
  • Keep stretching yourself by learning a new programming language or framework, teaching others or creating an open source library

Tips for Entrepreneurs

A few tips for entrepreneurs:
  • Use services like HARO to pair up with reporters and have your name out there.
  • Recruit other developers if you're working on something that's not in your domain of expertise.
  • Blogging is a great way to position yourself as an expert.
  • Try to avoid scope creep.
  • Starting over versus refactoring.
  • Basecamp and Freshbooks can be valuable tools for freelancers and entrepreneurs.
  • How to engage new clients.
  • LinkedIn and good old referrals are still strong networking tools, don't ignore them.

Career Tips

A few career tips that I liked were:
  • If you should learn how to code and how to learn from scratch.
  • What specialty should you take.
  • Which programming language.
  • Bootcamps and other ways to improve your programming skills.
  • Resume and salary tips.
  • Enterprise software job.


This book has tips for everyone. Don't forget that the life of a developer and/or entrepreneur is not easy. Coding is hard! Keeping up to date with libraries and techniques is hard! Dealing with clients is hard! So what can we do to keep up to date with all facets of our profession?

I personally enjoyed this book because some of the techniques/tips introduced here I was already using on my life (pomodoro technique, deep work, task switching, etc) and are things I always try to pass to my fellow developers when I can. Plus, the career tips on Part III were very insightful too.

Hope it has something that you're looking for too!


See Also

Monday, April 2, 2018

How to Build and Run ASP.NET Core on Linux

Building and Running ASP.NET Core apps on Linux is fun. Let's review how that works.
Continuing the discussion about .NET Core, on this post, let's talk about building web applications using the .Net Core framework entirely on Linux. But before touching code, what is Asp.Net Core?


Asp.Net Core  is the evolution of Asp.Net, a web application framework developed by Microsoft to build web applications, web APIs and web services. ASP.NET Core was renamed from ASP.NET v5 since it was a full rewrite to meet .NET Core's requirements.
For an in-depth introduction on ASP.NET Core, please check this page.

Why ASP.NET Core?

Because it represents the next generation of the existing Asp.Net stack with true multi-platform, faster and with many other improvements such as:
  • The framework is completely distributed as NuGet packages
  • Cloud-optimized runtime
  • A unified story for building web UI and web APIs
  • A cloud-ready environment-based a rewritten configuration system
  • A lightweight and modular HTTP request pipeline
  • Build and run cross-platform ASP.NET Core apps on Windows, Mac, and Linux
  • Open-source
  • Side-by-side app versioning when targeting .NET Core.


My favourite feature of ASP.NET Core is being multi-platform. That opens up the development to Mac and Linux. Being able to run on Linux is also an advantage because containers are Linux and running on Linux is faster, cheaper and more secure than on Windows.


Being able to run on Linux also allows us to run ASP.NET Core web apps on containers. Running our web apps on containers mean our apps can be scaled out more easily, are more secure and can be run on modern clusterization tools such as Kubernetes with very little effort.


Kestrel is another nice addition to .NET Core. With it, ASP.NET websites no longer rely on IIS to run, are easier to run on containers and on the cloud.
You should not use Kestrel in production as it does not have outstanding performance neither supports advanced features like virtual hosts, logging, security, etc.

Rich CLI

There are a lot of command-line tools that can be used to more easily create the command dotnet is the entry for them.We can start interacting with the dotnet tool by:
dotnet new --help
On Linux, if issue the command above I get:

    Creating a Razor-based ASP.NET Core app

    The simplest web app we can build in Asp.Net core is a razor web app. Assuming that we installed the templates described previously, the first command that we need to run is:
    dotnet new razor -o razordemo

    After cding into that folder, by running the command below I have my app running:
    dotnet run
    A scaffolded razor core web app running on Linux

    Creating a ASP.NET Core SPA app

    In order to create SPA web apps in .Net Core, we may need to install the Microsoft.AspNetCore.SpaTemplates nuget package. That package installs spa templates for the more common client side frameworks including Angular and React.js.

    Some of the templates may use NPM and  WebPack 2 to bundle and deploy all client resources (JavaScript, html, images, and CSS). They can be installed with the following dotnet core command:
    dotnet new --install Microsoft.AspNetCore.SpaTemplates::*
    Once installed with the command above, if you run dotnet new command you'll see your existing templates:
    dotnet new --help
    To create a new web app running Angular, for example, just run, as exemplified above:
    dotnet new angular -o angulardemo
    As informed, the installation is not ready yet. I still need to run "npm install" on the command line to finish package dependencies. So I cd into my angulardemo folder and run "npm install" and, to finish up, just run dotnet run to start your web app pointing your browser to that address:
    dotnet run


    On this post we introduced ASP.NET Core development on Linux. I hope it was clear to understand how easy it is to scaffold ASP.NET Core web apps entirely in Linux. I hope you now realize how mature the .NET Core framework has gotten on non-Windows platforms. You can reproduce the exact same steps on your Mac if you want. Linux is now a viable alternative for developers working with the .NET stack! Why don't you also give it a try yourself?


        See Also

          About the Author

          Bruno Hildenbrand      
          Principal Architect, HildenCo Solutions.