Here is my problem. I am a very big fan of Design by contract, I am using this concept especially when developing libraries that can be used by other developers. I just found out a new way of doing this which is: Contract.Requires instead of Exception:
So instead of having:
public void SomeMethod(string name){
if(name==null) throw new NullArgumentException("Null values not supported");
}
I now have:
public void SomeMethod(string name){
Contract.Requires(name != null);
}
EDIT: I am working under VS2010 on debug mode.
Problem: Contract.Requires does not do anything, even when name is null!
The MSDN documentation says:
Specifies a precondition contract for the enclosing method or
property.
But nothing is specified in case the condition is not met!
I also noticed there are other Contract.Requires overloads that throw exception, display message... but then what is Contract.Requires(Boolean) for?
EDIT Answer below highlighted that a plug-in must be installed to have the full power of Contract API but then what about Mono users who want their code to behave the same on different platforms?
You should do the following:
Install the Code Contracts add-in as nfechner has noted
Go to the project properties, 'Code Contracts' folder
Check 'Perform Runtime Contract Checking'
Switch 'Assembly Mode' to 'Standard Contract Requires'
Substitute your Contract.Requires with Contract.Requires<SomeException> (the first one throws System.Diagnostics.ContractException while the second throws the exception you specified which is important for public methods)
That's the basic setup. For more accurate configuration, refer to the manual
If you use Mono, probably, Contract class is empty. I haven't done this, but chapter seven from the Contracts manual seems to explain how to provide your own implementation.
From the Contract class docs:
Important
You must install a Visual Studio add-in to enforce contracts. The Code
Contracts Premium Edition add-in lets you specify static and run-time
checking of code contracts on the project Properties page. If you do
not enable run-time checking, contracts such as the Contract.Ensures
method will not throw exceptions during run time if a contract is
violated. The Visual Studio add-in does not ship with Visual Studio
2010 or the Windows SDK.
With a message like this it is usually helpful to specify exactly what you have done.
For example, you do not mention in the original message if you have installed the VS Addon, nor that you have enabled it under your project properties, or that you are actually running in debug vs release mode, etc.
Re Contract.Requires vs Contract.Requires<Exception>
Contract.Requires is recommended.
According to the manual
If your code must throw a particular exception on failure of a
particular precondition, you can use the generic overloaded form
below. (Please read Section 5.1 before committing to this form in your
code. You cannot use Requires < Exn <Exn>> without running the contract tools
on all builds. If you do, you will get a runtime failure everytime.)
Related
At compile time, how can I check if a data type (and or value) is being used within a method.
I'm attempting to build a living architecture that supports plugins.
I want the compiler to throw an error if an event is not being raised within the plugin.
I'm using VS2015 Preview.
Any suggestions?
This kind of validation is possible to implement using PostSharp. It is not trivial but easier than using Mono.Cecil. SyntaxTreeVisitor and ISyntaxReflectionService is a good foundation for implementing the analysis algorithm which has to be invoked from Aspect.CompileTimeValidate.
Roslyn must be mentioned as well. It allows you to "extend" C# (or VisualBasic) compiler with custom diagnostics and it is very well integrated with VS2015.
Disclaimer: I'm PostSharp developer.
I don't think you can make the compiler throw that error for you. You might be able to introduce an extra build step that executes a C# console app that checks (using reflection) what you want.
I'm using Code Contracts to declare that a property returns a non-null, non-empty sequence of strings like so:
public IEnumerable<string> Filenames
{
get
{
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
// Next line gives Resharper Warning
// "Possible null assignment to entity marked with 'not null' attribute":
Contract.Ensures(Contract.Result<IEnumerable<string>>().Any());
return new []{"TEST"}; // Dummy data for demo purposes.
}
}
I'm getting a warning from Resharper as described in the code comment above.
This is similar to the question here:, but I have tried applying the fix in the answer to that question and it doesn't fix this particular issue.
Does anyone know how to fix this (other than using Resharper comments to suppress the warning)?
I'm using Resharper 7.1.2 C# Edition, build 7.1.2000.1478
(I've checked on several machines and it happens on all of them. Vanilla install of R# - we haven't modified any of its XML files other than me trying to apply the fix from the answer that I linked above.)
Further information:
I'm trying this with Visual Studio 2012 with update 2, with .Net 4.0 and .Net 4.5.
Also, you need to add the conditional compilation symbol "CONTRACTS_FULL" to the project's Build settings (in the "conditional compilation symbol" textbox).
The problem is that although most of the Code Contracts are covered in ReSharper ExternalAnnotations, Ensures is not one of them (not even in any of the custom xmls floating around).
I just double checked ExternalAnnotations from the latest ReSharper v8 EAP, and they are still exactly the same as in the v7.1.3 - so absolutely nothing has changed so far.
I'll make a new question, asking if anyone knows how to implement it.
UPDATE: Code Contracts Ensures for ReSharper ExternalAnnotations
FINAL: it's not doable at all - simply as the attribute would somehow need to be implied for the method containing the code contract, and not what's inside the code contract itself...
I'm wondering whether should I throw exceptions or call Contract.Requires<TException>
For example:
public static void Function(String str)
{
if (str == null) throw new ArgumentNullException("str", "Input string cannot be null.");
// ...
}
vs
public static void Function(String str)
{
Contract.Requires<ArgumentNullException>(str != null, "Input string cannot be null.");
// ...
}
Since Contract.Requires<TException> doesn't require the CONTRACTS_FULL symbol I can keep it in my release builds as well.
This is my consideration:
Con: You can't call an overloaded version of the custom exception type constructor. There is simply no way to pass additional parameters to the constructor.
Pro: Static tools support (e.g. inform the caller of contract violation).
Which one should I use, and for what kind of situation?
The basic trade-off between if-then-throw and Requires<TException> as documented in the CodeContract user guide is how you build with your release bits.
Case 1: You only use if-then-throw, no Requires<TException>. In this case you can build your release bits without running the contract tools on your dll/exe. The advantage is that you have faster builds and no risk that the tool introduces bugs. A second advantage is that team members can opt out of using the CodeContract tools. Disadvantages are that you get no contract inheritance of requires, and your contracts are not necessarily visible to the tools (unless you use EndContract). You specify this case by using assembly mode: Custom Parameter Validation
Case2: You decide to run the CodeContract tools on your release bits always. This lets you use Requires<TException> and you get inheritance of contracts, including instrumentation of interfaces etc. Your contracts are clean and tool recognizable. The disadvantage is that everyone building your code must have the CodeContracts tools installed. You specify this case by using assembly mode: Standard in the Contract property pane.
Hope this clear things up.
I'm not sure that there are any earth-shattering differences between the two approaches, but here are two reasons why I prefer contracts...
1) The code is much neater, as you are writing a statement at the top of the method that shows the assumptions upon which the method is based. You don't clog up the code with the implementation of what happens if the assumption is violated.
2) You get the benefit of Visual Studio picking up on the code contracts when you are writing code, and giving you hints as to what the method you are about to call expects. This helps you ensure that you are sending the method valid parameters, without having to jump to the method definition to check the code there.
Once the code is compiled and running, I don't think there are any significant differences.
Hope this helps.
I've recently started using a private NuGet server to manage my organization's internal libraries. This means in order to step into our own code that is in a library, I need to disable "Enable Just My Code" in debugging options since we aren't referring to the projects directly any more. This is a pretty hefty MVC project that uses dynamic types and ExpandoObjects in addition to ViewBag. I get two RuntimeBinderExceptions for every single use of a dynamic type... which is a lot. This appears to be normal behavior from what I've read. Normal it may be, but useful it is not.
My first thought was to disable this particular exeption in the Debug-> Exceptions dialog. The exception is not to be found there. I can't figure out any way to be able to step outside the projects referenced directly, without also opening myself up to these exceptions. (And all manner of other low-level framework exceptions that I don't want to hear about, but this is the biggest offender by far).
What's the best way to deal with this?
Edit: This is the problem. How do I stop this with "Enable Just My Code" disabled?
You can add additional "exception" names (existing in your own code or other libraries)...so long as you know the exception's fully qualified type name.
Managing Exception with the Debugger
https://msdn.microsoft.com/en-us/library/x85tt0dd.aspx
In Visual Studio 2010
Via the Debug | Exceptions... dialog.
Use the Add button to add a new exception under the Common Language Runtime Exceptions group and call it Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
then just make sure Thrown and User-Handled are NOT ticked - thus causing the first chance exception to be ignored, rather than being caught by the debugger.
In Visual Studio 2017
Via the Debug | Windows | Exception Settings... panel
Use + to add the new exception name
make sure it's unticked
After reading about the System.Diagnostics.Contracts.Contract static class that has been influenced by the awesomeness of Spec# I was thrilled and immediately started peppering my code with calls to Contract.Requires() and Contract.Ensures().
I guess it's just because my code is so super-awesome and bug-free that checking that those calls actually did something just didn't come up until recently. A bug slipped through and I came to the realization that these calls do not do anything! I would have thought that they at least throw an exception when the condition is violated but no such luck.
Am I missing something? Does anyone know what the heck is the point?
From the Contract Class page at MSDN:
You must use a binary rewriter to
insert run-time enforcement of
contracts. Otherwise, contracts such
as the Contract.Ensures method can
only be tested statically and will not
throw exceptions during run time if a
contract is violated. You can download
the binary rewriter CCRewrite from
Code Contracts on the MSDN DevLabs Web
site. CCRewrite comes with a Visual
Studio add-in that enables you to
activate run-time contract enforcement
from the project Properties page. The
binary rewriter and the Visual Studio
add-in do not ship with Visual Studio
2010 or the Windows SDK.
Expanding on JSBangs' answer:
You must check the "Perform Runtime Contract Checking" box here:
(I also checked the "Static Checking > Peform Static Contract Checking" box)
If you want the .Requires call to throw an error you need to set an option in project settings or use .Requires<T> call