Monday, April 16, 2012

Creating a Structure for a web page using Razor Syntax

Generally a web page contains several different parts. For example, Header content, Navigation pane, Common page layout items, Common page markups (CSS, Scripts), etc. So these parts should be managed properly. All of these parts should not be loaded always and should behave separately. To handle these burdens, we should manage a proper structure for the page.

In ASP.NET web forms, you can do this using master pages, content pages, user controls, place holders and likewise. But with ASP.NET MVC 3 and Razor View Engine, you can achieve more complex structures and behaviors than web forms. Razor View Engine is the power of ASP.NET MVC 3 and its API lies on top of ASP.NET API. This API gives us all the facilities to maintain the structure of the page.

 (image source :

 I’ll explain step by step, how to make a structure for your ASP.NET web page.

01). in the default MVC 3 project, you can see a folder “~/Views/Shared”. This folder is the place for the content that is shared among all controllers.

 It contains a file called “_Layout.cshtml”.

(Note: As a practice, we put ‘_’ before the file name, if it is definitely used with some other View)

This file is the Master page for all the views. You can add all unaltered content of your site like Search bar, Navigation Pane, Script and CSS links (Common Page Markups) into this file.

How is this set as the master page?

Here you can see a code line in this file as “@RenderBody()”. This line allocates a space to render a View into this page. Then you should set the layout on top of your View as,

                     Layout = "~/Views/Shared/_Layout.cshtml";

But this is not required to do in all View files. You can do it in ViewStart.cshtml file, as you see in default MVC 3 project. Because web servers go through ViewStart file, for all web requests, before it goes to any other View file.  Only when you use different Layout, you can set it in particular View file.

02). There is another Razor method called “RenderSection()”. It gives more control on rendering. There you can specify a part of the View file that should be rendered in one place.

This false value says that the section is not “required”. Unless it gives an Error Message saying “the section is not declared”.

03). if you want to render the content of another View file into the file that you are working in, you can use “RenderPartial(<file name>)” method.
It doesn’t need more work. You can just type @RenderPartial(<file name>), and it will render the whole content into the file.

I think using these methods; you can create any complex structure for your Web Site.

Tuesday, April 10, 2012

Working with JSON

JSON, Java Script Object Notation, is a lightweight data-interchange format. Simply it’s a text format that is used to represent Objects of any Programming Language. When two systems communicate using JSON, they parse JSON Objects into their runtime Objects and send the results back again in JSON.

This is the official site for JSON. It explains the structure and functions of JSON clearly.

I found this Stack Overflaw Question on how to check a JSON Object for a particular property. When I’m working on this, I found that there are no many options to work with JSON objects directly. Most popular way is to convert the JSON Object into a JS Object and work with it. So this is the way of converting a JSON Object into a JS Object and check for a property in it.

//The JSON Object
var JSONObject={  "element1":
"element2": { "Number":  "0" },
"element3": { "Number":  "1" },
"element4": { "Number":  "2" }

//Converting JSON into JS
var JSObject=eval('('JSONObject + ')');

//Check whether there is a property called “element3”
var IsExistElement3 = JSObject.element1.hasOwnProperty("element3");

Thursday, April 5, 2012

Introduction to ASP.NET MVC3

If you are an ASP.NET web forms developer, you will not like to shift to MVC3 so quickly, because it’s not providing “drag and drop”. But when you get familiarize with MVC3 and Razor view engine, you will be amazed with its customizability. You can use web forms view engines as well in MVC3. But Razor provides syntax easier than web forms.

If you are confusing about what exactly this “View Engine” means, simply that is the part of .NET Framework that compiles the Server side code that we write in our .aspx or .cshtml files.

You can just shift from HTML code to C# code and vice versa, just using an “@” sign, not like open close tags of web forms, pretty much easier.

If you are using VS 2010, it has lot of supports to scaffold (generate) views and controllers for basic Add, Edit, Delete, Details and List View operations.

This is the MSDN article for MVC3.

and the Video Tutorials for “MVC3 – Razor”

This set of tutorials explains clearly how to make a simple MVC3 site with the support of SQL Server and Entity Framework.

As they mentioned in the tutorial as well, adding controllers and Views are supported with dedicated windows in VS 2010. They are so helpful to generate the basic code that is used in any project.

Add Controller Window

Add View Window

But if you want to do advance developments, definitely you should hack into this generated code and learn to modify it. Hope to explain it in my Next Blog Post.

Thursday, January 19, 2012

Data Migrations for Continuous Integration

Why we need Data Migrations for CI

In a typical Software Project, there are several developers who are working on a shared source code, and QA people use another version for testing and there may be another version in Production Server. Then can we make sure that all of these people get the latest version that comes out of the developer’s environment?
Yes. If we can push the changes everywhere (Build Server, Test Server and Production Server) as soon as someone commits his changes, then the problem is solved. But this should be performed automatically, since it’s tedious to do the same thing again and again by a human been. To do this, we need to configure the build server to,
     ·         Pull the latest version from the source controller
     ·         Build the project.
     ·         Make deployable packages with relevant configuration files
     ·         Copy files into relevant server. 

      below diagram depicts the work flow.

s  Here you can see a comprehensive explanation of doing this using Jenkins build server.
Purpose of this post is to explain the importance and necessity of Data Migrations in this process.

Problems of doing this

When we use Entity Framework Code First approach, we get a typical error “the model backing the context has changed since the database was created”. This occurs when the model in our code and model in DB are different. To prevent this error, people were using implementations of “IDatabaseInitializer” interface. With this interface, we have to drop and create either entire DB or set of tables. This results a complete data loss. We can preserve only a set of master data by executing some SQL scripts.


While a lot of people concern about this matter, Microsoft has come up with an intuitive solution – Migrations. Now they have released its beta version. This package can change most of the database changes at the moment while preserving your data.
It has two work flows.

      01)  Code Base Migration – Generates the code and let developer to do required changes.(sample)
   02)  Auto Migration – Generates and applies the changes automatically.(sample)

  Migration creates a table in the database named as “MigrationHistory”. It contains all the migrations applied to the database.

