Thinking about the new preview of MVC…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

So obviously this is related to actions on a controller returning a value instead of being a void.

As mentioned by ScottGu in his latest blog post on the changes in the next preview of MVC:
http://weblogs.asp.net/scottgu/archive/2008/04/16/asp-net-mvc-source-refresh-preview.aspx

Now generally I have a split opinion on this… from one side it really does seem like a great idea, but from other side somehow it just doesn’t feel right (don’t ask me why… it just doesn’t).

So I’ve been thinking that maybe it’s related to the way it’s written, it’s not that readable (IMHO). So without too much thinking (just throwing an idea out)… what do you think of something like this:

public class HomeController : Controller {

    public ActionResult Index() {

        ValueOfViewData["Title"] = “title”;

        return toView();

    }

    public ActionResult About() {

        return toAction(”Index”);

    }

}

so just trying to express ourselves a little better (method names above are not that good, but should prove a point)?

Cheers!

 


Filed under: ASP.NET MVC
Written on: 18 Apr 2008 · No Comments »

Last nights user group in Zadar…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

So, last night together with Tonci Kaleb, a colleague Siniša Dolinac and my ex. boss Tonci Vatavuk I’ve went to Zadar to the user group.

There I’ve held a presentation on the new ASP.NET MVC framework, while Tonci Kaleb talked about Smart Cards.

The meeting was great, I was pleased to see 10-15 people gather around for the user group in a smaller town like Zadar and we’ve talked from 17:30 well to 20:00 PM.

As promised here my materials are already published on my newfound code repository on google:

http://vladanstrigonet.googlecode.com

or you can access the presentation and materials directly via SVN from:

http://vladanstrigonet.googlecode.com/svn/presentations/aspnetmvc

(hint: download TortoiseSVN and use it to download from the Repository)

If you have any questions, don’t hesitate to ask.

Cheers!


Filed under: ASP.NET MVC, Presentations
Written on: 19 Jan 2008 · No Comments »

In Zadar this Friday? Visit SQL&Developers user group

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3 out of 5)
Loading ... Loading ...

As you might know from my previous posts I am hyped up about ASP.NET MVC. Naturally when I got the chance to talk about it, I took it hands on and am preparing a session for the user group which will be held this Friday.

Here is the session title and announcement in Croatian as published on the user groups website:

“…5. MS Community SQL/DEV okupljanje u Zadru

Pozivamo vas na 5. skup MS Community SQL & Developers User Group u Zadru.
Hrvatska udruga programera (HUPRO) u suradnji s Microsoft Hrvatska organizira skup SQL & Developers grupe korisnika u Zadru.

PETAK, 18.01.2008, 17:15

u informatičkoj učionici Sveučilišta u Zadru, Petra Svačića 9. (1. kat, zgrada bivšeg studentskog doma na Relji.)

Raspored događanja:


17:00 - 17:15 Dolazak i registracija sudionika

17:15 - 17:30 Uvodna riječ
Neven Pintarić i Niko Vrdoljak

17:30 - 18:15 Uvod u ASP.NET Model-View-Controller (MVC) Framework
Jedna od prednosti korištenja MVC metodologije jest pravilno odvajanje uloga pojedinih dijelova koda u aplikacijama. Kako će u bliskoj budućnosti i ASP.NET kao platforma imati mogućnost izrade aplikacija prema MVC arhitekturi kroz ovo predavanje nam je cilj pokazati vam osnove rada s tim frameworkom, kao i mogućnosti koje isti donosi već danas.Također ćemo vam usmjeriti pozornost na drugi važan cilj koji ispunjava novi Framework - testabilnost vaših aplikacija. Pokazati ćemo vam kako napokon ASP.NET dobiva mogućnost pravilnog verificiranja zahtjeva klijenta kroz automatizirane testove pišući iste kroz Test-Driven-Development način razvoja.

Vladan Strigo, Microsoft MVP, Netmedia

18:15 - 18:45 Pizza, pivo, sokovi, grickalice…

