ISpecification

public interface ISpecification<T> { bool IsSatisfiedBy(T candidate); ISpecification<T> And(ISpecification<T> other); ISpecification<T> Or(ISpecification<T> other); ISpecification<T> XOr(ISpecification<T> other); ISpecification<T> AndAllOf(IEnumerable<ISpecification<T>> specifications); T Target { get; set; } void GetResults(ResultsVisitor visitor); IEnumerable<Type> WhatWasAssessed(); Risks.IDemoCommand GetCommand(); } using System; using System.Collections.Generic; using Demo.Core.Commands; using Demo.Core.Risks; using Demo.Core.Specification.Common; namespace Demo.Core.Specification { public abstract class AbstractSpecification<T> : ISpecification<T> { protected SpecificationResult result; protected IList<Type> ruleList = new List<Type>(); protected bool SoftCheck { get; set; } public T Candidate { get; set; } public T Target { get; set; } public bool IsReplay {protected get; set;} public ISpecification<T> And(ISpecification<T> other) { return new AndSpecification<T>(this, other); } public ISpecification<T> Or(ISpecification<T> other) { return new OrSpecification<T>(this, other); } public ISpecification<T> XOr(ISpecification<T> other) { return new XORSpecification<T>(this, other); } public ISpecification<T> AndAllOf(IEnumerable<ISpecification<T>> specifications) { return new AndAllOfSpecification<T>(this, specifications); } public virtual bool Evaluate(T candidate) { throw new NotImplementedException("You need to provide a predicate or override IsSatisfiedBy"); } public virtual IDemoCommand GetCommand() { return new NoCommand(); } public virtual void GetResults(ResultsVisitor visitor) { if (result != null && !string.IsNullOrEmpty(result.Message)) { visitor.Add(result); } } public virtual IEnumerable<Type> WhatWasAssessed() { return ruleList; } public virtual string MessageFormat() { throw new NotImplementedException("You need to provide a result a message or override IsSatisfiedBy"); } public virtual bool IsSatisfiedBy(T candidate) { if (IsReplay) { return true; } Type ruleType = GetType(); ruleList.Add(ruleType); Candidate = candidate; bool satisfied = Evaluate(candidate); if (!satisfied || (SoftCheck && !string.IsNullOrEmpty(result.Message))) { result = new SpecificationResult { Satisfied = SoftCheck, Message = string.Format(MessageFormat(), candidate, Target) }; } return satisfied; } public AbstractSpecification<T> SuccessOrRhs(ISpecification<T> specification) { return new SuccessOrRhsSpecification<T>(specification); } } }

February 2010 · Smart Tech

Castle Windsor – WCF Endpoint Configuration

const int maxSize = 52428800; var binding = new BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; binding.Security.Message.AlgorithmSuite = SecurityAlgorithmSuite.Default; binding.MaxReceivedMessageSize = 1000000; binding.CloseTimeout = new TimeSpan(0, 1, 0); binding.OpenTimeout = new TimeSpan(0,1,0); binding.ReceiveTimeout = new TimeSpan(0,10,0); binding.SendTimeout = new TimeSpan(0,1,0); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MaxBufferSize = maxSize; binding.MaxBufferPoolSize = maxSize; binding.MaxReceivedMessageSize = maxSize; binding.MessageEncoding = WSMessageEncoding.Mtom; binding.TextEncoding = Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; binding.ReaderQuotas.MaxDepth = 32; binding.ReaderQuotas.MaxStringContentLength = maxSize; binding.ReaderQuotas.MaxArrayLength = maxSize; binding.ReaderQuotas.MaxBytesPerRead = maxSize; binding.ReaderQuotas.MaxNameTableCharCount = maxSize; container = new IocContainer(LifestyleType.Transient); container.AddFacility<WcfFacility>().Register( Component .For<ISharePointFacadeService>() .Named("DmsGateway") .ActAs( new DefaultClientModel() { Endpoint = WcfEndpoint .BoundTo(binding) .At("http://localhost/SharepointFacade/DMSService.svc/mex") }));

February 2010 · Smart Tech

ConvertPropertiesAndValuesToHashtable Extension method

