A few points to consider while working with literal string in ASP.NET

This post is for ASP.NET developers, working around with string literals in their applications for displaying run-time or dynamic data to their users. In the past few days, there have been quite a lot of new discussions about efficient way of creating a personalized string to represent the data on the websites.

A few tips that I had in my minds would be possible to share here with other developers of ASP.NET web applications. Note that, I have always been saying ASP.NET is built right on top of .NET framework, so anything that can be developed and run over .NET framework, can be used with ASP.NET too in the back-end. .NET exposes a few functions of the class System.String that are good for use with strings and modification and personalization of the strings.

Response messages

Usually, developers build a few messages to be shown to the clients as a result to their request. You can somehow, write a message (or return a message; possible way of usage in the ajax applications) in the Reponse.Write() function. You can write the string to return the data in the format of,

Response.Write("Thank you for your message " + name + " we will get back to you relating to your " + problem + " and we will have our " + client_name + " working on it right away to give you response in " + max_days);

Above code would work well, show the correct result, and at the very same time would be a good way to show your laziness too. No one uses string concatenation now-a-days. There is a very useful extension in .NET for String class. That is the .Format function. It is overloaded. Now let us consider writing the above code in a String.Format way,

Response.Write(
     String.Format("Thank you for your message {0} we will get back to you relating to your {1} and we will have our {2} working on it right away to give you response in {3}"), name, problem, client_name, max_days);

The second way of doing the same is more efficient. You,

  1. Write the message to print in a very literal (constant) way, with just embedding the parameters in the form a {index}.
  2. You pass the parameters to add to the string as a second, third, fourth and so on number of parameter to the function.

Now once you’re about to write the message in a new way; such as updating the message. You won’t have to worry about the concatenation problems, parser errors; that get raised a lot in ASP.NET applications. You can simply write the message in a string form. Embed the parameters. Pass the values via variables and .NET would take care of the rest.

HTML attributes

Another common usage of building strings is to create the HTML markup of the web applications, on the run-time and then returning the response to the client to be rendered.

Such scenarios, require your to build the HTML markup, in a well formatted way and then sent down to client. For example, this question on CodeProject provides a similar scenario for us to investigate a possible solution to such problems. That is a problem, which gets raised due to a similar problem of string concatenation in HTML elements and attributes.

You should always write the HTML attributes in a very similar way, to avoid concatenation, and making a use of variables and the String.Format() function. An example code can be the following one (the code from the question).