18:45 - 19:30 Pametne kartice
Danas sve više uređaja nosi epitet pametni - tako imamo pametne mobilne telefone, pametne automobile, pametne frižidere…
Kako mogu biti pametne plastične kartice? Kako se očituje ta njihova pamet?
Koristimo ih u mobilnoj telefoniji, bankarstvu, trgovini, zdravstvu, transportu, za ulazak u firmu, za gledanje satelitskih programa. Impozantan popis za tako malu stvar koja stane u svaki džep ili novčanik.
Predavanje će vam predstaviti pametne kartice.

Tonči Kaleb
, Splitska banka

19:30 - 20:00 Debate, prijedlozi i završna riječ
Iskoristite priliku i prijavite se ako želite održati predavanje/prezentaciju nekog svog rješenja.Ulaz je slobodan!
Molimo Vas da potvrdite svoj dolazak radi ograničenog broja mjesta na email: sqldevugzd@hotmail.com
Više o aktivnostima i djelovanju MS Community SQL/DEV zajednice možete pronaći na http://www.mscommunity.net…”

After the session the materials will be posted to the blog - both the presentation and the sample application I am working on.

Join us if you are near, I am sure it will be a blast!

Cheers!


Filed under: ASP.NET MVC, Presentations
Written on: 14 Jan 2008 · No Comments »

BDD and ASP.NET MVC… a match made in heaven

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

Whilst preparing for my user group session on MVC I’ve upgraded my BDD base class (actually subclassed it) with specifics related to specifying the behavior of MVC routes and controllers.

I’ve made for starters 2 new classes:

public class MvcMockedHttpContext
{
    private readonly MockRepository _mocks;
    private IHttpContext _context;          

    public MvcMockedHttpContext(MockRepository mocks)
    {
        _mocks = mocks;
    }          

    private void _CreateMocked()
    {
        _context = _mocks.DynamicMock<IHttpContext>();          

        SetupResult.For(_context.Request)
		.Return(_mocks.DynamicMock<IHttpRequest>());
        SetupResult.For(_context.Response)
		.Return(_mocks.DynamicMock<IHttpResponse>());
        SetupResult.For(_context.Session)
		.Return(_mocks.DynamicMock<IHttpSessionState>());
        SetupResult.For(_context.Server)
		.Return(_mocks.DynamicMock<IHttpServerUtility>());          

        _mocks.Replay(_context);
    }          

    public IHttpContext ReturnMocked
    {
        get
        {
            if (_context == null) _CreateMocked();          

            return _context;
        }
    }
    public MvcMockedHttpContext FakeoutUrlRequest(string url)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.AppRelativeCurrentExecutionFilePath)
                        .Return(url);
        SetupResult.For(_context.Request.PathInfo)
                        .Return(string.Empty);          

        return this;
    }
    public MvcMockedHttpContext FakeoutApplicationPath(string path)
    {
        if (_context == null) _CreateMocked();          

        SetupResult.For(_context.Request.ApplicationPath).Return(path);          

        return this;
    }          

}

Which I use to mock out the HttpRequest quickly and it serves me as a small mock out DSL for often used tasks with mocking the HttpRequest

Second part is the upgraded specification class:

public class MvcContextSpecification : ContextSpecification
{
    public MvcMockedHttpContext HttpContext
        {
            get
            {
                MvcMockedHttpContext context = new MvcMockedHttpContext(Mocks);
                return context;
            }
        }          

    public TController
                  CreateTestableControllerOf<TController>
                                                (string routeDataController,
                                                 string routeDataAction,
                                                 params object[]
                                                        paramsForControllerConstructor)
        where TController : Controller
    {
        TController controller =
                            CreateMockOf<TController>(paramsForControllerConstructor);          

        RouteData routeData = new RouteData();
        routeData.Values.Add(“Controller”, routeDataController);
        routeData.Values.Add(“Action”, routeDataAction);          

        IHttpContext context = HttpContext
                                    .FakeoutApplicationPath(“/”)
                                    .ReturnMocked;          

        controller.ControllerContext
                     = new ControllerContext(context, routeData, controller);          

        return controller;
    }          

