Visual Studio extensions you should(n’t) be using

In this article, we’ll talk about some of the extensions I use in Visual Studio. I do not consider this piece very technical, however I assume it might be interesting for some of you.

But…why the title?
Figure 1
Figure 1

I get it, you don’t understand the title. But let me explain. The very reason I used the negative, was to say one thing which applies to all extensions. They are going to be performance hogs. Regardless of whether we are talking about an extension as huge as ReSharper or one as small as WakaTime, the drawbacks will always exist.

Now let’s get to the extensions.

WakaTime

The companion extension to the famous web app. With a simple installation, prompting only for your account API key, this small service running it the background of Visual Studio allows me track how much time I code. It also gathers information about the time spent working on a specific project and how long I have been coding in a given language. Later I can compare my results with fellow developers from all over the world. According to their website, this extension supports 43 IDEs and editors, so you can continue tracking your progress even when working in other editors.

WakaTime Dashboard
Figure 2: WakaTime Dashboard

Price: free, more features for $9/month

Website: https://wakatime.com/

VS Gallery: https://marketplace.visualstudio.com/items?itemName=WakaTime.WakaTimehttps://wakatime.com/

Markdown Editor

This is one extension I like to use mainly for aesthetic reasons. It doesn’t really bring much to the table in terms of development, but it is nice to see my Markdown file in a more graphical manner. It is also a good way to make sure I am writing valid Markdown.

Markdown Editor
Figure 3: Markdown Editor

Price: free

Source: https://github.com/madskristensen/MarkdownEditor

VS Gallery: https://marketplace.visualstudio.com/items?itemName=MadsKristensen.MarkdownEditor

ReSharper

I saved the most famous extension for last. Almost everybody in the C# industry has either used or heard about ReSharper – a tool developed by JetBrains, the guys and gals behind IntelliJ. It offers a completely revamped key scheme with a handful of shortcuts designed to speed up one’s workflow. Something I really love is refactoring automation. It constantly checks my project for redundant code or convention irregularities. Apart from that, it allows for easier navigation in my project.

Unreachable code
Figure 4: Unreachable code of an if-else statement

However, it is one of the biggest extensions out there and often crashes when working on large projects. This extension also supports C++ development in Visual Studio.

Price: $299 for the first year

Website: https://www.jetbrains.com/

Extension link: https://www.jetbrains.com/resharper/

Sources

Figure 1: https://media.makeameme.org/created/yesyes-i-dont.jpg

Figure 2: https://wakatime.gallerycdn.vsassets.io/extensions/wakatime/wakatime/8.0.6/1484615403449/149763/1/ScreenShot-2014-10-29.png

Figure 4: ReSharper website

Getting rid of weird HTML indentation in Visual Studio Code

When editing HTML files in Visual Studio Code I have always been driven away by the weird auto-indentation when typing out closing tags. Since I am used to writing opening and closing tags before adding any further child elements, I have refrained from using VS Code for this purpose.

In the latest versions there seems to be certain improvement, though it still isn’t perfect. Therefore I decided to dig into the topic a little more and believe I found a solution to satisfy one’s needs. We shall achieve this by adding a simple line of JSON into user settings within Visual Studio.

How…?

We’ll start off by launching a new instance of Visual Studio and opening an HTML file. When adding some content as described above, we end up with something like this.

How I don't like it
How I don’t like it!

You can clearly see that the body tag is indented to the right when it shouldn’t be.   Though this might be a thing of personal preference I wanted to help those, who are feeling the same as me.

The workaround here is rather simple. Just bring up Command Palette using the Control + P (on Windows) or Command + P (on macOS) key combo and search for “user settings”. Another approach is to hit Control + , (on Windows) or Command + , (on macOS). This will open two JSON files. The one on the right will be empty. Here we will set the editor.formatOnSave setting to true. So make your file look like this.

Format on save
Format on save

Now you can go back to your HTML file and hit save. VS Code will automatically format the file as to your desire.

Edited file
Edited file

Custom TextBox in WinForms

