FriendlyURL : A new and exciting feature of ASP.NET

This is going to be the last post of 2012 by me. I am very happy that I am writing about a very exciting feature that is coming with ASP.NET.

I am really excited to learn and write on this. I really hated the ugly URLs and the extensions of the page that always visible when one opens the application unless and until you write your own custom url processor. With ASP.NET 4.0, Routing was introduced, which provided the capability to ASP.NET to have easier, manageable and SEO friendly urls, I wrote a post on it. You can click below to have a look on it.

URL Routing with ASP.NET 4.0

But that is little tidy to write. And it looks like writing extra code that does not produces any business functionality.

FriendlyURL as the name suggests gives a clean and SEO friendly URL.Currently it is available via NuGet and in pre release version.

So For this post, I have used my Visual Studio 2012 IDE. I created a new project as File-> New -> Website -> ASP.NET Empty Website.

Once the project got created. I require to install the NuGet for my application. So got to Tools-> Library Package Manager-> Package Manager Console

Package Manager Console

It opens a console then type Install-Package Microsoft.AspNet.FriendlyUrls -Pre and press enter as

FriendlyURL NugetInstallation

As you can see, I typed the command and can be seen in  the first red encircled area and press enter. It’ll install the NuGet and you can see the last red encircled area which shows FirendlyUrl is successfully added.

This can be used with two ASP.NET versions: ASP.NET 4.5 and ASP.NET 4.0.

Now you are ready for working with friendly URLs.

If you have  read the Readme.text. It gives a clear  idea how to start with. But I’ll take you through the steps. So let’s start

Step 1-> Add and Create a Class name preferably RouteConfig.cs ( You can have any name. I used MyRouteConfig.cs) and make it static. Also add the name space in the class Microsoft.AspNet.FriendlyUrls

Step 2-> Create a static Function in the class preferably named as RegisterRoutes with a Parameter of type RouteCollection and add  a line  routes.EnableFriendlyUrls() in the method as

public static class MyRouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.EnableFriendlyUrls();
    }
}

Step 3-> Add Global.asax file and add the following line in Application_Start as

  void Application_Start(object sender, EventArgs e)
    {
        MyRouteConfig.RegisterRoutes(RouteTable.Routes)
    }

Now you can start the development of your application. I have created two pages First.aspx and Second.aspx in my solution

That’s it. Now your code is ready for run.

First PageIf you see the above circled area in the above pic, it does not contain page extension (aspx). So now the url looks pretty. As an end user, I don’t care about the page extension and even some time it just irritates me.

Now if you want to redirect to another page, you can redirect by typing URL without page extension as

Response.Redirect("~\\Second");

There is one caveat here. You can not have a folder and Page with same name at the same level. If you have the name of a folder and the name of aspx page at same level, you would not be able to access the page without extension. So please keep it in mind.

Now you must have a question in Querystring. What will happen with Querystring?

You don’t need to worry at all. QueryStrings will work as earlier . Let’s have a look to the URL http://localhost:57353/First?Id=1001 then you can read the QueryString as below similar as earlier

string Id = Request.QueryString["Id"] as string;

Next point, if I have a URL say http://localhost:57353/First/Products/NewProduct and there is no page as NewProduct. What will happen It’ll open First.aspx.

But, How it works?

It starts from last segment (NewProduct) and will check if there is any NewProduct.aspx. If not then it moves to next segment and continue till it finds the exact aspx page.

Let’s explore more. Go to the server side of the page and include the namespace Microsoft.AspNet.FriendlyUrls. You’ll get bunch of methods that will be very useful at certain times.

  • Request.GetFriendlyUrlSegments() – It returns a collections of string which represents the URL segments. So if I have a URL http://localhost:57353/First/Products/NewProduct and the page exists First.aspx then it returns.
    URLSegments
    So you can see above, there is two segments and one can iterate through it. These url segments can be used to pass the values to a page via URL instead of QueryString. It also looks pretty.
  • Request.GetFriendlyUrlFileVirtualPath() – It returns the File virtual path. For the URL, discussed in the above example it will show as
    File Virtual Path
    You can see it shows the Virtual path of the file.
  • Request.GetFriendlyUrlFileExtension() -It returns the extension of the file. For the above url, it will be shown as File Extension
    As you can see, the extension of the page. As now with friendly url, the page extension is not shown. You can get the extension by the above method.

