Using C# 6 in ASP.NET 5

Introduction and Background

Previously on my blog, I had talked about the new features of C# 6, I discussed many things about those features as well as I talked about whether those features are “actually” new of just sugar coats. Anyways, no disrespect to the hard work team had put forth in implementing those features and I personally like most of those features. For those of you who are interested in reading that post of mine, please redirect here: Experimenting with C# 6’s new features. I hope you will like the post and consider it to be worth sharing.

In this post, I am going to talk about using those features in ASP.NET 5! I think, this would be my last post about ASP.NET 5, because later I would be talking about ASP.NET Core 1.0 which was introduced as the new name for the technologies from now on. Anyways, until then I am going to use ASP.NET 5 terminology and I will explain how you can use C# 6 features in your ASP.NET 5 applications, to make the processes even better, performance efficient and more readable if you are a team of programmers working together to bring a major project.

So basically, what you are going to learn in this post is:

  1. ASP.NET 5: Not very basics, but enough to allow beginners to understand.
  2. C# 6 features: They have already been discussed, so please read the previous post.
  3. How to improve performance of your web application!

This is another major post of mine, comprising of both ASP.NET and C# topics. Typically, I will use ASP.NET more than I am going to talk about C# itself so that web developers can gain some benefit from this post of mine. So let’s get started…

Using C# 6 features in ASP.NET

What we have in ASP.NET is just a framework used for building web applications. C# is just the language, that we can use to program the applications. However, the smoother, efficient and efficient the programs there would be, the better your web applications would perform. C# 6 is the latest version of C# programming language and would definitely use Roslyn compiler. You can use this language in your previous versions of ASP.NET, like ASP.NET 4.5. But for the sake of this post, I am going to use ASP.NET 5!

ASP.NET 5 itself is very fine tuned… But using the power of C# 6, you can make it even better. In this post, I am going to show you a few methods that you can use C# 6 in. I will start in the similar manner that we had previously (in the previous post) and I will explain the code usage in the terms of ASP.NET web application development scenarios, instead of simple C# programming.

String interpolation

Personally, I am a huge fan of this feature because I have waited for this feature for a very long time. I have always been using string.Format function or StringBuilder objects to generate the strings, but using this feature I can easily write the messages that I want to write…

Now, when you are going to write the strings using dynamic data from the users. I would recommend that you write them using the string interpolation. Like this,

var message = $"Hello {Username}, you have {count} unread messages.";

// Then you can use this value in views, or back-end model management, or in HTML
<p>@message</p>

This way, you won’t have to generate the string representations using concatenations, or to create the string builders. I have already demonstrated that this method is similar to what we had as String.Format() function! Only that this method is much better. A real world example of this usage is, that ASP.NET provides interfaces that you can use to trigger SMS and Email notifications. While previously you had to write the following code:

var message = string.Format("Hello, {0}! Use {1} as your code to activate the service.", username, token);

// Send the code through SMS or email services

Basically, that is a good approach, mostly developers use concatenation. Which is a really very bad approach to build strings. Instead now you can do the following:

var message = $"Hello {username}! Use {token} as your code to activate the service";

This is a really very short way of building the strings, and guess what? They always translate down to string.Format function calls. :-)

Conditional try…catch

Now, I have been mostly watching the source codes of programmers to be like:

try {
   // Code that may raise exception.
} catch (Exception er) {
   if(er is NullReferenceException) {
      // Log this null error
   } else {
      // Chain the exceptions or just leave...
   }
}

What this is, that it would always enter the catch block. Then, inside that block you would be checking the condition that you want to check. So, in C# 6, you can make it even more readable. You can change that code to be like this:

try {
   // Code that may raise exception.
} catch (Exception e) when (e is NullReferenceException) {
   // Execute this block in case the error was "null" reference.
} catch (Exception e) when (e is UnauthorizedAccessException) {
   // Execute this in case the exception was this one..
}

// You can chain the exception conditions...

This way, you can allow the exception to propagate back if you are not interested in logging the error on your end. The condition would be checked against, and then it would continue to next statement if the condition is not met.

nameof operator

In ASP.NET environment, I think this variable would have the most use! How? Most of the times, developers have to “guess” the variable and then write its own “hardcoded” name. For example like this,

string name = null;

// Now when you will call any function on name, 
// it would raise exception. Like:
int length = name.Length;

// Before C# 6, you would do:
// inside catch block 
var message = "Sorry, name was null.";

That is OK! There is no problem with this one… But, what if you later refactor your code and change the name of that variable? Even if the changes are not going to be reflected on the production environment, you are still going to use the details on your development environment. So what you would have to do is that you would have to change these string literals too, just to depict the changes in the system.

Well, C# 6 got you covered for that. You can now know which variable was the problem in your code.

string name = null;

int length = name.Length;

var message = $"Sorry, {nameof(name)} is null.";

That is same to what we had previously, but what is difference? The difference is that now you will be able to refactor the variable. By refactoring, previously, you would have to edit the strings too, instead in this method, while refactoring the variable names would be updated throughout and nameof() operator would return the “current” name of that variable! Also, if you were making a model and then rendering it…

class Model {
   public string Name { get; set; }
   public string Email { get; set; }
}

// You could do this:
var message = $"{nameof(Email)}: {Name}, {nameof(Email)}: {Email}";

Fully using the power of C# 6!

Null conditional operator

What I have seen in most of the cases, in my experience is that beginners typically get stuck at “NullReferenceException”! Anyways, what I think is that this error is very helpful in many cases and I suggest that you become a friend with this error, as it can be really very helpful in many cases. (Which cases? That requires a separate article post!)

You can then basically minimize the error if the error is to be null reference object. To do that you just append “?” to the variable name, and if that object is null at the time of execution, C# won’t throw an exception instead it would store null in turn.

string message = null;

var length = message?.Length;

In the previous case, it would throw an exception. However, in this case there won’t be any exception. But there is another “exception” to this use. I have already talked about that exception, the thing is… Your “length” variable is now also null, so if you would try to use that variable, it would then raise another error unless you use the same condition to override it.

I recommend that you read the same section in my previous post, and see how this operator “is” useful and how this operator “is not” useful at all.

Auto-properties

In ASP.NET, Models are typically just structures. You don’t have any default value in them, but if you would want to design your structures to hold a default value that you want to display when user is opening the form. You can do so like this:

class SomeForm {
   public string Name { get; set; } = "Your name.";
   public string Email { get; set; } = "youraddress@example.com";
   public string Message { get; set; } = "Enter your message here.";
}

When you would now render these as form elements, you are going to get these by default. You usually enter these in the HTML, hardcoded form. Instead, using this approach you can get a consistent and dissected environment in which you can later focus on the model itself, later.

You can also use the same for getter-only properties. The getter-only (or readonly) fields can also be initialized in the same manner:

public Helpers {
   public static string SMTP { get; } = "smtp.example.com";
}

This would allow you to manage the value in this one line itself, instead of using a constructor to initialize it with a value.

Lambda use in ASP.NET

If not string interpolation, then I am a huge fan of lambda expressions! These expressions come from the realm of functional programming. The benefit of them is that they don’t have any side-effects. By that, I mean that the function is just the evaluation of the values and then the values are returned instead of having a stack created for the function itself.

public int Multiply (int a, int b) { return a * b; }

This can be minimized to the following code,

public int Multiply (int b, int b) => a * b;

There are two benefits to having this.

  1. The code looks more readable.
  2. There is no more stack!
    • The code is evaluated and the value is returned.

So not just this improves the code readability, it also improves the performance of the code! You can try that out, and just to see the working, you should read the previous post.

Another good use of lambdas is in getter-only auto-properties! Old versions of the properties always relied on a backing field. These fields were then called to provide or set the values. However, that caused an extra call to be raised to the backing field. What lambda expressions have is that you can write a field like a  lambda, just as we know that lambda expressions don’t work around with other fields, this way… The lambdas would help us to develop readonly fields in a much better way.

So, for example, if you create a property like this:

public string Name { get; } = "Afzaal Ahmad Zeeshan";

What this is going to do is that it would create a backing field, then this value would be stored to that backing field. In turn, whenever you would call this property, it would then call the backing field to get that value. Another call would be made.

Instead, using lambda expressions you can do this:

public string Name => "Afzaal Ahmad Zeeshan";

What this has as a benefit is that,

  1. Since this is a readonly property:
    • You are not going to update it later.
    • You provide a default value in this.
    • It acts just like a constant field.
    • No overhead calls.
  2. More readable code!

Lambdas not just make your functions better, it also makes your (readonly) properties better! Technically, you can improve the performance of your applications.

Points of Interest

I have not yet covered all of the features that C# 6 introduced, why? Because most of them are not going to be used by “average” developers and only a number of people would be using them. A few of such cases is

  1. Index initialization in the dictionary.
  2. Parameterless constructor of struct type.
  3. So on…

However, this post would help you to understand the use of C# 6 features in ASP.NET web applications. You have already read that not just this improves the syntax, instead it also makes the application perform much better.

I would personally recommend the following uses to be made “must have” in your web applications:

  1. String interpolation
    • Makes your string much more readable.
    • String template can be edited easily.
    • Translates to the better method of generating the strings.
  2. Lambda expressions
    • You have read that lambda expressions make your functions more efficient.
    • The getter-only auto-properties are more like constant fields.
    • Auto-properties are much more readable.

These were a few of the tips that I wanted to give to those ASP.NET web developers who are going to use Roslyn compiler and are going to make use of C# 6 langauge. If you are into C# 6, I “recommend” that you make use of these cool features.

Later, I will share some more of the same tips and recommendations, once I have finished recording them for you. :-)