    public bool HasActionActionAttribute<TController>
                                       (Expression<Action<TController>> action)
    {
        StringBuilder sb = new StringBuilder();
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
            throw new InvalidOperationException(“Expression must be a method call”);
        if (call.Object != action.Parameters[0])
            throw new InvalidOperationException(“Method call must target lambda argument”);          

        Attribute attribute
                       = Attribute.GetCustomAttribute(call.Method,
                                                      typeof(ControllerActionAttribute));          

        return (attribute != null);
    }
}

These 2 classes are my base for BDD with MVC (although admittedly this is for the combination of TDD and BDD, because although I am mostly testing the behavior at some parts I am testing the configuration as well)

Now comes the sweet part… how does this look implemented?

Let me show you an example of specifying the routes:

[Specification]
public void And_the_Selected_route_data_should_resolve_default
                                   _route_when_default_url_is_received()
{
    using (How_SUT_should_Behave)
    {
        _httpContext = HttpContext
                            .FakeoutUrlRequest(“~/default.aspx”)
                            .ReturnMocked;
    }          

    using (What_SUT_should_Result_to)
    {
        RouteData routeData = _routes.GetRouteData(_httpContext);          

        Assert.IsNotNull(routeData);
        Assert.AreEqual(“home”, routeData.Values["controller"]);
        Assert.AreEqual(“index”, routeData.Values["action"]);
    }
}

Sweet, isn’t it? Let me show the controllers:

[Context]
public class When_OrdersController_List_action_is_called
                                         : MvcContextSpecification
{
    [Specification]
    public void Then_List_view_should_be_displayed_and_OrdersService
                                                 _should_get_the_data_for_view()
    {
        IOrdersService mockedOrdersService = CreateMockOf<IOrdersService>();          

        OrdersController controller
                  = CreateTestableControllerOf<OrdersController>(“orders”,
                                                                 “list”,
                                                                 mockedOrdersService);          

        IList<Order> dummyOrders = _GetDummyOrders();          

        using (How_SUT_should_Behave)
        {
            Expect.Call(mockedOrdersService.ListAll()).Return(dummyOrders);          

            controller.RenderView(“List”, dummyOrders);
        }          

        using (What_SUT_should_Result_to)
        {
            controller.List();
        }
    }          

    [Specification]
    public void And_List_action_should_have_an_action_attribute()
    {
        Assert.IsTrue(HasActionActionAttribute<OrdersController>(x => x.List()));
    }          

    private List<Order> _GetDummyOrders()
        {
            return new List<Order>{
                            new Order(),
                            new Order(),
                            new Order()
                        };
        }
}

I’ve mentioned this to Joe Ocampo… I am struggling with myself to try to write the vanilla unit tests now for my session so that the attendees can more easily grasp the concepts in testing the MVC controllers and routes, and I must admit that… I DON’T WANT TOOO!!! I like my specifications, they feel so “right”.

What do you think? As with the previous BDD article… I would love your comments is this any good or bad?

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · No Comments »

My variation of the BDD style specification base class

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

So lately I’ve been playing with BDD at home trying to *grok* the idea completely… as many people have said it in the past, one just needs to look pasted the *test* naming and understand your not doing BDD by naming your tests in natural sentence way… that’s just the tip of an iceberg.

However, to fully grasp the concept (I am still not 100% sure I have, but I am somewhere around hitting the target) one thing you definitely need is to bring the expressiveness in your tests (there I go again… Specifications) a few notches up to see the bigger picture.

So what I’ve done is… I took JP’s spec base class:

http://www.jpboodhoo.com/blog/BDDSpecificationBaseClass.aspx

…gave it my own touch and out came my version which is for me personally allot more expressive in it’s intent to describe the behavior of a functionality.

