Archive

Posts Tagged ‘MVC’

Sitecore MVC new Ninject Controller Factory – clean version

23/10/2012 2 comments

In this post we will have  revisit my last blog post, using Ninject with Sitecore MVC. In this new approach we will simplify the code to do the exactly same thing as in the last post LINK.
So what we want is to be able to inject Concrete implementation in the our Sitecore Controller.
We will do this by creating a ninjectc controller factory and forwarding  to the default Sitecore controller factory, so our implementation is used when Sitecore creates it’s controller. By doing it this way all standard Sitecore MVC functionality will still work, but we now have the possibility to inject our concrete implementation on creation time of the controllers.

First we need a Factory for creating the Ninject kernel


 public class NinjectKernelFactory
 {
   public IKernel Create()
   {
    return LoadAssembliesIntoKernel(new StandardKernel());
   }

   private IKernel LoadAssembliesIntoKernel(IKernel kernel)
   {
     foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
     {
      try
      {
        kernel.Load(assembly);
      }
      catch (Exception)
      {
         //Empty Catch used because ninject have problem
         //with loading some of the Sitecore MVC assemblies.
        // Method .ToString()
      }
    }
     return kernel;
   }
 }

With that in place we can create the the NinjectControllerFactory


 public class NinjectControllerFactory : DefaultControllerFactory
 {

  private IKernel _kernel;
  public NinjectControllerFactory(IKernel kernel)
  {
    _kernel = kernel;
  }

  public override void ReleaseController(IController controller)
  {
    _kernel.Release(controller);
  }

  protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
  {
    return (IController)_kernel.Get(controllerType);
  }
 }

]

All that is left is now for binding it all together in a new InitilizeContollerFactory


 public class InitializeNinjectControllerFactory
 {
   public virtual void Process(PipelineArgs args)
   {
    SetControllerFactory(args);
   }

  protected virtual void SetControllerFactory(PipelineArgs args)
  {
    NinjectKernelFactory kernelFactory = new NinjectKernelFactory();
    NinjectControllerFactory ninjectControllerFactory = new NinjectControllerFactory(kernelFactory.Create());
    SitecoreControllerFactory sitecoreControllerFactory = new SitecoreControllerFactory(ninjectControllerFactory);
    ControllerBuilder.Current.SetControllerFactory(sitecoreControllerFactory);
  }
 }

And off course we need to swap the originale InitlizeControllerFactory with our new one.

Sitecore default :

</pre>
<processor type="Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc"/>

Replaced with this:


<processor type="SitecoreNinjectModule.InitializeNinjectControllerFactory, SitecoreNinjectModule"/>

Now Lets try it our I have created a really simple example first an Item with a controller rendering on.

And the sourcode for the controller


public class StoryController : SitecoreController

{
 private ITestInterface _testInterface;
 public StoryController(ITestInterface testInterface)
 {
 _testInterface = testInterface;
 }

public ActionResult From()
 {

ViewBag.Froms = _testInterface.Get();
 return View();
 }
 }

And now to the View Code

And our RazerView


@model dynamic
 <h2>From vIew</h2>

@ViewBag.Froms

And a simple TestInterface and TestClass


public interface ITestInterface
 {
 string Get();
 }


public class TestClass : ITestInterface
 {
 public string Get()
 {
 return "Hallo From Test";
 }
 }

And the output of it all

There we are a much nicer and cleaner solution presented then I came up with in my last blog post and without breaking any Sitecore functionalit, and off course you can still unit test the controller.

Advertisements

Sitecore MVC the first controller.

03/07/2012 1 comment

Sitecore 6.6 is now out, (as a technical preview), with the realse of this version Sitecore now offers full support for MVC. There have all ready been quite a few blog post how to user MVC with Sitecore and some of the new fetures offers a great deal of ease when developing with Sitecore.

So this is the first in a series of how to develop with Sitecore using MVC and some of the benefits you get for free using MVC.

