MVP design pattern of ASP.NET

Posted: June 9, 2011 in ASP.NET

The MVP is Model, View , Presenter. This pattern is how the interaction between these layers can be done.

View: View can be your Aspx page in your web applications or any user controls/Interface for the end user.
Model: Contains all the business logic.

Presenter: Works as the intermediate agent for Model and View. It binds the view with the model. See the diagram below.

In the following diagram a couple of blocks are added which are interfaces through which the presenter will interact.

Let’s take a simple example of how to implement it.

Create a web application project in your Visual Studio. Now add 3 more classes named View.cs, Presenter.cs and Model.cs and add the interfaces IView and IModel.

Start with the aspx page (View). Add a label, a button and a TextBox.

Now we won’t write anything in aspx.cs file. First write the code in IView.

namespace WebApplication1
{
public interface IView
{
String Label { get; set; }
String TextBox { get; set; }
}
}

Similarly write some code in IModel.cs

namespace WebApplication1
{
public interface IModel
{
List setInfo();
}
}

Now Model.cs. Let’s say we send the information about the Label and TextBox from Model.

namespace WebApplication1
{
class Model : IModel
{
public List setInfo()
{
List l = new List();
l.Add(“Enter Name:”);
l.Add(“Use capital letter only”);
return l;
}
}
}

Now we need to write some code in the presenter so that the View and Model can communicate with each other. It’ll go like this:

namespace WebApplication1
{
public class Presenter
{
IView _pView;
IModel _pModel;
public Presenter(IView PView, IModel PModel)
{
_pView = PView;
_pModel = PModel;\
}
public void BindModalView()
{
List ls = _pModel.setInfo();
_pView.Label = ls[0];
_pView.TextBox = ls[1];
}
}
}

Finally go to aspx.cs and Implement the IView.