Just recently I had to deal with WinForms for the first time in a long while and I stumbled upon an interesting thought. How would I go about making a custom WinForms TextBox with some kind of ‘uncommon behaviour’? I dug deeper into this subject, did some research on it and I think I have come up with something that is worth sharing.

Little intro

As far as simple WinForms projects are concerned, customising behaviour of their controls can be done easily. However, if your project requires some TextBoxes to work traditionally and others to have been inbuilt with some validation logic, I suggest you follow the steps described in this piece.

I am going to demonstrate this on a project, where every a’ entered into a text box will become a ‘b’.

Let’s roll

To kick things off, create a WinForms project and name it whatever you want (I named mine CustomWinFormsTextBox).

Create new project
Create new project

Then right-click your project in the Solution Explorer and add a new class. I have chosen CustomTextBox as it’s name.

Set the class name
Set the class name

After the class is successfully created, make it a child of TextBox. Then in order to add the described behaviour, override the OnKeyPress method of the TextBox class. This method is called everytime we press a key on the keyboard while the TextBox is focused.

Edit OnKeyPress method
Edit OnKeyPress method

We are essentially checking if an ‘a’ has been pressed, in which case we would replace it with a ‘b’, that would then get displayed in the text box.

Now all that’s left to do is to add our CustomTextBox to the Toolbox window so that we can drag-and-drop it onto our form. The Toolbox won’t offer you custom control just yet. First you have to build your solution. Then if you search for CustomTextBox you should see it appear in the search results.

Search Results
Search Results

Now just simply drag and drop it onto the form, save your project and hit Start. If you try to enter ‘maniac’, the text box will show ‘mbnibc’.

Place CustomTextBox and Start the app
Place CustomTextBox and Start the app

Although I know this won’t come to good use to everyone, I still think it is worth knowing about it.

Adding Visual Studio Code to PATH

In connection with the last article regarding the basic concepts of working with ASP.NET Core MVC, I came up with a little tweak to speed up your development by at least a small margin. To make things clear enough I won’t go into much technical detail.

Consider the situation in which we were last time. We successfully created a new project and went ahead to open it in Visual Studio Code. What we did and always can do is to launch a new instance of Code and open the project folder by navigating to it in the Finder dialog window. While this approach works, I will show you a quicker way to do it.

Setup

Essentially, all that is needed to be done is to invoke a command that will do all the work for us.

  1. Launch Visual Studio
  2. Press Command + ShiftP, which will bring up the Command Palette.
  3. Enter “shell”.

    Command Palette within Visual Studio Code
    Command Palette within Visual Studio Code
  4. You should be presented with two results, one of them being “Shell Command: Install “code” command in PATH”. Click on this option and wait until the operation has completed. This usually takes no more that a second.

All is now setup. Let’s head to the usage!

Usage

So far, all seems a little easy, doesn’t it? Well…this part will be of no exception. Simply navigate to your project folder in a Terminal window and enter code . . This will instantly open a new Visual Studio Code instance with the project loaded. No further hassle.

This tweak helped me and I hope it will make your workflow a bit snappier, as well.

Working with ASP.NET Core MVC on macOS

For this article I decided that it would be appropriate to show off the process of installing and creating an ASP.NET Core MVC project on macOS. Also I will explain what you have to do differently when creating a web project instead of a console application.

Installation process

Microsoft’s ASP.NET Core website explains the installation part thoroughly. Nevertheless, here I prepared a short summary of what you have to perform prior to running the project.

  • Install Homebrew (if not already present on your machine)
  • Follow steps 1 and 2 as described on Microsoft’s .NET Core website
  • Enter the first two commands of step 3
    1. mkdir <dirName> – creates a new directory with a name of <dirName>
    2. cd <dirName> – mounts the <dirName> directory

Now since this article is about ASP.NET Core MVC you shall not follow the whole third step, because it advises to use dotnet new. This would, by default, create a .NET Core Hello World console application and it’s respective project structure. Instead, enter  dotnet new -t web into the Terminal window.

