nContract - Quick Start Guide
The purpose of this quick start guide is to step through a simple but complete example of how to create a third party component with configurable run-time checks of a contract specification using nContract. To fully follow along with this example you will need to download nContract QuickStart.
Create third party component
Here is a simple component with a single class and a single method DoWork that requires the input parameter to be greater than zero.
using ContractSpecification; [FormallySpecified] public class Test { [Pre("i > 0")] public virtual void DoWork(int i) { } }
Build the component with the following command:
csc /target:library /reference:ContractSpecification.dll Test.cs
Generate component with run-time checks
Now run Test.dll through nContract by running the command
nContract test.dll
This will produce TestWithChecks.dll and TestWithChecksConfig.xml
Use third party component
Here is a simple console application that uses the third party component. Notice that it uses a Factory method instead of the new operator to create the class.
using ContractSpecification; class Program { static void Main(string[] args) { Test test = Factory<Test>.Create(); test.DoWork(-1); } }
Build this client application with the following command:
csc /target:winexe /reference:ContractSpecification.dll,Test.dll ClientApp.cs
Configure run-time checks
Since the checks are enabled by default running ClientApp.exe will produce an assertion "Precondition failed on condition: i > 0".
By editing the TestWithChecksConfig.xml file one can configure the run-time checks.
<ClassConfiguration xsi:type="TestConfiguration" TypeName="Test" Enabled="true" UseDefaultTraceAssert="true"> <ctor_Void PreDisabled="false" PostDisabled="false" ExceptionalPostDisabled="false" InvariantDisabled="false" /> <DoWork_Int32 PreDisabled="false" PostDisabled="false" ExceptionalPostDisabled="false" InvariantDisabled="false" /> </ClassConfiguration>
To disable the checks for the entire class change Enabled="true" to Enabled="false".
Re-running ClientApp.exe will not produce an assertion because the checks have been turned off for that class. One can also enable or disable the checks on an individual method and check type level.
This example may seem very elementary but it shows the process, for more details see nContract Overview or nContract Thesis.