X Blogs

who you gonna call?

Manualy Submiting Unobtrusive MVC 3 Ajax Form

clock April 21, 2011 23:21 by author Rok Bermež
If you want to submit Ajax.BeginForm created ajax form a simple this.form.submit() wont work. Well to be exact it will, but not as it was intended. In order to make it work like expected, we can do it like this:
 
Html.DropDownList("selPredavanja",ViewBag.Lectures as SelectList,new { onchange = "Sys.Mvc.AsyncForm.handleSubmit( this.form, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'lectureData' });"})


ASP.NET MVC 3 AJAX REDIRECT RESULT

clock April 5, 2011 23:31 by author Rok Bermež
From time to time, we need to selectively redirect the browser to another location as a 
result of an AJAX action. Just returning RedirectResult won’t do the trick (even if we
are used to similar functionality in ASP.NET AJAX in combination with WebForms ). Here
is a very simple RedirectResult thet will be appropriate in those scenarios:

public class AjaxRedirectResult : RedirectResult { public AjaxRedirectResult(string url): base(url){} public override void ExecuteResult(ControllerContext context) { if (context.RequestContext.HttpContext.Request.IsAjaxRequest()) { JavaScriptResult result = new JavaScriptResult() { Script = String.Format("window.location='{0}';",
UrlHelper.GenerateContentUrl(Url, context.HttpContext)) }; result.ExecuteResult(context); } else base.ExecuteResult(context); } }


MVC3 Windows Azure Deployment

clock January 14, 2011 21:12 by author Rok Bermež

For RTM version of MVC 3 make sure the deployment contains following dlls:

  • Microsoft.Web.Infrastructure
  • System.Web.Helpers
  • System.Web.Mvc
  • System.Web.Razor
  • System.Web.WebPages
  • System.Web.WebPages.Deployment
  • System.Web.WebPages.Razor

 



MultipleGenericBindingGenerator for Ninject.Extensions.Conventions

clock January 11, 2011 02:55 by author Rok Bermež

Ninject.Extensions.Conventions provides convention based binding for Ninject modeled after the StructureMap 2.5 AssemblyScanner by Jeremy Miller.

When StructureMap users can use something like:

Scan(scanner =>
                {
                    scanner.AssembliesFromApplicationBaseDirectory(assembly => assembly.FullName.StartsWith("Ntk.Infrastructure."));
                    scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <,>));
                    scanner.ConnectImplementationsToTypesClosing(typeof (IMessageHandler <>));
                });

Ninject.Extensions.Conventions using GenericBindingGenerator can not:

            kernel.Scan(scanner =>
            {
                scanner.FromAssembliesMatching( "Ntk.Infrastructure.*.dll" );  
                scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<>)));
                scanner.BindWith(new GenericBindingGenerator(typeof(IMessageHandler<,>)));
                scanner.InTransientScope();
            });

So slightly modified version of GenericBindingGenerator called MultipleGenericBindingGenerator comes to the rescue:

            kernel.Scan(scanner =>
            {
                scanner.FromAssembliesMatching("Ntk.Infrastructure.*.dll");
                scanner.BindWith(new MultipleGenericBindingGenerator(typeof(IMessageHandler<>),typeof(IMessageHandler<,>)));
                scanner.InTransientScope();
            });

If anyone needs anything like this, here is the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ninject;
using Ninject.Activation;
using Ninject.Extensions.Conventions;

namespace TestProj{
    public class MultipleGenericBindingGenerator  : IBindingGenerator
    {
        private static readonly Type TypeOfObject = typeof (object);
        private readonly Type[] _contractTypes;

        /// <summary>
        /// Initializes a new instance of the <see cref="MultipleGenericBindingGenerator"/> class.
        /// </summary>
        /// <param name="contractTypes">Types of the contract.</param>
        public MultipleGenericBindingGenerator(params Type[] contractTypes)
        {
            foreach (var type in contractTypes)
            {
                if (!(type.IsGenericType || type.ContainsGenericParameters))
                {
                    throw new ArgumentException(String.Format("The contract must be an open generic type ({0}).",type.Name), "contractTypes");
                } 
            }
            _contractTypes = contractTypes;
        }

