Tag: Visual Studio
Auto Format C# Code

Auto Format C# Code

When you're reading code there are a few things which make the process a lot easier, particularly when it was code written by other people.

  1. It's commented well.
  2. It's written in a logical way.
  3. Lines of text aren't really really long meaning you have to side-scroll.
  4. The formatting is consistent.

There's not a lot we can do about the first two other than having a good team, but the second two are something that can be automated and enforced.

In many languages (particularly front-end code) there's a tool named prettier that can configure everything from tab spacing, line length and even if you end a line with a semi-colon or not. I've used it for years and it's brilliant. Unfortunately, it doesn't support C#.

A tool I have found though is CSharpier (https://csharpier.com/), and like Prettier it is an opinionated code formatter.

Add CSharpier to your project

To get started with CSharpier first create a tool-manifest file in the root of your project and then run the install command.

You can do this with the following terminal commands.

1# if you don't yet have a .config/dotnet-tools.json file
2dotnet new tool-manifest
3
4dotnet tool install csharpier

Next add a configuration file to your project so that all team members will produce the same results.

To do this add a JSON file named .csharpierrc.json to the root of the solution.

1{
2 "printWidth": 100,
3 "useTabs": false,
4 "tabWidth": 4,
5 "endOfLine": "auto"
6}

After you add CSharpier you will want to reformat every file in one go, otherwise your going to spend a year going through PRs mostly containing format changes as every file gradually gets reformated.

Do this with the following command.

1dotnet csharpier .

Configure Visual Studio to auto format on save

There's lots of options for triggering the format; You can do it manually, on Pre-commit hooks, or within CI tools, but I find the best is to have a file format on save. This way not only is it making your code readable to everyone else, it also makes it easier to read as your working on it. Plus when tab spacing doesn't fix itself correctly its a good indication there's something wrong with your code.

To do this you will need to install the Visual Studio extension https://marketplace.visualstudio.com/items?itemName=csharpier.CSharpier

Once installed you then need to configure it to format on save. This is located under Tools | Options | CSharpier | General and can either be configured at a global and project level.

CSharpier Visual Studio Config Dialog

And that's it. Now whenever you save a file it will automatically get reformated.

Running multiple projects from Visual Studio

Running multiple projects from Visual Studio

We're probably all familiar with the debugging experience in Visual Studio. Press F5 or hit the green play button and your application will run in debug mode. If you have multiple projects in you solution which can run (i.e. they're not a class library) then the one with a bold title in solution explorer will run.

To change which project starts by default right click the project and choose Set as Startup Project.

Selecting start up project in Visual Studio

You can also use the drop down next to the play button to switch which project will run when you start debugging.

Selecting project to run in Visual Studio

Running multiple project at the same time

However switching between projects might not be what your after. You may need multiple projects running that interact with each other. e.g. You could have an API written as an Azure Function and a Website which uses the API. The simple option is to just open to copies of Visual Studio and run one in each, but there is a better way.

Right click your solution in Solution Explorer and click properties.

Selecting properties for solution in Visual Studio

Make sure you have Startup project selected on the left. On the right change the radio to Multiple startup projects and in the grid use the drop down to change the action to either Start or Start without debugging on the projects you want to run.

Visual Studio selecting multiple startup projects

The drop down next the play button will now show that multiple startup projects have been selected.

Visual Studio multiple startup projects selected

Now when you start to debug all the projects you have set to start will all debug together for one seamless debugging experience. Just make sure they're not all running on the same port number.

Running Gulp tasks in Visual Studio

Running Gulp tasks in Visual Studio

Over the last decade, front end development has matured from a point where CSS and JavaScript were written in badly organised files containing the exact code a browser would interpret, to something that now more resembles back end development.

Pure CSS has become the byte code of the front end world with LESS and Sass becoming the languages of choice. Instead of MSBuild for running a compilation Gulp can be used to automate workflows to compile Sass files, minify them and do whatever else is needed to produce the code for deployment (not really an exact comparison, but you get the point).

To truly achieve a matured development setup though, the final step is to remove those "compiled" css and js files from source control. After all you wouldn't check in a dll with the source code for each build. If your using a build server then this is a relatively easy step to add to your workflow. However the bigger issue is not making life hard for your back end developers.

Without the final CSS and JS files in source control your back end devs may now be faced with a site lacking all style and front end functionality when they hit F5. With LESS and Sass also not really being there thing, they're now left not really knowing what to do, and also not overly happy about having to learn something about front end do continue with there back end work. To make matters worse, Visual Studio often isn't the front end dev's choice of tool so copying the front enders setup isn't an ideal solution either.

The Aim

The ideal solution would be for a back end dev to be able to check out a solution from source control (containing no compiled CSS of JS files), hit F5 in Visual Studio, the final CSS and JS be created as part of the build and the site to run. No opening a command prompt to run a gulp task, or any other process the front end devs may be using. It should be completely invisible to them.

