Skip to content

Instantly share code, notes, and snippets.

View danielgreen's full-sized avatar

Daniel Green danielgreen

  • Glasgow, United Kingdom
View GitHub Profile
@danielgreen
danielgreen / GarberIrish.js
Created May 30, 2013 11:30
Garber-Irish JavaScript implementation. Provides a way to execute script, on page load, based on the MVC controller and action that produced the page. This is a DOM-routing approach. It can help pages to avoid explicitly referencing numerous JS files. See http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution
/* Contains general scripts that may be used in any page.
* If this file starts to get large it can be split into page-specific files. */
/* The following code is the Garber-Irish implementation, a way to run relevant JavaScript on page-load
* based on the MVC action that produced the page. It's an unobtrusive approach, which means that the
* code to call the relevant JavaScript functions is all here instead of being hardcoded into the HTML.
* All this code needs from the page is data-controller and data-action attributes on the body tag.
* Since JavaScript is case-sensitive, the controller and action names we use here must be an exact match.
* http://viget.com/inspire/extending-paul-irishs-comprehensive-dom-ready-execution */
@danielgreen
danielgreen / AvailableAttribute.cs
Created May 30, 2013 08:33
General extension methods for Exceptions, Enums, etc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Utility
{
public class AvailableAttribute : Attribute
{
public AvailableAttribute(bool available) { this.Available = available; }
@danielgreen
danielgreen / MVCExtensions.cs
Created May 30, 2013 07:47
Some MVC-specific extension methods. The built-in LabelFor methods do not allow you to specify HTML attributes to be applied to the label element, so these LabelFor extensions plug the gap.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Linq.Expressions;
namespace Web.Extensions
{
@danielgreen
danielgreen / CheckApplicationOfflineAttribute.cs
Created May 29, 2013 15:49
A filter (which should be used as a global filter) to check whether the application is configured as offline, and throw an exception if this is the case. This is an alternative to placing a file named App_Offline.htm in the application's root. Using App_Offline.htm affects all users, cannot be selectively bypassed as in this case, and does not a…
using System;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;
namespace Web.Filters
{
/// <summary>
/// Check whether the application is marked as offline in the config file.
/// If so, and the user does not have the override permission, throw an exception.
@danielgreen
danielgreen / PreserveModelStateOnRedirect.cs
Created May 29, 2013 15:42
If an MVC action has detected validation errors in the model, the errors are held in ModelState. If the action returns a view containing the model, and the jQuery Validate plugin is present on the page, the validation errors are displayed. If the MVC action performs a redirect, however, the model validation errors are lost. Use the PreserveModel…
using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Mvc;
/* Based on the ModelStateToTempDataAttribute class from MVCContrib */
namespace Web.Filters
{
/// <summary>
/// When a RedirectResult or RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData.
@danielgreen
danielgreen / ELMAH-1.2-db-SQLServer.sql
Last active December 17, 2015 20:58
ELMAH.MVC is a useful NuGet package that provides an HTTP module to automatically log unhandled ("Yellow Screen Of Death") exceptions in your website, and provides a page (elmah.axd) to allow the exceptions to be reviewed. However, your MVC project is likely to use the built-in HandleErrorAttribute filter which, when custom errors are enabled, c…
/*
ELMAH - Error Logging Modules and Handlers for ASP.NET
Copyright (c) 2004-9 Atif Aziz. All rights reserved.
Author(s):
Atif Aziz, http://www.raboof.com
Phil Haacked, http://haacked.com
@danielgreen
danielgreen / PreventAjaxCaching.js
Created May 29, 2013 14:48
Prevent Ajax GET and HEAD calls from receiving cached results. This approach appends a timestamp to the query string to defeat web server caching. See http://api.jquery.com/jQuery.ajax and http://api.jquery.com/jQuery.ajaxSetup. Another approach is to amend server-side code to set an HTTP header such as Expires.
// Disable caching globally, for all Ajax requests
$.ajaxSetup ({
cache: false
});
// Make an Ajax request with caching explicitly disabled
$.ajax({
type: "GET",
cache: false,
url: "http://example.com/GetSomeData"
@danielgreen
danielgreen / FormatJavaScriptDate.js
Created May 29, 2013 14:39
Formatting JavaScript dates. Unashamedly nicked from https://gist.github.com/atesgoral/1005948 via http://www.140byt.es/keywords/date. See the linked Gist for more documentation. Alternatively see www.datejs.com and momentjs.com
function formatDate (d,f){return f.replace(/{(.+?)(?::(.*?))?}/g,function(v,c,p){for(v=d["get"+c]()+/h/.test(c)+"";v.length<p;v=0+v);return v})}
// Formats the date as a string e.g. "24/08/2013 17:04"
var formattedDate = formatDate(parsedDate, "{Date:2}/{Month:2}/{FullYear} {Hours:2}:{Minutes:2}");
//Instead of using classical format specifiers like "YYYY", "MM", "HH", "mm" etc.
//this function uses the Date instance getters like getFullYear, getMonth, etc.
//with support for zero-padding.
//For example, instead of:
@danielgreen
danielgreen / ParseJSONDates.js
Last active March 8, 2021 22:26
When an ASP.NET MVC 4 action returns JSON containing a DateTime value, the value is serialized into a format that cannot be natively understood by JavaScript. Here is some code to process the value into a JavaScript Date. A better solution than this is to use JSON.NET to serialize dates instead. See https://gist.github.com/danielgreen/5669903
function dateTimeReviver (key, value) {
var a;
if (typeof value === 'string') {
a = /\/Date\((\d*)\)\//.exec(value);
if (a) {
return new Date(+a[1]);
}
}
return value;
}
@danielgreen
danielgreen / invalidHandler.UnobtrusiveValidation.js
Created May 29, 2013 14:02
When using jQuery Validate, you may want to run some code when it detects that the form is invalid. When using Unobtrusive Validation, you don't have the ability to set invalidHandler directly when initialising the Validate plugin, so here is a workaround.
// If using Unobtrusive Validation then that library initialised the Validate plugin
// on our behalf, so we missed the chance to set invalidHandler. Even if we were to
// set invalidHandler now via the settings object it would have no effect, due to the
// way that Validate works internally. Instead, we can do the following:
$("#MyForm").bind("invalid-form.validate", function () {
// Do something useful e.g. display the Validation Summary in a popup dialog
$("div.ValSummary").dialog({
title: "Information",
modal: true,
resizable: false,