<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSnippet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Snippet>
      <Id>henjfp</Id>
      <UserId />
      <Code>        protected void Application_Start()
        {
#if DEBUG
            HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize();
#endif
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            RegisterDomainModel(AssemblyOf&lt;Item&gt;());
            
            SetupBaseServices();
            
            RegisterComponents&lt;ConnectionStringServicesInstaller&gt;();
            RegisterComponents&lt;DefaultAuthServicesInstaller&gt;();
            RegisterServices(AssemblyOf&lt;ServiceBase&gt;());

            RegisterControllers(AssemblyOf&lt;AccountController&gt;());
            
            RegisterControllerFactory();

            SetupMembership();
        }</Code>
      <Title>Application_Start in mvc2</Title>
      <Tags>mvc2, nhibernate, asp</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Andrea Balducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-06-24T02:56:23.603</Entered>
      <Views>44</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>b3w3pj</Id>
      <UserId>bgauehzf</UserId>
      <Code>using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Moq;
using MvcContrib.Web.Security;
using NUnit.Framework;

namespace MvcContrib.UnitTests.Rest.Security
{
	[TestFixture]
	public class BasicAuthenticationAuthorizeAttributeTester
	{
		#region Setup/Teardown

		[SetUp]
		public void SetUp()
		{
			_mockRequestBase = new Mock&lt;HttpRequestBase&gt;();
			_mockRequestBase.Setup(x =&gt; x.HttpMethod).Returns("GET");
			_mockRequestBase.Setup(x =&gt; x.Headers).Returns(new NameValueCollection());
			_mockContextBase = new Mock&lt;HttpContextBase&gt;();
			_mockContextBase.Setup(x =&gt; x.Request).Returns(_mockRequestBase.Object);

			_mockAuthorizationContext = new Mock&lt;AuthorizationContext&gt;();
			_mockAuthorizationContext.Setup(x =&gt; x.HttpContext).Returns(_mockContextBase.Object);

			_basicAuthenticationAuthorizeAttributeHelper = new BasicAuthenticationAuthorizeAttributeHelper();
		}

		#endregion

		private Mock&lt;HttpRequestBase&gt; _mockRequestBase;
		private Mock&lt;HttpContextBase&gt; _mockContextBase;
		private Mock&lt;AuthorizationContext&gt; _mockAuthorizationContext;
		private BasicAuthenticationAuthorizeAttributeHelper _basicAuthenticationAuthorizeAttributeHelper;

		private const string ValidUserName = "Fake ValidUserName";
		private const string ValidPassword = "Fake ValidPassword";
		private const string InvalidUserName = "Fake InvalidUserName";
		private const string InvalidPassword = "Fake InvalidPassword";

		private static string ConvertToBasicAuthenticationHeader(string userName, string password)
		{
			if(string.IsNullOrEmpty(userName))
			{
				throw new ArgumentNullException("userName");
			}

			if(string.IsNullOrEmpty(password))
			{
				throw new ArgumentNullException("password");
			}

			// Yep, we have something in this field...
			byte[] encodedText = Encoding.UTF8.GetBytes(userName + ":" + password);
			return "Basic " + Convert.ToBase64String(encodedText);
		}

		private class BasicAuthenticationAuthorizeAttributeHelper : BasicAuthenticationAuthorizeAttribute
		{
			public override bool IsAuthenticated(string username, string password)
			{
				return !string.IsNullOrEmpty(username) &amp;&amp; !string.IsNullOrEmpty(password) &amp;&amp;
				       username == ValidUserName &amp;&amp; password == ValidPassword;
			}
		}

		[Test]
		public void OnAuthorization_the_user_with_incomplete_credentials_authenticates_successfully()
		{
			// Arrange.
			// NOTE: No "authorisation" Request.Header key/value has been mocked .. on purpose for this test.

			// Act.
			try
			{
				_basicAuthenticationAuthorizeAttributeHelper.OnAuthorization(_mockAuthorizationContext.Object);

				Assert.Fail("An exception should be thrown.");
			}
			catch(HttpException httpException)
			{
				Assert.AreEqual((int)HttpStatusCode.Unauthorized, httpException.GetHttpCode());
				Assert.AreEqual(
					"Incomplete or no basic authentication data was provided.",
					httpException.Message);
			}
		}

		[Test]
		public void OnAuthorization_the_user_with_invalid_credentials_authenticates_successfully()
		{
			// Arrange.
			// Setup the basic authentication data.
			_mockRequestBase.Setup(x =&gt; x.Headers).Returns(new NameValueCollection
			{
				{
					BasicAuthenticationAuthorizeAttribute.AuthorizationRequestHeaderKey,
					ConvertToBasicAuthenticationHeader(InvalidUserName, InvalidPassword)
					}
			});

			// Act.
			try
			{
				_basicAuthenticationAuthorizeAttributeHelper.OnAuthorization(_mockAuthorizationContext.Object);

				Assert.Fail("An exception should be thrown.");
			}
			catch(HttpException httpException)
			{
				Assert.AreEqual((int)HttpStatusCode.Unauthorized, httpException.GetHttpCode());
				Assert.AreEqual(
					"Invalid basic authentication data was provided (eg. UserName/Password combindation doesn't match).",
					httpException.Message);
			}
		}

