Monthly Archives: August 2015

Adventures in ASP.NET MVC: A migration experiment from Laravel

Back in early 2014, my office briefly put me in a production support rotation for our flagship application built on ASP.NET. I’ve been wanting to get out of the PHP ghetto for a while, and I’ve experimented with building desktop applications with the .NET framework in the past.

So I bought some books and snagged a copy of Visual Studio 2012 to practice on my own. I made some tentative step in porting the Observant Records Administration site from PHP to C#. Then my rotation ended abruptly because business needs pulled me back into the PHP ghetto. I haven’t touched ASP.NET since then.

A recent lull allowed me to pull out that old abandoned code. Since then, Entity Framework and ASP.NET under went some revisions. I also ported the Observant Records Administration site from CodeIgniter to Laravel.

During that conversion, I noticed how much Laravel resembled ASP.NET MVC, which probably owes a lot from Ruby on Rails. Even Laravel’s templating engine, Blade, is a knock-off of ASP.NET MVC’s Razor.

So what would happen if I attempted to convert a Laravel application to ASP.NET MVC?

I spent few weeks at the start of 2015 finding out.

And just to make things interesting, the application I was building in ASP.NET MVC connects to my development MySQL database, not SQL Server.

So how did it go? Well, I got far enough to get a gist of how much would need to be refactored, then realized I would never launch it since I don’t have a production environment.

But I learned a lot about crossing programming cultures, which would be easiest to enumerate in a list.

PHP vs. C#

I’ve long ago adjusted to switching between static and dynamic typing. In fact, PHP best practices have moved to emulate static typing, and type hinting certainly bridges the gap between the two language styles. Part of me even looks forward to the strict mode in PHP7.

Although namespaces have been available since PHP 5.3, many of my projects have a lot of legacy code that predate their usage. I’ve slowly gotten into the habit of using namespaces, but the differences in how they work in PHP compared to C# and JAVA tripped me up quite a few times.

For example, I wanted to parse some JSON input in my ASP.NET MVC application, but Intellisense in Visual Studio didn’t recognize the JSON library in my controller. It turns out a library in ASP.NET MVC has a JSON property, so to parse JSON itself, I needed to import a different library.

If I worked more with namespaces, I would have realized it sooner.

C# vs. .NET

In the beginning, I thought I hated JavaScript, until I used JScript with ASP 3.0. I realized I didn’t mind JavaScript at all. It was the Document Object Model I hated.

A similar distinction can be made between C# and .NET. Although they’re tightly coupled in terms of how they’re discussed, they’re actually distinct entities. C# is a language; .NET is a framework. You use C# to manipulate the .NET framework.

It’s not too difficult to jump from another language to C#. The larger leap is navigating the .NET framework.

That’s where I felt most out of my depth. I would jump on the MSDN Library to figure something out, then to whatever search results to which Google directed me. And even after getting something working, I would be left with a sense that I didn’t come away with a complete picture of how everything worked.

A lot of this conversion process involved gleaning the underpinning machinations of Entity Framework without diving too far into the innards. I wanted to get something working, and I didn’t want to sink so much time fishing for the documentation to get me there.

Microsoft vs. not-Microsoft

Laravel’s Eloquent is an active record ORM, while Entity Framework is a data mapping ORM. There’s no point trying to compare the two since they operate on different paradigms.

Most of the applications with which I’ve worked use active record ORMs. SugarCRM is the only data mapper I’d encountered till grappling with Entity Framework and its Fluent API.

There are a lot of tutorials and examples out in the wild to explain how model properties map to database columns, and just about all of them assume you’re working within the Microsoft ecosystem of Visual Studio/IIS/SQL Server.

So it took a lot of debugging and random flaling to hit on a pretty important aspect about mapping to a MySQL source.

Here’s a simple example.

