index.html
<script src="scripts/require.js" data-main="scripts/lib/main.js"></script>
main.js
require(["Order"], function(Order){
var o = new Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
Order.js
define('"Customer"], // Required scripts (Customer)
function(Customer){ // Get Required objects
function Order(id, custName){
this.id = id;
this.customer = new Customer(custName);
}
return Order;
}
);
Customer.js
define([],
function(){
function Customer(name){
this.name = name;
}
return Customer;
}
);
Saturday, October 20, 2012
Javascript Namespace
main.js
$(function(){
var o = new ProjectNS.Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
order.js
(function(ns){
ns.Order = function(id, custName){
this.id = id,
this.customer = new ns.Customer(custName)
};
}(window.ProjectNS = window.ProjectNS || {}));
Customer.js
(function(ns){
ns.Customer = function(name){
this.name = name
};
}(window.ProjectNS = window.ProjectNS || {}));
$(function(){
var o = new ProjectNS.Order(1, "A Customer");
alert(o.id);
alert(o.customer.name);
});
order.js
(function(ns){
ns.Order = function(id, custName){
this.id = id,
this.customer = new ns.Customer(custName)
};
}(window.ProjectNS = window.ProjectNS || {}));
Customer.js
(function(ns){
ns.Customer = function(name){
this.name = name
};
}(window.ProjectNS = window.ProjectNS || {}));
Wednesday, September 26, 2012
Modular Javascript with RequireJS
<script data-main="/scripts/main" src="/scripts/require.js" type="text/javascript"></script>
main.js
(function(){
requirejs.config(
baseUrl: 'scripts',
paths:{
'jquery': 'jquery-1.7.2'
}
);
require(['alerter'],
function(alerter){
alerter.showMessage();
});
})();
alerter.js
define('alerter',
['jquery', 'dataservice'],
function($, dataservice){
var name = 'John',
showMessage = function(){
var msg = dataservice.getMessage();
$('#messagebox').text(msg + ', ' + name);
};
return{
showMessage: showMessage
};
});
dataservice.js
define('dataservice',
[],
function(){
var
msg = 'Welcome to Code Camp',
getMessage = function(){
return msg;
};
return{
getMessage: getMessage
};
});
main.js
(function(){
requirejs.config(
baseUrl: 'scripts',
paths:{
'jquery': 'jquery-1.7.2'
}
);
require(['alerter'],
function(alerter){
alerter.showMessage();
});
})();
alerter.js
define('alerter',
['jquery', 'dataservice'],
function($, dataservice){
var name = 'John',
showMessage = function(){
var msg = dataservice.getMessage();
$('#messagebox').text(msg + ', ' + name);
};
return{
showMessage: showMessage
};
});
dataservice.js
define('dataservice',
[],
function(){
var
msg = 'Welcome to Code Camp',
getMessage = function(){
return msg;
};
return{
getMessage: getMessage
};
});
Modular Javascript Without RequireJS
dataservice.js
var dataservice = (function(){
var
msg = 'Welcome to Code Camp',
getMessage = function(){
return msg;
};
return{
getMessage: getMessage
};
})();
alerter.js
var alerter = (function (dataservice){
var
name = 'John',
showMessage = function(){
var msg = dataservice.getMessage();
alert(msg + ', ' + name);
};
return{
showMessage: showMessage
};
})(dataservice);
main.js
(function (alerter){
alerter.showMessage();
})(alerter);
var dataservice = (function(){
var
msg = 'Welcome to Code Camp',
getMessage = function(){
return msg;
};
return{
getMessage: getMessage
};
})();
alerter.js
var alerter = (function (dataservice){
var
name = 'John',
showMessage = function(){
var msg = dataservice.getMessage();
alert(msg + ', ' + name);
};
return{
showMessage: showMessage
};
})(dataservice);
main.js
(function (alerter){
alerter.showMessage();
})(alerter);
Wednesday, September 19, 2012
Issue: Nuget.Config is corrupted
Issue: C:\Users\Administrator\AppData\Roaming\NuGet\Nuget.Config is corrupted.
Solution: Edit the Nuget.Config with the following text.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</packageSources>
<activePackageSource>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</activePackageSource>
</configuration>
Solution: Edit the Nuget.Config with the following text.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</packageSources>
<activePackageSource>
<add key="NuGet official package source" value="https://go.microsoft.com/fwlink/?LinkID=230477" />
</activePackageSource>
</configuration>
Friday, September 7, 2012
Issue: No implicit conversion between int and null
Issue: No implicit conversion between int and null
Solution:
int value = 999999;
int? result;
result = (value > 0) ? (int?)value : null;
Solution:
int value = 999999;
int? result;
result = (value > 0) ? (int?)value : null;
Thursday, September 6, 2012
LINQ .ToArray().Aggregate() Function
Method 1 (OLD):
var stringVar = new StringBuilder();
foreach (var item in itemsCollection)
{
stringVar.Append(item.PROPERTY + ", ");
}
if (codes.Length > 0)
{
stringVar.Remove(item.PROPERTY - 2, 2);
}
else
{
stringVar.Append("None");
}
return stringVar.ToString();
Method 2 (PREFERRED):
return itemsCollection.Any() ? itemsCollection.ToArray().Aggregate((first, second) => first + ", " + second) : "None";
var stringVar = new StringBuilder();
foreach (var item in itemsCollection)
{
stringVar.Append(item.PROPERTY + ", ");
}
if (codes.Length > 0)
{
stringVar.Remove(item.PROPERTY - 2, 2);
}
else
{
stringVar.Append("None");
}
return stringVar.ToString();
Method 2 (PREFERRED):
return itemsCollection.Any() ? itemsCollection.ToArray().Aggregate((first, second) => first + ", " + second) : "None";
Issue: Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.
Issue:
Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.
Solution:
Use .AsEnumerable() before .Select()
For example:
Table.Where(x=>...)
.AsEnumerable()
.Select(x=>...);
Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting Entity Data Model primitive types.
Solution:
Use .AsEnumerable() before .Select()
For example:
Table.Where(x=>...)
.AsEnumerable()
.Select(x=>...);
Wednesday, September 5, 2012
T-SQL Drop and Re-create Unique Constraint
ALTER TABLE [dbo].[TABLE_NAME]
DROP CONSTRAINT [UNIQUE_KEY_NAME]
GO
ALTER TABLE [dbo].[TABLE_NAME]
ADD CONSTRAINT [UNIQUE_KEY_NAME] UNIQUE NONCLUSTERED
(
[COLUMN_ID_1] ASC,
[COLUMN_ID_2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
DROP CONSTRAINT [UNIQUE_KEY_NAME]
GO
ALTER TABLE [dbo].[TABLE_NAME]
ADD CONSTRAINT [UNIQUE_KEY_NAME] UNIQUE NONCLUSTERED
(
[COLUMN_ID_1] ASC,
[COLUMN_ID_2] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
Saturday, September 1, 2012
Move SQL Server 2008 Databases
use master
go
sp_detach_db 'mydb'
go
sp_attach_db 'ShowsTix',
'C:\Data\mydb_log.ldf',
'C:\Data\mydb.mdf'
go
use mydb
go
sp_helpfile
go
Friday, August 31, 2012
dhtmlx TreeGrid
mygrid.setCellExcellType(100000, 2, "ro");
mygrid.setItemImage(100000, "blank.gif");
rowId = 100000
column index = 2
ro = read-only
mygrid.setItemImage(100000, "blank.gif");
rowId = 100000
column index = 2
ro = read-only
Friday, August 24, 2012
CI Build File and Web Application Deployment
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0"
DefaultTargets="Compile">
<UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\AsyncExec.dll" TaskName="AsyncExec.AsyncExec"/>
<UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll" TaskName="MSBuild.Community.Tasks.XmlRead" />
<ItemGroup>
<SolutionRoot Include="."/>
<BuildArtifacts Include=".\buildartifacts\"/>
<SolutionFile Include="..\src\Project.sln"/>
<MsDeploy Include="..\src\packages\MSdeploy2\msdeploy.exe"/>
<PackageFile Include=".\buildartifacts\package\Project.zip"/>
<Website Include=".\buildartifacts\_PublishedWebsites\Project.Website"/>
</ItemGroup>
<Target Name="Clean">
<RemoveDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Init" DependsOnTargets="Clean">
<MakeDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Compile" DependsOnTargets="Init">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
</PropertyGroup>
<MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);
Configuration=$(Configuration)"/>
</Target>
<Target Name="Package" DependsOnTargets="Compile">
<PropertyGroup>
<PackageDir>%(PackageFile.RootDir)%(PackageFile.Directory)</PackageDir>
<Source>%(Website.FullPath)</Source>
<Destination>%(PackageFile.FullPath)</Destination>
</PropertyGroup>
<MakeDir Directories="$(PackageDir)"/>
<Exec Command='"@(MsDeploy)" -verb:sync -source:iisApp="$(Source)" -dest:package="$(Destination)"'/>
</Target>
<Target Name="DeployToDev" DependsOnTargets="Package">
<PropertyGroup>
<WebServerName>DEVSERVER</WebServerName>
<Source>%(PackageFile.FullPath)</Source>
</PropertyGroup>
<Exec Command='"@(MsDeploy)" -verb:sync -source:package="$(Source)" -dest:iisApp="Default Web Site", computerName=$(WebServerName),username=,password='/>
</Target>
</Project>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
ToolsVersion="4.0"
DefaultTargets="Compile">
<UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\AsyncExec.dll" TaskName="AsyncExec.AsyncExec"/>
<UsingTask AssemblyFile="C:\svn\project\src\packages\ThirdParty\MSBuildCommunityTasks\MSBuild.Community.Tasks.dll" TaskName="MSBuild.Community.Tasks.XmlRead" />
<ItemGroup>
<SolutionRoot Include="."/>
<BuildArtifacts Include=".\buildartifacts\"/>
<SolutionFile Include="..\src\Project.sln"/>
<MsDeploy Include="..\src\packages\MSdeploy2\msdeploy.exe"/>
<PackageFile Include=".\buildartifacts\package\Project.zip"/>
<Website Include=".\buildartifacts\_PublishedWebsites\Project.Website"/>
</ItemGroup>
<Target Name="Clean">
<RemoveDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Init" DependsOnTargets="Clean">
<MakeDir Directories="@(BuildArtifacts)"/>
</Target>
<Target Name="Compile" DependsOnTargets="Init">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
</PropertyGroup>
<MSBuild Projects="@(SolutionFile)" Properties="OutDir=%(BuildArtifacts.FullPath);
Configuration=$(Configuration)"/>
</Target>
<Target Name="Package" DependsOnTargets="Compile">
<PropertyGroup>
<PackageDir>%(PackageFile.RootDir)%(PackageFile.Directory)</PackageDir>
<Source>%(Website.FullPath)</Source>
<Destination>%(PackageFile.FullPath)</Destination>
</PropertyGroup>
<MakeDir Directories="$(PackageDir)"/>
<Exec Command='"@(MsDeploy)" -verb:sync -source:iisApp="$(Source)" -dest:package="$(Destination)"'/>
</Target>
<Target Name="DeployToDev" DependsOnTargets="Package">
<PropertyGroup>
<WebServerName>DEVSERVER</WebServerName>
<Source>%(PackageFile.FullPath)</Source>
</PropertyGroup>
<Exec Command='"@(MsDeploy)" -verb:sync -source:package="$(Source)" -dest:iisApp="Default Web Site", computerName=$(WebServerName),username=,password='/>
</Target>
</Project>
Thursday, August 9, 2012
Tuesday, July 10, 2012
ASP.NET MVC Remote Validation
public class TimeCard : IValidatableObject
{
...
[Remote("CheckUserName", "Home", ErrorMessage="Username is invalid")]
public string UserName{get; set;}
...
}
public class HomeController : Controller
{
...
public JsonResult CheckUsername(string username)
{
var result = false;
if(username == "tkhuc")
{
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
{
...
[Remote("CheckUserName", "Home", ErrorMessage="Username is invalid")]
public string UserName{get; set;}
...
}
public class HomeController : Controller
{
...
public JsonResult CheckUsername(string username)
{
var result = false;
if(username == "tkhuc")
{
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
ASP.NET MVC Custom Client Validation
Implement IClientValidatable
Implement a jQuery validation method
Implement an unobtrusive adapter
public class GreaterThanDateAttribute : ValidationAttribute, IClientValidatable
{
...
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "greater";
rule.ValidationParameters.Add("other", otherPropertyName);
yield return rule;
}
customvalidation.js
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
jQuery.validator.addMethod("greater", function(value, element, param)
{
return Date.parse(value) > Date.parse($(param).val());
});
jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function(options){
options.rules["greater"] = "#" + options.params.other;
options.messages["greater"] = options.message; // ~ rule.ErrorMessage
});
Generated html output
<input class="text-box-single-line" id="EndDate" name="EndDate" type="text" value="1/1/2010 12:00:00 AM"
data-val="true"
data-val-greater="EndDate must be greater than StartDate"
data-val-greater-other="StartDate"
/>
Implement a jQuery validation method
Implement an unobtrusive adapter
public class GreaterThanDateAttribute : ValidationAttribute, IClientValidatable
{
...
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationType = "greater";
rule.ValidationParameters.Add("other", otherPropertyName);
yield return rule;
}
customvalidation.js
/// <reference path="jquery-1.4.4-vsdoc.js" />
/// <reference path="jquery.validate-vsdoc.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
jQuery.validator.addMethod("greater", function(value, element, param)
{
return Date.parse(value) > Date.parse($(param).val());
});
jQuery.validator.unobtrusive.adapters.add("greater", ["other"], function(options){
options.rules["greater"] = "#" + options.params.other;
options.messages["greater"] = options.message; // ~ rule.ErrorMessage
});
Generated html output
<input class="text-box-single-line" id="EndDate" name="EndDate" type="text" value="1/1/2010 12:00:00 AM"
data-val="true"
data-val-greater="EndDate must be greater than StartDate"
data-val-greater-other="StartDate"
/>
ASP.NET MVC Client Validation
<script src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
Global Settings
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavascriptEnabled" value="true"/>
</appSettings>
Page-level Settings
@Html.EnableClientValidation(false/true)
@Html.EnableUnobtrusiveJavascript(false/true)
Unobtrusive Javascript Validation
<input id="ConfirmHours" name="ConfirmHours" type="text value="0" class="text-box-single-line"
data-val="true"
data-val-equalto="ConfirmHours and Hours do not match."
data-val-equalto-other="*.Hours"
data-val-number="The field ConfirmHours must be a number."
data-val-range="The field ConfirmHours must be between 1 and 120."
data-val-range-max="120"
data-val-range-min="1"
data-val-required="The ConfirmHours field is required."
/>
<span class="field-validation-valid" data-valmsg-for="ConfirmHours" data-valmsg-replace="true"/>
<script src="jquery.validate.min.js" type="text/javascript"></script>
<script src="jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
Global Settings
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavascriptEnabled" value="true"/>
</appSettings>
Page-level Settings
@Html.EnableClientValidation(false/true)
@Html.EnableUnobtrusiveJavascript(false/true)
Unobtrusive Javascript Validation
<input id="ConfirmHours" name="ConfirmHours" type="text value="0" class="text-box-single-line"
data-val="true"
data-val-equalto="ConfirmHours and Hours do not match."
data-val-equalto-other="*.Hours"
data-val-number="The field ConfirmHours must be a number."
data-val-range="The field ConfirmHours must be between 1 and 120."
data-val-range-max="120"
data-val-range-min="1"
data-val-required="The ConfirmHours field is required."
/>
<span class="field-validation-valid" data-valmsg-for="ConfirmHours" data-valmsg-replace="true"/>
Data Validation using Data Annotations
Data Annotations
[Required()][StringLength(25)]
[Range(1,120)]
public int Hours{get; set;}
[Compare("Hours")]
public int ConfirmHours{get; set;}
<div class="editor-label">
@Html.LabelFor(model=>model.ConfirmHours, "Please confirm the hours worked")
</div>
<div class="editor-field">
@Html.EditorFor(model=>model.ConfirmHours)
@Html.ValidationMessageFor(model=>model)
</div>
Custom Validation Attributes
public class GreaterThanDateAttribute : ValidationAttribute
:base("{0} must be greater than {1}")
{
public string OtherPropertyName{get; set;}
public GreaterThanDateAttribute(string otherPropertyName)
{
OtherPropertyName = otherPropertyName;
}
public override string FormatErrorMessage(string name)
{
return String.Format(ErrorMessageString, name, otherPropertyName);
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetProperty(otherPropertyName);
var otherDate = (DateTime)otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisDate = (DateTime)value;
if(thisDate <= otherDate) //failed
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}return null; //succeeded
}
}
public DateTime StartDate{get; set;}
[GreaterThanDate("StartDate")]
public DateTime EndDate{get; set;}
Sunday, July 8, 2012
MVC 3 Child Output Caching
Controllers\HomeController.cs
public class HomeController : Controller
{
[OutputCache(Duration = 60)]
public ActionResult Index()
{
var model = DateTime.Now;
return View(model);
}
[ChildActionOnly]
[OutputCache(Duration = 10)]
public PartialViewResult CurrentTime(){
var model = DateTime.Now;
return PartialView(model);
}
}
Views\Home\CurrentTime.cshtml
@model DateTime
<p>This is the child action result, current time is: @Model.ToLongTimeString()</p>
Views\Home\Index.cshtml
@model DateTime
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>This is the index view for Home, rendering at time: @Model.ToLongTimeString()</div>
<div>@Html.Action("CurrentTime")</div>
public class HomeController : Controller
{
[OutputCache(Duration = 60)]
public ActionResult Index()
{
var model = DateTime.Now;
return View(model);
}
[ChildActionOnly]
[OutputCache(Duration = 10)]
public PartialViewResult CurrentTime(){
var model = DateTime.Now;
return PartialView(model);
}
}
Views\Home\CurrentTime.cshtml
@model DateTime
<p>This is the child action result, current time is: @Model.ToLongTimeString()</p>
Views\Home\Index.cshtml
@model DateTime
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<div>This is the index view for Home, rendering at time: @Model.ToLongTimeString()</div>
<div>@Html.Action("CurrentTime")</div>
MVC Request Validation
Be careful when sending HTML to server.
[ValidateInput(false)] - turn off all verification
[AllowHtml] - granular verification for view model
[ValidateInput(false)] - turn off all verification
[AllowHtml] - granular verification for view model
MVC 3 Action Results
HttpNotFoundResult
public ActionResult Results()
{
return HttpNotFound();
}
HttpRedirectResult
public ActionResult Results()
{
return RedirectPermanent("http://google.com");
}
HttpStatusCodeResult
public AtionResult Results()
{
return HttpStatusCodeResult(415, "Media type not recognized");
}
public ActionResult Results()
{
return HttpNotFound();
}
HttpRedirectResult
public ActionResult Results()
{
return RedirectPermanent("http://google.com");
}
HttpStatusCodeResult
public AtionResult Results()
{
return HttpStatusCodeResult(415, "Media type not recognized");
}
Global Filters
Controllers\HomeController.cs
public class HomeController : Controller
{
public ActionResult Index()
{
throw new InvalidOperationException();
return View();
}
Views\Shared\Error.cshtml
<h2>Sorry, an error occurred while processing your request.</h2>
Global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
}
Web.config
<system.web>
<customErrors mode="On"/>
....
Action filters: [Authorize], [HandleError]
Custom Action Filters
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext){}
public override void OnActionExecuted(ActionExecutedContext filterContext){}
public override void OnResultExecuting(ResultExecutingContext filterContext){}
public override void OnResultExecuted(ResultExecutedContext filterContext){}
}
public class HomeController : Controller
{
public ActionResult Index()
{
throw new InvalidOperationException();
return View();
}
Views\Shared\Error.cshtml
<h2>Sorry, an error occurred while processing your request.</h2>
Global.asax.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
RegisterGlobalFilters(GlobalFilters.Filters);
}
Web.config
<system.web>
<customErrors mode="On"/>
....
Action filters: [Authorize], [HandleError]
Custom Action Filters
public class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext){}
public override void OnActionExecuted(ActionExecutedContext filterContext){}
public override void OnResultExecuting(ResultExecutingContext filterContext){}
public override void OnResultExecuted(ResultExecutedContext filterContext){}
}
Sunday, June 3, 2012
Testing the Sad Path
When_passing_null_measurements.cs
using NUnit.Framework;namespace Domain.Tests.AveragingCalculator_Tests.SadPath
{
[Category("AveragingCalculator")]
public class When_passing_null_measurements
{
private AveragingCalculator _averageCalculator;
[SetUp]
public void Setup()
{
_averageCalculator = new AveragingCalculator();
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void When_measurement_is_null()
{
var measurements = Mother.Get4Measurements();
measurements.Add(null);
_averageCalculator.Aggregate(measurements);
}
}
AveragingCalculator.cs
namespace Domain{
public class AveragingCalculator : IAggregateCalculator
{
if(measurements.Contains(null))
{
throw new ArgumentNullException();
}
return new Measurement()
{
HighValue=measurements.Average(m=>m.HighValue),
LowValue=measurements.Average(m=>m.LowValue)
};
}
Test Project Structure
Solution
- Domain
- AggregationType.cs
- AveragingCalculator.cs
- IAggregateCalculator.cs
- IGrouper.cs
- Measurement.cs
- MeasurementAggregator.cs
- ModalCalculator.cs
- SizeGrouper.cs
- Domain.Tests
- References
- Domain
- AveragingCalculator_Tests
- SadPath
- When_passing_null_measurements.cs
- When_measurements_are_null()
- When_measurent_is_null()
- When_averaging_4_numbers.cs
- When_averaging_several_numbers.cs
- MeasurementAggregator_Tests
- When_aggregating_four_measurements.cs
- Mother.cs
Subscribe to:
Posts (Atom)