		[Test]
		public void OnAuthorization_the_user_with_valid_credentials_authenticates_successfully()
		{
			// Arrange.
			// Setup the basic authentication data.
			_mockRequestBase.Setup(x =&gt; x.Headers).Returns(new NameValueCollection
			{
				{
					BasicAuthenticationAuthorizeAttribute.AuthorizationRequestHeaderKey,
					ConvertToBasicAuthenticationHeader(ValidUserName, ValidPassword)
					}
			});

			// Act.
			try
			{
				_basicAuthenticationAuthorizeAttributeHelper.OnAuthorization(_mockAuthorizationContext.Object);
			}
			catch(Exception ex)
			{
				Assert.IsNotNull(ex);
				Assert.Fail("No exceptions should be thrown.");
			}
		}
	}
}</Code>
      <Title>Initial attempt at unit testing my MVCContrib fork :: BasicAuthenticationAuthorizeAttribute tester.</Title>
      <Tags>mvccontrib </Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Pure Krome</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-06-01T22:45:18.06</Entered>
      <Views>33</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>q1an9m</Id>
      <UserId>y6d63uee</UserId>
      <Code>namespace System.DataAnnotations
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.ComponentModel;
    using System.Reflection;
    using System.Globalization;

    public class LocalizedDisplayNameAttribute : System.ComponentModel.DisplayNameAttribute
    {
        private Func&lt;string&gt; messageResourceAccessor;
        
        public LocalizedDisplayNameAttribute(): base(string.Empty)
        { }

        public LocalizedDisplayNameAttribute(string displayName) : base(displayName)
        { }

        public string MessageResourceName
        {
            get;
            set;
        }

        public Type MessageResourceType
        {
            get;
            set;
        }

        public override string DisplayName
        {
            get
            {
                if (!string.IsNullOrEmpty(MessageResourceName) &amp;&amp; MessageResourceType != null)
                {
                    this.SetResourceAccessorByPropertyLookup();
                    return this.messageResourceAccessor();

                }
                return base.DisplayName;
            }
        }

        private void SetResourceAccessorByPropertyLookup()
        {
            if ((this.MessageResourceType == null) || string.IsNullOrEmpty(this.MessageResourceName))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Need Both ResourceType And ResourceName", new object[0]));
            }
            PropertyInfo property = this.MessageResourceType.GetProperty(this.MessageResourceName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
            if (property != null)
            {
                MethodInfo getMethod = property.GetGetMethod(true);
                if ((getMethod == null) || (!getMethod.IsAssembly &amp;&amp; !getMethod.IsPublic))
                {
                    property = null;
                }
            }
            if (property == null)
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Resource Type Does Not Have Property", new object[] { this.MessageResourceType.FullName, this.MessageResourceName }));
            }
            if (property.PropertyType != typeof(string))
            {
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Resource Property Not String Type", new object[] { property.Name, this.MessageResourceType.FullName }));
            }
            this.messageResourceAccessor = delegate
            {
                return (string)property.GetValue(null, null);
            };
        }

    }
}
</Code>
      <Title>Localized DisplayName attribute</Title>
      <Tags>dataannotations, displayname, mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Bruno Figueiredo</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-05-22T16:50:47.807</Entered>
      <Views>176</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>4ogtkm</Id>
      <UserId>zvhzqw76</UserId>
      <Code>// Map content before registering areas
protected void Application_Start()
{
	Content.Map&lt;MyPortableArea&gt;()
		.Master("~/Views/Shared/PA.master")
		.Title("PATitle")
		.Body("PAMain");

	AreaRegistration.RegisterAllAreas();

	RegisterRoutes(RouteTable.Routes);
}

// MyPortableArea (defined in the actual PA) is a class that defines the defaults

public class MyPortableArea : PortableAreaMap
{
	public KEPortableArea()
	{
		DefaultMasterPageLocation = "~/Views/Shared/Site.Master";
		DefaultBodyID = "MainContent";
		DefaultTitleID = "TitleContent";
	}
}
</Code>
      <Title>Mapping MasterPages &amp; ContentPlaceHolders</Title>
      <Tags>MvcContrib, PortableAreas, MasterPages, ContentPlaceHolderID</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>John Nelson</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-05-19T21:33:13.283</Entered>
      <Views>64</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>97yrcp</Id>
      <UserId>8bvgnmef</UserId>
      <Code>private static IEnumerable&lt;Type&gt; FindAllMessageHandlers()
{
	var iMessageHandler = typeof(IMessageHandler);

	var types = from type in AppDomain.CurrentDomain.GetAssemblies().SelectMany(t =&gt; t.GetTypes())
		    let canInstantiate = !type.IsInterface &amp;&amp; !type.IsAbstract &amp;&amp; !type.IsNestedPrivate
		    let isIMessageHandler = type.GetInterface(iMessageHandler.Name) != null
		    where canInstantiate &amp;&amp; isIMessageHandler
		    select type;

	return types;
}


/* became.... */

private static IEnumerable&lt;Type&gt; FindAllMessageHandlers()
{
	var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t =&gt; t.GetTypes());

	var types = allTypes.Where(type =&gt; IsValidType(type));

	return types;
}

public static bool IsValidType(Type type)
{
	if (type.IsInterface || type.IsAbstract || type.IsNestedPrivate)
		return false;

	bool isIMessageHandler = type.GetInterface(typeof(IMessageHandler).Name) != null;

	return isIMessageHandler;
}

</Code>
      <Title>Register MessageHandlers</Title>
      <Tags>MvcContrib, PortableAreas, MessageHandlers</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>John Nelson</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-05-06T19:03:34.793</Entered>
      <Views>65</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>m6xsdi</Id>
      <UserId />
      <Code>slickGrid.AddColumn(
	Column.ForId("riga")
		.Named("Riga")
		.ForField("id")
		.WithEditorFunction("TextCellEditor")
		.WithSetValueHandler("updateItem")
		.WithBehavior(Column.Behavior.selectAndMove)
	).AddColumn(
	Column.ForId("codice")
		.Named("Codice")
		.ForField("code")
		.WithEditorFunction("TextCellEditor")
		.WithSetValueHandler("updateItem")
		.WithBehavior(Column.Behavior.selectAndMove)
	);
