Wednesday 29 July 2015

[Asp.Net] Why Asp.Net MVC?

Problems with Asp.Net Web Forms

So when ASP.NET Webform was so successful, why Microsoft thought of creating ASP.NET MVC.The main problem with ASP.NET Webform is performance, performance and performance. In web application there are two aspects which define performance:
  1. Response time: - How fast the server responds to request?.
  2. Bandwidth consumption: - How much data is sent ?.

Response time issues

 Let us try to understand why response time is slower when it comes to ASP.NET Webforms. We did a small load testing experiment of Webform vs Asp.Net MVC and we found Asp.Net MVC to be twice faster.
Read more on how this test was done from here
Let us try to understand why ASP.NET MVC was better in performance in the above load test.Consider the below simple UI code and Code behind for that UI.
Assume the ASPX code has the below simple text box.

In the code behind you have written some logic which manipulates the text box values and the back ground color.
protected void Page_Load(object sender, EventArgs e)
{
            TextBox1.Text = "Make it simple";
            TextBox1.BackColor = Color.Aqua;
}

When you run the above program below is the HTML output.

If you see the HTML output by doing view source it looks something as shown below.


Now stop reading for a moment, close your eyes and think. Try to get answers to the below questions:
  1. Is this a efficient way of generating HTML?. Do we really need to make those long server trips to get those simple HTML on the browser ?.
  2. Can’t the developer write HTML straight forward, Is it so tough?

If you see for every request there is a conversion logic which runs and converts the server controls to HTML output.This conversion get’s worse and heavy when we have grids, tree view controls etc where the HTML outputs are complicated HTML tables. Due to this unnecessary conversion the response time is less.
Solution for this problem: “GET RID of CODE BEHIND”, fold your sleeves and work with pure HTML.

Bandwidth consumption

Viewstate has been a very dear and near friend of ASP.NET developers for past 10 years because it automatically saves states between post backs and reduces our development time. But this reduction in development time comes at a huge cost, viewstate increases the page size considerably. In this load test we found viewstate increases the page size twice as compared to Asp.Net MVC.
Below is the plot of the content length emitted from Webform and Asp.Net MVC.


The size increase is because of extra bytes generated from viewstate, below is the snapshot of a viewstate. Lot of people can argue that viewstate can be disabled but then we all know how developers are, if there is option given they would definitely try that out.



Solution for this problem: “GET RID of SERVER CONTROLS”.
Note: The rest of the three points down below are browny issues which have cropped up due to presence of code behind and server controls. But the main thing is always performance.

HTML customization

Now because we are salves of the code behind and ASP.NET web server controls, we have “NO IDEA” what kind of HTML can come out and how efficient they are. For example see the below ASPX code, can you guess what kind of HTML it will generate.


I am a panel
Will Label generate DIV tag or SPAN tag ?. If you run the above code below are the respective generated HTML. Label generates a SPAN , Literal generates simple text , Panel generates DIV tag and so on.
I am label
I am a literal
I am a panel
So rather than generating HTML using server controls how about writing HTML directly and taking complete control of HTML.
So the solution for this problem is “DO NOT USE SERVER CONTROLS” and work with direct HTML.
The other great benefit of working directly with HTML is that your web designers can work very closely with the developer team. They can take the HTML code put in their favorite designer tool like dream weaver, front page etc and design independently. If we have server controls these designer tools do not identify them easily.

Reusability of code behind class

If you watch any professional ASP.NET Webform project you will notice that code behind class is where you have huge amount of code and the code is really complicated.Now this code behind page class inherits from “System.Web.UI.Page” class. This class is not a normal class which can be reused and instantiated anywhere. In other words you can never do something as shown below for a Webform class:
WebForm1 obj = new WebForm1();
obj.Button1_Click();

Because the “WebForm” class cannot instantiate with out “request” and “response” object. If you have ever seen the “ButtonClick” events of “WebForm” they are as shown in the code below. From the code you can know how difficult it is to instantiate the same.
protected void Button1_Click(object sender, EventArgs e)
{
// The logic which you want to reuse and invoke
}

Solution for this problem: “GET RID of SERVER CONTROLS and CODE BEHIND”.

Unit Testing

As said in the previous section you cannot instantiate behind code straight forward it’s very difficult to do unit testing or I will say automation testing on the code behind. Someone has to manually run the application and do the testing.

Reference: http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day

[Asp.Net MVC] Passing Data from Controller to View

When we work with data in Asp.Net MVC, one important task is passing data from Controller to View for displaying. So how many way can we pass data from Controller to View? and which way should we choose? We are going to see in this post.

There are 3 ways:
  1. ViewData
  2. ViewBag
  3. Strongly Typed View

ViewData

ViewData is a dictionary, which will contains data to be passed between controller and views. Controller will add items to this dictionary and view reads from it.

Store data in ViewData in Controller:

ViewData["Employee"] = emp;
return View("MyView");

 Display data in View:

<div>
    @{
        WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee)
            ViewData["Employee"];
    }

<b>Employee Details </b><br />
    Employee Name : @emp.FirstName @emp.LastName <br />
    Employee Name : @(emp.FirstName emp.LastName) <br />
    Employee Name : @ViewData["Employee"].FirstName @ViewData["Employee"].LastName <br />
    Employee Name : @(ViewData["Employee"].FirstName + " " + ViewData["Employee"].LastName) <br />
    Employee Salary: @emp.Salary.ToString("C")
