Delegates To Lambdas Cheat Sheet

A cheat sheet Delegates & Lambdas in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

// DELEGATE DEFINITION
public delegate bool IsGreaterThan(int aParam, int compareTo);

// CREATION AND ASSIGNMENT

// .Net 1 version
IsGreaterThan isGreaterThanHandler = new IsGreaterThan(DelegatesToLambda.IsGreaterThanImplementation);

A cheat sheet for Ninject IOC Frmaework in C#

All source code can be found on GitHub <a href="https://github.com/lukewickstead/DOT-NET-on-Linux">here</a>.

// Method Group Conversion
IsGreaterThan isGreaterThanHandler = IsGreaterThanImplementation;

// Anonymous Function
IsGreaterThan isGreaterThanHandler = delegate(int aValue, int compareTo) { return aValue > compareTo; };

// Lambda Functions
IsGreaterThan isGreaterThanHandler = (int aValue, int compareTo) => { return aValue > compareTo; }; // Full hand
IsGreaterThan isGreaterThanHandler = (aValue, compareTo) => { return aValue > compareTo; }; // Param type inferrence
IsGreaterThan isGreaterThanHandler = (aValue, compareTo) => aValue > compareTo; // One line in method + return inferred
IsGreaterThan isGreaterThanHandler = aValue  => aValue > 1; // One param
IsGreaterThan isGreaterThanHandler = ()  => 2 > 1; // No params

// DELEGATES AND GENERICS

// Definition
public delegate string ConcatToString(T aValue, T compareTo);

// .Net 1 version
ConcatToString concatToStringHandler = new ConcatToString(DelegatesTestsWithGenerics.ConcatToStringImplementation);

// Method Group Conversion
ConcatToString concatToStringHandler = DelegatesTestsWithGenerics.ConcatToStringImplementation;

// Anonymous Function
ConcatToString concatToStringHandler = delegate(int aValue, int bValue) { return string.Format("{0}{1}", aValue, bValue); };

// Lambda Function
ConcatToString concatToStringHandle = (aValue, compareTo) => string.Format("{0}{1}", aValue, compareTo);

// FUNC<T, TResult>, ACTION PREDICATE

// Func, Action & Predicate are global delegates definitions to save creating your own.

// Func
// Func can take up to 16 parameter types and return one type

// Parameters expecting  a Func will looks something like
// Func
// Func<T, TResult>
// Func<T, T, TResult>
// Func<T, T, T, TResult>
// Func<T, T, T..... TResult>

Func<int, int, string> aHandler = delegate(int aInt, int bInt) { return string.Empty; }; // Anonymous Method
Func<int, int, string> cHandler = (anInt, anotherInt) => string.Empty; // Lambda

// Predicate can take up to 16 parameters and retun a bool
// Parameters expecting  a Predicate will looks something like
// Predicate<T, TResult>
// Predicate<T, T, TResult>
// Predicate<T, T, T, TResult>
// Predicate<T, T, T..... TResult>

Predicate aHandler = delegate(int anInt) { return anInt > 1; }; // Anonymous Method
Predicate cHandler = anInt => anInt > 1; // Lambda

// Action can take up to 16 parameters and retuns a null
// Parameters expecting  a Action will looks something like
// Predicate
// Predicate<T, T>
// Predicate<T, T, T>
// Predicate<T, T, T....., T>

Action aHandler = delegate(int x) { throw new Exception(); }; // Anonymous Method
Action bHandler = x => { throw new Exception(); };       // Lambda

// MULTICAST DELEGATES
// Multiple events can be registered and deregistered with += and -=
// All events are called one at a time.
// Last one returns the value.
IsGreaterThan isGreaterThanHandler = IsGreaterThanImplementation;
isGreaterThanHandler += IsGreaterOrEqual;
isGreaterThanHandler(1,2);
isGreaterThanHandler -= IsGreaterOrEqual;

// EVENTS
// Events are shorthand notation of grouping delegates
public delegate bool IsGreaterThan(int aParam, int compareTo);
public event IsGreaterThan IsGreaterThanEvent;
IsGreaterThanEvent += IsGreaterThanImplementation;
IsGreaterThanEvent += IsGreaterOrEqual;
IsGreaterThanEvent(1,2);
IsGreaterThanEvent -= IsGreaterOrEqual;

// CONTRAVARIANCE
Contravariance allows us to a method which has a parameter which is a child class of the defined parameter.

// COVARIANCE
Allows us to return a type which is a child class of the defined delegate return type

NInject Cheat Sheet

A cheat sheet for Ninject IOC Frmaework in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

You can also view my HowTos  here and here


// **** DETERMINING WHICH CONSTRUCTOR TO USE ****
// The main DI pattern is Constructor Injection
// A known constructor parameter is one which has been explicitly bound
// An unknown constructor parameter is one which has not been explicitly bound even if it has a resolvable constructor the following order defines which constructor is used
// 1. User defined costructor marked with [Inject] attribute
// 2. The constructor with the most known bound parameters.
// 3. The default parameterless constructor

// **** PROPERTY / METHOD INJECTION
// Properties and methods marked with the [Inject] property will be resolved imediatly after the selected constructor
// Properties are required to be public set and private get
// Methods should be public and return void

[Inject]
public void AMethod(IClass aClass)
{
    this.aClass = aClass;
}

[Inject]
public IClass Property { private get; set; }

// **** BIND TO ****
// Classes are automatically bound to themselves
Bind<IClass>().ToSelf( )			// Explicit self binding
Bind<IClass>().To<Class>();  			// Bind to class
Bind<IClass>().ToConstant( )			// Binding with constant (the returned class), implicitly sets scope to InSingletonScope
Bind<IClass>().ToConstructor( )			// Bind with constructor
Bind<IClass>().ToMethod( )			// Binding with method
Bind<IClass>().ToProvider( )			// Binding with provider, class with parent of Provider<T> allowing addressing of complex initiation

// **** BINDING SCOPE ****
// The lifetime of an instance can be defined via the scope of the binding
// The default scope is InTransientScope
kernel.Bind<IClassA>().To<B>(ClassA).InTransientScope()  	// Always create an instance per Get call
kernel.Bind<IClassA>().To<B>(ClassA).InSingletonScope()		// Create only one instance
kernel.Bind<IClassA>().To<B>(ClassA).InThreadScope()		// Create one instance per thread and always return this
kernel.Bind<IClassA>().To<B>(ClassA).InRequestScope()		// Create one instance per web request and return this
kernel.Bind<IClassA>().To<B>(ClassA).InScope(Func<object>)	// Returns an object associated with the lifetime. The same instances is returned for the same life time of this associated lifetime object. Once this has been garbage collected our bound object will be recreated