Programming C# on Mac — One post guide

Introduction and Background

I have dedicated most of my time to C# and C# programmers, I have already written a brief description and guide for C# programmers to be able to port their applications, develop them, build them and install them on Ubuntu… Which indirectly focusses on all of the Linux environments. Basically, C# is a Windows programming language and many frameworks like .NET, Windows Runtime, ASP.NET etc. are all using C# as their “popular” programming language. But developers have also worked very hard to provide a cross-platform support for C# programming language, using Mono you can develop C# applications and build and deploy C# applications on non-Windows environments too. If you are interested in the basic post, please read this post: Using C# for cross-platform development. You will be shown how Mono can help you, how you can build the applications on multiple frameworks and use them on those frameworks, operating systems too, and not just on Windows or .NET framework environments.

In this post, I am going to demonstrate how you can use C# for programming a Mac environment. I have never been a “huge” fan of Apple products, however, since I love C# so I think it should also be promoted on Mac environments and among Mac developers! C# can highly leverage the performance of their applications. If you are interested in using Mono framework, I recommend that you read the guide for C# programming on Ubuntu, the framework and features are similar. However, the installation is somewhat different and that is the topic for my post and I will explain the methods and steps required to install, run and test the Mono project, then I will also show how you can install Xamarin Studio (the IDE for Mono on Mac). So basically, this post is about setting up the environment for C# programming on Mac. I remember, when Siddharth Koya asked me whether I can write a guide for Mac or not, I told him that it would take some time… However, Sid! It is here. You can read this and then continue to read the related Ubuntu guides for Mono programming.

Information about Mono platform

So, before I move further, there are some prerequisites to the platform, too! You need to make sure you are using the correct platform of Mac OS and also that you are having required packages installed. Otherwise, Mono may not work! Mono supports, Mac OS 10.7 and onwards. You must at least have 10.7, otherwise, you should upgrade your systems.

Setting up the environment

The method for installing the Mono on Mac is somewhat different from others, however is also very easy at the same time. You need to have internet connection before you can continue to install the packages. The packages are free for download, install and then use. So basically, all you need to do is, just capture those packages, run and install them and there, you will have C# environment installed on your Mac in no time! First of all, I will show you how to install the packages, starting by showing you the URL address of the website, later I will show you to check if environment is set up or not, later I will show you how to install the IDE for Mono.

Mono is basically a set of compilers, debuggers and assemblies required to compile and build the projects. However, there are some GUI applications which integrate the components and present you with an IDE (Integrated development environment), which can be used to develop and build applications rapidly, without having to execute scripts each time to make your project work, you are provided with a clean and intuitive interface that can be used to create, modify and build the projects. IDEs also allow you to debug the applications in case you want to fine tune them, remove bugs or make them performance efficient.

So basically, what IDEs are meant to do is that they provide you with controls, that you can use to perform your actions that typically are done using scripts.

Downloading and installing the packages

First of all, I will talk about installing the packages and assemblies of Mono project. Now, in Ubuntu we did that using the terminal, in Mac, you are going to download the package itself and then install it using the GUI installer. The process is analogous to what we have on Windows environment, however, there are a few security steps that you would have to undergo before you can install the package itself. So, let’s start with downloading and installing the packages.

You can follow the same URL for Mono Project, and download the packages for Mac instead. Go to Mono Project’s Download web page and download the packages for Mac. If you are on Mac, the website will automatically load the page for Mac.

Screenshot (6191)
Figure 1: Mono downloads for Mac.

Typically, you are going to install using the 32-bit version. However, you can also install the packages for 64-bit environment. It would take some time depending on your network, once that is downloaded. Open it, and it would give you an installer. The installer would lead you through the procedure and you will have your packages installed successfully!

Screenshot (6192)
Figure 2: Package being downloaded.

Once this gets downloaded, open it…

Screenshot (5898)
Figure 3: Mono framework installer.

This installer is actually going to guide you through different steps, that you require to install Mono project on your Mac, however just for the sake of formality I am going to describe these stages. Once you click continue and move forward a bit, you will be shown the license information about the product. You “should” read the license terms before you click “I Agree”. Even though the license and product are free, you should know how much freedom you actually have. So, read the license and then continue.

Screenshot (5899)
Figure 4: Must read the license terms before you continue and click Agree. 

Continue to the next steps now. Once you have entered the details for disk usage, drive selection and others, you will be asked for security check, your password! Enter the password and continue with installation of the package.

Screenshot (5901)
Figure 5: Security check before installation.

You will then continue to install the package. The installation process would take some time, and after a while it would show you a success message. This message tells that the package has been indeed installed.

Screenshot (5902)
Figure 6: Mono framework is installed.

Although the packages have been installed. But, I would “recommend” that you test the packages and the framework itself. So, in the next section I am going to show you how to test if everything is OK!

Simple hello world!

In this section, I am going to show you a simple hello world program, using which you can determine if framework is installed correctly, or if there were some troubles during your installation process. You are all already very much aware and familiar with the hello world programs, so basically I am going to use that one program and I am going to demonstrate how you can test the C# environment easily, using the terminal.

Remember: Without IDE, you are going to use terminal, so I would recommend that you go and learn terminal scripting. Otherwise, just follow the scripts I share and then install Xamarin Studio if you don’t feel easy with terminal.

Anyways, you would require to create a new file… What I do is that I try to create a separate folder for each new project, you should do the same. Create a new folder, anywhere, (I chose desktop) and then create a new file in it, name it “Program.cs”. To do so, you would use the following shell script. Uh huh, before you write the code, open the terminal… For most of Apple users, it is found under Utilities in Application tab.

Screenshot (6194)
Figure 7: Terminal program in the Utilities tab.

Once you have opened the terminal, go to the location where your folder is created. Currently, it would be like this:

Screenshot (6193)
Figure 8: Program directory empty at the moment.

Initially the directory is empty, so we would create the file here. In that directory, create a new file, I used the following shell script to create a new file:

echo "" > Program.cs

This would create a new file, named Program.cs in your currently active directory (make sure it is the directory that you want!), the file would be created. Have a look below:

Screenshot (6195)
Figure 9: Shell script for pwd; “present working directory”.

Just to ensure that we are on the right directory. Later, enter that shell script to create the file. Shell won’t tell you what happened, it would just create the file there.

Screenshot (6196)
Figure 10: Shell.

As already mentioned, Shell didn’t reply or show a message. It just executed that statement, command or what-ever you want to call it.

Screenshot (6197)
Figure 11: Directory, file and the shell visible. A new file “Program.cs” created in the directory.

All three of our items are visible here! Our file has been created and we can now edit the file to write a C# program.

using System;

namespace Text {
   class Program {
      public static void Main(string[] args) {
         Console.WriteLine(25);
      }
   }
}

Sadly, Mac wouldn’t allow me to use double quotation marks and would turn them into something else, generating a compiler error. That is why I had to use an integer value and not a string message. However, to compile this program… Go to your directory, open up terminal, enter the following commands:

mcs Program.cs
mono Program.exe

These are the commands to compile and execute the programs.

  1. mcs Program.cs
    • This command would compile and build the program. Generating the executables in the same directory.
    • mcs == Mono C Sharp compiler.
  2. mono Program.exe
    • mcs would generate the executable (.exe) in the same directory, and this command would execute it under mono runtime!

The output would also be shown right under the command itself, in the terminal.

Screenshot (6199)
Figure 12: Program and build output shown.

You can see the program output and build output! Program output is shown in the terminal, where as build output is shown in the directory. However, this shows that our environment is set up and that we can continue to install other stuff, or use this and start building our C# projects to run on Mac itself.

Installing IDE

I don’t recommend going terminal. IDE is a great tool, that can help you in many things…

  1. Syntax highlighting: You can see in the code above, it is hard to see what is going on, unless you are experienced.
  2. Code suggestions.
  3. Keyboard shortcut to compile, build and debug.
  4. Debuggers and breakpoints.
  5. Integrated environment.
  6. Configurations for project files and output directories.

Much more! So I would recommend that you start by installing an IDE on your machine, instead of doing all this yourself by a terminal. Which takes a lot of time, I would say.

The IDE for Mac is different from what we had in Ubuntu, in Ubuntu we had MonoDevelop, however on Mac we have Xamarin Studio. They are both provided by Mono Project (which is led by Xamarin). You will now need to download Xamarin Studio from their download web page, download the package for Mac and install it.

It would start and Mac would try to run a security check and other package checks,

Screenshot (5931)
Figure 13: Verification of the Xamarin Studio package.

This would take a while, let it take a while. Later, you know what to do! Drag and drop the application to install it.

Screenshot (5932)
Figure 14: Drag and drop the Xamarin Studio to install.

Drag and drop it in Applications, it would copy the files and then your IDE would be installed for you on your machine.

Screenshot (5936)
Figure 15: Xamarin Studio installed on Mac.

Click on it to start it! Mac would attempt to tell you that this application was downloaded from Internet and that you should not trust everyone on internet, just continue to the next step.

Screenshot (5937)
Figure 16: Security warning by Mac.

Open it and then you would have your IDE active in front of you!

Screenshot (5939)
Figure 17: Xamarin Studio active window.

You can now create a new project, and then continue to use the Mono Project in your environment to create applications in C#!

Points of Interest

This is a very short post about Programming C# on Mac, which covers the required topics about setting up the environment for C# programming on Mac, however to continue learning more about Mono Project, what it offers you, how you can program C# on other platforms, I recommend that you check out my previous posts about “Programming C# on Ubuntu”! I am sure you are going to enjoy those posts, if you like C#.

