Quantcast
Saturday 11 december 2010 6 11 /12 /Dec /2010 15:52

Model View Presenter

Get Interview tutorials and videos on .NET 3.5, 4.0, Presenter, SQL Server, CAS, Security, WCF, SharePoint, Azure, OOPS and many more on www.questpond.com


Introduction and Goal

Pre-requisite

The simple stock project

Analyzing the project

So what’s the problem?

MVP (Model View Presenter) the solution

Implementing MVP in the stock project

The View

The simplest thing in the world the model

The complete flow for the stock project

Reusing the presenter in windows

The difference

Difference between MVC and MVP

Download the code



Introduction and Goal

In this article we will understand MVP, execute a sample project with MVP, implement the same using windows UI and then finally we will discuss about the differences between MVP and MVC.

For past some days I have been writing and recording videos in design patterns, UML , FPA , Enterprise blocks and lot you can watch the videos at http://www.questpond.com 

You can download my 400 .NET FAQ EBook from http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip
 

Pre-requisite

This article assumes you know MVC in case not you can read about the same at http://www.codeproject.com/KB/aspnet/3Musketeers.aspx

The simple stock project


The best ways to understand any architectural concept is by taking a small practical sample and then apply fundamentals on the same. So let’s first discuss a simple scenario and then let’s think how MVP fits in to the same. Below is a pictorial representation of a simple stock project. We can increase the stock value and decrease the stock value. Depending on the stock can have three status overstocked, under stocked or optimally stocked.



We have three scenarios depending on which the UI will change color.



Stock value Color
Value is in between 1 and 5 ( Optimally stocked) Green color
Value is above 5 ( Over Stock)  Blue color
Value is less than zero ( Under stocked) Red color


Analyzing the project


What we will do is define the problem logic in two parts:-

• Presentation logic
• Business logic



Business logic will be handled by business object Presentation Logic will ne handled in the ASPX or windows form
   
Receive the events from the presentation and maintain the stock value accordingly. In short increment and decrement the stock value. Trigger the events increment stock and decrement stock. The events will be triggered when the user clicks the increase stock button or the decrement stock button.
Depending on the value of the stock determine the three states under stocked, overstocked or optimally stocked. Depending the state of the stock change the visual colors :-
• Under stocked change to RED.
• Over stocked change to blue.• Optimally stocked change to green
 



The other responsibilities look fine let’s concentrate on the last responsibility which we have marked in red color where the UI needs to change colors depending on the stock value. This kind of logic in presentation is termed as presentation logic.


So what’s the problem?


If you look from a generic perspective the work responsibilities allocated to the business object and the user interface look fine. There is slight concern when we look at the presentation logic.



We have three big problems:-



Reuse of presentation logic


If we want to reuse the presentation logic in some other UI type like windows. I mean to say we have implemented this logic in ASP.NET web pages and we want to reuse the same in windows. As we have the presentation logic is tied up in the UI code it will be difficult to decouple the same from the UI. We also would like to use the same presentation logic with other pages of same types.



Presentation is tied up with the business object

The presentation is tied up with the business object. It’s doing lot of work checking the stock status using the business object and changing the UI colors accordingly.


UI testing


If we want to test the user interfaces it becomes difficult as the UI is highly coupled with the UI. It becomes difficult to test these parts as different pieces.


MVP (Model View Presenter) the solution


So let’s take the above three problems and see how we can solve it. MVP will help us solve the above three problems.
Problem 1:- Reuse of presentation logic

If we want to reuse the presentation logic irrespective of the UI type we need to move this logic to some separate class. MVP does the same thing. It introduces something called as the presenter in which the presentation logic is centralized.

Note: - In this scenario the presentation logic is simple. In real projects you will find the presentation 
logic complex and there is lot of bandwidth of reuse in other user interfaces.

Problem 2:- Presentation is tied up with the business object
To decouple the presentation from the business object we introduce an interface for every UI. The presenter always talks through the interface and the concrete UI i.e. the web page communicates also through the view interface. In this way the model is never in touch with the concrete UI i.e. the ASPX or windows interface. All user interface should implement this interface so that the presenter can communicate with the UI in a decoupled manner.






Problem 3 will get solved if we solve the first two problems.


Implementing MVP in the stock project


The View Interface and presenter of the stock project


We will first visualize how the UI will look like. There will be two buttons one which increments the stock value and the other which decrements the stock value. The stock value is displayed on the stock text box and the color is set according to the value of the stock.