// **** CONDITIONAL BINDING ****
Bind<IClass>().To<Class>().Named("AName");  				// Named Binding
Bind<IClass>().To<Class>().WithConstructorArgument("Iclass", delegat/object); // Constructor Argument
Bind<IClass>().To<Class>().WithMetadata("AMetaName", false); 		// Derrived Attribute Bindings
Bind<IClass>().To<Class>().WithParameter(new ConstructorArgument/Property("IClass/PropertyName", new XYZ() ); // WithConstructorArgument is a short cut to this
Bind<IClass>().To<Class>().WithPropertyValue(ProprtyName, delegate/object); // Explicit property injection
Bind<IClass>().To<Class>().When();					// Explicit Conditional binding
Bind<IClass>().To<Class>().WhenAnyAnchestorNamed("AnyParentInAncestry"); // When any class in ancestry is named
Bind<IClass>().To<Class>().WhenClassHas<AnAttribute>();  		// Binding with attributes based helpers
Bind<IClass>().To<Class>().WhenInjectedInto(typeof(AClass)); 		// Conditional injected into AClass or any derrived classes
Bind<IClass>().To<Class>().WhenInjectedExactlyInto(typeof(AClass));	// Conditional injected into AClass and not any derrived classes
Bind<IClass>().To<Class>().WhenMemberHas<AnAttribute>();  		// Binding with attributes based helpers
Bind<IClass>().To<Class>().WhenParentNamed("ParentName");		// Bind when the direct parent is named
Bind<IClass>().To<Class>().WhenTargerHas<AnAttribute>(); 		// Binding with attributes based helpers

// **** MULTIPLE BINDING WITH BindingConfiguration ****
// Default bind up to 4 however more can be found via caching and provinding the bind config.
var bindingConfiguration =
    Bind<IInterface1, IInterface2, IInterface3, IInterface4>()
        .To<Implementation>()
        .BindingConfiguration;
kernel.AddBinding(new Binding(typeof(IInterface5), bindingConfiguration));
kernel.AddBinding(new Binding(typeof(IInterface6), bindingConfiguration));

// **** OnActivation AND OnDeactivation EVENTS
// Trigger evets on the activation and deactivation
Bind<IClass>().To<Class( ).OnActivation( x => x.ActivationMethod())		// Called when an object is activate (instantiated)
Bind<IClass>().To<Class( ).OnDeactivation(x => x.DeactivationMethod())		// Called when an object is deactivate (disposed?)

// **** KERNEL CREATION ****
IKernel kernel = new StandardKernel();

// *** KERNEL MODULES ***
// Provide a grouping of registring bindings
public class WarriorModule : NinjectModule
{
    public override void Load() { } 	// Binding code goes in here
    public override void OnLoad() { } 	// OnLoad event
    public override void OnUnLoad() { } // OnUnload event
}

IKernel kernel = new StandardKernel(new AKernelModule());
IKernel kernel = new StandardKernel(new Module1(), new Module2(), ...);
kernel.Load/UnLoad("*.dll"); // Load / Unload all Kernel Modules within dll
kernel.Load.UnLoad(AppDomain.CurrentDomain.GetAssemblies()); // // Load / Unload all Kernel Modules within the current domains dll's

// **** GET / RESOLVE / INJECT ****
// During execution of code request instance of injected class via the kerel
// Any classes passed in as parameters to the constructor or INJECT marked methods/properties will be automatically resolved.
var aClass = kernel.Get<IClass>();
var classes = kernel.Get<IWarrior>( new ConstructorArgument( "IClass", new AClass() ) );
var classes = kernel.GetAll<IClass>();

// **** MULTIPLE BINDINGS
public ClassName( IEnumerable<IClass> classes) // An instance off all classes implementing the interface will be injected in

// **** NAMED BINDING ****
Bind<IClass>().To<ClassA>().Named("First"); 	// Name the binding during binding
Bind<IClass>().To<ClassB>().Named("Second");
kernel.Get<IClass>("First"); 			// Resolve the bind by providing the name
public ClassC ( [Named("First") IClass aClass]  // Consuctors, Methods and Properties can have named parameters to resolve their injection

// **** DERRIVED ATTRIBUTE BINDINGS ****
// Define an attribute
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class IsSomething : ConstraintAttribute {
    public bool Matches(IBindingMetadata metadata) {
        return metadata.Has("IsSomething") && metadata.Get<bool>("IsSomething");
    }
}

Bind<IClass>().To<AClass>().WithMetadata("IsSomething", false);
Bind<IClass>().To<BClass>().WithMetadata("IsSomething", true);

public AnotherClass([IsSomething] IClass aClass) {} // face resolves to BClass

// TODO: try this bit
kernel.Get<IClass>(metadata => metadata.Has("IsSomething") && metadata.Get<bool>("IsSomething") == false ) // resolves to AClass

// **** BINDING WITH ATTRIBUTE BASED HELPERS ****
// The Target: the parameter being injected into
// The Member: the property, method or constructor itself
// The Class: the class Type within which the Member or Target is defined within

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class WhenClassHas : Attribute{ }

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class WhenMemberHas : Attribute{}

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true, Inherited = true)]
public class WhenTargetHas : Attribute{}

public class InjectWhenMemberAndTargetHas
{
	[Inject, WhenMemberHas]
	public IClass WhenMemberHas { get; set; } // Member has an attribute
	public IClass WhenTargetHas { get; set; }
	public InjectWhenMemberAndTargetHas([WhenTargetHas] IClass aClass){WhenTargetHas = aClass;} // target has an attribute
}

[WhenClassHas]
public class InjectWhenClassHas
{
	[Inject] // Class is marked with attriibute. binding is done by class
	public IClass WhenClassHas { get; set; }
}

Bind<IClass>().To<KnownC>().WhenClassHas<WhenClassHas>();
Bind<IClass>().To<KnownD>().WhenTargetHas<WhenTargetHas>();
Bind<IClass>().To<KnownE>().WhenMemberHas<WhenMemberHas>();

// **** BIND WITH METHOD ****
// Used to bind to factory methods.
// Here we are passing in the reques5 context tyoe
Bind<IClass>().ToMethod( context => AFactory.Create( context.Request.Target.Type ) )
Bind<IClass>().ToMethod( x => new ClassC(x.Kernel.Get<IClassA>(), x.Kernel.Get<IClassB>()));

// **** BIND TO PROVIDER ****
// Binding with provider, class with parent of Provider<T> allowing addressing of complex initiation
Bind<IClass>().ToProvider(new AProvider())

public class AProvider : Provider<AClass>
{
    protected override AClass CreateInstance(IContext context)
    {
        return new AClass(); // Do some complex initialization here.
    }
}

// **** BIND TO CONSTRUCTOR ****
Bind<IMyService>().ToConstructor( ctorArg => new ClassC(ctorArg.Inject<IClassA>(), ctorArg.Inject<IClassB>())); // TODO what is the difference between constructor and method binding

// **** BIND WITH CONSTRUCTOR ARGUMENT ****
Bind<IClass>().To<Class>().WithConstructorArgument("ParameterName", x =>x.Kernel.Get<IClass>()); //

// **** BIND WITH EXPLICIT CONDITIONAL BINDING ****
Bind<IClass>().To<ClassA>().When(request => request.Target.Member.Name.StartsWith("ClassName"));
Bind<IClass>().To<ClassB>().When(request => request.Target.Type.Namespace.StartsWith("NameSpace.ClassName"));

Generics Cheat Sheet

A cheat sheet for Generics in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

My How To in Generics can be found here while some code examples can be found in my post here.


// **** WHY GENERICS ****
// Type Safe: Prevent having to cast between obect and a type when retrieving data from objects such as classes

// Faster: Value types which are placed into classes which are designed to be used on multiple types. No need to box/unbox value types.
// Allocating an object on the heap from the stack and vice versa is slow

// **** WHEN SHOULD I USE GENERICS ****
// When you have multiple method overloads which have the same functionality for multiple types

// *** WHEN SHOULD I NOT USE GENERICS ****
// If you find yourself restrcting access to an Interface or a base class then you should ask yourself if generics is really required here

// **** CONSTRAINTS ****
// Constrains provide a way to limit which types can be used
// In most cases no constraintss should be used
where T: struct 	// Value Type; System.ValeValue is found as an ancestor
where T: class 		// Reference type; System.ValeValue is not found as an ancestor (any class, interface, delegate or array type)
where T: new() 		// Provides a parameterless constructor.
where T:  	// Has an ancestory
where T:  	// Implements an interface
where T: U 		// One provided type is an ancestor of another.

// Examples
class Test<T, U> where U : struct where T : Base, new() {}
class List{ void Add<span style="text-decoration: underline;">(List<span style="text-decoration: underline;"> items) where U : T {}
class SampleClass<T, U, V> where T : V {}
void SomeFunction(T aValue) where T : V {}

// **** EQUALITY  ****
// Can not use != & == operators as we can not gurantee that concrete type will implement these
// Can compare to null though for value types will always return false.

// **** DEFAULT VALUE ****
return default(T); // returns the default value of the type; 0 for int etc.

// **** CASTING ****
// Can cast to and from System.Object and explcitly convert to any interfaces.
// Implicit cast can be to object or to constraint-specified types only.
// Implicit casting is type safe as incompatibility is discovered at compile-time.
// Explicit cast can be to interface only

// Consider
class MyClass where T : BaseClass, ISomeInterface {}

//Implicit
ISomeInterface obj1 = t;
BaseClass      obj2 = t;
object         obj3 = t;

// Explicit
ISomeInterface obj1 = (ISomeInterface)t;	//Compiles
SomeClass      obj2 = (SomeClass)t;     	//Does not compile

// Explcity achieved via temp object; is dangerous. better to use is or as operator
object temp = t;
MyOtherClass obj = (MyOtherClass)temp;

// Can Cast
bool IsInterface = typeof(ISomeInterface).IsAssignableFrom(typeof(T));
if(t is int)
if(t is LinkedList<int,string>)

// AS Cast; like a cast but returns null on failure
t as IDisposable
expression is type ? (type)expression : (type)null // equivalent to as
using(t as IDisposable)

// **** ATTRIBUTES ****
// These can not be used however you can check owning functions
myobj.GetType().IsSerializable

// **** TYPE ANALYSYS ****

// TypeCode Enum
TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );
TypeCode.Boolean;
TypeCode.Decimal;

