Using BaseUri to develop your VSTS extension

When you work on your Visual Studio Team Services or Team Foundation Server extension, you need a VSTS or TFS environment to deploy your extension to. To deploy your extension, you package all your JavaScript, HTML and CSS files into a VSIX and deploy the complete package.

This means that for every small change you make, you need to completely redeploy the package and then use your browser to validate the changes. Fortunately, there is an easier way to pickup changes while developing your extension.

BaseUri property for your manifest

While working on your extension, you can add a the properrty baseUri to your JSON manifest file. If this property is not present, all your files will be loaded from VSTS or TFS. When you add this property, you override the default location of your assets. By letting this property point to your local host you can serve the files locally and your extension will load them into the context of VSTS or TFS.

Take for example the following portion of a manifest:

 "manifestVersion": 1,
 "id": "AnotherSampleExtension",
 "version": "0.0.0",
 "publisher": "",
 "name": "Another Sample Extension",

Now you can add the the following line to enable serving your extension from your local host:

baseUri: "https://localhost:5000",

Do make sure that you specify a HTTPS enabled URL. Now while working on your extension, you can run the extension in the context of VSTS or TFS while are your local file changes are picked up without republishing your extension.

When you are finished with development, just remove the baseUri from your manifest file and publish the extension to the marketplace.

Microsoft is not your enemy

How do you feel about Microsoft? Do you think that Microsoft is a closed company that does everything in its power to win professionals and consumers over to the dark side? If so, you’re not alone. Many have a negative view of Microsoft. But is that view still true? Or is something totally unexpected happening and is Microsoft actually changing?

Microsoft is the enemy

But first, why should you listen to me? I am totally biased. I’m a Microsoft developer, have a Windows Phone, use a Microsoft Surface and I even have a Microsoft Band. I’m a Microsoft Most Valuable Professional (MVP) in Visual Studio and Development Technologies and I wrote several books on Microsoft stuff like Azure, C# and Visual Studio Team Services. I think Microsoft is the best. And I think Microsoft is changing, a lot, and I’m changing with it. It’s changing so much that I started learning Linux and Java and that I have ordered my first ever MacBook. Not because I’m leaving Microsoft but because I’m embracing the new direction that Microsoft is going in.

Live as a Microsoft fanboy

Open Source

My moment of revelation was on April 2014 during the keynote of the Microsoft Build conference. Anders Hejlsberg – C# lead architect and inventor of TypeScript – made a huge announcement on stage in front of thousands of Microsoft developers: he open-sourced the C# compiler and language. Yes, you read it correctly: Microsoft open-sourced one of its biggest projects and put it on GitHub (ok, first it was on Codeplex but that got quickly fixed). That was the first time I started really thinking about open-source and what that would mean for my future. Of course I already used some open source software such as jQuery but I hadn’t given it much thought.

Since April 2014 a lot has changed. One big step is that Microsoft started the .NET Foundation:

The .NET Foundation is an independent organization to foster open development and collaboration around the .NET ecosystem. It serves as a forum for community and commercial developers alike to broaden and strengthen the future of the .NET ecosystem by promoting openness and community participation to encourage innovation.

And the .NET Foundation is doing a lot of work. Big frameworks like .NET Core, the .NET Compiler Platform (Roslyn), ASP.NET Core, Entity Framework Core, MSBuild, and NuGet are all open sourced by the .NET Foundation. They accept pull requests and work completely in the open. You can read the language design notes for C# and you can view recordings of the discussions the ASP.NET team has on YouTube. Outside the .NET Foundation Microsoft is also running a lot of other projects on GitHub. PowerShell, CNTK (Microsofts AI framework behind Cortana), the JavaScript engine in Microsoft Edge and much more. Microsoft is even the top open source contributor on GitHub.

Cross platform

The .NET Core initiative is worth pointing out. This is a major initiative to make sure that .NET isn’t a Windows only platform. .NET Core supports Windows, Linux and Mac OS. Combine this with the Xamarin tooling and you can suddenly write .NET code for platforms ranging from the Microsoft Hololens to an iOS tablet, a Docker container or Raspberry Pi. On top of .NET Core, Microsoft builds ASP.NET Core: a cross platform framework for building modern web applications that can run anywhere. To support this new cross platform movement, Microsoft has also released SQL Server on Linux and made PowerShell run on Linux. This doesn’t mean that Microsoft is abandoning Windows but the world is definitely getting bigger from Microsofts point of view.