One great thing is that JP implemented and I followed Rhino Mocks and AutoMockingContainer which makes testing or specifying things allot better, faster and more natural (read JP’s article to get the idea of the full power of his Spec base).

Here it is my way:

public abstract class ContextSpecification
{
    private MockRepository _mocks;
    private AutoMockingContainer _container; 

    protected MockRepository Mocks
    {
        get { return _mocks; }
    }
    protected AutoMockingContainer Container
    {
        get { return _container; }
    } 

    [SetUp]
    public void BaseSetup()
    {
        _mocks = new MockRepository();
        _container = new AutoMockingContainer(_mocks);
        _container.Initialize(); 

        Before_Each_Specification();
    }
    [TearDown]
    public void TearDown()
    {
        After_Each_Specification();
    } 

    protected virtual void Before_Each_Specification()
    {
    }
    protected virtual void After_Each_Specification()
    {
    } 

    protected IDisposable How_SUT_should_Behave
    {
        get { return Mocks.Record(); }
    }
    protected IDisposable What_SUT_should_Result_to
    {
        get { return Mocks.Playback(); }
    }
    protected void Verify_Behavior_of(object mock)
    {
        _mocks.Verify(mock);
    }
    protected void Verify_Behavior_of_All_Objects()
    {
        _mocks.VerifyAll();
    }
    protected void Replay_Specified_Behavior_of(object specifiedObject)
    {
        Mocks.Replay(specifiedObject);
    }
    protected void Replay_Specified_Behavior_of_All_Objects()
    {
            Mocks.ReplayAll();
    } 

    protected T Mock<T>() where T : class
    {
        return _container.Get<T>();
    }
    protected T Create<T>()
    {
        return _container.Create<T>();
    } 

    protected void ProvideAnImplementationOf<Interface, Implementation>()
    {
        _container.AddComponent(typeof(Implementation).FullName,
                                        typeof(Interface),
                                        typeof(Implementation));
    }
    protected void ProvideAnImplementationOf<Interface>(object instance)
    {
        _container.Kernel.AddComponentInstance(instance.GetType().FullName,
                                            typeof(Interface), instance);
    } 

    protected IEnumerable<T> CreateEnumerableMockOf<T>()
    {
        return CreateMockOf<IEnumerable<T>>();
    }
    protected Interface CreateMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.DynamicMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStrictMockOf<Interface>(params object[] paramsForConstructor)
    {
        return Mocks.CreateMock<Interface>(paramsForConstructor);
    }
    protected Interface CreatePartialOf<Interface>(params object[] paramsForConstructor)
                            where Interface : class
    {
        return _mocks.PartialMock<Interface>(paramsForConstructor);
    }
    protected Interface CreateStubOf<Interface>(params object[] paramsForConstructor)
    {
        return _mocks.Stub<Interface>(paramsForConstructor);
    } 

}

And how do I use it, well it’s quite simple. Here is an example of the *loong* way-round specifying the behavior of an ASP.NET MVC route.

First my Specification template imports these:

using Context = MbUnit.Framework.TestFixtureAttribute;
using Specification = MbUnit.Framework.TestAttribute;

Then I use them like this:

[Context]
public class When_RouteContainer_is_configured : ContextSpecification
{
    private RouteCollection _routes;
    private IHttpContext _httpContext; 

    protected override void Before_Each_Specification()
    {
        _routes = new RouteCollection();
        RouteContainer.Initialize(_routes);
    } 

    [Specification]
    public void Then_RoutesCollection_should_be_initialized()
    {
        Assert.IsNotNull(_routes);
    } 

    [Specification]
    public void And_RoutesCollection_should_contain_2_routes()
    {
        Assert.AreEqual(_routes.Count, 2);
    } 