Programming C# on Linux or Mac is similar to using C# on Windows platform like .NET or Windows Runtime. Mono Project brings the same efficiency, same flexibility and same power to other platforms too, so that you can build your C# programs on Mac and Linux too. However, remember, that the programs built using Mono are executed on “mono” environment, or “mono runtime”. Mono runtime would be required before you can execute those applications, because Mono runtime provides the underlying foundation for this cross-platform support. Without this, you won’t be able to execute the programs, which is similar to installing .NET framework on Windows!

Anyways, this was to help you get started in Mac too, now you can check out the rest of posts! Hope to see you there too. :-)

Experimenting with C# 6’s new features

Introduction and Background

It has been a very long time, and trust me, I am fed up of “Cool new features of C# 6!” posts already. I mean, each post has the same things, same topics, same content and (usually!) the same code blocks to demonstrate the thing too. However, I never wanted to write the blog to describe the new things in C#, but now I think I should explain the things that are done “under the hood” for the C# 6’s code. I have been going through many posts and I already know what these new “cool” features are, so I just wanted to test them out and see when they work, how they work and when they are not going to work. Well definitely, that is something that people aren’t expecting by C# architect team, however, let’s find them out. :-)

Also, it has already been very late for C# 6 to be discussed because C# 7 has already been into the discussions of the team, you may want to read more about what C# 7 team has on their list. C# 7 Work List of Features.

Anyways, none of them are the final versions, final statements, or “C# 7 must-haves”. They are just what they are trying to inject to C# as per the demand and ideas provided to them on GitHub and other networks that they are having.

Enough of C# 7 already, now you have already seen all of the features, that were introduced in C# 6 and most of you have been using those features in your applications. But, did you try to use them in a way they were not intended to be used? I mean, have you tried to use them in a very “unknown” or “uncertain” manner?

Let me share, what I think of those features. I would also love to hear what you think of them! :-)

Counting the features of C# 6

Now let me show you a few things about these services, in a way that you were not expecting or you never cared about! These features are definitely interesting, but, a few are useful in one way, and a few are not at all useful in one way. Depends on your project, your perspective and ideas. So let me start by the very famous (and my favorite C# 6) feature: String Interpolation.

String interpolation

This feature is a great feature, personally saying, this is the best feature that I find on C# 6 features list. What I find easy while using “string interpolation” is, that I don’t have to use String.Format, I don’t have to concatenate the strings, I don’t have to use the StringBuilder at all. What I can do is that I can just simply write the string and it would include the variable data in the string. Now let me show you an example of multiple methods that can be used.

// Creating the private field
private static string Name = "Afzaal Ahmad Zeeshan";

// Then inside the Main function.

// 1. Using string concatenation.
Console.WriteLine("Hello, my name is: " + Name);

// 2. Using string format
Console.WriteLine(string.Format("Hello, my name is: {0}", Name));

// 3. Using string builders
StringBuilder builder = new StringBuilder();
builder.Append("Hello, my name is: ");
builder.Append(Name);
Console.WriteLine(builder.ToString());

Technically, their result is same. They all say the same message, and how they do it, we can find that out using the Assembly language (or the MSIL code, if you are fan of MSIL and not Assembly at the debug time), however, we do know that they present the same value on screen.

Screenshot (5950)
Figure 1: Same string rendered and generated, as a result of many ways.

Their IL benchmark would be different (because internally they are three different ways). That is because, they themselves are different. Their IL generated would be like this:

IL_0000: nop 
IL_0001: ldstr "Hello, my name is: "
IL_0006: ldsfld UserQuery.Name
IL_000B: call System.String.Concat
IL_0010: call System.Console.WriteLine
IL_0015: nop 

IL_0016: ldstr "Hello, my name is: {0}"
IL_001B: ldsfld UserQuery.Name
IL_0020: call System.String.Format
IL_0025: call System.Console.WriteLine
IL_002A: nop 

IL_002B: newobj System.Text.StringBuilder..ctor
IL_0030: stloc.0 // builder
IL_0031: ldloc.0 // builder
IL_0032: ldstr "Hello, my name is: "
IL_0037: callvirt System.Text.StringBuilder.Append
IL_003C: pop 
IL_003D: ldloc.0 // builder
IL_003E: ldsfld UserQuery.Name
IL_0043: callvirt System.Text.StringBuilder.Append
IL_0048: pop 
IL_0049: ldloc.0 // builder
IL_004A: callvirt System.Object.ToString
IL_004F: call System.Console.WriteLine
IL_0054: nop 

IL_0055: ret

You can see, that (indirectly) they are all different and execute different functions. What happens, is a “syntactic sugar“. They are typically just functions that are executed and compiler allows you to write all of these simply.

Now coming to the new way of writing the strings with variable content. C# 6 introduces this new way of writing the same message!

Console.WriteLine($"Hello, my name is: {Name}");

/* Output:
 * Hello, my name is: Afzaal Ahmad Zeeshan
 */

The output of this is also same… But, how does C# 6 does that is a bit of trick now. To find that part out, we will again go back and read the MSIL generated.

IL_0000: nop 
IL_0001: ldstr "Hello, my name is: {0}"
IL_0006: ldsfld UserQuery.Name
IL_000B: call System.String.Format
IL_0010: call System.Console.WriteLine
IL_0015: nop 
IL_0016: ret

Um, watching at this MSIL, what do you say? :-) If you pay attention to the highlighted code, this resembles to the code that we wrote using the String.Format() method. So what happens is, that this is also a syntactic sugar. There is no addition of anything, it is just what compiler does for you! Compiler simply takes away everything, and generates that previous version of code. Yet, in a very friendly and simple way. I like it.

Remarks and References:

String interpolation has been adopted by many programming languages by now. Swift by Apple and JavaScript (ECMAScript) is also moving forward to templated strings. I personally feel, since string type data is mostly used, this is a great feature. For more, please read:

  1. String class
  2. String.Format()
  3. String interpolation

Conditional try…catch

Now, I have never used VB.NET, because I was always busy in C# itself but I still listen that VB.NET had this feature way before C# implemented it. The conditional try…catch (or as the team calls them, “Exception filters“) just allows you to handle the exception when a condition is met, I am not going to talk about what they are, instead, I will talk about how you can use them in your code. So basically, if you execute a function that is supposed to have a side-effect, and before handling any further errors, you want to find out if there was a side-effect or did the error occur before the side-effect. You would possibly be left with only one way to check that out!

try {
   // Some code that breaks the execution.
} catch (MyException me) {
   // Just a function to check if value was updated
   if(field.Updated()) {
      // Log the error and then re throw the exception
   }
} catch (Exception e) {
   // Re-perform the same for other exceptions.
}

As an example of this case, have a look at the following code:

private int field = 25;

public static void Main(string[] args)
{
    try {
        Console.WriteLine("Do you want to change the field?");
        if(Console.ReadLine() == "yes") { field = 34; }
 
        // Just throw the exception
        throw new Exception();
    } catch {
        if(fieldModified()) {
           // Log error, it was thrown after modifying the field. 
        }
        // Other code...
    }
}

public static bool fieldModified() {
   return (field == 25) ? true : false;
}

This try catch would allow us to check if our fields were modified, if not, then we can simply ignore as there were no side-effects.

Now what C# 6 allows you to do is to add a condition outside the block, so that you don’t even have to enter the block itself, and the condition would just check if it needs to go to this block, if not, then exception would continue to grow and later catch blocks would try their luck, finally to the end. Something like this.

try {
    Console.WriteLine("Do you want to change the field?");
    if(Console.ReadLine() == "yes") { field = 34; }
 
    // Just throw the exception
    throw new Exception();
} catch when (fieldModified()) {
    // Log the errors, reverse the transaction etc. 
}

So instead of writing that condition inside, we can write that condition in front of that catch block itself. Technically, both were OK, only this way we are leaving most of the work to compiler and we are designing the code to be more readable, read it like “try .. this code .. catch when field modified .. continue“. This provides you with a simple way of reading the code. The IL get some branches around the catch block so that code can jump from one location to another and so on.

Remarks and references:

Technically, I won’t use this in any of my applications because I try to avoid transaction-like programming. But, if you are using a transaction-like programming, such as SQL queries, bank management systems. I would recommend that you use these conditions on your catches. They can be of great use when you are logging errors in transactions. The function used would determine if there were changes (or what-ever you want to do in that function!) and if that condition is true, error would be caught, logged (if code is provided) and then re-thrown (if code is provided).

For more:

  1. C# : How C# 6.0 Simplifies, Clarifies and Condenses Your Code

nameof operator

Before saying at all, I want to confess that I have been one of those responders, who said, you cannot have the name of the variable! Compiler doesn’t know the name of the variables, they are just labels. Well, not anymore. C# 6 provides you with another “amazing” feature that lets you get the actual name of the variable, not just the value of that variable.

Before C# 6, nameof operator was not present. With C# 6, this new feature can allow you to know the names of the variables, not just their values. So for example, previous we did:

Console.WriteLine($"Hello, my name is {Name}");

Now we can do this too,

Console.WriteLine($"Value of {nameof(Name)} variable is {Name}");

Screenshot (6011)
Figure 2: Use of nameof operator in real world.