Tips and Tricks for Data Migrations

In above samples given in the MSDN Blog, it explains the way of applying Migration using Package Console (Power Shell). But it’s not enough for a real project. We need to execute migration commands using our code. So I wrote to the owner of that post asking the methods that are invoked by those power shell commands. Then Brice Lambson from Microsoft sent me following map between power shell command and Migration API.

·         Update-Database = DbMigrator.Update
·         Update-Database -Script = MigratorScriptingDecorator.ScriptUpdate
·         Add-Migration = MigrationScaffolder.Scaffold
·         Get-Migrations = DbMigrator.GetDatabaseMigration

Then I could use many interesting features by hacking into these classes. Here is simply how we can apply automatic migrations using C#.

DbMigrationsConfiguration configuration = new DbMigrationsConfiguration()
                MigrationsAssembly = typeof(ProductContext).Assembly,
                ContextType = typeof(ProductContext),
                AutomaticMigrationsEnabled = false,

DbMigrator dbMigrator = new DbMigrator(configuration);

By examine above classes further, you will be able to play with Migrations nicely.


Saturday, April 2, 2011

Computer Engineer?


Among the various types of engineering fields, Computer Engineering is also another creative and highly intuitive Engineering Field. But for a long time, it was not mentioned as a separate type in many professional bodies. Institute of Engineering Sri Lanka accepted and categorized computer engineering into Information technology and Computer Engineering Category since 2010.
Then to be a Computer Engineer, what are the qualifications that should be fulfilled by someone. Most of people may answer this question as “follow a degree in computer science and engineering”. Then the hidden meaning of that answer is that doing another type of IT degree is not a qualification to be a computer engineer. Actually according to the convention, Computer Science and Engineering graduates are only considered as Computer Engineers. People who follow some IT degrees go to the category of IT professionals and People with Computer Science degrees, go to the category of Computer Scientists. But the problem is most of the Computer Science students do not have an ambition to be a Computer Scientist and end up as a Software Engineer.
My PoC is that none of these degrees are not the one and only way to be a Computer Engineer. Here I should mention that Software Engineer and Computer Engineer are two different characters, though both of them make software. Computer Engineer is a person who applied the theories of computing and latest hardware and networking technologies efficiently to overcome real world problems. Software Engineer engages in the software part of this big role. So being a computer engineer depends only on just someone’s knowledge and attitudes. People with very high education qualifications may not have the viewpoint to be a computer engineer. They just think from one side towards problem or always try to give typical solutions to the problems. There may be rarely some other people with law qualifications but who think as real engineers towards the problems.
So, if you want to be a Computer Engineer what you should do? You should improve your skills and attitude. Degree is enough to acquire some professional recognition. Knowledge of a computer engineer should spread through all the areas related to computing. He should know the h/w architecture and how they operate. If not he cannot use available resources efficiently. In software phase, he should know about s/w technologies and architectures that he is working in, in order to develop a better solution. At present, most of the systems run on the network. Solutions run on a local machine are not enough anymore. So the knowledge about basics of networking is also very important to a computer engineer. In addition to these, creativity, hard working and innovation makes him better.
These are the things that make a computer engineer, according to my point of view. Wish you all the best!