If you haven’t allready read John West blog post on how to setup you Sitecore solution to use MVC you can read them here start with Part 1 and use part 3 to setup a visual studio solution .John also wrote some simple examples on how to use the MVC framework to return JSON serialized result from a controller you read his original post here. For a first post in this Sitecore MVC series we will revisit his example and create our own controller but with a different approach, and with the soon to be released .Net 4.5 Framework which include the new web-api this should be even easier, and given you even more flexibility for free and out of the box, we will look back at this example when the final release is out.

By now you should now have an up an running Sitecore 6.6 solution. My visual studio solution setup is shown below.

Now lets create our first controller Code listed below.


public class ItemController : Controller
 {

public JsonResult Index(string id)
 {
 return Json(CreateObject(ChildRepository.Get(parentItemId)), JsonRequestBehavior.AllowGet);
 }

private ChildItemRepository _childRepository;
 public virtual ChildItemRepository ChildRepository
 {
 get { return _childRepository ?? (_childRepository = new ChildItemRepository()); }

}

private IEnumerable<object> CreateObject(IEnumerable<Item> items)
 {
 foreach (Item item in items)
 yield return new {item.Name};
 }

}

With the controller in place you can change the route to newly created controller John in his example uses a Pipeline in Sitecore to achieve this i like this approache so much more the using the global.asax so we reuse his code for this with some minor alternations. The Id of the node we want to retrieve children for if not specified default to the id of the Home-node. I’ve done this because i don’t like all his assert for empty id, and if you don’t like you can just use the original approach with optional url parameter.You could if liked alsp default the index action. But instead of getting the id trough the url route data you should supply it as a argument to the action method. The key here is that parameter Id must be named the same as the input parameter in index method.


public class SitecoreMVCRoutes
 {

public virtual void Process(Sitecore.Pipelines.PipelineArgs args)
 {
 this.RegisterRoutes(RouteTable.Routes);
 }

public bool MvcIgnoreHomePage { get; set; }

protected virtual void RegisterRoutes(RouteCollection routes)
 {
 if (this.MvcIgnoreHomePage)
 {
 routes.IgnoreRoute(String.Empty);
 }

routes.MapRoute(
 "Default", // Route name
 "Item/{action}/{id}", // URL with parameters
 new { controller = "Item", action = "Index", id = "{110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9}" } // Parameter defaults with Id to home node
 );
 }
 }

Now we will implement the busyness layer that will supply the controller with data.

This is done through a ChildRepository the code is listed below.

</pre>
public class ChildItemRepository
 {
 public virtual IEnumerable<Item> Get(string parentItemId)
 {
 ID parentId;
 if(ID.TryParse(parentItemId,out parentId))
 return GetChildNodes(parentId);
return new List<Item>();
 }

private IEnumerable<Item> GetChildNodes(ID parentId)
 {
 Item parentItem = Sitecore.Context.Database.GetItem(parentId);
 return parentItem.GetChildren();
 }
 }
<pre>

Lets test the new controller

First with out supplying a id,

Now with a valid id different form the home-node.

And now with a invalid id.

There we go the code does the same as Johns but with out all the assert tests.

Categories: .Net, C#, MVC, Sitecore 6, Uncategorized Tags: , ,

Loosely couple ninject kernel in MVC applications

27/07/2011 Leave a comment

I’m currently working on a hobby project “a photosite”, where I’m using MVC 3 with Entity Framwork 4 and Ninject IOC container. Maybe I overdid the decoupling of the Ninject kernel for this project, but I was fun to do and I gave material for this post :). The goal was to build a MVC project where the repository implementation was placed in separate project together with ninject binding.

So here is the repository Interaface:

public interface IGalleryRepository
{
   IEnumerable<Gallery> All { get; }
}

And here is the concrete implementation for the interface