public class ArtistMap : EntityTypeConfiguration
    {

        public ArtistMap()
        {
            // Primary Key
            this.HasKey(t => t.Id);

            // Properties
            this.Property(t => t.DisplayName).HasMaxLength(255);

            // Table & Column Mappings
            this.Property(t => t.Id).HasColumnName("artist_id");
            this.Property(t => t.DisplayName).HasColumnName("artist_display_name");
            this.ToTable("ep4_artists");
        }

Most tutorial examples for the HasColumnName method plug in the name of a model property straight into the method without explaining that the column name and model property are spelled exactly the same. That doesn’t quite work if your database schema predates the code and already has its own naming convention.

In my example, artist_display_name is the name of my column, and I want it mapped to the DisplayName property of my model. At first, I followed the examples — good old copy and paste! — and got nowhere because, duh, my database column is not named DisplayName.

This kind of assumption is reflective more of a culture than a platform. PHP programmers speak in a slightly different dialect than .NET programmers, even if we’re both speaking “programmer”. So when an interloper such as myself attempts to speak another culture’s dialect, subtext will always be missing in action.

 

How to customize controllers generated by Artisan in Laravel

I’m porting a web-based application I built in the office from CodeIgniter to Laravel, and I’m relying a lot on Artisan to generate REST controllers. I’m not doing anything terribly fancy with the generated controllers, so I end up copying and pasting a lot of code.

Yes, I could probably design this application to prevent all that copying and pasting, but it’s for a system that I intend to retire in the next 18 months. So I’m not hung up on cleverness.

Instead, I wanted to find a way to generate as much code as possible so the refactoring work concentrates mostly on refinement.

Artisan make commands generate very minimal scaffolds for models and controllers. What if you wanted Artisan to generate something with more meat on the bones?

That’s where the ControllerMakeCommand class comes in.

I found this class by performing a search of the Laravel vendor folder for one of the help strings in the php artisan list command. The class itself extends GeneratorCommand. By studying these classes, I could see extending ControllerMakeCommand and overriding a few methods could get me on my way to creating my own controllers.

Of course, you need to know a little bit about how to create your own Artisan commands before you can create your own controllers. I won’t go over that since the Laravel documentation does a good job of it already.

Here’s an example of an extended ControllerMakeCommand

<?php namespace App\Console\Commands; use Illuminate\Routing\Console\ControllerMakeCommand;


class CustomControllerMakeCommand extends ControllerMakeCommand {
     protected $name = 'example:controller';
     protected $description = 'Create a customized controller in Laravel.';

     protected function getStub()
     {
         return __DIR__.'/stubs/controller.custom.stub';
     }

     protected function buildClass($name)
     {
         $stub = $this->files->get($this->getStub());

        return $this->replaceNamespace($stub, $name)->replaceScaffold($stub)->replaceClass($stub, $name);
     }

    protected function replaceScaffold(&$stub)
    {
        // Parse input name.
        $name = str_replace('Controller', '', $this->getNameInput());

        // Create replacements
        $viewPathName = strtolower(str_replace('\\', '.', $name) );

        // Apply replacements
        $stub = str_replace('dummyViewPath', $viewPathName, $stub);

        return $this;
    }
}

ControllerMakeCommand reads a text file and substitutes strings in the file with values based on the namespace. To customize our controllers, we want our Artisan command to use our own text file instead of the one used by the parent class. So we override the getStub method in CustomControllerMakeCommand to point to a text file we prefer. In this example, it’s the directory in which our customized class resides, i.e. app/Console/Commands.

The controller.custom.stub file, then, contains your customized controller code.

The overridden buildClass method reads the .stub file and performs string processing. It usually processes the namespace (replaceNamespace) and the class name (replaceClass). You can inject additional string processing between these method calls, which is what replaceScaffold does. Note that the method returns the object reference ($this), not the processed string. Returning the object reference allows for chaining. replaceClass returns the final processed string.

The fire method in the grandparent GeneratorCommand class then generates the actual controller files with the string created by CustomControllerMakeCommand. All that’s left to use your custom command is to register it.

Models can also be customized in a similar fashion by extending the ModelMakeCommand class. Since it too extends GeneratorCommand, the same methods, particularly getStub, can be overridden.