Developer tools

And that’s not the only thing Microsoft is doing. When you look at the developer tools and languages that Microsoft builds, there are also a lot of changes. Where Visual Studio previously meant a rich desktop client aimed at developing applications for Windows, Visual Studio now spans a whole family of products:

  • VS Code is a super optimized cross platform code editor that’s developed in open source. A fun fact is that Google uses TypeScript (developed by Microsoft in open source) and VS Code to build Angular 2.
  • Visual Studio for Mac is a fully featured IDE that runs on the Mac and lets you build ASP.NET Core and Xamarin applications.
  • Visual Studio Mobile Center offers cloud and lifecycle features for your mobile applications. Automated builds, cross device testing and distribution are all integrated and the product is growing rapidly. You can get started with just a GitHub account.
  • Visual Studio Team Services is a cloud hosted SaaS solution for DevOps. VSTS helps you with your Agile and Lean processes, gives you a hosted continuous integration and continuous deployment option integrated with automated testing, package management and monitoring solutions for all kinds of languages and environments.

The Cloud

And then there is Microsoft Azure. Microsoft Azure is the cloud solution that Microsoft builds and operates. Azure is huge. It has the highest number of datacenters of all cloud providers and supports a lot of different platforms. If you look at the Azure Marketplace you see solutions like Ubuntu, Oracle, Java, PHP, Hadoop, Blockchain services, and of course .NET. In whatever language on whatever platform you choose to develop, you can run it on Azure.

For me these are really exciting times. I’m eagerly waiting on my first Mac while playing with Bash on Windows and use Pluralsight to get up to speed on the Java world. I can’t wait to see what the future is going to bring but for now I can already say: it’s a great time to be a Microsoft developer.

Questions? Feedback? Please leave a comment!

Playing with Feature Flags and LaunchDarkly

Feature Flags are an important part of DevOps. Where DevOps is initially about things like breaking down silos and implementing a continuous flow of value, the next steps are all about Feature Flags, A/B Testing and monitoring.

The concept of Feature Flags is simple. In my book, DevOps on the Microsoft Stack, I discuss how to use the open source FeatureToggle library from Jason Roberts hosted on GitHub. This library allows you to define toggles and store the state in your configuration file, a database or through a web service call. When a toggle is on, you activate a feature. When it’s off, you remove the feature and don’t show it to the user. That’s a great start but there is more possible when using Feature Flags.

Feature Flags with LaunchDarkly

LaunchDarkly is a commercial implementation of a Feature Flags framework. It’s very easy to use and it’s way more powerful then FeatureToggle but it’s not free. In the following steps I want to show you how to implement a very simple toggle for an ASP.NET MVC application.

You first have to signup for LaunchDarkly to get an API-key. You can start a free 30 day trial that gives you all the available features. If you navigate to https://launchdarkly.com/ you can start a free trial by entering only your email address and a password.

SignUpForLaunchDarkley

You’re then taken to the portal where you can create your first Feature Flag. I’ve created a flag named About Page that I want to use to determine the visibility of the about page in my ASP.NET MVC web app.

DashboardWithFeatureFlag

To integrate LaunchDarkly into your application, you need an API key. If you go the Account settings in the portal, you see that there are two predefined environments: production and test.  I’ve chosen to use the test environment API key for this project.

APIKeys

Now launch Visual Studio and create a new web project. I’ve chosen for an ASP.NET 4.6 MVC template with individual user authentication. After the project is created, install the the NuGet package with the LaunchDarkley client:

Install-Package LaunchDarkly.Client

LaunchDarkley requires the newest NewtonSoft.Json package so after installing LaunchDarkley run:

Update-Package Newtonsoft.Json

Update the HomeController.cs file to the following content:

using System.Web.Mvc;
using LaunchDarkly.Client;
 
namespace FeatureFlags.Controllers
{
    public class HomeController : Controller
    {
        static LdClient client = new LdClient("YOURAPIKEY");
 