    [Specification]
    public void And_the_Route_data_should_resolve_default_route_when_default_url_is_received()
    {
        using (How_SUT_should_Behave)
        {
            _httpContext = CreateMockOf<IHttpContext>(); 

            IHttpRequest request = CreateMockOf<IHttpRequest>();
            SetupResult.For(_httpContext.Request).Return(request); 

            Replay_Specified_Behavior_of(_httpContext); 

            SetupResult.For(_httpContext.Request.AppRelativeCurrentExecutionFilePath)
                            .Return(“~/default.aspx”);
            SetupResult.For(_httpContext.Request.PathInfo)
                            .Return(string.Empty);
        } 

        using (What_SUT_should_Result_to)
        {
            RouteData routeData = _routes.GetRouteData(_httpContext); 

            Assert.IsNotNull(routeData);
            Assert.AreEqual(“home”, routeData.Values["controller"]);
            Assert.AreEqual(“index”, routeData.Values["action"]);
        }
    }
}

Notice a few things:

  • Usage of different attribute naming to express intent
  • Usage of When…Then…And naming to express continuity
  • Expressiveness of the specification itself - notice the last one - read it from bottom up - The result of the work done with SUT, or When SUT is used in this particular way (”What_SUT_should_Result_to”) it’s behavior should be (”How_SUT_should_Behave”) …

What do you think? Comments would be appreciated.

If anyone is interested in the real code, it will be published in the near future as part of my (future) code repository.

Cheers!


Filed under: ASP.NET MVC, BDD, C#
Written on: 13 Jan 2008 · 2 Comments »

ASP.NET MVC tidbits found when browsing the code

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Preview notice: This information is based on the first CTP of the MVC framework, the information from here will likely change in the next CTP’s

So last night I went digging into the code of the new MVC framework, fired up my Reflector and went to dig into the:

c:\Program Files\Reference Assemblies\Microsoft\Framework\ASP.NET 3.5 Extensions\System.Web.Extensions.dll

and the new System.Web.Mvc namespace.
So, here are a few tidbits found (hopefully this is only the first post about things like these in the framework):

mvctidbits1

(click for full size pic)

mvctidbits2 

This basically says confirms that controllers must:

a) Be named ending with “Controller”

b) Implement IController (the base class implements it)

Another thing:

mvctidbits3

(click for full size)

mvctidbits4

And this basically says that for the default View Engine (ASP.NET one) Views (.aspx, .ascx, .master) must be located in:

a) /Views/[Somedirectory]/

b) /Views/Shared/

So you can’t throw them anywhere and expect it to work.

That’s it for the first post about tidbits, hope this helps someone.

Cheers!


Filed under: ASP.NET MVC
Written on: 14 Dec 2007 · No Comments »

ASP.NET MVC Route definition DSL

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Just had an interesting idea… wouldn’t it be cool to be able to define ASP.NET routes via DSL (Ayende got me hooked up on the idea).

As Ayende mentions, making the idea work is quite simple, check out his blog posts about it:

http://www.ayende.com/Blog/category/547.aspx


But doing something serious with it takes a little bit more work:

http://www.ayende.com/Blog/archive/2007/12/13/Requirements-of-a-DSL-engine.aspx


But before I complicate myself out of doing this, consider this idea. Instead of these route definitions (pictures from ScottGu’s blog):

route1

route2

route3 

route4

route5


Think if you could define them in Routes.boo with something like:


Route “[controller]/[action]/[id]“:
    Defaults:
        action “Index”, id null

Route “Default.aspx”:
    Defaults:
        controller “Home”, action “index”, id null

Route “Search”
    Defaults:
        controller “Search”, action “index”

Route “Search/[query]“
    Defaults:
        controller “Search”, action “results”

Route “Products/Detail/[id]“
    Defaults:
        controller “Products”, action “Detail”
    Validation:
        id “\d{1,8}”

 

What do you think?

Ill try Ayende’s Rhino.DSL one of these days and take a crack at it… maybe something useful will come of it (or at least some new knowledge :))


Cheers!


Filed under: ASP.NET MVC, DSL
Written on: 13 Dec 2007 · No Comments »

One idea for ASP.NET MVC… strong typed View names

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5 out of 5)
Loading ... Loading ...