// IsType
typeof(int).IsPrimitive
typeof(int).IsDecimal
typeof(int).IsArray
typeof(int).IsInterface

// Nullable Types
Nullable
t?

// **** CONVERTING BETWEEN TYPES ****
// Parse & Try Parse
Integer.Parse
Integer.TryParse( "1", out aValue)

// Change Type: Returns an object of the specified type and whose value is equivalent to the specified object.
int i = (int)Convert.ChangeType(-2.345, typeof(int));
DateTime dt = (DateTime)Convert.ChangeType("12/12/98", typeof(DateTime));

// TypeDescriptor Converter
public static T GetTfromString(string mystring)
{
   var foo = TypeDescriptor.GetConverter(typeof(T));
   return (T)(foo.ConvertFromInvariantString(mystring));
}

Linq Cheat Sheet

A cheat sheet for Linq in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 

// **** AGGREGATE ****

// Aggregate Linq Ext methods can be applied to natural Linq
.Count()
.Min()
.Max()
.Average()
.Sum()

// Aggregate
var count = (from p in people
 		select p).Count ();

// Conditional Aggregate
var count = (from p in people
             where p.Gender == Gender.Male
             select p).Count ();

// Nested Aggregate
var samplePeople = from p in people
		   select new { Name= p.Name,
				ChildrenCount =
				  (from c in p.Children
				   where c.Gender == Gender.Female
				   select c).Count () };

// Grouped Aggregate
var children = from p in people
	group p by p.Gender into peopleGenders
		let minKids = peopleGenders.Min( x => x.Children.Count())
	select new { Gender = peopleGenders.Key, Value = peopleGenders.Count() };

// Let satement
var children = from p in people
	let x = peopleGenders.Count( x => x.Children.Count())
	select x

// **** CONVERSIONS ****
// All conversions functions should be done with Linq ext methods ToArray(), ToList(), ToDictionary(), OfType(), Cast(); see Linq Ext cheet sheet here.

// **** ELEMENT ****
// All element functions should be done with Linq ext methods First(), FirstOrDefault(), Last(), LastOrDefault(), ElementAt(); see Linq Ext cheet sheet here.

// **** FILTER ****
// Where filter
var count = (from p in people
             where p.Age < 30
             select p).Count ();

// Drilled where filter
var count = (from p in people
             where p.Children.Count () > 0
             select p).Count ();

// **** GENERATION ****
// All generation functions should be done with Linq ext methods Enumerable.Range() and Enumerable.Repeat(); see Linq Ext cheet sheet here

// **** GROUPING ****
// Group by gender and count...
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.Count()};

// Split into groups of gender by grouping on Name
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.OrderBy( x => x.Name)};

// **** ORDERING ****
// Order ASC
var orderdPeople = from p in people
	orderby p.Name
	select new { p.Name, p.Age, p.Children, p.Gender };

// Order DES
var orderdPeople = from p in people
	orderby p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

// Order by multiple fields
var orderdPeople = from p in people
	orderby p.Age, p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

// Reverses the order
var orderdPeople = (from p in people
	orderby p.Name
    select new { p.Name, p.Age, p.Gender, p.Children }).Reverse ();

// **** PARTITIONING ****
// All partitioning functions should be done with Linq ext methods Take(), Skip(), TakeWhile() SkipWhile(); see Linq Ext cheet sheet here

// **** PROJECTION ****
// Select column
var allFemaleNames = from p in people
           			where p.Gender == Gender.Female
           			orderby p.Name descending
					select p.Name;
// Select columns into anonymous type
var parentsNameAndAge = from p in people
	where p.Gender == Gender.Female
	select new { Name =  p.Name, Age = p.Age };

// Select element
var boysWithFemaleParents = from parent in people
	where parent.Gender == Gender.Female
	from children in parent.Children
	where children.Gender == Gender.Male All
	select children;

// **** QUANTIFIERS ****
// Any() and All() functions can be applied here

// Any exists
var isAnyPeople = (from p in people
                   where p.Gender == Gender.Unknown
                   select p).Any ();

// Any exists in group
var isAnyPeople = from p in people
    			  where p.Children.Any (child => child.Gender == Gender.Unknown)
				  group p by p.Gender into genders
                  select new { Gender = genders.Key, People = genders};

// **** SETS ****
// Most set functions should be done with Linq ext methods Take(), Skip(), TakeWhile() SkipWhile(); see Linq Ext cheet sheet here
// inner join between person and gender description
var foo = from aPerson in people
	join aDes in genderDescriptions on aPerson.Gender equals aDes.Gender
select new { Name = aPerson.Name, Gender = aPerson.Gender, Desc = aDes.Descripion};

Linq Extension Methods Cheat Sheet

A cheat sheet for Linq Extension Methods in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


// **** AGGREGATE ****
data.Count() 						// The count of items
data.Cout(x => x.Condition == true)			// Count items which pass criteria
data.Sum (x => x.Value); 				// Sum of all items
data.Min(x => a.Value);					// Min value
data.Max(x => a.Value);					// Max value
data.Average(x => a.Value);				// Average
data.Select(x => new { A = x.Name, B = x.Min(x.Value))	// Nested Aggregate
data.GroupBy( x => x.Type)
	.Select( y =>
	new { Key = y.Key,
	      Average = y.Average ( z => z.Value ) } ); // Grouped Aggregate

// **** CONVERSIONS ****
data.ToArray();						// Convert to Array
data.ToList();						// Convert to List
data.ToDictionary( x=> x.Name ); 			// Convert to Dictionary keyed on Name
data.OfType<decimal> ().ToList ()			// Filters out all elements not of provided type
data.Cast<decimal> ().ToList ()				// Cast can only cast to Implemented Interfaces and classes within the hierachy
data.ConvertAll<double> (x => Convert.ToDouble (x));	// Convert all items with provided conversion method

// **** ELEMENT ****
data.First()						// Returns the first element
data.First( x=> x.Type == Types.A )			// Returns the first element passing the condition
data.FirstOrDefault( )					// Returns the first element or default*
data.FirstOrDefault( x => x.Type == Types.B )		// Returns the first element passing the condition or default*
data.Last()						// Returns the last element
data.Last( x=> x.Type == Types.A )			// Returns the last element passing the condition
data.LastOrDefault( )					// Returns the last element or default*
data.LastOrDefault( x => x.Type == Types.B )		// Returns the last element passing the condition or default*
data.ElementAt(0)					// Returns the element at position 0
*default						// Default is defined as default(typeOf(T)) or new Constructor() without any constructor parameters

// **** FILTERS ****
data.Where(x => x.Type == Types.A)			// Returns all elements passing the condition
data.Where(( x, index) => index <= 4 && x.Type == Types.A) // The elements index can be passed into the delegate

// **** GENERATION ****
Enumerable.Range(1, 10);				// Creates collection of 10 items between 1 and 10
Enumerable.Repeat(1, 10);				// Creates a collection of 10 1s.

// **** GROUPING ****
// Grouping is not like SQL where columns have to be aggregates or wihtin the group list; you group the elements into a list for each group

data.GroupBy (x => x.Type)
    .Select (grp => new { Key = grp.Key, Value = grp.Count ()}); // Group with count of data

data.GroupBy (x => x.Type)
    .Select (grp => new { Key = grp.Key,  Value = grp.OrderBy (x => x.Name)}); // Create a collection of elements ordered by name for each group of Type

// **** ORDERING ****
data.OrderBy (x => x.Name);					// Order by Name ASC
data.OrderBy (x => x.Name).ThenBy (x => x.Age);			// Order by Name ASC the Age ASC
data.OrderBy (x => x.Name).ThenByDescending (x => x.Age);	// Order by Name ASC then Age DESC
data.OrderByDescending (x => x.Name);				// Order by Name DESC
data.OrderBy (x => x.Name, 					// Order by Name ASC Case insensative
	StringComparer.CurrentCultureIgnoreCase);
data.OrderBy (x => x.Name).Reverse ();				// Reverse elements

// **** PARTITIONING ****
data.Take (3);							// Take 3 items
data.Skip (3);							// Skip 3 items
data.TakeWhile (x=>x.Type ==Types.A);				// Take all the items while the condition is met
data.SkipWhile (x=>x.Type ==Types.A);				// Skip all the items while the condition is met

// **** PROJECTION ****
data.Select (x => x.Name);					// Select collection of a column
data.Select (x => new { Name = x.Name, Age = x.Age });		// Select a collection of columns through an anonymus type
data.SelectMany (x => x.Children)				// SelectMany flattens collections into one collection

// **** QUANTIFIERS ****
data.Any (x => x.Type == Types.TypeA);				// Returns True/False if any element meets the condition
data.All (x => x.Type == Types.TypeA);				// Returns True/False if all the elements meet the condition

// **** SET ****
data.Distinct ();						// Returns a collection of distinct elements
data.Intersect(dataTwo);					// Returns the union / intersection of data; elements in both collections
data.Except(dataTwo);						// Returns elements in data which are not in dataTwo
data.Concat(dataTwo);						// Concatonates both collections; appends dataTwo to data
data.SequenceEqual(dataTwo));					// Returns True if data has the same data and sequence of dataTwo
data.Join(dataTwo, 						// Joins the data together like SQL join
    x => x.Type,						// Join field on data
    y => y.Type, 						// Join field on dataTwo
    ( d1, d2 ) => new { Name = d1.Name, Type = d1.Type, Desc = d2.Descripion} ); // Selection criteria

