代码合同和以编程方式编译项目

时间:2014-08-28 21:19:37

标签: c#

我有一堆遗留的Web项目,这些项目是使用我们编写的自定义构建应用程序编译的。这是因为依赖性很复杂,代码......不是最优的。从好的方面来看,它最近已升级到.NET 4.5,我们正在使用Visual Studio 2013。

我最近开始在其他项目中使用代码合同,并且非常喜欢它提供的SoC。我想在我们为新功能维护的遗留代码中实现这一点(不进行完整的重写)。在开发过程中,只要我在VS中进行构建并将已编译的DLL文件复制到Web应用程序的BIN文件夹(aps.net 32​​位最新IIS)中,我就可以使用它。

我想使用我们的Build工具将合同包含在我们的发布版本中。否则我将不得不使用该工具,然后使用VS创建一个两步过程的版本。我对该工具有完整的源代码控制(在我的DEV PC上本地执行),但我无法通过代码契约生成输出。我阅读了代码合同文档,他们提到了构建脚本Microsoft.CodeContracts.targets,我试图将其添加到构建代码中但没有成功。不可否认,我对构建过程,构建脚本等的知识充其量是缺乏的。任何有关如何使其工作的帮助/指示将不胜感激。我仍然希望通常在VS中编译我的代码并使合同工作以及使用构建工具和合同工作。

(我没有手动更改任何CSPROJ文件)

构建代码: 构建代码使用Microsoft.Build和Microsoft.Build.Framework程序集完成。

var pc = new ProjectCollection();
var buildLogger = new FileLogger();

var logFilePath = @"MyLog.log";
buildLogger.Parameters = string.Format("logfile={0}", logFilePath);

var binDirectory = Path.Combine(outputWebDir, "Bin");
var globalProperty = new Dictionary<string, string>();
globalProperty.Add("OutputPath", binDirectory);
globalProperty.Add("Configuration", publishParams.ReleaseMode);
globalProperty.Add("Platform", publishParams.PlatformMode);
if (projectFileToPublish.IndexOf("SOTAQ.WebPoint.Web.csproj", StringComparison.OrdinalIgnoreCase) < 0)
    globalProperty.Add("SolutionDir", publishParams.SparcoSolutionPath);
if (isWebSite)
{
    globalProperty.Add("WebProjectOutputDir", outputWebDir);
    globalProperty.Add("DeployOnBuild", "True");
}
globalProperty.Add("CodeContractsInstallDir", @"C:\Program Files (x86)\Microsoft\Contracts\");
globalProperty.Add("CodeContractRewriteCommand", @"C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrewrite.exe");
globalProperty.Add("CodeContractAnalysisTargets", @"C:\Program Files (x86)\Microsoft\Contracts\MsBuild\v4.0\Microsoft.CodeContractAnalysis.targets");
globalProperty.Add("CodeContractsCCDocgenCommand", @"C:\Program Files (x86)\Microsoft\Contracts\Bin\ccdocgen.exe");
globalProperty.Add("CodeContractsCCRefgenCommand", @"C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrefgen.exe");

string[] targets;
if (isWebSite)
    targets= new[] { "Build", "ResolveReferences", "_CopyWebApplication" };
else
    targets = new[] { "Build", "ResolveReferences" };


var buildRequestData = new BuildRequestData(projectFileToPublish, globalProperty, null, targets, null);
var buildParams = new BuildParameters(pc);
buildParams.Loggers = new[] {buildLogger};

BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParams, buildRequestData);

非常感谢任何帮助!! 提前致谢, -Igor

1 个答案:

答案 0 :(得分:2)

在阅读并重新阅读Visual Studio的诊断输出并将其与我的构建项目进行比较并尝试了许多可能的解决方案之后,我在网上找到答案是将变量CodeContractsEnableRuntimeChecking添加为值true。

globalProperty.Add("CodeContractsEnableRuntimeChecking", "true");

一旦添加,一切都按预期工作。

-Igor

相关问题