public partial class _Default : System.Web.UI.Page, IView
{
protected void Page_Load(object sender, EventArgs e)
{

}

#region IView Members

public string Label
{
get
{
return Label1.Text;
}
set
{
Label1.Text = value;
}
}

public string TextBox
{
get
{
return TextBox1.Text;
}
set
{
TextBox1.Text = value;
}
}

#endregion

Add an event for the button and write the code to get the data from Model through presenter and then bind it to the View. In the constructor of Presenter we passed “this” which means reference of the same aspx page.

protected void Button1_Click(object sender, EventArgs e)
{
Presenter p = new Presenter(this, new WebApplication1.Model());
p.BindModalView();
}

And you have implemented a small application with MVP pattern.

Windows Communication Foundation (WCF) is a dedicated communication framework provided by Microsoft. WCF is a part of .NET 3.0.

Creating and Consuming a Sample WCF Service:
Three major steps are involved in the creation and consumtion of the WCF services. Those are:
1. Create the Service.(Creating)
2. Binding an address to the service and host the Service. (Hosting)
3. Consuming the Service.(Consuming)

Step 1: Creating the Service

In WCF, all services are exposed as contracts. A contract is a neutral way of describing what the service does. Mainly we have four types of contracts:
Service Contract

This contract describes all the available operations that a client can perform on the service.

.Net uses “System.ServiceModel” Name space to work with WCF services.

ServiceContract attribute is used to define the service contract. We can apply this attribute on class or interface. ServiceContract attribute exposes a CLR interface (or a class) as a WCF contract.

OperationContract attribute, is used to indicate explicitly which method is used to expose as part of WCF contract. We can apply OperationContract attribute only on methods, not on properties or indexers.

[ServiceContract] applies at the class or interface level.
[OperatiContract] applies at the method level.

Data Contract

This contract defines the data types that are passed into and out of the service.

[DataContract] attribute is used at the custom data type definition level, i.e. at class or structure level.
[DataMember] attribute is used for fields, properties, and events.

Fault Contract

This contract describes about the error raised by the services.

[FaultContract(<>)] attribute is used for defining the fault contracts.

Message Contracts

This contract provides the direct control over the SOAP message structure. This is useful in inter-operability cases and when there is an existing message format you have to comply with.

[MessageContract] attribute is used to define a type as a Message type.
[MessageHeader] attribute is used for those members of the type we want to make into SOAP headers
[MessageBodyMember] attribute is used for those members we want to make into parts of the SOAP body of the message.

Sample Service Creation

[ServiceContract]

public interface IFirstWCFService

{

[OperationContract]

int Add(int x, int y);

[OperationContract]

string Hello(string strName);

int Multiplication(int x, int y);

}
Here “IFirstWCFService” is a service exposed by using the servicecontract attribute. This service exposes two methods “Add”,”Hello” by using the [OperationContract] attribute. The method “Multiplication” is not exposed by using the [OperationContract] attribute. So it wnt be avlible in the WCF service.

public class FrtWCFService : IFirstWCFService

{

public int Add(int x, int y)

{

return x + y;

}

public string Hello(string strName)

{

return “WCF program : ” + strName;

}

public int Multiplication(int x, int y)

{

return x * y;

}

}
“FrtWCFService” is a class,which implements the interface “IFirstWCFService”. This class definse the functionality of methods exposed as services.

STEP 2: Binding and Hosting

Each service has an end point. Clients communicates with this end points only. End point describes 3 things :

1. Address
2. Binding type
3. Contract Name (which was defined in STEP 1)

Address

Every service must be associated with a unique address. Address mainly contains the following two key factors :
Transport protocal used to communicate between the client proxy and service.

WCF supports the following transport machinisams:

HTTP (ex : http:// or https:// )
TCP (ex : net.tcp :// )
Peer network (ex: net.p2p://)
IPC (Inter-Process Communication over named pipes) (ex: net.pipe://)
MSMQ (ex: net.msmq://)

Location of the service.

Location of the service describes the targeted machine (where service is hosted) complete name (or) path and optionally port / pipe /queue name.
Example : localhost:8081
Here local host is the target machine name.
8081 is the optional port number.
Example 2: localhost
This is with out optional parameter.

Hosting:
Every service must be hosted in a host process. Hosting can be done by using the

IIS
Windows Activation Service (WAS)
Self hosting

IIS Hosting

IIS hosting is the same as hosting the traditional web service hosting. Create a virtual directory and supply a .svc file.
In Vs2008 select a project type: “WCF Service Application”.

In the solution explorer, under the App_code folder you can find the two files: “IService.cs” and “Service.cs”.
“IService.cs” class file defines the contracts. “Service.cs” implements the contracts defined in the “IService.cs”. Contracts defined in the “IService.cs” are exposed in the service.

In this one , end point node specifies the : address, binding type, contract (this is the name of the class that defines the contracts.)
Another end point node endpoint address=”mex” specify about the Metadata end point for the service.
Now host this serivce by creating the virtual directory and browse the *.SVC file:

STEP 3: Consuming the Service

With WCF, the client always communicates with the proxy only. Client never directly communicates with the services, even though the service is located on the same machine. Client communicates with the proxy; proxy forwards the call to the service. Proxy exposes the same functionalities as Service exposed.

Consuming WCF Service Hosted by IIS/WAS

Consuming WCF service is a very similar way of consuming a web service by using the proxy. To consume the service, in the solution explorer click on “Add service Reference” and add the service created in the STEP1.

A service reference is created under the service reference folder. Use this proxy class to consume the WCF service as we are doing with web services.

ServiceReference1.FirstWCFServiceClient obj = new

UsingWCFService.ServiceReference1.FirstWCFServiceClient();

Console.WriteLine(obj.Add(2, 3).ToString());

obj.Close();

Alternatively: We can create the proxy class by using the following command

svcutil.exe [WCFService Address]

This generates a service proxy class, just include this class in to the solution and consume the service.

Consuming by creating the channel factory:

We can consume the service by creating the channel factory manually. While creating the channel, we have to provide the same binding type and end point address where the service is hosted.

IFirstWCFService chnl = new ChannelFactory

(new BasicHttpBinding(), new EndpointAddress(“http://localhost:8080/MYFirstWCFService”)).CreateChannel();
Here IFirstWCFService is the service contract interface, that is exposed.

2010 in review

Posted: January 3, 2011 in General

The stats helper monkeys at WordPress.com mulled over how this blog did in 2010, and here’s a high level summary of its overall blog health:

Healthy blog!

The Blog-Health-o-Meter™ reads Minty-Fresh™.

Crunchy numbers

The Leaning Tower of Pisa has 296 steps to reach the top. This blog was viewed about 1,200 times in 2010. If those were steps, it would have climbed the Leaning Tower of Pisa 4 times

In 2010, there were 12 new posts, growing the total archive of this blog to 21 posts. There were 9 pictures uploaded, taking up a total of 498kb. That’s about a picture per month.

The busiest day of the year was August 19th with 28 views. The most popular post that day was Printing a datagrid.

Where did they come from?

The top referring sites in 2010 were alducente.wordpress.com, bigextracash.com, google.co.in, sadi02.wordpress.com, and me2u-paypal.com.

Some visitors came searching, mostly for dotnet changing wcf endpoint address, zameb wordpress, silverlight initparams service url, wcf endpoint dynamically, and dotnet 2010 command stored procedure.

Attractions in 2010

These are the posts and pages that got the most views in 2010.

1

Printing a datagrid August 2010

2

Dynamically changing url/endpoint for WCF service in Silverlight June 2010

3

Web Services October 2009
4 comments

4

About me October 2009

5

State Management in ASP.NET – View State and Session State November 2009

Hi all,

In one of my projects, I have coded like this.

code behind>>>>>>>>>>>>>>>>>>>

protected void Button2_Click(object sender, EventArgs e)
{
if (fupLogo.HasFile)
{
string fileFormat = fupLogo.PostedFile.ContentType;
Label1.Text = fupLogo.PostedFile.ContentType;
if (string.Compare(fileFormat, "image/jpeg", true) == 0 ||
string.Compare(fileFormat, "image/png", true) == 0 ||
string.Compare(fileFormat, "image/gif", true) == 0)
{
Label1.Text += "file format supported
";
}
else
{
Label1.Text +="file format not supported
";
}
}
else
{
Label1.Text += "file not exist
";
}
}

protected void Button1_Click(object sender, EventArgs e)
{
fupLogo.Visible = true;
Button2.Visible=true;
}

this behaves like on page load it shows a button then the onclick of the
button it shows a fileupload and upload button

Expected: when i cliks upload button after selecting any file
ouput must be “file format supported/not suported”

Actual:
but the output is “file not exist”.

As a solution I just found these,
Use style=”display:none” instead of Visible=”False”. In this case PostBackTrigger for Button2 works correctly.
Example:
..aspx file
asp:FileUpload ID="fupLogo" runat="server" style="display:none"
asp:Button ID="Button2" runat="server" Text="Upload"
OnClick="Button2_Click" style="display:none"

..cs file
protected void Button1_Click(object sender, EventArgs e)
{
fupLogo.Style.Remove("display");
Button2.Style.Remove("display");
}

Hi all,

In one of my projects I just had to come over a requirement where I have a search page with a search button and a gridview control which displays the search results. The search criteria list is a long one so, when the user clicks the search button, he/she may not even know that results have been displayed or not unless he/she scrolls down the page. In this example, I have the code for displaying the search results in button’s click event. So when the user clicks the button, the grid will get filled with the results and also a smooth scrolling is made to the position where the grid is placed.

For the above, you have just include these JQuery files.
http://code.jquery.com/jquery.min.js
http://gsgd.co.uk/sandbox/jquery/easing/

After including these files, just put the following code in the Page_Load
btnSearch.Attributes.Add("onclick", " $('html, body').stop().animate({scrollTop: $('#divCandidate').offset().top}, 5000, 'easeInOutExpo');;return true;");

In the above code “divCandidate” is the div in which the gridview is residing. 5000 is the scrolling time interval.

Also, make sure the criteria list (most probably, a table containing some controls) and the gridview are resided in an update panel.

Happy Scrolling!!

A JScript/VBScript Regex Lookahead Bug

Posted: September 6, 2010 in ASP.NET

Here’s one of the oddest and most significant regex bugs in Internet Explorer. It can appear when using optional elision within lookahead (e.g., via ?, *, {0,n}, or (.|); but not +, interval quantifiers starting from one or higher, or alternation without a zero-length option). An example in JavaScript:

/(?=a?b)ab/.test("ab");
// Should return true, but IE 5.5 – 8b1 return false

/(?=a?b)ab/.test("abc");
// Correctly returns true (even in IE), although the
// added "c" does not take part in the match

Thanks to a blog post by Steve that describes the bug with a password-complexity regex. However, the bug description there is incomplete and subtly incorrect, as shown by the above, reduced test case.

Fortunately, since the bug is predictable, it’s usually possible to work around. For example, you can avoid the bug with the password regex in Michael’s post (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/) by writing it as /^(?=.{8,15}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*/ (the .{8,15}$ lookahead must come first here). The important thing is to be aware of the issue, because it can easily introduce latent and difficult to diagnose bugs into your code. Just remember that it shows up with variable-length lookahead. If you’re using such patterns, test the hell out of them in IE.

Passing array to stored procedure

Posted: September 1, 2010 in ASP.NET

Consider the following simple method for defining the stored procedure using dynamic SQL. The array parameter is defined simply as a string and the input will be expected to be comma-delimited. By forming the sql dyanmically with the input string, we can query against the values in the array by using the IN command.

Stored Procedure
CREATE PROCEDURE [dbo].[GetData]
@MyCodes as varchar(500) = ”, — comma delimited list of codes, ie: ”’ABC”, ”DEF”, ”GHI”’
AS
BEGIN
DECLARE @query as nvarchar(500)

set @query = ‘SELECT * FROM DATA WHERE Code IN (@p_MyCodes)’

exec SP_EXECUTESQL @query,
N’@p_MyCodes varchar(500)’,
@p_MyCodes = @MyCodes
END

The above stored procedure definition will accept a comma-delimited string, which we process as an array using the SQL IN command. Note, we had to use dyanmic SQL to properly form the query (which involves expanding the comma-delimited string).

Next, we need to define the method to pass the data and execute the stored procedure from C# .NET.

The first step is to convert our array of data into a comma-delimited string, which is what the stored procedure expects to receive. Depending on your data type, this code may vary. For this example, we are using a .NET collection.

string myCodes = string.Empty; // Initialize a string to hold the comma-delimited data as empty

foreach (MyItem item in MyCollection)
{
if (myCodes.Length > 0)
{
myCodes += ", "; // Add a comma if data already exists
}

myCodes += "'" + item.Name + "'";
}

The code above will create a string in the following format:
‘Blue’,'Green’,'Red’

Now that the collection has been converted to a string, we can pass the value as a parameter to the stored procedure by using the following code:

using System;
using System.Data;
using System.Data.SqlClient;

SqlConnection MyConnection = null;
SqlDataReader MyReader = null;

try
{
// Create the SQL connection.
MyConnection = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI"))
MyConnection.Open();

// Create the stored procedure command.
SqlCommand MyCommand = new SqlCommand("GetData", MyConnection);

// Set the command type property.
MyCommand.CommandType = CommandType.StoredProcedure;


// Pass the string (array) into the stored procedure.
MyCommand.Parameters.Add(new SqlParameter("@MyCodes", myCodes));

// Execute the command
MyReader = MyCommand.ExecuteReader();

// ...
}

catch (Exception excep)
{
}

finally
{
if (MyReader != null)
{
MyReader.Close();
MyReader.Dispose();
}

if (MyConnection != null)
{
MyConnection.Close();
MyConnection.Dispose();
}

}

Tuples in .NET Framework 4.0

Posted: August 25, 2010 in .Net Framework

Another new feature in the .NET 4 Framework is support for tuples,which are similar to anonymous classes that you can create on the fly. A tuple is a data structure used in many functional and dynamic languages, such as F# and Iron Python. By providing common tuple types in the BCL, we are helping to better facilitate language interoperability. Many programmers find tuples to be convenient, particularly for returning multiple values from methods.

Here is a code which uses a function that returns two values.

class Program
{
static void Main(string[] args)
{
//Getting the values from the Tuple Function
Tuple details = GetDetails();
Console.WriteLine("FirstName : {0}, LastName :{1}", details.Item1, details.Item2);
Console.Read();
}

//Tuple function, which reads two values from
//user and returns to the main
static Tuple GetDetails()
{
Console.Write("Enter First Name:");
string _firstName = Console.ReadLine();
Console.Write("Enter Last Name:");
string _lastName = Console.ReadLine();
return new Tuple(_firstName, _lastName);
}
}

Printing a datagrid

Posted: August 19, 2010 in ASP.NET

Hi,

Here I would like to share the code to print a datagrid in ASP.NET

Put the given code in tag

function CallPrint(strid) {
var prtContent = document.getElementById(strid);
var WinPrint = window.open('', '', 'letf=0,top=0,width=1,height=1,t oolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();
//prtContent.innerHTML = strOldOne;
}

Put your datagrid in a

tag. Here I use a div named “divPrint”.

Put this code in your print button

OnClientClick="javascript:CallPrint('divPrint');"

or

OnClick="javascript:CallPrint('divPrint');"

:) Coding !!

Hi friends,

Session clearing is a very important issue after the user has logged out from his dashboard. After his/her logging out, the pages meant for the user should not be displayed. When we try to access these through links login page or any other respective pages are displayed. For the same we remove the sessions for the user when the user logs out.

Session.RemoveAll();

Above code will remove all the sessions created for the user. After this process when we try to access the user pages through URLs it will show the user has not logged in.

I would like to discuss a scenario where user logs out and we hits the browser back button, even if the sessions are cleared it shows the previous page, i.e, the user page. Is there a solution for this? Of course !!

Put this code in the Page_Load of the user page in addition to the session clearing code in the log out button.

Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);
Response.Expires = -1500;
Response.CacheControl = "no-cache";

Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();