Setting up Code Contracts in Visual Studio 2010 - c#

So I was trying to run some simple code with Code Contracts (that I haven't used for some time)
static void Main(string[] args)
{
double res = sqrt(-5);
}
static double sqrt(int a)
{
Contract.Requires(a >= 0, "a must be >= 0!");
return Math.Sqrt(a);
}
But it doesn't seem to do anything at all when I run it. From what I recall from some months ago, it should throw up an error about a being less than 0.
I reinstalled the Academic version from the Code Contracts site just to be safe and this still doesn't seem to be working. What are the steps needed to put Code Contracts to work?
EDIT: Resharper is telling me on Contract.Requires(a >= 0); that the method is being skipped, as it is either "conditional or a partial method without implementation".
Thanks

You should check this web page: link text
You should go to the project properties, Code Contracts tab and click the Runtime checkboxes.

Related

Can't step Into and debug the serviced component source code

I have developed a COM+ Component in C# be inheriting ServicedComponent.
Here is how it looks like:
[Transaction(TransactionOption.Required)]
[ClassInterface(ClassInterfaceType.AutoDual)]
[EventTrackingEnabledAttribute(true)]
[JustInTimeActivation]
[ObjectPooling(Enabled = true, MinPoolSize = 10, MaxPoolSize = 30, CreationTimeout = 15000)]
[Synchronization]
class MyComponent: System.EnterpriseServices.ServicedComponent
{
[AutoComplete(true)]
public string getHello()
{//2nd breakpoint
ContextUtil.SetComplete();
return "HelloWorld";
}
}
I have another test project from which I call this component.
class Program
{
static void Main(string[] args)
{
MyComponent myComp = new MyComponent();
myComp.getHello();//1st Breakpoint
}
}
I am not able to reach 2nd Breakpoint. This was working before I switched to VS 2012. Strange thing is after switching to 2012 its no longer working in VS 2010 too.
I've already tried,
Attach to process
Unchecked "Enable Just My Code" in debug settings
Can someone please give direction from here?
UPDATE 1
From the links given by Mike, I tried symchk for my DLL in the same folder where DLL and PDB files were there. It fails with error saying PDB mismatched or not found. I don't know how to resolve this error.
You may be missing the .pdb file in your project.
Check this microsoft link out for an explanation: https://msdn.microsoft.com/en-us/library/yd4f8bd1(vs.71).aspx

'Could not copy file "obj\x86\debug\..." ' Error After Adding Four Lines of Code

I'm getting this error:
Could not copy the file "obj\x86\Debug\TitleGenerator.exe" because it was not found.
When I try to compile, but it doesn't make any sense. The only thing I changed was to add the following lines of code to help me debug an issue:
#if DEBUG
if( title.Culture == null || title.Religion == null )
{
}
#endif
If I remove those lines, it compiles with no issue. If I change the if statement to if ( true ) {} it compiles fine.
Restarting Visual Studio doesn't help. I've also tried restarting my PC. As far as I can tell, the .Net framework, and Visual Studio are both up to date.
I'm using Visual Studio 2012, a target framework of 3.5, with the Default language level, CSS version 3.0
[Edit] It's now started working again. All I did was to remove output of title.TitleID from the output to the log.
Meaning I changed things like Log( " --Title in Ignore List: " + title.TitleID ); to Log( " --Title in Ignore List" );
The contents of title are decided during runtime, and it's the object of a foreach loop over a list.
Even more strangely, if I add this class to the project:
public class DebugBreak
{
[Conditional("DEBUG")]
public static void TitleIDBreak( Title title, string id )
{
if ( title.TitleID == id )
System.Diagnostics.Debugger.Break();
}
}
But don't even do anything with it, then it works. I don't even have to call the method. Just changing the build action of the file from None to Compile makes it work.
This is commonly caused by Avast.
If you are running that antivirus, add an exclusion for your project folder.
I've searched for this several times in the past. Its a file access issue, so it may not be your code at all.
What type is title? Is it even defined? Statements are checked for semantics even if DEBUG is not defined.
I'm guessing your code is not compiling.
C# does not use a "pre-processor" like early C compilers where the file was changed before the compiler even saw it.
There's nothing wrong with the code you have written based purely on what you've posted.
One thing you can try is to use a Conditional attribute for your debugging. Something like:
[Conditional("DEBUG")]
static void TitleCheck(Title title)
{
if( title.Culture == null || title.Religion == null )
{
System.Diagnostics.Debugger.Break();
}
}
private void MyProductionFunction(Title title)
{
// Do some stuff
TitleCheck(title); //<< This function call will be omitted completely if 'debug' conditional isn't met.
// Do more stuff
}

Is static checking performed for Contract.Ensures?

I cannot understand why static checker says that everything is ok for this method:
public static int GetNonNegativeValue()
{
Contract.Ensures(Contract.Result<int>() >= 0);
return -1;
}
Static checking is on.
Update:
this is also ok.
var i = Doer.GetNonNegativeValue();
Contract.Assert(i < 0);
It seems as if this warning disappears when you activate "Infer Requires" in the settings of the static checker.
It will than infer Contract.Requires(false) ("CodeContracts: Suggested requires: Contract.Requires(false);") which will make this method "invalid", as it now can't be called without raising a contract exception. It looks like the contract checker doesn't verify the Ensures on such a method, because it wouldn't execute the return statement anyway.
BTW: Activating or deactivating "Show squigglies" doesn't change this behaviour in any way. I can only assume that the OP didn't just change this setting when he tested it.
You might want to re-check the following check box and then, rebuild the project:
right click on the project -> Properties -> Code Contracts -> Show squigglies
Also, make sure that your solution's Active Config (or the specific project's Build configuration) matches the Configuration from the Code Contracts property page.