</Code>
      <Title>SlickGrid c# fluent wrapper</Title>
      <Tags>slickgrid jquery c# mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Andrea Balducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-04-22T01:50:45.1</Entered>
      <Views>139</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>bjcric</Id>
      <UserId />
      <Code>public override void RegisterArea(AreaRegistrationContext context)
{
    RegisterArea(context,Bus.Instance);
    RegisterAreaEmbeddedResources()
}
</Code>
      <Title>PortableAreaRegistration</Title>
      <Tags>MvcContrib, PortableAreas, AreaRegistration</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>johncoder</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-04-20T20:31:50.52</Entered>
      <Views>60</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>fdeo3j</Id>
      <UserId>1fnw5ygc</UserId>
      <Code>using System;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace MvcSamples.Html
{
	public static class UrlExtensions
	{
		public static bool IsCurrent(this UrlHelper urlHelper, String areaName)
		{
			return urlHelper.IsCurrent(areaName, null, null);
		}

		public static bool IsCurrent(this UrlHelper urlHelper, String areaName, String controllerName)
		{
			return urlHelper.IsCurrent(areaName, controllerName, null);
		}

		public static bool IsCurrent(this UrlHelper urlHelper, String areaName, String controllerName, params String[] actionNames)
		{
			return urlHelper.RequestContext.IsCurrentRoute(areaName, controllerName, actionNames);
		}

		public static string Selected(this UrlHelper urlHelper, String areaName)
		{
			return urlHelper.Selected(areaName, null, null);
		}

		public static string Selected(this UrlHelper urlHelper, String areaName, String controllerName)
		{
			return urlHelper.Selected(areaName, controllerName, null);
		}

		public static string Selected(this UrlHelper urlHelper, String areaName, String controllerName, params String[] actionNames)
		{
			return urlHelper.IsCurrent(areaName, controllerName, actionNames) ? "selected" : String.Empty;
		}
	}

	public static class HtmlExtensions
	{
		public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, String linkText, String actionName, String controllerName)
		{
			var tag = new TagBuilder("li");

			if ( htmlHelper.ViewContext.RequestContext.IsCurrentRoute(null, controllerName, actionName) )
			{
				tag.AddCssClass("selected");
			}

			tag.InnerHtml = htmlHelper.ActionLink(linkText, actionName, controllerName).ToString();

			return MvcHtmlString.Create(tag.ToString());
		}
	}

	public static class RequestExtensions
	{
		public static bool IsCurrentRoute(this RequestContext context, String areaName)
		{
			return context.IsCurrentRoute(areaName, null, null);
		}

		public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName)
		{
			return context.IsCurrentRoute(areaName, controllerName, null);
		}

		public static bool IsCurrentRoute(this RequestContext context, String areaName, String controllerName, params String[] actionNames)
		{
			var routeData = context.RouteData;
			var routeArea = routeData.DataTokens["area"] as String;
			var current = false;

			if ( ((String.IsNullOrEmpty(routeArea) &amp;&amp; String.IsNullOrEmpty(areaName)) || (routeArea == areaName)) &amp;&amp;
				 ((String.IsNullOrEmpty(controllerName)) || (routeData.GetRequiredString("controller") == controllerName)) &amp;&amp;
				 ((actionNames == null) || actionNames.Contains(routeData.GetRequiredString("action"))) )
			{
				current = true;
			}

			return current;
		}
	}
}
</Code>
      <Title>ASP.NET MVC 2 Extension Methods - Where am I?</Title>
      <Tags>ASP.NET, MVC 2</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Bobby Diaz</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-04-08T22:10:10</Entered>
      <Views>205</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>1</CommentCount>
   </Snippet>
   <Snippet>
      <Id>9ejh98</Id>
      <UserId>vvdk11nj</UserId>
      <Code>using System.IO;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;

namespace MyProject.ClassLibrary.Utilities
{
    public class Template
    {
        /// &lt;summary&gt;
        /// Render a Partial View (MVC User Control, .ascx) to a string using the given ViewData.
        /// &lt;/summary&gt;
        /// &lt;param name="controlName"&gt;&lt;/param&gt;
        /// &lt;param name="viewData"&gt;&lt;/param&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        public static string RenderPartialToString(string controlName, object viewData)
        {
            ViewDataDictionary vd = new ViewDataDictionary(viewData);
            ViewPage vp = new ViewPage { ViewData = vd };
            Control control = vp.LoadControl(controlName);

            vp.Controls.Add(control);

            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb))
            {
                using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                {
                    vp.RenderControl(tw);
                }
            }

            return sb.ToString();
        }
    }
}</Code>
      <Title>ASP.NET MVC 2 Render Template to String</Title>
      <Tags>aspnetmvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author />
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-04-06T20:40:27.677</Entered>
      <Views>117</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>9463ay</Id>
      <UserId>gynq4aue</UserId>
      <Code>// controller
public ActionResult Index([DefaultValue(1)] int page)
{
   if (Request.IsAjaxRequest())
      return PartialView("PagedDataControl", model.Data);

   return View(model);
}

// .aspx
$('#pager a').live('click', function(evt) {
	evt.preventDefault();
	$('#tabs-1').load($(this).attr('href'));
});</Code>
      <Title>Asp.Net MVC &amp;&amp; jQuery: degrading ajax pager</Title>
      <Tags>jQuery, AspNetMVC, Html, Ajax</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>andreabalducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-30T10:19:03.17</Entered>
      <Views>87</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>pnhbu1</Id>
      <UserId>gynq4aue</UserId>
      <Code>// Controller Action
        public JsonResult SearchItem(string nature, string term)
        {
            IEnumerable&lt;Item&gt; list = null;

            Transactional(() =&gt;
                              {
                                  switch (nature.ToLowerInvariant())
                                  {
                                      case "ricambi":
                                          list = _itemService.FindSpareParts(term);
                                          break;
                                  }
                              });

            return Json(
                from i in list
                select new
                           {
                               id = i.Id,
                               value = i.Id,
                               label = string.Format("{0} - {1}", i.Id, i.Description),
                               description = i.Description // additional data
                           }
                , JsonRequestBehavior.AllowGet
            );
        }


// js
            $('#Item').autocomplete({
                source: function(request, response) {
                    var url = '&lt;%= Url.Action("SearchItem", "Sdk") %&gt;';
                    // extra param
                    request.nature = 'Ricambi';
                    $.getJSON(url, request, response);
                },
                minLength: 2,
                select: function(event, ui) {
                    console.log(ui);
                    $('#Description').val(ui.item ? ui.item.description : '');
                }
            });</Code>
      <Title>jQuery Autocomplete: extra request params and extra autocomplete data</Title>
      <Tags>jQuery, mvc, autocomplete</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>andreabalducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-29T02:42:23.18</Entered>
      <Views>89</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>wyoyny</Id>
      <UserId>gynq4aue</UserId>
      <Code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Lucilla.Framework.Web.Mvc;
using DemoApp.Services.Model;

namespace DemoApp.WebSite.Controllers
{
    [Authorize]
    public class SdkController : LucillaBaseController
    {
        private readonly ICustomerService _customerService;

