Archive for the ‘Learning notes’ Category

MVC vs MVP again…

Monday, May 26th, 2008

Todd have a great new blog post about MVC vs MVP. :

 Model View Controller (MVC) Pattern

The MVC pattern is a UI presentation pattern that focuses on separating the UI (View) from its business layer (Model). The pattern separates responsibilities across three components: the view is responsible for rending UI elements, the controller is responsible for responding to UI actions, and the model is responsible for business behaviors and state management. In most implementation all three components can directly interact with each other and in some implementations the controller is responsible for determining which view to display (Front Controller Pattern),

Model View Presenter (MVP) Pattern

 

The MVP pattern is a UI presentation pattern based on the concepts of the MVC pattern. The pattern separates responsibilities across four components: the view is responsible for rending UI elements, the view interface is used to loosely couple the presenter from its view, the presenter is responsible for interacting between the view/model, and the model is responsible for business behaviors and state management. In some implementations the presenter interacts with a service (controller) layer to retrieve/persist the model. The view interface and service layer are commonly used to make writing unit tests for the presenter and the model easier.

Key Differences

So what really are the differences between the MVC and MVP pattern. Actually there are not a whole lot of differences between them. Both patterns focus on separating responsibility across multi components and promote loosely coupling the UI (View) from the business layer (Model).  The major differences are how the pattern is implemented and in some advanced scenarios you need both presenters and controllers.

 

Here are the key differences between the patterns:

 

·         MVP Pattern

o    View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.

o    Easier to unit test because interaction with the view is through an interface

o    Usually view to presenter map one to one. Complex views may have multi presenters.

 

·         MVC Pattern

o    Controller are based on behaviors and can be shared across views

o    Can be responsible for determining which view to display (Front Controller Pattern)

I previously wrote some notes on this topic.

Some other useful links:

http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf

Co-exist of ASP.NET MVC and Web forms

Sunday, January 13th, 2008

MVC makes a web application’s architect quite clear, however in my point of view, MVC is not a great for all solution.

One of MVC’s pain points is handling the form submission. For a simple form submission, generally you need 2 action: ActionShowForm and ActionUpdateForm, the first action show a web form interface to let user edit the form, the second action is for submission. If you use server side form validation, it will be a little bit more complicated (depends on how you display those validation information to users).

Traditional ASP.Net web form can handle above form submission in very simple and straight forward way, with just one .aspx file and one code behind .cs file, complex web form handling is a easy and enjoyable work. It’s also very easy and without too much code to use ASP.NET ajax’s update panel to get fancy update free ajax form effect.

MVC frameworks has been used in Java web developing for a long time, look at what’s Java’s new movement?   It’s JSF(Java Server Face), something really like ASP.NET, it also have something similar to “view state” and “post back”. What a interesting thing it is:  after so many years working with MVC, Java guys are looking to web form alike “new” technology,  and after using web forms for so many years, ASP guys are so exciting about MVC. :)

In one of my experiment project, I used ASP.NET MVC together with the web form.  MVC is used as the major part of the web site, Web forms are used for all those form handling, they co-exist pretty well.

I create a folder named “forms”, and put all web forms files (aspx and cs) inside this folder. Though it’s ok to put them inside the “view” folder, I separated them because they are different  in modeling. The web forms share the same “Model” part (if it require to access the “model”), I use session data object to pass data in/out the  web forms.

Microformats parsing tips

Saturday, December 29th, 2007

http://theryanking.com/presentations/2007/www2007-microformats-parsing/

some tips on microformats parsing:

* shared “n” and “fn”:

      <span class="vcard">
        <span class="fn n">
          <span class="given-name">Ryan</span>
          <span class="family-name">King</span>
        </span>
      </span>
  fn is "Ryan King"
* "value"
  • if children that match .value
  • concatenate values

      <span class="vcard">
        <span class="fn n">
          ...
        </span>
        <span class="title">I'm an
          <span class="value">Engineer</span>
          at Technorati.
        </span>
      </span>
    
Title is "Engineer"
* mailto
  • omit mailto URI scheme and query string

      <span class="vcard">
        <span class="fn n">
          ...
        </span>
        <a class="email" href="mailto:ryan@theryanking.com?Subject=nice+presentation">
          email me!
        </a>
      </span>
    

email is just “ryan@theryanking.com”

* URL

