Retargeting All Projects in a Solution to .NET 4.5.2 - c#

I have a solution in Visual Studio 2012 with 170 C# projects in it. I need to retarget all of the projects from .NET Framework 4.0 to 4.5.2.
I prefer to let Visual Studio handle this by going into the properties of each project, changing the targeted framework, and letting Visual Studio make any necessary changes to the .csproj files.
I noticed that these changes include adding a few new XML tags to the .csproj, depending on some attributes of the current project.
How can I batch retarget all 170 C# projects without just using a replace text tool to replace the targeted version number? I want Visual Studio to make all the necessary tag modifications and additions and replace alone will not permit that to happen.

The MSDN documentation "Migration Guide to the .NET Framework 4.5" and "How to Configure an App to Support .NET Framework 4 or 4.5" only discusses modifying projects. There's no details on applying changes to the entire solution at once, nor have I seen a function in VS that supports it.
However, there's a (well-rated) extension called Target Framework Migrator available in the Visual Studio gallery, which supports upgrading to 4.5.2 (as well as newer versions**) and looks like it'll do exactly what you want. The source code is available on GitHub, if you're interested.
Note that the lack of such a feature may be intentional (and not just an omission). I'm just guessing, but maybe MS figures only projects that need the new Frameworks will be upgraded. FWIW, if you end up upgrading some projects that are shared with other solutions, those solutions may fail to build until they're upgraded too.
That being said, if you're in a small shop with just one (or a few) solutions and you're looking to upgrade everything in one go, then perhaps the above tool will work for you.
There's been no development on this for years, and apparently the developer has no plans to pass the baton to anyone else.
If you're unable to get it to work with a newer .NET Framework version, check the existing PRs and Issues for fixes, but you may have to apply them yourself. For example, someone posted a fix for .NET Framework v 4.7.1. Hopefully these will get merged, but I wouldn't hold my breath.
If anyone else is seeing the same error as Anas (in the comments), here's a GitHub issue from a couple weeks ago, and another possibly related issue from 2017. Consider thumbs upping them and adding more details if you're having the same problem.

For a .NET Framework solution, a simple "Replace in files" did the trick for me:
eg: From .NET Framework 4.5.2 to .NET Framework 4.7.2
In package.config files, replace all
targetFramework="net452"
to
targetFramework="net472"
In *.csproj files, replace all
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
to
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>

Since the Target Framework Migrator is broken, I rolled my own search/replace (using git bash, it works ok on windows) ; Basically it changes the v4.6.x into v4.7.2, then it converts back the files to using the infamous DOS's CRLF :
find . \( -iname '*.csproj' -o -iname '*.vcxproj' -o -iname 'app.config' \) \
-exec grep -Z -l 'v4\.6\..' \{} \; | xargs -0 sed -i 's/v4\.6\../v4.7.2/'
find . \( -iname '*.csproj' -o -iname '*.vcxproj' -o -iname 'app.config' \) \
-exec grep -Z -l 'v4\.7\..' \{} \; | xargs -0 unix2dos

I have built myself a simple tool to migrate the target framework versions for an entire solution, because the Target Framework Migrator Extension does not support Visual Studio 2017. Download the tool from my GitHub repository https://github.com/Xpitfire/TargetFrameworkMigrator
I know this is not the best way to go, but it worked for me and maybe it will also help someone else.

Target Framework Migrator is pretty useful. By default, it comes up to v4.7. However, it's easy to add support for v4.7.1, v4.7.2 and v4.8.
Find Frameworks.xml file in C:\Users{username}\AppData\Local\Microsoft\VisualStudio\ folder and edit by adding these framework versions:
<Framework Id="262152" Name=".NETFramework,Version=v4.8"/>
<Framework Id="262663" Name=".NETFramework,Version=v4.7.2"/>
<Framework Id="262407" Name=".NETFramework,Version=v4.7.1"/>
After you restart visual studio, you will see new versions.