        public SdkController(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        public JsonResult SearchCustomer(string term)
        {
            using(BusinessTransactionManager.CreateOrJoinCurrent())
            {
                return Json(from c in _customerService.FindCustomers(term) select new
                    {
                        id = c.Id.CustSupp,
                        value = c.CompanyName,
                    }, JsonRequestBehavior.AllowGet);
            }
        }
    }
}
</Code>
      <Title>Asp.Net MVC &amp;&amp; jQuery autocomplete</Title>
      <Tags>mvc, jquery, autocomplete</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>andreabalducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-26T04:31:17.59</Entered>
      <Views>167</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>7jvdtv</Id>
      <UserId>qi6x3szk</UserId>
      <Code>{
   "Fields":[
      {
         "FieldName":"Name",
         "ReplaceValidationMessageContents":true,
         "ValidationMessageId":"Name_validationMessage",
         "ValidationRules":[
            {
               "ErrorMessage":"Meno musí mať 5 až 40 znakov.",
               "ValidationParameters":{
                  "minimumLength":0,
                  "maximumLength":40
               },
               "ValidationType":"stringLength"
            },
            {
               "ErrorMessage":"The Name field is required.",
               "ValidationParameters":{

               },
               "ValidationType":"required"
            }
         ]
      },
      {
         "FieldName":"Email",
         "ReplaceValidationMessageContents":true,
         "ValidationMessageId":"Email_validationMessage",
         "ValidationRules":[
            {
               "ErrorMessage":"Zadali ste nesprávny e-mail.",
               "ValidationParameters":{
                  "pattern":"^\\w+@[a-zA-Z_]+?\\.[a-zA-Z]{2,3}$"
               },
               "ValidationType":"regularExpression"
            },
            {
               "ErrorMessage":"Zadajte váš e-mail.",
               "ValidationParameters":{

               },
               "ValidationType":"required"
            }
         ]
      },
      {
         "FieldName":"Text",
         "ReplaceValidationMessageContents":true,
         "ValidationMessageId":"Text_validationMessage",
         "ValidationRules":[
            {
               "ErrorMessage":"Správa musí mať 5 až 140 znakov.",
               "ValidationParameters":{
                  "minimumLength":0,
                  "maximumLength":140
               },
               "ValidationType":"stringLength"
            },
            {
               "ErrorMessage":"The Text field is required.",
               "ValidationParameters":{

               },
               "ValidationType":"required"
            }
         ]
      }
   ],
   "FormId":"form0",
   "ReplaceValidationSummary":false
}
</Code>
      <Title>ASP.NET MVC Validation - Rules in JSON</Title>
      <Tags>asp.net, mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Jozef Izso</Author>
      <Language>JavaScript</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-09T07:37:01.393</Entered>
      <Views>118</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>tdzvap</Id>
      <UserId>6ybsj5dj</UserId>
      <Code>// The view: Index.aspx

&lt;!-- the non-AJAX form to filter the list --&gt;
&lt;% using (Html.BeginForm()) { %&gt;
    &lt;fieldset&gt;
    &lt;legend&gt;Search&lt;/legend&gt;
    &lt;input name="SearchTerm" /&gt;
    &lt;input type="submit" value="Go" /&gt;
    &lt;/fieldset&gt;
&lt;% } %&gt;

&lt;!-- the AJAX form to filter the list --&gt;
&lt;script src="/Scripts/MicrosoftAjax.js" 
    type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="/Scripts/MicrosoftMvcAjax.js" 
    type="text/javascript"&gt;&lt;/script&gt;

&lt;% using (Ajax.BeginForm("Index2", 
    new AjaxOptions { UpdateTargetId = "results" })) { %&gt;
    &lt;fieldset&gt;
    &lt;legend&gt;Search&lt;/legend&gt;
    &lt;input name="SearchTerm" /&gt;
    &lt;input type="submit" value="Go" /&gt;
    &lt;/fieldset&gt;
&lt;% } %&gt;

&lt;!-- render the partial inside the view --&gt;
&lt;div id="results"&gt;
    &lt;% Html.RenderPartial("Search", Model); %&gt;
&lt;/div&gt;

// The partial: Search.ascx (a default LIST 
// T4 template, nothing special/custom)</Code>
      <Title>Implement AJAX in MVC (the View)</Title>
      <Tags>C#,AJAX,MVC</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Jerry Nixon</Author>
      <Language>HTML</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-05T09:32:15.357</Entered>
      <Views>182</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>ssjt1i</Id>
      <UserId>6ybsj5dj</UserId>
      <Code>//
// GlossaryController.cs

public ActionResult Index()
{
    return View(Models.Term.SelectAll());
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(FormCollection collection)
{
    // used by non-AJAX form 
    string _SearchTerm;
    _SearchTerm = collection["SearchTerm"];
    // don't indicate the partial here
    // the view will call it
    return View(Models.Term
         .Where(x =&gt; x.Term.Contians(_SearchTerm)));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index2(FormCollection collection)
{
    // used by AJAX form 
    string _SearchTerm;
    _SearchTerm = collection["SearchTerm"];
    // you must indicate the partial here
    // it's all you want to render
    return View("Search", Models.Term
         .Where(x =&gt; x.Term.Contians(_SearchTerm)));
}</Code>
      <Title>Implement AJAX in MVC (the Controller)</Title>
      <Tags>C#,AJAX,MVC</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Jerry Nixon</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-03-05T09:29:03.807</Entered>
      <Views>143</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>qpyny1</Id>
      <UserId>gynq4aue</UserId>
      <Code>&lt;div id="toolbar-pane"&gt;
    &lt;% 
        Toolbar
            .Create()
            .SetCorners(Corners.CornersType.top)
            .AddSet()
                .AddIconButton("btnOpen", "Open", "folder-open")
                .AddIconButton("btnSave", "Save", "disk")
                .AddIconButton("btnDelete", "Delete", "trash")
            .EndSet()
            .AddToggle()
                .AddButton("btnToggleLock", "Lock")
            .EndSet()
            .AddSet()
                .AddIconSolo("btnAddSlide", "Add slide", "plus")
                .AddIconSolo("btnRemoveSlide", "Remove slide", "minus")
                .AddIconSolo("btnAddText", "Add text", "pencil")
                .AddIconSolo("btnAddImage", "Add image", "image")
                .AddIconSolo("btnDeleteSelected", "Delete selected", "trash")
                .AddIconSolo("btnAlignLeft", "Align left", "arrowstop-1-w")
            .EndSet()
            .Render(Writer);
    %&gt;
&lt;/div&gt;</Code>
      <Title>jQuery.Extensions</Title>
      <Tags>jQuery.UI AspNet.MVC </Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>andreabalducci</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-02-24T02:22:00.087</Entered>
      <Views>80</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>cnmgnd</Id>
      <UserId>snk8huzd</UserId>
      <Code>  &lt;Target Name="AfterMerge"&gt;
  &lt;ItemGroup&gt;
    &lt;JsFiles Include="$(TempBuildDir)\Scripts\infinitecarousel.js;$(TempBuildDir)\Scripts\jquery.autocomplete.js;$(TempBuildDir)\Scripts\core.js"/&gt;
    &lt;CssFiles Include="$(TempBuildDir)\Content\reset.css;$(TempBuildDir)\Content\infinitecarousel.css;$(TempBuildDir)\Content\Site.css" /&gt;
  &lt;/ItemGroup&gt;
    
  &lt;ReadLinesFromFile File="%(JsFiles.Identity)"&gt;
    &lt;Output TaskParameter="Lines" 
            ItemName="jsLines"/&gt;
  &lt;/ReadLinesFromFile&gt;
  
  &lt;WriteLinesToFile File="$(TempBuildDir)\Scripts\core.js" 
                    Lines="@(JsLines)" 
                    Overwrite="true" /&gt;
    
  &lt;ReadLinesFromFile File="%(CssFiles.Identity)"&gt;
    &lt;Output TaskParameter="Lines" 
            ItemName="cssLines"/&gt;
  &lt;/ReadLinesFromFile&gt;

  &lt;WriteLinesToFile File="$(TempBuildDir)\Content\core.css" 
                      Lines="@(cssLines)" 
                      Overwrite="true" /&gt;
  &lt;/Target&gt;
 
  &lt;Import Project="$(MSBuildExtensionsPath)\Microsoft\MicrosoftAjax\ajaxmin.tasks" /&gt;
  &lt;Target Name="AfterBuild"&gt;
    &lt;ItemGroup&gt;
      &lt;JS Include="**\Scripts\gasync.js;**\Scripts\core.js" 
          Exclude="**\*.min.js" /&gt;
    &lt;/ItemGroup&gt;
    &lt;ItemGroup&gt;
      &lt;CSS Include="**\Content\core.css" 
           Exclude="**\*.min.css" /&gt;
    &lt;/ItemGroup&gt;

    &lt;AjaxMin JsSourceFiles="@(JS)" 
             JsSourceExtensionPattern="\.js$" 
             JsTargetExtension=".min.js" 
             CssSourceFiles="@(CSS)"
             CssSourceExtensionPattern="\.css$" 
             CssTargetExtension=".min.css" /&gt;

    &lt;ItemGroup&gt;
      &lt;!-- remove our own bespoke files as they are replace with the minified/combined version --&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)web-site_mvc.csproj.user" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)web-site_mvc.sln" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)web-site_mvc.csproj" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\core.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\jquery.autocomplete.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\infinitecarousel.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\jquery-1.4.1.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\gasync.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\jquery-1.4.1-vsdoc.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\MicrosoftAjax.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\MicrosoftAjax.debug.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\MicrosoftAjax.debug.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Scripts\MicrosoftMvcAjax.debug.js" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Content\core.css" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Content\infinitecarousel.css" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Content\Site.css" /&gt;
      &lt;DeleteAfterBuild Include="$(OutputPath)Content\reset.css" /&gt;
    &lt;/ItemGroup&gt;
    &lt;Delete Files="@(DeleteAfterBuild)" /&gt;
    &lt;RemoveDir Directories="$(OutputPath)\obj" /&gt;
  &lt;/Target&gt;</Code>
      <Title>MsBuild Task Combine &amp; Minify</Title>
      <Tags>minify, MSBuild, asp.net, mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>ArranM</Author>
      <Language>XML</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-02-16T14:25:23.133</Entered>
      <Views>458</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>8v7ipq</Id>
      <UserId />
      <Code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Reflection;
using Activity_Search.Code;

namespace Activity_Search.Controllers
{
    public class SearchController : Controller
    {
        // GET: /Search/Activities
        public JsonResult Activities(string q, int limit)
        {
            Regex regex = new Regex(@"(" + q + ")", RegexOptions.IgnoreCase);
            IList&lt;ActivitySearchResultItem&gt; results = new List&lt;ActivitySearchResultItem&gt;();

            // Find all controllers
            IList&lt;Type&gt; controllers = Assembly.GetExecutingAssembly().GetTypes().Where(type =&gt; type.IsSubclassOf(typeof(Controller))).ToList();
            foreach (Type controller in controllers)
            {
                if (results.Count == limit)
                    break;

                // Get all public non-static methods of the controller
                var methods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                foreach (var method in methods)
                {
                    if (results.Count == limit)
                        break;

                    if (method.ReturnType == typeof(ActionResult))
                    {
                        // We don't want to show POST methods
                        var httpPostAttribute = method.GetCustomAttributes(typeof(HttpPostAttribute), true)
                                            .Cast&lt;HttpPostAttribute&gt;()
                                            .FirstOrDefault();

                        // Find the DisplayName attribute
                        var attribute = method.GetCustomAttributes(typeof(ActivitySearchAttribute), true)
                                            .Cast&lt;ActivitySearchAttribute&gt;()
                                            .FirstOrDefault();

                        // Return those results, which:
                        // Are GET method
                        // Have 'DisplayName'
                        // And 'DisplayName' of the action, matches the search criteria
                        if (httpPostAttribute == null &amp;&amp; attribute != null &amp;&amp; regex.IsMatch(attribute.Text))
                        {
                            results.Add(new ActivitySearchResultItem(attribute.Text, Url.Action(method.Name, controller.Name.Replace("Controller", "")), attribute.ImageUrl));
                        }
                    }
                }
            }

            // Return the results in a JSON form
            return Json(results, JsonRequestBehavior.AllowGet);
        }
    }
}</Code>
      <Title>Facebook-like Search Controller</Title>
      <Tags>ASP.NET, MVC, Controller</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author />
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-02-09T05:31:14.173</Entered>
      <Views>80</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>9y7zh5</Id>
      <UserId />
      <Code>    /// &lt;summary&gt;
    /// Extension methods on HtmlHelper and UrlHelper that provide strongly-typed access to URLs and ActionLinks for AccountController actions
    /// &lt;/summary&gt;
    public static class HelperExtensionsForAccountController
    {
        /// &lt;summary&gt;
        /// Html Helpers for Controller = Account
        /// &lt;/summary&gt;
        public static AccountControllerActionLinks Account(this HtmlHelper htmlHelper)
        {
            return new AccountControllerActionLinks(htmlHelper);
        }

