Ricardo Sanchez
Coder, Photographer, Youtuber, Blogger

Development

How to add simple logging to your Web App using Elmah

Logging is a crucial part of any application. Logging can be used to track events, identify code issues, security holes, etc. In this blog post, I’ll describe how to add logging to your ASP.NET web application using an open source logging framework called Elmah.

Elmah has been around for a while, it became very popular for its pluggable framework. Elmah can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

Another common open source logging framework for .NET is a port of the excellent Apache log4j framework to the Microsoft .NET runtime, log4net. However, in this blog, I’ll focus on how to enable logging for your ASP.NET web application using Elmah.

Install Elmah

Get the latest Elmah version by typing the following into your Package Manager Console.

PM> Install-Package elmah.sqlserver

In this example, I am using the Elmah SQL package that comes with the files and configuration needed to log errors in a SQL table. After running the command above, you’ll see a new directory, App_Readme with two files in it.

solution1 Continue Reading

Programming: A short history of computer languages

What is computer programming

The action or process of writing computer programs, that is the definition of computer programming. Unfortunately that doesn’t tell us much.

In a more descriptive way, programming refers to the act of describing processes and procedures by developing a list of instructions and commands for a computer to execute. The type of objects that these instructions manipulate are numbers, words, sounds, images, and the like. The goal of manipulating these objects is to make a computer perform a task and get results which would be nearly impossible for a human being to perform in a timely and accurate manner. The tasks we instruct a computer to make are usually very repetitive and can involve million of calculations in a short period of time. Continue Reading

An introduction to Single Responsibility principle (SRP)

This is the fifth and last article describing SOLID principles. This article is about the Single Responsibility principle. Hopefully it will help you understand what the principle is all about and why it’s important to keep it in mind when designing and writing your code.

What is the Single Responsibility principle?

Here is the definition from Wikipedia: The term was introduced by Robert C. Martin in an article by the same name as part of his Principles of Object Oriented Design, made popular by his book Agile Software Development, Principles, Patterns, and Practices. Martin described it as being based on the principle of cohesion, as described by Tom DeMarco in his book Structured Analysis and Systems Specification. Continue Reading

An introduction to Open Closed principle (OCP)

This is the fourth article on SOLID principles which I started a few weeks ago. I hope this is useful for you and that it gives you a simple understanding of what the Open/Closed principle is all about.

What is the Open Closed principle?

Bertrand Meyer coined the term Open/Closed Principle which appeared in his book titled Object Oriented Software Construction in 1988. The principle reads “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification“. Continue Reading

An introduction to Liskov substitution principle (LSP)

This post is about the Liskov substitution principle (LSP). This is also the third of my posts about SOLID principles, following the posts I wrote about DI and ISP in the past few weeks.

What is Liskov substitution principle (LSP)?

This principle is based on Barbara Liskov’s definition of subtyping, commonly known as the Liskov substitution principle which states the following:

if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program

or in my own words, in programming we cannot always represent our objects with real-life objects and so we need to make sure subtypes respect their parents. Using the illustration below, in order to follow this principle we need to make sure that the subtypes (duck, cuckoo, ostrich) respect the parent class (bird). This means that in our code, we should be able to replace bird with duck, cuckoo or ostrich.

Subtyping

The above illustration shows clearly how in object-oriented programming (OOP) we can reuse some of our classes by making use of inheritance. This also shows very simply how using a base/parent class can be very beneficial and it is a main part of OOP.

So what is the problem you might ask? what is the purpose of the Liskov substitution principle? the purpose of it is to help you avoid some problems when modeling your objects by making you aware of potential problems that aren’t so obvious when using inheritance at the time of development.

The idea is to keep the LSP in mind when developing our classes so a parent class like “bird” can point to any of its child class objects i.e. “duck”, “cuckoo” or “ostrich” during runtime without any issues.

A classic example of LSP violation

One of the most classic examples of LSP violation is the use of a Rectangle class as the parent of a Square class. At first it seems this is the right thing to do as in Mathematics a square is a rectangle. However, in code this is not always true and this is what I meant when I wrote above that you cannot model your objects in code as you would do in the real world.