All events are first sent to the presenter. So all the events needs to connect to some methods on the presenter. All data needed by the UI i.e. in this instance we need the stock value and the color should be defined in the interface so that presenter can communicate using the same.

So below is the interface for the ASPX page. We need the stock value so we have defined a method called as ‘setStockValue’ and we also need the color so we have defined a method called as ‘setColor’.

public interface StockView
{
void setStockValue(int intStockValue);
void setColor(System.Drawing.Color objColor);
}

The presenter class will aggregate the view class. We have defined an ‘Add’ method which takes the view object. This view will set when the ASP.NET page starts.

public class clsPresenter
{ 
StockView iObjStockView;
public void add(StockView ObjStockView)
{
iObjStockView = ObjStockView;
}
.....
.....
.....
}

When the user presses the increase stock button it will call the ‘increasestock’ method of ‘clsPresenter’ and when the decrease stock button is called it will call the ‘decreasestock’ method of the ‘clsPresenter’ class. Once it increments or decrements the value it passes the value to the UI through the interface.

public void increaseStock()
{
Stock.IncrementStock();
iObjStockView.setStockValue(Stock.intStockValue);
ChangeColor();
}
public void decreaseStock()
{
Stock.DecrementStock();
iObjStockView.setStockValue(Stock.intStockValue);
ChangeColor();
}

We had also talked about moving the presentation logic in the presenter. So we have defined the ‘ChangeColor’ method which takes the status from the ‘Stock’ object and communicates through the view to the ASPX page.

public void ChangeColor()
{
if(Stock.getStatus()==-1)
{
iObjStockView.setColor(Color.Red);
}
else if (Stock.getStatus() == 1)
{
iObjStockView.setColor(Color.Blue);
}
else
{
iObjStockView.setColor(Color.Green);
}}


The View


Now let’s understand how the UI will look like. The UI either it’s an ASPX or windows should inherit from the stock view interface which we have previously explained. In the page load we have passed the reference of this page object to the presenter. This is necessary so that the presenter can call back and update data which he has received from the model.

public partial class DisplayStock : System.Web.UI.Page,StockView
{
private clsPresenter objPresenter = new clsPresenter();
protected void Page_Load(object sender, EventArgs e)
{
objPresenter.add(this);
}
…..
…..
…..
}}

As we have inherited from an interface we also need to implement the method. So we have implemented the ‘setStockValue’ and the ‘setColor’ method. Note that these methods will be called by the presenter. In both the buttons we have called the ‘increaseStock’ and ‘DecreaseStock’ method of the presenter.

public partial class DisplayStock : System.Web.UI.Page,StockView
{
private clsPresenter objPresenter = new clsPresenter();
protected void Page_Load(object sender, EventArgs e)
{
objPresenter.add(this);
}
public void setStockValue(int intStockValue)
{
txtStockValue.Text = intStockValue.ToString();
}
public void setColor(System.Drawing.Color objColor)
{
txtStockValue.BackColor = objColor;
}
protected void btnIncreaseStock_Click(object sender, EventArgs e)
{
objPresenter.increaseStock();
}
protected void btnDecreaseStock_Click(object sender, EventArgs e)
{
objPresenter.decreaseStock();
}}



The simplest thing in the world the model


The model is pretty simple. It just increments and decrements the stock value through the two methods ‘IncrementStock’ and ‘DecrementStock’. It also has a ‘getStatus’ function which tells what is the stock level type i.e. over stocked, under stocked or optimally stocked. For simplicity we have defined the stock value as a static object.

public class Stock
{
public static int intStockValue;

public static void IncrementStock()
{
intStockValue++;
}
public static void DecrementStock()
{
intStockValue--;
}
public static int getStatus()
{
// if less than zero then -1
// if more than 5 then 1
// if in between 0
if (intStockValue > 5)
{
return 1;
}
else if (intStockValue < 0)
{
return -1;
}
else
{
return 0;
}

}}


The complete flow for the stock project

Below is a complete flow of the stock project from MVP perspective. The UI first hits the presenter. So all the events emitted from the UI will first route to the presenter. Presenter will use the model and then communicate back through the interface view. This interface view is the same interface by which your UI will inherit.




We have solved all the three problems with all the actions passing through the presenter the ASPX / Windows is completely decouple from the model. The presenter centralized the presentation logic and communicates through the interface. As the presentation logic is in a call we can reuse the logic.