However, the actual use cannot be determined here. The actual use of this would be when we want to know the variable names too. We could definitely (before C# 6) hardcode the names, but after modification, refactoring, they would be of no use anymore. However, now C# 6 can allow us to have the names of those variables too.

To understand the working, have a look at the MSIL generated:

IL_0000: nop 
IL_0001: ldstr "Value of {0} variable is {1}"
IL_0006: ldstr "Name"
IL_000B: ldarg.0 
IL_000C: ldfld UserQuery.Name
IL_0011: call System.String.Format
IL_0016: call System.Console.WriteLine
IL_001B: nop 
IL_001C: ret

This shows, that the variable names are passed as string objects to the function and then the string formatted (as we talked in the string interpolation), and finally the result is printed. So basically, all of this is just sugar-coating.

Null-conditional operator

For this feature too, I have been always very narrow-minded. I never liked it, perhaps because I have written a “good way to handle null exception” as:

if(obj != null) {
   // "Safe" code here
}

// OR
try {
   // Code here...
} catch (NullReferenceException e) {
    // Code here...
}

But, things have changed. Previously, I was writing a library, in which I was supposed to get a list of objects from JSON data. So basically, if the source was empty or like “[]”, the array would be typically null. In other words, to overcome the exception, I would have to write something like this:

// Deserialize the string
var list = JsonConvert.DeserializeObject<List<Type>>(jsonString);

// Then check if it is null before returning
return (list == null) ? new List<Type>() : list;

//  Or using null-coalescing operator
return list ?? new List<Type>();

However, as of C# 6 introduced something new, just to overcome the null exception in each line.

var item = list?[index]; // item would be null, if list is null

I am still not very much pushed by this feature, because setting something to null based on null-ness of another is not a good idea. Is it? We can easily do this:

// Get the list
var list = Model.GetList();
var item = new Item(); // Just assume it

if(list != null && index < list.Count) {
    item = list[index];
} else {
    // Show the error
}

// In C# 6 we do
var list = Model.GetList();
var item = list?[index];

if(item == null) {
   // Show the error
}

Now basically, following this approach, we have “easily” removed on conditional block. But still, our code is exposed to:

  1. Null reference exception: We still need to check the item for this, or continue to use the same steps to avoid null reference exception along the track, and finally, tell the client, “Oooooops! There was a problem!”.
  2. Index out of range: In the previous code, we would check the index too, however to do that, we would require a new block in C# 6 code, and that would ultimately lead us to a state where null-conditional operator would lose its meaning.

So, have a look at this code:

List<int> i = null;
var item = i?.First();
 
// Item would be null if list is null. But we managed to minimize errors "yay!"

Technically, we know item is null. But just to check it, we generate the MSIL too,

IL_0000: nop 
IL_0001: ldnull 
IL_0002: stloc.0 // i
IL_0003: ldloc.0 // i
IL_0004: brtrue.s IL_0011
IL_0006: ldloca.s 02 
IL_0008: initobj System.Nullable<System.Int32>
IL_000E: ldloc.2 
IL_000F: br.s IL_001C
IL_0011: ldloc.0 // i
IL_0012: call System.Linq.Enumerable.First
IL_0017: newobj System.Nullable<System.Int32>..ctor
IL_001C: stloc.1 // item
IL_001D: ret

Look at IL_0017, what this does is, that it just creates a new instance of an integer of nullable type. So basically, what we have above is:

int? nullable = null; // Int is struct! That is why we append "?" to the type.

The MSIL for this case is:

IL_0000: nop 
IL_0001: ldloca.s 00 // nullable
IL_0003: initobj System.Nullable<System.Int32>
IL_0009: ret

Gotcha! This is same as to what we had previously. Only difference is the syntax now. Nothing new. So we can also conclude that our item is of type “Nullable<int>“. We already had that, didn’t we? :-)

Remarks and references:

This is (yet!) another sugar coat to C# compiler and the syntax. But I like it. However, there are still many things that you may want to learn before digging any deeper into the code.

  1. Nullable Types in C#

Static, just got better!

Another new feature provided by C# 6 is the static keyword in the using statement. So basically, what we have got is a method to include the classes themselves, and not just the namespace packages. What this feature does is already very much popular, so let me just continue to talk about what I had to talk about. I have a few things that I want to talk about… Starting with the first one:

First of all, when you write something like,

using static System.Console;

It doesn’t mean, that each time you call “WriteLine” (or other Console’s member functions), it would be the function of Console that gets called. This is more like ambiguity here. For example, the following code:

using System;
using static System.Console;

namespace CSTest
{
    class Program
    {
        static void Main(string[] args)
        { 
            WriteLine("Love for all, hatred for none.");
            Read();
        }

        public static void WriteLine(string message) 
        {
            Console.WriteLine($"'{message}' printed by member function."); 
        }
    }
}

The output of this programs is:

Screenshot (6014)
Figure 3: Output of the member function.

So basically, what we can conclude is that even though our Console class is introduced, but compiler prioritizes the member functions. The priority is done in the case of both being static. If your member function is instance, then compiler would raise an error, so in that case you will always have to write the full name for the function with the type it is associated to. Like this:

using System;
using static System.Console;7

namespace CSTest
{
    class Program
    {
        static void Main(string[] args)
        {
             Console.WriteLine("Love for all, hatred for none.");
             Read();
        }

        public void WriteLine(string message) 
        {
            Console.WriteLine($"'{message}' printed by member function."); 
        }
    }
}

This would now run the function from Console class object.

Screenshot (6016)
Figure 4: Message printed by Console.WriteLine function.

This just executes the function. There is another thing that I want to discuss, the static include is not just for the built-in classes, you can use them in your cases and your class objects too. Just for the sake of example, I created a sample class that would allow us to use the functions in a similar behavior.

class Sample
{
    public static void StaticFunction() { }
    public void InstanceFunction() { }
}

// Adding a struct would also work. Static functions would be pulled.
struct SSample
{
    public static void StructStaticFunction() { } 
}

Now, I don’t want to demonstrate the use of struct or class. So, now you can call those functions in your own class as if you were calling them from within the class itself.

Remarks and references:

This works for structs and as well as classes. The thing is that this works with the functions who are:

  1. Public, private functions are not shown (of course!)
  2. Static, instance functions require an instance, so compiler doesn’t bother showing them at all.

Static classes are all static, their members are also meant to be static so every member function of a static class would be accessible. However, in case of instance classes, only static functions are visible in the list of IntelliSense.

For more information, please read:

  1. Static Classes and Static Class Members

Auto-properties, and their improvements

Auto-properties have been available in C# for a long time by now, the thing is that they now introduce a new feature. “Initializers” can be used to initialize these properties to their defaults. A few of the ways that they can be used is like this:

private string Name { get; set; } = "Afzaal Ahmad Zeeshan";

// Without a setter, a readonly
private string Name { get; } = "Afzaal Ahmad Zeeshan";

// Simply read-only
private readonly string Name = "Afzaal Ahmad Zeeshan";

But remember, the last one is a field, not a property. For example, see this:

private string Property { get; set; } = "Afzaal Ahmad Zeeshan";

private string getterOnlyProperty { get; } = "Afzaal Ahmad Zeeshan";

private readonly string readonlyField = "Afzaal Ahmad Zeeshan";

This would be translated as:

IL_0000: nop 
IL_0001: ret

get_Property:
IL_0000: ldarg.0 
IL_0001: ldfld UserQuery.<Property>k__BackingField
IL_0006: ret

set_Property:
IL_0000: ldarg.0 
IL_0001: ldarg.1 
IL_0002: stfld UserQuery.<Property>k__BackingField
IL_0007: ret

// getterOnlyProperty is a getter-only, so not set_ field is available.
get_getterOnlyProperty:
IL_0000: ldarg.0 
IL_0001: ldfld UserQuery.<getterOnlyProperty>k__BackingField
IL_0006: ret

The code is categorized under getters and setters for the properties, and the readonly field is just a variable in the program.

Remarks and references:

The new thing introduced in C# 6 is that you can now set the values to a default, in previous versions you would have to enter a new value in the constructor. However, now you can enter that value right there!

For more please read:

  1. Accessors in C# on MSDN.

Lambdas have evolved

If you have ever read my previous posts, you may have known that I am a huge fan of lambda expressions of C#, specially when it comes to handling the events. I have always enjoyed programming, based on these lambdas.

  1. Handling events in WPF in an easy and short hand way

What now can be done is that lambda expressions can be used now to create the functions too (just like before), not just that. They can be used to simplify the getter-only properties too.

The syntax, cannot show you how simple it gets. For example, the following code block,

public int Multiply (int a, int b) { return a * b; }

It looks very much simple, and is optimized. However, the MSIL code looks “horrible”.

Multiply:
IL_0000: nop 
IL_0001: ldarg.1 
IL_0002: ldarg.2 
IL_0003: mul 
IL_0004: stloc.0 
IL_0005: br.s IL_0007
IL_0007: ldloc.0 
IL_0008: ret

This is a very long MSIL, which would be translated and would require a lot of CPU cycles. While on the other hand, if you can see this code:

public int Multiply (int a, int b) => a * b;

This lambda expression does same, as what the previous one did. But, is very much performance-efficient. The MSIL generated with this code is like this:

Multiply:
IL_0000: ldarg.1 
IL_0001: ldarg.2 
IL_0002: mul 
IL_0003: ret

How small MSIL code, right? So this demonstrates that using a lambda expression to write our function, we can not just simplify the code size, we can also fine-tune the code that is executed for that.

Another major use of these lambdas is while creating getter-only fields. Now, their topic is already discussed above. But, however, I would like to talk about them again…

public double PI { get; } = 3.14;

The MSIL generated for this would be (you guessed it right!) a get property, and a backing up field. Like this:

get_PI:
IL_0000: ldarg.0 
IL_0001: ldfld UserQuery.<PI>k__BackingField
IL_0006: ret

So basically, what we have is a block, that returns the value of the field that is backing up this property; whenever we call the property. Now, to fine tune it using C# 6, what we can do is something like this:

public double PI => 3.14;

The MSIL for this is really very amazing, just the way we improved the function, we can improve this field too, increasing the access time. So now the MSIL is:

get_PI:
IL_0000: ldc.r8 1F 85 EB 51 B8 1E 09 40 
IL_0009: ret

Pretty much amazing, and short! It just pushes this content, as float, on the stack. Then calls the return to provide the value. The thing is that we don’t need a backing field at all. To make it more readable, please read this:

public string PI => "Afzaal Ahmad Zeeshan";

Now, in the case of a field-backed-property, the value would be stored in the backing field and when we would call this, the backing field would be called (a new call!) and then that value would be returned. However, in this case, what happens is something like this:

get_PI:
IL_0000: ldstr "Afzaal Ahmad Zeeshan"
IL_0005: ret

Simply, this would load the string on the stack, and would then return this value. It is more like having that constant field in your project that gets places wherever it is called from and so on.

Remarks and references:

Lambda expressions are definitely very useful, not in just decreasing the syntax size, but also in making the source code size small, too. The lambdas are inherited from “Functional programming”, and well, in the world on object-oriented programming they have seriously marked their place.

For more please read:

  1. Functional programming
  2. Lambda expressions in C#
  3. => operator

Points of Interest

In this post, I have talked about the most “popular” and interesting features that C# 6 has introduced to its users. However, until now most of the times I have only seen the “same song and dance“. Programmers have just talked about the fuss, no one talked about their internal implementation.

In this post, I have shown what difference they have, how they differ, who are just syntactic sugars and which really do have an influence on your programs. Basically, from this list, my favorites are:

  1. String interpolation
  2. Lambda expressions

Others are useful, yet I don’t feel like using them in my own projects. If you have anything else on your mind, that I yet don’t know… Please share it with me. :-) I would love to hear.

Guide for building C# apps on Ubuntu: NuGet packages

Introduction and Background

If you have been programming C# applications, then chances are you are pretty much aware of what NuGet packages are. However, if you don’t know what that is, it is an online storage for dynamic-link libraries (.dll) for .NET programs. Most programmers (including me) have contributed toward the total packages currently available on NuGet. NuGet allows developers to reference the libraries from third-party programmers, easily, all by typing a command!

In the previous posts, I had already talked about the basics of Ubuntu programming using Mono, in this short piece I am going to talk about NuGet packages in Mono. NuGet packages are of great use in Visual Studio, you can download the most wanted packages from NuGet to increase the productivity of your application. I have personally used Newtonsoft.Json package many times to introduce data sources in my applications based on JSON files and C# code, a usual example of this can be LoginKeys framework that I wrote for authentication systems. There are many other useful packages that you would like to use while programming, in this post I am going to talk about, methods to include the package in your application development project.

Managing the NuGet packages

In this section, I will demonstrate two things:

  1. How to manage the repositories, from where to fetch from.
  2. How to install the packages and use them.

So that you can have a good understanding of NuGet packages, package management and how to use them in your projects.

Configuring the IDE

First step is to configure the IDE, by default, IDE is configured to capture the packages from NuGet’s current API version, which is, https://www.nuget.org/api/v2/. In future that may change, so that is why you may need to configure the IDE… Just showing, the settings are available under IDE settings.

Screenshot (5864)
Figure 1: NuGet package gallery management.

You can edit this to configure the IDE to capture the packages from the actual location. You can also open these settings from the NuGet package management window itself, by selecting “Configure sources”.

Screenshot (5865)
Figure 2: Options available for currently provided NuGet galleries and option to configure the sources.

This would allow you to alter the sources and other settings, you can also change the names for the galleries. However, that is pretty much simple, and I am sure you can manage to do that all by yourself. Now, let us consider installing and using the packages in our applications.

Installing the packages

Fun part starts! The packages, can be easily installed using the GUI window provided to us by MonoDevelop itself. We can search for the packages, or install the most popular ones that are shown in the listview itself. It is very much simple, to install the package.

I have demonstrated the procedure in the following image:

Screenshot (5867)
Figure 3: NuGet package management window.

Now, what I have done is that I have introduced steps required to install the package. You can follow the same steps to install any package.

  1. Find the package in the list. I have selected, Json.NET package.
  2. If you find yourself confused while selecting a package, you can check for the explanation of the package in the right side, name, version, description and author details are shared here. You can make sure you are selecting the “correct” version of library.
  3. Click on “Add Package” to add it.
  4. This option is not required, and is used to turn on and off beta versions, pre-releases.

Now, once you have clicked on the “Add Package” button, MonoDevelop would take a minute or two and then add the library package to your application. In my system, it took ~5 seconds, so don’t worry it would download and install the packages, in a while. Once that is installed, your references would look like this:

Screenshot (5868)
Figure 4: Newtonsoft.Json package installed to the project.

Json.NET library is the Newtonsoft.Json library, so it gets added to the project under “From Packages” category. This has been added to the project, and you can then get to use it in your project. Before, I do that, let me show you how to search for the project packages in NuGet.

Where on file system are they stored?

This is another interesting thing, in Mono environment, the project packages that are downloaded from the galleries, are stored in the same package directory. For more on package directories, please read my previous post: Guide for building C# apps on Ubuntu: Project files and output. In the directory, a new folder, “packages” would be created and then your newly referenced package will be stored there for later references.

Screenshot (5873)
Figure 5: “packages” folder in the project directory.

You will find the code, and other files all in this folder. This is done so that you can use the package later, the packages in NuGet are online and thus you cannot bear to pay the price of network latencies each time you want to build the project, downloading the assemblies is the easiest method.

Searching for a library

Search bar is also provided in NuGet management window, that you can use to search for the libraries. The list shows only the popular ones, but if you want to search for third-party average project libraries, that are not in the use of people more often, you can use the search box to search for those libraries and window would bring up the matches that it finds on the gallery. You can then select from those results and get what you want to install in your application project. For example, to install LoginKeys package, you can write the keyword in the search box and NuGet package manager would bring the results, so that you can select from the search results.

Screenshot (5869)
Figure 6: LoginKeys package being shown in the search results.

You can see that the GUI window has shown the results, and also, it has provided me with the details so that I can know that I am installing the correct version of library, from the author I trust (do I trust myself? Nah!), then I can follow the same steps and install this package to my project too.

Updating and restoring packages

In Mono, updating and restoring the NuGet packages is also very simple, and takes just a click! Yes, have a look below:

Screenshot (5874)
Figure 7: Options to update or restore the NuGet packages.

These are the options provided, to update or restore the packages, just click on the option and Mono would do it for you! There are many other options also available along with these.

Referencing the package namespace

Once you have added the package to your project, you need to reference it in your source files too, although the assembly is available, but to be able to reference the functions in your source file, you also need to add the using statement in your project. We are having the Newtonsoft.Json package, to be able to consume the library, we would need to reference it and then build the application.

Have a look at the following code:

Screenshot (5871)
Figure 8: Compiler error shown.

The problem, you are right, is raised because we have not yet referenced the namespace to include the object JsonConvert in our project. So, we write the code like this:

using System;
using Newtonsoft.Json; // Adding the reference

namespace NugetPackages
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            /*
             * We do not need to create a new class, instead
             * we can create anonymous types. 
             */
            object anon = new { Name = "Afzaal Ahmad Zeeshan", Age = 20 };

            // Now the function would serialize the anon object
            var serialized = JsonConvert.SerializeObject (anon);

            // We then print the JSON format on screen.
            Console.WriteLine (serialized);
        }
    }
}

This code would compile and execute safely. The output of this code is like this (I think, you already know),

Screenshot (5872)
Figure 9: Result of the above code.

Pretty simple, I don’t need to explain it at all, because Newtonsoft.Json namespace is already very famous and widely used package.

Points of Interest

THis is another post in the series of “Programming C# on Ubuntu” category of articles. In this post, you were taught to use NuGet packages in your Mono projects on Ubuntu. The post was intended for absolute noobs and beginners in Mono programming on Ubuntu, and hopefully, you have been taught to program applications on Ubuntu.

This was somehow a short descriptive post for NuGet packages only. In later post, you will be taught to develop libraries and re-use them in other projects. Stay tuned for the upcoming post. :-)

Guide for building C# apps on Ubuntu: Cryptographic helpers

Introduction and Background

In the previous posts, I had shown how you can use MonoDevelop IDE of Mono Project to get started programming C# applications on Linux environment and for the operating system I used Linux distro, Ubuntu operating system. However, since all of the topics are covered already and I am just skimming through the snippets and small portions of the data that I can share, this is another post in the series before I continue to write a guide for this, in a compiled form. In this post, I am going to talk about cryptographic support provided in Mono itself, for Ubuntu. However, you can always write your own compiled modules that run the cryptographic services and you can also write your own modules that represent the procedures and steps shown in the certified algorithms for cryptography. But, in this post I will talk about the built-in classes and objects provided to you for these services.

I have also talked about security tweaks a lot before, and I would like you to read my previous posts about security in .NET framework too, A few tips for security in .NET framework. Since this is much more about Ubuntu and C# programming using Mono Project. I recommend that you read the previous posts in this series of articles.

  1. Guide for building C# apps on Ubuntu: MonoProject Introduction
  2. Guide for building C# apps on Ubuntu: Language quickies
  3. Guide for building C# apps on Ubuntu: Project files and output

So basically this is another post in the series of Ubuntu programming using C# language, Mono Project has been a great tool for C# geeks. In this post I am going to talk about the hashing algorithms, and what else Mono Project has for us!

Security APIs in Mono

No wonder Mono is influenced based on .NET’s philosophy and C# language, but still it lacks many things when it comes to the core APIs, such as security API. It does not have a full package of the APIs in it. For example, on .NET framework the support has been increased to SHA256, SHA512 and more, where as on Mono there are not much flavors currently added and you only have to stick to either one of the provided, or you would have to manage the base algorithms and write your own implementation of the algorithms. Which, definitely, would be hard job! Until Mono introduces some new algorithms, let’s stick to the provided ones and learn about them, how to use them and what they can serve us with.