Below is an example of how in code, something like deriving a class of type Square from a Rectangle class might seem ideal…

public class Rectangle
 {
    public double Height { get; set; }
    public double Width { get; set; }
 }

 public class Square : Rectangle
 {
    public Square CreateSquare(double w)
    {
       var newSquare = new Square
       {
          Height = w, Width = w
       };
       return newSquare;
    }
 }

The example above looks fine, you can call the method CreateSquare by passing a value which is then assigned to both the height and width values of the object, this results in a proper formed square where all sides are equal. The problem arises when you define a rectangle where the height and width have different values, if you then try to substitute that object using a Square object… you will get unexpected results as the Square object expects its height and width properties to have the same value all the time.

However, the Liskov substitution principle says that you should be able to substitute any of the child classes for its base class and the example of the rectangle/square clearly breaks that rule.

The Liskov Susbtitution Principle (LSP) is one of the SOLID principles which can help you during software development to avoid common mistakes that are hard to notice if you are not thinking about them when using inheritance and modeling your classes/objects.

Happy coding!

 

An introduction to Interface Segregation Principle (ISP)

Last week I wrote a post about Dependency Injection (DI) with some basic examples in C#. Today I would like to write and offer a simple example of what is known as Interface Segregation Principle (ISP) which can happen if you are not careful when using and implementing interfaces in your code.

What is Interface Segregation Principle (ISP)?

The goal behind ISP is that no client consuming an interface should be forced to depend on methods it does not use. For example, you might have a class that implements an interface called IPersist. Let’s call it ReservationDatabase, and this class has code that persists a hotel reservation details to a database. IPersist contains the public method declaration of the method in ReservationDatabase that performs the persistence to the database. IPersist looks like this:

public interface IPersist
 {
    bool Save(ReservationDetails reservation);
 }

As you can see, this interface is very simple and it only has one responsibility. You could implement this from several classes that have a public method labeled “Save” to save some data to a database, to a XML document, to other data repository, etc… Everything is good so far.

Now, let’s say that you have a new class for logging some of the tasks related to the reservation, and you would like this ReservationLog class to implement IPersist as well as one of the functions of ReservationLog is to save this to a log repository. To implement IPersist you simply add the following at the top of your class:

public class ReservationLog : IPersist

This is the entire ReservationLog class that now implements IPersist:

public class ReservationLog : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to perist data to database...
       return true;
    }

    public void Log(ReservationDetails reservation)
    {
       // imagine some code here to log to a log repository
    }

    public void SendNotification(ReservationDetails reservation)
    {
       // imagine some code here that notifies about logging
    }
 }

Now, since we are already implementing IPersist in our ReservationLog class which has two other methods, we update IPersist so it includes the two other methods from ReservationLog because it will be easier for the class or classes consuming IPersist to access these methods when logging is needed. So the updated IPersist interface looks like this now:

public interface IPersist
 {
    bool Save(ReservationDetails reservation);
    void Log(ReservationDetails reservation);
    void SendNotification(ReservationDetails reservation);
 }

What we did above might not look like a big change but it is. What we did above is wrong if you didn’t first carefully consider the consequences of implementing IPersist in a class that has multiple public methods and then adding those new method declarations to IPersist. The main responsibility of IPersist was until now to abstract the details from classes that allowed to save reservation details to some data repository. By implementing IPersist on ReservationLog and adding all of its public method declarations to this interface, the result is broken code in all of the classes that are implementing IPersist IF they don’t have public methods that match with those in the IPersist interface.

For example, the original ReservationDatabase class looks like this:

public class ReservationDatabase : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to persist data to database...
       return true;
    }
 }

This code won’t compile anymore as this class and perhaps other classes in our code that implement IPersist, do not have methods that implement the two new declarations we added to IPersist:

void Log(ReservationDetails reservation);
void SendNotification(ReservationDetails reservation);