        #region Implementation of IBindingGenerator

        /// <summary>
        /// Processes the specified type creating kernel bindings.
        /// </summary>
        /// <param name="type">The type to process.</param>
        /// <param name="scopeCallback">the scope callback.</param>
        /// <param name="kernel">The kernel to configure.</param>
        public void Process( Type type, Func<IContext, object> scopeCallback, IKernel kernel )
        {
            Type interfaceType = ResolveClosingInterface( type );
            if ( interfaceType != null )
            {
                kernel.Bind( interfaceType ).To( type ).InScope( scopeCallback );
            }
        }

        #endregion

        /// <summary>
        /// Resolves the closing interface.
        /// </summary>
        /// <param name="targetType">Type of the target.</param>
        /// <returns></returns>
        public Type ResolveClosingInterface( Type targetType )
        {
            if ( targetType.IsInterface || targetType.IsAbstract )
            {
                return null;
            }

            do
            {
                Type[] interfaces = targetType.GetInterfaces();
                foreach ( Type @interface in interfaces )
                {
                    if ( !@interface.IsGenericType )
                    {
                        continue;
                    }

                    if (_contractTypes.Contains(@interface.GetGenericTypeDefinition()))
                    {
                        return @interface;
                    }
                }
                targetType = targetType.BaseType;
            } while ( targetType != TypeOfObject );

            return null;
        }
    }
}



T4MVC templates for strongly typed ASP.MVC

clock January 10, 2011 21:19 by author Rok Bermež

T4 templates for strongly typed ASP.MVC

 

MVC is a software pattern, that has been first introduced 1979 by Norwegian scientist Trygve Reenskaug.  The idea was to decouple the tight knot between views and models, to have a much more control over the software.

For example, very known ASP.NET 2.0 technology had the implementation of views, but controllers and models were combined in the code behind, which has the impact on the testing and other features, which is needed to build a easy proficient sustainable web solution.

Year ago Microsoft has launched a framework ASP.NET MVC for supporting software pattern and add additional value with different view engines , such as Razor, to eliminate this requirement. Since then, developers are having  few consideration about choosing between ASP.NET WebForms and ASP.NET MVC, but that is topic for another blog post.

MVC grew very quickly and alot of developers are using the new .NET framework to write efficient, light weight, powerfull web apps. Even though we do have a great enviroment for writing, testing, debugging  .NET apps, there is still a lack of string and mis-machted typos.

Consider following example:

<%:Html.ActionLink(»My link«,«Indeks«,«Home«) %>

This is a link to the Home controller, with a method Indeks. But wait, there is no indeks method there. It is a typo. Since we forgot to write x, instead of ks, we got a runtime error. We have to run the site, click of the link, read the error message, ask ourself, what did we do, use the debugger, run the site, check again, go through bunch of step, just because we made a typo.

This is the reason, why expert developers, such as david Ebbo, created a helper (T4 templates), that goes through the code and created a strongly typed strings for controllers, views, even a content.

Fixed upper example:

<%:Html.ActionLink(»My link«, MVC.Home.Index)%>

Its so easy. No more runtime checking, no repro bugs, even intellisense helps us understand, which name and even parameters we will use. 

You can use the following strongly typed helpers in the whole app, not only the views ( also in controllers, etc.)

It is quite simple to use it:

1.       Download the zip file on the codeplex site

2.       Required watching the David Ebbo intro with examples

3.       Unzip the file

4.       Add the 2 files in the root of your MVC app (T4MVC.tt and T4MVC.setting.t4)

5.       Build it

6.       Use it J

You can change the setting for t4 in the settings file to bend it to you will J

Happy no-typo coding.



About the author

Rok Bermež is Slovenian Windows Azure MVP, he works as a Software Engineer and Microsoft Certified Trainer at Kompas Xnet. His primary interests include cloud computing and web development. With extensive experience in development and architecture he participated in many projects and since the CTP release of Windows Azure much of those projects are based on Windows Azure platform. Rok has been delivering courses, writing code and speaking at conferences and community events on Microsoft technologies for the last couple of years. You can also find him on Twitter (@Rok_B).

Month List

Sign In