Sometime back I was doing a small POC on Castle MonoRail. So here are my quick notes on this.
-
MonoRail is an MVC Framework from Castle inspired by ActionPack.
-
MonoRail enforces separation of concerns with Controller handling application flow, models representing data and View taking care of the presentation logic.
-
To work with MonoRail you need Castle Assemblies.
-
It also utilizes nHibernate
-
You can use Castle MonoRail Project Wizard or create the project manually.
-
Project structure –
-
Content
-
Css
-
Images
-
-
Controllers
-
HomeController.cs
-
-
Models
-
Views
-
Home \ index.vm
-
Layouts \ Default.vm
-
Rescues \ Generalerror.vm
-
-
-
You can use different view engines for rendering views like –
-
nVelocity
-
Brail
-
Asp.Net Web Forms
-
-
Some of the assemblies used in MonoRail –
-
Castle.Core.dll
-
Castle.MonoRail.Framework.dll
-
NVelocity.dll
-
Castle.MonoRail.Framework.Views.NVelocity.dll
-
-
To configure MonoRail you need to –
-
Register httpHandler for (.castle or .rails ) extension.
-
Create MonoRail Configuration Section
-
Setup Module for Controllers and ViewEngines (nVelocity)
-
-
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.
-
-
PropertyBag is used to pass data to view like – PropertyBag[“name”] = “John”;
-
PropertyBag value can be accessed in View for nVelocity as - $name
-
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
-
-
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).
-
-
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()
-
-
-
ActiveRecord Scaffolding can be used to create quick prototypes with very little code.
-
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.
-
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
-
If you want a specific method to be not invocable then it should not be public.
-
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
-
-
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.
-
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.
-
-
-
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.
-
-
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;}
-
-
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();
-
-
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.
-
-
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