The common and not recommended “fix” for this is to “implement” these methods in all classes that implement IPersist and then just return a not implemented exception if anyone ever uses it. Using our example, our ReservationDatabase will look like this if we apply the quick fix:

public class ReservationDatabase : IPersist
 {
    public bool Save(ReservationDetails reservation)
    {
       // imagine some code here to persist data to database...
       return true;
    }
    public void Log(ReservationDetails reservation)
    {
       throw new NotImplementedException();
    }
    public void SendNotification(ReservationDetails reservation)
    {
       throw new NotImplementedException();
    }
 }

The code above is a clear example of breaking the interface segregation principle, which advises not to force any client to depend on methods that it does not use… like the two methods in our illustration above. If you ever see code like this in your projects, where the methods are implementing an interface and all its methods and just throwing NotImplementedException errors on some of them, the code is breaking the interface segregation principle. It is bad as the fix is quite simple and by fixing it you will end up with more maintainable code that can be easier to read and debug.

How to avoid violating the ISP principle?

It is actually very easy, it does require a bit more work but in the end you will have better organized code, you will be following this principle and a few more such as single responsibility and the universal KISS principle.

If you wanted to implement IPersist in your ReservationLog class you can still do it. However, do not update IPersist to accomodate for the other public methods in your ReservationLog class, instead create a new interface, implement it and use it to add any log related methods from your class to it. This is what this new interface might look like:

public interface ILog
{
   void Log(ReservationDetails reservation);
   void SendNotification(ReservationDetails reservation);
}

Now you can implement ILog in your ReservationLog class. You can do this by adding a comma and typing the name of it after IPersist which was implemented earlier.

public class ReservationLog : IPersist, ILog

That’s it! by doing this you can still implement IPersist without having to change other classes that might implement it and you also create a new interface that can be used by any classes wanting to implement the Log and SendNotification methods.

You could probably remove the SendNotification method and abstract it to yet another interface named INotify to keep your code simple, organized and maintainable.

Also, if your code is already violating ISP and you have interfaces that already have multiple method declarations then your should consider fixing this by refactoring your code using the Adapter pattern, take a look at this to see a clear example of it.

Hope this is useful to you. Happy coding!

 

An introduction to Dependency Injection (DI) and Inversion of Control (IoC)

Comments Off on An introduction to Dependency Injection (DI) and Inversion of Control (IoC)

There is so much confusion and arguing about what dependency injection is and whether is the same as inversion of control or just one form of it. If you are new to these terms it can be very confusing to say the least. I’ll try to describe what these are with some examples written in C# and hopefully you’ll have a better understanding of what this is and how to actually implement them in your code.

Dependency Injection (DI) vs. Inversion of Control (IoC)

According to Martin Fowler these two are exactly the same thing, here is some text extracted from his own article about inversion of control:

As a result I think we need a more specific name for this pattern. Inversion of Control is too generic a term, and thus people find it confusing. As a result with a lot of discussion with various IoC advocates we settled on the name Dependency Injection.

Based on this I have personally settled on calling it all Dependency Injection which can be implemented in different forms. So, what is Dependency Injection? my definition of it? instead of having your classes creating a dependency or asking a factory object to make one for them, you pass the needed dependencies in to the constructor or via property setters, and your class doesn’t care about much else. This helps you to decouple dependencies that your classes are dependent on to do their work to make your code more flexible and testable.

For example, let’s say we have a booking service which we use to create a reservation object when a traveler books a hotel in a website. The reservation class might include things like validation and other business logic but it also calls code from another class to save the reservation details to a database. Here is an illustration of what I just described: mockup The photo above shows how the Reservation class depends on the ReservationDatabase class. In other words, Reservation knows that it needs a ReservationDatabase instance in order to be able to save the reservation details. The question to ask is, does the Reservation class really needs to know that it uses ReservationDatabase? It should be enough that Reservation class knows about the behavior, the methods, properties etc, of ReservationDatabase without knowing who actually implements that behavior. Let’s take a look at the code representation of the above:

public class Reservation
    {
        public void ProcessReservations(ReservationDetails reservation)
        {
            // business logic, validation, etc...

            // save booking to database
            new ReservationDatabase().Save(reservation);
        }
    }

Now, imagine if you wanted to test the code in the Reservation class, it wouldn’t work as in the example above uses an instance of ReservationDatabase which has the code to save the reservation to the database. In other words, you would need a database to test the code above. Also, the code above is not very flexible as it forces one class to know about the class that implements some of the code. For example, if you wanted to unit test the Reservation class you would need to test the code behind the Save method too as it is a method used in the code above. You cannot isolate your code using the implementation above.

Applying Dependency Injection

With dependency injection we can solve the potential problems we described above and with a few simple changes our code can be more flexible and testable. We can isolate our code and decouple our classes so one does not have to know the details of the other, just needs to know about the interface and not the class that implements it at run time. So how we do this? We can remove the dependency of Reservation on ReservationDatabase by extracting an abstract definition of the behavior used by Reservation in ReservationDatabase, in other words, let’s create an Interface to separate the two classes and ‘hide’ the implementation details of ReservationDatabase to the Reservation class. This is illustrated below: dependencyinjection In the illustration above, ReservationDatabase implements IPersist (interface) and Reservation uses it. At this point Reservation might still be using ReservationDatabase but it doesn’t know it, it just knows that is uses something that implements IPersist. We could change what happens in ReservationDatabase and the Reservation class wouldn’t know about it, or perhaps we could have a new class implement IPersist and again, Reservation wouldn’t know or care about it. Here is the code representation of the above, first you’ll see how Reservation now uses the new interface IPersist which is implemented by ReservationDatabase in our example:

public class Reservation
    {
        private IPersist _reservationDatabase;

        public Reservation(IPersist reservationDatabase)
        {
            this._reservationDatabase = reservationDatabase;
        }

        public void ProcessReservations(ReservationDetails reservation)
        {
            // business logic, validation, etc...

            // save booking to database
            _reservationDatabase.Save(reservation);
        }
    }

The code above shows you a basic implementation of Dependency Injection (DI), now let’s see how we benefit from this. The code above shows how we injected the dependency (IPersist) into our Reservation class by using a constructor. We did this by using what is called constructor injection, where we supply the IPersist instance to Reservation’s constructor, or property injection where we supply it to Reservation after it has been instantiated by setting a property on it.

This gives us the ability to use any code that implements IPersist without knowing the details of that code. For example, let’s say that we wanted to not only persist the reservation to the database but also to some XML document for whatever reason. With the updated code we would just need to write a new class that had all of the code to create a new XML document and then make sure that implements our interface IPersist. By doing this, our Reservation class will now be able to save the reservation data to XML without having to make any code changes in that class. See illustration below:

dependencyinjectionThe above illustration shows clearly how Reservation only needs to know about IPersist but it doesn’t know what other classes implement it, and that is OK. As you would imagine, we could keep adding classes to perform some sort of persistence without having to make a single change on Reservation, all we need to do is implement IPersist and we’ll be done.

Dependency injection in this example is what we showed in the code example above, notice how Reservation has a constructor which requires an instance of IPersist as a parameter. It stores this instance in a field and when invoked the last step of ProccessReservations method uses this injected instance to save the reservation.

I will write about Dependency Injection Containers / IoC Containers in a follow up post but for now, use the examples above as a basic way to implement Dependency Injection in your code to make it a bit more flexible and testable. Cheers!

Building a Todo web app using PHP, Laravel and Bootstrap

I want to learn more about web frameworks that I am not too familiar with. My plan is to write simple web and mobile apps using different frameworks and technology stacks that I don’t have much experience with. While this is not going to make me an expert on any of these technology stacks or frameworks, it will give me the right amount of knowledge to decide if I like it by learning how to set up my environment, the tooling and the basic syntax of each. The first one of these apps is a to-do list which I wrote using PHP and bootstrap. Since I want to try new (to me) web frameworks I also used Laravel which is a PHP web framework that has everything you need to build a web application.

