Virtual conference MVCConf 2011

Yesterday MVCConf 2011 was held. MVCConf is a virtual conference about ASP.NET MVC and since ASP.NET MVC 3 has shipped a few weeks ago there was a lot to talk about. The conference is organized by the community and there are a lot of speakers from the Community as well as from Microsoft.

Some videos are online already at www.mvcconf.com/live but all videos are coming online later at the www.mvcconf.com site.

Since I’m an ASP.NET MVC fanatic I’ve used my free evening to watch the sessions and will view more tomorrow.

mvcconf

Sessions I watched:

Keynote by Scott Guthrie @scottgu

Scott talked about the history of ASP.NET MVC 3 and the older versions (ofcourse everyone knows he wrote version 1 during a single flight from his home to some conference a few years ago) and held an interactive session where people could ask questions using twitter. He talked about the difference of webforms and mvc ofcourse since this is a question that is always asked when talking about mvc on a high level. He noted again that webforms, webmatrix and MVC will all exist next to each other in the future and serve different purposes. to make this more clear he gave 3 keywords for all methods of building ASP.NET applications

WebMatrix

  • Simple
  • Light
  • Fast

Web Forms

  • Familiar
  • Reusable
  • Productive

MVC

  • Powerfull
  • Extensible
  • Agile

Other things he talked about is the focus of Microsoft on JQuery. Microsoft added JQuery to the MVC 1.0 and in 3.0 they even switched completely to JQuery when you look at all examples etc. Microsoft is also actively helping in creating a new JQuery plugin for the JQuery Datatable. this is something I would really like to see!!

Scott also told us about project Orchard which is a new open source CMS project by Microsoft. this is also looking really promising. Another thing Scott talked about really quick was an Asset management system for CSS and JS functions / snippets. more to come about this in the future. (he wasn’t supposed to say anything about this.)

Finally he talked about large sites running ASP.NET MVC. He couldn’t tell a lot about this since he didn’t know which company liked him saying their technology choices. but some examples he did tell were bing.com and other microsoft sites. other examples people on twitter added are the channel 9 site, stackoverflow.com and cheezburger.com :D

Phil Haack on nuget @haacked

Phil talked on Microsoft opensource project nuget by showing how you use it in visual studio using the extension manager and the console. I think most people have already seen and used nuget but this session went deeper. phil showed us how to create packages and how to use advanced functions the console. Something that was new to me he showed us is the local repository you can add in nuget. I’m going to have another look at this later so we can use it within our company.

after this he showed us how nuget is working under the hood. All in all a really nice session for me.

Brad Wilson on “Advanced MVC 3.0” @bradwilson

Brad talked on some advanced topics of MVC 3.0. It’s hard to do a recap on this one since it’s a lot of stuff. some things were really interesting. he started off with statefull filters to show how to use filters per request, per session or per applications. after this he talked about validation with unobstructive Ajax with Jquery. very interesting!!

He also talked about how to use different kinds of objects as classes for your model and about routing constraints.

If you are a more advanced MVC developer this is a session you shouldn’t miss.

Steve Sanderson on MVC Scaffolding @stevesanderson

Steve talked about the opensource project MVC Scaffolding. The original idea for this came from the Ruby community where people wanted to generate simple crud forms and the database itself from the model classes. Steve has created a package which you can get with nuget to have this in ASP.NET MVC 3.0.

Phil showed a quick sample of this on his nuget presentation and Steve also showed an example where he automatically generated everything using the repository pattern so you get a nice decoupled scenario without typing any code. after this he showed more complex situations. for more info check this blogpost:

http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/

Other sessions I haven’t watched yet but will do later are:

BDD in ASP.NET MVC using SpecFlow, WatiN and WatiN Test Helpers by Brandon Satrom

Quality Driven Web Acceptance Testing by amir Barylko

WebMatrix by Rob Conery

Entity Framework “Code First”: Domain Driven CRUD by Chris Zavaleta

I really enjoyed the sessions. MVCConf and all speakers thanks and hopefully I’ll be able to join MVCConf 2012 again next year.

When all video’s are up I’ll edit the post with the links to the videos

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Using the SPContext in HttpModules in SharePoint

When you are building custom HttpModules in SharePoint a common thing to do is to use the SPContext object to get acces to your SPSite, SPWeb, SPList or SPListItem. When doing this you have to be careful because the SPContext isn’t available everywhere because HttpModules can run early in the ASP.Net request pipeline so the SPContext object isn’t available yet.