Visual Studio Task Runner

With Visual Studios Task Runner, this is entirely possible.

The Task Runner is built into Visual Studio, so there's no need for the back end dev to install any extra tools, and more importantly, tasks can be linked into a before build event so that the back end dev doesn't need to do anything.

A bit of background on gulp and the task runner

When front end developers set up gulp, they will configure a set of gulp tasks within a file named gulpfile.js (in reality they may actually separate the tasks into multiple files referenced by gulpfile.js, but this file is the important bit). These tasks may look a bit like this:

1gulp.task("min:js", () => {
2 return gulp.src([paths.js, "!" + paths.minJs], { base: "." })
3 .pipe(concat(paths.concatJsDest))
4 .pipe(uglify())
5 .pipe(gulp.dest("."));
6});
7
8gulp.task("min:css", () => {
9 return gulp.src([paths.css, "!" + paths.minCss])
10 .pipe(concat(paths.concatCssDest))
11 .pipe(cssmin())
12 .pipe(gulp.dest("."));
13});
14
15gulp.task("min", gulp.series(["min:js", "min:css"]));

In this example there are 3 tasks. The first minifies some JS while the second minifies some CSS. The third is defining a series which runs the first 2.

Visual Studios task runner will look file the file called gulpfile.js and pull out all the tasks within it. The task runner window may not be open by default, so to open it type task runner in the search box and select it from the results. Alternatively you can right click the gulpfile in the solution and select Task Runner from the context menu.

The task runner window will open at the bottom of the screen, and will list out all the gulp tasks found within the gulpfile.js file. If the front end devs have organised the tasks into separate files, as long as the gulpfile.js file in the root of the project has some way of referencing them, they will still show up.

If you don't see any of the tasks, and have only just added the file or a task to the file. You may need to click the refresh button.

To run a task, simply right click it and then choose Run.

Automating on build

Being able to run a gulp task is handy, but what we're really after is for it to be automated as part of the build.

For this we just need to right click the task to be run, and then from the bindings option, select before build.

This will add a comment to the top of the gulpfile.js which Visual Studio will look for to know what task should be run before a build.

1/// <binding BeforeBuild='min' />

With this set, the back end devs no longer need to be concerned with not having any compiled css and js, and with a small amount of knowledge also have the ability to make minor changes to css and js where needed.

Some others tips

Depending on your front end devs setup there could be some additional challenges to overcome.

Front end devs not using Visual Studio

Quite often Visual Studio isn't the choice of dev environment for a front end dev. One issue this can lead to is files missing from the Visual Studio solution. However an easy fix for this is to use wild cards in the csproj file.

If the front end devs code can be grouped into specific folders then use a wild card to include all the files from that folder in the project.

1<None Include="build\js\**\*.js" />

CSS/JS not in the web project

If the front end devs have a separate folder for there work. e.g. they might work with static html files. Then the code may not be in the project what will be run, and therefore nothing will trigger the gulp file to have it's task run.

A simple solution for this is to create a visual studio project for the folder with there work so that it has a build event to be attached to. Make sure your web project also references this project to trigger it to be built when the web project is.

Links

For more info on using Gulp with Visual Studio. Check out Microsofts guide on using Gulp with ASP.NET Core.

Using Visual Studio with Git Hub

This is one of those great examples of writing a blog post to yourself to remind you how to do something.

If your using Visual Studio 2012 then to add Git support you will need the Visual Studio Tools for Git plugin created by Microsoft's TFS Power Tools Team (http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c), if your using a later version of Visual Studio then it's already built in.

If you're thinking in of using Git Hub as your source control provider then the most basic thing you're going to need to know is how do you get the Git plugin to link up to GitHub. Here's a couple of different methods;

Creating a Project in Git Hub

Click New Repository. Enter a new, Select Public or Private and click Create new Repository.

A new repository will be created in Git Hub

Clone the Project in Visual Studio

Now the project has been created in Git Hub you will need to clone it to your machine so that you can start adding files and sync then back.

Open a new instance of Visual Studio and do the following:

  1. Open the Team Explorer window
  2. Click the connect button
  3. In the list of Local Git Repositories click clone
  4. In the URL box enter the HTTP URL from Git Hub
  5. The second box should auto populate with a location on your hard disk
  6. Click Clone

Creating a Repository on Git Hub using the Git Hub app

Rather than creating the Git Hub repo through the GitHub website you can use their app. Once you've got the app installed and logged in do the following:

  1. Select the GitHub account you want to add the repo to on the left
  2. Click Create button at the top
  3. Enter a name and click create
  4. The repository will be created in GitHub and automatically sync with the folder on your machine

Adding an existing Repository to Visual Studio

If you already have a repository cloned on your machine but it's not showing in Team Explorer you can add it by clicking on Add

  1. Click the Connect button to view the list of local repositories
  2. Click add an enter the path to the repository on your hard drive
  3. Click Add