Tag Archives: exception handling

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. 🙂

Advertisements

What is a null error in code Execution

In my past few years of experience in coding I have faced many times the exception for passing on Null values. Due to which, the compiler or the machine throws this exception out to the screen.

System.NullReferenceException

Actually, many times this case has been discussed by other professional developers and part-time developers and they’ve provided the solution to this many times that I think, if you just close your eyes and go for the solution, you’ll find it on the very 3rd web page for the tutorial websites.

System.NullReferenceException is the exception raised when you try to dereference a null object. Read the post for more information on that.

What actually this error is?

This error occurs, when you’re passing on a null value. A null value means that there is actuall no value in this variable. Its not even a zero. String is the major case for this exception because other variables sometimes get a zero value, and hide this error. Arrays give out this error, when they’re empty. So in general, anything that has no value, is called to have a null value.

Null means that the object doesn't exist.

Null means that the object doesn’t exist.

If you read this MSDN post, you will get the understanding of the concept of null, how they’re created in programming, how they’re a cause of an error in programming.

Why does this error come up?

This error generally comes up, when you’re trying to pass a null value as an argument (parameter) to a method (function) that needs an active parameter to work on. When the parameter being passed is empty, null it throws this error. Telling the developer that the variable that he passed is zero.

You can take the example of a shopkeeper. You ask him to give you a packet of biscuits, but you don’t pay him. What would he do? He’d shout at you like, ‘Hey, you didn’t pay for the biscuits!’. Exact is this thing. You don’t pass any value and the compiler complains to you in this manner, telling you that you’ve provided him with nothing.

In programming, many functions or properties accept an argument to work on. For example take an example of the following code,

int myVar = null;

// use the myVar in some methods etc

Once this code executes, the myVar is more likely to raise the NullReferenceException in your program execution.

Example of NullReferenceException being raised.

Example of NullReferenceException being raised in an application. Object reference not set to an instance of object means that the reference does not exist.

Empty lists, empty strings are an example of objects that might trigger a null reference exception in your software applications.

Update — Object reference not set to an instance of object

I wanted to update the blog post in order to add another possible candidate to throw this exception. Although the above conclusion and explanation is correct, the null exception is thrown if the object you tried to reference doesn’t exist. But, in .NET framework (or perhaps in other frameworks also) you would usually stumble upon a condition when you will see the message of the exception to be, “Object reference not set to an instance of object“. This error means that there is a type-mismatch. Now, there are commonly two problems which might cause this

  1. The first candidate is discussed above; doesn’t exist!
  2. Type mismatch

The second type is when you try to reference the object which is not of the type expected. A possible candidate to such type is child-object of the same class, expected one but got the other and so on.

How to handle this error?

There are many ways of doing this. You can either use a try catch block to see what is the error and then handle it. You can either use a simple condition operator (if else, in this scenario) to detect the value and then do respectively. Or you can use your own idea to check the value is not null. Or you can even prompt the user to enter the value, otherwise don’t trigger the function at all. Or…you can do any thing.

Usually you handle all type of exceptions in your software, to minimize any possible condition that would stop the program execution and would break the application causing a bad user experience.

Here are a few samples for that,

Using a try catch block

A try catch block is a simple block of code, which executes a block of code in the try part and if there is an error in the code, it passes that error to the catch block for the developer to handle it in a User Friendly manner.

try 
{
   // your source code here...
   // that would trigger the exception
} 
catch (System.NullPointerException e) 
{
   Console.Write("There was a raised error in your code.");
}

In the above example, the catch block would execute if the variable being used was empty. If there would have been some value, the array would have value and thus preventing the error. Somehow, even if there is an error in your code, the application won’t break but will show an error message to the user. Which are helpfull for creating enterprise softwares, where softwares load a lot of data before creating the UI and loading to let the user start using it.

This MSDN post shows the concept of a try catch structure in programming.

Flowchart for a try catch structure is,

Exceptions are only caught using try catch block.

Exceptions are only caught using try catch block.

if else Block 

This block is basic block of the conditional operation. It checks for a value, and executes either one depending on the true or false result of a condition. It is pretty handy and short for those who don’t have to work with errors but just with values and condition.

if(something != null) { // check for value null
  Console.Write("Not null! String is " + something);
} else {
  Console.Write("Whoops! Null exception.");
}