Code Contract : ccrewrite exited with code -1?

I'm new to code contracts. I downloaded the latest build of code contract project (1.4.40314.1) and started to implement it in my project. When i enabled 'Runtume Checking' through Code Contracts Tab in VS2010, i got this Error
Error 1 The command ""C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrewrite" "#Application1ccrewrite.rsp"" exited with code -1.
everytime i build the project. Plz help.
Now it's a major problem for me.
Every project using code contracts is showing same error in VS2010 Errors window and 'Application1ccrewrite.rsp' not found in output window, but it is there.
I tried out everything. I installed both versions (Pro, Std) but the problem persist. Plz help !
I had this problem as well. In my case the problem was that ccrewrite cannot work with files in a network folder but requires the project to be on your local hard disk.
I had this problem. The Assembly name and Default namespace of the class library that causes the problem had the same name as an existing DLL in the destination folder. I had been refactoring my code and whilst the namespaces in the CS files had all be changed to namespace2 the default namespace in the properties file was still namespace1
When I corrected this the files all built successfully...
Sometimes you can get this when your solution path is too long, especially with many projects.
Try moving to c:\temp and building it, it might fix it (although of course, this might not be a solution if you need it in the folder it currently is).
This bug I noticed in earlier CC versions and may now be fixed.
I don't know if you had the same problem as me, but I also saw this error. In my case, I had a method with a switch statement, and depending on the branch taken, different requirements applied:
static ITransaction CreateTransaction(
String transType,
MyType1 parm1,
/* Other params unimportant to this example */
String parm5)
{
switch (transType) {
case Transaction.Type.SOME_TRANSFER:
Contract.Requires<ArgumentNullException>(parm1.Account != null, "Account cannot be null.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm5), "parm5 cannot be null or empty.");
// Create instance
return someInst;
case Transaction.Type.SOME_OTHER_TRANSFER:
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Type), "Type cannot be null or empty.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Number), "Number cannot be null or empty.");
// Create instance
return someInst;
/* Other cases */
default:
throw new ApplicationException("Invalid or unknown transaction type provided.");
}
}
This was giving me the error you noted in the Errors List when I tried to build. In the output window, I was getting this:
EXEC : Reference Assembly Generator
warning : Something is wrong with
contract number 1 in the method
'TerraCognita.LoanExpress.Domain.Loan.CreateLoanTransaction'
AsmMeta failed with uncaught
exception: Operation is not valid due
to the current state of the object.
I pushed each branch into a method of its own, making Contract.Requires the first lines of code in each method, and I no longer had a compilation problem. It appears that Contract.Requires must be the first lines of code in a method - which makes sense, since they are intended to be used to define pre-conditions.
Hope this helps.
The solution is to put the pre and pos conditions in the first lines. The ccrewrite does not accept that pre and post conditions are below command lines.

How do I use the Mono.CSharp interpreter in Microsoft.NET