I really hate magic numbers, strings, etc… In all my projects I really try to avoid them as much as possible.

Wouldn’t it be nice if MS (or we as a community if they don’t… I can think of several ways to do it) would generate a strongly typed class called Views which contains the name of each View in the application, so like:

- View.Home
- View.About
- View.Contact
- VIew.Products


and instead of referencing by magic string:

mvc-strongtype1

something like this (of course implemented all over, not only in ActionLink):

mvc-strongtype2

(Resharper has put it in red… disregard that coloring issue)

Arguably a small detail… but as I said, not too hard to implement and… I REALLY hate magic strings :)


What do you think?


Filed under: ASP.NET MVC
Written on: 12 Dec 2007 · No Comments »

News about MVC framework and other bits from MS

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Finally some news. I’ve been really pissed of that as an MVP for ASP.NET I cannot get into the group which gets the early bits of the new MVC framework but it looks like it’s going to be released to the public anyway so ok (although I am still not ok that it was a very closed circuit).

So, the news is… seems like we are going to see it (and allot of other goodies) sometime next week as ScottGu mentions in his blog here:

 

http://weblogs.asp.net/scottgu/archive/2007/11/29/net-web-product-roadmap-asp-net-silverlight-iis7.aspx

 

So, interested in knowing what’s next? Interesting getting the early bits?

Then read the above blog post for more details on the future of the platform and the general roadmap.

 

Cheers!


Filed under: .NET, ASP.NET, ASP.NET MVC, Ajax, Interesting sites, VS2008
Written on: 30 Nov 2007 · 1 Comment »

ASP.NET MVC… one thing I like best…

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

While talking to a developer today, and without hiding my enthusiasm for the new framework I was asked what is my favorite thing about it?

It’s easy I said… It seems, they took all other *big* MVC frameworks, dissected them, took the good ideas, tried to come up with a good solution to bad ones… and for everything other… they made extensibility model… and that’s the thing I like best

And while I still don’t know how good it will be (until I get my hands on it), for starters… this sounds like a formula for success :)


Cheers guys! Just keep on with it, and give me a download! :)



Filed under: ASP.NET MVC
Written on: 13 Oct 2007 · No Comments »

More info on ASP.NET MVC!

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 3 out of 5)
Loading ... Loading ...

Let me mention again that it’s great to see that Microsoft is working on this… I am trilled about it! Really!

Ok, now a few more details… first off, I’ve talked to Scott Guthrie after his talk on ALT.NET and he told me they will publish more info in the coming weeks, so stay tunned for it…

As for the resources available now, these mostly consist of blog posts and some videos shot by Soctt Hanselman:

http://www.hanselman.com/blog/ScottGuMVCPresentationAndScottHaScreencastFromALTNETConference.aspx


Without me pasting the same blog posts links, you can find them in the post from Scott (my intention was to do it, but I am lazy :))

I am going to continue watching the videos, talk to you later!

Cheers!


Filed under: ASP.NET, ASP.NET MVC
Written on: 09 Oct 2007 · No Comments »

Scott Guthrie to announce ASP.NET MVC at ALT.NET!

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Finally!

Too bad I am not there… personally I would rather be there then on TechEd.

Ok.. back to the subject… Earlier this year on the MVP summit in Seattle Scott Guthrie announced that they might (finallly :)) build a real MVC framework.

Well… seems they were woring hard on it and now finally Scott is ready to go public with some of the concepts as Jeffrey mentiones here:

http://codebetter.com/blogs/jeffrey.palermo/archive/2007/10/05/altnetconf-scott-guthrie-announces-asp-net-mvc-framework-at-alt-net-conf.aspx


By the things he is saying it will be pretty good… I just hope someone will make a video of Scott’s presentation so I can view it :(

Can’t wait for Scott to publish some more details himself!




Filed under: ASP.NET, ASP.NET MVC, C#, Interesting sites
Written on: 06 Oct 2007 · No Comments »