Tag Archives: .NET

A few tips for security in .NET framework

Hello everybody, I am back with another good article for covering security in .NET framework for passwords of users. Although I was very much disappointed by the articles and resources published previously by many editors and authors. So I thought I must publish an article that covers all of the parts, that a good article needs.

I wrote an article for C# Corner community specifically, titled as: Efficiently Storing Passwords in .NET Framework. In that article I have discussed a lot of points and topics that a reader is trying to get in an article about Cryptography. A few major points are:

  1. What is cryptography? Why protect the passwords?
  2. How password should be protected?
  3. What algorithms are there to protect my password.
  4. Which of those algorithms are out-dated and which are expensive for my company?
  5. Where would the algorithms in .NET framework work.

And many more similar things are discussed there. Another major thing to understand is the usage of Salt. A salt is a random string generated to prevent password cracking attacks, such as Rainbow Table attack, Dictionary attack and many more. Salt just prevents any of them from happening.

Hashing, is an algorithm function that generates a random alphanumeric string for a password that is impossible to convert back to plain-text password, easily. Note the term, “easily”. Although a hash algorithm is designed to never run backward, still computer can run such algorithms that can get the password string back or at least try as much combinations to get the same hash value!

You should read the article from C# Corner, and learn how to protect passwords and other sensitive data in .NET framework.

Efficiently Storing Passwords in .NET Framework


Downsides of learning {programming-language} in {x} days!

This might be my first post about such topics… Which might contradict other (self-claiming) authors who say that they can teach you a programming language in a number of days. For example, “Learn ASP.NET in 7 days”, “Learn HTML5 in a matter of 3 days”. Let me point out a few of the downsides of this type of teaching and learning for new developers, who might fall for this approach.

Who are the victims?

The most victims to this type of approach are the young developers… Inexperienced, rushing to learn new things, express-to-impress type of teens and those with a deadline of them self fall to this type of approach very often. Sometimes those who cram the rules, types, structures of the language do so.

Remembering never helps you out! You have to understand how things work.

Remembering never helps you out! You have to understand how things work.

Most usually, the teens who are eager to learn something in a very short number of time are victims to this approach. 7 days? 14 days? Seriously? What is it like… A pond’s challenge! Programming is something that cannot be fed into minds of other people; you cannot move a clock in simple harmonic motion and expect the human to become a programmer once you’re done hypnotizing and brain washing him. It cannot be taught the way we learnt it. It must be taught by lowering our standards to the standard that our student can understand us. Our students come to us to learn… We should educate them, not force them to remember what we said.

Who claims such thing?

I have no personal hatred towards those who claim such. In fact people who are extraordinary in learning and experimenting claim such things. They learn things in a very fast manner. Authors who write a title to their publication in a way, “Learn {subject} in {x} days!” are them self very quick learners. That is why they expect others to learn the same subject in a very fast manner.

It won’t be false to claim that they actually are very genius of their era. They have a very resilient grip of their subject and field. But not all fingers are of same size. Are they?

Discussing the downsides of this approach

Now let us discuss, why new programmers should not learn programming or any architecture or a framework using this approach. I would state a few points of mine, you can have your own feelings and opinions and might contradict to mine. But… Be logical and learn stuff slowly and by understanding what they are to you!

Not at all a true statement

First downside that I feel about such content is that they are not at all true. How can someone claim to teach you something in a matter of deadline. I teach programming to a few, some of them learn the concept very quickly. Some take time… Some take a lot of time. For those who take a lot of time, I try to make sure that they at least learn and understand the basic concept and tend to do something with it. I do not expect them to cram to reach the “x” days limit.

More appropriately such topics for publications are a term for publicity stunt. Because they are more straight-forward, targeted by those who want to make more in less time, author is challenging himself to be able to teach you more in less days.

Different psyche levels

Humans do not have similar psyche level… And you just cannot expect everyone to be similar when it comes to ability to learn and understand something. It would be responsibility of the instructor to teach his/her student in a way that they can surely learn something and not just waste their own time. I have taught people of almost every psyche level… From geniuses to average students. Those who were genius asked such questions which led me to go deep inside my mind to extract a scrap of information which I had locked in my limbo for a decade (not really!). Those who were average students had to pay some more time to learn it, they also tried not to understand the concept as to apply it. But just to learn it… To learn it!

I had never been a great instructor. So I have tried giving them a lesson in a way a friend would. Publications claiming to 5, 7 or 30 days time period don’t claim that they would teach programming to those with average mind set. They are of the same period and good use to someone who has the 100% same mental ability as the author had when he was learning the same framework or language.

A book, in any way cannot claim that the readers are expected to benefit from the content. But, claiming something that is not expected or guaranteed should not be used. When an author claims something, he must be able to prove it.

Only good side of this…

