Skip to main content

Notes on Castle MonoRail

 

Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this.

  1. MonoRail is an MVC Framework from Castle inspired by ActionPack.

  2. MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic.

  3. To work with MonoRail you need Castle Assemblies.

  4. It also utilizes nHibernate

  5. You can use Castle MonoRail Project Wizard or create the project manually.

  6. Project structure –

    • Content
      • Css
      • Images
    • Controllers
      • HomeController.cs
    • Models
    • Views
      • Home \ index.vm
      • Layouts \ Default.vm
      • Rescues \ Generalerror.vm
  7. You can use different view engines for rendering views like –

    • nVelocity
    • Brail
    • Asp.Net Web Forms
  8. Some of the assemblies used in MonoRail –

    • Castle.Core.dll
    • Castle.MonoRail.Framework.dll
    • NVelocity.dll
    • Castle.MonoRail.Framework.Views.NVelocity.dll
  9. To configure MonoRail you need to –

    • Register httpHandler for (.castle or .rails ) extension.
    • Create MonoRail Configuration Section
    • Setup Module for Controllers and ViewEngines (nVelocity)
  10. Controllers are the entry point in MonoRail

    • Name + Controller suffix convention is used.
    • ControllerDetails attribute can be used to define exact name of the controller.
    • Controller name is by default type name, so HomeController type means the name of the controller is Home.
    • They inherit from SmartDispatcherController
    • Public methods in the controller become the Actions for the controller.
    • Layout Attribute helps define default layout in layouts folder (master pages) and Rescue attribute helps define default error page in Rescues folder.
    • Action name is used by default to decide the view to render.
  11. PropertyBag is used to pass data to view like – PropertyBag[“name”] = “John”;

  12. PropertyBag value can be accessed in View for nVelocity as - $name

  13. Views using nVelocity –

    • They have an extension of .vm
    • $ is used to get the values from variables
    • # is used to execute command constructs in view
    • $SiteRoot – variable represents root of the application
    • $childContent – variable used on layout templates is replaced with the content for individual views.
    • Use following to define a macro or function –
        #macro(<fnname> $argument)
        #end
    • To define an if statement use –
        #if (condition)
        #end
    • To create and set the value of a variable
        #set($newvarname = $varname)
    • To access last exception
        $context.LastException
    • $FormHelper.TextField(“contact.from”) to create text box with the value of contact.from property.
    • $FormHelper.TextArea(“contact.message”) to create text area.
    • To show errors use –
        #if(Flash.error)
        $Flash.error
        #end
  14. SmartDispatcherController –

    • Is used to implement smart way to invoke actions.
    • You can bind querystring or form entries to action parameter
    • It provides for databinding with custom object types like – ActionName([DataBind(“contact”)] Contact contact).
  15. Using ActiveRecord for Data access –

    • Assemblies used –
      • Castle.ActiveRecord.dll
      • Castle.DynamicProxy.dll
      • Log4net.dll
      • nHibernate.dll
    • To configure ActiveRecord –
      • Define configuration section for ActiveRecord in web.config
      • Define driver_class, dialect, provider, connection string and factory_class for ActiveRecord usage.
      • Create entity classes by inheriting from ActiveRecordBase<entityname> and using the attribute ActiveRecord for entity.
      • Use [PrimaryKey] attribute on property to define a primary key.
      • Use [Property] attribute on property to define a normal column.
      • Use [BelongsTo(“<primaryKeyColName>”)] attribute to define a foreign key.
      • Call ActiveRecordStarter.Initializer in Global.asax to initialize activerRecord
      • Call ActiveRecordStarter.CreateSchema() to generate the schema from classes.
    • CRUD methods provided by ActiveRecord –
      • FindAll()
      • Find(id)
      • Create()
      • Update()
      • Delete()
  16. ActiveRecord Scaffolding can be used to create quick prototypes with very little code.

  17. Just use the Scaffolding attribute on Controller like – [Scaffolding(typeof(Supplier))] and you need to define none of the actions to have fully functional CRUD operations ready.

  18. Areas are a logical groups of Controllers. All controllers belong to an Area. Default area is unnamed.

      Eg – [ControllerDetails(Area=”Admin/users”)]
      then the url path becomes - /Admin/users/Supplier/Index.rails
  19. If you want a specific method to be not invocable then it should not be public.

  20. Useful properties in Controllers are –

    • Context – context of the request execution.
    • Session – Gets the session dictionary.
    • Flash – gets the dictionary of volatile items like success and failure messages.
    • HttpContext –
    • Request
    • Response
    • Params
    • Form
    • Query
    • Name – Controller name
    • AreaName – Area name
    • LayoutName – layout specified
    • Action – Action being processed
  21. If DefaultAction attribute is used on a controller then a method by the name of DefaultAction will be used in case a url cannot be translated to a specific action.

  22. Using Filters –

    • Create a class that implements IFilter interface
    • Implement Perform Method with following parameters – ExecuteWhen, IEngineContext, IController, IControllerContext.
    • Return false from Perform method to stop execution of the action method.
    • ExecuteEnum parameter specifies the context of the execution
      • BeforeAction
      • AfterAction
      • AfterRendering
      • Always
    • To associate filter to an action use the FilterAttribute on Controller like –
      • [FilterAttribute(ExecuteEnum.BeforeAction,typeOf(YourFilterClass)]
    • In case of more than one filterAttributes the order cannot be predicted so use ExecutionOrder like -
      • [FilterAttribute(ExecuteEnum.BeforeAction,typeOf(YourFilterClass), ExecutionOrder=0]
    • Use SkipFilter attribute to skip all filters on an Action
    • Use SkipFilter(typeOf(YourFilterClass)) to skip specific filter on an action.
    • To Pass custom parameter in to filters we need to do the following –
      • Create a class that inherits from FilterAttribute class
      • Mark this class with AttributeUsage attribute
      • Create constructor overload and property for passing parameter.
      • Create your Filter Class that implements IFilter and IFilterAttributeAware interfaces
      • Associate Filter to the controller.
  23. Benefits of MVC –

    • Comfortable for traditional developers
    • Control over HTML markup
    • Supports unit testing, Test Driven development, agile development
    • Its possible to mix controller based development with web forms based development in a single project.
  24. Using Ajax –

    • It uses Prototype js framework
    • $AjaxHelper.InstallScript() is used to render js links for ajax
    • Use new Ajax.Request(‘$UrlHelper.For(“%{Action=<youractionname>}”)’,
        { method : ‘get’,
        Parameters : { paramName: value},
        onSuccess : showResult,
        onFailure: showMessage})
    • Methods for Success and Failure will accept an input parameter transport like –
        showResult(transport) {alert(transport.responseText;}
  25. Using JSON –

    • You can use [JSONBinder(“paramname”)] in action.
    • You use Object.toJSON(jsdata) to transform javascript object to JSON
    • To return JSON use attribute – [return:JSONReturnBinder]
    • To create JSON object – transport.responseText.evalJSON();
  26. For Testing –

    • Castle.MonoRail.TestSupport was introduced for enabling easy testing of MonoRail Project.
    • You will need to add references to –
      • nUnit.Framework
      • Castle.Monorail.TestSupport
    • Create a Test cases class and this should extended from BaseControllerTest
    • Use [TestFixture] attribute on the Test Cases Class.
    • Create public methods with [Test] attribute
    • Call PrepareController passing in controller instance, Area name, controller name and action name from with-in a test
    • Finally make assertion calls.
  27. Using Helpers –

    • Helpers are ordinary classes but associated with controller and made available to be used on View.
    • Use [Helper(typeOf(MyHelperClassName))] attribute on controller to make the helper available to be used on View associated with this controller
    • It can optionally extend from AbstractHelper class inorder to get access to the controller instance.

Comments

Popular posts from this blog

Workflow Foundation 4 - Part 3 - Data storage and management

This is my third post on WF4. First one was an introductory post on WF4 and in second one we focused on executing workflows. In the this post I am going to focus on the topic of data storage and management. Every business process or flow depends on data. When you think of data there are three elements to it as listed below - Variables - for storing data Arguments - for passing data Expressions - for manipulating data. Let us first look at the variables. Variables are storage locations for data. Variables are declared before using them just like in any other languages like C# or VB.Net. Variables are defined with a specific scope. When you create a variable in an activity the scope of the variable becomes that activity's scope. Variables can also have access modifiers like None, Mapped or ReadOnly. Let us look at an example where we will create two variables and assign a scope to them along with access modifiers. //Declare a sequence activitiy Sequence seqWf = new Sequence(); //de...

Introduction to Workflow Foundation 4 (WF4)

I finally decided to pick-up my blogging once more. Since I have been trying to learn Windows Workflow Foundation 4 (WF4) I thought I might as well start off with this topic. WF4 is a development framework that enables you to create a workflow and embed it in a .Net application. It is neither an executable application nor a language. It provides a set of tools for declaring a workflow, activities to create your logic and to define control flow and a runtime for executing the resulting application definition. It also provides services for persistence of state, tracking and bookmarking. You can create your workflow directly in code, in mark-up or in a combination of both. Workflow provide us with two major advantages - Creating unified application logic. Making application logic scalable. Workflow Authoring styles - Sequential Workflow executes a set of contained activities in a sequential manner. Workflow Foundation was introduced in the .Net 3.0 and updated in 3.5. In .net 4 it has bee...