if you try to acces the SPContext to early in the pipeline you’ll get a System.InvalidOperationException error.

The earliest you can use the SPContext is in the “PreRequestHandlerExecute” so don’t use it at the BeginRequest event what most people try to use when they want to add code as early in the pipeline as possible

code:

   1: public class RequestHandlingHttpModule : IHttpModule, IRequiresSessionState

   2: {

   3:  

   4:     public void Dispose() {}

   5:  

   6:     public void Init(HttpApplication application)

   7:     {

   8:         application.BeginRequest += application_BeginRequest;

   9:         application.PreRequestHandlerExecute += new EventHandler(application_PreRequestHandlerExecute);

  10:     }

  11:  

  12:     void application_PreRequestHandlerExecute(object sender, EventArgs e)

  13:     {

  14:         string webUrl = SPContext.Current.Web.Url;

  15:     }

  16:  

  17:     void application_BeginRequest(object sender, EventArgs e)

  18:     {

  19:         // do not use SPContext here it will throw a System.InvalidOperationException 

  20:         // this event is fired before PreRequestHandlerExecute so code that doesn't uses SPContext goes here

  21:     }

  22:  

  23: }

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Combined power of SharePoint and JQuery part 2: Changing the SharePoint webpart edit menu position

Have you ever had the problem using SharePoint 2007 that when you create small webpart zones that the edit button disappeared because the title of the webpart was to long? I ran into this problem at my current project and instead of shortening down the titles i came up with the idea of changing the position of the edit button to be on the left of the title. when the button is on the left and the title is on the right the title will be trimmed automatically since the webpart zones have a fixed length.

In your server side code it’s really hard to change these kinds of things because this is standard SharePoint functionality and you can’t change it server side. So the solution is to fix it using javascript and to make that easier I’m using JQuery.

first I’ll show you the results below and then how I did it using a small JQuery script.

before:

sharepointjquery1

after:

sharepointjquery2

Below is the JQuery script to change the position of the edit menu to the left. the only thing you have to do is save this code to a js file, include the reference to the js file and a reference to the JQuery library js file on your masterpage and you’re done.

   1: $(document).ready(function() {

   2:     SPEditMenuFix();

   3: });

   4:  

   5: function SPEditMenuFix() {

   6:     $(".ms-WPHeader").each(function() {

   7:         var first = $(this).children("td:first").clone(true);

   8:         var last = $(this).children("td:last").clone(true);

   9:         $(this).children("td:first").replaceWith(last);

  10:         $(this).children("td:last").replaceWith(first);

  11:     });

  12: }

Enjoy!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Creating an MVC based website with reusable widgets

After the Asp.net MVC Framework was released i was pretty impressed of how it worked but one of my main problems was how to handle the data on the page that is not the main goal of the specific page.

In ASP.NET MVC every page has its specific controller and views that can handle the data for the page that is requested. for example when you’re building a web shop you’ll probably have a ProductController that handles everything that has to do with the Products in your shop. But when you are browsing a web shop product page you would also like to see other data that has nothing to do with products, for example your shopping basket, current login state etc. Should you add this logic to the ProductController? imo you shouldn’t since the Products controller only responsibility should be the products. So how should we handle this in the MVC framework?

My first idea that came to mind to solve this problem was doing an Ajax request to for example, the shopping basket controller on your view when you would like a shopping basket added to your page. This can be in some situations the best way to do it but in some cases you might not want to use Ajax since then this content can’t be indexed by search engines for example.

An example how to use Ajax widgets is found here: http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=310

My main goal was to be able to add widgets to a page without the controller of that page knowing about these widgets. I found some solutions to this called partial requests found here: http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/

These partial requests weren’t my favorites also since i didn’t want to put this logic in the view so i developed my own CMS like solution for this problem.

My idea was that a page can have several page zones and page zones contain widgets. widgets and complete page zones should be reusable by other pages so i stored these in my CMS database. how my database is build up you can see in the image below

image