The only good side of this approach is that the subject is catchy! 😉

Personal views

There are many other points… But, I would not want to criticize such content any more. Instead I would share my views to beginners how can they benefit from less in more time.

Practice makes you better!

First of all, I should say that you need to practice what you learn. Practice is something that doesn’t make the applicable task easier, it just makes you better!

You should never think things are getting easier. It is you who have evolved.

You should never think things are getting easier. It is you who have evolved.

What Google might respond to your search as?


I learnt programming in a matter of 2 months. I just learnt C# at that time… Not software programming! There was nothing that I knew about creating an efficient software, writing a good API, creating a web application and so on. The more your practice the better you get. More errors you get, more you will understand. Sometimes when I go back in time 3 years ago and have a look at my questions, problems that I faced. I laugh. That doesn’t mean things are easy. That means practice has just given me enough understanding of these frameworks that now I can slice and dice them in any way that I want to. It also now has an impact on my social life.

Now, after learning and practicing. I speak less but qualitative. The quality of my speech is great now. I do not speak gibberish (or that I feel like).

Now, after learning and practicing. I speak less but qualitative. The quality of my speech is great now. I do not speak gibberish (or that I feel like).

There is no limit to study

I can build good applications in a matter of day or two. But that doesn’t mean I should give up learning more and more about such particular platform or subject. I have good grip over .NET framework, but I believe I should learn more and more.

Every new developer must only focus on learning part. I remember a lot of good threads where I have participated, ended up in a same conclusion. That you cannot learn anything in a matter of week, fortnight, month or even a year. You need at least to consume 5-10 years to learn something. Yes, if you’re going to cram through the concept for a term test then good, do it. It might even take 3 days for that.

Focus on something… Put smaller time periods in your learning

But to learn something fully, you need to focus on it in a very better way. Give more and more time to it. Let it settle down. Give your education a short time of more like 30 minutes, 45 minutes regularly. Try something, learn something. You would stumble upon more like a million errors before you can think yourself as a pro beginner! Before you can even enter intermediate level, you will fall into the errors like a million, or billion times.

Do not rush!

There is no need to rush. You can learn something in a very easy, smooth and friendly way. For new developers, it is a very good approach to read articles of other developers, read their code. Reading good content, good articles, good code helps you out to understand how they did. Remember they might be better than you (I don’t mean to tease anyone here, sorry if you take my words seriously), so if they did something in one day and you took 3 days. Do not hesitate! It is OK!

Finally. It is you, who knows where you lag. Best learning environment is when there is an instructor available for you. Books, articles, blogs do not teach you in a way they can. If you are a beginner never rely on them. If books were everything there would have been no requirement for a school, institution or university. There would have been great great libraries every where. You should ask your instructor what to do and how to do. Your instructor should help you out… He should be able to know where you lag behind others. He should polish you in a way that you can really get into something.

How to calculate birthday from year, month and date

You might have usually created applications for evaluating and calculating the age of people using their date of birth. In this post I will teach how you can perform the math to find the birthday of a person.

Required input

For this program to run and find the birthday we require three inputs.

  1. Years — That have passed
  2. Months — That have passed
  3. Days — That have passed (negative value if the date has still to come in this month).

Then we can pass those values to the AddDays, AddMonths, AddYears functions of DateTime to find the birthday.


