Search code examples
.netwindows-servicescode-contracts

CodeContracts unproven in ServiceBase


I have following code in autogenerated part of windows service class (ServiceBase derived):

                private void InitializeComponent()
                {
                    components = new System.ComponentModel.Container();
problem line 32:    this.ServiceName = "QueueService";
                }

and Code Contracts enables, i see few warnings, which i doubt are correct:

Warning 5   CodeContracts: requires unproven: !value.Contains("/")  ...\QueueService.Designer.cs    32  4   ...
Warning 6   CodeContracts: requires unproven: !value.Contains("\\") ...\QueueService.Designer.cs    32  4   ...
Warning 7   CodeContracts: requires unproven: value.Length <= MaxNameLength ...\QueueService.Designer.cs    32  4   ...

What is the problem with this code, and how fix this warnings?


Solution

  • I believe the problem is that currently Code Contracts doesn't "look inside" strings, even if they are compile-time constants, so it doesn't know anything about whether or not the contract will be satisfied.

    For example, the following will give a warning:

    var test = "test";
    Contract.Assert(!test.Contains("/")); // Warning here
    

    You can use Contract.Assume to silence the warnings.

    For example:

    var test = "test";
    Contract.Assume(!test.Contains("/"));
    Contract.Assert(!test.Contains("/")); // no warning