        /// &lt;summary&gt;
        /// Url Helpers for Controller = Account
        /// &lt;/summary&gt;
        public static AccountControllerUrls Account(this UrlHelper urlHelper)
        {
            return new AccountControllerUrls(urlHelper);
        }
    }

    /// &lt;summary&gt;
    /// References to all the URLs you'll need to link to any of the actions in this controller
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// This allows you to do =Url.{ControllerName}.LinkTo{ActionName}(params) for example and have strongly typed parameters
    /// and .Action calls are never broken without knowing about it
    /// &lt;/remarks&gt;
    public class AccountControllerUrls
    {
        private UrlHelper urlHelper;
        public AccountControllerUrls(UrlHelper urlHelper)
        {
            this.urlHelper = urlHelper;
        }

        public string LinkToHome() { return urlHelper.Action("Home", "Account", new { }); }

        public string LinkToLogin() { return urlHelper.Action("Home", "Login", new { }); }

        public string LinkToUpgrade (Account account, Project project, Slide slide) 
        { 
            return urlHelper.Action("Upgrade", "Account", new { Account = account, Project = project, Slide = slide }); 
        }

        // etc., one method for each Action that you want to link to in any View
    }

    /// &lt;summary&gt;
    /// ActionLinks for all the URLs you'll need to link to any of the actions in this controller
    /// &lt;/summary&gt;
    /// &lt;remarks&gt;
    /// This allows you to do =Html.{ControllerName}.LinkTo{ActionName}(params) for example and have strongly typed parameters
    /// it also means you can refactor easily because your code is not littered with strings for the Controller Name or the Action Names
    /// and ActionLinks are never broken without knowing about it
    /// &lt;/remarks&gt;
    public class AccountControllerActionLinks
    {
        private HtmlHelper htmlHelper;
        public AccountControllerActionLinks(HtmlHelper htmlHelper)
        {
            this.htmlHelper = htmlHelper;
        }