public class GalleryRepository : IGalleryRepository
{
   PhotoSiteContext context = new PhotoSiteContext();
   public IEnumerable<Gallery> All
   {
    get { return context.Galleries; }
   }
}

Now we need to alter the global.asax file with the following.

public class MvcApplication : NinjectHttpApplication
{
   public static void RegisterGlobalFilters(GlobalFilterCollection filters)
   {
     filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Gallery", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected override void OnApplicationStarted()
{
base.OnApplicationStarted();

AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
protected override IKernel CreateKernel()
      {
var kernel = new StandardKernel();
kernel.Load(AppDomain.CurrentDomain.GetAssemblies());
return kernel;
}
}

By loading the kernel this way Ninject will looke through all dll’s in the bin folder of MVC project “main project” and load all assemblies which inherit from the NinjectModul class.

Now we cant in same project as the implementation of the inteface make a new class which derives from Ninject modul. The class should look like this.

public class SqlCompactNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IGalleryRepository>().To<GalleryRepository>();
}
}
With this setup it would be possible to switch the gallery implementation simply by adding a new dll with a NinjectModule and a concrete implementation of the IgalleriInterface.
I hope you find this usefull.
Categories: .Net, MVC Tags: , , ,

CMS Friendly URL With MVC (Simple)

04/05/2011 Leave a comment

I currently working on HUGE MVC project for a customer through Pentia. They are rebuilding their entire website from .Net webforms to MVC 3 with Razer.

So one of the first task was to build som simpel functionality tha could resolve their url delivered from the underlying CMS.Instead of register specific routes for the different pagetypes in the CMS

I came up with this solution shown in this blogpost.

To begin with I registered a new “CMS route in global.asax”. All URL shoul hit this route, ofcourse you could make other routes before this.


//RouteMap for CMS content
routes.MapRoute("CMSRoute", "{*url*}").RouteHandler = new CmsRouteHandler();

Now to the simple CmsRouteHandler implementation it simply calls the CmsHttpHandler a relying on the handler to find a correct controller to desplaying the current request.

public class CmsRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new CmsHttpHandler(requestContext);
}
}

Now the CMSHttpHandle which for this blogpost is simplyfied to always returning the
frontpage. This should offcourse by matching the url to a page i DB and displaying the
and resolve it to the correct controller.


public class CmsHttpHandler : IHttpHandler
{
private RequestContext RequestContext { get; set; }
private IControllerFactory ControllerFactory { get; set; }
private IController Controller { get; set; }

public CmsHttpHandler(RequestContext requestContext)
{
RequestContext = requestContext;
}

public void ProcessRequest(HttpContext context)
{
HttpContext = context;
InstantiateControllerFactory();
InstantiateController();
SetupRequestContext();
Controller.Execute(RequestContext);
}

private HttpContext HttpContext { get; set; }

private void InstantiateControllerFactory()
{
ControllerFactory = ControllerBuilder.Current.GetControllerFactory();
}

private void InstantiateController()
{
Controller = ControllerFactory.CreateController(RequestContext, Pagetype);
}

private void SetupRequestContext()
{
RequestContext.RouteData.Values.Add("controller", Pagetype);
//Always render Index action, all pagetype controllers must implement Index action
RequestContext.RouteData.Values.Add("action", "Index");

AppendQueryStrings();
}

private void AppendQueryStrings()
{
foreach (string name in HttpContext.Request.QueryString)
RequestContext.RouteData.Values.Add(name, HttpContext.Request.QueryString[name]);
}

private static string ResolvePagetypeFromUrl()
{


//Should return apgetype from db/URL
return Pagetype


}

private string _pageType;
private string Pagetype
{
get
{
//Resolve pagetype from DB fx
//For now we will just return the frontpage
/return string should match controller name
return "frontpage";
}
}

public bool IsReusable
{
get
{
throw new NotImplementedException();
}
}
}

Hope you find it usefull..

Categories: C# Tags: ,