Tag Archives: server-side

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

Where to start from?

Many new developers ask the question to themself and to other fellow developers. The question is simple, for me and for old developers but, it is not easy for the new ones. Question is, ‘Where to start the journey?‘. I had the very same question when I started the journey of development.

I first became a Web Developer, I learnt HTML basics and CSS basics at w3schools.com, but I won’t recommend that website to others. They do have an editor and show some of the code. But they’re not good at explaining the code. They just explain that this code would do this. But not, why this code would do this.

I would recommend using Mozilla Developer Network, if you need an editor (currently, Mozilla doesn’t support this feature. If, when you’re visiting this page, Mozilla adds this, comment please) to test your HTML knowledge, you should go with any online text editor like jsfiddle.net. Otherwise, you can even use your very own NotePad to do this. Here is the process for that

  1. Open the Notepad in the Windows, or any other OS. Just make sure you can write the text in it.
  2. Write the HTML codes, make sure, you’re having the HTML elements properly opened and closed.
  3. Saving the file. Here is the main part, just write the file name and add the format of html or htm, like this
    fileName.html

This would create a Browser file for you. Once you click on it, browser would load the file and will show the HTML content to you.

Pretty easy right?

Once you’re good to go with the HTML thing. Try creating something. Like a personal landing page, using all the HTML elements and other stuff like that. After this, you should go for a server-side language and Install the Softwares required and all that kinda thing. I think I had that covered in the other page.

Dynamic Content on a Website

Sometimes you have to show a lot of content to the user, but don’t want to create multiple pages for each of the object. For example, if you were a shopkeeper or a baker or cook. You might not want to create a seperate page for cake.html, cookie.html, chicken-soup.html. That is pretty sick right?

That’s where you use the Query Strings or the Url Data. You just append a data to your URL, and on the server-side, you use that data from the URL, and change the content on the web page. That would be just like, changing the switch from ON to OFF.

Let’s continue our example. If you were the developer of your website for your bakery. You might have to write the code in each of the page. And at the same time, you might to make a new page if your bakery gets a new item. Then your file system would have been like:

  1. Default.html (or index.html)
  2. About.html
  3. Contact.html
  4. Order.html
  5. Cake.html
  6. Cookie.html
  7. Apple-pie.html
  8. Juice.html
  9. …etc

But, you can reduce this to just one page. Yes! Lets change the File System to this:

  1. Default.html (or index.html)
  2. About.html
  3. Contact.html
  4. Order.html
  5. Item.html
  6. …etc

If you’re using ASP.NET Web Pages, that we’re using since the beginning. Then you can try this code out, you will find it really simple, handy and amazing.

The example URL would be like: http://www.example.com/item/item-id-or-item-name

@{ 
   var item = UrlData[0]; /* get the urldata */
   var content = "";
   if(item == "somevalue") {
     content = "Cakes are good!";
   } else if (item == "someothervalue") {
     content = "Cookies are fresh!";
   }
}

<div>@content</div>

Now, I will explain the code, the code takes the URL data of the page, you must keep a note that the content placed infront of the page name can be accessed. In the example we had:

http://www.example.com/page-name/url-data-content-here-infront-of-page

Then I used the ASP.NET to get the first part, note the [0] first parameter after the page name. And then used an if else block to show the dynamic content depending on the item-name.

Lets do this code with out own example:

http://www.example.com/item/cake/purchase

@{
   var item = UrlData[0];
   var action = UrlData[1]; /* notice the paramter */
   var response = "";
   var content = "";
   if(item == "cake") {
     content = "Cakes are good for birthday party!";
   }
}

<div>
   <p>@content</p>
   @if(action == "purchase") {
     <a href="buy-item/@item">CHECK OUT</a>
   } else {
     <a href="item/@item/purchaase">PURCHASE THIS</a>
   }
</div>

This is a sample, you can see that the code would execute and would check for the URL, and inside the URL it would change the content of the Website. You can have as many URL parameters as much you want and they are better to read too. You can add actions, such as feedback, purchase, contact email sent etc.

How to interact with File; File System

Every website on our Internet uses a File System, where the user sometimes gets access to write the data, as everyone has some access to read the data. Lets get the common examples.

For beginners: What do you think read/write permissions are?

When the user is being provided read permission, it means he can read all the files; for example, he can view all the text files (.html, .css, .js etc). Which are required for a user to visit and surf the website. Let’s say Error Code 403 is one of these, any error code that starts with a 4 (403, 401) is an error; which means the users will never get access to these files or directories untill or unless webmaster allows him/her!

Now, lets cover the write permission. This permission is granted to the users which can edit, update, or upload new data to the server’s file System. For example, you might use some service which lets you share your images or text data (For example, Facebook, Google+, Tumblr., WordPress etc..). Now these websites allow their users to read (you know what read means now) and write some data (write = upload, update, delete, and other of this kind) to the server. This can be done on a Database. Which we will cover in future, but for now!

Read: To read the files present on the server, where we can easily access the files by just giving a virtual link to the file.

Write: To let the users alter the current file System data. To let him upload, or delete the files present on the File System of the server.

Coming to the point

When you select a file in the form, the basic idea for them is to provide you with a beautifull form, where you are asked to select a file, which indirectly is a

<input type="file" name="image" />

Which is used to select the files and then send it to the server, You will need enctype to convert and encode the data to the type which is best for image and other data upload. Such as

<form method="post" enctype="multipart/form-data">

And so on.