If you are learning PHP I want to recommend you give Laravel a try.

Setting up your environment

I recommend using Composer to install Laravel, Composer is a package management for PHP, just like Nuget for .NET, Maven for Java, RubyGems for Ruby, or npm for Node.js – you get the idea…

To install Composer you can do one of the following:

curl -sS https://getcomposer.org/installer | php
php -r "readfile('https://getcomposer.org/installer');" | php

Or using the Windows installer. The installer will download composer for you and set up your PATH environment variable so you can simply call composer from any directory.

Download and run Composer-Setup.exe – it will install the latest composer version whenever it is executed.

Once you have composer in your system, use it like this:

composer create-project laravel/laravel your-project-name --prefer-dist

This command will download and install a fresh copy of Laravel in a new your-project-name folder within your current directory. Next run the composer install command in the root of your manually created project directory. This command will download and install the framework’s dependencies.

Serving your web app

You can use a web server such as Apache or Nginx to serve your Laravel applications. Also, if you are in a Windows environment and have Webmatrix installed, you can use this to serve and also write your Laravel applications as well.

However, for this example I used PHP’s built-in development server, it is great for use while developing a Laravel application.

You will need to have PHP 5.4+ installed in your system to use it.To start PHP’s built-in development server and launch your application type the following command

php artisan serve

By the way, artisan is the name of the command line interface (CLI) included in Lavarel, you can read more about it here.

After executing the above command, you should see the following message:

Laravel development server started on http://localhost:8000

This development server automatically uses port 8000 to serve web applications, you can change the port number if necessary by specifying it as --port=some-port-number

php artisan serve --port=8080

 Setting up Routing

Setting up routes using Laravel is quite easy. See example below:

Route::get('hello', function()
{
      return 'Hello World';
});

The above route will return “Hello World” when you browse to http://localhost:8000/hello.

In my web application example I have the following routes:

Route::get('todos', function()
{
	$todos = Todo::all();

    return View::make('todos')->with('todos', $todos);
});

Route::post('todos', 'HomeController@savetodo');

The first route basically returns http://localhost:8000/todo with a list of all todo items stored in the database. The second route posts to the HomeController, and used the function saveTodo to save a new todo item. Before we can use the above routes, we have to setup our views, model and database.

Setting up Views

Views live in the app/views directory and contain the HTML of the application. We’re going to place two new views in this directory: layout.blade.php and todo.blade.php. First, let’s create our layout.blade.php file which you can find in its entirety here, but this is the one important line that needs to be included in the view:

@yield('content')

The code above is the entire layout.blade.php view which acts as a template for your web application. The rest of the views use this template, they are rendered by calling @yield(‘content’).

In order for the rest of your views to use this template you have to add the following to the top of your views:

@extends('layout')
@extends('content')

I am excluding the rest of the content in the view todos.blade.php for brevity but you can download the entire project here.

That is all for this PHP ToDo web app built using the Laravel framework and Bootstrap. Hope it is useful for some and please feel free to download it, use it, change it and please let me know any thoughts you might have about it. Cheers!

I am currently available for freelance – contact me if you need help with a software project.

Install MongoDB service on Windows 8

MongoDB (from “humongous”) is an open-source document database, and the leading NoSQL database. Written in C++.

MongoDB is great for modeling many of the entities that back most modern web-apps, either consumer or enterprise:

  • Account and user profiles: can store arrays of addresses with ease
  • CMS: the flexible schema of MongoDB is great for heterogeneous collections of content types
  • Form data: MongoDB makes it easy to evolve structure of form data over time
  • Blogs / user-generated content: can keep data with complex relationships together in one object
  • Messaging: vary message meta-data easily per message or message type without needing to maintain separate collections or schemas
  • System configuration: just a nice object graph of configuration values, which is very natural in MongoDB
  • Log data of any kind: structured log data is the future
  • Graphs: just objects and pointers – a perfect fit
  • Location based data: MongoDB understands geo-spatial coordinates and natively supports geo-spatial indexing

Continue Reading