A widget should be able to render itself so i made an abstract BaseWidget class that has a Render Method. A widget can also be a call to a different controller so i made a SubController class that inherits from BaseWidget. The SubController Widget has an Controller, Action and ID so it can call the controller it belongs to.

   1: public abstract class SubControllerWidget : BaseWidget

   2: {

   3:     public string Controller { get;  set; }

   4:     public string Action { get;  set; }

   5:     public object ID { get; set; }

   6: 

   7:     public SubControllerWidget(string Controller, string Action) : base()

   8:     {

   9:         this.Controller = Controller;

  10:         this.Action = Action;

  11:         this.ID = null;

  12:     }

  13: 

  14:     public SubControllerWidget(string Controller, string Action, object ID)

  15:         : base()

  16:     {

  17:         this.Controller = Controller;

  18:         this.Action = Action;

  19:         this.ID = ID;

  20:     }

  21: 

  22:     public override void Render(System.Web.Mvc.ViewContext vc)

  23:     {

  24:         vc.RouteData.Values["controller"] = Controller;

  25:         vc.RouteData.Values["action"] = Action;

  26:         vc.RouteData.Values["id"] = ID;

  27:         IHttpHandler handler = new MvcHandler(vc.RequestContext);

  28:         handler.ProcessRequest(System.Web.HttpContext.Current);

  29:     }

  30: 

  31:     public abstract void SetSettings(WidgetSettings settings);

  32: }

To build a specific widget just inherit a widget from SubControllerWidget and you are ready to go. Set the Controller, Action and ID to call and that specific controller will be called.

To add these page zones and widgets to the pages dynamically i’ve created a CMSController that overrides the OnActionExecuted method so it can insert the page zones and widgets to the model that’s been send to the View.

   1: protected override void OnActionExecuted(ActionExecutedContext filterContext)

   2: {

   3:     if (ViewData.Model == null)

   4:     {

   5:         ViewData.Model = new CMSViewModel();

   6:     }

   7:     string controller = filterContext.RequestContext.RouteData.Values["controller"] != null ? filterContext.RequestContext.RouteData.Values["controller"].ToString() : "";

   8:     string controllerAction = filterContext.RequestContext.RouteData.Values["action"] != null ? filterContext.RequestContext.RouteData.Values["action"].ToString() : "";

   9:     string controllerActionid = filterContext.RequestContext.RouteData.Values["id"] != null ? filterContext.RequestContext.RouteData.Values["id"].ToString() : "";

  10:     IList<PageZone> zones = _cmsRep.GetPageZonesForPage(controller, controllerAction, controllerActionid);

  11: 

  12:     CMSViewModel page = (CMSViewModel)ViewData.Model;

  13:     if (page.PageZones == null)

  14:     {

  15:         page.PageZones = zones;

  16:     }

  17:     else

  18:     {

  19:         foreach (PageZone zone in zones)

  20:         {

  21:             page.PageZones.Add(zone);

  22:         }

  23:     }

  24: 

  25: 

  26:     base.OnActionExecuted(filterContext);

  27: }

 

So now all widgets beloning to a page will be retrieved from the CMSRepository and are added to the CMSViewModel so now it’s the View’s turn to render all widgets.

In my master page I’ve added the following line that is responsible for rendering all widgets:

<% Html.RenderPageZones(Model); %>

For that to work I’ve created a few html extension methods to render the page zones.

   1: public static class HtmlCMSExtensions

   2: {

   3:     public static void RenderPageZones(this HtmlHelper html, CMSViewModel page)

   4:     {

   5:         if (page != null && page.PageZones != null)

   6:         {

   7:             foreach (PageZone zone in page.PageZones)

   8:             {

   9:                 html.RenderPartial("PageZone", zone);

  10:             }

  11:         }

  12:     }

  13: 

  14:     public static void RenderWidgetsInZone(this HtmlHelper html, PageZone zone)

  15:     {

  16:         if (zone != null && zone.Widgets != null)

  17:         {

  18:             foreach (IWidget widget in zone.Widgets)

  19:             {

  20:                 widget.Render(html.ViewContext);

  21:             }

  22:         }

  23:     }

  24: }

In my PageZone view i’ve added the other html extension method called RenderWidgetsInZone so all widgets are rendered by itself.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<VanDerCruijsen.MVC.CMS.Model.PageZone>" %>

<div id="<%= Html.Encode(Model.Name) %>">

name:<%
   1: = Html.Encode(Model.Name)

%>

<%
   1:  Html.RenderWidgetsInZone(Model);

%>

</div>

This is the way I use to create widgets on my ASP.NET MVC pages. If you have any recommendations or better ways how to do it please let me know.

When I have the time I’m going to build an admin controller to be able to add widgets and pagezones via the webinterface since now the only option is to add them in the database by hand.

My sources aren’t really cleaned up so if you want a working source/solution please send me mail or leave a comment.

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