In Mono APIs, you get two namespaces for security algorithms. The algorithms can be for simple encryption and decryption or it may be for the password hashing purposes. Now, these two are different in many ways, however they are categorized under “Cryptography” in computer science.

  1. Encrypting/decrypting: is a process in which you encode the data in such a way, that a special secret key is required to bring the data back in its original form. It is used while securing the data from potential spywares, because each time you have to access the data, you need to pass a special secret key with it.
  2. Hashing: is a process, typically used for passwords, but is not only restricted to passwords. Hashing is a technique, in which data is encrypted, in such a way that it is impossible to be converted back to its original form.

Mono namespaces provide you with objects that allow you to work around with these functions and add a layer of security to your applications. Now, let us first of all, talk about password hashing and then we will get into the encryption and decryption techniques provided in Mono runtimes for developers.

During the article, I will only focus on the objects provided in System.Security.Cryptography, however you can still use Mono.Security.Cryptography, but the recommended one is the native .NET framework’s cryptography namespace.

Hashing the passwords

Hashing the passwords has been widely used in every network based application, or online application. Hashing is a process, that is not just restricted to the passwords, as I have already said, the hashing has been widely used to determine the file consistency. Most of the software packages are introduced with MD5 or SHA hash values, they are used to determine if the file is in its real form or if it has been tampered with on its way to your machine. This ensures that the software package that you are installing is actually the “safe” package and has not been mixed with any malware or spyware content. The code from open source communities, such as Ubuntu, Linux and other open-source projects are widely exposed to such attacks, and if you install such packages they make expose your private data and even ask you for some revenue, that happens in cases of ransomware, Linux.Encoder.1 was one of such viruses, that encrypted the user data and then asked them to pay revenue to get their data back. However, hashing is a very simple task in .NET framework at least.

Usually, there are many algorithms provided in every framework that can be used in your applications, most commonly used are:

  1. MD5
  2. SHA-128
  3. SHA-256
  4. SHA-512
  5. So on…

Now, before I move any further, I should warn that you should never ever use MD5 for hashing the passwords. MD5 algorithm is very weak and a simple rainbow table attack would expose the passwords. In many cases, you should use SHA-128, or SHA-512. But the recommended one is SHA-256, because of the digest that it creates and the security that it has. I would personally recommend that you use SHA-256, if you want to store a small size of digest (hashed password string; in hex), otherwise, my personal advice is to store SHA-512.

The benefit of having SHA-512 over SHA-256, is that you can minimize the chances of collisions  while generating the hashes for the passwords. A collision would typically occur when the hash results are similar for different values. The thing is that the hash function would return a hashed string to a limited size, but it can get an input of any size. Bigger files of larger byte arrays may result in a collision. So, to overcome the collision you may want to generate a hash of bigger size.

Now, talking of hashing the passwords, let me share how to hash the passwords in C#. The procedure is actually similar, if you have a code for .NET on Windows, same would be used on Mono on Ubuntu. Have a look below:

// Function to hash the passwords
public static string HashPassword(string message) {
   // Create a new instance of the SHA-256, 
   // you should use SHA256Managed instead of SHA256 object.
   using (var algo = new SHA256Managed ()) {
       var bytes = System.Text.Encoding.UTF8.GetBytes (message);
       var hashedBytes = algo.ComputeHash (bytes);

       // The hash has been computed, to convert those bytes to string
       // I will use the following code, you may use your own
       // code to convert the byte array to string
       System.Text.StringBuilder builder = new System.Text.StringBuilder ();
       foreach (byte bite in hashedBytes) {
          builder.Append (bite.ToString("x2"));
       }

       // Return it to the caller, to write it.
       return builder.ToString ();
   }
}

So, basically, what I have done is that I have just used that algorithm and I have got what I was expecting from it. Now, the way we call it defines how we use it. In this sample, I will be calling it to write the hash of it, to the screen and nothing else.

Console.WriteLine ("Enter the string to work on:");

// Get the message
string message = Console.ReadLine ();

// Hash the password.
string hashedStr = Crypto.HashPassword (message);
Console.WriteLine ("Hashed string is: " + hashedStr);

Basically, we have already created the function that does the thing for us. So we are only calling it in this code. So, if I run the above code it would be something like this…

Screenshot (5858)
Figure 1: Working of the hashing algorithm on the word, “Afzaal”.

You would store this hashed string in your database when you want to save it. Never save the passwords or sensitive information that you do not want to get back in the actual form, in plain-text form.

Adding some salt to the hash

Now since we are talking about hashing the passwords, it is necessary to add a specific string text to the actual string, which acts as salt to the data. The procedure is very much simple and straightforward, you simply add extra string to the actual string and then find the hash for it. Where you add the salt is your choice, you can append it, prepend it, or insert it at the medians or what-so-ever, that is your choice.

HashPassword (password + salt);             // OK
HashPassword (salt + password);             // OK
HashPassword (salt + password + salt);      // OK

But only thing that you should consider is that you should use the same method to get the hash again, because if you calculate hash differently, their hash value would be different.

2a3a25c485162eb7767a9ce20a52febf
Figure 2: Demonstration of the hashing a string message using salt.

When to use hashing?

You can use the following list items to determine when to use hashing functions on your data.

  1. When you want to secure your data from potential sights.
  2. When your data is valuable only for comparison and not required in its raw form. Passwords are a good example of this type of data.
  3. When you want to check if the file system is tampered with.

References:

If you want to learn more about hashing functions, you should go and read the following links:

  1. Security in .NET Framework
  2. System.Security.Cryptography namespace on MSDN
  3. SHA-2 on Wikipedia

Encryption and decryption of data

Now that we have already talked about the hashing of the passwords and the data, we can now continue to talk about the encryption and decryption of data in Mono using C#. Encryption and decryption techniques are used to hide the data from unwanted users. It can be shared with other users, and they can also view it, but any user who is not required to be using or viewing the information can be removed from the list of viewers.

r4VtMoZ
Image courtesy: This image demonstrates how encryption and decryption is done.

Now we will talk about the coding practices in encryption and decryption. The plain-image, pseudocode and algorithm is very much easy, however, the coding in .NET environment is also very much easy. In the coming sections, you will be shown and taught how to use .NET objects, to perform security restrictions in your applications.

As far as the algorithms are concerned, just like in case of hashing, there are a lot of encryption and decryption algorithms: AES, Rijndael, DES etc. All of them are used, but there are some problems with the later ones and that is why AES algorithm is recommended. However, in my case, I will use Rijndael algorithm, you can change it to AES (and you should change it to AES, I am only using it for demonstration purposes!).

What we do, is that we actually divide the process in a number of steps:

  1. Create the object for algorithm; Rijndael in this case.
  2. Case the memory stream to hold the data.
  3. Create a cryptostream for that memory stream.
  4. Create a stream writer/reader based on encryption or decryption process undergoing.
  5. Return the encrypted or decrypted text.

Each encryption algorithm would require you to pass a special “Key” that would be used for encryption and decryption. The key is the backbone. Without that key, data cannot be converted back to its original form. That is why, keys are kept secretly, in safe places so that potential hackers cannot get to the data. So for demonstration, let’s use the IDE to write some code in it.

1. Encryption function

First of all, let us write a function that encrypts the data as we mentioned in the steps above. A hash function would return an array of bytes, so we would define our custom function to do the same, so that later when working with the values, we can change the data in any form, or save it just the way that it is.

public static byte[] Encrypt(string data) {
    byte[] bytes = null;
 
    // Instantiate the algorithm
    using (var rjndl = new RijndaelManaged ()) {
       // Set up the properties
       rjndl.Key = key;
       rjndl.IV = iv;

       // Create the memory stream
       using (MemoryStream stream = new MemoryStream ()) {
          // Create the crypto stream
          using (CryptoStream cStream = new CryptoStream(stream, rjndl.CreateEncryptor(), CryptoStreamMode.Write)) {
             // Create the stream writer to write the data.
             using (StreamWriter writer = new StreamWriter (cStream)) {
                writer.Write (data);
             }
          }

          // Convert the stream of encrypted text, to array.
          bytes = stream.ToArray ();
      }
   }

   // Return the bytes.
   return bytes;
}

This function is enough,  this would encrypt the data and would provide us with the bytes of the data, in encrypted form. We can then convert those bytes to string, or save then in BLOB format or what-so-ever as required. I will demonstrate the usage in a later section, currently I just want to jump to the decryption part.

2. Decryption function

As name suggests, it is an inverse of the encryption function. The steps required are similar, only that we create a decryptor object for the cryptostream and then start reading the stream in a decryptor object using the same key that was used to encrypt the data in this bytes form. If you use a different key, results are “unknown”.

The following code does the thing for us:

public static string Decrypt (byte[] data) {
    string message = null;

    // Instantiate the algorithm
    using (var rjndl = new RijndaelManaged ()) {
        // Set up the properties
        rjndl.Key = key;
        rjndl.IV = iv;

        // Create the memory stream with the bytes of data
        using (MemoryStream stream = new MemoryStream (data)) {

            // Create the stream with the decryptors
            using (CryptoStream cStream = new CryptoStream (stream, rjndl.CreateDecryptor (), CryptoStreamMode.Read)) {

               // Create a stream reader for the crypto stream
               using (StreamReader reader = new StreamReader (cStream)) {
                   // Read the data to the end.
                   message = reader.ReadToEnd ();
               }
           }
       }
   }

   // Return the message.
   return message;
}