public void ChangeFramework() {
//Add Reference to envdte (Assemblies\Extensions\envDTE)
string SolutionFile = #"C:\MyProject\MyProject.sln";
string ProjectName = "MyProject";
//------------------------------------------------------------------------
//Find the Program ID from the registry for VisualStudio.DTE
//Look it up In Registry: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Classes
System.Type oType = System.Type.GetTypeFromProgID("VisualStudio.DTE", true);
EnvDTE.DTE dte = (EnvDTE.DTE)Activator.CreateInstance(oType, true);
//------------------------------------------------------------------------
//Open your Solution
dte.Solution.Open(SolutionFile);
//------------------------------------------------------------------------
//Now In your solution go through what is listed in dte.Solution.Projects
//and find the one that match what you want to change target for
int iItemsCount = dte.Solution.Projects.Count;
string sCurrent = "";
for (int i = 1; i <= iItemsCount; i++) {
sCurrent = dte.Solution.Projects.Item(i).Name;
if (dte.Solution.Projects.Item(i).Name == ProjectName) {
//Once you find your project, Change the Framework
EnvDTE.Project oProject = dte.Solution.Projects.Item(i);
oProject.Properties.Item("TargetFrameworkMoniker").Value = ".NETFramework,Version = v4.6.2";
}
}
//------------------------------------------------------------------------
//Close your Solution
dte.Solution.Close();
}

Related

Error MSB4186 while build c# ".NET 5.0" in mono

Maybe one of you know how to solve the problem.
I want to run a written c# project ".NET 5.0 Framework" on a raspberry pi 4 in the mono ide. For this I insalled allready the ".Net 5.0 SDK Framework" from Microsoft homepage. In the settings of mono I set the right path to the "dotnet" folder. He found the ".NET Core SDK" (5.0.201) and ".NET Core Runtime" (5.0.4).
If I try now to build the project in the mono ide, I get the build error :
"/home/pi/dotnet5sdk/sdk/5.0.201/Sdks/Microsoft.NET.Sdk/targets/Microsoft.NET.TargetFrameworkInference.targets(54,5): error MSB4186: Invalid call syntax for static method: "[MSBuild]: : GetTargetFrameworkIdentifier ('$ (TargetFramework)') ". Method '[MSBuild] :: GetTargetFrameworkIdentifier' not found. The following format must be used to call static methods: $ ([complete type name] :: method ()). Example: $ ([System.IO.Path] :: Combine (a, b)). Make sure that all parameters are defined, are of the correct type, and are specified in the correct order.
I also use xbuild instead of MSBuild.
I searched in a lot of forums but didn't found anything that could help me with this issue.
Did I forget some required settings?
https://github.com/mono/mono/issues/20250
Wait for an update to introduce latest MSBuild please. Without that .NET 5 projects can only be compiled by .NET 5 SDK dotnet command.

MSBuild fails for solution with project dependencies

