Posts Tagged “monorail”

Follow


My Birthday gift for myself

  

http://groups.google.com/group/castle-project-devel/browse_thread/thread/3067daaf559276bf/48c1e0be044698f4

 

I had tremendous fun coordinating work on the project, and I enjoy working with Monorail on my day job. I just do not have neither the time nor the attention to give the project anymore, and John is a much better fit, as he proved over the last few months with his efforts for the project.

 

So I treated myself to a one demanding hobby less.

 

I hope it will help me post more regularly now.

 

 

Interesting enough, I plan to do a few posts about recent performance issues I tackled in AspView. So I guess my MR days really aren’t over yet :)

Castle project has finally moved to git

  

http://github.com/castleproject/

 

thanx a bunch to the work done by Mauricio Scheffer, Henry Conceição and the rest of the people helping out in the process.

 

fork away :)

Monorail view engines usage poll

  

If you use monorail, then go ahead and vote:

http://twtpoll.com/bbsrdu

What’s new in Monorail 2.0

  

During the long, long time it took to get from 1.0RC3 to 2.0, many things have changed, and many things were added. I probably won’t cover it all in this post, and I’ll probably forget a few things that I got so accustomed to use (I have always used trunk versions, even way before I became a committer).

 

  Programmatic config If (like me) you do not like putting stuff in config files that the operations team do not care about, you can now run a Monorail application without the Monorail section in the web.config file.

How?  you’d need your Global class to implement IMonoRailConfigurationEvents.

e.g. from many of my websites: (I’m configuring AspView as view-engine)

public void Configure(IMonoRailConfiguration configuration)
{
	configuration.ControllersConfig.AddAssembly(Assembly.GetExecutingAssembly());
	configuration.ViewEngineConfig.ViewPathRoot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Views");
	configuration.ViewEngineConfig.ViewEngines.Add(new ViewEngineInfo(typeof(AspViewEngine), false));
}

you can setup many optional things that way. e.g.:

// configue jquery as the validation engine
configuration.JSGeneratorConfiguration.AddLibrary("jquery-1.2.1", typeof (JQueryGenerator))
	.AddExtension(typeof (CommonJSExtension))
	.ElementGenerator
	.AddExtension(typeof (JQueryElementGenerator))
	.Done
	.BrowserValidatorIs(typeof (JQueryValidator))
	.SetAsDefault();
// configure url extensions
configuration.UrlConfig.UseExtensions = false;

delve into the intellisense on the IMonoRailConfiguration interface to find more

  Return binders The example speaks for itself:

public class State
{
    public string Code { get; set; }
}

[return: JSONReturnBinder]
public State[] GetStates()
{
    // fake code for the sake of the demonstration
    return new[] { new State { Code=“CA” }, new State { Code=“WA” } };
}

will render the JSON representation of the given State array

  New routing engine see http://www.castleproject.org/monorail/documentation/trunk/advanced/routing.html

and http://kenegozi.com/blog/2009/02/10/monorail-routing-and-the-homepage-routing-rule.aspx for setting a homepage route

  RescueController A rescue controller will take care of exceptions that have happened during an Action.

You’d create your rescue controller, implement IRescueController, inherit from SmartDispatcherController, and setup the rescue controller in the RescueAttribute on the regular controller.

see more here: http://www.castleproject.org/monorail/documentation/trunk/usersguide/rescues.html

  AspView The C# based view engine became a first class citizen in Monorail. There has been many improvements there during the time, which deserve a separate post perhaps. meanwhile you can look at the aspview tag on this blog: http://kenegozi.com/blog/Tag/aspview.aspx

 

I can’t think of more stuff right now, so ping me if I forgot anything.

Monorail 2.0 – why the hell did it take so long

  

Being an Open Source project, with very good test coverage and a very active development, most users that actually run Castle bits in production were running off of trunk anyway.

 

The trunk is very stable, and the act of “release” should have simply been tagging any single commit to trunk as the 2.0 RTM.

 

However, we felt that we wanted some more stuff to justify a release – like updating the documentation, re-doing samples and Visual Studio integration packages, etc.

That lead us to a halt, as active committers did not use neither integrations nor samples, and same for the documentation. My personal stand was (and still is) that if someone wanted an official release so badly, then that one should contribute toward this, either with time and work, or with sponsorship money to buy this time and work.

 

No one did.

 

A few attempts at these parts was taken, but none concluded.

 

Meanwhile the project grew more and more, and parts of it became mandatory dependencies to various mainstream projects (such as NHibernate), while Windsor became more and more adopted as an IoC container of choice for many people.

Getting to a single point of approval across the board for the whole castle stack, without breaking third-party projects that depends on parts of Castle, became very difficult.

  Breaking apart In order to allow a manageable release process, the project was broken down to its parts. Now we have the four main projects, released on their on, with depending projects using compiled releases of the others.

The main projects are:

More details can be found on the projects page of castle’s website

 

An all-trunk builds can be retrieved with the aid of the horn-get project.

  So why is Monorail last? The reason is rather simple. Monorail depends on almost any other part of the stack. It even has subprojects such as ActiveRecord’s DataBinder (ARDataBind) which depends on ActiveRecord, and a WindsorIntegration project which depends on the IoC stack.

As a result we had to wait to get releases for all other projects.

  What’s next? I still have no idea. There are a few discussions going on about that (such as this one on the new roadmap), and you are all welcome to join the debates.

Monorail 2.0 is out

  

After a long huge wait, finally Monorail 2.0 is out, get yours from  https://sourceforge.net/projects/castleproject/files/

 

HUGE thanks to John Simons and the rest of the Castle project committers, plus the rest of the good people that have supplied us with patches, bug fixes, and whatnot.

 

This move somewhat concludes the move from the old 1.0RC3 release from 2007, to the new releases of the Castle stack about two years afterwards.

 

I’m going to follow up with a couple of “what’s new”, “how-to upgrade” and “why the hell did it take so long” posts soon, so keep watching.

NHibernate (and ActiveRecord’s) show_sql in web application

  

Looking into When using an OR/M of any kind, it is quite worthwhile to be able to look at the SQL generated by the tool, for various reasons (such as tuning the DB, finding SELECT N+1 issues, and sheer curiosity).

  Solution #1 One way of doing that is to start a profiler on the DB engine, but it has its downsides. For one, you would need a profiler tool, which is not always freely available. You might also not be able to access the DB engine with that kind of tool on various hosted environments.

 

In NHibernate’s configuration (and it is also exposed to Castle’s ActiveRecord users) you can set a property names “show_sql” to true. This will cause NHibernate to spit every SQL query, along with its parameters, onto the Console. Very useful when running Tests, but when running within a Web Application, you do not have access to the Console window, and can’t really see what is going on.

That also leads to another problem with using a profiler on the DB engine – you won’t be able to figure out which queries belong to which web request.

  Solution #2 One comprehensive solution is to use the excellent tool from Oren Eini – NhProf. I will not cover this tool here; it does lots of great stuff, and can help your development cycle. However not everyone will be willing to pay the price for using it.

 

not to worry, I hereby offer you two more options, which gives you less options, but are good enough for the problem at hand, and are free.

  Free solution #1 NHibernate is using log4net. it stores a lot of what it’s doing there. So, one can always setup a logger named “NHibernate.SQL” and get a hold of the queries. I do not cover log4net usage here. Google it up, and then set up the NHibernate.SQL logger.

You’d also want to setup a log4net variable for you to group the queries it gets by the web-request that needed them. You can do so by setting a property on log4net’s GlobalContext. e.g., in Application_BeginRequest:

log4net.GlobalContext.Properties["page_url"] = Context.Request.RawUrl + "|" + Guid.NewGuid();

then you’d set the log appender to write the page_url value, and you’ll be able to Group By it.

 

 

But this suck. You need to depend on log4net even if you do not want to, and setup that hack-ish global property, then read it from the log4net storage, and lots of complexities. wouldn’t it be great if you could simply got a hold of the Console’s output (or at least the NH parts of it?)

  Free solution #2 – even simpler The Console object allow you to set a custom Writer to its Out stream. Meaning, you can grab the Console’s output into an in memory string during a request, and then at the end of the request, grab all lines that starts with “NHibernate:” and you’re done:

 

on Application_BeginRequest:

var writer = new StringWriter();
Console.SetOut(writer);
Context.Items[SqlLogFilter.SQL_LOG_WRITER_KEY] = writer;

on Application_EndRequest:

var writer = HttpContext.Current.Items[SQL_LOG_WRITER_KEY] as StringWriter;
if (writer != null)
{
	var lines = writer.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
	var relevantLines =
		lines.Where(l => l.StartsWith("NHibernate") || l.Length > 0 && char.IsWhiteSpace(l[0])).ToArray()
		;
	var queries = string.Join(Environment.NewLine, relevantLines)
		.Split(new[] {"NHibernate:"}, StringSplitOptions.RemoveEmptyEntries)
		.Select(q => q.Trim());
	DoSomethingWith(queries);
}

 

within DoSomethingWith you can do whatever you like with the queries string collection

 

The more complete solution that I use, is taking advantage of a feature in Monorail’s AspView called ViewFilter (you can do this with ASP.NET’s output filter; look up HttpFilter. it’s not as clean, but workable). I create a filter that wrap the stuff that’s on the Application_EndRequest, turn the queries collection into a bunch of <pre> elements, and stick it within the view-engine’s output by simple string.Replace call, injecting these <pre> elements into a marker location in the markup.

I’d then use jQuery to make these <pre> elements visible when clicking somewhere secret on the screen.

 

The ViewFilter’s code (for reference):

public class SqlLogFilter : IViewFilter
{
	public static readonly string SQL_LOG_PLACEHOLDER = &quot;SQL_LOG_PLACEHOLDER&quot;;
	public static readonly string SQL_LOG_WRITER_KEY = &quot;SQL_LOG_WRITER_KEY&quot;;
	public string ApplyOn(string input)
	{
		var log = &quot;&quot;;
		var writer = HttpContext.Current.Items[SQL_LOG_WRITER_KEY] as StringWriter;
		if (writer != null)
		{
			var lines = writer.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
			var relevantLines =
				lines.Where(l => l.StartsWith(&quot;NHibernate&quot;) || l.Length > 0 &amp;&amp; char.IsWhiteSpace(l[0])).ToArray()
				;
			var queries = string.Join(Environment.NewLine, relevantLines)
				.Split(new[] {&quot;NHibernate:&quot;}, StringSplitOptions.RemoveEmptyEntries)
				.Select(q => q.Trim());
			log = queries
				.Select(q => &quot;&lt;pre&gt;&quot; + q + &quot;&lt;/pre&gt;&quot;)
				.Aggregate(&quot;&quot;, (q1, q2) => q1 + q2);
			var count = queries.Count();
			log = &quot;&lt;p&gt;Queries: &quot; + count + &quot;&lt;/p&gt;&quot; + log;
		}
		return input.Replace(SQL_LOG_PLACEHOLDER, log);
	}
}

DefaultValue attribute for MonoRail

  

Another gem from Daniel Hölbling.

 

In short – it will allow you to write code like:


public void Browse([DefaultValue(&quot;beer&quot;)] string category, [DefaultValue(1)] int page)&#160; {&#160; 

   ...
}

 

grab it here

 

 

 

The cool thing is that because MonoRail is so extremely flexible, one can really easily add this type of functionality without touching the code-base, but rather implementing a straightforward interface. That’s what I call extensibility.

One more super kudos to Hammett for the overall architecture of MonoRail.

Monorail Release - Status update and call for help

  

I want to release MonoRail as soon as I can. In order to do so I will need some help from the community. Let me list the things currently missing:

Any help with the above will be greatly appreciated.

 

thx,

Ken.

MuHaHaHaHa, or Livin’ La Vida Loca without the Page Lifecycle

  

 

http://weblogs.asp.net/ricardoperes/archive/2009/03/08/asp-net-page-events-lifecycle.aspx

 