data.Distinct (new AComparer ()).				// Distinct with providing an equality provider
public class AComparer : IEqualityComparer<A>
{
    public bool Equals (A x, A y) { return a == a;}
    public int GetHashCode (A obj) { return obj.GetHashCode(); }
}

XUnit Cheat Sheet

A cheat sheet for the XUnit test framework

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


using System;
using System.Collections.Generic;
using Xunit;
using Xunit.Extensions;
namespace GenericsExamples.Tests
{
    public class AccountTests : IDisposable,                             // Allows Test TearDown via Dispose()
                                IUseFixture<AccountTests.TestSetUpClass> // Allows Test Set Up via injected class
    {

        public AccountTests()
        {
            // TestFixture Setup code here
            Console.WriteLine("AccountTests Constructor");
        }

        public void SetFixture(TestSetUpClass setupClass)
        {
            // Can inject a class to provide any set up here.
            setupClass.AnyFunction();
        }
        /// <summary>
        /// The very simply example.
        /// </summary>
        [Fact]
        public void SimpleExample()
        {
            Console.WriteLine("AccountTests.TestOne()");
            Assert.True(true);
        }

        /// <summary>
        /// InLineData allows multiple traversals of the same test with different parameters
        /// </summary>
        /// <param name="number"></param>
        /// <param name="expectedResult"></param>
        [Theory,
        InlineData(1, true),
        InlineData(2, true),
        InlineData(3, false)]
        public void InlineDataExample(int number, bool expectedResult)
        {
            Console.WriteLine("AccountTests.DemoSimpleTestWithInLineData(int {0}, bool {1})", number, expectedResult);
            Assert.Equal(number < 3, expectedResult);
        }

        /// <summary>
        /// Properties returning IEnumerable can be used instead of InLineData.
        /// </summary>
        public static IEnumerable<object[]> SamplePropertyDataProperty
        {
            get
            {
                yield return new object[] { 1, true };
                yield return new object[] { 2, true };
                yield return new object[] { 3, false };
            }
        }

        /// <summary>
        /// PropertyData allow multiple calls of a test function with parameters defined in a property usign yield
        /// </summary>
        /// <param name="number">Test data</param>
        /// <param name="expectedResult">Expected Result</param>
        [Theory]
        [PropertyData("SamplePropertyDataProperty")]
        public void PropertyDataExample(int number, bool expectedResult)
        {
            Console.WriteLine("AccountTests.PropertyDataExample(int {0}, bool {1})", number, expectedResult);
            Assert.Equal(number < 3, expectedResult);
        }

        /// <summary>
        /// A run throw of the most common Assertions
        /// </summary>
        [Fact]
        public void AsertionExamples()
        {
            Console.WriteLine("AccountTests.AsertionExamples()");

            Assert.Contains("n", "FNZ", StringComparison.CurrentCultureIgnoreCase);
            Assert.Contains("a", new List<String> { "A", "B" }, StringComparer.CurrentCultureIgnoreCase);

            Assert.DoesNotContain("n", "FNZ", StringComparison.CurrentCulture);
            Assert.DoesNotContain("a", new List<String> { "A", "B" }, StringComparer.CurrentCulture);

            Assert.Empty(new List<String>());
            Assert.NotEmpty(new List<String> { "A", "B" });

            Assert.Equal(1, 1);
            Assert.Equal(1.13, 1.12, 1); // Precsions Num DP
            Assert.Equal(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCultureIgnoreCase);
            Assert.Equal(GetFoo(1, "A Name"), GetFoo(1, "a name"), new FooComparer());

            Assert.NotEqual(1, 2);
            Assert.NotEqual(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCulture);

            Assert.False(false);
            Assert.NotNull(false);
            Assert.Null(null);
            Assert.True(true);

            Assert.InRange(1, 0, 10);
            Assert.NotInRange(-1, 0, 10);

            Assert.IsType(Type.GetType("System.Int32"), 1);
            Assert.IsNotType(Type.GetType("System.Double"), 1);

            var foo = new object();
            var moo = new object();

            Assert.Same(foo, foo);
            Assert.NotSame(foo, moo);

            Assert.Throws<Exception>(() => { throw new Exception(); });
            Assert.True(true);
        }

        private static Foo GetFoo(int id, string name)
        {
            return new Foo { ID = id, Name = name };
        }

        public void Dispose()
        {
            // TestFixture Teardown attributes
            Console.WriteLine("AccountTests.Dispose()");
        }

        # region Internal Classes
        public class Foo
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }

        public class FooComparer : IEqualityComparer<Foo>
        {
            public bool Equals(Foo x, Foo y)
            {
                return x.ID == y.ID && x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase);
            }

            public int GetHashCode(Foo obj)
            {
                return obj.ID.GetHashCode();
            }
        }

        public class TestSetUpClass
        {
            public void AnyFunction()
            {
                Console.WriteLine("TestSetUpClass.AnyFunction()");
            }
        }
        #endregion
    }
}

NUnit Cheat Sheet

A cheat sheet for the NUnit test framework

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 

using System;
using System.Reflection;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;

namespace NUnitCheatSheet
{
	/// <summary>
	/// TestFixtureSetUp: Provides a config class for setting up and tearing down the test fixture.
	/// Provides the config for all TestFixture classes witin the same namespace.
	/// </summary>
	[SetUpFixture]
  	public class TestFixtureSetUp
  	{
		/// <summary>
		/// SetUp; run once before all tests in a test fixture.
		/// Run once for each TestFixture in the same namespace.
		/// </summary>
	    [SetUp]
		public void RunBeforeAnyTests()
		{
		  // Set up code here.
		}
		/// <summary>
		/// TearDown; run once after all tests in a test fixture.
		/// Run once for each TestFixture in the same namespace.
		/// </summary>
	    [TearDown]
		public void RunAfterAnyTests()
		{
		  // Clear up code here.
		}
  	}

	/// <summary>
	/// Factory class for providing test data for tests with the TestCaseSource attribue.
	/// </summary>
	public class TestCaseDataFactory
	{
		/// <summary>
		/// TestCaseSource tests can consume IEnumerable properties which return TestCaseData
		/// </summary>
	  	public static IEnumerable TestCasesDataForTestCaseSourceTest
		{
		    get
		    {
		      yield return new TestCaseData( 1, "1" ).Returns( 2 ); // Defines the test data and the expected return
		      yield return new TestCaseData( 2, "2" ).Returns( 4 );
		      yield return new TestCaseData( 0, "a" )
						.Throws(typeof(ArgumentException)); // Defines the test data and the expected throw exception
		    }
		}
	}

	/// <summary>
	/// TestFixture defines a class of tests
	/// </summary>
	[TestFixture(), Category("MyTests"), Description("NUnut Cheat Sheet!")]
	public class Test
	{
		/// <summary>
		/// TestCaseSource attributes can use static properties to return an array of test data
		/// </summary>
		public static object[] CaseSourceTestData =
		{
		    new object[] { 1, 1.1m, "2.1" },
			new object[] { 2, 2.2m, "4.2" },
			new object[] { 3, 3.3m, "6.3" },
		};

		# region Setup and Tear Down
		/// <summary>
		/// TestFixtureSetUp called once before any tests have been run in the same TestFixture
		/// </summary>
		[TestFixtureSetUp] public void FixtureSetUp()
    	{
			// Set up code here.
		}
		/// <summary>
		/// TestFixtureTearDown called once after all tests have been run in the same TestFixture
		/// </summary>
    	[TestFixtureTearDown] public void FixtureTearDown()
    	{
			// Clear up code here.
		}

