Alexander Beletsky's Development Blog: 2011-07

How to be better developer or 3 accounts rule

Oh no, not again! - you might think. Yet another Mr.SmartyPants are going to share his own vision of how to improve in development.

I'll say very obvious thing - if you are going to be great in something, you have to do that a lot. Like, if you going to be a great snowboarder you have to ride a lot; If you going to be great mathematician you have to solve a lot of problems; If you going to be great developer you simply have to do a lot programming :).

The road from "good to great" is long and difficult, you could not be great in one year.. or ten, or even whole life. But what you definitely can do, be a better. Only realizing that you are better than yesterday (month, year ago) is a great benefit, believe me.

But just the fact of knowing "I need to do something a lot" would hardly could help you to progress. What you need to have is indicators. Simple criteria's that make you understand what your progress is. Are doing great or you suck?

Three account's that I created almost year ago, help me to get those indicators.

  • github.com - producing of code, that what we do. you have to have github to store all code you produce, doesn't matter it is a product or tool or just a gist you created to help someone - it have to be stored. with a github you should be able to see how much you coding are changing through the time. you should review you last year code and think "Oh, God I suck a lot!".
  • blogger.com - besides of code writing, you have to share your technical thoughts. the blog, is a great motivator for seeking and sharing knowledge. as well as coding, blogging requires much skills. I see some relation between producing good code and good post. blog would also help you to look back, to remind you problems you was thinking of.. and how much you were right on that? is your opinion changed on some topics or not?
  • stackoverflow.com - if you can't explain something to another, you don't understand it. giving an answers is extremely difficult, especially in such competitive environment as stackoverflow. the time I created account there I was not able to give any answer in meaningful time. I just had not enough skills for that. stackoverflow is great indicator, since it contains a reputation system.

Well, do you think it is useful? It works for me and I'm going to proceed.

PS. That's my 100 post for this blog.. and that's my Friday before week vacation.

A little bit on Javascript magic inside C# code

C# and Javascript are both my favorite languages. I believe that those two are best languages in a world (perhaps I haven't started to learn Ruby). With a quite long practice in Javascript, you start to feel real power of dynamic language. Even more, you are so much get used for particular code constructions that you try to do the same things in C#.

This is something you might do in javascript a lot. Consider that code,

code

Method createConfig takes options object, dynamically construct config object and returns it back to client. Maybe it is the best example, but shows - I dynamically able to construct an object, just putting new properties into it.

Now, let's try to do that same with C#. Believe me or not, but I can do exactly (OK, mostly exactly) code with C#.

code

We can play "Find a difference" game here. Anyway, what I can say: "anonymous types + dynamic + ExtendoObject", is a magic spell that turn you C# code into Javascript.

  • With Anonymous Types you easy get a notion of JavaScript dynamic object, just use new { MyProp = 1 } JavaScript analog { MyProp: 1 }.
  • Dynamic would tell to compiler - "Do not check my type now, let Runtime do that". So, with dynamic objects you can do obj.MyProp, compiler would allow this code, existence of property would be checked on runtime, if absent - exception will be thrown.
  • ExpandoObject is a super-power of .NET, allows you to construct object at runtime. You can see, that I just assign new property, that property would be dynamically added to config object.

Life would not be so interesting if every thing is so easy. My first implementation failed to work, in line if (option.Ip || option.Proto) then I called createConfig with object that actually contains no such properties. As I said above, dynamic simply throws an exception if property is missing. I could wrap code in some try / catch cases, but it would be to ugly and magic would gone. We have to extend our magic formula with one component - Reflection. So, let's pronounce spell again, "anonymous types + dynamic + ExtendoObject + Reflection" and check out final secret piece of code.

DynamicProxy is simple wrapper around the dynamic, it overloads [] operator and check availability of property using Reflection.

code

That's it. I've made C# code look like and behave like JavaScript, utilizing power of .NET platform. As always, you can find a source code on github - csharp-js.

Disclaimer

You should not probably doing such tricks a lot. C# is still static language (even with dynamic features in it). It is better to rely on types, wherever it is possible to.. The code above is created to solve my particular problem and I had a lot of fun detecting this C# and JavaScript analogy. But now I still thinking to re-write that to statically typed less-beauty, less-magic solution :).

Switching from ASPX to Razor view engine

I've been moving my application to MVC3 quite time ago. There was absolutely no issues of migration, everything that worked OK in MVC2 worked fine with MVC3. One of major feature that MVC3 brings with is Razor. Razor is view engine which combines HTML and code in very elegant fashion. Just from first sight to Razor you begin to understand how much ASPX sucks (I don't blame ASPX since it has been designed for WebForms, actually.. and it just does not fit MVC much).

Of cause, till that time I had a lot of already made markup with ASPX. I have register task to switch all my views to Razor. But for a long time it's being un-touched, I just been either doing some other things or too lazy for that kind of job. Yes, it is not very exiting to change *.aspx to *.cshtml.. Finally I put all my will on that, thinking better late than never.

