ASP.NET MVC Routing For WebFom Developers

Today, I will try to explain ASP.NET MVC Routing from prespective of a ASP.net Webforms developer. Attempt over here is to stay away from page lifecycle and be focused till the instantiation of the page/controller class.

ASP.NET Web Forms

As such there is no routing in ASP.NET Webforms. But if you look at a page class, often you would have a question how is the page class instantiated. Class responsible for creating a page object is PageHandlerFactory. This class is registerd in web.config and in simple words the request pipeline is like 

  1. Execute modules registered in web.config
  2. Get the Page object using the PageHandlerFactory regiestered in web.confg. PageHandlerFactory’s GetHandler returns an Object that implements IHttpHandler, in case of .aspx request it is Page class that implements the IHttpHandler interface. But the actual instance returned is not the codebehind class but a class derived from code behind class (Details)
  3. Invoke the ProcessRequest method of the Handler returned by the PageHandlerFactory. After this step the page events are invoked. 

ASP.NET MVC 

Now, what happens in case of MVC is that Page (which is an IHttpHandler) is replaced by another class that implements IHttpHandler that is MvcHandler, and the class responsible for creation of MvcHandler is MvcRouteHandler (method GetHttpHandler) which is equivalent of PageHandlerFactory (GetHandler). 

But the question is what stage is it determined to use MVC objects but not the Webform ones. This is done by a module called UrlRoutingModule, UrlRoutingModule attaches itself to PostResolveRequestCache and PostMapRequestHandler events of the HttpApplication instance and overrides the default behaviour of MapRequestHandler stage.

At this stage the Route Table to which routes are set in Application Startup (as following) is used to determine if the URL match to one of the routes defined, by default it uses MvcRouteHandler, which can be overwritten by custom routehandler.  

  
public class MvcApplication : System.Web.HttpApplication
  {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }

So, in simple words UrlRoutingModule returns MvcRouteHandler which returns MvcHandler, now MvcHandler is the class that create an instance of the controller using controller factory. 

 

Refs

http://blog.thekfactor.info/posts/tag/mvchandler/

http://blogs.charteris.com/blogs/gopalk/archive/2009/01/20/how-does-asp-net-mvc-work.aspx

http://msdn.microsoft.com/en-us/magazine/dd347546.aspx

http://www.4guysfromrolla.com/articles/051309-1.aspx

http://www.4guysfromrolla.com/articles/050510-1.aspx

http://www.beletsky.net/2011/06/inside-aspnet-mvc-route-to-mvchanlder.html

http://www.dotnetframework.org/default.aspx/4@0/4@0/untmp/DEVDIV_TFS/Dev10/Releases/RTMRel/ndp/fx/src/xsp/System/Web/Routing/UrlRoutingModule@cs/1305376/UrlRoutingModule@cs

How to have your own mysql server for free in cloud

To have a free your own cloud mysql server, First you need an instance of amazon ec2 which is free for first year of your trial :)  Details http://aws.amazon.com/ec2/

First step get an EC2 instance, very simple follow http://www.edukatr.com/how-to-start-an-ec2-ubuntu-server-for-your-developer-in-6-minutes/

Once you got your ubuntu instance up and running. Install mysql http://www.howtogeek.com/howto/ubuntu/install-mysql-server-5-on-ubuntu/

Now it is time to open port 3306 following steps are from http://stackoverflow.com/questions/5004159/opening-port-80-ec2-amazon-web-services

This is actually really easy:

  • Go to the Security Group settings in the left hand navigation
  • Find the Security Group that your instance is apart of
  • Click on Inbound Rules
  • Use the drop down and add HTTP (port 80)
  • Click Apply and enjoy

now ssh into ubunutu server using Your keyfile edit “/etc/mysql/my.cnf” and comment line “bind-address = 127.0.0.1″ or put a “#” in front of it

restart mysql

  sudo service mysql restart

Create a new database and create new user with host ‘%’


CREATE DATABASE  IF NOT EXISTS  mydatabase;

GRANT ALL on mydatabase.* to 'mydatabaseuser'@'%' identified by 'mydatabasepass';

Thats.. it now just like u connect to a local mysql from command line, connect to this one by changing the host to be the ip of the cloud amazon server.

Setting up PHP debugging for PHPStrom on Ubuntu using xdebug and Chrome

First Install xdebug

apt-get install php-xdebug

Verify Install

using command line

php -i | grep xdebug

or phpinfo.php , save following in your webroot dir, by default /var/www/ (This is recommended, this will help in future as well)

   

Now, make sure remote_enable is “On” in phpinfo.php page or command line output. if not then

  sudo vim  /etc/php5/apache2/php.ini 

at the end of the file add

  xdebug.remote_enable=1

verify using the above steps make sure that it says remote_enable = “On”

Open PHPSTROM, open your php project.

Go to Menu , click on Run -> Break at First Lines in PHP Scripts
then click on Run -> Start Listen PHP Debug connections

