Using the SPContext in HttpModules in SharePoint

By Geert van der Cruijsen at May 23, 2010 17:20
Filed Under: Asp.net, 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

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

By Geert van der Cruijsen at May 20, 2010 22:55
Filed Under: Asp.net, SharePoint, JQuery

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

Creating an MVC based website with reusable widgets

By Geert van der Cruijsen at July 12, 2009 10:46
Filed Under: Asp.net, Geert's Projects, MVC

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

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

By Geert van der Cruijsen at June 05, 2009 13:47
Filed Under: Asp.net, MVC, dotnetmag

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

ASP.NET MVC framework 1.0 released

By Geert van der Cruijsen at March 18, 2009 15:23
Filed Under: Asp.net
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  

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

By Geert van der Cruijsen at March 31, 2008 21:48
Filed Under: Asp.net, General

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

Internet Explorer 8 will render with 'super standard mode'

By Geert van der Cruijsen at March 04, 2008 20:04
Filed Under: Asp.net, General

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

Using the Flickr.net Api on a medium trust server

By Geert van der Cruijsen at December 29, 2007 19:37
Filed Under: Asp.net

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