As all the commands are passing through the presenter the UI is decoupled from the model. Now that we have all the components decoupled we can test the UI component separately using the presenter.


Reusing the presenter in windows


To just show how magical the presenter is. I have reused the same presentation logic in a windows application.




In the below sample we have ported the same presenter logic in a windows application.

private void Form1_Load(object sender, EventArgs e)
{
objpresenter.add(this);
}

private void btnInCreaseStock_Click(object sender, EventArgs e)
{
objpresenter.increaseStock();
}

private void btnDecreaseStock_Click(object sender, EventArgs e)
{
objpresenter.decreaseStock();
}

#region StockView Members

public void setStockValue(int intStockValue)
{
txtStockValue.Text = intStockValue.ToString();
}

public void setColor(Color objColor)
{
txtStockValue.BackColor = objColor;
}


The difference

You can understand the difference of how consuming the model objects directly and using a presenter varies. When we use the presenter we have moved the UI presentation logic to the presenter and also decoupled the model from the view.
Below is the code in which the UI directly uses the model…Lot of work right.





With presenter all the presentation logic is now centralized




Difference between MVC and MVP





The above figure summarizes the difference between MVP and MVC. We have just summarized the figure in tabular format below.



MVP MVC
In MVP the view and the model is completely decoupled. In MVC the view and model is not completely decoupled.
In MVP presenter handles all the UI events In MVC the views handles the events
In MVP the presenter calls back to update the view via the view interface. In MVC the controller passes the model to the view and the view then updates itself.


Download the code

You can download the stock project from the link http://www.codeproject.com/KB/aspnet/ModelViewPresenter1/MVPStockSample.zip

 The project is coded from three aspects :-
• Using simple UI and Model perspective.
• Implementing MVP using WEB.
• Implementing MVP using windows.

The Web and windows samples are shown to show how we can reuse the presentation logic.


By Shivprasad koirala
Enter comment - View the 0 comments
Saturday 11 december 2010 6 11 /12 /Dec /2010 10:06

.Net Generics Interview Questions

Get list of .Net Interview Questions and Answers on Generics

 

What are Generics?

  • The System.Collections.Generics namespace contains the generics collections.
  • Generics can be a method, class, structure, or an interface to which it acts upon
  • Generics  can be refer to a method ,class, structure or an interface in a type – safe manner
  • Generics provide the ability to create type-safe collections in .NET.
  • Generics.Net is a well organized class which contains data structures, algorithms, design patterns and other utilities in generic form.
  • Generics are used to make the code more reusable.
  • Generics can act like any data type means there is no need to write any internal code.

 

What are Constraints in Generics?

  • Constraints are represented in C# using the where keyword
  • Constraints is something restriction the way doing that in generics
  • There are 3 types of Constraints

                 1.       Constructor constraint

                 2.       Derivation constraint

                 3.       Reference / value type constraints

 

What are Generics and Casting?

  • The C# compiler only lets you implicitly cast generic type parameters to Object, or to constraint-specified types
  • The compiler explicitly cast generic type parameters to only an interface but not a class.

 

How to use I Dispose of a Generic Type?

  • Just pass value of generic type parameter to the using statement then compiler will allow you to specify any instance of generic type

 

 

How to declare Generic Methods?

  • Generic method is defined by specifying the type parameter after the method name but before the parameter list.
  • Doe Example public string Add<T>(T val1, T val2).

 

What is use of Generic List?

  • Generic List is an efficient method of storing a collection of variables
  • Generic List is strongly typed and casting.
  • Name space to declare generics is using System.Collections.Generic.
  •  

Difference between Generics and Array List?

  • Array List is not type safe because it faces problems of boxing and UN boxing.
  • List generics are type safe and do not require boxing and UN boxing situations.
  • In terms of performance of application List generics is better than array list.
  • Array List can save different type data types.
  • List generics we can save only specific data type.
  • Array List consumes lots of memory compare to list generics/
By Shivprasad koirala
Enter comment - View the 0 comments
Friday 10 december 2010 5 10 /12 /Dec /2010 14:32

33 .net interview questions on Caching Concepts

This section will cover questions related to Caching Concepts during .net interview by the interviewer so have a look on the following and do revise it when ever you go for the .net interview

Normally the .net interviewer starts with.....

What is an application object?

What is the difference between Cache object and application object?


How can get access to cache object?


What are dependencies in cache and types of dependencies?

 

Can you show a simple code showing file dependency in cache?

 

What is Cache Callback in Cache?

 