		/// <summary>
		/// SetsUp is called once before each Test within the same TestFxiture
		/// </summary>
		[SetUp] public void SetUp()
    	{
			// Set up code here.
			// If this throws an exception no Test in the TestFixture are run.
		}

		/// <summary>
		/// TearsDown is called once after each Test within the same TestFixture.
		/// </summary>
    	[TearDown] public void TearDown()
    	{
			 // Clear up code here.
			// Will not run if no tess are run due to [SetUp] throwing an exception
		}
		# endregion

		/// <summary>
		/// ExpectedException defines what exception and how it is configured
		/// </summary>
		[Test, ExpectedException( typeof(Exception), ExpectedMessage = "Foo", MatchType = MessageMatch.Exact)]
		public void ExpectedExceptionAttributeTest()
		{
			// MessageMatch is an enum of: Contains, Exact, Regex, StartsWith
			throw new Exception("Foo");
		}

		/// <summary>
		/// Explicit defines tests which are only run manualy.
		/// </summary>
		[Test, Explicit("Test has to be run explicitly")]
    	public void ExplicitAttributeTest()
    	{
		}

		/// <summary>
		/// Ignore marks tests which are not run even if run manually
		/// </summary>
		[Test, Ignore("Ignore this test")]
    	public void IgnoreAttribueTest()
    	{
		}

		/// <summary>
		/// MaxTimeAttribute defines the max run time in milliseconds before the test is considered as failed but allowed to complete.
		/// </summary>
		[Test, MaxTimeAttribute(2000)]
		public void MaxtimeAttributeTest()
		{
		}

		/// <summary>
		/// Timeout defines the max run time in milliseconds before the test is automatically failed.
		/// Can be used on TestFixture to set for each contained Test's
		/// </summary>
		[Test, Timeout(200)]
		public void TimeOutTest()
		{
		}

		/// <summary>
		///
		/// </summary>
		[Test, Platform("Mono"), Culture("en-GB")]
		public void PlatformAttributeTest()
  		{
			// Can also provide exclusion culture and platform
			// Test case is ignored if Platform or Cultrue can not be provided
 		}

		/// <summary>t
		/// Property: categorises the test witin the test output XML.
		/// </summary>
		[Test, Property("PropertyName", "Value")]
		public void PropertyAttributeTest()
    	{}

		/// <summary>
		/// Custom Property: categorises the test within the test output XML.
		/// </summary>
		[Test, CustomPropertyAttribute(CustomPropertyValue.One)]
		public void CustomPropertyAttributeTest()
    	{}

		#region Parameterized
		/// <summary>
		/// Combinatorial: The test is run with each combination of Values for each parameter
		/// </summary>

		[Test, Combinatorial]
		public void CombinatorialAttributeTest ([Values(1,2,3)] int a, [Values("a", "b", "c")] string b)
		{
			// Called 9 times with  parameter pairs of: {1,a}, {1,b}, {1,c}, {2,a}, {3,b}....
		}

		/// <summary>
		/// Random: Test can be run with a random value. Random(Min,Max,Count)
		/// </summary>
		[Test]
		public void RandomAttributeTest(
    	[Random(1, 10, 2)] int value)
		{
			// Called 2 times with a random integer between 1 and 10
			Assert.That(value, Is.InRange(1,10));
		}

		/// <summary>
		/// Sequential: Parameters with values are run in sequence
		/// </summary>
		[Test, Sequential]
		public void SequentialAttributeTest(
    	[Values(1,2,3)] int x,
    	[Values("A","B")] string s)
		{
			// Test runs for parameter pairs {1,A}, {2,B}, {3, null}
		}

		/// <summary>
		/// Range: Parameter is run with a sequence of values incremented. Range(Min,Max,Increment).
		/// </summary>
		[Test]
		public void RangeAttributeTest(
    	[Range(0.0, 1, 0.5)] decimal value)
		{
			// Test run for parameters, 0.0, 0.5, 1.0
			Assert.That(value, Is.InRange(0m,1m));
		}

		/// <summary>
		/// TestCaseSource: referencing a public property which privides a sequence of test data
		/// </summary>
		[Test, TestCaseSource("CaseSourceTestData")]
		public void CaseSourceTest(int a, decimal b, string c)
		{
			// Can also specify the class to which the property is found upon.
			Assert.That(a + b, Is.EqualTo(Decimal.Parse(c)));
		}

		/// <summary>
		/// TestCaseSource: referncing a class and property which provides a sequence of test data and expected output.
		/// </summary>
		[Test,TestCaseSource(typeof(TestCaseDataFactory),"TestCasesDataForTestCaseSourceTest")]
		public decimal TestCaseSourceTest(int a, string b)
		{
			int bInt;
			if( !int.TryParse(b, out bInt))
				throw new ArgumentException(string.Format("Can not parse '{0}' to an integer", b), "b");

			return a + bInt;
		}

		/// <summary>
		/// TestCase: provides a test input data and expected result.
		/// </summary>
		[TestCase(1,1, Result=2)]
		[TestCase(2,2, Result=4)]
		[TestCase(3,3, Result=6)]
		public int TestCaseTest(int a, int b)
		{
		  return( a + b);
		}
		#endregion