public static class Extensions { public static Hashtable ConvertPropertiesAndValuesToHashtable(this object obj) { var ht = new Hashtable(); // get all public static properties of obj type var propertyInfos = obj.GetType().GetProperties().Where(a=>a.MemberType.Equals(MemberTypes.Property)).ToArray(); // sort properties by name Array.Sort(propertyInfos, (propertyInfo1, propertyInfo2) => propertyInfo1.Name.CompareTo(propertyInfo2.Name)); // write property names foreach (PropertyInfo propertyInfo in propertyInfos) { ht.Add(propertyInfo.Name, propertyInfo.GetValue(obj, BindingFlags.Public, null, null, CultureInfo.CurrentCulture)); } return ht; } } Tests using System; using System.Collections; using System.Globalization; using System.Linq; using System.Reflection; ...

January 2010 · Smart Tech

Obliterate Database

declare @vcFK varchar(250), @vcTable varchar(250), @vcSP varchar(250), @vcView varchar(250), @vcFn varchar(250) -- ...drop all foreign key constraints select @vcFK = min(name) from sysobjects where type='F' while @vcFK is not null begin print 'Dropping FK constraint ' + @vcFK -- ...get name of table corresponding to the foreign key select @vcTable = S2.name from sysobjects S1 inner join sysconstraints C on S1.id = C.constid inner join sysobjects S2 on C.id = S2.id where S1.name = @vcFK and S1.type='F' exec ('alter table ' + @vcTable + ' drop constraint ' + @vcFK) select @vcFK = min(name) from sysobjects where type='F' and name > @vcFK end -- ...drop all tables select @vcTable = min(name) from sysobjects where type='U' and name not like 'dt%' while @vcTable is not null begin print 'Dropping table ' + @vcTable exec ('drop table ' + @vcTable) select @vcTable = min(name) from sysobjects where type='U' and name not like 'dt%' and name > @vcTable end -- ...drop all our stored procedures select @vcSP = min(name) from sysobjects where type='P' and (name like 'usp%') while @vcSP is not null begin print 'Dropping procedure ' + @vcSP exec ('drop procedure ' + @vcSP) select @vcSP = min(name) from sysobjects where type='P' and (name like 'usp%') and name > @vcSP end -- ...drop all views select @vcView = min(name) from sysobjects where type='V' and name like 'v%' while @vcView is not null begin print 'Dropping view ' + @vcView exec ('drop view ' + @vcView) select @vcView = min(name) from sysobjects where type='V' and name like 'v%' and name > @vcView end -- ...drop all functions select @vcFn = min(name) from sysobjects where type='FN' and name like 'udf%' while @vcFn is not null begin print 'Dropping function ' + @vcFn exec ('drop function ' + @vcFn) select @vcFn = min(name) from sysobjects where type='FN' and name like 'udf%' and name > @vcFn end

December 2009 · Smart Tech

WCF Tracing

In the web.config in between the tags <system.diagnostics> <sources> <source name=“System.ServiceModel” switchValue=“Information, ActivityTracing” propagateActivity=“true”> <listeners> <add name=“traceListener” type=“System.Diagnostics.XmlWriterTraceListener” initializeData= “WCFTrace.svclog” /> </listeners> </source> </sources> <trace autoflush=“true” /> </system.diagnostics>

November 2009 · Smart Tech

Log4Net config

Log4Net config <? xml version\="1.0" encoding\="utf-8" ?\> <configuration> <log4net> <appender name=“WindowsEventAppender” type=“log4net.Appender.EventLogAppender”> <param name=“LogName” value=“Application” /> <applicationName value=“Phoenix” /> <layout type=“log4net.Layout.PatternLayout”> <conversionPattern value="%date [%thread] %-5level %logger%newline => %message%newline" /> </layout> <filter type=“log4net.Filter.LevelRangeFilter”> <param name=“LevelMin” value=“DEBUG” /> </filter> </appender> <appender name=“RollingFile” type=“log4net.Appender.RollingFileAppender”> <file type=“log4net.Util.PatternString” value=“logs\\phoenix.log” /> <appendToFile value=“true” /> <maximumFileSize value=“500KB” /> <maxSizeRollBackups value=“2” /> <layout type=“log4net.Layout.PatternLayout”> <conversionPattern value="%date [%thread] %-5level %logger%newline => %message%newline" /> </layout> </appender> <root> <level value=“DEBUG” /> <appender-ref ref=“WindowsEventAppender” /> <appender-ref ref=“RollingFile” /> </root> </log4net> </configuration> ...

October 2009 · Smart Tech

Context Specification

Context Specification Base Class namespace Example { using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Rhino.Mocks; public abstract class ContextSpecification<T> { protected Exception executionException; protected T sut { get; set; } [TestInitialize\] public void Start() { this.Context(); this.SetupMockResults(); this.Because(); } [TestCleanup\] public void CleanUp() { this.Clean(); } protected virtual void Context() { } protected virtual void SetupMockResults() { } protected virtual void Because() { } protected virtual void Clean() { } protected TInterface GetDependency<TInterface>() where TInterface : class { return MockRepository.GenerateMock<TInterface>(); } public void Execute(Action action) { try { action(); } catch (Exception ex) { executionException = ex; } } } } ...

October 2009 · Smart Tech

SQL Server error handling

CREATE PROCEDURE AS BEGIN SET NOCOUNT ON BEGIN TRY --Do work END TRY BEGIN CATCH /* Note that catching and rethrowing an exception is a lossy operation. ERROR_PROCEDURE() etc will be reset. */ DECLARE @errorMessage NVARCHAR(4000); DECLARE @errorSeverity INT; DECLARE @errorState INT; SELECT @errorMessage = ERROR\_MESSAGE(), @errorSeverity = ERROR\_SEVERITY() , @errorState = ERROR\_STATE(); --Perform required recovery actions. RAISERROR ( @errorMessage, @errorSeverity, @errorState ); RETURN 1; END CATCH ...

September 2009 · Smart Tech

Resharper Live Templates

September 2009 · Smart Tech

Extensions Methods

All these extension methods are now contained here https://github.com/chrismckelt/ExtensionMinder and available on nuget at https://www.nuget.org/packages/ExtensionMinder/

July 2009 · Smart Tech

RandomHelper

using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace TestHelpers { public static class RandomHelper { /* This method can be used to fill all public properties of an object with random values depending on their type. CAUTION: it does not fill attributes that end with 'ID' or attributes which are called 'pk'. They have to be filled manually.*/ private static readonly Random randomSeed = new Random(); /* Generates a random string with the given length*/ public static T FillPropertiesWithRandomValues<T>(bool fillBaseObjects) { return CreateItem<T>(true); } public static T FillPropertiesWithRandomValues<T>() { return CreateItem<T>(false); } private static T CreateItem<T>(bool fillBaseObjects) { Type type = typeof (T); var item = (T) Activator.CreateInstance(typeof (T)); while (type != null) { PropertyInfo[] infos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (infos.Length == 0) { if (item.GetType().BaseType != null) { infos = item.GetType().BaseType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); } } foreach (PropertyInfo info in infos) { Type infoType = info.PropertyType; Type nullableType = null; if (infoType.IsGenericType && infoType.GetGenericTypeDefinition().Equals(typeof (Nullable<>))) { nullableType = ExtractTypeFromNullable(infoType); } if (!info.CanWrite) continue; if (infoType.Equals(typeof (DateTime)) || infoType.Equals(typeof (DateTime?))) { info.SetValue(item, RandomDateTime(DateTime.Now, new DateTime(3000, 01, 01)), null); } else if (infoType.Equals(typeof (string))) { info.SetValue(item, info.Name + "_" + RandomString(20, false), null); } else if ((infoType.Equals(typeof (long)) || infoType.Equals(typeof (double)) || infoType.Equals(typeof (int)) || infoType.Equals(typeof (long)) || infoType.Equals(typeof (int))) && !info.Name.ToLower().EndsWith("id") && !info.Name.ToLower().Equals("pk")) { info.SetValue(item, RandomNumber(0, 999999), null); } else if ((infoType.Equals(typeof (long?)) || infoType.Equals(typeof (double?)) || infoType.Equals(typeof (int?)) || infoType.Equals(typeof (long?)) || infoType.Equals(typeof (int?))) && !info.Name.ToLower().EndsWith("id") && !info.Name.ToLower().Equals("pk")) { Type genericType = info.PropertyType.GetGenericArguments()[0]; info.SetValue(item, Convert.ChangeType(RandomNumber(0, 999999), genericType), null); } else if (infoType.Equals(typeof (decimal))) { info.SetValue(item, 1m, null); } else if (infoType.Equals(typeof (bool))) { info.SetValue(item, true, null); } else if (infoType.Equals(typeof (Guid))) { info.SetValue(item, Guid.NewGuid(), null); } else if (infoType.Equals(typeof (Enum))) { Array values = Enum.GetValues(infoType); List<object> list = values.Cast<object>().ToList(); object val = list[new Random().Next(0, list.Count)]; info.SetValue(item, val, null); } else if (((infoType.BaseType != null) && (infoType.BaseType.Equals(typeof (Enum))))) { Array values = Enum.GetValues(infoType); List<object> list = values.Cast<object>().ToList(); object val = list[new Random().Next(0, list.Count)]; info.SetValue(item, val, null); } else if (nullableType != null) { if (nullableType.BaseType.Equals(typeof (Enum))) { Array values = Enum.GetValues(nullableType); List<object> list = values.Cast<object>().ToList(); object val = list[new Random().Next(0, list.Count)]; info.SetValue(item, val, null); } } else if (infoType.IsArray) { Console.WriteLine("Object contains array of objects need to fill these"); MethodInfo sm = info.GetSetMethod(true); if (sm.ReturnType.IsArray) { object arrayObject = sm.Invoke(item, null); foreach (object element in (Array) arrayObject) { foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties()) { Console.WriteLine(arrayObjPinfo.Name + ":" + arrayObjPinfo.GetGetMethod().Invoke(element, null)); } } } } } if (!fillBaseObjects) break; type = type.BaseType; } return item; } ///<summary>Indentify and extracting type from Nullable Type</summary> public static Type ExtractTypeFromNullable(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>)) { PropertyInfo valueProp = type.GetProperty("Value"); return valueProp.PropertyType; } else { return null; } } public static string RandomString(int size, bool lowerCase) { var randomString = new StringBuilder(size); /* Ascii start position (65 = A / 97 = a)*/ int start = lowerCase ? 97 : 65; /* Add random chars*/ for (int i = 0; i < size; i++) { randomString.Append((char) ((26*randomSeed.NextDouble()) + start)); } return randomString.ToString(); } public static int RandomNumber(int minimal, int maximal) { return randomSeed.Next(minimal, maximal); } /* Returns a random boolean value*/ public static bool RandomBool() { return randomSeed.NextDouble() > 0.5; } /* Returns a random color*/ public static DateTime RandomDateTime(DateTime min, DateTime max) { if (max <= min) { const string message = "Max must be greater than min."; throw new ArgumentException(message); } long minTicks = min.Ticks; long maxTicks = max.Ticks; double rn = ((Convert.ToDouble(maxTicks) - Convert.ToDouble(minTicks))*randomSeed.NextDouble()) + Convert.ToDouble(minTicks); return new DateTime(Convert.ToInt64(rn)); } } }

April 2009 · Smart Tech

Design Principles

The Open/Closed Principle Software entities (classes, modules, etc) should be open for extension, but closed for modification The Liskov Substitution Principle Liskov’s notion of “subtype” is based on the notion of substitutability; that is, if S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program (e.g., correctness). ie Derived classes must be usable through the base class interface without the need for the user to know the difference ...

March 2009 · Smart Tech

Sorting Algorithms

Bubble Heap Insertion Merge Quick Selection Shell Which sorting algorithm has the best asymptotic runtime complexity? Heap Sort

March 2009 · Smart Tech

Winforms UI cross thread operations

ThreadPool.QueueUserWorkItem(new WaitCallback(LoadUsers)); private void LoadUsers(Object stateInfo) { var site = new SPSite(testHarnessSettings.Url); var web = site.OpenWeb(); foreach(SPUser user in web.AllUsers) { if (usersListBox.InvokeRequired) { usersListBox.Invoke( new MethodInvoker( delegate { usersListBox.Items.Add((user.LoginName)); })); } }

February 2009 · Smart Tech

Biztalk notes

Databases SSODB – Enterprise Single Sign-On database BizTalkRuleEngineDB – Repository for your business rules BizTalkMsgBoxDb – Storage for a multitude of BizTalk activities, notably messages BizTalkMgmtDb – Database for server meta data BizTalkHwsDb – Human Workflow Services storage database BizTalkEdiDb – State data for the EDI adapter BizTalkDTADb – BizTalk tracking engine storage BizTalkStarSchema – Staging, dimension, and measure tables BAMPrimaryImport – Raw tracking data for BAM BAMArchive – Archive for older business activity BAMAlertsNSMain – Notification services for BAM monitoring BAMAlertsApplication – Alert information for BAM notifications Orchestration Tools ...

February 2009 · Smart Tech

WCF Windsor Interceptor, AOP with Logging and Exception Handler Interceptor

The above example uses Windows Communication Foundation (WCF) Integration Facility The main idea here is that WCF should get the service instances from Windsor, which gives us all the usual advantages of IoC plus Windsor’s interceptors capabilities. It isn’t a lot of code, but it makes it much easier to work with WCF services. The service contains 2 simple methods on the HelloWorld class. SayHello – returns a string “Hello World” ThrowException – throws an exception Every single call to each of these is intercepted and logged. Whilst the throw exception will always be caught by the exceptionhandler interceptor. ...

February 2009 · Smart Tech

Performance Testing using a counting semaphore -- Dijkstra

Running some performance tests using Fitnesse to test the limits of a new Sharepoint DMS solution produced this solution. The code we are trying to test is the AddDocument and the time it takes each call to this to succeed. So we need to add n number of documents to Sharepoint using x number of threads through a WCF service_,_ where n and x are configurable via the Fitnesse wiki ...

January 2009 · Smart Tech

NANT CruiseControl NUnit - How to get unit tests running and displaying on the build server

NANT CruiseControl NUnit - How to get unit tests running and displaying on the build server <target name="webtest" haltonfailure="false" failonerror="true"\> <echo message="Running unit tests"/> <echo message="${project.local.folder}"/> <property name="test\_dll\_folder" value\="${project.local.folder}\\McKelt.Tests\\bin\\Debug\\"/> <exec failonerror="true" program="${nunit-console.exe}" workingdir="${project.local.folder}" verbose="true" append="true" commandline="${test\_dll\_folder}McKelt.Tests.dll /xml=${test\_dll\_folder}TestResults.xml /output=${test\_dll\_folder}TestOutput.txt /err=${test\_dll\_folder}TestErrorOutput.txt"> </exec> <echo message="-- TEST COMPLETE -- "/> In the following file – c:\program files\CruiseControl.Net\Server\CCNet.config <msbuild> <executable>C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe</executable> <workingDirectory>C:\CCWorking\McKeltOnlineForms\CodeBase\</workingDirectory> <projectFile>McKeltOnlineForms.sln</projectFile> <buildArgs> /noconsolelogger /p:Configuration=Debug /v:quiet </buildArgs> <targets>Rebuild</targets> <timeout>120</timeout> <logger>c:\Program Files\CruiseControl.NET\server\Rodemeyer.MsBuildToCCNet.dll</logger> </msbuild> </tasks> <publishers> <merge> <files> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\McKelt.Web.Application.Tests\bin\Debug\testresults.xml</file> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\McKelt.Service.Implementations.Tests\bin\Debug\testresults.xml</file> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\Tests\AcceptanceTests\bin\Debug\TestResults.xml</file> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\McKelt.Web.Application.Tests\bin\Debug\*Output.txt</file> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\McKelt.Service.Implementations.Tests\bin\Debug\*Output.txt</file> <file>C:\CCWorking\McKeltOnlineForms\CodeBase\Tests\AcceptanceTests\bin\Debug\*Output.txt</file> </files> </merge> </publishers> ...

December 2008 · Smart Tech

Windows SharePoint Services Notes

SharePoint main objects SPSite = Site; Collection SPWeb = Site Web; SPSite siteCollection = new SPSite("http://localhost/sites/sitename"); SPWeb web = siteCollection.OpenWeb(); Features Features define a mechanism for defining site elements and adding them to a target site or site collection through a process called feature activation An example feature <Feature Id=“6AA03A00-02B5-4d83-A041-1CEB0DE9EF9E” Title=“Chris Document Manager” Description=“Test description” Version=“1.0.0.0” Scope=“Web” ImageUrl=“TestImage.gif” ReceiverAssembly=“DocumentManager, Version=1.0.0.0, Culture=neutral, PublicKeyToken=52cb0cd67d773ef7” ReceiverClass=“DocumentManager.FeatureReceiver” xmlns=“http://schemas.microsoft.com/sharepoint/"> <ElementManifests> <ElementManifest Location=“elements.xml” /> </ElementManifests> </Feature> ...

October 2008 · Smart Tech

How to use DB Deploy

Here is a quick example of how to use DB Deploy This example uses NANT to run DBDeploy which in turn generates the output.sql file. This is then run against the database causing our changes to be run in and putting an entry in the ChangeLog table to tell you which sql files have been run. To run this sample Download to a location on your computer e.g. C:\Examples\DBDeployExample Create a database onyour localhost called DBDeployExample In a command prompt (Or PowerShell) use NANT to build the solution –(I have this setup as an environment variable setup and simply type ‘NANT’) NANT will build the default.build file and run the database changes Opening the solution file looks like this ...

August 2008 · Smart Tech