</div>

ViewBag

ViewBag is just a wrapper for ViewData. ViewBag uses the dynamic feature of C# 4.0 and makes ViewData dynamic.

Store data in ViewBag in Controller:

ViewBag.Employee = emp;
return View("MyView");

 Display data in View:

<div>
    @{
        WebApplication1.Models.Employee emp = (WebApplication1.Models.Employee)
            ViewBag.Employee;
    }

<b>Employee Details </b><br />
    Employee Name : @emp.FirstName @emp.LastName <br />
    Employee Name : @(emp.FirstName emp.LastName) <br />
    Employee Name : @ViewBag.Employee.FirstName @ViewBag.Employee.LastName <br />
    Employee Name : @(ViewBag.Employee.FirstName + " " + ViewBag.Employee.LastName) <br />
    Employee Salary: @emp.Salary.ToString("C")
</div>

Problems with ViewData and ViewBag

ViewData and ViewBag is a good option for passing values between Controller and View. But in real time projects it’s not a good practice to use any of them. Let’s discuss couple of disadvantages of using ViewData and ViewBag.

Performance issues

Values inside the ViewData are of type Object. We have to cast the value to correct type before using it. It adds additional overhead on performance.

No Type safety and no compile time errors

If we try to cast values to wrong type or if we use wrong keys while retrieving the values, we will get runtime error. As a good programming practice, error should be tackled in compiled time.

No Proper connection between Data sent and Data Received


In MVC, controller and View are loosely connected to each other. Controller is completely unaware about what’s happening in View and View is unaware about what’s happening in Controller.
From Controller we can pass one or more ViewData/ViewBag values. Now when Developer writes a View, he/she have to remember what is coming from the controller. If Controller developer is different from View developer then it becomes even more difficult. Complete unawareness. It leads to many run time issues and inefficiency in development.

Understand strongly typed Views

Reason for all three problems of ViewData and ViewBag is the data type. Data type of values inside ViewData, which is “Object”.
Somehow if we were able to set the type of data which need to be passed between Controller and View problem will get solved and that’s wherestrongly typed Views comes to picture.

Step 1 – Make View a strongly typed view

Add following statement in the top of the View

@model WebApplication1.Models.Employee
 
Above statement make our View a strongly typed view of type Employee.

Step 2 – Display Data

Now inside View simply type @Model and Dot (.) and in intellisense you will get all the properties of Model (Employee) class.




Step 3 – Pass Model data from Controller Action method

Change the code in the action method to following.

Employee emp = new Employee();
emp.FirstName = "Sukesh";
emp.LastName="Marla";
emp.Salary = 20000;           
return View("MyView",emp);

Conclusion 

Although it's a best practice to use strongly typed view when we need to pass data from Controller to View, it's OK to use ViewBag when appropriate. To be more specific, anything you want strongly-typed in your view, then, needs to be on your model. If you have something you don't want on your model or that is one-off, then ViewBag is provided as a generic catch-all for all non-model data, which is why it is a dynamic.

Reference: http://www.codeproject.com/Articles/897559/Learn-MVC-in-days-Day

Wednesday 22 July 2015

[iOS] How to avoid Redefinition of 'Category' as different kind of symbol error in Xcode

Reference: http://pinkstone.co.uk/how-to-avoid-redefinition-of-category-as-different-kind-of-symbol-error-in-xcode/


I got a weird error in Xcode 5.1 today while developing a Mac App which serves as a data entry tool for an iOS app: Redefinition of ‘Category’ as different kind of symbol. The weird thing is that the Mac App builds and runs fine, but when I import the model over to iOS I get an error at compile time:
Screen Shot 2014-05-08 at 19.09.19
The puzzle’s solution lies in something called “Namespacing”. Not that I even remotely care or pretend to understand this, but in a nutshell it means that the name Category is reserved and already defined in /usr/include/objc/runtime.h:
/// An opaque type that represents a category.
typedef struct objc_category *Category;
What that file is or where it comes from will forever remain a mystery to me, just like why it’s not a problem in a Mac App. I could probably try to figure this out for the rest of my days but really: life’s too short as it is. Let’s just
  • rename the Category entity
  • regenerate all NSManangedObject sub classes
  • remember Category as an evil string for the future
and be done with it. Note that you must rename the Entity as well as the Class it creates, and for good measure re-create all your NSManagedObject subclasses:
Screen Shot 2014-05-08 at 19.27.39
I guess that’s why at the beginning of a new Xcode project we have the option to prefix all our classes (which would undoubtedly avoid such problems in the future).
For those who care:

[iOS] StatusBar disappear after playing video

A small problem is after the MPMoviePlayerController plays the video, the status bar disappears. We can see the status bar is lack of time, battery notice… It may cause some other bugs such as the frame is calculate wrong.
The problem is the controlStyle of the MPMoviePlayerController. Except using MPMovieControlStyleFullscreen, use MPMovieControlStyleEmbedded
Reference:
—————–
Tuy nhien, MPMovieControlStyleEmbedded sẽ không có nút Done cho người dùng nếu họ muốn stop video đang chạy.
Nguyên nhân là do bị mất status bar. Do đó, khi FinishPlayingVideo, ta thêm 1 dòng code để hiện lại status bar. 
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delay * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
        [UIApplication sharedApplication].statusBarHidden = NO;
    });
Reference:
Dung Nguyen