My article about the ASP.NET MVC Framework published in the Dutch .Net Magazine

Hello everyone,

It’s been a while since my last post (again :( ) but I’ve been quite busy testing out the new ASP.NET MVC Framework. I have to say i really like it. Currently I’m building my own little CMS framework on top of the MVC framework so it becomes easier to use widgets or other non main data items on your pages. As soon as it’s in a show able form I’ll  post it on my blog.

I’ve also written an article about the ASP.NET MVC framework for the Dutch .Net Magazine (in Dutch) so if you are a reader of the magazine check out page 22 of the June 2009 release (#25) :)

The Title of my article is: “Volledige controle over je webapplicatie met het ASP.NET MVC Framework” (“Total control over your web app using the ASP.NET MVC Framework”)

The article will also come online sometime but the official site (also used to sign up for the free magazine) www.dotnetmag.nl is still showing #23 as the newest one.

When the pdf is put online I’ll add the link to this post.

I’ve focused on writing about how to build an ASP.NET MVC application using TDD because I think this is one of the major advantages over the “old” way of building web applications in ASP.NET.

If you have any feedback or comments about the article please let me know!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

ASP.NET MVC framework 1.0 released

After the announcement of silverlight 3.0 i was chatting with a colleague about how cool it would be if asp.net MVC framework would also be released at mix.

My colleague started searching and came up with this link:

http://www.microsoft.com/downloads/details.aspx?FamilyID=53289097-73ce-43bf-b6a6-35e00103cb4b&displaylang=en

Pretty cool huh? I haven’t seen any official press releases from Microsoft but since you can download it it seems that it has been released! 

My guess is that it will be announced on MIX today or tomorrow but I couldn’t wait to share it with you already J 

Geert van der Cruijsen  

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Small things that make life easier: attach Visual studio debugger to multiple processes

Hello again.

Today a really small post from me about a really simple thing i found out today. Ofcourse a lot of people know this but i also know lots of people dont know this while you are using it quite often. When you are developing for SharePoint for example you’ll have to debug by attaching your debugger to the right w3wp.exe process. When i did this i always selected 1 and hoped it was the right one. Today i was debugging together with a collegue and then he selected more processes at once and i was like *DOH*!!!

This discovery can save a lot of time if you always pick the wrong w3wp.exe process like i did :)

so for everyone who didnt know this use this option from now on. I will do it for sure!

 

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Internet Explorer 8 will render with ‘super standard mode’

Today Microsoft promised Internet Explorer 8 will use the ‘super standard mode’  rendering mode by standard instead of the IE7 version ‘Quirks mode’ that was planned earier.

Because of this People will be forced using the W3C standards OR add a special tag so the browser knows it should render the page in IE7 mode. Hopefully this will help to have 1 standard html which every browser will show the same way. More information about this: http://blogs.msdn.com/ie/archive/2008/03/03/microsoft-s-interoperability-principles-and-ie8.aspx 

With this change IE8 will be able to pass the ACID2 test but guess what the “Web Standards Project” released the ACID3 test today which is supposed to test Ajax and other dynamic content in browsers. IE7 get’s a score of 5 out of 100 while FireFox is getting the current best score with 50/100. Still a long way to go for every browser to pass this test. You can find the test and more information here: http://www.webstandards.org/action/acid3/

 

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter

Using the Flickr.net Api on a medium trust server

The photo sharing site Flickr has a nice api which you can use in your own applications. On codeplex is a .net version of this api Flickr.net.

I had to make a little script for a friends project so she could view random flickr photo’s on her site. I made a aspx page using the Flickr.Net dll and it worked perfectly on my own machine. after uploading it to my hosted webserver i ran into trouble. the following error came up when browsing to the aspx page

Exception Details: System.Security.SecurityException: Request for the permission of type ‘System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.

After some research i came to the conclusion that it had something to do with my site running in a medium trust. The Flickr.Net api uses a caching function standard which doesnt has the right permission on a hosted envoirment.

The real solution was easy after i found out what the real problem was. The only thing i had to do was disable the caching:

Flickr.CacheDisabled = true;

 

After doing this the script was running perfectly. during the search for the solution to this problem i came across a lot of people who had the same problem when deploying their Flickr.net enabled scripts so i thought it was handy to post this simple solution.

Have fun with your Flickr.Net enabled Scripts!

Geert van der Cruijsen

Share on Facebook
Kick It on DotNetKicks.com
Shout it
Post on Twitter