What is scavenging?

 

What are different types of caching using cache object of ASP.NET?

 

How can you cache different version of same page using ASP.NET cache object?

 

How will implement Page Fragment Caching?

 

Can you compare ASP.NET sessions with classic ASP?

 

Which are the various modes of storing ASP.NET session?

 

Is Session_End event supported in all session modes?

 

What are the steps to configure StateServer Mode?

 

What are the steps to configure SQLServer mode?

 

Where do you specify session state mode in ASP.NET?

 

What are the other ways you can maintain state?

 

What are benefits and Limitation of using Hidden fields?

 

What is ViewState?

 

Does the performance for viewstate vary according to User controls?

 

What are benefits and Limitation of using Viewstate for state management?

 

How can you use Hidden frames to cache client data?

 

What are benefits and limitations of using Hidden frames?

 

What are benefits and limitations of using Cookies?

 

What is Query String and what are benefits and limitations of using Query Strings?

 

What is Absolute and Sliding expiration?

 

What is cross page posting?

 

How do we access viewstate value of this page in the next page?

 

Can we post and access view state in another application?

 

What is SQL Cache Dependency in ASP.NET 2.0?

 

How do we enable SQL Cache Dependency in ASP.NET 2.0?

 

What is Post Cache substitution?

 

Why do we need methods to be static for Post Cache substitution?

 

 

Answer to above given question on Caching concept of Most asked Dotnet interview questions

By Shivprasad koirala
Enter comment - View the 0 comments
Thursday 9 december 2010 4 09 /12 /Dec /2010 15:02

25 important .net interview questions on Threading

This section will cover the most asked questions related to Threading during .net interview by the interviewer so have a look on the following and do revise it when ever you go for the .net interview

Normally the .net interviewer starts with.....

What is Multi-tasking?

What is Multi-threading?

What is a Thread?

Did VB6 support multi-threading?


Can we have multiple threads in one App domain?


Which namespace has threading?


What does Address Of operator do in background?


How can you reference current thread of the method?


What is Thread.Sleep () in threading?


How can we make a thread sleep for infinite period?


What is Suspend and Resume in Threading?

What the way to stop a long running thread?


How do I debug thread?


What is Thread.Join () in threading?


What are Daemon threads and How can a thread be created as Daemon?


How is shared data managed in threading?


Can we use events with threading?


How can we know a state of a thread?


What is use of interlocked class?


What is a monitor object?

 

What are wait handles?


What is ManualResetEvent and AutoResetEvent?

 

What is Reader Writer Locks?


How can you avoid deadlock in threading?


What is the difference between thread and process?


So friends answering to above question on Threading of important Dotnet interview questions helped me to clear topic on threading in front of the interviewer.

By Shivprasad koirala
Enter comment - View the 0 comments
Wednesday 8 december 2010 3 08 /12 /Dec /2010 14:05

32 important .net interview questions

When interviewer starts with .net basic questions then following are most likey asked important questions during an interview. So always prepare and revise it when ever you go for the .net interview

Normally the .net interviewer starts with.....


What is an IL?

What is a CLR?

What is CTS?

What is a CLS (Common Language Specification)?

What is a Managed Code?

What is a Assembly?

What are the different types of Assembly?

What is NameSpace?

What is Difference between NameSpace and Assembly?

If you want to view an Assembly how do you go about it?

What is Manifest?

Where is version information stored of an assembly?

Is versioning applicable to private assemblies?

What is GAC?

What is the concept of strong names?

How to add and remove an assembly from GAC?

What is Delay signing?

What is garbage collection?

Can we force garbage collector to run?

What is reflection?

What are different types of JIT?


What are Value types and Reference types?


What is concept of Boxing and Unboxing ?


What is the difference between VB.NET and C#?


What is the difference between System exceptions and Application exceptions?


What is CODE Access security?


What is a satellite assembly?


How to prevent my .NET DLL to be decompiled?


What is the difference between Convert.toString and .toString () method?


What is Native Image Generator (Ngen.exe)?


If we have two version of same assembly in GAC how do we make a choice?


What is CodeDom?


Really friends having answered to interview questions and answers for .NET is one thing and answering with the proper right key word will help you to impress in front of the interviewer.

By Shivprasad koirala
Enter comment - View the 0 comments

Important .NET and C# interview questions and answers

.Net interview questions: - Explain why it is not preferred to use finalize for clean up?

.Net interview questions: - Show the five levels in CMMI?