<a     class="url" href="foo">bar</a>
<area  class="url" href="foo">bar</a>
<img   class="url" src="foo" alt="bar" />
<object class="url" data="foo">bar</a>

the value is “foo”

*

<img   class="fn" alt="foo" src="bar" />
<area  class="fn" alt="foo" href="bar" />
<abbr  class="fn" title="foo">bar</abbr>

the value is “foo”

How to design a Web API

Monday, December 24th, 2007

 

Useful links:

http://ajaxpatterns.org/Web_API_Patterns

  • Basic: Use GET for read-only requests and POST for those which change server state (creation, updating, deleting).
  • Simple: You should be able to type a URL into the browser address bar and get a view of the corresponding resource. You should be able to submit a standard HTML form to affect server state
  • Authentication: Any authentication is handled with simple API keys and/or cookies; not some custom protocol.

Versioning

  add a version in API URI. e.g.  /api/1.0/method

Data format

How do clients determine which data format they want? There are a few options:

  1. use file suffix as data format. e.g. twitter use .xml and .json as suffix for different data format the API return
  2. use an additional “format” parameter
  3. in HTTP header, with “accept: “.

Web service pattern & anti patterns: http://msdn2.microsoft.com/en-us/library/ms954638.aspx

Anti patterns

#1. CRUD interface

CRUD operations are the wrong level of factoring for a Web service. CRUD operations may be implemented within or across services, but should not be exposed to consumers in such a fashion. This is an example of a service that allowed internal (private) capabilities to bleed into the service’s public interface.

CRUD interface for SOA could be a very dangerous service since it could leave the underlying data in an inconsistent state

#2. Loosey Goosey (APIs such as “ExecuteCommand” and command could be anything in the parameters)

There is virtually no contract. A service consumer has no idea how to use the service. The contract does not provide enough information to consumers on how to use the service.

 

Patterns

#1  Document Processor

Define or reuse an XML schema to represent request and response messages for your service. Ensure that all public interactions with your service use these schemas.

Generate objects directly from your schemas to speed up development.

There are 2 more patterns seemed not very useful for me at this time.

 

http://ajaxpatterns.org/RESTful_Service

Common REST mistakes

Monday, December 24th, 2007

Common REST Mistakes

When designing your first REST system there are a variety of mistakes people often make. I want to summarize them so that you can avoid them. If any are unclear, ask for more information on rest-discuss.

  1. Using HTTP is not enough. You can use HTTP in a Web service without SOAP or XML-RPC and still do the logical equivalent of SOAP or XML-RPC. If you’re going to use HTTP wrong you would actually be better off doing it in a standard way! Most of these other points describe ways in which people abuse HTTP.
  2. Do not overuse POST. POST is in some senses the “most flexible” of HTTP’s methods. It has a slightly looser definition than the other methods and it supports sending information in and getting information out at the same time. Therefore there is a tendency to want to use POST for everything. In your first REST Web Service, I would say that you should only use POST when you are creating a new URI. Pretend POST means “create new URI as child of the current URI.” As you get more sophisticated, you may decide to use POST for other kinds of mutations on a resource. One rule of thumb is to ask yourself whether you are using POST to do something that is really a GET, DELETE or PUT, or could be decomposed into a combination of methods.
  3. Do not depend on URI’s internal structure. Some people think about REST design in terms of setting up a bunch of URIs. “I’ll put purchase orders in /purchases and I’ll give them all numbers like /purchases/12132 and customer records will be in /customers…” That can be a helpful way to think while you are whiteboarding and chatting, but should not be your final public interface to the service. According to Web Architectural principles, most URIs are opaque to client software most of the time. In other words, your public API should not depend on the structure of your URIs. Instead there would typically be a single XML file that points to the components of your service. Those components would have hyperlinks that point to other components and so forth. Then you can introduce people to your service with a single URI and you can distribute the actual components across computers and domains however you want.
    My rule of thumb is that clients only construct URIs when they are building queries (and thus using query strings). Those queries return references to objects with opaque URIs.
  4. Do not put actions in URIs. This follows naturally from the previous point. But a particularly pernicious abuse of URIs is to have query strings like “someuri?action=delete”. First, you are using GET to do something unsafe. Second, there is no formal relationship between this “action URI” and the “object” URI. After all your “action=” convention is something specific to your application. REST is about driving as many “application conventions” out of the protocol as possible.
  5. Services are seldom resources. In a REST design, a “stock quote service” is not very interesting. In a REST design you would instead have a “stock” resources and a service would just be an index of stock resources.
  6. Sessions are irrelevant. There should be no need for a client to “login” or “start a connection.” HTTP authentication is done automatically on every message. Client applications are consumers of resources, not services. Therefore there is nothing to log in to! Let’s say that you are booking a flight on a REST web service. You don’t create a new “session” connection to the service. Rather you ask the “itinerary creator object” to create you a new itinerary. You can start filling in the blanks but then get some totally different component elsewhere on the web to fill in some other blanks. There is no session so there is no problem of migrating session state between clients. There is also no issue of “session affinity” in the server (though there are still load balancing issues to continue).
  7. Do not invent proprietary object identifiers. Use URIs. URIs are important because you can always associate information with them in two ways. The simplest way is to put data on a web server so that the URI can be dereferenced in order to get the data. Note that this technique only works with URIs that can be dereferenced so these URIs (http URIs!) are strongly preferred to URN or UUID-based URIs. Another way is to use RDF and other techniques that allow you to project metadata onto a URI that may not be under your control.
    If you use URI syntax with UUIDs or something like that then you get half of the benefit of URIs. You get a standardized syntax but have no standardized dereferencing capability. If you use an HTTP URI then you get the other half of the benefit because you then also have a standardized derferencing mechanism.
  8. Do not worry about protocol independence. There exists only one protocol which supports the proper resource manipulation semantics. If another one arises in the future, it will be easy to keep your same design and merely support the alternate protocol’s interface. On the other hand, what people usually mean by “protocol independence” is to abandon resource modelling and therefore abandon both REST and the Web.