Monorail has never felt this good

Monorail Routing and the Homepage routing rule

  

Scenario: You are building a Monorail web site, and want to setup a route from the application’s path to a given action (usually home/index)

The problem: The pattern “/” does not work, so

RoutingModuleEx.Engine.Add(
    new PatternRoute("Home", "/")
        .DefaultForArea().IsEmpty
        .DefaultForController().Is("Home")
        .DefaultForAction().Is("Index")
    );

will fail to serve http://yoursite/

Same will happen if you’re using the Code Generator for setting up rules.

[PatternRoute("Homepage", "/")]
public void Index() { ... }

will fail just the same

The fix: Use the pattern “/[controller]”, like that:

RoutingModuleEx.Engine.Add(
    new PatternRoute("Home", "/[controller]")
        .DefaultForArea().IsEmpty
        .DefaultForController().Is("Home")
        .DefaultForAction().Is("Index")
    );

or if you’re using the Code Generator:

[PatternRoute("Homepage", "/[controller]")]
public void Index() { ... }

Future fix: I’m considering adding a useful HomepageRoute that will derive from PatternRoute and will have all the needed conventions for easily setting up the homepage rule. Hopefully will be in trunk by this weekend. This will allow a simpler default syntax:

RoutingModuleEx.Engine.Add(
    new HomepageRoute()
    );

or (using the code generator):

[HomepageRoute]
public void Index() { ... }

Convention over Configuration.

Stuff from the Monorail presentation

  

Here is the promised presentation from the talk I gave yesterday, for the Web Developers Community at Microsoft offices in Ra’anana.

The sources for the demo I showed are hosted on github. If you’re not using git (and you should give it a try if that is the case), you can grab a zip of the latest snapshot from that site (there’s a ‘download’ button). Git is worth using if only for the great service given by github.

http://github.com/kenegozi/monorail-aspview-demo/tree/master

As for the slides - I tried using scribd and SlideShare, both attempts ended up not too well. I’ll try to get a better format later on.

I’d like to thank Noam King, the organiser of the WDC group, for having me as a speaker. I’d also like to thank Damien Guard who have created the Envy Code R font which I used during the presentation.

Monorail talk

  

I’ll be giving a talk on Monorail tomorrow evening, at Microsoft offices in Ra’anana.

Registration details are here:

https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032402276&Culture=he-IL

I’ll try to upload the presentation beforehand to here (no promises though).

See you there :)

Beware of static session

  

The bug: Weird behaviours regarding session management

  The blame: (within session access wrapper static class):

private static IDictionary session;
...
if (session == null)&#160;&#160; session = new SessionAdapter(HttpContext.Current.Session);
...

so the first time the last line is called, the then-current-session is stored in a static variable, thus the first session is always referenced even for newer sessions.

 

The reason for the above code being present in the first place is that:

public static void SetSessionTo(IDictionary newSession)
{
    session = newSession;
}

So that tests that a stubbed ‘session’ could have been injected into the session-wrapper-static-class thingie.

Clearly, the implementation was wrong.

  The fix: now the code looks like this:

private static IDictionary stubbedSession;

static IDictionary Session
{
    get { return stubbedSession ?? MonoRailHttpHandler.CurrentContext.Session; }
}

And these were 60 seconds on careless coding.

 

Ken, the careless coder

Monorail usage poll

  

Following my last post, I’ve put up a quick poll for trying to grasp some knowledge about the way people are using (or not using) MonoRail.

It’s not complete, and there will be further polls as I can already think of questions I have for the community, that did not make their way to this poll, and are very important imo.

So, if you care for the future of MonoRail, please do spare some moments to fill in the poll. Be nice and write down your feelings, pain-points and general rants in the text areas. I won’t be offended by anything.

No personal details will be published (at least not deliberately - and I don’t believe anyone will hack into the lousy SQL server it’s stored on).

so, without further ado, I give you the poll:

http://kenegozi.com/monorailpoll.html

Introducing Monorail Project

  

From the mailing list:

… the PMC decided to make a few changes to the Castle Project:- Projects will be split- Each project will have a leader (positions open to any committer)By that we intent to fix our release debt. as having each project running individually allow us to release and document each one of them without dragging/waiting for others.

We still haven’t decided how to solve dependencies and such, but with time I’m certain we’ll be able to come up with solution that will benefit the community.

ah, and I have been the one appointed as Project Leader for Monorail.

Quoting again from the mailing list:
We would expect from the leaders to oversee the development (near and long term), set up goals, roadmaps, coordinate the documentation effort and release it.

So my main effort now will be to push a Monorail 1.0 RTM release out of the door. There are many things that need be done before this comes true as in terms of the non-code aspects (like docs, wizards, etc.), Monorail is not as ready as ActiveRecord for example.

I will be posting some specific requests for help on the various tasks that will need to be done. I hope that with the aid of the community, we will have a release soon-ish.

Single and looking

  

explanation (before the wife kills me): I have some free time in the coming months, so I’m looking for interesting consulting gigs.

So, if you’re in a company / dev team, and looking for some help with Castle (Windsor, MonoRail), NHibernate, or general information system design and architecture advices or training, setting up build and test environments, or any other of the things I rant about in this blog, then I’m your guy.

I also do web-client ninja work, dancing the crazy css/html/javascript tango (jQuery: yes, Ms-Ajax: no)

I currently live in Israel, but I’m fine with going abroad for short terms if you’re an off-shore client.

you can contact me at “ken@kenegozi.com”

Creating a custom parameter binder for MonoRail actions - IParameterBinder

  

Background When using SmartDispatcherController as a base class for a MonoRail’s Controller, there are built-in smarts for binding values from the client (Form, QueryString, Request.Params) into .NET data types.So, assuming the request holds “age=30”, and there’s an action

public void SomeAction(int age) ...

then the integer variable ‘age’ will get populated with the value 30.

This will work for every .NET primitive (int, string, bool) and even DateTime and Guid. If the value is missing from the request, a default value will be set, for example - 0 for integers, or null of nullable types.

There’s also DataBindAttribute that allow you to bind values to a non-primitive DTO object.Say you have

public class User
{
    string Name {get;set;}
    int Age {get;set;}
}

and that your request is holding “User.Name=Ken&User.Age=30”, then the following action

public void SomeAction([DataBind("User")] User user) ...

will bind the age and name into a new instance of User.

Problem Yesterday, on Castle devs mailing list Andre Loker was asking about a way to bind a value to an action argument, but with the value having a name that cannot match a c# variable name.For example, let’s say that the request is holding “User.Age=30”, but you do not want to bind to a User instance (through DataBind) but you want only the Age part, into an integer variable.You certainly cannot have your action signature look like

public void SomeAction(int User.Age) ...

Solution: Luckily for us, MonoRail was built with extensibility in mind (and whenever a user feels something more is required in the field of extensibility, a patch is always welcome :) ).The extension point here is the IParameterBinder interface, which is being used in DataBindAttribute to let the framework know that the attribute is to be used for data binding.

IParameterBinder:

/// &lt;summary&gt;
/// Implemented by attributes that wants to perform 
/// some conversion to populate a smart dispatcher 
/// action argument.
/// &lt;/summary&gt;
public interface IParameterBinder
{
    /// &lt;summary&gt;
    /// Calculates the param points. Implementers should return value equals or greater than
    /// zero indicating whether the parameter can be bound successfully. The greater the value (points)
    /// the more successful the implementation indicates to the framework
    /// &lt;/summary&gt;
    /// &lt;param name="context"&gt;The context.&lt;/param&gt;
    /// &lt;param name="controller"&gt;The controller.&lt;/param&gt;
    /// &lt;param name="controllerContext"&gt;The controller context.&lt;/param&gt;
    /// &lt;param name="parameterInfo"&gt;The parameter info.&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo);

    /// &lt;summary&gt;
    /// Binds the specified parameters for the action.
    /// &lt;/summary&gt;
    /// &lt;param name="context"&gt;The context.&lt;/param&gt;
    /// &lt;param name="controller"&gt;The controller.&lt;/param&gt;
    /// &lt;param name="controllerContext"&gt;The controller context.&lt;/param&gt;
    /// &lt;param name="parameterInfo"&gt;The parameter info.&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo);
}

The CalculateParamPoints function is used by the framework to help SmartDispatcherController decide with overload of a given action should be used.

the Bind function, well, binds the request data into the given parameter.

Here is a naive BindFrom attribute, which is to be used like that:

public void SomeAction([BindFrom("User.Age")] int age) ...

The code:


[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class BindFromAttribute : Attribute, IParameterBinder
{
    private readonly string parameterName;
    private readonly IDataBinder binder = new DataBinder();

    public BindFromAttribute(string parameterName)
    {
        if (string.IsNullOrEmpty(parameterName))
        {

            throw new ArgumentException("parameterName must not be null or empty", "parameterName");
        }
        this.parameterName = parameterName;
    }

    public string ParameterName
    {
        get { return parameterName; }
    }

    public int CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
    {
        var token = context.Request[parameterName];
        if (CanConvert(parameterInfo.ParameterType, token))
            return 10;
        return 0;
    }

    static bool CanConvert(Type targetType, string token)
    {
        if (token == null)
            return false;



        try

        {
            Convert.ChangeType(token, targetType);
            return true;
        }
        catch(FormatException)
        {
            return false;
        }
    }

    public object Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)
    {
        var token = context.Request[parameterName];
        if (CanConvert(parameterInfo.ParameterType, token) == false)
            return null;

        return Convert.ChangeType(token, parameterInfo.ParameterType);
    }
}

Conclusion The IParameterBinder interface is very important as it allow a user to extend MonoRail to his exact needs. If you want to learn more about that interface and it’s uses, the best places to look are DataBindAttribute.cs in Castle.MonoRail.Framework/Attributes, and ARDataBindAttribute.cs in Castle.MonoRail.ActiveRecordSupport

As a side note, I’m thinking about adding the discussed behaviour into the default DataBindAttribute, so one would be able to bind into primitives, say from “User.Age=30&User.Name=Ken” using

public void SomeAction([DataBind("User")] int age, [DataBind("User")] string name) ...

MonoRail sample gone AspView

  

Some more AspView love:

This dude, Morten Lyhr (great blog - go on and subscribe), has taken the sample MonoRail Getting Started project and AspView-ed it.

 

Take a look.

I didn't brake the build

  

After making it build locally and reaching the conclusion that AspView builds correctly as part of the main Castle build , I’ve commited the changes to the repository, and the build server appear to agree with me:

Build_Succeded_on_the_build_server

Build Succeeded - A happy red screen

  

can you guess why this makes me happy?

Build_Succeded

This is the output of building Castle’s trunk, both for .NET 3.5 and .NET 2.0, after inserting AspView into the core project. Took me a while as I had to:

So, soon enough (hopefully by the end of this day) you’d be able to see AspView on the build server.

 

Thx again for all of the users and patch-contributors for your faith in this library.

FileBinderAttribute to ease FileUpload in MonoRail

  

Following Scott Hanselman’s post on FileUpload in ASP.NET MVC, I’ll add here a few bits on doing that in MonoRail.

First, as MonoRail is an extension on top of plain ol’ ASP.NET, just as ASP.NET MVC is, you can do the exact same thing - i.e iterate over Request.Files, and use a mocked Files collection for test or something.

But as the action parameters binder is very smart, and easily extensible, it’s even nicer to just bind the posted data to a HttpPostedFile, using a FileBinder:

   1:  [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]   2:  publicclass FileBinderAttribute: Attribute, **IParameterBinder**   3:  {   4:  publicint CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)   5:      {   6:  var key = parameterInfo.Name;   7:  return context.Request.Files[key] != null ? 10 : 0;   8:      }   9:    10:  publicobject Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)  11:      {  12:  var key = parameterInfo.Name;  13:  return context.Request.Files[key] as HttpPostedFile;  14:      }  15:  }

So a custom binder is an attribute, that implements IParameterBinder, a two methods interface:

so now you’re action can look like this:

   1:  publicvoid Save([FileBinder] HttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

Cool? well actually what really is cool is that binding to HttpPostedFile is baked into MonoRail to begin with - so you don’t even need this FileBinderAttribute at all ! you can simply

   1:  publicvoid Save(HttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

So why did I show you that?

Testablility.

Since HttpPostedFile is not easily mockable* (cuz it’s bloody sealed and not new-able), you should do what you always do when in need to bypass one of these un-testable hard-to-test* sealed classes: Adapter pattern. Introduce IHttpPostedFile, and supply your own HttpPostedFile encapsulating the built in one.

so:

   1:  [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]   2:  publicclass FileBinderAttribute: Attribute, **IParameterBinder**   3:  {   4:  publicint CalculateParamPoints(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)   5:      {   6:  var key = parameterInfo.Name;   7:  return context.Request.Files[key] != null ? 10 : 0;   8:      }   9:    10:  publicobject Bind(IEngineContext context, IController controller, IControllerContext controllerContext, ParameterInfo parameterInfo)  11:      {  12:  var key = parameterInfo.Name;

  13:          var file = context.Request.Files[key] as HttpPostedFile;    14:  return file == null ? null : HttpPostedFileAdapter(file);  15:      }  16:  }

and

   1:  publicvoid Save([FileBinder] IHttpPostedFile myfile)   2:  {   3:  if (myFile != null)   4:      {   5:  // do stuff with the file   6:      }   7:  }

MonoRail talk at The Developers Group

  

Have just came back from my talk, given for The Developers Group in Microsoft’s Victoria offices, London UK.

Took me a bit to find the place, as the building does not say “Microsoft” on the outside (as opposed to the offices in Israel).

The presentation went pretty much ok, considering it was my first time actually presenting in English, in front of an English crowd, and considering I had a PC malfunction that has forced me to recreate the Demo project, on the train today … Just finished it up 5 seconds before connection the laptop to the projector.

I didn’t manage to squeeze in some of the parts that I wanted to, like JSONReturnBinder and Windsor integration, and like Unit-Testing controllers and views, but I do hope that I managed to do justice with this wonderful stack, within the limited time and my horrible English …

Unfortunately, I missed the post-meeting-pub-thing as I just happened to leave the place last and didn’t see where everyone did go, so if you were there and has some questions, please do not hesitate to leave them here as comments.

Anyway, as promised, here are the slides and the demo project.

If you are using git, and have a git-hub account, then you would be able to follow the demo project’s source at http://github.com/kenegozi/monorail-aspview-demo/tree/master

Have fun.

P.S

I’d like to thank Jason from The Developers Group, and Nina from Microsoft, who have helped with the administration part of things. Everything went smooth despite my late arrival. I’d also like to thank the attendees for their patience and listening. I hope you’ve enjoyed it, I definitely have :)

alt.net uk conf

  

This weekend I’ve had to pleasure to attend the altnetuk conf in London. This has been quite an amazing experience. I have really liked the way it has ben organized into open-spaces, and I just wish I could’ve split myself to four, so I’d be able to be at all of the sessions (the F# one was greatly missed …)

I have met great people, have discussed exciting things, and had a lot of fun.

Most of the people referred to me as “the MonoRail guy” which was quite amusing, as I am only the creator of AspView (which in turn is a shameless idea-and-code ripoff from Brail), and I have very little to do with the actuall coolness and usefulness of MonoRail … I do hope though that I did manage to address pepole concerns regarding MonoRail, and the Castle Project as a whole.

Interesting (however not surprising) moment:

On the panel dealing with MVC frameworks for ASP.NET, about 25 people were around the table. When people who are actually using MonoRail/ASP.NET MVC for commercial production environment, only 4 have raised their hands. however, all the others said that they wish the could have done that, and the only reason they do not, is the reluctance from their bosses/clients.

My Favorite Quote From AltNetUK conf

  

After being told that MonoRail would not make his dreams come true, Dylan Beattie have answered:

“MonoRail would not make my dreams come true. It would however, make my nightmares disappear”

Brilliant.

StaticMapGenerator for ASP.NET, First Teaser

  

Last night I got frustrated with the fact that I have no intellisense (nor compile time check) for locating static files like .js, .css and image files.

So I sat up and created a simple console application that can generate exactly that, out of the site’s filesystem.

usage:

D:\MyTools\StaticMapGenerator /site:D:\Dev\MySite

it generates a file called Static.Site.Generated.cs within the site’s root folder, and then I go and include that file in my web project.

No I can do stuff like:

&lt;script type="text/javascript" src="<%= Static.Site.Include.Scripts.myscript_js %&gt;"> &lt;/script&gt;&lt;link rel="stylesheet" href="<%= Static.Site.Include.CSS.master_css %&gt;" />&lt;img alt="Ken Egozi" title="My Logo" src="<%= Static.Site.Include.Images.Logos.my_logo_png" /&gt;

How cool is that?

It works in every ASP.NET compatible web framework (MonoRail, ASP.NET MVC, even WebForms …)

The only prequisite is .NET 2.0 runtime.

Sorry for keeping it out of reach for the moment. I need a little bit of time to setup a svn repository to make the source public (it would of course be BSD/Apache2/MIT thing) and to upload a binary. No promises given, I’ll try to make it in the coming weekend, or even tonight, so stay tuned.

The code is somewhat naive, and certainly does not cover any edge cases, however it’s enough to work cleanly on the largest project I’m currently involved in (Music Glue). Patches to make it more configurable and able to handle more edge cases would be gladly accepted once it’s out.

One cool spot - as part of this, I have also implemented my tiny IoC container in 33 LoC.

Conditional Rendering, or I Do Not Want Analytics Code On Dev Machine

  

From time to time you’d want some of your markup rendered only on ‘real’ scenarios. For example, you wouldn’t want google analytics to track visits you do on your dev machine. Sometime you’d even develop while your machine is not even connected to the internet, and every page would try get the analytics script and will behave strangely.

In Monorail, the Request has a property named IsLocal, just for that. I’ve wrapped it in a nice ViewComponent.

public class GoogleAnalyticsComponent : ViewComponent{
 public override void Render() { if (Request.IsLocal) return; RenderView("AnalyticsCode"); }} 

Accompanied by the AnalyticsCode view template:

&lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime" %&gt;&lt;script src="https://ssl.google-analytics.com/urchin.js" type="text/javascript"&gt;&lt;/script&gt;&lt;script type="text/javascript"&gt; _uacct = "MY_URCHIN_CODE"; urchinTracker();&lt;/script&gt;

, that can easily be extensible to set the urchin code with a parameter.

AspView and the Latest Castle Trunk

  

Lately there has been a major refactoring work being done on MonoRail, as part of the effort toward a release hopefully later this year. As of today, AspView’s trunk is once again compatible with Castle’s trunk.

As usual, code’s here, binaries are here.

Using Layout From a Custom Location

  

It’s been asked on the Castle mailing list, and was implemented for NVelocity (and for Brail too, I think), so now it works on AspView, too.

So, doing:

[Layout("\custom\layout")] public class MyController ...

Would use the template from Views\Custom\Layout.aspx

No More Null Ref (almost)

  

I found out that on many occasions I use stuff like:

&lt;aspview:properties&gt;string message = "";&lt;/aspview:properties&gt;

To avoid the need of:

&lt;% = message ?? "" %&gt;

That’s it.

From now on, null values would just be ignored.

Notice that it won’t help you on

<%=post.Blog.Title %> if post.Blog is null …

New Features For The New Year

  

In a good timing for the new year, I’m happy to announce new features to AspView.

I have dedicated a post for each so I’d have a way to reference those features, and for my dear readers to comment on each feature.

So, what’s all the fuss about?

Downloads, as always, are from www.aspview.com

Nested Layouts

  

A cool feature, repeatedly asked for by users (of AspView, and of MonoRail in general).

When stating the layout name in the controller, you use a comma separated list of layouts to be applied, from the most general (outer) inward.

Example:

in the controller:

[Layout("Site, Admin")]public class UsersController : SmartDispatcherController{ public void Index() { }}

and given those schematic templates:

We’d get:

rendered view

Html Encoded Output In View Templates

  

The existing <%= %> syntax would keep output the raw strings, so it can be used to output properties that has markup inside, like CMS data, the ViewContents in layouts, CaptureFor data, etc.

If you want http encoded output, use <%# %> or ${} instead.

Example:

Given the following view template:

&lt;%string markup = "<span&gt;";%>&lt;%=markup%&gt;&lt;%#markup%&gt;${markup}

The rendered output would be:

&lt;span&gt;&amp;lt;span&amp;gt;&amp;lt;span&amp;gt;

Have fun.

Embedded Script Blocks

  

Say you want to have the possibility to create a method to work in views.

for the sake of argument, let it be:

public string DoubleId(string s){ return s + s;}

your options:

But what if it’s simple enough (so you won’t need a unit-test) and it’s not supposed to be reused (so creating a Helper/Base class is an overkill)?

Now you can put it directly in your view template, and this is how:

&lt;script runat="server"&gt;public string DoubleId(string s){ return s + s;}&lt;/script&gt;Regular view code&lt;%=DoubleIt(view.Name) %&gt;

Now the devil advocates would say that “Logic In View Is Evil”. And I would concur. But it’s not actually logic. It’s supposed to be used for view-related string manipulations and such. And anyway you can do Evil Deeds without it, too. And you don’t HAVE to use it if you don’t want to.

The idea (and 99% of implementation) is by Gauthier Segay. Thanks dude !

XSS, HttpEncode, AspView and being Secure By Default

  

If you know not what XSS is or how easily you can expose your application to XSS, take a short read at the next posts:

AspView was written by me, for my (and my employer at the time) use. Therefore, I did not make it ‘secure by default’ in terms of HttpEncode.

However, seeing now that the convention lean toward outputing HtmlEncode-ed by default, I’m adapting AspView to that.

The usage would be similar to the one suggested for Asp.NET MVC at http://blog.codeville.net/2007/12/19/aspnet-mvc-prevent-xss-with-automatic-html-encoding/

So,

&lt;%="<tag&gt;" %> 

would output

&amp;lt;tag&amp;gt;

While

&lt;%=RawHtml("<tag&gt;") %>

would output

&lt;tag&gt;

The only exception here is ViewContents on layouts. since the view contents is 99% of the times made of markup, so in the layout would still write:

&lt;%=ViewContents %&gt; 

All of that stuff is being implemented with AspView trunk (versions 1.0.4.x) that works with Castle trunk.

If anyone wishes me to bubble it down to the 1.0.3.x branch (for Castle RC3), please leave your comments here. Unless I’ll see that people actually want that I would probably not make the effort.

New stuff in AspView

  

I’m pleased to announce that the first step of AspView refactoring is over. The pre-compilation process is now way more coherent and easy to follow and to test. Soon enough, as I’ll complete adding a service locator to the mix, it would also be easily extensible.

What can you do now that you couldn’t have done before? Use a custom base class for views.

For example: let’s say that you have created a supercool helper. You’d probably name it SuperCoolHelper. Now you register that helper on the controller:

[Helper(typeof(SuperCoolHelper))]public class MyController ...

You can, ofcourse declare it on every view:

&lt;aspview:parameters&gt;&lt;%SuperCoolHelper SuperCoolHelper;%&gt;&lt;/aspview:parameters&gt;&lt;%=MyCoolHelper.CoolStuff() %&gt;

You can also use the DictionaryAdapter and add the helper to the base view interface:


public interface IView{ SuperCoolHelper SuperCoolHelper { get; set; }}

...&lt;% Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime<IView&gt;" %>

...&lt;%=view.MyCoolHelper.CoolStuff() %&gt;

But now you can create a base class for the view:

The base class:

public class MyView : AspViewBase{ SuperCoolHelper SuperCoolHelper { get { return (SuperCoolHelper)Properties["SuperCoolHelper"]; } }}

A mocked class that inherit from Web.UI.Page to make intellisense play nicely:

public class MyViewAtDesignTime : ViewAtDesignTime{ SuperCoolHelper SuperCoolHelper { get { throw new NotImplementedException("useless"); } }}

and in the view:

&lt;% Page Language="C#" Inherits="MyViewAtDesignTime" %&gt;...&lt;%=MyCoolHelper.CoolStuff() %&gt;

You can mix that with the DictionaryAdapter integration:

&lt;% Page Language="C#" Inherits="MyViewAtDesignTime<IPostView&gt;" %>...
&lt;%=MyCoolHelper.CoolStuff(view.Post.Title) %&gt;

As usual: http://www.aspview.com

AspView refactoring status

  

77 tests, all green.

That’s all new tests from the last week.

I think it’s almost stable enough for releasing it on aspview.com

I’ll just put the old tests back in (with Ignore) as regression tests, until I’m comfortable enough to remove.

So - custom base classes for views are just around the corner.

Right after that - better extensibility (through custom Pre Compilation Steps provider and MarkupTransformation Provider)

you can of course watch the progress on svn (it’s all on the trunk, so if you’re using trunk for production, please restrain yourself a few more days …)

stay tuned …

Is ASP.NET MVC Around the Corner

  

Well, According to Scott Gu we’d be able to download the binaries Next Week,

I can’t wait to put my hands on that, and start finding the possibilities of this framework in conjunction with MonoRail.

Using the CodeGenerator and the DictionaryAdapter

  

Following users requests, I have just posted two documents to using.castleproject.org.

The first is an explanation about the CodeGenerator (from Contrib), and another one, on using the DictionaryAdapter.

Here are the links:

Related stuff:

Screen Cast - Creating MonoRail-AspView Web Application From Scratch

  

Following many requests from users, I’ve created a screen cast in which I show how to setup a new MonoRail/AspView website, from scratch (no wizards).

CreatingMonoRailAspViewWebProjectFromScratchinVisualStudioExpress.wmv

On that demo, I’ve used Visual Web Developer 2008 Express and Visual C# 2008 Express, both in Beta2, just to show how you can simulate some of the “Web Application Project” experience in the Express editions. Of course it’s much easier to work with a full Visual Studio with Web Application Project as you then have everything in a single application, and it’s easier to handle.

Nothing on the demo is 2008 specific, and it runs on .NET 2.0, so VS2005 would do just fine here.

The demo is very simple, and I have generally just showed a “Hello World” level of setup. I hope to spare some time to follow up with setting up things like Windsor Integration, the Castle.Tools.CodeGenerator, and other cool stuff.

The links I use on the demo are:

I’ve used Windows Media Encoder to capture the screen, and my SHURE SM58 mic to record the narrating. It’s a great mic, however plugged into my sorry excuse for a sound-card.

It’s my first screen cast, and I’d love to hear comments from you people, both on the content and on the presentation.

ViewFilter - Take 2

  

I’ve been asked lately about the use of the ViewFilter mechanism in AspView.

I’ve once written about it briefly here on my blog, and you can see it at http://kenegozi.com/Blog/2007/01/08/introducing-viewfilters.aspx

However, I’ll post another (a bit more realistic) example here.

Scenario: some kind of a CMS thing. You want to present the user with some markup, in both “preview” mode and “Source” modes.

If the server had direct access to the markup in a string literal, things were easy. That usually happens when the markup is to be supplied by an end user, either directly or through a WYSIWYG Html editor. You’d end up with something like:

public interface IContentItem{ public string Markup { get; }}

your view would look like:

...
&lt;h3&gt;Preview:&lt;/h3&gt;&lt;div&gt;&lt;%=view.ContentItem.Markup %&gt; &lt;/div&gt;&lt;h3&gt;Source:&lt;/h3&gt;&lt;div&gt;&lt;%=Helpers.Html.HtmlEncode(view.ContentItem.Markup) %&gt; &lt;/div&gt;...

easy enough.

However, what if the piece of markup that you want to show, has some view-logic, so you have a template generating the markup from an entity? For example, this blog has a view “Posts/One” that gets a Post entity, and fits it into a single post markup, putting the title in a <h4>, tags in <span> with theit title and href, etc.

How can you show the markup source for that?

ViewFilter to the rescue.

In short - A ViewFilter is a way to transform a chunk of a view, using simple manipulations. Do not look for that on other View Engines, as it’s currently an AspView-only feature.

Let’s code our needed filter:

public class HtmlEncodeViewFilter : IViewFilter{ public string ApplyOn(string input) { return HttpUtility.HtmlEncode(input); }}

and in the view:

...&lt;% foreach (Post post in view.Posts) { %&gt;&lt;h3&gt;Preview:&lt;/h3&gt;&lt;subview:.Posts.One post="<%=post %&gt;" > &lt;/subview:.Posts.One&gt;&lt;h3&gt;Source:&lt;/h3&gt;&lt;filter:HtmlEncode&gt; &lt;subview:.Posts.One post="<%=post %&gt;" > &lt;/subview:.Posts.One&gt;&lt;/filter:HtmlEncode&gt;&lt;% } %&gt;

Hey - you won’t even need to create that filter. AspView is supplied with four basic (however useful) filters:

Can you think of more reusable view filters? why not post them here, or better yet, supply a patch to AspView with you filters?

ASP.NET MVC Framework - Demo App by Scott Guthrie

  

Scott Guthrie is going to present a demo application using the ASP.NET MVC Framework.

First episode is here: http://weblogs.asp.net/scottgu/archive/2007/11/13/asp-net-mvc-framework-part-1.aspx

Very interesting. I can already see four things that my current VS2005/MonoRail/AspView/IIS5-6 stack lack.

Sounds bad?

Well:

So - all the downsides are taken care of.

Plus, the stack I use is being used in production environment by gazillion people (ok, AspView is not that common, but the ViewEngine is just 5% of the whole stack, and it’s the rock solid part anyway). It is working with .NET 2.0 so I need not convince clients to go for installing .NET 3/3.5 on their shared hosting solution, and since it’s open-source, I can tweak stuff for my needs without the need to wait for a hotfix/ServicePack that might never appear, if not too late.

And if I’m not enough of a jerk for ranting like that, I’m going to try (if I’d have enough time) to put up a sample application using MonoRail/AspView similar to Scott’s, but this time, you would actually be able get the bits and run it on your machines.

Stay tuned.

Nesting View Components in AspView

  

Following a request from Gauthier Segay, AspView now supports nested view components.

scenarion: you are using CaptureFor to inject markup from a view to a layout, and you want the injected markup to include a view component output.

in the layout:

...&lt;%=CapturedContent %&gt;...

in the view:

...&lt;component:CaptureFor id="CapturedContent"&gt; Some markup &lt;component:SomeFancyStuff&gt;Fancy component content&lt;/component:SomeFancyStuff&gt;&lt;/component:CaptureFor&gt;

While working on that, I found out yet another problem. nested components of same type would brake

so:

&lt;component:Bold&gt;&lt;component:Bold&gt;stuff&lt;/component:Bold&gt;&lt;/component:Bold&gt;

would brake.

As you probably might know, the whole preprocessing of view, from AspView syntax to standard C# is done with Regular Expressions. For quickly doing the above, I helped myself to http://puzzleware.net/blogs/archive/2005/08/13/22.aspx in order to build the balanced tags aware regular expression, and now it works like a charm. Roy Osherove’s Regulator was helpful, too.

So, as of revision 360 in Castle Contrib repository, nesting view components works (for both the trunk and the RC3 compatible branch)

As usual - go to http://www.aspview.com to get the binaries, or to http://svn.castleproject.org:8080/svn/castlecontrib/viewengines/aspview/ for the sources.

Cheers.

DevTeach Vancouver - I won't be there, but you should

  

I wish I had the time (and cash) to go there, as great speakers would host there.

Anyway - if I would’ve got there, I’d go for:

Anecdotes:

AspView - AutoRecompilation mode is fully operational

  

If you set autoRecompilation=”true” in your aspview section on web.config, then you need not use the vcompile.exe on every build. The views would get compiled in memory from sources.

Benefits: Change a view source, refresh the browser - viola, you can see he change impact. No need to rebuild the web project, the application is not restarted so no session is lost, and no need for “double refresh”.

Still, when you deploy it’s strongly advised that you’d run VCompile manually, copy the compiledViews.dll to the server, and set autoRecompilation=”false” on the server’s web.config.

The starter tutorial on using.castleproject.org is now updated, and you can download AspView binaries from http://www.aspview.com

Please use that (and other) new features and leave me some comments please …

New Homepage for AspView

  

I’ve just setup a brand new site for AspView.

It’s main purpose is to aggregate AspView related data to one central location. It would contain links to AspView related posts from this blog and others, links to online documentation and samples.

There’d be also a “download” page containing the latest builds to be used with Castle RC3 and Castle trunk.

The site’s link is (surprise surprise): http://www.aspview.com

AspView - New Syntax for Properties Section (Breaking Change)

  

So, what is Properties Section?

View sources files used to look like this:

&lt;%Page Language= ... %&gt;&lt;% int someProperty;%&gt;... rest of view ...

The problem was that if you had no properties (or have used the DictionaryAdpater option described here) then you had to have an empty section, like:

&lt;%Page Language= ... %&gt;&lt;%%&gt;... rest of view ...

Which is quite ugly.

So, following Lee Henson’s suggestion,the properties section should now be wrapped in a special tag, and you can just omit that tag if you do not need to declare any properties.

The new syntax (new stuff in Bold Italic Font):

&lt;%Page Language= ... %&gt;**&lt;aspView:properties&gt;**&lt;% int someProperty;%&gt;**&lt;/aspView:properties&gt;**... rest of view ...

You can download the new binaries, and a utility to migrate your existing views to the new syntax, from http://www.aspview.com

AspView - New Syntax for Passing Parameters to SubViews (Breaking Change)

  

The old syntax for passing parameters to subviews was:

View sources files used to look like this:

&lt;%Page Language= ... %&gt;... blah blah ...&lt;subview:whatever name="value"&gt;&lt;/subview:whatever&gt;

The problem was thatyou could only have passed variables (byname), so if you needed to pass a string literal you had to declare a string object with the literal:

&lt;%Page Language= ... %&gt;... blah blah ...&lt;%string value="literal";  %&gt;&lt;subview:whatever name="value"&gt;&lt;/subview:whatever&gt;

The new syntax follows the syntax for view components, and also the expected scripting syntax.

so now:

&lt;%Page Language= ... %&gt;&lt;%%&gt;&lt;subview:whatever name="mike" age="<%=30%&gt;" currentItem="&lt;%=item%&gt;">&lt;/subview:whatever&gt;

would pass the string literal “mike” to name, the int constant 30 to age, and the object item to currentItem.

You can download the new binaries, and a utility to migrate your existing views to the new syntax, from http://www.aspview.com

Tackling Issues When Testing MonoRail Controllers

  

Usually I’m not doing a strait linking to other’s posts.

However, this time I am, as it explicitly answers a few newbie questions in MR and in UnitTesting.

So now I have a reference …

Typed View Properties in MonoRail and AspView

  

Following my last post on the DictionaryAdapter, I’ll demonstrate here how you can get typed access to your views’ properties.

What it requires from you:

  1. Declare an interface for each of your views. That is a Good Thing anyway, as designing to a contract is a good best practice, and it allows for easy testing.

  2. Have a base class for your controller that would define TypedFlash and TypedPropertyBag. Not mandatory, but very convenient.

  3. Use the newest build of AspView. Again - not mandatory, but helpful.

Now for the showtime.

First we would create a base class for our controllers, with a TypedPropertyBag and TypedFlash properties:

public abstract class Controller&lt;IView&gt; : SmartDispatcherControllerController    where IView : class{    IDictionaryAdapterFactory dictionaryAdapterFactory; IView typedPropertyBag; IView typedFlash; protected IView TypedPropertyBag { get         {             if (typedPropertyBag == null)         typedPropertyBag = dictionaryAdapterFactory.GetAdapter&lt;IView&gt;(PropertyBag);            return typedPropertyBag;         } }  protected IView TypedFlash { get         {             if (typedFlash == null)         typedFlash = dictionaryAdapterFactory.GetAdapter&lt;IView&gt;(Flash);            return typedFlash;         } }  protected override void Initialize() { base.Initialize();        IDictionaryAdapterFactory dictionaryAdapterFactory = new DictionaryAdapterFactory(); }}

tip:

You can look at a more complete version of that base-class, written by Lee Henson (who have made some improvements to the original DictionaryAdapter, and also have introduced me to Peroni Beer).The base controller also declares a type parameter for a Session DictionaryAdapter, hooks into the Castle.Tools.CodeGenerator, and uses IoC for DI.Talking about those issues is a separate subject, for other posts.

Now let’s create the view contract. A rather stupid example would be:

public interface IStupidView{ Guid Id { get; set; }    string Name { get; set; }}

controller:

public class StupidController : Controller&lt;IStupidView&gt;{    public void Index()    {    }    public void DoStuff(string name, string password)    {        if (password != "AspView Rocks")        {            TypedFlash.Name = name;            TypedFlash.Message = "Wrong Password";            RedirectToAction("Index");            return;        }        TypedPropertyBag.Id = Guid.NewGuid();        TypedPropertyBag.Name = name;    }}

view (Index.aspx):

&lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime<IStupidView&gt;" %>&lt;%%&gt;&lt;p&gt;&lt;%=view.Message %&gt;&lt;/p&gt;&lt;form action="DoStuff.rails"&gt;Name: &lt;input type="text" name="name" value="<%= view.Name %&gt;" /> &lt;br /&gt;password: &lt;input type="password" name="password" /&gt; &lt;br /&gt;&lt;input type="submit" /&gt;&lt;/form&gt;

view (DoStuff.aspx):

&lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime<IStupidView&gt;" %>&lt;%%&gt;The data was: &lt;br /&gt;Id: &lt;%= view.Id %&gt;, Name: &lt;%= view.Name %&gt;

Look at the intellisense (and at my ultra-cool black color scheme):

TypedView intellisense

Things to notice:

  1. Do not forget to reference the Assembly that has the view interface declaration. On the test site within aspview’s source repository the interface is declared in the Web project (AspViewTestSite), so the web.config has this:

view (Index.aspx):

&lt;aspview ... &gt;... &lt;reference assembly="AspViewTestSite.dll"/&gt;...&lt;/aspview&gt;
  1. you can use the DictionaryAdapter directly, on older versions of AspView (and on WebForms aspx/ascx files) by simply grabbing an adapter manually. sample:
...&lt;% IMyViewContract view = new Castle.Components.DictionaryAdapter.DictionaryAdapterFactory()       .GetAdapter<IMyViewContract&gt;(Properties); %>...blah blah &lt;%=view.UsefulProperty %&gt;...

Ok, cut the crap. where can I get it?

here (release, debug, source)

UPDATE:

The DictionaryAdapter was initially written by the guys from Eleutian as part of Castle.Tools.CodeGenerator.

MonoRail Faq

  

Following Adam Esterline’s post, some Frequently Asked Questions regarding MR, and my answers:

Q: “What kinds of projects work best with MonoRail?”:

A: all. I’d rather use SmartGridComponent (someone has added auto sorting lately) that GridView, anyday.Especially because those “reporting only” projects tend to grow business rules.

Q: “Can we use 3rd party CustomControls?”

A: Maybe (using WebFormsViewEngine, and other ‘bad’ stuff). However, you can use 3rd party DHTML Controls, which usually are much better, cooler, (and cheaper)

Q: “How do I find new developers? I’d need to teach new devs a lot of new stuff to get them started”

A: I’ve never saw a new developer being productive on day 1. Since there’s no convention in the .NET world, he’d need to learn a lot on arrival, and on every time you’d take him to a new project.Learning to use MR is surprisingly simple, and from my experience, developers learn that very fast, can easily hook to existing Controllers and Views code. I’ve been involved in a WebForms->MR move on four companies, on all cases, all of the existing developers learned it fast, enjoyed it a lot and enough to use MR on future projects, and at least in one place, it allowed the team to recruit a former PHP dev and integrate him to the team in a breeze.

As for recruitment, the idea of HiddenNetworks is genius. People who read my blog (or even better, Ayende’s blog) are probably familiar with MR, so try and grab them. Hey, don’t forget to tell the HiddenNetworks guys that I’ve sent you!

Q: “Now that Microsoft MVC is out, should I use MonoRail?”

A: Microsoft MVC is great. It means that the Big Guns are actually listening to the community. However, it is definitely not Out. I believe it would take a considerable amount of time until it’d beRTM. While MonoRail is in production quality for a long time now, it’s proven, many sites use that, and surly it’s a better choice today, as Ms.MVC is not a choice yet. You should play with MS.MVC, you should learn about it, and when the day comes, you’d be able to move from MR to Ms.MVC if you’d like, cuz the concepts are similar enough.

AspView for Castle RC3 - new release

  

Although about three weeks too late, I present thee:

AspView, builtfor Castle RC3 (release, debug, source)

I’ve also introduced a well due improvement to the engine. Now it supports the use of a 404 rescue view, that would get rendered in case of the url mapping to a non-existent controller.

the commit comment (for revision 314) says it all:

Handling view creation for EmptyController, specifically when a controller is not found and a 404 rescue exists

Next improvement will include an option for doing AutoRecompilation in memory, as sometimes the IIS process gets hold on the CompiledViews assembly files (dll and pdb) and failing the automatic recompilation process.

I certainly need that as it happens on my machine too much, and building the Web project takes a solid 10-15 seconds, while running vcompile is a milliseconds thing only.

Soon …

Some details on the new web MVC framework from Microsoft

  

Now that the Big Boys do actually listening to the community, and gives a shot at a solid MVC web framework is a Good Think.

I would really like to see that in action, and would really like to see how they are coming up with stuff that are more than just url->action wiring, such as parameter bindings, view-components, etc.

It’s going to be interesting, and MonoRail (and) might need some boost to keep being the (imho) no. 1 choice for Web MVC in .NET

It would be interesting also to see where would AspView fit in the new playground.

btw, would that be part of .NET 4.2?

Anyway, since it might take some time to get this new stuff on a production level, I do not believe that no one that works on production system (or those that are supposed to be at production during the coming year) should ditch MR. Even when it’d be out, I might consider MR as a better solution as it’s Open Source, therefore more self twickable, and a lot more responsive in terms of bugfixes.

Some notes from MonoRail/AspView talk

  

Regarding my MonoRail/AspView talk from last week, Oren Ellenbogen has compiled a list of “things to remember”.

His list (with my notes):

These are my notes about the lecture (as someone who wants to use it in our project at Semingo):

  1. DataBind of fields - nice migration from string into classes and vice versa.

  2. Need vcompile.exe in order to compile views.

  3. Cannot use asp.netcontrols. Actually we don’t need it in our project. (Actually you can use ‘em in MonoRail, if you are using the WebFormsViewEngine, but it hurts the simplicity of MonoRail too much)

  4. Routing is a must (think about url structure in our project). (RoutingHttpModule will do the job)

  5. Learn about the mapping process between controllers, views & parameters.

  6. Can use Castle.Validation in order to validate our business objects. (Sweet)

  7. Ask Egozi about client side validation .vs. server side validation in MonoRail. (Castle.Component.Validation integrates well into prototype’s Real-Easy-Field-Validation, as well as some more js validation libraries)

  8. The controller can be injected with outside components (database, services etc) via Windsor, it’s integrated easily. (Another sweet spot)

  9. TDD is easy (controller and view(should we?)), we can mock everything! Don’t forget to call PrepareController method (inside the base class). (Actually PrepareController is Per Controller, so usually it will be called in [SetUp] of each Fixture)

  10. FormHelper & DictHelper should make our life easier. (and you can build your own Helpers easily)

  11. Controller fills PropertyBag(view use it) & Flash (customer messages) – need to define a property in the view (make it string.Empty as default, if Flash[“property_name”] wasn’t filled).

  12. Use Flash property (dictionary) and RedirectToReferrer method to “refresh” page.

  13. Layout[“X”] – like master page! (I wouldn’t say “like MasterPage” as it’s just a simple ol’ view, but it gives you a common markup frame for your views, in a similar way of a WebForms’ MasterPage)

  14. ViewComponent – like a custom control (without the dark magic of asp.net) but contains only UI rendering logic.

  15. component:CaptureFor -> we can use it to add javascripts, css files into the html header in the “master page”. (dude - It’s a Layout, not a MasterPage ;) )

  16. We can override the “default” render of the controls via sections in the markup (define sections will override it). (dude - It’s a component, not a control;) )

  17. Egozi uses prototype (pasha as well?) as ajax framework. For Ajax – call CancelLayout method and RenderView(“name_of_view”). This is called SubView and we use it in the markup with <subView:name_of_view />. (Actually I tend to use prototype as a Javascript enhancement, where needed. If only ‘ajax’ calls are needed, jQuery or YAHOO.connection would be a better lightweight solution)

  18. We can use the Cache attribute (MonoRail) over the controller method (aka “Action”) in order to avoid cacheability of urls (like Response.Exired = DateTime.Now.AddDays(-1) or something like this). (You can also use Response.Cache as before, the attribute makes our code nicer)

  19. We can use Filter for authentication – read about it a little. Each action on the controller will trigger this before running (or after).

  20. PropertyBag uses string, eleutian solved it with a smart code generator (pre-build). Create typed Flash and PropertyBag if implementing interfaces. Read about it (ask Egozi for link). (it’s in **Castle.Tools.CodeGenerator on CastleContrib, and also look at their blog. The tool actually is being used for typing of your site’s Controllers, Actions, and Views. As a side effect, they have created DictionaryAdapter than can do the IDictionary<->TypedObject thing.And yuu can also hand-type PropertyBag and Flash.)**

Thanks Oren.

Slides and Zips From MonoRail / AspView Talk

  

Ok. After some delay (couldn’t get Internet Connection at my mother in-law’s house), here are the links from my MonoRail / AspView talk:

  1. The slides (used the newly released StarOffice from Google Apps. Should show ok in Powerpoint)

  2. A zip file, containing AspView built against MonoRail from revision 4016 (build no. 472), including a skeleton web project (as shown on my talk), the minimal castle dll’s needed to run the skeleton project and links to Castle’s build server (to get the full castle libraries) and to my blog.

MonoRail / AspView Talk in IVCUG

  

I did that MonoRail / AspView talk yesterday at August’s IVCUG (that’s Israeli Visual C#/++ User Group) at Microsoft offices in Raanana, Israel.

I was a great experience for me, and I thank all of you who came in, asked questions, left some change in my hat (damn, I forgot the hat), and (hopefully) had a great time.

The presentation will be uploaded here soon, so will the demo code, and the promised zip with AspView executables for castle build 472 (revision 4016) + stub web.config. It’s just that I need to actually WORK today since the last days was more “prepare to presentation” that “work for a living” kinda days.

So, tune in. It would be by here this weekend.

Meanwhile you can go over aspview source code (there’s AspViewTestSite that demonstrate many of MonoRail and AspView features. It’s quite old and when I wrote it I was quite a MonoRail newbie, so stuff there are not necessarily best-practice quality, but you can grasp how to use subviews, viewcomponents, viewfilters, etc very easily).

http://svn.castleproject.org:8080/svn/castlecontrib/viewengines/aspview/trunk/

You can also look over my blog engine’s sources that I have presented yesterday. It’s at:

http://kenegozi-weblog.googlecode.com/svn/

The code shown was from going-ddd branch.

bad name btw, as the model is too simple for DDD, and I also violate it from time to time … (Repository<Comment> …)

MonoRail / AspView talk on August 15th

  

I’m going to give a talk about MonoRail (and AspView, of course), on the next C# UserGroup meeting, at Microsoft Israel offices in Raanana.

If you’re interested in a solid MVC implementation for web development, that leverages all the goodies of ASP.NET, without the complications of WebForms - this talk is for you.

I’ll brief over “what is MVC” , and then will demonstrate some of MonoRail’s features that can help you build web applications in a way that is easy, expressive, testable and fun. I’ll also demonstrate how to create a full MonoRail/AspView application from scratch, using trunk versions, as this is something that many people ask for on the Castledev and user lists, and on my email’s Inbox, too.

If you have any ideas/question about MonoRail or AspView, that you’d like me to address during that talk, please drop a comment here or to my email, and I’ll try to make room for that in my talk.

Admission is free, and you may attend without reserving a place.

However, the group admins kindly request that you notify them if you plan to attend so that they can be sure to have enough chairs and FOOD!

Contact them through the usergroup’s webpage.

See ya.

Checkbox Grids in MonoRail

  

Referring Jon Galloway’s post, here is my 5-minute-scracth-up-somthing that includes no hacking at all:

The Controller:

publicclassGourmetController : SmartDispatcherController
    {
        [AccessibleThrough(Verb.Get)]
        publicvoid WineMatch()
        {
            PropertyBag["matches"] = FoodAndWineMatchRepository.FindAll();
        }
        [AccessibleThrough(Verb.Post)]
        publicvoid Update([DataBind("matches")]FoodAndWineMatch[] matches)
        {
            FoodAndWineMatchRepository.UpdateAll(matches);
            RedirectToAction("WineMatch");
        }
    }

The View:

&lt;%@PageLanguage="C#"%&gt;
&lt;%@ImportNamespace="Gourmet"%&gt;
&lt;%
    FoodAndWineMatch[] matches;
%&gt;
&lt;%
    IDictionary @checked = DictHelper.CreateDict("checked='checked'");
%&gt;
&lt;formaction="Update.aspx"method="post"&gt;
&lt;table&gt;
&lt;tr&gt;
&lt;th&gt;Food Name&lt;/th&gt;
&lt;th&gt;Cabarnet&lt;/th&gt;
&lt;th&gt;Zinfandel&lt;/th&gt;
&lt;th&gt;Pinot&lt;/th&gt;
&lt;/tr&gt;
&lt;%int i = 0; %&gt;
&lt;%foreach (FoodAndWineMatch match in matches)  { %&gt;
&lt;tr&gt;
&lt;td&gt;
&lt;span&gt;&lt;%=match.FoodName%&gt;&lt;/span&gt;
&lt;inputtype="hidden"name="matches[<%=i%&gt;].FoodName"value="&lt;%=matches[i].FoodName%&gt;"/>
&lt;/td&gt;
&lt;td&gt;
&lt;%=FormHelper.CheckboxField("matches[" + i + "].MatchesCabarnet", matches[i].MatchesCabarnet?@checked:null)%&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;%=FormHelper.CheckboxField("matches[" + i + "].MatchesZinfandel", matches[i].MatchesZinfandel?@checked:null)%&gt;
&lt;/td&gt;
&lt;td&gt;
&lt;%=FormHelper.CheckboxField("matches[" + i + "].MatchesPinot", matches[i].MatchesPinot?@checked:null)%&gt;
&lt;/td&gt;
&lt;/tr&gt;&lt;%++i; } %&gt;
&lt;tr&gt;
&lt;tdcolspan="4"&gt;
&lt;inputtype="submit"value="Save"/&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;/form&gt;

And the mocked “domain objects”:

publicclassFoodAndWineMatch
    {
        privatestring foodName;
        privatebool matchesCabarnet;
        privatebool matchesPinot;
        privatebool matchesZinfandel;

        public FoodAndWineMatch() { }
        public FoodAndWineMatch(string foodName)
            :
            this(foodName, false, false, false) { }
        public FoodAndWineMatch(string foodName,
                                bool matchesCabarnet,
                                bool matchesPinot,
                                bool matchesZinfandel)
        {
            this.foodName = foodName;
            this.matchesCabarnet = matchesCabarnet;
            this.matchesZinfandel = matchesZinfandel;
        }

        publicstring FoodName
        {
            get { return foodName; }
            set { foodName = value; }
        }

        publicbool MatchesCabarnet
        {
            get { return matchesCabarnet; }
            set { matchesCabarnet = value; }
        }

        publicbool MatchesPinot
        {
            get { return matchesPinot; }
            set { matchesPinot = value; }
        }

        publicbool MatchesZinfandel
        {
            get { return matchesZinfandel; }
            set { matchesZinfandel = value; }
        }
    }
    publicstaticclassFoodAndWineMatchRepository
    {
        privatestaticFoodAndWineMatch[] _matches = null;
        publicstaticFoodAndWineMatch[] FindAll()
        {
            if (_matches == null)
                _matches = newFoodAndWineMatch[] {
                newFoodAndWineMatch("Salmon"),
                newFoodAndWineMatch("Steak"),
                newFoodAndWineMatch("Chicken"),
                newFoodAndWineMatch("Chocolate")
            };
            return _matches;
        }
        publicstaticvoid UpdateAll(FoodAndWineMatch[] matches)
        {
            _matches = matches;
        }
    }

No hacking needed. Controller code is short and intuitive.

Oh. No postback for every client click …

I especiallyliked one of the comments on Jon’s post:

I love ASP.NET because of tricks like this that the developer can use.

Well, Ido not likeWebForms because it makes me “do tricks” (or hack) instead of bringing business value.

So I do not mean that Jon’s “hack” is bad. That’s what you have to do when you’re WebForm-ing. I just say that there are other web development frameworks (actually, all but WebForms) that are more suited for reasonable html generation and for dealing with the http protocol.

Redirecting syndication link from dasBlog's one to the new one

  

TodayI was informed by Dror that although I managed to redirect all requests to html/aspx url’s on my blog (the ones that dagBlog was using) to the new pemalink format, I forgot to do the same for the old syndication link.

So that link was http://kenegozi.com/blog/SyndicationService.asmx/GetRssand now it’s http://kenegozi.com/Blog/Syndication/Atom.aspx

I could’ve used the monorai redirection module that is already in use on my blog, but I chose to do it differently, with a dedicated handler, just to show how easy it is do to such stuff, even without a full blown redirection engine.

So, I’ve added this:

publicclassSyndicationRedirectionHandler : IHttpHandler 
{
    #region IHttpHandler Members
    publicbool IsReusable
    {
        get { returntrue;}
    }

    publicvoid ProcessRequest(HttpContext context)
    {
        context.Response.StatusCode = 301;
        context.Response.Redirect("http://kenegozi.com/Blog/Syndication/Atom.aspx");
    }

    #endregion
}

and that line into web.config:

<addverb=”*“path=”SyndicationService.asmx”type=”KenEgozi.Com.Weblog.SyndicationRedirectionHandler, KenEgozi.Com.Weblog”/>

Voila.

Regionerate - c# region maker

  

Check out this nice tool from Omer Rauchwerger.

It could help a team to manage a coding convention. Should be very useful in Open Source environments. For example, when committing changes to castle project (or sending a patch) there is a coding standard than needs to be followed. Regionerate could help a lot with that effort.

I need to see if it can select methods and properties by attributes. It could then help making MonoRail controllers and ActiveRecord decorated classes more readable (region of all actions with a “SkipFilterAttribute”, region of “Property” and region of “HasMany”, etc.)

UPDATE:

Silly me, I forgot to mention that I found about this great tool at Roy Osherov’s blog. A very good one, that is. Many Agile related stuff, and funny little things, too. So go on and subscribe to it’s feed.

The daily quote: "the single best thing any ASP.NET developer can learn right now is MonoRail"

  

taken from Karl Seguin post about his .net wishlist:

Thinking beyond the common request to implement an MVC pattern, I’d be great if the ASP.NET team could rethink the current model and life cycle. It leaks badly in any complicated scenario. 6 years after its release, I still don’t fully understand it, and I’m ready to bet that I’m in the overwhelming majority. The only time it doesn’t leak is when you don’t need any of the fancy stuff it tries to do. I’m almost at the point where I just don’t use .NET if I’m building a heavy web-based application. Forget learning an O/R mapper, test driven development or understanding domain driven development, the single best thing any ASP.NET developer can learn right now is MonoRail.

Could not agree more …

AspView - a little bugfix

  

If you are an AspView user you might have noticed a problem.

If you setup a nullable-value-type parameter with a default value other than null, then you’d get a casting error.

example:

&lt;%
 int? someInt = default(int);%&gt;
some markup 
&lt;% if (someInt == default(int)) DoSomething();%&gt;

it happened because of the way GetParameter worked

GetParameter is a method that gets a view parameter value from the view’s properties collection (PropertyBag, Flash, Request.Params, etc.). It’s located inthe AspViewBase class (the base class for each and every view in the AspView world).

So, now it’s fixed, and a test was added to make sure it’ll stay that way.

As soon as google.com will be accesible again, you’d be able to check out and build.

UPDATE:

I’m too tired (3am here). The sources are on castle contrib and not on google, so you’d find them here

Default value for value type parameter in AspView does not work

  

Today we tried to have this in a view’s parameters section:

<%

int id = default(int);

%>

It won’t work.

Internally, AspView looks for a parameter (in the PropertyBag, Flash, Form, QueryString etc.) with the name “id”.

Now if it is not found, it should set to “default(int)”. The problem is duw to a bug in AspViewBase (which is the base class for all views) that sets a null value if the property is not found, thus failing the cast to value type (you cannot (int)null).

I’ll add a test, fix the bug, and commit it, hopefully by this weekend.

Meanwhile, we “solved” the problem by using:

<%

object id = default(int);

%>

Full blog comments feed

  

The newest addition to the blog engine.

From the subversion commit comment:

Some refactoring to avoid code duplicationAdded support for CommentsAtom - a feed with all of the comments in a blog, used for tracking purposes by the blog writer

Now you can access http://the_blog_url/Syndication/CommentsAtom.aspx and get a feed of all the comments.

Useful as a tool for the blog writer, as it enables tracking of comments all overthe blog

as usual - sources are here.

Castle build from the trunk - revision 3812

  

From Castle Project users group:

I’ve just built the trunk yesterday (rev 3812).

Main reason: I needed the BaseControllerTest from Castle.MonoRail.TestSupport.

The build was targeting .NET 2.0, in release, and no tests were run.

You can download it from: http://kenegozi.com/Castle_r3812_net-2.0_release_not_tested.zipNote that it is not tested, so use it at your own risk. If you’re not going production this week, it should not be a problem …

NANT 0.85 rc3 and .NET 2.0

  

I needed to manually Castle today, for the first time.

The need is for Castle.MonoRail.TestSupport.BaseControllerTest only, so I do not really care about all the rest.

Opened “How to build.txt”

I know that the builds in the CI server are failing due to some filing tests on DP2, so I add “-D:common.run-tests=false”.

no brainer.

I am also targeting .net2 only, so I add “-t:net-2.0”

baboom. This fails.

The nant exe is telling me that I can only build to .net 1.1, or .net compact framework 1.0.

So I went to nant’s config file, and found out to my surprise, that the frameworks that are present there are:

.net 1.1,

.net compact framework 1.0

.net 2.0 BETA 1

hmmm.

So I’ve edited the config, changed the existing .net 2.0 config name to .net2.0Beta1,

copy&pasted the .net node to another one, now switching version number from

sdkdirectory=”${path::combine(sdkInstallRoot, ‘bin’)}” frameworkdirectory=”${path::combine(installRoot, ‘v2.0.40607’)}” frameworkassemblydirectory=”${path::combine(installRoot, ‘v2.0.40607’)}”clrversion=”2.0.40607”

to

sdkdirectory=”${path::combine(sdkInstallRoot, ‘bin’)}” frameworkdirectory=”${path::combine(installRoot, ‘v2.0.50727’)}” frameworkassemblydirectory=”${path::combine(installRoot, ‘v2.0.50727’)}”clrversion=”2.0.50727”

voila. Now the build is starting.
However, the Castle.Components.Validator.Tests dll refuse to build. I’ll disable it, too.

UPDATE:

I’m an idiot. Did not notice that NAnt has gone far beyond rc3 a long time ago …

sync.marketwatch.com - Another MonoRail powered site

  

They just keep on coming …

http://sync.marketwatch.com

New feature to the blog - a blogroll

  

just added a blogroll.

To the DB, to the Domain, to the controller and to the view.

Took me (all in all) 30 minutes, including all the coding, CSS-ing, uploading to the webserver, setting up the DB table on the hosted server, adding a few entries, clearing the browser’s cache, and viewing it.

ah, and committing changes to Google code.

All of that was made in the Budapest Airport cafeteria, while waiting for my flight home (was a great trip. Photos, though not many of them, will be posted later on).

Rest assure that the DB access code is tested, and that the calls to the DB and to the cached data from the Controller and View are all typed.

I’d like to thank NHibernate, Castle and AspView (hey - that’s me !), who made this possible.

I bet Ayende would have done it in 20 …

Real world AspView powered sites

  

I’ve just noticed two sites that uses AspView vienegine (of course they’re on MonoRail)

The first, https://www.musicglue.com/, has the static “home-page” stuff being served from a standard webforms aspx files. The Signup Procees however, and other applicative parts are using MonoRail, with AspView based views. The team behind this site said to me that they’re moving to a complete MonoRail/AspView solution in time.

The other, http://www.escapegreat.com/, is using AspView, top to bottom.

Both sites seam to be working great.

Gives me strength to continue the development on AspView, and find ways to improve it even better.

A new version of AspView - 0.7

  

I’ve just commited to the repository a new version of AspView.

The main addition is “Auto Recompilation” feature.

This means that when you change one of the view sources, the application will automatically recompile the views upon the following request.

You enable the feature by adding the next attribure to the aspview config section in web.config:

&lt;aspview .... autoRecompilation="true" ... &gt; ...&lt;/aspview&gt;

Breaking change:

If you happen to reference an assembly from the GAC (using the aspview configuration in the web.config) you need to add a hint for the engine, like this:

&lt;reference assembly="MyAssemblyFromGAC.dll" isFromGac="true" /&gt;

Known issues:

  1. You need to let ASPNET user (or the Application Pool user) a modify access on the bin folder.Note that if you use the inner WebServer of Visual Studio this should not be a problem, since in that case the web application runs with your user, that has the needed peremissions on the bin folder.

  2. For a strange reason, after you change a view and do the F5 in the browser, you still see the old version, and only on second F5 will the views be actually recompiled and refreshed. I hope to fix it soon …

Download from here.

Sources are here.

My blog is running on ActiveRecord-MonoRail-AspView

  

So long dasBlog. It was great to have you, but it’s time to move on.

After a lot of work, I am proud to announce that my blog is running on MonoRail, using AspView for the views, and ActiveRecord to do DB stuff.

Not too fancy codewise, since I have very little spare time.

Most of the time spent on the blog upgrade process was on:

  1. Exporting the data from the “old” blog, and

  2. making a decent markup and design for the new one.

oh. and 3. letting WindowsLiveWriter do the edits, since I wasn’t in the mood to create a backoffice.

I’ll blog more about the process, and I’ll make the source available.

Please leave your comments here about the overall look’n’feel. There must be tons of bugs and I want your feedback.

Ruby.NET integration in Visual Studio, plus debugging support

  

I’ve just got the announcement from the Ruby.NET team at QUT, about the new beta release, numbered 0.7.

The two major things in there:

  1. the compiler now creates pdb files, which means that it can be debugged with the interactive debuggers,

  2. Visual Studio 2005 integration, including Ruby projects.

Can’t wait to check this out.

I’d like to see if I can do some integration into the AspView project, to enable a RubyOnMonoRail thing. I guess it’d have to wait for the BCL integration, promised to be released around the end of this year, but it is quite interesting as it is right now.

MonoRail is gaining interest

  

I’d like to point you to a new podcast from HanselMinutes, about MonoRail. Scott Hanselman is interviewing a couple of guys from Eluetian as MonoRail Power Users. Theyare doing a lot of workwith MonoRail using Brail.

Listen to that if you want to hear about how simple MVC for ASP.NET can be.

Actually, It seams that it is getting so much attention, that even MSFT are thinking about implementing something Rails-i in the future ASP.NET. Read this if you do not believe me.

AspView 0.6 is out

  

What’s new?

  1. Support for ViewComponents, including those with Sections. It is tested against CaptureFor, and GridComponent.

  2. You can now specify saveFiles=”true” in the config, and the compiler will leave the .cs files generated from the views to the disk, so you can match compilation errors from Visual Studio directly to the view’s concrete class source.

The syntax for the ViewComponents is xml-like: just add

&lt;component:VIEWCOMPONENTNAMEARGUMENTS&gt;&lt;section:SECTIONNAME&gt;&lt;/section:SECTIONNAME&gt;Some content  &lt;/component:VIEWCOMPONENTNAME&gt;

where VIEWCOMPONENTNAME is the component’s class name, SECTIONNAME is the section name, for components that uses sections, and the ARGUMENTS are xml-attributes, for example: id=”capturedContent” myData=”<%=items %>”

examples (from the test site):

for constant arguments:

&lt;component:CaptureForid="capturedContent"&gt;   This content should be rendered in the captured-for place holder  &lt;/component:CaptureFor&gt;

for variable arguments:

&lt;component:GridComponentsource="<%=items%&gt;">    &lt;section:header&gt;&lt;table&gt;&lt;thead&gt;&lt;th&gt;Id&lt;/th&gt;&lt;th&gt;Word&lt;/th&gt;&lt;/thead&gt;&lt;/section:header&gt;&lt;section:item&gt;&lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;&lt;%=item %&gt; &lt;/td&gt;&lt;/tr&gt;&lt;/section:item&gt;&lt;section:footer&gt;&lt;/table&gt;&lt;/section:footer&gt;&lt;/component:GridComponent&gt;

As usual, source code is at http://svn.castleproject.org:8080/svn/castlecontrib/viewengines/aspview/trunk/,

Note that for a successful build you’d need to fix the siteRoot parameter in vcompils’s app.config, to point to the actual physical path to the test site’s root

Long time no posting. Must write.

  

I haven’t written much lately, since I was:

a. Learning for my final exam so I’d get my Bachelor’s Degree at this decade.b. Under a lot of preassure at work, since we have a cool web2.0 thingie approaching a public beta real soon (will be followed).c.Sneasing my heart out, darn flew.d.Got into a new project at my personal business. This one is driven by Castle’s ActiveRecord+MonoRail+AspView, and due to the client’s request it’ll use Access as the backend DB, and that would be a first-time-ActiveRecord/access for me. I still hope to convince him to at-least go for embedded FireBird.

So, stay tuned to some experiences with AspView, and hopefully in about a month you’ll havetwo MonoRail/AspView driven websites out in the open. I am excited. Are you?

Introducing ViewFilters

  

Here is the latest addition to AspView.

example:

&lt;%@PageLanguage="C#"Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime"%&gt;  &lt;%  %&gt;  Outside the filter  &lt;filter:LowerCase&gt;Inside the LowerCaseViewFilter - this text should be viewed in lower case&lt;/filter:LowerCase&gt;  Outside the filter AGain  &lt;filter:UpperCase&gt;  Inside the UpperCaseViewFilter - this text should be viewed in upper case  &lt;/filter:UpperCase&gt;  Finally - outside the filter

As you can see, the syntax is simple. Given a viewFilter, named “MyViewFilter”, you use the xml tag <filter:my> or <filter:myViewFilter>. The viewfilter itself has to be suffixed with “ViewFilter” (Just like Controllers are suffixed with “Controller”, etc.), and it has to implement IViewFilter which is defined with:

using System;using System.Collections.Generic;  using System.Text;    namespace Castle.MonoRail.Views.AspView  {publicinterfaceIViewFilter     {string ApplyOn(string input);         }}  

The power of the ViewFilters is than they can apply to a whole SubView, while the subview is rendered as a black box, the filter does the work AFTER the subview was rendered.

Grab the sources, play, and have fun.

AspView has entered CastleContrib

  

After hammet’s approval, I hav finallyadded AspView source to the Castle Project’s Contrib section of the subversion repository.

Thank hammet and the rest of the Castle crew for voting for that.

So from now on, you’d be able to grab the sources from http://svn.castleproject.org:8080/svn/castlecontrib/viewengines/aspview/

Two last comments:1.The latest edition works with Castle’s trunk from build 229.2. The latest additions are supporting “~” as a macro for siteRoot, and “~~” as a fullSiteRoot (~ would expand to the virtual directory, and ~~ would expand to full url- http://…).

Some improvements in AspView - revision 47 is out

  

What’s new?

  1. siteRoot has been added to AspViewBase, so you can ditch the “string siteRoot” from the declerations area.

  2. Some permormance improvements. Instead of using “Activator.CreateInstance” everytime a view is to be rendered, a hashtable with ConstructorInfo objects is generated upon reading CompiledViews.dll. This was taken from the c# version of Brail

  3. A new syntax for subviews:

you can use

   1:  &lt;subView:MyMenu item="menuItem"&gt;&lt;/subView:MyMenu&gt;

instead of

   1:  &lt;% OutputSubView("MyMenu", Helper.Dict("item", "menuItem")); %&gt;

take note the <subView:Blah /> is not currently allowed. I’ll fix it shortly.

the link is here

Things I've been doing lately

  

I’ve been off the radar lately, due to some extensive work I do on a website for my employer.

It is still in early stages and I cannot talk about the site itself, but I can talk a little about the technology that drives it.

In one word: Castle.

In a few more words:

Data Access and OR/m: Castle’s ActiveRecord over NHibernate

Web UI Engine: Castle’s MonoRail

ViewEngine: AspView (by yours truely, inspired by Ayende’s Brail). All my spare time from work goes there.

Client Side Javascript stuff: Prototype and Scriptaculous.

I really believe in the efforts made by Castle group, and I hope the the site I’m working on will be successful, as to serve for yet another prove of concept.

One more thing I’m doing last month, is that I’ve decided to finally end the thing with my Bachelor’s degree. I needed to retake Linear Algebra I (yep, that one the all the non-bullet-time Matrixes … I H-A-T-E adjoined matrixes. yuck) so that’s actually why AspView doesn’t progress as I’d want it too (and as some of my readers want, too).

AspView rev 38 is out

  

What we have:

  1. Default Helpers are now declared in the AspViewBase. It means that you can use <%=FormHelper.LabelFor(…) %> without the need to declare the helper at the begining of the view.

  2. the compiler was refactored to allow for better testing, and for implementation of further view languages. vurrently I’ve started with VB.NET but it is not working yet, since I have no time to make sure the VB syntax is correct. The tests of the compiler are missing due to some stupidity on my side, of not commiting the TestCase …

I’ve wanted to let svn access but I have some trouble with that. I’ve started a sourceforge project but I cannot upload the repo to the site. I did all they’ve asked on the site but the import process reporting failure no matter what I do. I guess that the best way will be if the Castle team would allow AspView into it’s codebase, maybe on the Contrib repo to begin with …

So meanwhile you can download the current bits from here.

Keep me posted,

Ken.

Hammet likes AspView

  

Just read it.

I started commenting to that post, but I figured that the people who’ve downloaded AspView up to now (I have about 30 or so downloads last week) will want to read it, so I’m posting it here.

So, as Hammet said, the extension is determined on the web.config. The .aspx is used for the view source files so VSNET will color and intellisense them. however, the actions are mapped to an extension that is mapped in the web.config.Still, AspView have some .aspx hard-coded in it, simply cuz I needed to get something working, and working fast. This is why I’ve left non-crucial features out for the moment, such as:1. Dynamic compilation (It is non crucial. IMHO real applications should be pre-compiled, while the dynamic thingie is for design time only)2. Nicer code (more maintainable, less typos such as “extention”, refactoring for testability).3. View Components (subviews are doing the trick for me for now, but in order to mature there must be implementation for it) 4. using the .config. 5. A lot more

btw, helpers ARE supported, You just need to add the declaration in the place, like

<% Post[] posts;AjaxHelper AjaxHelper;AjaxHelper AjaxHelper;%>

In the trunk there is some improvements, such as refactored AspViewCompiler, so it uses a PreProcessor that has subtypes. Currently it has a working CSharpPreProcessor, and a non-working VbPreProcessor. I intend to try adding a BrailPreProcessor … I hope to be able to mix view languages in the same site. each language group will be compiled to a module, and linked to the CompiledViews.dll assembly.

Since I haven’t set any public repository yet, and since I do not have much time for uploading bits manually, you cannot see the work in progress, and it’s my bad. I’ll upload the latest stuff soon, and I’m working on setting up a repo somewhere. btw - do you have recommendation? (CodePlex? Sf? )

AspView - first release

  

So I’m releasing AspView.

You can download the source from here.

It was written against the Castle 1.1 from the trunk, build no. 152.

Please note that in order to run the TestCases you’d have to make sure that the latest Castle.MonoRail.TestSupport is in the GAC.

The documentation is poor since I have a little time now. I am working on a website for my employer (that utilizes AspView and AR) and until the first beta release I won’t have time to do anything but major bugfixes. This project isn’t open sourced so I won’t be able to share it’s sources, however since this will be a public site, it would serve as a Proof Of Concept to the MonoRail and AspView.

The views MUST have the following structure: a. Page header - Must be present for intellisense to work:

   1:  &lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime"%&gt;

b. Directives - Not mandatory:

   1:  &lt;%@ Import Namespace="System.Text"%&gt;   2:  &lt;%@ Import Namespace="System.Drawing"%&gt;

c. Properties decleration - Currently it’s mandatory. If you have no properties you mast have an empty block:

   1:  &lt;%   2:  string[] strings;   3:      DateTime today;   4:  int index;   5:  %&gt;

or just

   1:  &lt;%   2:  %&gt;

d. View body

In a layout view you place the inner view using the ViewContents property, like this:

   1:  blah   2:  blah   3:  &lt;%=ViewContents%&gt;   4:  blah   5:  blah

AspView - Yet another MonoRail ViewEngine

  

.hlt { background-color:yellow;}
So what is AspView?

It is a Visual Studio 2005 friendly ViewEngine implementation.

The scripting is done using VisualStudio languages (c# and VB.NET). The views are precompiled, (or can be compiled on-demand, but anyway not interpreted).

The project was inspired by the Brail ViewEngine, but since it doesn’t use Boo it is more Management-Friendly, since they need not worry about getting out of the “safe” microsoft world.

I tend to like Boo as a language very much, and I like Brail a lot, too (since it allows for less code in the view thanks to the Boo magic) but I lack the tight Visual Studio integration (opening .boo files in #Develop messes up my desktop), and the intellisense is quite important, at least for the developers I worl with.

So I will post in the next few days about it, and I’ll make it available to be downloaded (source and binary) as soon as I’ll test it a little more. I hope to have a public svn repository soon.

A little demo view:

   1:  &lt;%@ Page Language="C#" Inherits="Castle.MonoRail.Views.AspView.ViewAtDesignTime"%&gt;   2:  &lt;%   3:  string[] strings;   4:  %&gt;   5:     6:     7:  hello from index&lt;br /&gt;   8:  This are the strings:&lt;br /&gt;   9:  &lt;%foreach (string s in strings) { %&gt;  10:  &lt;%=s %&gt;&lt;br /&gt;  11:  &lt;%  } %&gt;  12:    13:  &lt;br /&gt;  14:  End of normal view  15:  &lt;br /&gt;  16:  &lt;% OutputSubView("Home/SubViewSample"); %&gt;

Building Application using Castle RC2

  

Ayende has recently posted a walkthrough for building Web Apps using the Castle Project’s libraries.

He covers ActiveRecord and MonoRail basics, showing off some of the shiny and new abilities (AR scaffolding, ARSmartDispatchers, Generics integration and so on).

The only thing missing is IoC-ing using Winsdor or even Binsdor. Maybe to hook some BL layer or something.

So it concludes (as of now) a Part I, Part II , and source-code.

If you wanna see a decent web development framework at action - tune up to those posts.

MonoRail vs. WebForms

  

Ayende has posted about the matter, only he’ve used the title “MonoRail vs. ASP.NET” instead. I think that his title isn’t accurate since MonoRail is actually a WebForms replacement that is built ontop of ASP.NET, exploiting all of the cool features found in ASP.NET and in the .NET framework alltogether. It’s the Web development framework that Microsoft forgot. So it has the benefits of the Rails interpretaion for MVC, with the power of .NET.

Here is the comment I’ve posted to Ayende’s post:

“My point of argue in favor of MR for people who are afraid of “non-microsoft” is, that actually MR is ASP.NET. It is just not WebForms. You get all the good stuff from ASP.NET: the .NET framework for start, compiled views (on Brail - kudos to you), the HttpModule stuff, seeamless integration with AR. This is what I say to the PMs, etc. To the developers themselves who are afraid, There’s a more detailed approach. Developers (especially ones who didn’t do web programming aside ASP.NET, and probably has a lot of VB experience but no PHP/JSP/ASP) like WebForms cuz they can get to the txtUsername.Text, txtPassword.Text, and txtAge.Text easily, not needing Request.Form[“Password”] (hey - it’s not typed !!!) . But then I reffer them to the fact that actually txtAge.Text isn’t typed too. it’s a string, and should be parsed, tried, validated etc. They should also manually create a User instance, and fill it’s properties. Doing the same on MR with Dispatching and AR is there without any line of code. I show them an example aqnd then hold them as they almost fall off their chairs. Not’n like a good example. Maybe having a ViewEngine that’s use c# or VB.NET instead of boo (not the WebForm ViewEngine which suck, but somthing similar to Brail) can make the move from WebForms to easier for developers, but frankly, as you’ve said, people who can’t get it OJT with a few examples aren’t the one’s I’m likely to work with anyway.”

ASP.NET Ajax (aka ATLAS) is maturing and reached Beta 1 stage

  

As said in the title, ASP.NET Ajax (aka ATLAS) is maturing and reached Beta 1 stage.

I haven’t being too mush into it lately, since I’ve beenunder the impression that though Microsoft’s ASP.NET Ajax library was very rich and had many features, it also suffered from many childhood problems, including too many js errors, and a huge .js script to download.

Now, it has an official name, and a beta release, and it’s maturing. The .js was split by functionality, release and debug version of the .js are present, prototyped classes have replaced the closure based ones, and it’s better for me cuz I find it easier to overload behaviuors when needed.

So try it outand read what Scott Guthrie has to say about it.

Since nowadays I’m more into MonoRail over Brail than into Webforms, I guess that the Core package is what really intresting for me, and I’ll try to combine it with AjaxHelper from MonoRail. I hope to report on the matter shotrly.

Allowing XHTML tags intellisense in Monorail documents

  

PROBLEM:When editing Monorail views, you are losing the XHTML intellisense that normal webforms have in Visual Studio.

SOLUTION:Add a proper xmlns to the html tag.My layouts start with this:

   1:  &lt;?brail 
   2:      output '<'
   3:      output '?xml version="1.0" encoding="utf-8"?'
   4:      output '&gt;'
   5:  ?>
   6:  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
   7:  &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="he-il" lang="he" &gt;

This applies to brail, but can of course be used on any other view engine, with the needed adjustments.

Lines 1-5 is needed due to a bug(?) in some versions of brail. brail used to recognize a script by ‘<? ?>’, ‘<?brail ?>’ and ‘<% %>’ signs. therefore, using a <?xml ?> declaration caused the boo compiler to say that he knows nothing about ‘xml’. I think that Ayende has solved the problem now, by allowing only ‘<?brail ?>’, but I think it’s not yet on the main trunk, so I still use the listed method.

Line 6 is the DOCTYPE, I use XHTML 1.0 transitional.

Line 7 is the magic part. Visual Studio parses this line, reads the xmlns, and can hint you with intellisense forhtml tags and attributes. The xml:lang and lang attributes are of course changeable.

It works in layouts, or in views that are a full html document (with <html> tag) but not with VieComponents or views that uses layouts.

If someone has a way to do that, please share it.

My presentation layer of choice: Brail over Castle's MonoRail

  

I’ve evaluated some methods to rail and to MVC in the .NET world, without using webforms.

The first method I tried was to treat aspx’s kind’a like old ASP, no server controls, allowing multiple forms, no __VIEWSTATE __EVANTVALIDATION __UGLYHIDDENFIELD in the generated markup, and calling actions on the server, implemented as Controllers over ashx’s, or directly linking to a new .aspx view (if no operation is required).It allowed me to create super clean html, but it has it’s limits, since I’ve had to implement a mechanism for MasterPages and UserControls, and that suck.There is BooWebness. Seams like a great effort, and I like the natural .ashx approach, but I am not very into its whole framework there.

Then I’ve went after MonoRail.Cool.Has a lot out-of-the-box, including MasterPages(Layouts), UserControls(ViewComponents), Markup Helpers, AjaxHelpers, and a large community. Being part of Castle is a Big Bonus. I believe in Castle. I’ve been using Castle’s ActiveRecord for a while and I find it almost too good to be true. So MonoRail fits well in Castle’s world, so I’m into it.

Now I needed to choose a view engine.NVelovity was disqualified for its discontinuesness, and the need to learn something new and narrow. Not to mention the fact that it’s interpreted.The WebForms hybrid just doesn’t look too good.Brail from Ayende is very nice. Learning Boo isn’t like learning a new thing, since I’ve had a little taste of it in the past, and since it’s .NET, and since it has a very readable syntax that any C#/VB.NET/Python/Perl/java/you-name-it developer can learn in minutes. Brail is a lovely name, and I can count on Ayende to keep developing it as much as it’s needed.

So Brail over MonoRail it is.

Posts about the matter will come shortly.

HtmlHelper vs. html tags

  

Should I use HtmlHelper?

take a look at this: ${HtmlHelper.Form(‘/Home/Search.rails’)} ${HtmlHelper.LabelFor(‘q’,’search:’)} ${HtmlHelper.InputText(‘q’, ‘’, 50, 50)} ${HtmlHelper.SubmitButton(‘Search’)} ${HtmlHelper.EndForm()} and that: <form method=”post” action=”Home/Search.rails”><label for=”q”>Search:</label><input type=”text” name=”q” /><input type=”submit” value=”Search” /></form> Okay. So AjaxHelper is cool, and maybe FormHelper will have someAdded Value in it, but I cannot figure out yet the benefits of using HtmlHelper, especially for non-data elements, such as <label>

If you have a good reason to use HtmlHelper, please enlight my.

Brail and xml-ing the markup

  

I like XHTML more than I like HTML.

But IE doesn’t think so.

He needs the markup to be very explicit about the web page being xhtml.

.xhtml isn’t enough, and even not Doctype-ing.

No. he must have the optional <?xml version=”1.0” ?>.

So I’ve added it to my Layout.boo file.

Boo? Boom. Boo marks macros (such as <?brail ?>) with <? ?> blocks, and Boo doesn’t recognize a macro with the name xml.

My current solution is to write: <?brail output ‘<’ output ‘?xml version=”1.0” ?’output ‘>’ ?> I guess that adding a dummy xml macro would make the boo templates look nicer, but it is an ugly solution, and since (ugly & nice != nice), we need a better solution.

Maybe a change in Brail (on BrailPreProcessor.boo), to transform <?xml … ?> stuff to it’s “output” equiv, can be done.


Follow @kenegozi