        public ActionResult Index()
        {
            User user = GetUser();
            bool value = client.Toggle("about-page", user, false);
 
            ViewData["togglevalue"] = value;
            return View();
        }
 
        public ActionResult About()
        {
            User user = GetUser();
 
            bool value = client.Toggle("about-page", user, false);
            if (value)
            {
                ViewBag.Message = "Your application description page.";
                ViewData["togglevalue"] = value;
                return View();
            }
            else
            {
                return HttpNotFound();
            }
        }
 
        private static User GetUser()
        {
            return LaunchDarkly.Client.User.WithKey("bob@example.com")
                            .AndFirstName("Bob")
                            .AndLastName("Loblaw")
                            .AndCustomAttribute("groups", "beta_testers");
        }
 
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
 
            User user = GetUser();
            bool value = client.Toggle("about-page", user, false);
            ViewData["togglevalue"] = value;
            return View();
        }
    }
}

And update the rendering of the About Action Link in _Layout.cshtml to:

@if (ViewBag.togglevalue == true)
{
    <li>@Html.ActionLink("About", "About", "Home")</li>
}

OK. So what did we do? The HomeController starts with initializing a static LaunchDarkley client. This member is static because the documentation says that you only want one instance of this variable for your whole application.

Then all three action methods are modified to check if the user has access to the about page. In the Index and Contact method, this data is passed to the view in the ViewBag. When hitting the About page, this data is not only passed to the view but it’s used to check if the user is allowed to see the page. If not, an HttpNotFound is returned.

Finally, the _Layout.cshtml page checks the toggle value and renders the link if the user is allowed to see it.

If you now run the application, you’ll see that the About link is not visible and that navigating to /Home/About returns a 404. This is because the user is not known to the system and by default the flag is set to false.

MenuWithoutAboutLink

To enable the toggle, go to the LaunchDarkly portal and select the About Page feature toggle. In the targeting panel you can explicitly list users that are allowed or disallowed based on their key, country, IP, etc. For this sample, just add Bob Lowblaw (the hard coded name of the user in this sample) to the included list and hit save changes.

AboutFeatureToggleConfig

If you now refresh your local website, the About link becomes visible and you can navigate to it.

And this is only the beginning. Targeting users (or groups of users) is a great start but still requires manual configuration. Another feature of LaunchDarkley is rolling out your application to a configurable percentage of your users. You can also configure goals that you have (such as a number of page views), link these goals to your feature flags and then analyze the data coming out of this.

I think LaunchDarkley is a very interesting product that can prove to be really useful. If it’s worth the money depends of course on the project but I would encourage you to have a look at it and see if it fulfills your needs.

Questions? Feedback? Please leave a comment.

Keeping a Continuous Integration build from starting

When configuring your Build Definitions on Visual Studio Team Services or Team Foundation Server, you can configure a Continuous Integration (CI) build. A CI build runs for every checkin or commit that you make to source control. This allows you to start an automated process that for example compiles and deploys your build.

CI Trigger for Build

Now that’s a very useful feature and I try to setup a CI build for every project that I work on. However, sometimes you don’t want a CI build to run. For example, if your making a change to Markdown file that contains your documentation or you’re updating an image or something else that’s not part of your build. Normally, these kind of changes will trigger a CI build.

One easy way to avoid a CI build when you commit a change is to add ***NO_CI*** to your comment as a suffix. This signals to VSTS that you don’t want to run a CI build. Since the commits are part of your history, you can always trace back why a certain change didn’t trigger a build.

Do you know any other useful tricks and tips for VSTS/TFS? Please leave a comment!

Exploring Visual Studio “15”: Code Styles

Styling your code is important. You are reading your code more often then you’re writing it. Making sure that reading is as easy as possible, especially when you work with multiple developers on a project, can be a challenge.

Fortunately, Microsoft is investing in Visual Studio to help you with styling your code.

Code Styles in Visual Studio “15” Preview

How do you style your switch statements? Do you use indentations for your curly braces { } ? Where do you place your open brace? Does everyone on your team agree? How do you enforce these kinds of rules?

Visual Studio “15” helps you. If you go to the options menu in Visual Studio “15”, you will find a new group named Code Styles in Text Editor –> C#.

Code Styles - General