There are other important methods/features available that can be used to generate the URL etc. I’ll discuss some of those here

An available class FriendlyURL provides few static functions/properties that is very useful. Let’s see

  • FriendlyUrl.Segments ; Returns the segments of of the current URL similar as returned by Request.GetFriendlyUrlSegments()
  • FriendlyUrl.Resolve : This can be used to resolve the FriendlyUrl
    • FriendlyUrl.Href – It takes few parameters virtual path and list of url segments and generate the friendly URL out of it. And it is very useful while generating the URL in data binding and several other places. We can write
      FriendlyUrl.Href("~/First", "Product", 1001);
      

      And what it will return
      FriendlyURLgeneration

Hope you must have liked this new coming feature of ASP.NET. This will will let you get rid of aspx extension at URL , Frankly speaking, during my earlier days of career, I used to see the extension to check if the website is developed in asp.net.

I find this feature as one of the most of the exciting features of ASP.NET. Hope you all enjoy it and also like the post.

Enjoy and Love ASP.NET. And A very Happy New Year to all.
Cheers.
Brij

Inheritance with JavaScript

This post is in continuation in my last post.  In my last post, I discussed various ways to create custom object in JavaScript. I’ll advise you to go through that if you didn’t get a chance to have a look then you can go through it. Please find the link below

Various ways to Create custom objects in JavaScript

In this post, We will discuss, how we can use other features of Object Oriented concepts in JavaScript. Today I’ll discuss one of the main concepts of Object Orient Programming that is Inheritance.

So how can we use Inheritance with JavaScript ?

Various ways and plugins are available that provides similar ways to use Inheritance that we have used in other object oriented language. But the prototype based Inheritance is used most.

JavaScript is a object based language that is based upon Prototype based programming. It is free from Class and completely rely on objects only .

Did you hear earlier  that What is Prototype based language or what is Prototype based programming?

I would say this is just another way to provide object oriented feature by a language. As per wiki

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming”.

So let’s start learning. To create a Class in JavaScript, we are required to create a function  that we also used to call a Constructor. I’ll use the word constructor in my further discussion. So Let’s create a Constructor called person

         function Person() {
             this.ToString = function () { alert('I am a Person'); }
             this.DisplayResidence = function () { alert('I stay near my office'); }
         }

As in my last post, I mentioned that Person is a nested function. As you can see that here we have following two functions in the Person constructor.

  1. ToString
  2. DisplayResidence

So let’s create a new object and display it

function DisplayObject()
{
var objPerson = new Person(); // Line- 1 Creates the instance of Person
objPerson.ToString();  // Line- 2
objPerson.DisplayResidence(); // Line- 3
}

Here both display as expected . Line 2 - I am a Person and Line 3 - I stay near my office

Now let’s say we want to create a constructor Employee as

         function Employee() {
             this.ToString = function () { alert('I am an employee'); }
             this.DisplayRole = function () { alert('My role is development and implementation'); }
         }

As you can see it has two methods ToString and DisplayRole. Now how can Employee inherit the properties/methods of Person. It can be done by writing as

Employee.prototype = new Person();

Now the employee has the properties of person as well. Now it has three methods

  • ToString()
  • DisplayResidence()
  • DisplayRole()

Let’s examine it by the method

         function DisplayObject() {
                var objPerson = new Person(); // Line- 1: Calles constrouctor Person to create an instance and assign it to objPerson
                objPerson.ToString(); // Line- 2: Calles ToString method of Person
                objPerson.DisplayResidence(); // Line- 3: Calles ToString method of Person

                var objEmployee = new Employee();  // Line- 4: Calles constrouctor Employee to create an instance and assign it to objEmployee
                objEmployee.ToString(); // Line- 5: Calles ToString method of Person
                objEmployee.DisplayResidence(); // Line- 6:  Calles ToString method of Person
                objEmployee.DisplayRole(); // Line- 7:  Calles ToString method of Person

                alert(objPerson instanceof Person);  // Line- 8:  Checks the type of objPerson
                alert(objEmployee instanceof Person);  // Line- 9:  Checks the type of objEmployee
         }