.NET interview questions and answers: – Which is the best place to store connection string in .NET projects?

C# interview questions and answers: – Explain the use of Icomparable in c#?

C# interview questions: - How can we check which rows have changed since dataset was loaded?

C# interview questions and answers: - Can you write a simple c# code to display Fibonacci series?

.NET interview questions and answers: - What is difference betweenIcomparable VS Icomparer ?

C# and .NET interview question: -What is short circuiting in C#?

C# and .NET interview question: - What are symmetric and asymmetric algorithms?

Important c# and .NET interview question on object pooling and Gridview events?

.NETinterview questions and answers: – Will the finally run in this code?

How to prepare for c# and .NETinterviews?

C# and .NET Interview questions: - What is Thread.Join () in threading?

.NET Interview questions and answers: -What is serialization and deserialization in .NET?

C# and .NET interview question: - What is hashing?

c# and .NET interview question:- what connects dataset and data source ?

.Net interview questions and answers: - What is the difference between “Web.config” and “Machine.Config”?

.NET interview questions and answers: - What is TPL?

.NET Interview questions and answers: -What are different access modifiers?

.NET and c# Interview Question and answers: – If we want to update interface with new methods, what is the best practice?

 MVC ( Model view controller) interview questions and answers      

ASP.NET Application and Page Life Cycle 

12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage) 

 6 important use of Partial/Mock testing

6 important uses of Delegates and Events

7 Simple Steps to Run Your First Azure Blob Program

8 Steps to Create Workflows using SharePoint Designer

Azure FAQ Part 1

C# Code Reviews using StyleCop – Detailed Article

Four real world uses of Partial classes and Partial methods

SharePoint Quick Start FAQ Part 1

SharePoint Quick Start FAQ Part 6 – Workflows, Workflows and Workflows

SharePoint Workflow Basics

 

 

 

 

. NET and C# interview questions videos

MVC Interview questions videos

Viewdata,viewbag,tempdata

 

 

MVC Interview questions and answers Article

 

(Model view controller)MVC Interview questions and answers

MVC interview questions with answers video: – What is Web API how to implement the same?

 

 

WCF Interview questions videos

 

overloading in WCF

WCF fault exceptions ?

 

C# Interview Questions & Answers Article

 

12 Important FAQ’s on VSTS Testing (Unit testing, load testing, automated testing, database testing and code coverage)

6 important use of Partial/Mock testing

6 important uses of Delegates and Events

7 Simple Steps to Run Your First Azure Blob Program

8 Steps to Create Workflows using SharePoint Designer

Azure FAQ Part 1

C# Code Reviews using StyleCop – Detailed Article

Four real world uses of Partial classes and Partial methods

SharePoint Quick Start FAQ Part 1

SharePoint Quick Start FAQ Part 6 – Workflows, Workflows and Workflows

SharePoint Workflow Basics

C# (Csharp) interview questions and answers: – What are indexers in .NET?

C# OOP interview questions and answers: - I do not want to implement all the interface methods?

C# design pattern (UNIT of Work Design Pattern)

C# design pattern interview questions – What is Dependency injection ?

C# interview questions and answers: - What is the difference between “==” and .Equals()?

How questions are asked in c# interviews?

C# design pattern interview question: - DI vs IOC

8 important C# Interview questions on IL code, JIT, CLR, CTS, CLS and CAS

What is the difference between Reflection and Dynamic in C#?

Algorithm Interview Questions

Algorithm interview questions and answers: – Can you write code for bubble sort algorithm?

Algorithm interview questions and answers: – What is inserted sort algorithm?

ASP.NET Interview Questions & Answers Article







 

SQL Server Interview Questions & Answers Article

 

SQL Server Interview Questions & Answers Article

SQL Server interview questions and answers: - What is HID data type in SQL Server ?

 

.NET INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

.NET interview questions and answers: - How to reverse a string in .NET ( DotNet)?

.NET interview questions and answers: - What is the use of Click Once?

.NET interview questions and answers: - Will the below codes create new instances?

C# and .NET interview questions with answers – What is Nuget?

Dependency injection (DI) VS Inversion of Control (IOC)

.NET interview questions with answers: - What is the difference between Reflection and Dynamic?


WPF INTERVIEW QUESTIONS & ANSWERS ARTICLE

 

6 important WPF and Silverlight Multi-threading interview questions with answers


Create your blog for free on over-blog.com - Contact - Terms of Service - Earn Royalties - Report abuse - Most commented articles