I was under the impression Mono's compiler was usable in Microsoft.NET
edit: updated blog posting here that I originally missed that explains some of it (is consistent with Justin's answers)
I created a simple class to try to use it
[TestFixture]
class Class1
{
[Test]
public void EXPR()
{
Evaluator.Run("using System;");
int sum = (int)Evaluator.Evaluate("1+2");
}
}
And a project in Visual Studio 2010 that references C:\Program Files (x86)\Mono-2.10.1\lib\mono\4.0\Mono.CSharp.dll.
However when I try to run this task I get the following exception, thrown at the Evaluator.Run call:
System.TypeInitializationException was unhandled by user code
Message=The type initializer for 'Mono.CSharp.Evaluator' threw an exception.
Source=Mono.CSharp
TypeName=Mono.CSharp.Evaluator
StackTrace:
at Mono.CSharp.Evaluator.Run(String statement)
at Experiments.Class1.EXPR() in W:\Experiments\Class1.cs:line 16
InnerException: System.TypeLoadException
Message=Method 'Mono.CSharp.Location.ToString()' is security transparent, but is a member of a security critical type.
Source=Mono.CSharp
TypeName=Mono.CSharp.Location.ToString()
StackTrace:
at Mono.CSharp.Evaluator..cctor()
InnerException:
A google confirms one other person asking this question but no answer. I tried to start reading the microsoft article on security transparent code but got confused quite quickly. Would someone be able to suggest a quick workaround to allow me to use this? And possibly summarise the security implications, if any, to me (in the context of my situation - in the future I hope to package it with a thick client application, to be used both internally and by end-users)
It has worked under .NET since April of last year.
Small point but I notice you are missing a semi-colon in your expression for sum.
int sum = (int)Evaluator.Evaluate("1+2;");
I only have Mono 2.11 (from git) at the moment and they have changed to using a multi-instance version of the compiler instead of the static version. So, my code looks a little different:
using System;
using Mono.CSharp;
namespace REPLtest
{
class MainClass
{
public static void Main (string[] args)
{
var r = new Report (new ConsoleReportPrinter ());
var cmd = new CommandLineParser (r);
var settings = cmd.ParseArguments (args);
if (settings == null || r.Errors > 0)
Environment.Exit (1);
var evaluator = new Evaluator (settings, r);
evaluator.Run("using System;");
int sum = (int) evaluator.Evaluate("1+2;");
Console.WriteLine ("The sum of 1 + 2 is {0}", sum);
}
}
}
EDIT: I guess I should confirm that I did in fact successfully execute this on .NET 4 (using Visual C# Express 2010 on Windows XP)
EDIT AGAIN: If you have Visual Studio, you can download the latest version of Mono.CSharp and compile it yourself. There is a .sln (solution file) included with the source so you can build it on Windows without Mono. The resulting assembly would run the code above. Miguel has a post explaining the new Mono.CSharp here.
FINAL EDIT: I uploaded the compiled Mono.CSharp.dll assembly that I actually used here. Include it as a reference to compile the code above.
It looks like this is a bug in Mono.
.NET 4 abandoned Code Access Security but kept the concept of Security Transparent Code. In a nutshell, low-level code that does stuff, like call unmanaged code, must be "security critical". Application level code is marked "transparent". "Transparent" code cannot call into "security critical" code.
It sounds like Mono.CSharp.Location.ToString() needs to be marked with the [SecuritySafeCritical] attribute if you want the Mono 2.10 code to work with .NET 4. Maybe even better would be marking all of Mono.CSharp as SecuritySafeCritical.
http://msdn.microsoft.com/en-us/library/system.security.securitycriticalattribute.aspx
PS. Sorry to have multiple answers for one question. After I realized that 2.11 would work, I became more curious about what the error with 2.10 meant. I cannot really combine this answer with the others.
I decided I should have kept the code more like the question but I did not want to overwrite my previous answer:
The code below works with version 2.11 of Mono.CSharp (available here including a solution file for building with Visual Studio/.NET). It was tested with .NET 4 on Windows XP. I do not have access to Mono 2.10 at the moment.
[TestFixture]
class Class1
{
private Evaluator evaluator;
public Class1()
{
var report = new Report(new ConsoleReportPrinter());
evaluator = new Evaluator(new CompilerSettings(), report);
}
[Test]
public void EXPR()
{
evaluator.Run("using System;");
int sum = (int)evaluator.Evaluate("1+2;");
}
}
EDIT: I uploaded the Mono.CSharp.dll assembly that I actually used here. Include it as a reference to compile the code above.

Categories