Response.Write("<script language=javascript> 
                    alert('"gk_szEnter_Value_Error_Message"'); 
              </script>");

The above code has a problem of attribute, well can be handled, but another major problem is the concatenation of the string by a variable. Which required him to add this value using a + operator but didn’t so caused a problem.

This could be possibly minimized by using the format function, in the following way,

Response.Write(String.Format("<script>alert('{0}');</script>"),    
                              gk_szEnter_Value_Error_Message);

Now the above string would be created as it is, but the parameter would be filled by the value passed. This now avoids any error of concatenation-type and so. Secondly, for HTML elements like image element, you can create that element in a way,

// Notice the single quote in the strings; whichw ould be converted to double.
String.Format("<img src='{0}' alt='{1}' />", image_source, alternate_text);
// which would yield
"<img src="~/value/of_image_source.png" alt="value of alternate_text" />"

These methods allow us to efficiently create strings. This code lets .NET framework handle the rest of the problems.

A tip for ajax developers in ASP.NET MVC framework

Download the sample project from Dropbox.

This is another quick blog post for the ASP.NET developers, who’re using ajax (or are going to use the ajax in their applications for async calls for the data to the server), and might be getting confused in the View-part of the MVC pattern. This blog post, would try to tip them up with a simple method of creating ajax functionality in their applications, and how to get the confusion about View-part clear. The background to this post is a question, that arose, of how to use the ajax to get the data in ASP.NET MVC framework. Although that was a simple task, but I know new developers get into trouble in making the logic, that is why I am writing this blog post, to explain the core-concept of the behaviour.

I will also be providing a sample code, that you can download and test in your application. This application would be a simple “Hello world, using Ajax in ASP.NET MVC” application. You can after that, make this application complex as per your own requirements.

Getting hands dirty in some ASP.NET code

First stage would be to write the back-end code for our application, which is the ASP.NET MVC application. Wait, the first thing I want to elaborate here is that ajax requests don’t usually require you to send entire HTML markup, to be rendered. Usually, ajax requests are used to download just a few details about the user, such as their name, their company name, or a little message such as success message for the process user has started. That is why, sending entire HTML markup would take a lot of time, and network size, by sending entire XML tree as HTML markup.

That is why, I am going to not-create any View in this project. But I am going to work with just a single Controller. That controller would be used to perform all of the actions, and after the controller has been made, I am going to use the Route mechanism to allow custom URLs in our application; which do not map to our actual HTML files on the application set up. Don’t worry, as the application would build up, the concept of this paragraph would start to get some gravity and you will understand it how did I do and what you would do in order to create your own Ajax running ASP.NET MVC application.

Note: If you’re unaware of the ASP.NET MVC framework itself, I force you to please go and read my other article that focuses on the ASP.NET MVC framework itself. In this blog post, I am not going to explain any concept about the framework itself, instead I am just going to simply swap things up and explain the ajax and ASP.NET MVC part. So, it would be better if you move on to that article and first understand the underlying concepts about Controller, View and Model (that makes up the MVC part of the ASP.NET MVC framework).

First of all, let us create a Controller. To create a controller, you can get some help from Visual Studio, click on the Controllers folder and Add Controller to it. Name it, what so ever you want to. I named it as AjaxController; to specify that it would control all of the ajax requests over HTTP protocol. Once that has been done, you can create your own action methods that would response to your own personal functions. I didn’t bother creating any complex task, instead I just simply created a function, named it as “CustomAction”. It would be used as the URL to our ajax handling web page.

Inside that page, you would write the following code, to handle it and provide the result to it. Like simple C# application, the functions can have any return data type and thus, in ASP.NET MVC application we can, instead of a View, return a string (or any other data type object) that would be sent down to the client as the response to his ajax request. It would be much simpler, and much shorter in structure.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AjaxRequests_in_ASPNET_MVC.Controllers
{
   public class AjaxController : Controller
   {
      // GET: Ajax
      public string Index()
      {
         return "Not allowed";
      }

      // Our custom action, URL would be /ajax/customaction
      public string CustomAction()
      {
         // We're going to return a string, not a view.
         return "Hello world, using Ajax in ASP.NET MVC application.";
      }
   }
}

The above code would return a string, that can be then used as a response and rendered into the HTML or done what-so-ever with it.

Now let us change the routes to actually let the application run without having to use a web page that is a View inside the Ajax folder in our Views folder. Open the App_Start folder, and inside there open the RouteConfig file, and inside it. Write this new route.MapPath() function.

// Create a new route, set the controller to "Ajax" and the remaining would be the Action
// Note that there are no Views in the Views folder to map to this location.
routes.MapRoute(
   name: "AjaxController",
   url: "Ajax/{action}",
   defaults: new {controller = "Ajax"}
);

Now this code would create a routing scheme in your application, and is able to let your application run without actually having to have a specific file at that location to run and handle the ajax request. In the above code, I am using the URLs of the type “/ajax/customajax“, in this URL ajax is a constant string value, used as a path, and then the customajax would be the action of the controller. When this URL would be called, ASP.NET would execute the CustomAjax action of the controller, and would return the string result inside the function.

Performing the ajax code

The ajax code for this project is simple jQuery code to create an async request to the server, to download some more data. But before I share the code for the ajax request, I would like you to make a few changes in the _Layout.cshtml file of your project. The change is to include the jQuery library in the project, so that in the web page you can use the jQuery (because we will be using that layout). Add this line of code to your HTML markup’s <head> element.

<script src="~/Scripts/jquery-1.10.2.js"></script>

Now that the jQuery has been added to your HTML DOM, you can use this library in other pages which has this page set as their layouts, to make use of the jQuery syntax and other objects. I will be using the ajax.

The following code depicts the code used for an example ajax request,

$(document).ready(function () {
   $.ajax({
      // The URL
      url: "ajax/customaction",
      // If the request was successfull; which will be, if it is not successfull check for errors
      success: function (data) {
         // Alert the data; it would be "Hello world, using Ajax in ASP.NET MVC application."
        alert(data);
      }
   });
});

Now once this code would run, it would try to make a call to the URL specified, in the above section we discussed how ASP.NET would handle that request using the routings and action methods, and then would return a single string value. It would finally alert the user with the string that would be returned. That would be a single ajax running application, which would return simple plain message to the user without any complex and large sized View.

Points of Interest

ASP.NET MVC framework can support the ajax requests, just like any simple website would.

You can use the routings to define your own custom URLs. You can define the paths that you want to use, and the controller or action patterns. You are not required to always have a view being returned to the user. Sometimes (if you want) you can also send any kind of data (which in turn would be serialized to string for transmitting).

Overview of DateTime object usage in ASP.NET websites and web applications

This blog post is meant for ASP.NET website and web application beginners who are striving their way through learning processes and want to build their own ASP.NET websites or web applications which makes use of real-time processes and/or some basic stuff like user profiles where they would be using some code to display the age of the user of whom profile is being viewed. I will be giving an overview of the DateTime object that would be used in ASP.NET website (so please make up your mind, that I am not actually talking about the DateTime object itself, instead I am going to talk about the procedures that will be taken in order to create a better user-interface for your website, so you can categorize this blog post as a front-end developer only post. If you’re interested in learning about the DateTime object, or wanted to learn about it and were redirected to this web page, then you’ll be wasting your time reading any further, please go to this article of mine that explains the DateTime object in .NET framework) and how you can use different methods and server-side codes (I will be using C#, you can chose your own) to use the objects to provide the data for your users and to build the user-interface that makes use of date instances, like age calculator, calender applications etc.

What might be the use of DateTime object?

Since ASP.NET developers are unaware of the actual processes taking place in the back end, because of awesome-ness of the ASP.NET framework, usually the new developers are left in dark of what actually these objects and functions are. The major thing and the major problem in this process is the usage of the keyword “var” in the ASP.NET web applications. Although it leaves a lot of not-required code behind (as in the second code line) but still it does’t allow new developers to understand the concept of “variable declaration“.

var dateTime = DateTime.Now;

// is same as

DateTime dateTime = DateTime.Now;

I had the same problem in the beginning. I didn’t know that each object must be saved in its own data type, and that is why I was unable to solve a problem where it said, “Unable to convert type right-value to left-value.” and that is why I thought it must be noted here, that no wonder ASP.NET is being used as a framework for web applications and there is a lot of abstraction in .NET framework and the ASP.NET, ASP.NET provides different assemblies as compared to those provided in the .NET framework and thus it usually feels like the code just runs.

In ASP.NET, DateTime object is used to represent different elements in HTML which require some data that would be better represented by the DateTime object, like a calender application, although you can write a loop for 31 days, but who wants to when you’ve got a structure to take care of that for you?

DateTime is a struct in .NET, it is not a class. See MSDN for more specification. There is a different between them both, one is value-type and other is reference-type; class is reference-type.

Similarly, you can perform different other tasks using DateTime object, such as finding the age and all other such processes. I will be explaining the concepts of finding the age, and the code required to complete the process in this blog post later. Until then, it is just a few scenarios that you might want to accomplish using DateTime object. Sometimes, your user wants to edit the way he gets to see the date on your application, the default machine date would be displayed as month/day/year, but people here from Pakistan are more familiar with day/month/year, you would have to either define multiple modules for that. Or, you can easily just use the DateTime object and display the dates in different formats that the user wants.

I would show how to pass simple string-like formats to the objects, to create their string notations. This would help you in different scenarios, such as fetching the user-friendly formats from database or other data source etc.

Using the DateTime in ASP.NET applications

Although ASP.NET applications are now using the .cshtml (or for VB.NET developers .vbhtml) pages which come embedded with all of the required assemblies already included into the file, for you to simply use them without having to reference them all one-by-one such as System and a bunch of other ASP.NET-required assemblies, but still you can make use of the .NET assemblies by using them as you would do them in any C# application. DateTime is found in the System namespace, so no further reference is required. You can use the DateTime object directly in the web page. Let us create our first module.

Calculating the age of the user

Of course for the user’s age, we’re going to use a DateTime object, to get the year and then the month and date of the user. I can’t say about the old days, but yes, you can possibly do that using three different integer values too; one for year, month and day. But since you have got the DateTime object you can easily just use this object and let the .NET framework handle the rest of the things for you.

A user’s age is the total days (in .NET framework I am talking, because there are no Years in .NET, just Day member) the member has lived on the planet, that started from the day he got born, or you can add some extra precision to the instance, by adding the hours, minutes and seconds for when the person was born. To calculate the age, you would subtract that date (birthdate) from the very now instance. In .NET framework, you can get the current instance of the time by using DateTime.Now, it is a static member, so you can get this value without having to create a new instance. Now let us write the code to calculate the age of the user. Suppose, I was a user, I would do it this way.

Did you know: A year is made up of 365.25 days, that is why there is a leap year after every 4 years.

/* -------------------------
 * Age finding code here... */

// Create a new object
var dateOfBirth = new DateTime(1995, 2, 2);
// Get the today object
var timeSpan = DateTime.Today.Subtract(dateOfBirth);
 
// Now let us stylize it a bit to make sure we get enough details.
// Divide the days by 365.25; make years
var age = (int) (timeSpan.TotalDays / 365.25);

This above code would find the age for the user (note the 356.25 in the division operator, if you would use the 365, then the age would be a little more than the real one). For me, it gave me 19; well that is my age at this instance of time, I might be elder when you are reading this blog post.

Age calculator. Provides the age of the user by using a DateTime object.
Age calculator. Provides the age of the user by using a DateTime object.

I donot need to show the HTML code, that was used, everyone knows this basic code to render the data in the HTML form.

Finding the total time spent

Usually, there are some scenarios in which developers want to find a time span which has passed for some other instance of time. Like, how much time has elapsed since last meeting, or how much time has passed since the last presentation etc. In such conditions, .NET framework has introduced an object TimeSpan, which is used to display the actual time span between two datetime objects. We all know the difference between two objects is found be subtracting the later one from the first one, the result in the case of DateTime objects is a TimeSpan object.

Let us take another example of this case, we will take a date (no longer than a day) to test the hours, and another date (no longer than a year) to test the days that have been passed since that particular date.

/* -------------------------------------------------
 * Code for time spans for finding the elapsed time */

// Create instances
var preTimeHour = new DateTime(2015, 2, 10);
var preTimeYear = new DateTime(2014, 8, 29);
 
// Get the time elapsed for these times
var elapsedHours = DateTime.Now.Subtract(preTimeHour).Hours;
var elapsedYear = DateTime.Now.Subtract(preTimeYear).Days;

The above code would find the values that we’ve appened (.Hours, and .Days). The following output was printed in this case (in my instance of time; yours would not resemble).

These dates and their results depend on my machine's time, the results on your screen would be different.

These dates and their results depend on my machine’s time, the results on your screen would be different.

Another similar scenario

There is another similar scenario, like we see on different social platforms that the time of the social activity is shown, in a format like “<variable> minutes ago”. That is the similar thing above discussed, but a slight difference. That is, that in this case now seconds would be involved, to set the precision for the actual time that the activity took place.

Tip: Do not use the Seconds member of the TimeSpan in this case, use the TotalSeconds. TotalSeconds would return the total number of the seconds for the time span, Seconds would only return the seconds part of the current TimeSpan notation (0-59 only). 

Let us take a few examples into consideration and see how .NET framework would let us know of how much time has been consumed since that time instance.

// Create a new generic list instance
var list = new List<DateTime>();
 
// Add a few instances to the list
list.Add(new DateTime(2014, 2, 2));
list.Add(new DateTime(2015, 1, 19));
list.Add(new DateTime(2015, 2, 12));
list.Add(new DateTime(2015, 2, 12, 1, 0, 0));
list.Add(new DateTime(2015, 2, 12, 0, 0, 0));
list.Add(DateTime.Now);

Now let us see, what did .NET render on the screen in the browser by using these instances. In the HTML markup, I wrote another code, to find the difference of the seconds. I am going to share that HTML markup (in Razor syntax) that you would be interested in reading in. Give the following markup a look,

@foreach (var dateTime in list)
{
   // For each of the instance of the DateTime, check how much time has elapsed
   var seconds = (DateTime.Now - dateTime).TotalSeconds;
   <p>
      The time that has elapsed since @dateTime.ToString("MMMM dd, yyyy hh:mm:ss") is 
      @if (seconds < 1)
      {
         // Zero seconds, hopefully that DateTime.Now object
         @:zero seconds, thus <i>just now</i>.
      }
      else if (seconds > 0 && seconds < 60)
      {
         // Seconds are greater than zero but less than 61 (minute)
         @:@seconds seconds.
      }
      else if (seconds > 60 && seconds < 3600)
      {
         // seconds are greater than minute but less than hour
         @:@(Convert.ToInt16(seconds / 60)) minutes.
      }
      else if (seconds > 3600 && seconds < 86400)
      {
         @:@(Convert.ToInt16(seconds / 3600)) hours.
      }
      else
      {
         @:more than a day.
      }
   </p>
}

Now, that above code block would find the actual time that has elapsed. The only reason that it is a long one is that it had to perform some complex function, to find the actual instance, starting from a second, to minute, to hour and all the way to day. You can add more statements and conditions to test for a month, week or a year and so on. I am not going to create that entire solution plugin here, because it is just meant for a tutorial. The result of the above code was something like this,

Time Span representation of the date.

Time Span representation of the date.

Different formats of DateTime object

In our applications, we need to display the DateTime object in the format that user loves to view. Think of it like a user from America would be interested in reading the date in the format month/date/year, but a user from Pakistan would be loving to read the date in the format date/month/year. Now, .NET framework allows you to format your date into the format that you love it in. That is why, the .ToString() function of the DateTime object is overridden and overloaded to allow you to pass multiple values and parameters to change the format of the date in the format that the user wants.

Tip: Using the method I am going to show, you can use a string value from the database and pass it to the .ToString() function of the object and it would show it in that format.

I created a few string formats for date. That I would be using to display our date in, I am going to use a single instance of the DateTime, to remove any ambiguity from your minds and to show it in different formats by using those formats.

/* -----------------------------------
 * The DateTime ToString() extensions */
var formats = new List<string>();
formats.Add("MMMM dd, yyyy");
formats.Add("MMMM dd, yyyy hh:mm");
formats.Add("MMMM dd, yyyy 'at' hh:mm ss");
formats.Add("MMMM dd, yy hh:mm");
formats.Add("MMMM dd, yy dddd");

Now, the result of this string elements list would be printed, they would be used as format for the DateTime object, for the string notation of it. I used the following HTML, to convert the date into the representative string format.

@foreach (var format in formats)
{
    @:"@format" is used to render the DateTime object as, <b>@DateTime.Now.ToString(format)</b>.
    <br />
}

The result of this (at my instance of time was)

DateTime object different formats.

DateTime object different formats.

This is the blog post, of mine to explain the concept of the DateTime object in ASP.NET website.

Points of Interest

The DateTime object is available in the .NET framework, and can be used in the ASP.NET website. If you use .cshtml then you can make a good use of these assemblies without having to reference them in your file, they’re already there for you.

You can use the DateTime object, in performing different functions in the ASP.NET websites, that require to use a date-like data, such as calender applications. DateTime is an effective way of completing your project, instead of using integer data values for month, date and year etc.

You can pass simple string-data formats for the DateTime notation to convert the DateTime object into your own custom string notation. For more on this, you can read this MSDN document.

Email successfully sent! Success message in the Console application.

Sending emails over .NET framework, and general problems – using C# code

Most of the times new developers stumble upon a very simple task, “sending emails” over .NET framework. Well, I am not going to talk about any language here (C# or VB.NET, Visual C++ you’re also included), I am going to talk generally about the .NET framework and the assemblies exposed by .NET framework for sending the emails, using your own SMTP server’s settings, such as username/password combination, port number and (most specially) the hostname for your SMTP server.

Background

Emails stands for electronic mail, and they are widely used in regular basis for communication, you can send email for sharing text data or you can send your albums over emails easily. Email has been a part of the internet entertainment since a great time, and people use many different email clients, some love the online clients eg. Gmail, Yahoo! etc, and some prefer an offline version of their email clients which use the internet connection to download the emails from a server, such as Thunderbird, Outlook etc.

But the fact is that all of them use the same protocol for transferring the emails over internet network. In this blog post, I will talk about sending the emails over the network, downloading the emails is a totally seperate topic and would have a seperate protocol working on the back end to download the emails from the server.

Sending the emails

Emails are sent using the SMTP protocol, over the internet. It is similar to the Hypertext protocol (not in way of communication, but in a way that is a protocol for communcation). For more on SMTP you can find yourself glad to read the Wikipedia page, I am not going in depth of the protocol here, instead I will just elaborate the methods to send the emails over the .NET framework.

What does .NET framework offer me?

.NET framework (who is oblivious to this one?) has a bunch of cool assemblies for us to work with, using our favourite languages, from C# to C++ and the assemblies in the .NET framework allow us to focus on the quality of the application and the logic, leaving the rest of the low-level coding to the framework itself, including and most specially the garbage collection like stuff and memory management.

.NET framework has a namespace, known as System.Net. This namespace is responsible for the network communication for the .NET applications. But we will be more concerned about the System.Net.Mail namespace, for working with the mail protocol, which exposes the SmtpClient, MailMessage classes for us to easily just pass our data to the objects and send the email using .NET framework.

Creating the module for sending email

Since .NET framework exposes a lot of frameworks to create your applications over, starting from as basic as Console application, to as much user-friendly as Windows Presentation Foundation. Interesting thing is, that in .NET framework same code can be used on the back-end of a Console app and the WPF application. So, the code that would be used to send the email in a Console application is just the same as you would be using for the WPF application. That is why I am not going to specify any framework, instead I am going to use a Console application for our project, for being simpler to be understood, and to focus more on the code instead. You can (in your own IDE) create any kind of application you want, from Windows Forms, to WPF to a web application (using ASP.NET).

Once your application has been created, you can create a simple module (function; not to be confused with the VB.NET’s Module). Inside that you can write the following code, don’t worry I will explain the code in the coming section of the blog post.

// You should use a using statement
using (SmtpClient client = new SmtpClient("<smtp-server-address>", 25))
{
   // Configure the client
   client.EnableSsl = true;
   client.Credentials = new NetworkCredential("<username>", "<password>");
   // client.UseDefaultCredentials = true;

   // A client has been created, now you need to create a MailMessage object
   MailMessage message = new MailMessage(
                            "justin17862@gmail.com", // From field
                            "justin17862@gmail.com", // Recipient field
                            "Hello", // Subject of the email message
                            "World!" // Email message body
                         );

   // Send the message
   client.Send(message);

   /* 
    * Since I was using Console app, that is why I am able to use the Console
    * object, your framework would have different ones. 
    * There is actually no need for these following lines, you can ignore them
    * if you want to. SMTP protocol would still send the email of yours. */
    
   // Print a notification message
   Console.WriteLine("Email has been sent.");
   // Just for the sake of pausing the application
   Console.Read();
}

Voila, (if you added correct details in the above code) you would have your emails sent to destination without any trouble; apart from Internet connection trouble. Now let us dissect the code into pieces and understand what happened, after that I will mention a few problems that arise in programming and cause a havoc for new developers in understanding the entire process, which includes the errors that are raised due to problems in connections and so on.

Explaination of the above code

First step in the code is the usage of the using statement. In .NET framework, you stumble upon different objects that use resources, which need to be disposed off properly, or atleast closed. For example, while a file is created it is required to call the Close() function, before any other process can use that file, similarly some processes requires that you can a Dispose() function on them, to release all the resources. But you can use a using statement, to let the .NET framework take care of all of the objects that need such functions to be called itself. For example, the following code,

using (SmtpClient client = new SmtpClient()) {
   // code here
}

is better than,

SmtpClient client = new SmtpClient();
// code here..
client.Dispose();

due to many particular factors, that I am not going to talk about here. That leaves the discussion about the using statement, you would find a few more deeper detail about using statements on MSDN documentations.

Next comes the SmtpClient object, the SmtpClient is used to create an object that would establish the connection between your machine and the SMTP server you’re using. SmtpClient requires you to set up a few things in it.

  1. Host name, which is the name of your SMTP server’s address in string format.
  2. Port that you will be using to connect, default is 25 (TCP port).
  3. Most of the connections require that you set the SSL active. You can see that happening in our code too.
  4. Credentials are required before you can use a service, most of the servers (Gmail, Outlook etc) require that you send a username/password combination in order to send email from your account using the SMTP protocol. That is why in most of the cases default credentials forward the developers into errors. We use NetworkCredential object (from System.Net namespace) to pass our username/password to the server.

Since SmtpClient is disposable, that is why we’re using it inside a using statement. We’re about to send an email, for that we create an object called MailMessage, and we pass our data to it. MailMessage object can set From, To, Subject and Body fields of an email message and then can be sent. You can see in our example, we’re using the constructor to create the MailMessage object that would hold the data for our From, To, Subject and Body fields.

Finally, we’re sending the email using the Send() function. Interesting thing is, in a GUI framework such as WPF or Win Forms, we should be using SendAsync for the sake of asynchrony in our application that would help us to create a fluid GUI for our application, otherwise the application woul stay stuck until the email has been sent and the control continues from this line of code. To learn more on asynchronous programming, please move to the MSDN link and learn more from there, they’ve got a great content for beginners like you.

A few errors in programming

Generally, there are always errors that developers miss and then tries to confuse himself for “Where did I miss it?”. Similarly, in sending the email and establishing a secure connection, there are usually a lot of problems, some are syntax, some are logically, but I would talk about the connection errors that might be raised. I tried to raise some exceptions myself to share them with you here, for you to understand when these exceptions might cause a problems for your environment.

Usually, the exceptions in the connection are raised only at the Send, or SendAsync method when the SmtpClient is not able to send your email successfully. It can be due to the connection problem, authentication problem or any other problem.

Problems with SMTP hostname

A general problem can be the hostname that you’re passing to the client to connect to, it must be correct and without the “http://“. You might stumble upon such a problem,

Hostname could not be resolved, because it is having "http://" in it. Just pass the smtp.gmail.com, if you're using gmail as your SMTP server. Otherwise you should contact the SMTP developers for their SMTP hostname.

Hostname could not be resolved, because it is having “http://&#8221; in it. Just pass the smtp.gmail.com, if you’re using gmail as your SMTP server. Otherwise you should contact the SMTP developers for their SMTP hostname.

This would be resolved, by making sure that the hostname is correct. Every SMTP provider has its own setting for its server. Make sure you’re using the correct ones. This is the first problem you would stumble upon if you’re going to get any error. Failure sending mail can also be raised if the Firewall is blocking the network. 

Another problem with the SmtpClient is, if you’re not using the correct port number, then the connection might not establish and the worst thing is that there won’t be any exception raised. For example, use 295 port number. The command would continue to execute without any success message or exception. Make sure you’re using correct port number, otherwise use the default TCP port number; 25. For me, 25 port number works always.

Errors authenticating the user

While servers require the correct authentication, it is compulsary that you pass correct and required authentication details to the server. First stage is to enable the SSL over your connection. Mostly, servers close the connection if the connection isn’t over SSL. Recall the code in this blog post, and see the enable SSL command,

client.EnableSsl = true;

After this, you should make sure that you’re using the correct combination of your username and password. If they’re incorrect, server is free to close the connection. The following exception is raised if any of such (authentication) problem occurs in your application.

Server requires SSL connection, or correct username/password combination. Make sure you're not wrong in both of these scenarios.

Server requires SSL connection, or correct username/password combination. Make sure you’re not wrong in both of these scenarios.

Once these problems are resolved, (and other problems don’t come out) your email would be sent, and you will see a success message in your application, mine showed me the following.

Email successfully sent! Success message in the Console application.

Email successfully sent! Success message in the Console application.

Points of Interest

In .NET framework you can use the System.Net and its namespace to work with network. For mailing, you use the System.Net.Mail namespace. System.Net.Mail exposes an SmtpClient object, that uses a hostname and a port to connect to the SMTP server for sending the emails. Some of the servers require SSL connection, and credentials (username/password combination).

MailMessage is the object you would use to send the email, you can fill this object with the From, To, Subject and Body field of your email message. SmtpClient would send this object, you can use Send or SendAsync methods to send email, depending on your framework and the methods that you would use to send the email from.

Exceptions are raised in SmtpClient, when the code reaches the Send (or SendAsync) function. That is because the connection problems occur at this stage, server tells the .NET framework for the errors in sending the email, and the exception is raised. Usually exceptions are raised due to following factors,

  1. Username/Password is incorrect.
  2. SSL is not enabled.
  3. Hostname is not correct, so the SmtpClient was not able to establish the connection at all.
  4. If the port number is incorrect, there is no error message at all. This is a tricky part for every developer. This can be minimized by using 25 (default TCP port).

SmtpClient exposes Dispose() function, that is why it is better to use the SmtpClient object in a using statement, not just as a simple (and ordinary) object to call dispose over later. Using a using statement lets you leave the releasing of the resources to the .NET framework itself.

For those, who are looking for a VB.NET code, you can use the Telerik converter to convert your C# code in VB.NET code (or vice versa).

.NET allows you to use the same code over different frameworks and platforms that run over .NET. Such as WPF, Console app, ASP.NET web applications. That is why, you can use this code above in almost all of your applications, no matter software apps, web apps or what-so-ever client application you’re creating until it runs over .NET framework. Because these assemblies are present in .NET, not in the language itself.

Understanding ASP.NET MVC using real world example, for beginners and intermediate

You can download the sample at Dropbox.

ASP.NET presented developers with a new framework for website development, in which they would easily distinguish between data layer, business layer and the methodology they would use to render these objects on the screen. They called this framework ASP.NET MVC, in which MVC stands for Model, View, Controller.I will elaborate these items in this blog post as well as other objects and technologies I am going to use too. First lets talk about what is MVC pattern itself, and what ASP.NET MVC offers us as compared to other ASP.NET frameworks; which include and are well-known, Web Pages and Web Forms, and all other web-scripting frameworks.

ASP.NET MVC

First thing is to understand the ASP.NET MVC framework itself, once we’ve gotten enough understanding of the ASP.NET MVC framework, then it would be a lot easy for us to understand why ASP.NET team provided us with this framework. In web development, there are different schemes used to create web sites and web applications, which at a minor age don’t seem to cause a problem. Solving a bug might take hours of headscratching and some other help too. It is harder to find the problem that is scripted inside the HTML web page. In these scenarios, it is always found helpfull to seperate your code from your data and from your HTML markup. This would make it a lot easier to find and solve the problem. Because, now all of the code has been seperated and finding the problem at exact location won’t be a harder task. These three fields are divided and make up the MVC; Model, View and Controller pattern for web development.

Actually this is not a pattern, specific to the web development. If you go to Wikipedia’s web page for this, you will find that it is actually a framework used for software development, meaning that it can be applied anywhere, where you want to distinguish between your application’s data link layer, business logic layer and the rendering code.

MVC-Process.svg

The link between these three objects of MVC pattern have been depicted in this image above.

Controller

The Controller in the MVC comes at the last, but is the most used part of the MVC pattern. It is used to work with the HTTP requests, coming from the clients; from the browsers  or from any other application that can generate an HttpRequest (not to be confused with the .NET’s HttpRequest object; but a simple HTTP Request). Each request, when comes, is handled by the Controller and then Controller, according to the request makes decisions to load the data, create the response and then sends the data back to the client.

It should also be noted here, that your Controller acts as a bridge between your Model and the View. Because they, as themself, cannot perform any action. Controller triggers their events and makes them do something, like return data from Model, or to render the HTML document from the View etc. All of the resources and errors are also handled by the Controller. Making it the heart of the pattern, because the response is also sent back from a controller. You can think of an example of a Controller to be the entire Business-logic-layer. The code that is used to run the application’s back-end processing, like creating accounts, managing solutions etc, would make up the Controller section of this pattern.

View

Next comes the part of the View, this is the actual web page that is being displayed to the user. It contains the HTML codes that are to be sent back to the data as a response to his request. Correct, Controller sends this response back to the client, View – its self – doesn’t send this response to client whereas Controllers takes this data, and sends back to the client.

View, can also be created dynamically. As already said, all of the requests are handled by Controller, so any parameter (including QueryStrings) can also be handled by Controllers. Using these parameters, we can generate dynamic Views. So dynamic content in our view, change their layouts or show some other error messages if the data sent is not of our own choice. View, generally depends on the Model that is being used to create the View and these dynamic data objects are capture from the Model (Model is discussed in the next section).

Point to be noted here is that while section-in-action is View, still Controller is playing a vital role for passing the values and for retrieving the data to be sent to client. 

Model

As the name suggests, it is a model of some object. The object in this case is our application’s data. It can be of any type, like extracted from a database; no matter which one, SQL Server, MySQL or MS Access etc, or it can be a simple data that comes from a Reporting, or from a Spreadsheet etc. Model is never shown to the user (actually, the client) because he is supposed to see the data and the results we want him to see, that is why, it is a good approach to keep a great abstraction layer between Model and the user (the client).

Model doesn’t only store the data, it – at the same time – keeps the View and the Controller updated or any change being made to it. Models are designed, just like Controllers and Views are designed, just so that there is no ambiguity between three of them and it  is easy for them to communicate to make the web application fluent. Everytime a change is made, View is update by the Controller, because Controller is informed about the change (this informing event is also raised by Controller; as I already said, Controller handles the events). To store anything in the Model, the user has not been provided with any form that is directly connected to the Model, instead a form is generated in the View by the Controller for the user to fill in. Once the form is filled, the form values are then passed to the model for storing purposes. All kinds of data validations (most special type of which are SQL Injections) can be checked at the Controller level rather than loosing (important) data.

The user must be allowed to interact with Model himself, instead a Controller must be used to connect to the Model to get the data for the user's View that would be shown to him.

The user must be allowed to interact with Model himself, instead a Controller must be used to connect to the Model to get the data for the user’s View that would be shown to him.

Until now, we’ve been discussing the ASP.NET MVC itself, in the next section we will be discussing a real-world example of an ASP.NET MVC Application, and I will show how to create custom Controllers, Views and Models. In an ASP.NET MVC project a user triggers the Controller, the controller then reads and manipulates the requests, Requests the Model for data, gets the data and then Updates the View to be sent back to the client.

Overview of MVC pattern.

Overview of MVC pattern.

Real world example of ASP.NET MVC Application

In this blog  post, I am going to explain creating an MVC application to control your client’s data. For that, I am going to use the Model, View and Controller architecture, so that I can easily distinguish between the data of my application (which would be the data for the clients), code for the requests and responses (which would constitute the controller) and how the data is shown to the users (views of my application). I am going to create everything from scratch, to make every thing understandable for you. For that I am going to start from creating every single  object in my application, every controller, every view and model in my project.

One thing you should think about here is that I am going to use JSON files as data source, because database field has already been covered by the ASP.NET team at its best. I don’t think there is any need to re-write the same thing, that is why I am going to explain how to use anything as your model. If you want to read that one, and want to stick to SQL Server database you can go to ASP.NET MVC’s tutorial website to learn that. You’re right, Entity framework won’t be supported here! That is why I am saying I am going to create everything from scratch, to explain every bit of the MVC pattern for you and how you can create actions that respond to your actual processes, not just to the built-in ones.

Real-life example

Let’s have an example of a simple office, where a person gets different clients, whose name, address is stored. Just to distinguish them all, an ID is also stored. Whether the client is trusted or not, is also stored along with him. Office manager wants to be able to, create new clients, modify the existing ones, and once he is done with them he wants to be able to delete the previous ones. To implement this basic example in ASP.NET MVC, we will start off by creating a simple ASP.NET MVC application. To do so, you can either press CTRL+SHIFT+N, or you can click on File, then New and a Project. Like this,

Creating a new project - in Visual Studio 2013

Creating a new project – in Visual Studio 2013

After this, please select the Web and inside select ASP.NET Web Application, then name it as you want. I named it, ASPNET_MVC_Application. You can use any name that you want.

Selecting an ASP.NET web application.

Selecting an ASP.NET web application.

Then you will be required to make the selections for your application in the next tab. You shouldn’t make any change for now, keep the selected options selected and click Next on this tab.

Screenshot (160)

This would then create your application, with the default content for your application settings. You might see this web page inside your Visual Studio.

ASP.NET MVC read me page viewed inside the Visual Studiom 2013 - application's first run.

ASP.NET MVC read me page viewed inside the Visual Studiom 2013 – application’s first run.

This is the tutorial until creation of the application. This web page is also a sign of success, if you still want to make sure that everything runs, just press the green button (with a Browser’s name on it; mine had Google Chrome) to see your application runs in the browser. In the next section, I will be creating the application’s objects (MVC) and then showing you how they can interact and in the end I will give some tips for making your application better.

Customizing the ASP.NET MVC Application

Once all of the things are set, and your application runs. You can continue to make changes to it, so that it would reflect your own application and not the default ASP.NET MVC application that is a sample. First thing to do is to create a controller which we’re going to be using inside our application to control all of the requests and is going to send back the response (view). How to create views and what would be the model will be covered in coming sections. For now, just make up your mind to understand the Controller in MVC.

Required package: Since we’re going to use JSON data, Newtonsoft.Json package is a very usefull package to use, so before you go any further open your NuGet package manager console (inside the Tools) and run the following command to download and include it in your project. It is required.

Install-Package Newtonsoft.Json

Creating a custom Controller

A custom controller is something that you can use to create your custom controllers for your application, that would handle the requests coming for them and they will provide the user with a view filled in with the data from the model. You can name them as you would like to name them, there is no convention; but just one convention which is to append “Controller” to the name of the class. Controller is a class in real which inherits from System.Web.Mvc.Controller class, making it able to inherit all of the functions and members of the Controller (parent) class. Let us create a Controller. Inside your Source code, there is a folder named as Controllers. If you open it, there would be 3 controllers by default, you can create your own.

Default controllers in ASP.NET MVC application

Default controllers in ASP.NET MVC application

Right click on Controller folder and inside the Add option, click Controller to create a new one.

Creating a new Controller

Creating a new Controller

Give a custom name to your controller; remember to have that Controller at the end of your class’ name. You must create an empty controller, because for the sake of this post we’re not going to use anything built-in but just scratch classes.

Screenshot (170)

We just need an Empty controller, to create our own functions (actions in MVC) for it to handle and perform.

We just need an Empty controller, to create our own functions (actions in MVC) for it to handle and perform.

At this stage, your basic Controller has been created and you’re now ready to customize it. Before we move on to create actions that this Controller would perform. I wanted to remind you about (automatic) changes that were made in your Views folder. What Views folder is about, is – yes, well – self-explainatory but we’ll be talking about it too in the coming section. Right now, there is a new Client (or what ever Controller you create’s named) folder inside your View folder. Now it does start to make some sense, doesn’t it? Every controller has its own particular view to display data for, and each time the request would initiate from client (not our class, but the user of course) the Controller would be used (you can think like an instance of that class would be created) and then the Action of Controller would be checked against (inside the URL; which would then trigger the function of the Controller, which we’re going to create next). Like every class, we can create different functions for our Controllers, which are known as Actions. Let us think what we’re supposed to let our manager do with the client, he wants to

  1. Create a new client – Create
  2. Modify current client’s data – Update or Edit
  3. Delete clients when he has finished the work – Delete

We can use above logic to create our functions for the Client Controller. Open your ClientController.cs file and edit it, to write this code in it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Mvc;

using ASP.NET_MVC_Application.Models;
using Newtonsoft.Json;

namespace ASP.NET_MVC_Application.Controllers
{
   public class ClientController : Controller
   {
      // GET: Client
      public ActionResult Index()
      {
         // Load the data for the client
         var clients = Client.GetClients();

         // Return the view.
         return View(clients);
      }

      public ActionResult Create()
      {
         ViewBag.Submitted = false;
         var created = false;
         // Create the Client
         if (HttpContext.Request.RequestType == "POST")
         {
            ViewBag.Submitted = true;
            // If the request is POST, get the values from the form
            var id = Request.Form["id"];
            var name = Request.Form["name"];
            var address = Request.Form["address"];
            var trusted = false;
 
            if(Request.Form["trusted"] == "on") {
               trusted = true;
            }

            // Create a new Client for these details.
            Client client = new Client()
            {
               ID = Convert.ToInt16(id), 
               Name = name,
               Address = address,
               Trusted = Convert.ToBoolean(trusted)
            };

            // Save the client in the ClientList
            var ClientFile = Client.ClientFile;
            var ClientData = System.IO.File.ReadAllText(ClientFile);
            List<Client> ClientList = new List<Client>();
            ClientList = JsonConvert.DeserializeObject<List<Client>>(ClientData);

            if (ClientList == null)
            {
               ClientList = new List<Client>();
            }
            ClientList.Add(client);

            // Now save the list on the disk
            System.IO.File.WriteAllText(ClientFile, JsonConvert.SerializeObject(ClientList));

            // Denote that the client was created
            created = true;
         }

         if (created)
         {
            ViewBag.Message = "Client was created successfully.";
         }
         else
         {
            ViewBag.Message = "There was an error while creating the client.";
         }
       return View();
     }

     public ActionResult Update(int id)
     {
        if (HttpContext.Request.RequestType == "POST")
        {
           // Request is Post type; must be a submit
           var name = Request.Form["name"];
           var address = Request.Form["address"];
           var trusted = Request.Form["trusted"];

           // Get all of the clients
           var clints = Client.GetClients();

           foreach (Client client in clints)
           {
              // Find the client
              if (client.ID == id)
              {
                 // Client found, now update his properties and save it.
                 client.Name = name;
                 client.Address = address;
                 client.Trusted = Convert.ToBoolean(trusted);
                 // Break through the loop
                 break;
              }
           }

           // Update the clients in the disk
           System.IO.File.WriteAllText(Client.ClientFile, JsonConvert.SerializeObject(clints));

           // Add the details to the View
           Response.Redirect("~/Client/Index?Message=Client_Updated");
       }


       // Create a model object.
       var clnt = new Client();
       // Get the list of clients
       var clients = Client.GetClients();
       // Search within the clients
       foreach (Client client in clients)
       {
          // If the client's ID matches
          if (client.ID == id)
          {
              clnt = client;
          }
          // No need to further run the loop
          break;
       }
       if (clnt == null)
       {
           // No client was found
           ViewBag.Message = "No client was found.";
       }
     return View(clnt);
   }

   public ActionResult Delete(int id)
   {
      // Get the clients
      var Clients = Client.GetClients();
      var deleted = false;
      // Delete the specific one.
      foreach (Client client in Clients)
      {
        // Found the client
        if (client.ID == id)
        {
          // delete this client
          var index = Clients.IndexOf(client);
          Clients.RemoveAt(index);

          // Removed now save the data back.
          System.IO.File.WriteAllText(Client.ClientFile, JsonConvert.SerializeObject(Clients));
          deleted = true;
          break;
       }
    }

     // Add the process details to the ViewBag
     if (deleted)
     {
        ViewBag.Message = "Client was deleted successfully.";
     }
     else
     {
        ViewBag.Message = "There was an error while deleting the client.";
     }
     return View();
    }
  }
}

Done! That was our controller, if you have a look at the code above you will find a few functions, a few ViewBags and a few Views etc. I will explain them in the end, because they’re built-in functions of ASP.NET MVC for the application and which we are bound to use them for application to run. Each time you’re going to create a request to your application to load data about clients, this controller would take action, and will provide with the data that user (in case here, you) want from the application. In the above code Create, Update, Delete and Index are the functions of the class, in MVC application they will act as Actions of the application’s Controller. You will use them to tell the application what to do, when user triggers such a particular action in your application. They’re just average functions in a simple class; which inherits from System.Web.Mvc.Controller.

Creating a custom View

Now that back-end code (Controller code) has been done, and you can now create the Views for your application. Views are used to show the content (data) of your application to the client (user) in HTML markup. Because browser can only render HTML content, we will be using that markup, and Views are used for that. Each controller has its own particular view. One thing to note here, is that to return a View, the name of the View must match the Action’s name. You can put it, like each of the Action (function) in the Controller is meant for a particular View (HTML document to be returned) in the application. We, need four Views, for our four Actions; Index, Create, Update, Delete. To create a View you can click on the Views folder, and create a new folder; but remember, here you don’t need to create any new folder, because as I already said when you created the Controller a new folder was already created with the name of the Controller “Client”. Right-click that folder, and inside the Add click on the MVC 5 View with Layout and click Next to go to the next step.

Creating a new View (with Layout)

Creating a new View (with Layout)

Now name the View, I named it Index because we need a view for Index page.

Screenshot (172)

Now select the layout, layout is applied across the pages (Views) to design them a like. You can use your own views too, but for this I am going to use the default layout. Screenshot (173)

This is the step-by-step method to create the View in ASP.NET MVC using Visual Studio. ASP.NET uses Razor syntax to create HTML pages, which shortens the codes for the developers. Update the code inside this page and write this following code,

@model IEnumerable<ASPNET_MVC_Application.Models.Client>

@{
   ViewBag.Title = "All Clients";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<h3>Following table shows the Clients detail</h3>
<p>You will find their details, as well as other links to other actions that can be performed and operated over the client objects. </p>

<p>You can also create a new client <a href="~/Client/Create">here</a>. </p>

<table class="clients-table">
   <tr>
   <th>ID</th>
   <th>Name</th>
   <th>Address</th>
   <th>Trusted</th>
   <th>Actions</th>
</tr>

 @if(Model != null && Model.Count() > 0)
 {
   foreach (var client in Model)
   {
     // Create the list of these clients
     <tr>
       <td>@client.ID</td>
       <td>@client.Name</td>
       <td>@client.Address</td>
       <td>@client.Trusted</td>
       <td>
         <a href="~/Client/Update/@client.ID">Update</a>
         <a href="~/Client/Delete/@client.ID">Delete</a>
       </td>
     </tr> 
   }
 }
</table>

In the above page’s source code, you will find one new thing. @model IEnumerable<ASPNET_MVC_Application.Models.Client> that is the type of the data that has to be used inside this View; Yes, it is the model being used here. After that it is just simple razor syntax, to create the HTML document (View) and to return to the client (user). The Model object (the one used in the foreach loop) is having the value of what ever is passed for the @model thing.

You should create next three Views yourself (as a test) and write this content to them.

For Create View:

@{
   ViewBag.Title = "Create";
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<div>
   <h3>Fill in the following form</h3>
</div>
<form method="post" style="margin: 5% 0 0">
   <div class="float-left">
     <p>Client ID</p>
     <p>Name</p>
     <p>Address</p>
     <p>Trusted</p>
   </div>
   <div class="float-right">
     <input type="text" style="margin: 1px 0 2px" name="id" /><br />
     <input type="text" style="margin: 1px 0 2px" name="name" /><br />
     <input type="text" style="margin: 1px 0 2px" name="address" /><br />
     <input type="checkbox" style="margin: 1px 0 2px" name="trusted" /><br />
     <input type="submit" value="Save" />
   </div>
</form>

<p>
   @if (ViewBag.Submitted)
   {
     // If the form was submitted
     @ViewBag.Message
   }
</p>

For Update View:

@model ASP.NET_MVC_Application.Models.Client

@{
   ViewBag.Title = "Update the Client";
   Layout = "~/Views/Shared/_Layout.cshtml";
}


<div>
  <h3>Update the following form</h3>
</div>
<form method="post" style="margin: 5% 0 0">
  <div class="float-left">
     <p>Name</p>
     <p>Address</p>
     <p>Trusted</p>
  </div>
  <div class="float-right">
     <input type="text" style="margin: 1px 0 2px" name="name" value="@Model.Name" /><br />
     <input type="text" style="margin: 1px 0 2px" name="address" value="@Model.Address" /><br />
     <input type="checkbox" style="margin: 1px 0 2px" name="trusted" 
          @if (Model.Trusted) { <text>checked="checked"</text> } 
     />
 <br />
     <input type="submit" value="Save" />
  </div>
</form>

<p>
   @if (ViewBag.Submitted != null && ViewBag.Submitted)
   {
      // If the form was submitted
     @ViewBag.Message
   }
</p>

For Delete View:

@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}

<p>@ViewBag.Message</p>

You will find, that in Create view I am not passing any model. That is because, for a View, to have a model is not obligatory. Model is just to allow dynamic content to it, if you don’t want to use any model, fair enough, you don’t have to use a model in every view to create it an MVC application. These are just simple HTML pages, that are being made update-to-the-content by the razor syntax and then sent back to the browser in an HTML markup, for rendering purposes. _ViewStart.cshtml page is used as the first page to check for any layouts. If you don’t want to set any layout for all of the pages themself and want a unique look across the web app, you can set that in this page and it will be applied to all of the pages.

Creating the custom Model

As far as Model is concerned, ASP.NET MVC allows you to use any kind of data (coming from a data source; server or what so ever) to be used as a Model. You can pass the data from the model to the view from the Controller, which will be then rendered as a simple HTML markup and will be displayed inside the browser to the user.

I have already mentioned, and in-case you missed it above, if you want to use SQL Server database as your Model for application, then ASP.NET team has provided a very good tutorial for that and you might want to join them on their journey here. They used Entity Framework for their Actions. In our project, we will be using JSON files and custom created Actions to perform CRUD operations. This would (try to) remove ambiguity in our minds about this MVC pattern and its extensiveness for other technologies and frameworks.

A Model, like a Controller,  is just a class file, that we can instanitiate and get different objects from, when working with a request from a client. A model is a representation of the real-world objects in our own context; which here is the ASP.NET MVC Application. Think of it like there is a Client model. He would have a ClientID, Name, Address and a Trusted as a flag (you should recall our scenario if you have no idea of where these came from). What would you write as a class for this Client? Look at the following class code and have understanding of the Model we’re going to have.

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Newtonsoft.Json;

namespace ASP.NET_MVC_Application.Models
{
   public class Client
   {
     public static string ClientFile = HttpContext.Current.Server.MapPath("~/App_Data/Clients.json");

     public int ID { get; set; }
     public string Name { get; set; }
     public string Address { get; set; }
     public bool Trusted { get; set; }

     public static List<Client> GetClients()
     {
        List<Client> clients = new List<Client>();
        if (File.Exists(ClientFile))
        {
           // File exists..
           string content = File.ReadAllText(ClientFile);
           // Deserialize the objects 
           clients = JsonConvert.DeserializeObject<List<Client>>(content);

           // Returns the clients, either empty list or containing the Client(s).
           return clients;
        }
        else
        {
           // Create the file 
           File.Create(ClientFile).Close();
           // Write data to it; [] means an array, 
           // List<Client> would throw error if [] is not wrapping text
           File.WriteAllText(ClientFile, "[]");

           // Re run the function
           GetClients();
        }

        return clients;
      }
   }
}

A simple C# class file, that would serve our application as a Model. You will find one other major change, which is the namespace this class is location in. The name is having an extra .Models attached to our project’s name. That makes up our different fields. ASP.NET and Visual Studio do these things for us, although they’re not required but just conventions to be followed. Let us create a Model for our application, click on the Models folder in your app, and inside Add click on Class file and name it Client.cs and click Next to continue.

Select a new class file to be created as a Model

Select a new class file to be created as a Model

Screenshot (175)

Name it what-ever-you-want, but I would be using Client.

These were the three major fields in the MVC that are used to create an application. However, there are a few other minor fields that work and run our application, that I will be covering here for you to atleast know how to kick-start your project.

As far, we have covered what is Controller (controls the HTTP requests coming our going to client), what is a View (it is rendered as HTML output in the browser, the response that is returned to the client in HTML markup can be said to be the View) and finally what is a Model (the representation of the real-world data in our application is called a model). Now, we can go and have a look at the classes and objects which run our application. Like all other apps, that run over .NET framework, ASP.NET also exposes some functions for its developers to use, to perform different actions when the app starts, when the app crashes etc. If you open the folder App_Start in your application, you will find a few classes there. BundleConfig is used to configure your JavaScript libraries, ASP.NET also enables the developers to perform some client-side actions. IdentityConfig configures the Identity service (user authortization servicer), but the main file that I wanted to talk about here, which needs our attention too, is the RouteConfig.cs file.

In ASP.NET, you do not need to have a physical path fixed in order for the client to send a request to its virtual location to read it. Instead, you can now create custom URLs to let your users visit your application, without you having to have a specified file at that location. You create different routing techniques, to allow different data values inside the URL to create dynamic web pages for the clients.

If you open up this file, you will find the following code in it, (I am going to use a partial part of the file)

routes.MapRoute(
   name: "Default",
   url: "{controller}/{action}/{id}",
   defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

This defines a route, for your application. It has been named “Default” and has the default configurations for the URL, any URL that comes will be matches against this scheme. First value would match for a Controller second to an action (the function inside the Controller class) and then an optional field (see the default values field). You can change this sequence of arragement, to make sure that the URLs are website and user-friendly for your context.

Every ASP.NET can have as many routes enabled in it, every one will be used but the best possible route would be used, but at least one route must be present for the app to run. Let us now run the app and test, for anything that might need our attention.

Running the application (Optional part; if you want to download and test the app, skip this section)

This application was run over the app named “ASP.NET MVC Application” but I created a new app named “ASPNET_MVC_Application”, there is a huge different between these two, usually only difference is the namespace naming one so if you were following the blog post you might find this a bit of confusion; so my apologies for that. :)

In the beginning, the table is empty.

In the beginning, the table is empty.

Now let us, start adding a few objects; at this instance, let us just take one object under consideration.

Fill in this form and click Save, the application would save this client's information.

Fill in this form and click Save, the application would save this client’s information.

Message showing the success of our operation.

Message showing the success of our operation.

If you go back to the main page of the Client’s directory (controller), you will find a record available there.

Screenshot (149)

Let us, now try to update this client’s value, in the Actions attribute of table, you will find two hyperlinks, they actually are just Actions (functions) of our controller, we will pass (optional) ID of our client to it, and then we will update the value. We will update our value as,

Screenshot (151)

Let’s go back and see if our View now reflects any change.

Screenshot (152)

Voila! It does reflect our change, which proves that a Model updates the View for any new change that we make. Try using the second hyperlink, it would delete the object from the collection.

Screenshot (153)

That was up, for the working process. Now our application runs fine enough, our manager can add clients, remove clients or modify their data as per his requirements. As far as now, this application is running and our clients can visit and use it as per their requirement.

This was a basic overview of ASP.NET MVC application, that contains the Model for our data, View for the users to visit and see and a Controller that controls the HTTP data coming or going to the client.

Points of Interest

ASP.NET MVC pattern contains a Controller for controlling all of the HTTP requests coming, and responses going to the clients. A view for generating HTML web pages, Razor view engine is used for creating the HTML markup from C# objects. A Model is a simple C# class that contains the object’s properties. Each time the application is run, Controller gets the data from the Model and populates the View for the user to read the result in his/her browser.

Every real-world object can be used in ASP.NET MVC application as the data source. To create a model, C# files are used (if you’re using C#, otherwise you would be creating a file related to your language). The properties and members act as properties that you would be using inside your HTML markup for rendering purposes.

You can control what kind of URLs are being used in your application by creating routing techniques. These define the structure of your application’s URLs. You must define at least one route in your application for it to run, otherwise you can define as many as you want.

MVC pattern removes the ambiguity between the data and the code-behind of your application. Your code-behind is now a part of the Controller of your application and is written inside the Controllers. The data is stored inside the Model (actually which is just the representation of the data, actual data is stored in somewhere like a file or database) and the what user sees is written in the View. This way, any error can be fixed as soon as possible without having to worry about any other bug, because every field is now controlled and written in a different part.

Model part of this pattern must always not perform any kind of business-logic, because that would entirely kill the actual purpose of this MVC pattern. That is why, all of the logic code is written in the controller; even the creation of data or the manipulation of data should be done in controller through functions, since user has no connection with Model, it provides an extra layer of safety as the user is totally oblivious to the schema of the database.

ViewBag and the View are special objects in ASP.NET used to manipulate the View (HTML markup), you can pass any member (which is dynamic) to this ViewBag from the Controller, to be used inside the View page (.cshtml in these cases) for rendering; like I did for showing some messages like an error or a success message.

How to connect ASP.NET website to Remote Database for CRUD operations

Download the attachment for this blog post

Introduction

This article is an overview for connecting an ASP.NET website or a web application to a remote SQL Server database. This article also covers what is the Database class inside the ASP.NET library to help the developers. Also, this post also covers how to create the XML notation for the configuration of websites to automatically connect to the database, through Database class objects.

Furthermore this post would cover the basics about CRUD operations over database and how ASP.NET can allow the users to perform these actions over databases using SQL language and send the commands to the database (data source) to load data, edit data, create data and delete the data if no longer required. These actions are generally the short form for: Create, Read, Update, Delete (making up CRUD).

ASP.NET Database object

In WebMatrix, a tool by Microsoft for the web developers to create ASP.NET web sites instantly, there was a special class designed for the developers to write less code to connect and perform other SQL commands on the database connected to their systems. This was written over .NET framework, making all of the SqlConnection class code shorter so that the developer can only focus on the actual command instead of maintaining and sustaining the objects and the memory etc.

Database object lets the users to simply call a function Open and connect to the database to perform tasks like SELECT, INSERT INTO and complete the procedures etc. The actual work in done inside the web.config file where the settings and the connectionString for the database an the server (collectively the data source). The name of the database connection is set in that connectionString node in the web.config file. Which is then used inside the ASP.NET server-side code to open the connections for the database at that connectionString.

An example of this connectionString can be as the following code,

<connectionStrings>
   <add name="MyDatabase"
        providerName="System.Data.SqlClient"
        connectionString="Data Source=.\SQLEXPRESS; 
                          Initial Catalog=MyDatabase; 
                          Trusted_Connection=true" />
</connectionStrings>

In the above code the providerName is the name for the library (namespace) to be used to call operations on this database. Since I am going to use SQL Server, I will use this one. If you’re going to use any other namespace (library) then use that one. Inside the connectionString attribute, Data source is the address for the server, and the Initial Catalog is the name of the database I am going to use. Since I used Windows Authentication, so that is why instead of User ID and Password, I am passing Trusted_Connection as a true field in the connectionString for the connection to my database.

Above connection is simple XML object placed inside the web.config file of your ASP.NET database and provides an attribute for you to specify for your website. The important point to note here is that the actual name of your database (actual database file; SQL Server file) does’t need to be the same as your XML object’s name attribute. Interesting thing in this is, that you can use any of the name inside the name attribute to be consumed inside the ASP.NET connection. But this doesn’t add anything to the security, but just a simplicity for the developers to not have to write entire connectionString everytime they have to write the code. But just to open the connection for the name that they’ve added inside the web.config file.

Using the Attachment

If you’re wanting to use the attachment that I’ve attached to this blog, then you can try first to download it and open it inside your IDE. You might consider creating a new solution and then adding these files to it.

Once done, you’re first required to have a database. You can name it as you want it to have a name, but the schema must be defined as this following schema of the table.

ASP.NET CRUD Table properties

Edit your table to look like this, and name it ‘Products’.

I am using SQL Server 2012, you can use your own version or download the SQL Server 2012 Express for development purposes and inside the Management Studio edit the table as the one above.

Once the table has been created inside your database server. You can add that database connection to your ASP.NET website, as in the connectionString setting above. Once the connection has been made, you will be able to query the database. If that doesn’t happen, then there is a problem inside your connectionString, try changing the properties of the connectionString to make it connect correctly. Possible issues might include passing a User Id and a Password instead of Trusted_Connection because of Database authentication mode and so on, possibly you will get your answers from the database engine (SQL Server; or what so ever data source server you’re using).

Performing operations

There are 4 operations that, we can perform for creating our applications, which include creating objects, reading their properties and data, updating them or deleting them once you’re done working with them.

Reading the data

Reading the data from the server is the most basic and usually the first step in the application’s cycle. You can use the SELECT clause to pass the data from server down to the client.

// Select all the rows
var result = db.Query("SELECT * FROM Products");
 
<table>
  <tr>
    <th>ProductID</th>
    <th>Name</th>
    <th>Description</th>
    <th>Price</th>
    <th>Actions</th>
  </tr>
  @foreach (var row in result)
  {
    <tr>
       <td>@row.ProductID</td>
       <td>@row.Name</td>
       <td>@row.Description</td>
       <td>$@row.Price</td>
       <td>
         <a href="~/application?view=update&id=@row.ProductID">Update</a>
         <a href="~/application?view=delete&id=@row.ProductID">Delete</a>
      </td>
    </tr>
  }
</table>

Above code would render all of the data from the database, in my case it gave me the rows that were present inside the table for the products. Following image depicts the example data.

Products ASP.NET

Available products inside the database.

Creating new objects

Creating new objects can be another state of application in which the user is provided with a form to fill in to create a new object for the database. Most of the validation can be performed here, to make sure that the data is accurate and according to the policies and conditions designed by the DBA. But I am not going to go deeper into them, and just I am going to provide a simple example of saving the data inside the database.

Note: I am going to make a user of the Database object so there won’t be any SqlConnection and SqlCommand objects inside it. 

if (IsPost)
{
  // Save the data inside the Database...
  db.Execute("INSERT INTO Products (ProductID, Name, Description, Price) 
                          VALUES (@0, @1, @2)",
  Request.Form["name"], Request.Form["description"], Request.Form["price"]);
  Response.Redirect("~/application?view=read&message=created");
}
 
// For the Create View
<form method="post">
  <input type="hidden" name="type" value="create" />

  Name <input type="text" name="name" /> <br />
  Description <input type="text" name="description" /><br />
  Price <input type="text" name="price" /> <br />
  <input type="submit" value="Submit" />
</form>
This is the form rendered in the HTML form in the browser.

This is the form rendered in the HTML form in the browser.

In ASP.NET web pages framework you can validly write the content inside the file as plain text and it will be rendered as valid HTML in the browser. Also you can have the ProductID to be an Identity field making it easier to update the field everytime a new record is added instead of updating the value yourself. 

Once this code would execute, it will return you with the following window. Displaying all of the records in the database including the new row that was added to the database by the user while submitting the form.

5th row is the new row in the table that we added. It depends on your data, the data you pass to the table.

5th row is the new row in the table that we added. It depends on your data, the data you pass to the table.

 Updating and Deleteing the data

Updating and deleting the data from the website doesn’t require any special web page to be generated (apologies, because you still need a form for the user to input the fields) for them to be worked. You can allow the user to enter the values that you want to get from him inside a form and then submit the data to the database for update purposes.

Update process of the data in the database, can be run through this example code,

var row = db.QuerySingle("SELECT * FROM Products WHERE ProductID = @0", Request.QueryString["id"]);

if (IsPost)
{
  db.Execute("UPDATE Products SET Name =@0, Description =@1, Price =@2 WHERE ProductID = @3", 
  Request.Form["name"], Request.Form["description"], Request.Form["price"], Request.QueryString["id"]);
Response.Redirect("~/application?view=read&message=updated");
}
 
// For the Create View
<form method="post">
  <input type="hidden" name="type" value="update" />

  Name <input type="text" name="name" value="@row.Name" /> <br />
  Description <input type="text" name="description" value="@row.Description" /><br />
  Price <input type="text" name="price" value="@row.Price" /> <br />
  <input type="submit" value="Submit" />
</form>

The above form will allow the user to pass values to the database. A simple query was performed in order to let the user know which data he is going to edit and what is the previous data that is currently stored inside the database. Upon successfull execution the user would be redirected to the default page for results. User is not interested in knowing how, when and where the data is stored. All he wants to read is that the data was stored and updated in the system.

Delete command, doesn’t even require a form so there is no need to write any other code. All you can do, is run a simple query and the data would be removed from the database, once that has been done you can redirect the user back to the default page (read) for the user to continue his work.

// For the Delete View
var id = Request.QueryString["id"];

db.Execute("DELETE FROM Products WHERE ProductID = @0", id);
Response.Redirect("~/application?view=read&message=deleted");

A parameter (id) was passed in order to let the database know only to delete the  objects with that particular condition. Otherwise all of the records from the database would be removed. 

Points of Interest

You can connect the ASP.NET applications and websites, not only to the databases present inside the directory of the website but to any other database, of whose authentication you can take care of, like server address, database name and credentials etc.

In ASP.NET, you can provide any name for the database object to be used inside the web application, keeping your database’s actual name hidden.

CRUD operations are simple command operations on database, such as SELECT, INSERT INTO. But in a different manner. You can create conditions inside the forms to use and then execute the command over the database using the SQL language. Which would perform the CRUD operations on the Database. CRUD operations stand for: Create, Read, Update, Delete.

It is not necessary to create a page for the Delete and Update messages, you can just execute the commands and come back to the default page (the page to Read the data) and just show the message returned from the server.

Connecting to the remote database will take some extra time depending on the network connection since the connection will be established remotely thus making the system a little heavier and connections a little slower. However, there is no difference in connecting the application’s own database or a remote database, assuming permissions do not come into action.

The provider for the connection of SQL Server is System.Data.SqlClient. For other database connections and types their provider must be provided instead of SqlClient namespace. It is required by ASP.NET to create the connections to the databases. You can learn creating connectionStrings for ASP.NET applications for SQL Server from any of the following links.

http://www.connectionstrings.com/sql-server/

http://www.asp.net/mvc/overview/getting-started/introduction/creating-a-connection-string

http://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

MSDN and ASP.NET links have a +1 point for their clarity and their content.

History

First version of the post.

How is strong password, a strong password?

Introduction

Using the Internet, well, either that you’re a guest or you’re a member of the website that you’re visiting right now to read this post. If you’re a user, you must have logged in using a form, where you were asked to enter a password. That password is your key to your vault in the server, if misplaced, anyone can use your vault for any purpose. That is why it is mostly asked to use a Strong password and at the very same time a strong-o-meter or a secure-o-meter is also given for the user to understand whether the password that he’s using is a strong one, or not strong.

Password

A password is a set of alphanumeric characters used as a key to let the users authenticate them self to use a service. It can be a few letters long, containing a Capital case, any integer (such as numbers) or some special characters. Making it a stronger combination of the characters in a string which, no one other than himself can know to authenticate himself. Think of it just like the code combination of your locks for the safe. If you share that code with anyone else, he can (if not surely) use that code for some personal uses, might even steal things or read confidential content from your safe.

Websites are just like safe that you use in your houses. On websites you can store your personal data, your contacts or lists that contain a To-do list. The code for the website is known as a Password. At the time of creation of membership account, the users are asked to enter a password that will be used as their key which the user would have to enter before continuing to the service to be consumed by him.

Securing the Password

Once the password has been shared by the user now it is the time for the website owners, more like the developers to try their best to secure the password. The technique they use is called “Password Hashing” in which a hash of the password is generated, which is not identical to password in any way and also it is not-understandable by the humans in any way. This method makes the password secure, not only that any human user can never read and understand the string, but in a way that this string is not convertible back to its original form. There is no chance for the user, or hacker to convert the string saved inside the database to its original form to get the code.

Tips for a strong password:

The above mentioned things are the precautionary measures taken on the service side. User is not involved in this, in any way. The hashing process is completed on the server-side. Before that, the user comes into action and it is his responsibility to choose such a password that is not directly or indirectly guess-able by others but him. This might include special characters, numbers and other alphabets collectively.

Best method to create a strong password, is to avoid usage of words from dictionary and try to make up words from common language, chatters etc. Also you must include numbers, special characters to the password as much as you can. This is why, because most of the times when the hash is generated, it can be regenerated using the same password. Including special characters, numbers would minimize this problem to occur, to prevent cracking of the passwords.