Você está na página 1de 7

5stepstotargetingmultiple.

NET
frameworks
ByPunitGanshani(http://blogs.msmvps.com/punitganshani/author/punitganshani/)
WhendesigninganAPIorlibraries,weaimtohavemaximumcoverageofavailable.NETframeworksso
thatwecanhavemaximumnumberofclientsadoptourAPIs.Thekeychallengeinsuchscenariosistohave
acleancodeandanefficientwaytomanagemultipleversionsofcode,Nugetpackagesandbuilds.
Thisarticlewilloutlineaquickandeasywaytomanagesinglecodebaseandtargetmultiple.NET
frameworkversions.IveusedthesameconceptinKonfDB(https://github.com/punitganshani/KonfDB)

Step1VisualStudioProjectConfiguration

First,weneedtouseVisualStudiotocreatemultiplebuilddefinitions.Iwouldprefer2definitionsper.NET
configurationlike
.NET4.0DebugNET40,ReleaseNET40
.NET4.5DebugNET45andReleaseNET45
Whenaddingtheseconfigurations,clonethemfromDebugandReleaseandmakesureyouhaveselected
CreateNewProjectConfigurations

Thiswillmodifyyoursolution(.sln)fileandProject(.csproj)files.

Ifcertainprojectsdonotsupportbothversions,youcanuncheckthembeforeclickingonClosebutton.This
isusuallydone,whenyoursolutionhas2partsAPIandServerandyouwanttheAPItobemulti
frameworktargetandServercodetorunonaparticularversionof.NET

Step2FrameworkTargetinginProjects

Thereare2typesofchangesrequiredintheProject(.csproj)filestomanagemultiple.NETversions
Everyprojecthasdefaultconfiguration.Thisisusuallythelowestorbaseconfiguration.Thisisdefinedby
xmlpropertylike
<ConfigurationCondition="'$(Configuration)'==''">Debug</Configuration>
<PlatformCondition="'$(Platform)'==''">AnyCPU</Platform>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>

Changethisto
<ConfigurationCondition="'$(Configuration)'==''">DebugNET40</Configuration>
<PlatformCondition="'$(Platform)'==''">AnyCPU</Platform>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>

MakesurethatalltheprojectsinsolutionhavesamedefaultConfigurationandTargetFrameworkVersion
Whenweaddedmultipleconfigurationstooursolution,thereisonePropertyGroupperconfigurationadded
toourProject(.csproj)files.Thisappearssomethinglike,
<PropertyGroupCondition="'$(Configuration)|$(Platform)'=='DebugNET40|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>


Weneedtoadd/modify3linesineachofthesePropertyGrouptagstochangeOutputPath,
TargetFrameworkVersionandDefineConstants
For.NET4.0:
<OutputPath>bin\$(Configuration)\$(TargetFrameworkVersion)\</OutputPath>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<DefineConstants>DEBUG;TRACE;NET40</DefineConstants>

For.NET4.5:
<OutputPath>bin\$(Configuration)\$(TargetFrameworkVersion)\</OutputPath>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<DefineConstants>DEBUG;TRACE;NET45</DefineConstants>

Wewillusethesesettingslaterinthearticle.

Step3ReferencesTargetinginProjects

Ourdependentlibrariesmayhavedifferentversionsfordifferentversionsof.NET.Aclassicexampleis
NewtonsoftJSONlibrarieswhicharedifferentfor.NET4.0and.NET4.5.Sowemayrequireframework
dependentreferencesbeitStandardReferencesorNugetReferences.
Whenweareusingstandardreferences,wecanorganizeourlibrariesinframeworkspecificfoldersandalter
theprojectconfigurationtolooklike,
<ReferenceInclude="Some.Assembly">
<HintPath>..\Libraries\$(TargetFrameworkVersion)\Some.Assembly.dll</HintPath>
</Reference>

ToreferenceNugetpackages,wecanaddconditionstothereferencesasshownbelow

<ItemGroup>
<ReferenceInclude="Newtonsoft.Json,Version=6.0.0.0,Culture=neutral,
PublicKeyToken=30ad4fe6b2a6aeed,processorArchitecture=MSIL"
Condition="'$(TargetFrameworkVersion)'=='v4.5'">

<HintPath>..\..\..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll</HintP
ath>
</Reference>
<ReferenceInclude="Newtonsoft.Json,Version=6.0.0.0,Culture=neutral,
PublicKeyToken=30ad4fe6b2a6aeed,processorArchitecture=MSIL"
Condition="'$(TargetFrameworkVersion)'=='v4.0'">

<HintPath>..\..\..\packages\Newtonsoft.Json.6.0.8\lib\net40\Newtonsoft.Json.dll</HintP
ath>
</Reference>
</ItemGroup>

WhenwenowdoabatchbuildinVisualStudio,thesolutionshouldcompilewithouterrors.

Step4ManagingCleanCodewithmultiple
frameworks

Thereare2waystomanageourcodewithdifferentversionsof.NET.

BRI DG IN G T H EG A P OF .N ET 4 .5 . X IN .N ET 4. 0

Letsassumewearecreatinganarchivalprocesswherewewanttozipthelogfilesanddeletethelogfiles
afterzippingthem.Ifwebuildthisfunctionalitywith.NET4.5framework,wecanusetheZipArchiveclass
(inSystem.IO.Compression)in.NET4.5butthereisnosuchclassin.NET4.0.Insuchcases,weshouldgo
forinterfacedrivenprogramminganddefine2implementationsonefor.NET4.0andonefor.NET4.5.
These2implementationscannotcoexistinthesolutionastheymaygivecompilationissues.Toavoidthese
weneedtoedittheProject(.csproj)fileto

<CompileInclude="LogFileMaintenance40.cs"Condition="'$(TargetFrameworkVersion)'==
'v4.0'"/>
<CompileInclude="LogFileMaintenance45.cs"Condition="'$(TargetFrameworkVersion)'==
'v4.5'"/>

Boththesefilescanhavethesameclassnamesasatagiventime,onlyoneofthemwillcompile

TH E UN C LE AN WAY

TheuncleanwayiswhereweusetheDefineConstantstodifferentiatebetweentheframeworkversions.
Earlierintheprojectconfiguration,wechangedtheDefineConstantstohaveNET40andNET45.Wecanuse
theseDefineConstantsaspreprocessordirectivestoincludeframeworkspecificcodelike,
#ifNET40

#endif
#ifNET45

#endif

Thismethodologyshouldbeadoptedonlyifthereisminorchangeinthefunctionalitiesasitisverydifficult
todebugthiscode.

Step5BuildwithoutVisualStudio

WhileVisualStudioallowsustotriggerbuildsforanyconfigurationbymanuallyselectingtheconfiguration
fromthedropdown,wecanalsocreateabatchfiletoallowusbuildoursolutionwithdifferent.NET
frameworks.ThisbatchfilecanbeusedwithanyBuildSystemlikeTFS,Jenkins,TeamCity,etc.

REMBuildSolution
SETCONFIGURATION=%1
setPATH_SOURCE_SLN="%cd%\OurSolution.sln"
if[%1]==[](
SETCONFIGURATION=DebugNET40
)
MSBuild%PATH_SOURCE_SLN%/p:Configuration=%CONFIGURATION%

This5stepprocessallowsustodevelopoursolutiontargetingmultiple.NETframeworksandallowsusto
narrowdowntheimplementationtoaparticular.NETframeworkduringthebuild.

Posted:June21,2015(http://blogs.msmvps.com/punitganshani/2015/06/21/5stepstotargetingmultiple
netframeworks/).
Postedin:Uncategorized(http://blogs.msmvps.com/punitganshani/category/uncategorized/).
Bookmarkthepermalink(http://blogs.msmvps.com/punitganshani/2015/06/21/5stepstotargeting
multiplenetframeworks/).

Search

SEARCH

RecentPosts
5stepstotargetingmultiple.NETframeworks
(http://blogs.msmvps.com/punitganshani/2015/06/21/5stepstotargetingmultiplenet
frameworks/)
Event:Windows10DevReadinessWebcasts
(http://blogs.msmvps.com/punitganshani/2015/05/30/eventwindows10devreadinesswebcasts/)
5stepstocreateUbuntuHyperVImage(http://blogs.msmvps.com/punitganshani/2015/05/03/5
stepstocreateubuntuhypervimage/)
GettingStartedwithIaaSandOpenSourceonAzure

(http://blogs.msmvps.com/punitganshani/2015/04/24/gettingstartedwithiaasandopensource
onazure/)
MicrophonedetectioninArduino/Galileo(IoT)usingVC++
(http://blogs.msmvps.com/punitganshani/2015/02/26/microphonedetectioninarduinogalileo
iotusingvc/)

Categories
Azure(http://blogs.msmvps.com/punitganshani/category/azure/)
CSharp(http://blogs.msmvps.com/punitganshani/category/csharp/)
Galileo(http://blogs.msmvps.com/punitganshani/category/iot/intelgalileo/)
IoT(http://blogs.msmvps.com/punitganshani/category/iot/)
Sessions(http://blogs.msmvps.com/punitganshani/category/sessions/)
Uncategorized(http://blogs.msmvps.com/punitganshani/category/uncategorized/)
WCF(http://blogs.msmvps.com/punitganshani/category/csharp/wcf/)

Archives
June2015(http://blogs.msmvps.com/punitganshani/2015/06/)
May2015(http://blogs.msmvps.com/punitganshani/2015/05/)
April2015(http://blogs.msmvps.com/punitganshani/2015/04/)
February2015(http://blogs.msmvps.com/punitganshani/2015/02/)
January2015(http://blogs.msmvps.com/punitganshani/2015/01/)

Você também pode gostar