		/// <summary>
		/// Assertion Based Test
		/// </summary>
		[Test(), Category("Assertion based testing")]
		public void TestAssertions ()
		{

			// Equality
			Assert.AreEqual (true, true);
			Assert.AreNotEqual (true, false);

			// Identity
			Assert.AreSame (string.Empty, string.Empty);
			Assert.AreNotSame (new object (), new object ());
			Assert.Contains (string.Empty, new List<object> (){string.Empty});

			// Condition
			Assert.IsTrue (true);
			Assert.IsFalse (false);
			Assert.IsNull (null);
			Assert.IsNaN (Double.NaN);
			Assert.IsEmpty (new List<object> ());
			Assert.IsEmpty (new List<object> ());
			Assert.IsNotEmpty (new List<object> (){1});
			Assert.IsNotEmpty ("Foo");

			// Comparision
			Assert.Greater (Decimal.MaxValue, Decimal.MinValue);
			Assert.GreaterOrEqual (Decimal.MinValue, Decimal.MinValue);
			Assert.Less (Decimal.MinValue, Decimal.MaxValue);
			Assert.LessOrEqual (Decimal.MinValue, Decimal.MinValue);

			// Types
			Assert.IsInstanceOf<decimal> (decimal.MinValue);
			Assert.IsNotInstanceOf<int> (decimal.MinValue);
			Assert.IsNotAssignableFrom (typeof(List<Type>), string.Empty);        	// Equivalent to Type.IsAssignableFrom Method
			Assert.IsAssignableFrom (typeof(List<decimal>), new List<decimal> ()); 	// http://msdn.microsoft.com/en-gb/library/system.type.isassignablefrom.aspx
			Assert.IsNotAssignableFrom<List<Type>> (string.Empty);
			Assert.IsAssignableFrom<List<decimal>> (new List<decimal> ());

			// Exceptions
			Assert.Throws (typeof(ArgumentNullException), () => {
				throw new ArgumentNullException (); }
			);

			Assert.Throws<ArgumentNullException> (() => {
				throw new ArgumentNullException (); }
			);

			Assert.DoesNotThrow (() => { });

			Assert.Catch (typeof(Exception), () => {
				throw new ArgumentNullException (); }
			);

			Assert.Catch<Exception> (() => { // Similar as Throws but allows any derrived class of the thrown exception
				throw new ArgumentNullException (); }
			);

			// Strings
			StringAssert.Contains ("Foo", "MooFooMoo");
			StringAssert.StartsWith ("Foo", "FooMoo");
			StringAssert.EndsWith ("Moo", "FooMoo");
			StringAssert.AreEqualIgnoringCase ("FOO", "foo");
			StringAssert.IsMatch ("[0-9]", "1");

			// Collections
			CollectionAssert.AllItemsAreInstancesOfType (new List<decimal> (){ 0m }, typeof(decimal));
			CollectionAssert.AllItemsAreNotNull (new List<decimal> (){ 0m });
			CollectionAssert.AllItemsAreUnique (new List<decimal> (){ 0m, 1m });
			CollectionAssert.AreEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 0m });
			CollectionAssert.AreEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 0m }); // Same as AreEqual though order does not mater
			CollectionAssert.AreNotEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 1m });
			CollectionAssert.AreNotEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 2m });  // Same as AreNotEqual though order does not matter
			CollectionAssert.Contains (new List<decimal> (){ 0m, 1m }, 1m);
			CollectionAssert.DoesNotContain (new List<decimal> (){ 0m, 1m }, 2m);
			CollectionAssert.IsSubsetOf (new List<decimal> (){ 1m }, new List<decimal> (){ 0m, 1m }); // {1} is considered a SubSet of {1,2}
			CollectionAssert.IsNotSubsetOf (new List<decimal> (){ 1m, 2m }, new List<decimal> (){ 0m, 1m });
			CollectionAssert.IsEmpty (new List<decimal> (){ });
			CollectionAssert.IsNotEmpty (new List<decimal> (){ 1m });
			CollectionAssert.IsOrdered (new List<decimal> (){ 1m, 2m, 3m });
			CollectionAssert.IsOrdered (new List<string> (){ "a", "A", "b"}, StringComparer.CurrentCultureIgnoreCase);
			CollectionAssert.IsOrdered (new List<int> (){ 3,2,1}, new ReverseComparer()); // Only supports ICompare and not ICompare<T> as of version 2.6

			//  File Assert: various ways to compare a stream or file.
			FileAssert.AreEqual (new MemoryStream (), new MemoryStream ());
			FileAssert.AreEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile.txt"));
			FileAssert.AreEqual ("MyFile.txt", "MyFile.txt");
			FileAssert.AreNotEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile2.txt"));
			FileAssert.AreNotEqual ("MyFile.txt", "MyFile2.txt");
			FileAssert.AreNotEqual (new FileStream ("MyFile.txt", FileMode.Open), new FileStream ("MyFile2.txt", FileMode.Open));

			// Utilities: will cause the test to stop immediatly and mark the test as:
			Assert.Pass ();
			Assert.Fail ();
			Assert.Ignore ();
			Assert.Inconclusive ();

			// Defining the failed message
			Assert.IsTrue(true, "A failed message here"); // also object[] params can be defined
		}

		/// <summary>
		/// Constraint based testing: Test cases with a fluent design pattern
		/// </summary>
		[Test()]
		[Category("Constraint based testing")]
		public void TestConstraints ()
		{

			// Numerical Equality
			Assert.That (1, Is.EqualTo (1));
			Assert.That (1, Is.Not.EqualTo (2));
			Assert.That (1.1, Is.EqualTo (1.2).Within (0.1)); // Allow a tollerance
			Assert.That (1.1, Is.EqualTo (1.01).Within (10).Percent); // Pass tollerance within percent

			// Float Equality
			Assert.That (20000000000000004.0, Is.EqualTo (20000000000000000.0).Within (1).Ulps); // Pass tollerance with units of last place

			// String Equality
			Assert.That ("Foo!", Is.EqualTo ("Foo!"));
			Assert.That ("Foo!", Is.Not.EqualTo ("FOO!"));
			Assert.That ("Foo!", Is.EqualTo ("FOO!").IgnoreCase);
			Assert.That (new List<string> (){ "FOO!"}, Is.EqualTo (new List<string> (){ "Foo!"}).IgnoreCase);

			// Date, Time and TimeSpan equality
			Assert.That (DateTime.Today, Is.EqualTo (DateTime.Today));
			Assert.That (DateTime.Now, Is.Not.EqualTo (DateTime.Now));
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (TimeSpan.FromSeconds (1))); // Time based pass tollerances
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Days);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Hours);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Minutes);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Seconds);
			Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Milliseconds);

			// Collection equality
			Assert.That (new double[] {1.0,2.0,3.0}, Is.EqualTo (new int[] {1,2,3}));
			Assert.That (new double[] {1.0,2.0,3.0}, Is.Not.EqualTo (new int[] {1,2,3, 4}));
			Assert.That (new double[] {1.0,2.0,3.0,4.0}, Is.EqualTo (new  int[,] {{1,2}, {3,4}}).AsCollection); // Compare data and not collection (flattens a collection of collections)

			// Customer Comparer
			Assert.That( int.MinValue, Is.EqualTo(int.MaxValue).Using(new WhoCaresComparer()));

			// Identity (Same instance of)
			Assert.That( string.Empty, Is.SameAs(string.Empty));
			Assert.That( new object(), Is.Not.SameAs(new object()));

			// Condition
			Assert.That( string.Empty, Is.Not.Null);
			Assert.That( true, Is.True);
			Assert.That( true, Is.Not.False);
			Assert.That( double.NaN, Is.NaN);
			Assert.That( string.Empty, Is.Empty);
			Assert.That( new List<int>(), Is.Empty);
			Assert.That( new List<int>(){1,2,3}, Is.Unique);

			// Comparision
			Assert.That(1, Is.LessThan(2));
			Assert.That(1, Is.GreaterThan(0));
			Assert.That(1, Is.LessThanOrEqualTo(1));
			Assert.That(1, Is.GreaterThanOrEqualTo(1));
			Assert.That(1, Is.AtLeast(0));	// Same as GreaterThanOrEqualTo
			Assert.That(1, Is.AtMost(2)); 	// Same as LessThanOrEqualTo
			Assert.That(1, Is.InRange(1,2));

			// Path: comparision on file path only without comparing the contents.
			// All paths are converted to 'canonical' path before comparing; full direct path to file.
			Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt"));
			Assert.That( "MyFile.txt", Is.SamePath( "MYFILE.TXT" ).IgnoreCase );
			Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt").RespectCase);
			Assert.That( "/usr/bin", Is.SubPath("/usr"));			// directory exists within another
			Assert.That( "/usr/bin", Is.SamePathOrUnder("/usr"));	// SamePath or SubPath

			// Type Constraints
			Assert.That(new MemoryStream(), Is.InstanceOf(typeof(Stream)));  // Is type or ancestor
			Assert.That(new MemoryStream(), Is.TypeOf(typeof(MemoryStream))); // Is type and not ancestor
			Assert.That(new object(), Is.AssignableFrom(typeof(MemoryStream))); // Can be assigned from
			Assert.That(new MemoryStream(), Is.AssignableTo(typeof(Stream))); // Can be assignable to

			Assert.That(new MemoryStream(), Is.InstanceOf<Stream>());  // Is type or ancestor
			Assert.That(new MemoryStream(), Is.TypeOf<MemoryStream>()); // Is type and not ancestor
			Assert.That(new object(), Is.AssignableFrom<MemoryStream>()); // Can be assigned from
			Assert.That(new MemoryStream(), Is.AssignableTo<Stream>()); // Can be assignable to

			// String Comparision
			Assert.That( "Foo", Is.StringContaining( "o" ) );
			Assert.That( "Foo", Is.StringContaining( "O" ).IgnoreCase );
			Assert.That( "Foo", Is.StringStarting( "F" ) );
			Assert.That( "Foo", Is.StringEnding( "o" ) );
			Assert.That( "Foo", Is.StringMatching( "^[F]" ) ); // Regular ecpression match

			// Collection Comparison
			Assert.That( new List<int>(){1,2,3}, Has.All.GreaterThan(0) );
			Assert.That( new List<int>(){1,2,3}, Is.All.GreaterThan(0) );
			Assert.That( new List<int>(){1,2,3}, Has.None.GreaterThan(4));
			Assert.That( new List<int>(){1,2,3}, Has.Some.GreaterThan(2));
			Assert.That( new List<int>(){1,2,3}, Has.Count.EqualTo(3));
			Assert.That( new List<int>(){1,2,3}, Is.Unique);
			Assert.That( new List<int>(){1,2,3}, Has.Member(1));  // Contains
			Assert.That( new List<int>(){1,2,3}, Is.EquivalentTo( new List<int>(){3,2,1})); // Same data without carring about the order
			Assert.That( new List<int>(){1,2,}, Is.SubsetOf( new List<int>(){3,2,1})); // All are cotained.

			// Property Constraint
			Assert.That( new List<int>(), Has.Property("Count").EqualTo(0));  // Checks public property
			Assert.That( new List<int>(), Has.Count.EqualTo(0));			  // Same as Has.Property("Count").EqualTo(0)
			Assert.That( string.Empty, Has.Length.EqualTo(0));				  // Same as Has.Property("Length").EqualTo(0)
			Assert.That ( new Exception("Foo"), Has.Message.EqualTo("Foo"));  // Exception has message
			Assert.That ( new Exception("Foo", new ArgumentException("Moo")), // Inner exception is of type and has message
			             Has.InnerException.InstanceOf<ArgumentException>().And.InnerException.Message.EqualTo("Moo"));

			// Throws Constraint
			// See also Property constrains for Message and Inner Exception
			// Throws.Exception allow AND, Throws.InstanceOf<> is short hand
			Assert.That (() => { throw new ArgumentException("Foo"); },
				Throws.Exception.InstanceOf<ArgumentException>().And.Message.EqualTo("Foo"));

			Assert.That (() => { throw new ArgumentNullException("Foo"); },
				Throws.Exception.TypeOf<ArgumentNullException>());

			Assert.That (() => { throw new ArgumentNullException("Foo"); },
				Throws.InstanceOf<ArgumentNullException>());

			Assert.That (() => { }, Throws.Nothing);

			Assert.That (() => { throw new Exception("Foo", new ArgumentException("Moo"));},
				Throws.Exception.Message.EqualTo("Foo").And.InnerException.InstanceOf<ArgumentException>());

			Assert.That (() => { throw new ArgumentException(); }, Throws.ArgumentException);

			// Compound Constraints
			Assert.That( 2, Is.Not.EqualTo( 1 ));
			Assert.That( new List<int>(){ 1, 2, 3 }, Is.All.GreaterThan( 0 ) );

			Assert.That( 1, Is.GreaterThan( 0 ).And.LessThan( 2 ) );  // .And amd & are the same
			Assert.That( 1, Is.GreaterThan( 0 ) & Is.LessThan( 2 ) );

			Assert.That( 1, Is.LessThan( 10 ) | Is.GreaterThan( 0 ) ); // .Or and | are the same
			Assert.That( 1, Is.LessThan( 10 ).Or.GreaterThan( 0 ) );

			// Delayed
			Assert.That(() => { return true;}, Is.True.After(10));		// Passes after x time
			Assert.That(() => { return true;}, Is.True.After(10, 10));	// Passes after x time and polling..

			// List Mapper
			Assert.That(List.Map(new List<string>(){"1", "22", "333"}).Property("Length"),  // Allows all elememts in a list to have a condition provided for them
			            Is.EqualTo(new List<int>(){1,2,3}));
		}
	}
	# region Elements consumed by the tests above
	public class WhoCaresComparer : IEqualityComparer<int>
	{
	    public bool Equals(int b1, int b2)
	    {
			return true;
	    }

	    public int GetHashCode(int aNumber)
	    {
			return aNumber.GetHashCode();
	    }
	}

	public class ReverseComparer : IComparer
	{
		public int Compare (object a, object b)
		{
			return ((int)b).CompareTo((int)a);
		}
	}

	public enum CustomPropertyValue
	{
    	One,
    	Two,
   	}

	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
	public class CustomPropertyAttribute : PropertyAttribute
	{
    	public CustomPropertyAttribute( CustomPropertyValue value ) : base( "Custom", value.ToString() )
		{
		}
	}
	#endregion
}