We now have the counterpart of our encryption/decryption algorithm or service (call it what you like!). Now that we have both of our functions ready, we can now test the function and see if it works in our cases for encryption and decryption.

I am going to enter my name, and then I will get the encrypted text plus the decryption function would be executed to get the data back.

Following is the main function,

Console.WriteLine ("Enter the string to work on:");

// Get the message
string message = Console.ReadLine ();
Crypto.Setup (); // Look at the code block below!

// Run the logic
var encrypted = Crypto.Encrypt (message);
var decrypted = Crypto.Decrypt (encrypted);

string encryptedStr = null;
StringBuilder strBuilder = new StringBuilder ();
foreach (var b in encrypted) {
   strBuilder.Append (b.ToString("x2"));
}

encryptedStr = strBuilder.ToString ();

Console.WriteLine ("Original text was '" + message + "', it was encrypted to: \n" + encryptedStr);
Console.WriteLine ("Decrypted text is: " + decrypted);

The output of this program was,

Screenshot (5859)
Figure 4: Encryption and decryption function on “Afzaal Ahmad Zeeshan” string.

Pretty simple, right? :-) So, finally we have encrypted and decrypted the text in Ubuntu using Mono Project…

Tips:

  1. Consider changing the Rijndael to AES.
  2. Keep a strong key, use the provided functions to generate a “strong” random key.
  3. Decrypt when needed.
Using Rijndael or AES?

Rijndael and AES can be confusing somehow. Don’t worry, I was also confused as to which is better and which is not. The thing is, Rijndael algorithm was developed along with numerous other algorithms, to come on top as “best algorithm for encryption and decryption“. Rijndael won, and was selected as AES algorithm.

Does that make sense? It should… If that doesn’t, read this blog post.

Points of Interest

This is another post in the series of “Programming C# on Ubuntu” articles. In this, I have talked about cryptographic programming in Mono Project on Ubuntu. The services are similar to what we have in .NET framework on Windows operating system. However, there are some other namespaces provided by Mono itself, but still, .NET namespaces rule them out. The services that you can find in .NET are amazing, and C# language itself is just perfect language to be used for any project! I am writing this guide, to share the beauty of C# on cross-platform environments too, for those who are unaware of this currently.

In this post, you were given a few tips and you were shown how to perform cryptographic functions on your data, including hashing the passwords, encrypting and decrypting the data on your machine. Cryptography can greatly influence your application’s performance, and your users would like the privacy and other services that you have for them, such as encryption and decryption of the data, using which they can save their data from unwanted users, and yes, hackers!

In later post, I will talk about NuGet package managements, and then I will head over to writing a guide, in the form of a book itself. See you in the later posts. :-)

Guide for building C# apps on Ubuntu: Project files and output

Introduction and Background

In the previous posts for the series I talked about the IDE itself, I talked about the tools provided in the MonoDevelop and the Mono Project for C# developers that would help them do their jobs quickly. You may want to read those posts first and then continue to read this post, or the either way as I have tried to abstract the posts enough.

  1. Guide for building C# apps on Ubuntu: MonoProject Introduction
  2. Guide for building C# apps on Ubuntu: Language quickies

Later, you can continue to read this post. This post has a primary focus on the project files, compiled assemblies and the executable files generated after the build process. So, although this would be a very short guide, I would try to explain every aspect of it. You can however, do let me know if you find something missing here.

I assume that you already have an idea of C# project files, typically they are:

  1. One solution file (.sln)
  2. A folder for the project itself.
  3. Properties files
  4. Binary and object files folder.

You will find this template for a project of C# everywhere, from Console to any graphical application that you may be using. The template is chosen to make sure you can always skim through the file system and find the required item there. So now let’s talk about these items in detail…

Project files and output locations

If you have ever programmed in C# on Windows, using Visual Studio you may know the common folders and locations for the project and the generated binaries. For each of the project that you create, Visual Studio creates a quite similar project directory and puts the source code, project settings files, and others in that directory.

MonoDevelop does the same for you! MonoDevelop would ask for a location to create the directory for the project and would then use that location to create new files, and to place the compiled executables. We are going to talk about a few of these locations and the files generated there.

1. Project directory itself…

First of all, let us talk about the project directory that gets created. This location is chosen by you, you are given full permissions to chose a location to select the directory at. You can enter the location and then MonoProject would use the same location to perform the actions, like creating and adding new files, resources and source files, also the same location is used to generate and place the binaries and object code files. So, this directory is used throughout the project life, chose it wisely.

So, for example, when we created the project (in the previous sections), we entered the following location to be selected as the project directory.

Screenshot (5241)
Figure 1: Creating the project and entering the location for the project directory. 

Have a look at the “Location” field in the above window. We can change it from here, we can also browse for a new location and well, you get the idea that we can create the directory anywhere that we find it helpful and easy to be found!

Remember: Projects is also a manual location in Ubuntu, by default the home folder for users do not contain a folder named Projects.

Once we create the project, the files are generated at that location and the project window opens. However, we are only interested in viewing the directory itself and not the project code. The files that are generated here, are very much similar to Visual Studio’s files, it also contains the solution file, Solution files typically hold the information for the project, files and other settings and configurations that you make in the project; like architecture support. Only these files are provided along with the templates because IDEs use a special project file to determine the configuration and the files for the project.

By default, the directory has 1 sub-directory and 2 files:

Screenshot (5708)
Figure 1: Root level of the project, one folder and solution and preferences files in the directory.

As already discussed, the directory is used to hold the files and references for the projects and also holds the generated binaries and executable files. However, before diving any deeper. Let us talk about the files that we can see right here. These files contain the settings for the project and for the user sessions.

Solution file

First of all, let us talk about the solution file itself. The solution file is basically the settings and overall configurations that you make to the project itself. The project is what you create when you start Mono and go ahead creating something. Things that you create in a project are files, resources and source code files etc.

We can open the file up in the text editor, the code in this file is simply commands and settings that would train the environment to set up the configuration for build and a few others, like the name of the project (obviously!)

This file contains the information about:

  1. Project itself.
    • Name
    • Package identifier. Sometimes a GUID.
  2. Build configurations.
    • They are written in the global scope for the environment.
    • Active build configurations for debug and release mode.
    • Extra configurations.
    • CPU architectures used.
  3. Project details file name and other minimal files used for project management.

So, this file is created and is maintained throughout the project. You can also start the project by double-clicking the file for C# project in the same directory (make sure you do not open it in text editor itself). For more on Solution files please refer MSDN, as they describe the file in a much better way: Solution (.Sln) File.

User preferences

Ever wondered how does your IDE know where to start and which line you were previously working on? This file holds the information for that, this file holds the information for currently active file, currently active line and even the column where your cursor was!

So, basically this file holds the information for your currently active session and when you reload the IDE and the same project, your IDE would know where to get you started from. This saves a lot of time of developers as the source code file and the line is already active, they can just continue to work from where they left it.

This file also keeps a hold of your breakpoints. So, everything and every change that you make in the files (not the project!) is saved here. This file is checked against when a new instance is starting so that your sessions are started without any trouble.

This ends here. I think the purpose of these files is pretty much clear. The next step is to go inside the folder and look there… Next I will simply just talk about the files, and the output folders where you would find your assemblies being generated.

2. Inside the project directory

Inside the project directory, the required files for the project building procedure are available. The source files, project building libraries, executables and other binaries are all managed and collected to be placed here. Each new file that you create is created here, and the project knows which files you currently hold and which files that you have removed. So overall the directory is just to hold the files for the project. This directory is used as the location for the files and resources when the build process starts.

Screenshot (5710)
Figure 2: Inside the project directory.

Now these are the entire files required to run our sample project! The project files, solution files and user preferences are all found here and… Well, there is another a simple Program.cs file found too. All of these files are used to generate the assemblies (which are later placed in the bin folder, displayed above). Technically, if either one of these files are missing (the ones that are required at the compile-time), your project cannot compile. You will get errors and you would either have to create a new project, or edit the profile itself to make sure that the errors are minimized. So it is recommended that you do not tamper with these files and let the IDE do what it is intended to do.

Properties

This is another folder in the project itself and well technically it contains the properties for your project. The properties are of the assembly, the information about the assembly, versioning etc are found here. Currently, this folder contains just one file, “AssemblyInfo.cs”.

Screenshot (5835)
Figure 3: Properties folder.

This file is used when referencing the assemblies in the projects. You can get more information from MSDN or any other resource that talks about Assembly Information in C# applications.

bin and obj folders

These folders are used when IDE has finished building a project. They are used to maintain the executables for the project. However, they are not required to be there. Your IDE would itself create these folders when you run the build process, if you have deleted them before.

Just for the sake of demonstration, please see the following image, the executable can be found in the following folder:

Screenshot (5836)
Figure 4: Debug executable found in the bin folder.

This “.exe” file can be used to execute the code that we just wrote in the application. But remember, if you previously deleted the folders, you still need to build the project again to find the executables here. Otherwise, the folder would be empty.

Points of interest

This is another post in the series of Programming C# on Ubuntu. In this post, I have talked about the overview of the project file and directory structure. Where are your executables placed, what files are provided in the templates and which are optional locations.

This was just an introductory post and that is why is much concise. In upcoming post, I will talk about cryptographic services provided by MonoDevelop for C# programming on Ubuntu. So, stay tuned for the next publication.

Guide for building C# apps on Ubuntu: Language quickies

Introduction and Background