        public MvcHtmlString ActionLinkForHome(string linkText, Account account) { return htmlHelper.ActionLink(linkText, "Home", "Account"); }

        public MvcHtmlString ActionLinkForLogin(string linkText, Account account) { return htmlHelper.ActionLink(linkText, "Login", "Account"); }

        public MvcHtmlString ActionLinkForUpgrade(string linkText, Account account) { return htmlHelper.ActionLink(linkText, "Upgrade", "Account", new { Account = account, Project = new Project() { ProjectUID = 5 }, Slide = new Slide() { SlideUID = 2 } }, null); }

        // etc., one method for each Action that you want to link to in any View
    }


IN A VIEW YOU CAN THEN DO ... AND HAVE FULL INTELLISENSE AS YOU TYPE:

LINK = &lt;%=Url.Account().LinkToUpgrade(this.Model.Account, this.Model.Project, this.Model.Slide) %&gt;
A LINK = &lt;%=Html.Account().ActionLinkForUpgrade("Click to upgrade", this.Model.Account)%&gt;




</Code>
      <Title>Strongly typed extensions for htmlHelper and urlHelper to Action methods on a Controller</Title>
      <Tags>ASP.NET, MVC, strongly typed</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Ian</Author>
      <Language>NoFormat</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-02-07T19:29:00.277</Entered>
      <Views>339</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>cw8ie4</Id>
      <UserId />
      <Code>       [Test]
       public void Should_create_a_new_meeting()
       {
           _webBrowser.ScreenCaptureOnFailure(() =&gt;
              {
                  Form&lt;LoginInputProxy&gt;("/login/login/index")
                      .Input(m =&gt; m.Username, "admin")
                      .Input(m =&gt; m.Password, "password")
                      .Submit();
                   
                  Form&lt;MeetingInput&gt;(GetUrl("meeting", "new"))
                      .Input(m =&gt; m.Name, "TX")
                      .Input(m =&gt; m.Topic, "my topic")
                      .Input(m =&gt; m.Summary, "this will be a normal meeting")
                      .Input(m =&gt; m.Description, "The description")
                      .Input(m =&gt; m.Key, Guid.NewGuid().ToString())
                      .Input(m =&gt; m.LocationName, "our location")
                      .Input(m =&gt; m.LocationUrl, "http://foolocation.com")
                      .Input(m =&gt; m.SpeakerBio, "this is a great speaker")
                      .Input(m =&gt; m.SpeakerName, "bart simpson")
                      .Input(m =&gt; m.SpeakerUrl, "http://thesimpsons.com")
                      .Input(m =&gt; m.TimeZone, "CST")
                      .Input(m =&gt; m.StartDate, "12/11/2010 12:00 pm")
                      .Input(m =&gt; m.EndDate, "12/11/2010 1:00 pm")
                      .Submit();
                  
                  _webBrowser.Url.ShouldBe("/home");
              });
       }