It’s now really easy to configure styles for your liking. The Options dialog box shows automatically updated sample code that follow the styles you configure. Figure 2 shows your preferences for indenting the content of a case statement in a switch.

Code Styles - Switch formatting

You can also apply coding styles to the naming of your elements. For example, you can enforce PascalStyling in the names of your symbols. If you go to Options –> Text Editor –> C# –> Code Style –> Naming, you can create a new naming rule. The following configuration enforces PascalStyle naming:

First, you select which symbols you want to apply the naming rule to.

MatchAllElements

Then you define the naming rule. In this scenario, only Pascal Case Name is chosen for capitalization.

PascalCaseStyle

Then finally, you configure the severity of the rule. In this case, I made it an error.

ConfigureNamingRule

Now, if you create a method that doesn’t start with an Uppercase letter, you get an error and an automatic code fix in the editor.

PascalCasing_UppercaseB

Some things that I would like to see for Code Styles is the ability to configure styling as a part of your project in Visual Studio. That way, you can bring your Code Styles under source control and share them with your team. Maybe we can even move the Code Styles to a NuGet package allowing us to share rule sets over multiple projects.

What do you think of Code Styles? Any feedback or comments?

File encoding: UTF-8 and UTF-8 BOM

Before packaging an extension, I parse the JSON manifest and update the version number. This allows me to set my version at packaging time and then use the same version when deploying to several different environments.

While parsing my manifest file, I suddenly ran into the following error:

Error occurred while updating tasks version: Error determining tasks manifest paths: SyntaxError: Unexpected token

Somehow, my code wasn’t able to open manifest file and parse the JSON in it. After reaching out to the product group I found out that this had to do with the encoding of my JSON manifest file. If the encoding is UTF-8, everything works as it’s supposed to do. My manifest had an encoding of UTF-8 BOM. BOM stands for Byte Order Mark. This is a ‘magic string’ that appears at the start of a file to signal to a reader of the file things like encoding and endianness (see Wikipedia for more information).

All I had to do was convert my JSON manifest file from UTF-8 BOM to UTF-8. The easiest way that I found was using Notepad++. After opening the manifest file in Notepad++, you can change the encoding of the file from the encoding menu and then save the file to disk.

Encoding in Notepad++Saving the file as UTF-8 fixed the error.

My VSTS Presentation at SDN

Last week I had the privilege of giving a presentation at the Software Development Network conference. There was a nice turn-out of around 50 people. After a couple of slides I had one big demo that showed the different elements of Visual Studio Team Services such as Plan, Code, Build, Test, Release and Monitor.

You can find the presentation here: From 0 to 60. After the slides I included a series of screenshots that take you through the demo (in case of a failing internet connection!).

During the presentation we had some interesting questions and discussion points like:

  • My team uses an on-premises TFS. When will all the new features of VSTS be available for TFS?

You can check the Visual Studio Team Services Features Timeline to see when features will be available for TFS.

  • My testers work in an Agile way. Can they use the testing features without having to create huge test cases upfront?

Yes. You can use Exploratory Testing. You can run an Exploratory Testing session with Microsoft Test Manager or with the new extension for Chrome.

  • What’s Kanban?

Through a demo I showed how to use and configure the Kanban board. To get a grasp of the basics of Kanban, you can find info on MSDN.

  • What’s the Marketplace for VSTS and is it useful?

It’s absolutely useful! The Marketplace allows you to find an install extensions for Visual Studio, Visual Studio Team Services, Team Foundation Server and Visual Studio Code. You can find small, easy to use extensions like Folder Management and Branch Delete and more complex extensions like Work Item Visualization and File owner.

  • Who are the ALM Rangers?

I always insert a slide that explains what we do as ALM Rangers. Often people haven’t heard of us yet but have already used guidance or tooling that we build. You can find more info at aka.ms/vsarunderstand.

Questions or other feedback? Please leave a comment. 

 

Typings for TypeScript

When using TypeScript, you will need TypeScript definition files to work with external libraries. A lot of those definition files are available on GitHub: DefinitelyTyped. At the time of writing, there are 1708 entries which is to much to show, even for GitHub.

Let’s say you want to work with jQuery. If you look at the DefinitelyTyped folder for jQuery, you’ll find a couple of files:

jQuery-DefinitelyTyped