Terminal window with a command to create ASP.NET Core MVC project
Terminal window with command to create new ASP.NET Core MVC project

After the command is executed you may proceed to step 4  ( dotnet restore — which will restore NuGet packages for the project and ensure that installed packages and it’s versions comply to those of the project.json file int the root folder — and dotnet run which will start serving the project under http://localhost:5000).

Testing YOUR Project

If you now navigate to the above-mentioned localhost URL in your browser, you are presented with a default ASP.NET page known for many years as part of ASP.NET MVC.

Working with the project

At this point you can edit each file of your project as you like. When the page gets refreshed, all changes will be applied instantly — without the need to run  dotnet run in your Terminal window — and seen in your browser window.

I myself have struggled to create web application instead of a console application when it came to .NET Core CLI. Now I hope the process has been properly explained. However, if you ever get lost, feel free to use the dotnet --help  command. From there you will sure get to the bottom of your problem.

Ultimate casting showdown: is vs. as

I know that many C# developers scratch their heads all the time, wondering how casting in really works and where lies the difference between the is and as keywords in C#.

Let’s dive in

To make this article easy to understand I won’t go into much detail.

For illustration purposes, imagine we have two classes – Car and Student. Obviously, these two classes do not belong to the same inheritance tree. All they have in common is that they both derive from System.Object. This piece of will be common for all upcoming examples.

Explicit casting

Now that we have declared the two objects, we can perform a casting operation. We will assign the student object to the car object. Unfortunately, this will fail. Using explicit casting, we will be informed about such problem by an InvalidCastException, which means the remaining Console.WriteLine statement won’t be executed.

As

If casting is valid, the car object will be assigned the value of the student object. Otherwise, it will have the value of null.

When using the as keyword, checks against the null value have to be carried out. This is done within the if statement. If all goes well, we should see “All went good” printed to the console.

Is

As far as the is keyword is concerned, we have a pretty straightforward and type-safe approach to deal with casting.

Within an if statement we simply check if the cast would be valid. Following this check, we can proceed to explicit conversion, a.k.a. explicit cast.

This method, however, is quite inefficient, because at first we check the types and then carry out the cast. It’s true in situations when we know the cast will go through.

ProjectToReadme: simply a time-saver

I think the time has come to get you equipped with some tools, which will make publishing .NET Core apps a seamless experience. As the heading implies, ProjectToReadme will get it’s honourable mention today.

Brief introduction

ProjectToReadme allows you to generate simple yet complete README files which you can later insert in your GitHub repository or anywhere else.

WHY?

I think many of us are sometimes too tired or too discouraged to make a README file after finishing a project. We all want to publish it ASAP. And that’s when this program comes into play.

How?Question mark

This tool is a simple CLI interface, with a few neat features. As the GitHub page says itself, there are three options to be set upon each README generation. Using the -s or -S modifiers, you tell the program where to find your project.json file. The -f or -F set the output format, such as Markdown, HTML or plain text. The last option, -t or -T, specifies whether the end result will be saved as a README.md(html, txt) file or outputted directly to the console.

You’ve got to give me some of that!

If you want to give ProjectToReadme a go, you may do so here. To get more information about it, please visit the GitHub repository.

Expression bodied properties in C#

Today I would like to introduce you to an often disregarded feature of C# 6.0. As you might already know from the title, it will be about expression bodied properties.

Although, this revamped property initialization syntax has been around for 2 years, I see many developers still not making use of it.

Advantages of using expression bodied properties
Space consumption

I understand the competition for an additional kilobyte of memory is not really a thing nowadays, but when putting this feature in use, your source files will get smaller.

Readablity

Since the body of your property is much more minimalistic, others might find it easier to get around in you code.

Example time!

I think a perfect example to demonstrate the use of expression bodied properties is the implementation of read-only properties.

We defined a private field _version , which is set to a version string within the SetVersion()  method. At the bottom, we have a Version property, which has a getter to return the version string. Very simple code…but could be even simpler.

This old way of getting stuff done can be replaced with this revamped code snippet.

It doesn’t really matter which way you choose. But sometimes there is no need to define a setter method in the body of a property. In such situations, the new syntax might come in handy.

C# 7.0: Tuples

Microsoft has recently unveiled some changes, that developers will be introduced to in the future release of C#, the C# 7.0.

Among all developers who see sharp 😀 , there is an enormous amount of anticipation of the features in the final release. In the meantime, I decided to interpret you one of them today. So let’s dive into it!

Tuples, I'm ready!
[1]: Tuples, I’m ready!
Tuples

One of those things, that may please current developers and possibly attract new ones, are tuples. Tuples or tuple-like syntax can be found in many languages.

The universe before C# 7.0

In previous versions of C#, it could have been achieved this way using the out keyword when passing variables as parameters to a method:

This keyword allowed multiple values to be “returned” by the method. I am using apostrophes, because it is not really a tuple case-in-point and the GetTwoValues doesn’t really return any value, as well.

Getting closer…

This example in Python shows tuples the way they are commonly understood.

The example here is pretty straightforward and easy to understand. I personally haven’t been in a position wanting to return two or more values within a method, but is sure a step forward in the versatility of the C# language.

C# 7.0 at last

Let’s finally examine how tuples will look like in C# 7.0.

This sample works the same as the other one with out keywords shown earlier in the article. We get the values as elements in a tuple, store them into a variable of unknown type and then print them to the console. Each value is stored in the resulting container as an element called Item1 (Item2, Item3 and so on).

Item1 and Item2 is not overly descriptive. To avoid this woe, we can make use of named tuple elements. Let’s edit our code a bit.

The only, but important, change here is the switch from Item1 and Item2 to First and Second. Hence, making our code far more readible.

What do you think about C# 7.0 and tuples? Leave a comment down below.

Source: MSDN

Exceptions in C#

Imagine you are building a JSON parsing library in C# and the program crashes. You don’t want the user end up having no JSON file parsed and not knowing, what went wrong.

Confused
Figure 1: source

You are not that kind of a developer, are you?

Developer
Figure 2: source
So what are exceptions?

Exception is an event, that stops the execution of the program, due to some behavior, that you, as the programmer, cannot expect. In C#, all types of exceptions derive from the base Exception class in the System namespace.

Consider the following Console Application.

This for loop works well until the point, where the index reaches 4. At this point in time, the index would point to the 5th element in the array (since arrays start at index 0). But there are only 4 elements! This causes the .NET runtime to throw an IndexOutOfRangeException. When debugging the code in Visual Studio, this particular exception looks like this.

You’ve probably already met numerous third-party libraries (either as a developer or end-user), that use custom exceptions, but you never noticed. That is because there was no invalid operation to the program, which would cause the exception to be thrown. If there was and you would want the user to be informed pleasantly, you would have to use .NET exception handling.

.NET exception handling

In C#, the three most used keywords that enable this techique are  throw , try and  catch . They allow you to prevent an exception from completely stopping the program execution and leaving the user wondering, what happened.

For an unexpected behavior to be properly handled, it has to be caught (therefore the catch keyword).

To demonstrate this behavior, I will expand on the previous example. Consider this code.

The whole little “program” we made is inside the try block. Each time the for loop is successfully looped through, the number is written to the console. Then when the program gets to the critical index (see the example application description from So what are exceptions? paragraph for explanation), the catch block is executed. In this example, it would only get executed, when there was an IndexOutOfRangeException thrown. If there was a larger piece of code in the try block and it threw a FileNotFoundException, the program would crash just as any other program without exception handling.

Defining custom exceptions

When you are designing your own CLI compliant library, you can define you own set of exceptions, that best describe what went wrong.

When defining your own exceptions, they have to be placed into a class that inherits from System.Exception (this base class defines three constructors – a default constructor and two custom ones). They can all be created in your custom exception class, but have to call the respective base constructor.

Note: Exception classes should define as many constructors as possible.

An example would look like this.

When throwing CustomException somewhere in the code, you would do  throw new CustomException("Something doesn't work"); .