JQuery Cheat Sheet

A cheat sheet for JQuery.

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

 


// ******** JQUERY SELECTORS ********

// Selectors
$('#id');			// html id
$('a');				// html tag
$('.cssclass');			// css class
$('#navigationBar a'); 	    	// descendants
$('#body > a'); 		// child nodes
$('#h2 + div');			// adjacent siblings

// Compounds selections
= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
id
name
href

// Attribute Selectors
$('img[alt]');			// has attribute set
$('input[type=text]');		// has attribute value equal to
$('a[href^=http://]');		// has attribute value starting with
$('a[href$=.pdf]');		// has attribute value ending with
$('a[href*=google.com]'); 	// has attribute value containing

// Filters
$('tr:even');			// even elements
$('.strippedTbl tr:even');	// even elements
$('.strippedTbl tr:odd');	// odd elements
$('a:not(.myClass)');		// elements with exclusion filter
$('a:not([href^=http://])');	// elements with exclusion filter
$('li:has(a)');			// elements with inclusion filter
$('a:contains(Click Me!)');	// elements with inclusion text
$('div:hidden').show();		// elements with hidden filter

// ******** METHODS ********
$('.foo').show().width(300);	// Inline chaining
$('.foo').show()				// Multi line chaining
	.width(300)
	.height(300);

$('.foo').html();			// replaces Javascript innerHtml
$('.foo').html = '<br>';		// replaces Javascript innerHtml
$('.foo').text = '<br>';		// encodes html (to show code in html)

// Adding and replacing page content
$('.foo').append('<br>')	// adds as last child element of selected element
$('.foo').prepend('<br>')	// adds as first child element of selected element
$('.foo').before('<br>')	// adds element before
$('.foo').after('<br>')		// adds element aftter
$('.foo').remove()		// removes element
$('.foo').replace('<br>')	// replaces element
$('#AnID tbody:last').append("<tr><td></td></tr>"); // Add html into a section

// Setting and Reading Tag Attributes
$('.foo').addClass('class')		// adds CSS Class
$('.foo').removeClass('class')	    	// remove CSS Class
$('.foo').toggleClass('class')	    	// toggle add/remove CSS Class
$('.foo').css('background-colour')	// Get CSS property.
$('.foo').css('font-size', '200%')	// Set CSS property.
$('.foo').css({
			'background-colour' : '#FF0000',
			'font-size' : '200%'
			});								// Set multiple CSS properties.

// Reading, setting and removing HTML Attributes
$('img').attr('src')			// Get attribute
$('img').attr('src', 'foo.jpg');	// Set attribute
$('img').removeAttr('src');		// Remove attribute
$('img').fadeOut();			// Set attribute

// Examples
$("input[type=text]").val('');							// All text items
$("input[id^=ProductWrapperName][value='Foo']").get(0).id 			// Starts with and has value
$("input[id^=ProductWrapperProductType][value='" + productType + "']").get(0) 	// Starts with and has value
$("input[id^=TrustP][id$=Trustee][value='Yes']").size(); 			// Starts with and ends with and value
$("text[id^=ProductWrapperName]:contains('Foo')")  				// Text box id starts with html contains
$('#chktable' + asTable + 'Match' + jnRecordRow + ':checked').val() != null 	// Element is checked
$('#contributionsInputPanel input').val('');					// Id and input
$("#myid").length > 0								// Element by Id exists
$("#input").val("Hello");							// Set value
$("#input").val();								// Get value
$('#' + prefix + 'CrystallisedRegularIncomeRadioNo').attr("checked", true );    // Check item
$("input[name=DiscardOption]:checked").val();					// Item is checked
$(".selector").attr("checked", false); 						// Check item
$("input[name='Thirdpartytype1']:checked").val();				// Item is checked
$("input").attr("readOnly", true); 						// Set readonly
$("input").removeAttr("readOnly");						// Remove readonly
$("input").attr("disabled", true); 						// Disable
$("input").attr("disabled", ''); 						// Remove readonly
$("select").removeAttr("disabled");
$("input").show();
$("input").hide();

// ******** LOOPS *********

$('img').each(functionName);		// Named function
$('img').each(function(){		// Anon function
	this				// old school element
	$(this)				// jquery element
	});

var myData = { firstName: 'Bob', lastName:, 'Smith'};
$('#foo').bind('click', myData, functionName);
var fname = evt.data.firstName;
$('#foo').bind('click', functionName);

// ******** EVENTS ********
// Registered as functions (see each above)
// Mouse Events
$('.foo').click(functionName);			// called upon release
$('.foo').dblclick(functionName);		// called upon second release
$('.foo').mousedown(functionName);		// called upon left click down
$('.foo').mouseup(functionName);		// called upon release
$('.foo').mouseover(functionName);		// called when mouse enters area
$('.foo').mouseout(functionName);		// called when mouse leaves area
$('.foo').mousemove(functionName);		// called when mouse moves

// Document / window Events
$(document).load(functionName);			// called after everything loaded; ready better
$(window).resize(functionName);			// called upon release of resize (not always)
$(window).scroll(functionName);			// called upon release of scroll (not always)
$(window).unload(functionName);			// called upon exit (not always)

// Form Events
$('.foo').submit(functionName);			// called upon submit of form
$('.foo').reset(functionName);			// called upon reset of form
$('.foo').change(functionName);			// called entity change
$('.foo').focus(functionName);			// called entity focus recieved
$('.foo').blur(functionName);			// called entity focus released

// Keyboard Event
$('.foo').keypress(functionName);		// called upon key release
$('.foo').keydown(functionName);		// called upon key down
$('.foo').keyup(functionName);			// called upon key release

// JQuery Events

// You can chain events
$(document).ready(functionName)			// Called when javascript manimulation should be made
$('#id').hover(showFunc, hideFunc)		// Encompas mouseover and moustout events
$('#id').toggle(togOffFunc, togOffFunc)		// Encompas toggle on and off functions