The build for my solution, which contains multiple projects, suddenly appears to be broken and the cause of the issue isn't clear. All of the projects in the solution target the same framework (4.5.1), however, some of the projects' dependencies might be targeting an earlier version of the framework. As of last week, we were able to successfully build solutions that fall under this scenario. Starting last Thursday, the builds appear to be broken without any changes to the build server or the solution.
To illustrate and remove some of the complexities with our production setup, I created a sample solution which mimics the behavior.
Project structure:
CBI Solution
CBI website
CBI Implementation Library
CBI Core library, defining the interfaces
Target Framework Version for the website and class libraries is 4.5.1
Replication Steps
Solution 1
Github repo: https://github.com/NikitaGolovko/Solution1.git
Build, using MSBuild 14. My command is:
msbuild.exe "%SOLUTION1PATH%\CBILite.sln" /p:platform="Any CPU" /p:configuration="Release" /v:d
Output
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v /localhost_61806 -p cbi\ -u -f PrecompiledWeb\lo
calhost_61806\
Microsoft (R) ASP.NET Compilation Tool version 4.7.2046.0
Utility to precompile an ASP.NET application
Copyright (C) Microsoft Corporation. All rights reserved.
Done executing task "AspNetCompiler".
Task "Message" skipped, due to false condition; (!((false) or ('$(AspNetConfiguration)' == 'Debug') or ('$(AspNetConfig
uration)' == 'Release'))) was evaluated as (!((false) or ('Release' == 'Debug') or ('Release' == 'Release'))).
Done building target "Build" in project "cbi.metaproj".
Done Building Project "D:\Work\DotNet\Nikita\Solution1\cbi.metaproj" (default targets).
Done executing task "MSBuild".
Done building target "Build" in project "CBILite.sln".
Done Building Project "D:\Work\DotNet\Nikita\Solution1\CBILite.sln" (default targets).
Build succeeded.
0 Warning(s)
0 Error(s)
Time Elapsed 00:00:03.10
Full output is located here: https://github.com/NikitaGolovko/Solution1/blob/master/MSBuild_Output.txt
Solution 2
Github Repo: https://github.com/NikitaGolovko/Solution2.git
The solution is nearly identical to the Solution1, with the only exception being a dependency for Unity in CBI Implementation library. To simplify the process and eliminate the nuget restore step, I have included nuget packages with the solution.
Build, using MSBuild 14. My command is:
msbuild.exe "%SOLUTION2PATH%\CBILite.sln" /p:platform="Any CPU" /p:configuration="Release" /v:d
Output
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v /localhost_61806 -p cbi\ -u -f PrecompiledWeb\lo
calhost_61806\
Microsoft (R) ASP.NET Compilation Tool version 4.7.2046.0
Utility to precompile an ASP.NET application
Copyright (C) Microsoft Corporation. All rights reserved.
D:\Work\DotNet\Nikita\Solution2\cbi\Index.aspx.vb(5): error BC30002: Type 'CBILite.Calculator' is not defined. [D:\Work
\DotNet\Nikita\Solution2\cbi.metaproj]
The command exited with code 1.
Done executing task "AspNetCompiler" -- FAILED.
Done building target "Build" in project "cbi.metaproj" -- FAILED.
Done Building Project "D:\Work\DotNet\Nikita\Solution2\cbi.metaproj" (default targets) -- FAILED.
Done executing task "MSBuild" -- FAILED.
Done building target "Build" in project "CBILite.sln" -- FAILED.
Done Building Project "D:\Work\DotNet\Nikita\Solution2\CBILite.sln" (default targets) -- FAILED.
Build FAILED.
Full output is located here: https://github.com/NikitaGolovko/Solution2/blob/master/MSBuild_Output.txt
Observations
Bin folder
When looking in the bin folder of the website, I notice that CBILite.dll is missing after the build for Solution2, but present in Solution1.
TargetFrameworkVersion
Passing TargetFrameworkVersion in the MSBuild arguments does not appear to influence the build. I have attempted to pass 4.5, 4.5.1 to no avail. HOWEVER passing 3.5 results in the successful build. This is extremely strange.
Metaproj
When comparing Metaproj files generated for both solutions, the only observable and seemingly important difference is the lack of the TargetFrameworkVersion element. Solution1 (without dependencies), contains v.4.0 element. Solution2 (with the dependency) does not.
I didn't include metaproj files in the repo but can share them if needed.
Visual Studio
Building the solution in Visual Studio works just fine.
Additional thoughts
The issue manifested itself rather suddenly and seems to be affecting most of our solutions that have mixed projects (C#/VB + website). Web Projects continue to function normally.
I've attempted to use MSBuild 15, but it resulted in the same behavior.
There are a few workarounds
Retaining the metaproj file with the solution and modifying it manually by adding v4.5.1 element.
Adding an additional build step to manually copy CBILib.dll into the website project (via the batch file or other means).
Adding a refresh file for the website pointing to CBILib/bin/Release folder
While all of these solutions might work, they're certainly hacks and will present problems in the future.
I'm hoping someone else has a better suggestion on how to handle this.
Make sure you have installed the following NuGet packages:
Microsoft.NET.Test.Sdk
MSTest.TestAdapter
MSTest.TestFramework
Microsoft.NETCore.App (if you use .NET Core)

OmniSharp-VIM, OmniSharp-Roslyn, and dotnet core on Ubuntu 16.10 - Syntax checking not recognizing C# 6 and requires solution file

I am trying to set up my Ubuntu machine for dotnet core development. I've painstakingly installed Omnisharp-vim and set it to work with the OmniSharp-Roslyn server. I also have Syntastic and YouCompleteMe installed. I am getting syntax checking and Intellisense. I have two problems though:
Omnisharp-vim does not work without a solution file. Dotnet core projects don't have to have solutions files. How do I get around this?
I am getting syntax error for valid C# 6 code. For instance, it does not recognize the nameof operator.
How?
Add a valid global.json file to your root directory.
{}
Add two lines to the top of your vimrc file.
let g:OmniSharp_server_type = 'roslyn'
let g:OmniSharp_prefer_global_sln = 1
Why?
Those two OmniSharp settings tell omnisharp-vim to use Roslyn and to use the directory that contains a global.json file.
Here is the OmniSharp.vim file source-code that uses those variables.
if g:OmniSharp_server_type ==# 'roslyn' && g:OmniSharp_prefer_global_sln
let global_solution_files = s:globpath(dir, 'global.json')
call filter(global_solution_files, 'filereadable(v:val)')
if !empty(global_solution_files)
let solution_files = [dir]
break
endif
endif
If that does not work...
Try starting OmniSharp manually from the command line:
omnisharp-vim\omnisharp-roslyn\artifacts\scripts\OmniSharp.cmd -s C:\temp\
The C:\temp\ directory contains a new .NET Core project with a valid global.json file.

Adding C# support to SCons on Mac

I found C# support for SCons (https://bitbucket.org/russel/scons_csharp/overview), but I don't know where to install (copy) the python scripts are copied into.
I installed Scons with brew command, so I have /usr/local/Cellar/scons/2.3.4 directory on my Mac.
What should be the next step to install the C# builders?
Please visit the index of all external SCons Tools at http://www.scons.org/wiki/ToolsIndex . Under the section "Install and usage" you can find a list of search directories for each platform.
Note that, since the C# support is not a core package, it's not installed into your default SCons distribution. Instead, it's treated like a customization (decoration?) of the standard sources...hence the machine/user-specific search paths.
Create a directory ~/.scons/site_scons/site_tools.
cd ~/.scons/site_scons/site_tools
hg clone https://bitbucket.org/russel/scons_csharp
Change one line (460) from csharp.py (~/.scons/site_scons/site_tools/scons_csharp/csharp.py).
env['CSC'] = env.Detect('mcs') or 'csc'
We need this change because the default setting for compiler (gmcs) is outdated.
Create build file: SConstruct.
env = Environment(
tools=['scons_csharp']
)
sources = ['Hello.cs']
prog = env.CLIProgram('myapp', sources)
Execute scons -Q to get:
mcs -nologo -noconfig -out:.../myapp.exe Hello.cs
References
http://www.scons.org/wiki/ToolsIndex
http://www.scons.org/wiki/CsharpBuilder

Switched targeted .NET versions and now project won't build

I'm running VS 2010 and I have a project which was originally set to build to .NET 4.0. This rev of .NET is too high for many of the windows platforms this app is expected to run and so I switched it from .NET 4.0 to .NET 2.0. Now, the project doesn't build.
At first I was getting null reference exceptions with the project resources. I found this link on MSDN forums which proved helpful in fixing that issue. Essentially, the answer (among the many) that worked was to change all instances of:
Version=4.0.0.0
to
Version=2.0.0.0
... in the *.resx files. I did this to all *.resx files I could find in the project directory. Walla, no more null reference exceptions during the build. However, now the project simply fails to build and the build window offers nothing in way of help to resolve. This is literally what's there:
2>CoreCompile:
2> C:\Windows\Microsoft.NET\Framework\v4.0.30319\Csc.exe /noconfig /nowarn:1701,1702 /nostdlib+ /platform:x86 /errorreport:prompt /warn:4 /define:TRACE /reference:C:\Users\afalanga\Dev\Tools\Program\FrontEnd\Resources\WrapNativeLibrary.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\mscorlib.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Data.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Deployment.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Management.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll /reference:C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Xml.dll /debug:pdbonly /filealign:512 /optimize+ /out:obj\x86\Release\FrontEnd.exe /resource:obj\x86\Release\FrontEnd.Panel.resources /resource:obj\x86\Release\FrontEnd.PrivilegesForm.resources /resource:obj\x86\Release\FrontEnd.Main.resources /resource:obj\x86\Release\FrontEnd.Properties.Resources.resources /resource:obj\x86\Release\FrontEnd.SoftwareLicense.resources /resource:Resources\WrapNativeLibrary.dll,WindowsUpdateTool.Resources.WrapNativeLibrary.dll /resource:Resources\INativeLibrary.dll,FrontEnd.Resources.INativeLibrary.dll /target:exe /win32icon:Resources\FrontEnd.ico /win32manifest:Resources\app.manifest Environment.cs Check.cs Exceptions.cs Updater.cs LibAccess.cs PrivilegesForm.cs Form1.Designer.cs OSInfo.cs Constants.cs PersonalizationManager.cs Silent.cs drivePanel.cs drivePanel.Designer.cs Main.cs Main.Designer.cs Program.cs Properties\AssemblyInfo.cs SoftwareLicense.cs SoftwareLicense.designer.cs VerticalProgressBar.cs Properties\Resources.Designer.cs Properties\Settings.Designer.cs
2>
2>Build FAILED.
Is it due to the fact that the C# compiler being referenced is the 4.0 version? At this point, I'm completely at a loss for what to check. I'm considering a fresh checkout of the branch for this code from TFS and trying there but haven't gone that route yet. I would appreciate any insight as everything I can see from the project properties says it should be targeting .NET 2.0 and it "should" build.
Thanks,
Andy
When you're downgrading your build target, you might be better off to start with a new project, change the build target then import your code into it. This way all your core dependencies start out right, and you'll only have to worry about the code being able to work.

Categories