Overall, the thing to keep in mind is that REST is about exposing resources through URIs, not services through messaging interfaces.

from:http://www.prescod.net/rest/mistakes/

Conventional Controller

Sunday, December 16th, 2007

ASP.NET MVC action method we need to call RenderView(”viewname”), ASP.NET MVC will look the viewname.aspx under “view/action/” and “view/shared”.  In Ruby On Rails, this step is not required, Rails will try to find same name view under view directory. 

Can we do that in ASP.NET MVC, Phil Haack has done this:

http://haacked.com/archive/2007/12/09/extending-asp.net-mvc-to-add-conventions.aspx

So instead of writing your controller like this:

public class HomeController : Controller
{
  [ControllerAction]
  public void Index()
  {
    //Your action logic
    RenderView("Index");
  }
}

Using my class you could write it like this

public class HomeController : ConventionController
{
  public void Index()
  {
    //Your action logic
  }
}

RenderView() into a buffer.

Sunday, December 16th, 2007

RenderView into a buffer and then we can do something on the result before output.

via: http://forums.asp.net/t/1193898.aspx

[ControllerAction]public void About(){	StringWriter interceptingWriter = new StringWriter();	TextWriter originalWriter = this.ControllerContext.HttpContext.Response.SwitchWriter(interceptingWriter);	RenderView("About");

	originalWriter.Write("The text written was: " + interceptingWriter.ToString());}
This is still raw, but we can have a customized controller class handle all those better. 
 

ASP.NET MVC Authentication links

Sunday, December 16th, 2007

Some links on learning ASP.NET MVC:

http://weblogs.asp.net/fredriknormen/archive/2007/11/25/asp-net-mvc-framework-security.aspx

[ControllerAction]
public void Edit(int? id)
{
if (!Roles.IsUserInRole(”Admin”))
throw new SecurityException(”Access denied”);
  …
}

To avoid writing this check in the Action methods we can instead use the PrincipalPermissionAttributes shipped with .Net:

[ControllerAction]
[PrincipalPermission(SecurityAction.Demand, Role="Admin"]
public void Edit(int? id)
{
   …
}

If we want to make sure all Action methods in a Controller have the check, we can add the PrincipalPermissionAttribute to the Controller class:

[PrincipalPermission(SecurityAction.Demand, Role="Admin")]
public class HomeController : Controller

If we want to handle the SecurityException we can use the ExceptionHandlerAttribute I wrote about in my previous post. This can catch the SecurityException and Render a View that will display the exception message.

[ControllerAction]
[PrincipalPermission(SecurityAction.Demand, Role="Admin"]
[ExceptionHandler("Error", typeof(SecurityException))]
public void Edit(int? id)
{
   …
}

If we don’t want to use the PrincipalPermissionAttribute and instead write our own Security handler, we can override the OnPreAction method and implement the security check. The OnPreAction method will be executed before any Action methods are executed.

protected override void OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
{
if (actionName == “Edit”)
   {
if (!Roles.IsUserInRole(”Admin”) || !User.Identity.IsAuthenticated || !User.Identity.Name = “Administrator”)
throw SecurityException(”Access denied!”);
   }
}

http://forums.asp.net/t/1192300.aspx

You could always make a base controller and have your other controllers you want to secure extend it.

Example

public class SecureController : Controller

{

    public SecureController()

    {

        HttpContext context = HttpContext.Current;

        if (context.User == null || !context.User.Identity.IsAuthenticated)

        {

            // redirect to login.

      } 

    }

}

public class MemberController : SecureController

{

}

Implement Java servlet filter alike function in ASP.NET MVC

Saturday, December 15th, 2007

As a Java guys who turn to .NET, I always look for some nice stuff in Java inside .Net’s. 

Java’s Servlet filter is something good, I think in ASP.NET the similar concept is httpmodule (correct me if I am wrong). Filter is a great place to implement authentication, logging, auditing, data compression, transcoding, data transforming (e.g. XSLT), …etc.

When I am planning to add OpenID into ASP.NET MVC application, I couldn’t find a good enough place to put the OpenID authentication codes.

ASP.NET’s form authentication mode should be able to work together with ASP.NET MVC, I already see a blog article talk about this. The only change is configure an action URL in the form action loginUrl . Monorails also suggested its user to use this way.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <system.web>
        <authentication mode="Forms">
            <forms name="auth" loginUrl="auth/login">
            ...
            </forms>
        </authentication>

I wish ASP.NET MVC could also support something like MonoRails’ filter. MonoRails filters are executed before and|or after actions. It is useful for security, dynamic content and to keep away repetitive code.

Fortunately, on Controller class there are some virtual functions which enable we do something before, after the action:

protected virtual bool OnError(string actionName, MethodInfo methodInfo, Exception exception);
protected virtual void OnPostAction(string actionName, MethodInfo methodInfo);
protected virtual bool OnPreAction(string actionName, MethodInfo methodInfo);

We can the implement some of our own controller class, so we can make it easier to implement something like Java servlet filters (and its chain).

Still learning… so maybe I am not that right…

ASP.NET MVC + Dynamic Data Sample

Friday, December 14th, 2007

ASP.NET MVC and Dynamic Data are both nice stuff, can they work together? sure! David just blog about it:

Will this work with MVC?

In this initial Preview, Dynamic Data is mostly targeting ’standard’ ASP.NET pages, but we are absolutely planning to support Dynamic Data for MVC.  And the good news is that you can actually try this today!  To do this:

This was completely unadvertised, so most folks probably didn’t see it, but it’s in there for you to play with!  Start by just running it, and then look through the source code, which is all part of the solution.  Of course, it’s all very preliminary, and far from feature complete, but it should give you an idea of where we’re heading.  If there is enough interest, I’ll try to make a screen cast that shows it.

The ASP.NET MVC Toolkit provides HTML rendering helpers and dynamic data support for MVC, it’s separated from the CTP install package.

This is how the blog sample works:

Controller, inherit from DynamicDataController, defined inside the toolkit.

namespace Blog.Controllers {
    public class CommentController : DynamicDataController<Comment> { }
}

The DynamicDataController will render some aspx views default inside “view/shared”.  In the example, the view post define its own view in “view/post/Show.aspx”, since ASP.NET MVC’s RenderView(”Show”) will fist look inside view/<controllerName>/<viewname> first, the customized version will be used over the shared one.

The default “Dynamic Data web” project created by template have very different structure than the MVC Dynamic Data demo project.  I wish in the next release, tge MVCDynamicData can be included by default.

What I expecting is the feature that user can drag database table columns into a web form, and generate the CRUD scaffold with those web form, in that case, database centric web develop will be much easier.  (though FoxPro, PowerBuild, Delphi, or maybe VB,  have this kind of feature for many years)  That’s something that I expected for a long time, can’t believe  this kind of solution doesn’t exist before.