The extension .d.ts signals that the file is a TypeScript Definition file. To use these files in your project, you can choose to download the Definition file and copy it to your project. But manually downloading and searching for files doesn’t sound like the best option.

Fortunately, there is an easier way: Typings.

Using Typings for TypeScript

One scenario where I used Typings is while developing the open source Folder Management extension that you can find at GitHub.

The Folder Management project uses Node Package Manager to download external libraries that it uses. If you look at the package.json file you can see which packages are used in this application:

{
 "name": "folder-management",
 "version": "1.0.0",
 "description": "Microsoft DevLabs Folder Management extension",
 "keywords": [
 "vsts",
 "tfs"
 ],
 "scripts": {
 "initdev": "typings install",
 "copyfiles": "copyfiles -f node_modules/vss-sdk/lib/VSS.SDK.js node_modules/jquery/dist/jquery.min.js scripts/lib",
 "setup": "npm run initdev && npm run copyfiles",
 "package": "tfx extension create --manifest-globs vss-extension.json",
 "publish": "tfx extension publish --token <token> --manifest-globs vss-extension.json"
 },
 "author": "ALM Rangers",
 "license": "MIT",
 "devDependencies": {
 "copyfiles": "^0.2.1",
 "grunt": "~0.4.5",
 "grunt-cli": "^1.1.0",
 "grunt-contrib-copy": "~0.8.2",
 "grunt-exec": "~0.4.6",
 "grunt-typescript": "*",
 "jquery": "^2.2.2",
 "requirejs": "2.1.22",
 "tfx-cli": "^0.3.19",
 "tsconfig-glob": "^0.4.0",
 "typescript": "^1.7.5",
 "typings": "^0.6.6",
 "vset": "^0.4.24",
 "vss-web-extension-sdk": "^1.96.1"
 }
}

The dependency we’re now interested in is typings. Adding this line to your package.json makes sure that the typings library is downloaded to your node_modules folder. If you then look at the script sections you see a line named initdev that runs a typings install command.
The Task Runner Explorer shows the custom tasks that I defined in package.json. The initdev task is the one we’re interested in.

Task Runner Explorer - NPM tasks

When you run this script, typings looks for a typings.json file and starts downloading the definition files that you need. The typings.json file for Folder Management looks like this:

{
 "dependencies": { },
 "devDependencies": { },
 "ambientDevDependencies": {
 "Q": "github:DefinitelyTyped/DefinitelyTyped/q/Q.d.ts#4de74cb527395c13ba20b438c3a7a419ad931f1c",
 "jquery": "github:DefinitelyTyped/DefinitelyTyped/jquery/jquery.d.ts#470954c4f427e0805a2d633636a7c6aa7170def8",
 "knockout": "github:DefinitelyTyped/DefinitelyTyped/knockout/knockout.d.ts#4de74cb527395c13ba20b438c3a7a419ad931f1c",
 "tfs": "github:microsoft/vss-web-extension-sdk/typings/tfs.d.ts",
 "vss": "github:microsoft/vss-web-extension-sdk/typings/vss.d.ts"
 }
}

You configure a name and a url to each definition file that you want to have. In this case, I’m downloading the files for Q, jQuery, Knockout and the TFS and VSS sdks. The easiest ways to get the URL, is navigate to the file in GitHub and use the ‘Copy path’ button.

If you have the typings dependency downloaded through NPM and you have the typings.json file, you’re ready to run the typings install script. Running this script will give you a new folder named typings. In this folder, there is a main.d.ts file that references all your downloaded definition files. All you have to do, is add a reference to main.d.ts from your TypeScript files and you’re done.

Solution Explorer showing typings

And that’s all there is. Feel free to download the code from GitHub and open the solution in Visual Studio. You’ll then automatically download the NPM packages and be able to use the Task Runner to run the initdev script to download the typings.

Feel free to leave a comment!

 

Why I’m starting to like Git – Part 2

In the previous post, I looked at the distributed nature and local history of Git. In this post I discuss another feature that makes Git particularly powerful: branching.

Branching in Git

If you look at the guidance for branching in TFVC, you will learn that branching is something you should try to avoid as long as possible. There are scenarios where you do need branching but branching in TFVC is hard and easily leads to merging conflicts and branching hell. Often the best branching strategy is having no branches at all.