In the last post, I talked about many things that C# programmers usually look forward to in their IDEs and environment. If you didn’t read the previous post, please read it at Guide for building C# apps on Ubuntu: MonoProject Introduction. In that post, I talked about usual features and tools that C# developers want to use while working on their projects. In yet another post, I talked about using C# for cross-platform development and technically, that post had most of the content for C# programming on cross-platform environment, but in this post I am specifically talking about the Ubuntu environment only. You may want to read that post first, so head over to “Using C# for cross-platform development” and read that post too. I think you will find that post also very much helpful.

C# programming language has already become very popular in programmers, many beginners are taught C# for their object-oriented programming lessons. The concept of object-oriented is very intuitive and understandable, and praising the .NET, it has been made very easy and simple to program an entire object-oriented project in C# to run on any device having .NET framework installed on it.

In this post, I am going to talk about the language quick help toolkit provided in MonoDevelop environment. MonoDevelop has a great toolkit for C# language help in building the small snippets of code blocks in your programs.

Helpful tools and features in MonoDevelop

Let us count the helpful items and features provided in MonoDevelop. MonoDevelop has some great tools and features, available just for language guide and help while development, but however, we will only talk about a few of them in this section as discussing them all won’t be available in this one small post of mine and I will hopefully cover those topics in the book that I am going to write later. Make sure to check that book once it gets released.

1. Language specification

Sometimes, when you are working on a project, the specification for the language is a “must have” part in your “have this” setup! I have myself found it very hard to get the project running when I forget a single piece of code or how to write this and similar things. It just happens, and you have no control over it. However, usually tools do not come with the language specification and language references and guides. MonoDevelop and Mono Project however do come shipped with the language guide for you! You can get the offline version of their documentation on your machine so that you can reference it whenever you want to.

Mono Documentation is the application that contains the references to the technical part of the language, framework and the software platform itself.

Screenshot (5364)
Figure 1: Mono Documentation application in the All Applications list on Ubuntu Studio.

Mono Documentation is an application package downloaded and installed while you are installing the Mono Project. This applications contains almost everything that you would ever need while programming a project on MonoDevelop IDE. The library tooling contains almost everything, a few of them can be enlisted as:

  1. Mono embedding
    • JIT, Object, Reflection and other core features are listed and described here.
  2. Language
    • Language references: Contains the language information, syntax and structures.
    • Exceptions and errors: Compiler errors are also listed here so that you can search for one.
  3. Commands
    • Some commands for the platform itself.
  4. Mono libraries
    • Of course, Mono wouldn’t run without them! They are native Mono assemblies written to make sure that your .NET code runs on the Ubuntu.

You can use this guide, you can even update this guide because Mono Project is open source and relies on help from the community. Each contribution that you make, is pushed to others! “Sharing is caring“, right? :-)

This is just a guide, so you are going to have the same one there. But I am just going to show you a few of the pages that you would find interesting and “much wanted”.

Screenshot (5367)
Figure 2: Mono Embedding window open in Mono Documentation. 

These are core components and I would personally recommend that you read them out before using Mono Project for development. Having an understanding at core level is very helpful, even while programming C#!

Language specification can also be captured from this application, C# language has been greatly explained in this application. You will find the explanation for everything in C#, from objects, to strings, to classes to structs and to anything that you would find to learn about in C# and while programming an application.

Screenshot (5371)
Figure 3: C# language overview window opened in Mono Documentation.

However, posting an image and description of each of the page would go out of scope here and it would take a lot of time. I am not going to do that, you can surf that yourself.

2. Compile time error specification

Another main thing that C# programmers usually want to get is a compile time error specification. Of course, you can tell by the message, “Constant value 256 cannot be converted to byte“. But, the compiler error for this is, CS0031. For an intermediate programmer (like me!) that can be easily solvable, and maybe generated from the following code:

// Saving the value '256' to byte type.
byte b = 256;

We can solve that easily, by just changing the value to 255 (or less), or by changing the type to integer and so on. However, what in case when you need to get an example of the context when the errors are somewhat complex.

Remember, errors are thrown when you do not follow the rules defined when a compiler is designed and created. Compiler would always follow those rules, you need to stick to them. These documentations would have those rules defined. So, for example for our problem above, the sample error documentation is like below:

Screenshot (5373)
Figure 4: Compile-time error specification window open in Mono Documentation.

This page would contain many examples of the cases when you may raise this compile-time error. You can read this guide, learn what you did wrong and then solve the problem. Although most of the beginners want to ask questions, however that is not a good way of learning. At least, not in my case. I have always prefered learning by doing it wrong again. This way, I could get an idea of fixing my problems easily. This way would:

  1. Give you a better idea of compiler theory; not that subject, instead the way compiler is trying to compile the code.
  2. Show you other scenarios when the code goes wrong.
  3. Teach you how to fix the code.
  4. Give you a few other helpful resources in the code itself.

There are many other error codes discussed and shared about, you may want to find yourself some help and guidance in those guides. MSDN is a great resource for any C# programmer and you can surely find help by trying to Google for the problem and looking for an answer, but I find this method also very much helpful if you are a beginner and want to learn C# programming.

3. Toolbox support

If you have ever built applications for graphical user-interface, then you are already aware of the toolbox. A toolbox is an element that contains the most used controls ready for you to drag-and-drop or double-click to create in your application project’s currently open window. Now, what MonoDevelop has in it is that it also allows you to create code-snippets by double-clicking on the items in the toolbox. You don’t have to write the long codes yourself, you are provided with the templates for the code snippets and you can then allow MonoDevelop to create them up for you.

Just for the sake of example, have a look at this image below:

Screenshot (5376)
Figure 5: List of C# program structures provided in MonoDevelop Toolbox.

Now, if you have ever programmed in C#, you would know that these are all keywords and structures provided by C# to their programmers. You can chose from these and create a new structure at once. MonoDevelop would do the honor to write down the code for you.

For the sake of example, have a look at our class (this class was created in the previous post of this series, you should consider giving it a look), it doesn’t actually have a constructor so we will create a constructor using this toolbox.

Screenshot (5377)
Figure 6: Class without a constructor.

Once we double-click the item from the Toolbox, (ctor is constructor), our class would now have the following code: (Remember to place the cursor where you want to enter this constructor, or any other code-snippet)

Screenshot (5378)
Figure 7: A sample constructor in our class. 

It just added the constructor to the class… We can now refine it to look better or to add the logic that we want, MonoDevelop doesn’t know of the logic so it would just leave that to us. Maybe it is not intelligent enough. :-)

Screenshot (5379)
Figure 8: A sample constructor with a comment in it.

Looks better now, doesn’t it? There are many other methods, structures, loops and even class templates that you may want to try out. I have just demonstrated the basic one, and I leave the rest to you. Try them all.

4. Unsafe code in MonoDevelop

C# is a high-level language, agreed! But it does allow developers and programmers to go in an unsafe context and work around with pointers, references and other low-level stuff that C and C++ programmers usually brag about. Well, not anymore, MonoDevelop also supports unsafe context and they can use the power of low-level and “on-demand” memory-management!

By default that is not enabled, so if would like to write something like that,

unsafe {
   // Some "unsafe" code here...
}

You will get an error when you would try to compile the code.

Screenshot (5387)
Figure 9: Unsafe context code with error.

You can fix that in the settings for your project. Right under the general settings, select, “Allow unsafe” and you’re good to go then.

Screenshot (5390)
Figure 10: Allowing the unsafe context in MonoDevelop project configuration window.

The code would now execute and run successfully (unless there are other errors in the source code that you may want to fix first!).

Screenshot (5391)
Figure 11: Unsafe context code compiled successfully and application runs. No code in unsafe context, just for demonstration. 

Good to this point, I guess.

5. IntelliSense in MonoDevelop

Just a quick overview of IntelliSense in MonoDevelop for C# programmers. The IntelliSense feature is very friendly feature, in MonoDevelop for C# programmers as it helps them to:

  1. Write long codes, shortly.
  2. Provide suggestions based on current context and the APIs and references selected.
  3. Show errors and warnings.
  4. Show the list of constructors available to the developers and their description.

However, basically, IntelliSense works and shows the code API suggestions, like in the case of a Console.

Screenshot (5393)
Figure 12: IntelliSense showing code suggestions plus the description of the suggested object (functions are also considered to be objects).

You can see how powerful this feature is. It suggests the programmers with the possible candidate for the function or object and also describes the object to them. Share the overloading of the functions and also gives a brief summary of the function. It is deemed helpful in many cases. However, most of you are already aware of these features in your own IDE as every IDE supports this feature.

Finally: A Visual Studio fan? Like me?

If you are a Visual Studio fan, then chances are that you are also not going to enjoy the default Linux look and feel of the IDE and the code structures. Trust me, I also didn’t like it and I wanted to change the look and feel of the code blocks at least because the code was really hard for me to read and understand.

Screenshot (5385)
Figure 13: Default code and syntax highlighting in MonoDevelop.

You can edit the settings in the Preferences window. Find the Preferences window under Edit header and then chose the syntax highlighting.

Screenshot (5386)
Figure 14: Opening up the Preferences in the Edit category. 

You can then find the settings for the syntax highlighting and select Visual Studio there. That would set up the code and syntax highlighting as per Visual Studio look.

Screenshot (5384)

This would then change the theme and you would get the same syntax highlighting as you had in Visual Studio.

Points of Interest

Well, finally I finished up this post, in which I have covered the quick and helpful material for C# programmers in MonoDevelop. Actually, there are plenty of tools and services available to C# programmers in MonoDevelop but for this short guide, I am going to write a few of them and the ones that I find handy in many cases.

I will post a few other posts discussing the features of MonoDevelop for C# programmers, and however, I will also publish a book collective of all of these features and other tips for C# programmers, soon.

Do let me know what you think is missing, or what you think I shared and you didn’t know of. Looking forward to your replies. :)