Let’s discuss it by Line numbers

Line 2 and Line 3- same as discussed above

Line 5- What it will display ? It displays I am an employee because ToString is available at both current and parent. But because the objEmployee holds the instance of derived class so the overridden method is called.

Line 6- Here DisplayResidence is not defined in Employee so it calls the base class(Person) method and displayed.

Line 7-  DisplayRole is added in Employee object only and it shows ‘My role is development and implementation‘.

Line 8 – To check more on the type I added the last two lines. As objPerson is instance of Person only so it shows true.

Line 9 – As Employee inherits Person so it also shows true but if you delete the below line ….

<br />Employee.prototype = new Person();<br />

then it’ll show false as it does not inherit person any more.

Now you must have got enough Idea about prototype based inheritance in JavaScript.

There is one more way to add a method to and existing constructor as Person has two methods and  that we defined as nested class. You can write that in the following way as well

         function Person() {
         }
         Person.prototype.ToString = function () { alert('I am a Person'); }
         Person.prototype.DisplayResidence = function () {alert('I stay near my office');}

Now the question arises,  how Inheritance works in JavaScript.

Whenever we create an instance using the new Operator, It creates all the properties/methods and also has internally a variable called __proto__ (double underscore at both side) this is the variable which is responsible for the inheritance feature. So let’s say I created a instance of Employee as

var objEmployee = new Employee();

It’ll be having two methods/properties as defined and on __proto__ as

  1. ToString
  2. DisplayRole
  3. __proto__

Just because I have written also as

Employee.prototype = new Person();

The __proto__ variable gets assigned to the person instance. This __proto__ used to determine the prototype chain and return the property values. This allows us to access the base class methods and public properties.

As I talked about prototype chain, means as soon as I assign

Employee.prototype = new Person();

a __proto__ variable gets available to us that can be be further used for inheritance. So lets create another constructor as

         function TeamLead() {
             this.ToString = function () { alert('I am a Manager.'); }
             this.DisplayRole = function () { alert('I rarely code but do lot of code reviews'); }
             this.DisplayMeetings = function () { alert('I have 3 meetings scheduled daily'); }
         }

Now as soon as I’ll create an instance using new operator then instance will be have the properties

  1. ToString
  2. DisplayRole
  3. DisplayMeetings
  4. __proto__

Now if we write the code for inheritance as

TeamLead.prototype = new Employee();

It can access all the properties in the hierarchies. We can check the type of instances as

 function DisplayObject() {
             var objTeamLead = new TeamLead();
             alert(objTeamLead instanceof Person);  // returns true because TeamLead inherits base class Person
             alert(objTeamLead instanceof Employee);  // returns true because TeamLead inherits  base class Employee
             alert(objTeamLead instanceof TeamLead); // returns true as expected
             }

You can see the results and they are expected

Let’s see the prototype chain as discussed earlier

         function DisplayObject() {
             var objTeamLead = new TeamLead();

             // Also here I'll show, How the prototype chain works
             alert(objTeamLead.__proto__ == TeamLead.prototype); // returns true because it represents the same prototype
             alert(objTeamLead.__proto__.__proto__ == Employee.prototype);  // returns true because second level __proto__ belongs to Employee.prototype
             alert(objTeamLead.__proto__.__proto__.__proto__ == Person.prototype);  // returns true because third level __proto__ belongs to Employee.prototype
         }

As you can see that actually __proto__ variable is actually the key for the inheritance.

Now you all must have got enough Idea about Prototype based programming and how we can use inheritance with JavaScript.

Do share your feedback.

Happy Coding,
Brij