I used the following code to perform this function.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FindingBirthday
    class Program
        static void Main(string[] args)
           // Create variables
           int year = 0, month = 0, date = 0;

           // Get the values
           Console.WriteLine("How many years have passed?");
           year = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("How many months have passed?");
           month = Convert.ToInt32(Console.ReadLine());

           Console.WriteLine("How many days have passed?");
           date = Convert.ToInt32(Console.ReadLine());

           // Do the math and write it!
               String.Format("Your birthday was on {0}",
               DateTime.Now // Get current instance of time
               .AddYears(-year) // Add years
               .AddMonths(-month) // Add months
               .AddDays(-date) // Add days
               .ToString("MMMM dd, yyyy on dddd") // Format it

           // Just for sake of pausing the Console

The above code performs the action required and finds the date of birth.


For my input, the result was August 29, 1995 on Tuesday. Which is my date of birth calculated from my input of years, months and days that have passed since my birth.

What is code reuse and why use it?

In computer programming, there are many techniques used by programmers to make their programming life easier and better, different terms are used to denote the simple and compactness of a framework, such as, Object-oriented programming language. For example there are quite possible methods to let you re-use the same functions and properties in your code, by inheriting the actual class and using those members; functions or properties, inside your derived class. But OOP has been criticized a lot for its less reusability. But that is not the topic of discussion

Re usability

In programming, code re usability is using the similar code in different functions… No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code re usability defines the methodology that you can use to use the similar code, without having to re-write it everywhere; like I already said not in a way to copy and paste it. There are a lot different techniques that you can use in order to make use of code reusability in your applications. This technique follows the general programming DRY (Don’t repeat yourself) rule, which states, “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.” and helps the developers to maintain the structure of their applications from being messed up and frustrating while debugging the applications. There are quite different scenarios and methods to use,

  1. Inheritance
  2. Functions
  3. Libraries
  4. Forking

And it continues with many other frameworks being formulated every day and new paradigms being designed every decade and being used. But I would like to explain a few of these and why they’re better and so on. Finally, it would be clear, why DRY rule is better and how does it support the developmental process and makes it easy to debug our applications efficiently. You should also know that I am not going to demonstrate entire paradigm, I will just describe the use of paradigm in code-reuse.


Inheritance has been into programming world since quite a long time and is overly used in Object-oriented programming paradigms. This paradigm lets you use the base-class’s functions and members in other classes, most of the times an Animal class is used to describe this behavior, Animal is used to inherit from for a Lion and Human and many other types of the Animals. Who have their own different functions, like Lion can roar, human can speak, but they have something similar… Such as walk. So  it is not necessary to write walk function for all of these objects separately instead you can create this function for an Animal and use it in your derived classes; Lion, Human etc. Let us go through a code example of this scenario…

class Animal {
   // properties
   int legs;
   // functions
   void run () { /* code to run here.. */ }

Now you can then use the above class as the basic structure to define two other classes, with same properties and functions, like this.

class Animal {
   public int Legs = 4;
   public void Run() { 

class Human : Animal { }

class Lion : Animal { }

I know that this code hides inherited members and I should have used virtual or abstract keyword inside the Animal class. But, you get the idea don’t you?

Now this is just a complex way, to ensure that the members of Animal class are available under Human and Lion classes also. If you can the function Run over Lion or Human object, you will see that it will Run. Although making the functions work for different objects differently is a totally different aspect of this, you need to implement virtual or abstract keywords to avail such functionality to allow the developer to override the functions (or members more specifically) and add the body of their own; to write “Human running…” instead of just “Running…”.

Function calls

Function calls are another way of reusing the code from different parts of your application. You create small code blocks of an algorithm or logic-based source code, and give it a name, identifier. Which identifies your code; can describe the process too. Functions have,

  1. A return type, which denotes what type of data would be returned or a void.
  2. An identifier, which is used to make a call to this function.
  3. Function body, which is the code block containing the code to be executed when this function is called.
  4. Zero or more parameters to provide values to the code block variables.

Function are used to make sure that every logic is written once, and so that if there has to be made a change in the logic, we make it once and it is updated everywhere in the application. For example, if you have to greet a user many times inside your application, instead of writing a greeting message everywhere, you can create a greeting function

void greet() {
   // Greet user

This can be then used in enormous places to greet the user. Good thing is that it can be edited at one location, and changes will be reflected through where-ever you call this function. This was a very basic example, if you allow users to post something (such as status, photo etc.) then instead of writing post_update code everywhere, you can create a function in the business-logic-layer and call that function from where-ever you want to call it. Good thing, once again, is that you get to update the function at one place only and the changes will be reflected everywhere.


You might have heard of using Dynamic-link library? Yes, the most used .dll files. These libraries are a set of compiled programs, majorly used by larger and enterprise level software, to support the execution as they can be executed upon call.

If you have ever used NuGet packages, tried using .dll files, or added any assembly to your bin folder in .NET application or ASP.NET application, then chances are that you’ve already used libraries before and are well-known with these libraries. Most of the packages that are distributed to be used by other clients, are libraries that can be linked to your executable for purposes that they are defined for.

Most of the framework allow support of creating third-party libraries and to distribute them through different methods. You can also note, that System (namespace of the .NET framework) is also present in the System.dll library.


Forking, well if you’re a git geek, then you should know it better than me because I use Github’s GUI version and I don’t have much knowledge about underlying git. But, forking is a process of using someone else’s source code and making changes to it to fit your own needs, to distribute, use, share etc.

You can also fork someone else’s source code and write some more details to it. Make some bug fixes, add some patches and share it. This terminology and method has been widely used by different companies, to fork open source projects, make a few changes to the “Under the hood” and then distribute it with their own label and tag.

In my opinion, Forking is not one of the code reuse methods. You do not just reuse the code, you use it from ground up, building another framework of it and so on. But everyone has their own opinion, I have mine and so I cannot say anything about your opinions. Although, these methods have proved a lot helpful in programming, as to create robust and strong enterprise applications and have helped programmers maintain their hairs on their head and not in their hands as the application reaches the enterprise level of complexity.

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.
   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 () {
      // 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."

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));

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;
      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.
         @:more than a day.

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.

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.


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

    * 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

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

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.