// Event object
$(document).click(function(evt){});		// Passed into events
evt.pageX;				        // distance from mouse pointer to left page edge
evt.pageY;				        // distant from mouse poiner to top page edge
evt.screenX;			                // distance from mouse pointer to monitor edge x
evt.screenY;			                // distance fom mouse pointer to monitor edge y
evt.shiftKey;			                // boolean indicating if shift key press *
evt.which;				        // numeric code of key press
evt.target;				        // element bound upon
evt.data;					// data passed in with bind method

String.fromCharCode(evt.which);			// * Get char from key code

// Stoppnig and removing events
evt.preventDefault();				    // prevents other events getting raised
return false;					    // shorthand of preventDefault
evt.stopPropagation();				    // Prevents parent elements recieving bubble events
$(document).unbind('click')			    // remove registered events

JavaScript Cheat Sheet

A cheat sheet for JavaScript.

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

<pre>
// Java Script Basics
document.write("
Hello!
");
name = prompt ("Please Enter Your Name.","Your Name Goes Here");

// ******** ARRAYS ********
var foo = [1,2,3];
var foo = new Array( 1,2,3);
foo[2];
foo[2]=3;
foo.length;
foo.push(4);  					// adds an element at the end
foo.push(5,6,7) 				// can take more than one element
foo.unshift(0); 				// adds an element at the beginning
var lastEl = foo.pop(); 		        // gets and removes last element
var firstEl = foo.shift(); 		        // gets and remove first element
var array.splice(index,howMany,e1,e2,ex) 	// adds and or removes elements. Returns remove elements
document.write(arrayFoo); 		        // writes comma separated to documented
foo.concat()  					// joins two or more arrays, and returns a copy of the joined arrays
foo.join() 					// joins all elements of an array into a string
foo.reverse() 					// reverses the order of the elements in an array
foo.slice() 					// Selects a part of an array, and returns the new array
foo.sort() 					// sorts the elements of an array
foo.toString() 					// converts an array to a string, and returns the result
foo.valueOf() 					// returns the primitive value of an array

// ******** LOOPS ********

for (i=0;i<=5;i++){}   		// for
while (i<=5){i++;}		// while
do{i++;} while (i<=5);		// do while
for (x in foo) {foo[x]};	// for in
break; 				// stop loop
continue; 			// continue next iteration

// ******** TRY CATCH THROW ********

try {	} catch(err) {	txt = err.description; }
try {	throw "Err1"; } catch(er)
{
  if(er=="Err1")
  {	alert("Error! The value is too high");
  }
}

// ******** CHARACTERS / STRING ********
// Escape characters
var txt="We are the so-called "Vikings" from the north.";

"\'"  	// single quote
"\"" 	// double quote
"\&" 	// ampersand
"\\" 	// backslash
"\n" 	// new line
"\r" 	// carriage return
"\t" 	// tab
"\b" 	// backspace
"\f" 	// form feed

"".charAt() 				// Returns the character at the specified index
"".charCodeAt() 	 		// Returns the Unicode of the character at the specified index
"".concat() 				// Joins two or more strings, and returns a copy of the joined strings
"".fromCharCode() 		        // Converts Unicode values to characters
"".indexOf() 				// Returns the position of the first found occurrence of a specified value in a string
"".lastIndexOf() 			// Returns the position of the last found occurrence of a specified value in a string
"".match() 				// Searches for a match between a regex and a string, and returns the matches
"".replace() 				// Searches for a match between a substring (or regex) and a string, and replaces
"".search() 				// Searches for a match between a regular expression and a string, and returns the position of the match
"".slice() 				// Extracts a part of a string and returns a new string
"".split() 				// Splits a string into an array of substrings
"".substr() 				// Extracts the characters from a string, beginning at a specified start position, and through the specified number of character
"".substring() 				// Extracts the characters from a string, between two specified indices
"".toLowerCase() 			// Converts a string to lowercase letters
"".toUpperCase() 			// Converts a string to uppercase letters
"".valueOf() 				// Returns the primitive value of a String object

// ******** DATE / TIME ********
today = new Date()
d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)
myDate.setFullYear(2010,0,14)
myDate.setDate(myDate.getDate()+5);

getDate() 			// Returns the day of the month (from 1-31)
getDay() 			// Returns the day of the week (from 0-6)
getFullYear() 			// Returns the year (four digits)
getHours() 			// Returns the hour (from 0-23)
getMilliseconds() 	        // Returns the milliseconds (from 0-999)
getMinutes() 			// Returns the minutes (from 0-59)
getMonth() 			// Returns the month (from 0-11)
getSeconds() 			// Returns the seconds (from 0-59)
getTime() 			// Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() 	 	// Returns the time difference between GMT and local time, in minutes
Date.parse(datestring)		// Parse
setDate()  			// Sets the day of the month (from 1-31)
setFullYear() 			// Sets the year (four digits)
setHours() 			// Sets the hour (from 0-23)
setMilliseconds() 	        // Sets the milliseconds (from 0-999)
setMinutes() 			// Set the minutes (from 0-59)
setMonth() 			// Sets the month (from 0-11)
setSeconds() 			// Sets the seconds (from 0-59)
setTime() 			// Sets a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970
toDateString()  		// Converts the date portion of a Date object into a readable string
toDateString()  		// Converts the date portion of a Date object into a readable string
toGMTString() 			// Deprecated. Use the toUTCString() method instead
toLocaleDateString() 		// Returns the date portion of a Date object as a string, using locale conventions
toLocaleTimeString() 		// Returns the time portion of a Date object as a string, using locale conventions
toLocaleString() 		// Converts a Date object to a string, using locale conventions
toString() 			// Converts a Date object to a string
toTimeString() 			// Converts the time portion of a Date object to a string

// ******** NUMBER ********

Number.NaN
toExponential(x)  	 	// Converts a number into an exponential notation
toFixed(x) 			// Formats a number with x numbers of digits after the decimal point
toPrecision(x) 			// Formats a number to x length
toString() 			// Converts a Number object to a string
valueOf() 			// Returns the primitive value of a Number object

// ******** MATH ********

// Math.Constants
E 				// Returns Eulers number (approx. 2.718)
LN2 				// Returns the natural logarithm of 2 (approx. 0.693)
LN10 			     	// Returns the natural logarithm of 10 (approx. 2.302)
LOG2E 			    	// Returns the base-2 logarithm of E (approx. 1.442)
LOG10E 		        	// Returns the base-10 logarithm of E (approx. 0.434)
PI 				// Returns PI (approx. 3.14159)
SQRT1_2 	        	// Returns the square root of 1/2 (approx. 0.707)
SQRT2 			    	// Returns the square root of 2 (approx. 1.414)

// Math.Methods
abs(x) 				// Returns the absolute value of x
acos(x) 			// Returns the arccosine of x, in radians
asin(x) 			// Returns the arcsine of x, in radians
atan(x) 			// Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) 			// Returns the arctangent of the quotient of its arguments
ceil(x) 			// Returns x, rounded upwards to the nearest integer
cos(x) 				// Returns the cosine of x (x is in radians)
exp(x) 				// Returns the value of Ex
floor(x) 			// Returns x, rounded downwards to the nearest integer
log(x) 				// Returns the natural logarithm (base E) of x
max(x,y,z,...,n) 		// Returns the number with the highest value
min(x,y,z,...,n) 		// Returns the number with the lowest value
pow(x,y) 			// Returns the value of x to the power of y
random() 			// Returns a random number between 0 and 1
round(x) 			// Rounds x to the nearest integer
sin(x) 				// Returns the sine of x (x is in radians)
sqrt(x) 			// Returns the square root of x
tan(x) 				// Returns the tangent of an angle

// ******** GLOBAL *******

// Properties
Infinity 			// A numeric value that represents positive/negative infinity
NaN 				// "Not-a-Number" value
undefined 			// Indicates that a variable has not been assigned a value

// Functions
decodeURI() 		    	// Decodes a URI
decodeURIComponent() 		// Decodes a URI component
encodeURI() 			// Encodes a URI
encodeURIComponent() 		// Encodes a URI component
escape() 			// Encodes a string
eval() 				// Evaluates a string and executes it as if it was script code
isFinite() 			// Determines whether a value is a finite, legal number
isNaN() 			// Determines whether a value is an illegal number
Number() 			// Converts an object's value to a number
parseFloat() 			// Parses a string and returns a floating point number
parseInt() 			// Parses a string and returns an integer
String() 			// Converts an object's value to a string
unescape() 			// Decodes an encoded string