       [Test]
       public void Should_require_fields()
       {
           _webBrowser.ScreenCaptureOnFailure(() =&gt;
           {
               Form&lt;LoginInputProxy&gt;("/login/login/index")
                   .Input(m =&gt; m.Username, "admin")
                   .Input(m =&gt; m.Password, "password")
                   .Submit();

               Form&lt;MeetingInput&gt;("/Meeting/New")
                   .Input(m =&gt; m.Name, "foo")
                   .Submit();

               _webBrowser.UrlShouldBe("/meetinG/ediT");
               _webBrowser.ValidationSummaryExists();
               _webBrowser.ValidationSummaryContainsMessageFor&lt;MeetingInput&gt;(m =&gt; m.Topic);
               _webBrowser.AssertValue&lt;MeetingInput&gt;(m =&gt; m.Name, "foo");
           });
       }

</Code>
      <Title>Sneak Peek of MvcContrib UI Test Helper syntax for testing your Strongly Typed MVC Views.</Title>
      <Tags>mvccontrib, mvc, asp.net mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>eric hexter</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-01-28T21:39:42.283</Entered>
      <Views>334</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>jx8rag</Id>
      <UserId>288r5dv6</UserId>
      <Code>public enum StyleConditions {
   IE6OrLess, IE7OrLess
}

public static class HtmlHelpers {
   #region Image
   public static string Image(this HtmlHelper helper, string route, string action, int id, int height, int width, int imageType,
      string altText, string cssClass) {
      var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
      var imageUrl = urlHelper.RouteUrl(route, new RouteValueDictionary(new {
         action = action,
         id = id,
         height = height,
         width = width,
         imageType = imageType
      }));

      var imgTag = new TagBuilder("img");
      imgTag.MergeAttribute("src", imageUrl.ToLower());
      imgTag.MergeAttribute("height", height.ToString());
      imgTag.MergeAttribute("width", width.ToString());

      if (altText != null)
         imgTag.MergeAttribute("alt", altText);

      if (cssClass != null)
         imgTag.AddCssClass(cssClass);

      return imgTag.ToString(TagRenderMode.SelfClosing);
   }
   #endregion

   #region Meta
   public static string MetaTag(this HtmlHelper helper, string name, string content) {
      var metaTag = new TagBuilder("meta");
      metaTag.MergeAttribute("content", content);
      metaTag.MergeAttribute("name", name);

      return metaTag.ToString(TagRenderMode.SelfClosing);
   }
   #endregion

   #region Style Tag
   public static string StyleTag(this HtmlHelper helper, string href, string condition) {
      var styleTag = new TagBuilder("link");
      styleTag.MergeAttribute("href", href.ToLower());
      styleTag.MergeAttribute("rel", "stylesheet");
      styleTag.MergeAttribute("type", "text/css");

      var html = styleTag.ToString(TagRenderMode.SelfClosing);
      if (condition != null)
         html = String.Format("&lt;!--[if {0}]&gt;{1}&lt;![endif]--&gt;", condition, html);

      return html;
   }

   public static string StyleTag(this HtmlHelper helper, string href, StyleConditions styleCondition) {
      string condition;
      switch (styleCondition) {
         case StyleConditions.IE6OrLess:
            condition = "lt IE 7";
            break;
         case StyleConditions.IE7OrLess:
            condition = "lt IE 8";
            break;
         default:
            throw new NotImplementedException("StyleCondition not implemented.");
      }

      return StyleTag(helper, href, condition);
   }

   public static string StyleTag(this HtmlHelper helper, string href) {
      return StyleTag(helper, href, null);
   }
   #endregion

   #region Script Tag
   public static string ScriptTag(this HtmlHelper helper, string src) {
      var scriptTag = new TagBuilder("script");
      scriptTag.MergeAttribute("src", src.ToLower());
      scriptTag.MergeAttribute("type", "text/javascript");

      return scriptTag.ToString(TagRenderMode.Normal);
   }
   #endregion

   #region Recaptcha
   public static string GenerateCaptcha(this HtmlHelper helper, string theme, string publicKey, string privateKey) {
      if (helper.ViewContext.HttpContext.Request.IsAjaxRequest())
         return helper.GenerateAjaxCaptcha(theme, publicKey);

      var captchaControl = new RecaptchaControl {
         ID = "recaptcha",
         Theme = theme,
         PublicKey = publicKey,
         PrivateKey = privateKey
      };

      var htmlWriter = new HtmlTextWriter(new StringWriter());
      captchaControl.RenderControl(htmlWriter);

      return htmlWriter.InnerWriter.ToString();
   }

   public static string GenerateAjaxCaptcha(this HtmlHelper helper, string theme, string publicKey) {
      var htmlWriter = new HtmlTextWriter(new StringWriter());

      htmlWriter.WriteLine("&lt;script src=\"http://api.recaptcha.net/js/recaptcha_ajax.js\" type=\"text/javascript\"/&gt;");
      htmlWriter.WriteLine("&lt;div id=\"recaptchaAjax\"&gt;&lt;/div&gt;");
      htmlWriter.WriteLine("&lt;script type=\"text/javascript\"&gt;");
      htmlWriter.WriteLine("Recaptcha.create(\"" + publicKey + "\", \"recaptchaAjax\", { theme: \"" + theme + "\" });");
      htmlWriter.WriteLine("&lt;/script&gt;");

      return htmlWriter.InnerWriter.ToString();
   }
   #endregion

   #region Repeater
   // Based on http://haacked.com/archive/2008/05/03/code-based-repeater-for-asp.net-mvc.aspx

   public static void Repeater&lt;T&gt;(this HtmlHelper html, IList&lt;T&gt; items,
      Action&lt;T, string&gt; render, Action renderIfEmpty, string cssClass, string cssClassAlt) {
      if (items.IsNullOrEmpty()) {
         renderIfEmpty();
      }
      else {
         int i = 0;
         items.ForEach(item =&gt; {
            render(item, (i++ % 2 == 0) ? cssClass : cssClassAlt);
         });
      }
   }

   public static void Repeater&lt;T&gt;(this HtmlHelper html, IList&lt;T&gt; items,
      Action&lt;T, string&gt; render, Action renderIfEmpty) {
      Repeater&lt;T&gt;(html, items, render, renderIfEmpty, "", "alt");
   }

   public static void Repeater&lt;T&gt;(this HtmlHelper html, string viewDataKey,
      Action&lt;T, string&gt; render, Action renderIfEmpty, string cssClass, string cssClassAlt) {
      var items = GetViewDataAsList&lt;T&gt;(html, viewDataKey);
      Repeater&lt;T&gt;(html, items, render, renderIfEmpty, cssClass, cssClassAlt);
   }