See, this was pretty easy to handle. Using this structure, you allow the user to do what ever he wants to do. But you move down to the critical stages only if the user has provided enough details for the software to work on.

This if else block check for the value, if the condition meets (the value is provided) then it will execute the code otherwise the second blocks code would be executed.

Still remember, that if else blocks do not prevent any error chances if just checks for the value. It is not a good approach to minimize the null reference exception using an if else block. But programmers usually use it instead of try catch. But the best method of catching exceptions of any kind is to use the try catch block. It allows you to capture all of the exceptions that are raised in the application and do programming according.

This MSDN post explains if else structure.

Flowchart for if else block is as,

If else is just used to check a condition.

If else is just used to check a condition.

Remedies

Now there are some other ideas and logics to work with the code and prevent this error from happening. One of them is to always ask for the value and then continuing, if user doesn’t provide the value, keep him prompted that once he adds value only then he can use that particular feature and all that stuff. Otherwise just to prevent the error don’t show stuff to the user.

For example, the following UI is useful to get the values from the user. Until he doesn’t provide any value, either continue to how that error message or just try to disable any button or control that would trigger the function to get the values from the controls and work on them

Disabling the Button is a better User Experience as compared to showing an Alert Box. Always look for the better UX.

Disabling the Button is a better User Experience as compared to showing an Alert Box. Always look for the better UX.

Minimizing the Error (Exception) in Web and Software development

Sometimes we create a code to execute for us. Let’s say, we create a calculator app. In which we have many classes; which include data and methods. Each class has its own specified set of data and methods on which it works.

So, now that you’re having a class of Calculator, and it has some data as value1 and numerous methods. For example you’re having something like a Mathematics class and all of its methods. I won’t use any of the methods that is defined inside a language, because this tutorial is not only for ASP.NET, but is also applicable, to all other programming languages too. Such as Java, C++ and some other Object-oriented languages. I am not aware of PHP, if it applies, do let me know.

@{
  var calc = new Calculator(); // create an calculator class object
  /* variable declaration */
  var val1 = 30;
  var val2 = 15;
  /* expressions and all other activity here... */
  var result = 0;
  result = (val2 * 2) - val1; // we know its gonna be 0
}

Now, lets continue. We have a simpe program, to calculate the result from these 2 provided variable. Please note that this code was for those, who are using ASP.NET, for those you might be using Java the above code would be changed to the following:

public class fileName {
  public void main () {
    Calculator calc = new Calculator(); // create an calculator class object
    /* variable declaration */
    int val1 = 30;
    int val2 = 15;
    /* expressions and all other activity here... */
    int result = 0;
    result = (val2 * 2) - val1; // we know its gonna be 0
  }
}

Ummm, why hate C++? Here is the code for that too:

int main () {
  Calculator calc = new Calculator(); // create an calculator class object
  /* variable declaration */
  int val1 = 30;
  int val2 = 15;
  /* expressions and all other activity here... */
  int result = ;
  result = (val2 * 2) - val1; // we know its gonna be 0
  return 0;
  /* can use void to prevent the return line */
}

Now, you might have come to know about what was done here. There was a simple subtraction, now the user might want to get another result using a division method. Such as:

var some = 2;
var res = some/result;

Boing! Here you get an error, which is known as Exception in the language of Programming. These are the errors that the are generated on the go. In this case it is:

 System.DivideByZeroException

There are many other Exceptions like this, which are annoying. In Web development, they are shown to users which are annoying and are not that much user-friendly. Secondly, in the Software development, these exceptions can break the operation and close the entire software. Too much annoying for the user, that he might uninstall your app.

To control these, you use a block that is known as try catch block. In the try section you write the code to be tried by the Compiler or the machine and in the Catch block you tell compiler what to do if an exception occurs. For example

try {
  /* all your code here to be tried... */
} catch (Exception e) { /* catch all exceptions.. */
  Response.Write("Following error generated: " + e.Message);
}

This way, you can check if any exception occurs and you can do anything related to it. You can show him an error popup, that might be less annoying or even sometimes helpfull too. You can just say: ‘Sorry, you cannot divide an integer by a zero’, instead of ‘Exception detailed CSxxxx: System.DivideByZeroException, blah and blah and blah’.

Try some other codes and tell me where I might be missing some information.