How to access and work with file System

In ASP.NET, its really simple to access and update the files present on the server’s file system. All you need is just a few variables to make all the process simple and user readable.

You remember, how we interact with the form submission by setting their methods to post. We will be using the same method here!

<form method="post">
   <input type="text" name="name" />
   <input type="submit" value="Submit" />
</form>

Now, when this is submitted, all the data (input, select, textarea) is submitted to the server alongwith other data that is inside the current form only.

Now lets handle this data on the server. We will start the IsPost block and read the data from the form and do some stuff in the server.

I need you to do something before that,

  1. Create a folder somewhere, lets say C:\<username>\Documents\filename.txt
  2. Now, you will use this link, and write the stuff!
if (IsPost) {
   var name = Request["FirstName"];
   var Data = name + Environment.NewLine; // new line there in the file..
   var FileToSaveOn = Server.MapPath("write the link to the file that you created here..");
        File.WriteAllText(@FileToSaveOn, Data);
}

Now go to the file in the Documents of yours. You will see the data written in the file.

Retry the whole process by changing the variable name to understand how they interact, try to change the code to get the information about how you can change and update the code and make it usefull. There are some other types of the File property too. You can use them to delete, update or create files too! Example are:

File.AppendAllText(); // this will update the file

There is just a slight difference between AppendAllText and WriteAllText, and its that WriteAllText will remove the previous data and then write the current data only. AppendAllText will keep the previous data and add this data at the end of the file. Pretty nice huh? 🙂

File.Exists("link to the file"); // checks whether the file is available or not..
File.ReadAllLines(); // reads the data in the file..
File.Delete(); // deletes the file; whose link is in paranthesis..

Its a better approach to first check whether file is present or not before proceeding, because it might give you an Exception, and for a developer Exceptions ain’t good! You should handle these tiny exceptions by using null as value inside the if else block.

In my next post, I will cover the basics of the file uploading and saving.

HTML Forms and their data; Plus Variables

I will assume that you guys are having the tools downloaded. So lets start!

What you currently have is IIS8, WebMatrix3 and some other tools that would run your database, which were installed alongwith the WebMatrix installation.

Now lets continue.

First of all, try to remind yourself of the HTML markup, and the CSS and JS.

Note: We will be using jQuery more often as compared to JavaScript.

So lets continue!

First of all, lets start with a very basic concept.

Using a Form!

<form method="post">
   <input type="text" name="name" />
   <input type="text" name="age" />
   <input type="submit" value="Submit" />
</form>

Now lets try to understand the very basics of it.

This form uses a method=”post” which changes the method of HttpRequest of the current form to POST. Which means that your form values will be submitted safely and directly to the browser. Contrary to this, you might have also used method=”get”; please note that this is the default behaviour of the form too. If there is no method, then it is a GET request.

The very basic difference for a beginner would be; a GET request creates a URL for the parameters of the FORM, and then the Server uses those parameters and processes the Request. Contrary to this, POST will just send the request directly to the server, and not having the Browser of any other ClientAgent involved.

Now lets move to the next part; the input. This is used to let the user write some values in a field, which will be sent to the server then. You can have other type of inputs too, such as radio buttons, checkboxes, email input, even password.

Now, the last and the same type of element used is the input, but with the type attribute set to submit. Which means that this button will submits the current form.  This way, you will get your data submitted to the server within a few seconds. Well actually it depends on what kind of data to send too.

This was the part which was easy to code, now comes the real horror! No wait, don’t worry it will be easier as talking. Lets start.

Since you downloaded WebMatrix, you might have noticed some other softwares downloaded too, such as Web Pages 2 and some other MS technologies. Now its their time to jump in and save the data. How?

Since these are the server-side technologies, you will use these languages to save the data or do what ever you want to do with them. I am sure, you might have downloaded that StarterSite template or any other from the Template Gallery; donot download WordPress or Joomla! templates as we won’t discuss PHP here right now. You require an ASP.NET website.

So, in a new page called “NewPage.cshtml” create a form as demonstrated above. Once you load the page, you will be able to see the form there. Now what you might want to do is to write some of the server-side codes there too. To make sure the data sent to the server gets saved somewhere too, as the user won’t like to keep sending the data when you’re not even saving it.

So here is the code for too.

First you need to create a server-side block for the code to execute.

@{
   // all the codes will be written here..
}

This is the way, a server-side code gets started and an end, in ASP.NET. Now how to manage it.

Use this:

@{
  if(IsPost) { // remember that we have set method to post, 
               //so if method is post then this..now create variables
    var name = Request.Form["name"]; // request the name input from the form
    var age = Request.Form["age"]; // request the age input from form
    // do whatso ever here.. then close the block and done!
  }
}

This block needs to be on the top of the page, even before HTML tag. Since we won’t require it in the client side, so we won’t need to care where it is placed. But remember we need to place it above, so that when the page is being executed all the variables and the code are compiled and are available throughout the DOM. For example:

@{ 
   var something = newThing;
   var newThing = "Hello";
}

This is wrong, because the server will look for the variable something in the current document, but there won’t be anything, since the variable is being declared below. So this would cause an error. To minimize this, each variable should come below its creation such as:

@{ 
   var newThing = "Hellow";
   var something = newThing;
}

You can use as many of the variables you want, and you can name them on your choice. Think like they’re your kids.

You can learn more about saving the form data to a file, reading the file in a server-side, deleting and creating a file in the link below.

http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files