Git is different. Git promotes branching. In Git it’s customary to create (and delete!) multiple branches a day. Branching can be done completely locally without having to contact the server. When you start working on a new feature, you can easily create a local branch, do your work and merge the changes back to the main line. This allows you to keep development on several features nicely isolated.

Branching in Git is fast. Creating a new branch and switching between branches are operations that run locally on your machine. You don’t have to contact a central server to branch. Merging between branches is also easier in Git then in TFVC.  Since Git knows the completely history, it can see which changes where made since you branched and use this to do a merge as optimal as possible.

While working on some Git projects for VSTS extensions, I created a branch for every new feature I started working on. When finished, I did a pull request (a topic for a future post) or merged the changes locally to the main branch. This is a nice way of working. It makes it easy to have different versions of your application locally and switch between these when the need arises.

Do it yourself!

The following script starts with a new Git repository. You then add two new files and commit these to the current master branch. After that, you create a new branch named dev and switch to it. You then add a third file and commit it. If you now switch back to master, you’ll see that the third file is not visible in your working directory.

git init

New-Item index.html -type File
New-Item readme.md -type File

git add .
git commit -a -m "Initial commit"

git checkout -b dev

New-Item script.js -type File

git add .
git commit -a -m "Added script"
git status

git checkout master
dir

What’s next?

Gits distributed nature gives you a local history and lets you easily create and switch between branches. Another powerful feature that Git offers is pull requests. That’s what the next post will discuss.

So what do you think? Git: love it or hate it?

Why I’m starting to like Git – Part 1

Git. Some people love it, others hate it. I have to admit that I was in the camp of the haters. Not that I didn’t like Git, I just found it too difficult and didn’t understand why Git was so popular. Team Foundation Version Control (TFVC) was so much easier to use and I was already familiar with it so why look at Git?

This is the first post in a series where I discuss some of the things I learned about Git and that made me start liking Git more and more.

Local History in Git

Git is fundamentally different from TFVC. Git is a distributed version control system (DVCS) The whole idea behind a distributed version control system is that you not only have the current snapshot of your code but also the complete history in your local repository. In TFVC (a centralized version control system), when you do a Get Latest, the server is contacted and a snapshot of the latest state of your code is downloaded to your machine. With Git, when you download the latest changes to your machine, you don’t download a snapshot. Instead, you download all the changes that where made to your code and apply these to your local repository.

A direct consequence of this is that you can append changes to your local history without uploading them to a central server. This is called a Commit in Git. A Commit is like a changeset in TFVC that’s stored in your local repository. You can commit multiple times and then decide to upload these changes to a central location where other team members can download them. This is called a Push.

Git is a Distributed Version Control System

Why helped this feature change my mind? The advantage of local history is that you can easily experiment with changes. Instead of having to wait with uploading your changes until your code is ready to be shared with others, you can locally commit your changes and create a history where you can easily go back to a previous version without having to share your code with others.

Do it yourself

To get a feeling of how this works, run the following commands in a PowerShell console on your local machine. Make sure you have installed Git.

First, create a new repository in a folder on your machine:

md mylocalrepository
cd mylocalrepository
git init

Then create two files, add them to your local repository and commit the changes

New-Item index.html -type File
New-Item readme.md -type File
git add .
git status
git commit -a -m "Initial commit"
git status

Now create a third file and commit it.

New-Item scripts.js -type File
git add .
git commit -a -m "Added scripts"

If you check your log, you’ll see that you now have 2 commits. By using the checkout command you can view the state of your files for a specific commit. By using reset –hard, you move the complete state of your local repository back to that moment in time

Make sure to replace the two commit ids with values of your own as shown in the log command

git log
git checkout 0d1d7fc32
git reset --hard 0a2681d8fc
git log

What’s next?

This was only one of the features that made me reconsider Git.Understanding the idea behind distributed version control and Git in particular and temporarily forgetting your TFVC experience helps when moving to Git. Of course this doesn’t mean that TFVC is dead and that I’ll never use it. It’s still popular and is actively developed by Microsoft. Git is just another tool for your toolbox.

In the following part, I take a look at Git branching and how that differs from TFVC.

So what do you think? Git: love it or hate it?