And you know, it was not so difficult and boring as I originally thought. Here are some obvious tips:

  • Rename file from *.aspx to *.cshtml
  • If you have master page like (Public.Master) change it to _PublicLayout.cshtml (Razor don't use term Master, but rather Layout)
  • <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Web.Models.LastArticleFromBlogModel>" %> became @model Web.Models.LastArticleFromBlogModel
  • <asp:ContentPlaceHolder ID="head" runat="server"/> became @RenderSection("Head", required: false) in Layout pages
  • <asp:ContentPlaceHolder ID="maincontent" runat="server"> became @RenderBody() in Layout pages
  • <%@Import Namespace="Web.Helpers.Extensions" %> became @using Web.Helpers.Extensions
  • <%: are changed to @ and %> changed to nothing (I simply used Find&Replace for that)
  • At the top of content page
    @{
     ViewBag.Title = "Admin | Admin Dashboard";
     Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
    }
  • For content pages, everything that is inside is Body (no special sections for that)
  • If you need to override Head section, simply @section Head { }
  • Layout could be nested, in nested Layout page you should mention parent Layout, like above

That's basically it.. Along the way I've changed all HTML to comply HTML5 standard and reformatted (with Ctrl K + Ctrl D) and now markup looks definitely better!

One really strange issue I should mention. As soon as I finished and pushed code to github my friend Jenkins immediately picked up changed and deployed them. But I as went to check it, I got 404 Error just from very beginning. After investigation I found the reason - as I was just renaming files *.aspx to *.cshtml, in *.csproj (project file) all of them are became in "None" item, instead on "Content".. and site publishing just ignored that items. I have to manually change it back, as soon as I committed, it started to work like charm.

So, there are no any technical issues with moving from ASPX to Razor, just don't be to lazy and do it today :)

Git with SVN, what the benefits are?

My previous post about starting up of using Git inside on SVN organization appeared to be really attractive, I received many questions through twitter and dzone. All of them are really interesting and I going to do a separate posting on that, but primary question is "Why, oh why?".

So, what actual benefits I see by using approach of git-svn?

First, let's see the root, what kind of VCS Git is? It is distributed one. The distribution basically means that each developer host the repository on it's own machine. Not a working copy as in SVN case, but real repository with all corresponding functionality - commits, reverts, branches, merges etc. You are not longer depend on server, even if sever is not available you still able to continue your job.

Since you have your local repository, you can do whatever you want without interfering the rest of the world. In SVN all operations like commit or branch creation or tag - they are global one. As soon as you created branch for instance, everybody will notice that; if you committed something, everybody will notice that. In many organizations SVN has policies, like you have access only for some branches.. you can't create branches, only by request to admin etc. But, what I basically do on my job - I want to try out something (new idea or apply some refactoring) without disturbing a lot of people, I want that quickly. It perfectly works with Git, I create the branch just by one command, work inside (means do what ever number of commits I want) and if I think I'm ready, merge it back to master and push changes to SVN.

Remember you last merge operation with SVN? If you haven't seen 'Tree conflict' type of conflict, you are not SVN user. I've seen them a lot and many people suffer much of it! This type of conflict happens because SVN keeping and tracking information about folder in which file is placed. Git does not do that, it is basically content tracking system - Git cares about content of the file, not file it self. Since the information about content (blob) and filesystem information (tree) is separated each of other, you will never get a 'Tree conflict' in Git.

By the fact that branches and merges are very easy in Git you are getting one really cool bonus. Have you ever been in situation then in a middle of your flow, then tens files are already changed, but you still struggling with task, your boss is contacting you saying - 'Hey, we have critical bug, required to be fixed now'? Such things make you a little uncomfortable, you already got some changes, but they are not 'commitable'.. you could not throw it away, because some value is already there, but you need to get SVN update and start to fix bug. With git, you can switch from one task to another with out any problems. You just commit your results (even if they are not compliable or tests are red, who cares - it's yours repository) create another branch for bugfix and start to work.

To summarize that a little I would say that my personal benefits of starting using Git are:

  • Isolation - do whatever I want, whenever I want
  • Merges - forget about 'Tree conflicts'
  • Task switching - no more, "please wait till I commit this, so I can start to work on that"
  • Fun - it is interesting to me to learn new system and to change a mind how VCS can work

Inside ASP.NET MVC: ControllerBuilder class

Integral part of MvcHanlder is ControllerBuilder. ControllerBuilder is a singleton that is responsible to produce IControllerFactory instance.

controller builder

Construction

ControllerBuilder have 2 constructors, the default one and one with parameter. One of the major changes between MVC2 and MVC3 was the improvements of Dependency Injection. MVC is using Service Locator pattern for resolving dependencies.Default constructor calls constructor with parameter, passing null as argument, saying that SingleServiceResolver object have to be used as default service resolver.

Please note, even if MVC is using Service Locator to locate different entities (like Controllers, Views, Filters) and so on, it does not include any kind on IoC frameworks itself.

Controller factory get/set

MvcHanlder uses GetControllerFactory method to get controller factory.

controller builder

Method itself is fairly simple, it just ask service resolver to get current instance of controller factory.

Setter method allows you to change default controller factory with custom one. This an extremely useful then you want to change the way of Controller creation. The most useful case is delegate the controller creation to some DI container (Ninject, Unity, StructureMap) to allowing your application to get benefits of using IoC principles.

Basically, IControllerFactory is a strategy of controller creation. Depending of implementation it might use different techniques, later on we will see how DefaultControllerFactory works.

As and additional option, it is possible to supply custom controller factory just from the specific type

controller builder

Substitute default controller factory

As you see, we have to options of substitution default factory:

  1. Call SetControllerFactory method and pass custom object into.
  2. Implementing new IDependencyResolver.

Here is an example of how that could be done (please note, it is just demostartion.. you typically should not use both approaches in the same type).

controller builder

Conclusions

ControllerBuilder is simple class that delegates responsibility to IResolver which is responsible to resolve IControllerFactory instance. IControllerFactory is a strategy of controllers creation. ControllerBuilder is designed in a way of chaning this strategy easily, either by using custom IControllerFactory or by custom IDependencyResolver.

What is next?

Next we are going to look closer into SingleServiceResolver and see how it actually acts for resolving types.

Previous: Inside ASP.NET MVC: All begins here - MvcHanlder