Install xdebug-helper in your chrome

type in address bar of chrome chrome://extensions/ , search for xdebug helper, click on options,

In IDE Key section choose “Other” in dropdown and put PHPSTROM in textbox.

Now, open your php project in chrome, in address bar, next to star you will see a bug click on that and click “Debug”, bug must turn green , refresh the page, It must break in PHPSTROM first line. If that doesn’t work, Put comments, I will try to help you guys :) see ya for now

MySql Compare databases schema and data options

Source of the article

http://stackoverflow.com/questions/225772/compare-two-mysql-databases

If you want to compare use following shell script, from the stackover flow question.


#!/bin/sh

echo "Usage: dbdiff [user1:pass1@dbname1] [user2:pass2@dbname2] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname $table > $2
}

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; user=${up%%:*}; pass=${up##*:}; dbname=${1##*@};
for table in `mysql -u $user -p$pass $dbname -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
  else
    echo "Ignored '$table'..."
  fi
done
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

Ignore Joomla tables, Since data is getting created on login..

jos_session,jos_content,jos_users,jos_updates.jos_update_sites

Accessing Home PC from office PC without logmein or hamachi for free.

For this we can use amazon aws micro instance as our vpn server and home PC and office PC as vpn clients.

  1. Set up amazon aws micro ubuntu instance – This is free if you have an amazon account
  2. Install Neo Router‘s Product called Neo Router Free on the Amazon cloud server
  3. Open the required ports on the Amazon cloud server
  4. Install the clients on the machine that you want to make part of network

Thats it for now. I will try to provide the details instructions, whenever I am free :)

PHP Applications, like vtiger, joomla wordpress etc blank page issue

So, this is a very stupid issue, and a really annoying one as well :) . But really simple to fix. These instructions are valid for apache 2.2.22, with default settings

Diagnosis

run following command

 
   tail /var/log/apache2/error.log

If you see something like following


[Wed Feb 20 19:31:19 2013] [error] [client 127.0.0.1] 
PHP Warning:  Cannot modify header information - headers already sent by (output started at 

/var/www/vtiger/include/utils/ListViewUtils.php:1) in /var/www/vtiger/index.php on line 91

“/var/www/vtiger/include/utils/ListViewUtils.php” could be any file path, similarly “/var/www/vtiger/index.php” could be any path as well. The key over here is the :1. That means the issue is at the line 1. This might be because of something called Byte Order Mark or BOM.

Fix

Open “/var/www/vtiger/include/utils/ListViewUtils.php” in vim
and save the file without a BOM:

        :setlocal nobomb 
        :w 

To ask Vim if there is a BOM:

        :setlocal bomb? 

Simple, this should fix it.

BackgroundWorker’s RunWorkerCompleted event’s weird behavior in Outlook Add In developed using VSTO 4.0

If one uses “BackgroundWorker” class in an application.Then, as per the documentation and the discussion found online. It is suppose to raise “RunWorkerCompleted” and “ProgressChanged” on the same thread. On which the object of “BackgroundWorker” was created. Which in case of Windows form application would be UI Thread.

But, if one uses “BackgroundWorker” class in an Outlook Add In developed using VSTO 4.0. Then “RunWorkerCompleted” works differently and it is raised on different thread then UI Thread.

One of the possible explanation of this behavior can be found here. What it states that only in case of GUI Windows Forms it is suppose to behave that way. Since, BackgroundWorker uses the synchronization model provided by SynchronizationContext.Current to dispatch events.

In that case the only thing to rescue is InvokeRequired and Invoke . Details of How to use these can be found here.

Delegates in C# Basics and Advanced

Recently, I was reading C# In Depth, By Jon Skeet. It is one of the best books about learn advanced details about C#. While reading the book, I decided to prepare notes. So, that I can just go through the notes to revise, If I have to. Following are the points about the delegates that I read in the book.

1. Delegate is a strongly typed function pointer (Simple but vague)
2. Delegate term is often used for delegate type as well as instance. So, better to be clear is it delegate type or delegate instance.
3. Delegate type is like an interface with a method
4. Delegate type is just another type in C#. A delegate type inherits System.MulticastDelegate which in turn inherits from System.Delegate
5. Delegate instance has a list of actions/methods (Multicast Delegate). This is called invocation list.
6. Delegate type uses 2 methods of System.Delegate Class called “Combine” and “Remove” to add actions/methods as well as remove actions/methods
7. Delegate instance are immutable like string, each addition(+ or +=) causes creation of one more instance and actions are copied over. Same is true for removal using – or -= which in turn calls Remove.
8. “Invoke” method causes the invocation of all the actions/methods in the invocation list
9. All of the actions are executed in order. But the value returned is the value returned by the last action, or if you wish to have return value of each method/action then invoke using “Delegate.GetInvocationList”
10. If any one methods in invocation list throws an exception, Invocation is stopped and remaining methods/actions are not invoked/executed.