   public static void Repeater&lt;T&gt;(this HtmlHelper html, string viewDataKey,
      Action&lt;T, string&gt; render, Action renderIfEmpty) {
      var items = GetViewDataAsList&lt;T&gt;(html, viewDataKey);
      Repeater&lt;T&gt;(html, items, render, renderIfEmpty);
   }

   static IList&lt;T&gt; GetViewDataAsList&lt;T&gt;(HtmlHelper html, string viewDataKey) {
      var items = html.ViewContext.ViewData as IList&lt;T&gt;;
      var viewData = html.ViewContext.ViewData as IDictionary&lt;string, object&gt;;
      if (viewData != null) {
         items = viewData[viewDataKey] as IList&lt;T&gt;;
      }
      else {
         items = new ViewDataDictionary(viewData)[viewDataKey]
           as IList&lt;T&gt;;
      }
      return items;
   }
   #endregion
}
</Code>
      <Title>Html Helpers</Title>
      <Tags>c#, html-helpers, asp.net, mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Richard Kimber</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-01-20T13:16:58.417</Entered>
      <Views>423</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>o87fsn</Id>
      <UserId />
      <Code>[Test]
     public void Testing()
     {
         FormCollection form = new FormCollection()
         {
             { "foo", "bar" },
             { "lazy", "susan" }

         };

         var stuff = form.ToValueProvider();  // &lt;-- Bombs here with Missing Method Exception 

         //var bindingContext = new ModelBindingContext()
         //{
         //    ModelName = "CustomerModel",
         //    ValueProvider = form.ToValueProvider()
         //};

         //Assert.IsTrue(bindingContext != null); 
     }
</Code>
      <Title />
      <Tags>mvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author />
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2010-01-14T06:10:49.567</Entered>
      <Views>115</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>nhkeki</Id>
      <UserId>cfpj7acm</UserId>
      <Code>&lt;% using(Html.BeginForm&lt;AccountController&gt;( x=&gt; x.ChangeEmailAddress(), FormMethod.Post, new { enctype = "multipart/form-data", id= "ChangeEmailAddressForm" })) { %&gt;
	    &lt;div id="ErrorDiv" style="display:none;"&gt;&lt;/div&gt;
		&lt;h3&gt;All fields are required&lt;/h3&gt;
		!{Html.EditorFor(Model =&gt; Model)}
	&lt;% } %&gt;</Code>
      <Title>Spark tastes so good!</Title>
      <Tags>spark asp-netmvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Eric Polerecky</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2009-12-21T15:38:32</Entered>
      <Views>89</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
   <Snippet>
      <Id>8iubvk</Id>
      <UserId />
      <Code>public class CsvActionResult : ActionResult
{
    public IEnumerable ModelListing { get; set; }

    public CsvActionResult(IEnumerable modelListing)
    {
        ModelListing = modelListing;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        byte[] data = new CsvFileCreator().AsBytes(ModelListing);
        new FileContentResult(data, "text/csv").ExecuteResult(context);
        
    }
}

</Code>
      <Title>CSV Action Result Example</Title>
      <Tags>aspnetmvc</Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Eric Hexter</Author>
      <Language>C#</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2009-12-13T15:45:20.11</Entered>
      <Views>243</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>1</CommentCount>
   </Snippet>
   <Snippet>
      <Id>ffrgqf</Id>
      <UserId>514ru5ce</UserId>
      <Code>Sub ToggleMvcBuildViews()
    DTE.ExecuteCommand("Project.UnloadProject")
    DTE.ExecuteCommand("OtherContextMenus.StubProject.EditProjectFile")

    Dim wasSetToTrue As Boolean = SetMvcBuildView(True)
    Dim wasSetToFalse As Boolean
    If Not wasSetToTrue Then
        wasSetToFalse = SetMvcBuildView(False)
    End If

    If (wasSetToTrue Or wasSetToFalse) Then
        DTE.ActiveDocument.Save()
    End If

    DTE.ActiveDocument.Close()
    DTE.ExecuteCommand("Project.ReloadProject")

    Dim msgBoxTitle As String = "Toggle MvcBuildViews"
    If wasSetToTrue Then
        MsgBox("MvcBuildViews property was set to True", Title:=msgBoxTitle)
    ElseIf wasSetToFalse Then
        MsgBox("MvcBuildViews property was set to False", Title:=msgBoxTitle)
    Else
        MsgBox("Unexpected Error: Unable to toggle MvcBuildViews property", Title:=msgBoxTitle)
    End If
End Sub

Function SetMvcBuildView(ByVal value As Boolean) As Boolean
    DTE.ExecuteCommand("Edit.Replace")

    Dim findResult As vsFindResult
    findResult = DTE.Find.FindReplace(vsFindAction.vsFindActionReplaceAll, _
        FindWhat:="&lt;MvcBuildViews&gt;" &amp; IIf(value, "false", "true").ToString() &amp; "&lt;/MvcBuildViews&gt;", _
        vsFindOptionsValue:=(vsFindOptions.vsFindOptionsFromStart Or vsFindOptions.vsFindOptionsMatchCase), _
        ReplaceWith:="&lt;MvcBuildViews&gt;" &amp; IIf(value, "true", "false").ToString() &amp; "&lt;/MvcBuildViews&gt;", _
        Target:=vsFindTarget.vsFindTargetCurrentDocument, _
        ResultsLocation:=vsFindResultsLocation.vsFindResultsNone)

    SetMvcBuildView = True
    If (findResult = vsFindResult.vsFindResultNotFound) Then
        SetMvcBuildView = False
    End If

    ' close find/replace dialog
    DTE.Windows.Item("{CF2DDC32-8CAD-11D2-9302-005345000000}").Close()
End Function</Code>
      <Title>Visual Studio macro to toggle the MvcBuildViews value</Title>
      <Tags>.NET, VisualStudio, ASP.NET MVC, Macro </Tags>
      <IsPrivate>false</IsPrivate>
      <ShowLineNumbers>false</ShowLineNumbers>
      <Author>Al Gonzalez</Author>
      <Language>VB.NET</Language>
      <IsAbuse>false</IsAbuse>
      <Entered>2009-12-08T21:31:39.267</Entered>
      <Views>179</Views>
      <IsTemporary>false</IsTemporary>
      <CommentCount>0</CommentCount>
   </Snippet>
</ArrayOfSnippet>