This repository was archived by the owner on Oct 4, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathDotNetProject.cs
1719 lines (1463 loc) · 59.7 KB
/
DotNetProject.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DotNetProject.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2009 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
using System;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Threading;
using MonoDevelop.Core;
using MonoDevelop.Core.Execution;
using MonoDevelop.Projects.Policies;
using MonoDevelop.Projects.MD1;
using MonoDevelop.Projects.Extensions;
using MonoDevelop.Projects.MSBuild;
using MonoDevelop.Core.Assemblies;
using System.Globalization;
using System.Threading.Tasks;
using System.Collections.Immutable;
using MonoDevelop.Projects.MSBuild.Conditions;
namespace MonoDevelop.Projects
{
public abstract class DotNetProject : Project, IAssemblyProject, IDotNetFileContainer
{
bool usePartialTypes = true;
DirectoryAssemblyContext privateAssemblyContext;
ComposedAssemblyContext composedAssemblyContext;
IAssemblyContext currentRuntimeContext;
CompileTarget compileTarget;
LanguageBinding languageBinding;
protected ProjectReferenceCollection projectReferences;
protected string defaultNamespace = String.Empty;
DotNetProjectFlags flags;
protected DotNetProject ()
{
Initialize (this);
}
protected DotNetProject (string languageName, params string[] flavorIds): base (flavorIds)
{
this.languageName = languageName;
Initialize (this);
}
public static DotNetProject CreateProject (string language, params string[] typeGuids)
{
string typeGuid = MSBuildProjectService.GetLanguageGuid (language);
return (DotNetProject) MSBuildProjectService.CreateProject (typeGuid, typeGuids);
}
protected override void OnInitialize ()
{
projectReferences = new ProjectReferenceCollection ();
Items.Bind (projectReferences);
FileService.FileRemoved += OnFileRemoved;
Runtime.SystemAssemblyService.DefaultRuntimeChanged += RuntimeSystemAssemblyServiceDefaultRuntimeChanged;
base.OnInitialize ();
if (languageName == null)
languageName = MSBuildProjectService.GetLanguageFromGuid (TypeGuid);
}
protected override void OnExtensionChainInitialized ()
{
projectExtension = ExtensionChain.GetExtension<DotNetProjectExtension> ();
base.OnExtensionChainInitialized ();
if (IsLibraryBasedProjectType)
CompileTarget = CompileTarget.Library;
flags = ProjectExtension.OnGetDotNetProjectFlags ();
usePartialTypes = SupportsPartialTypes;
}
protected override void OnSetShared ()
{
base.OnSetShared ();
projectReferences.SetShared ();
}
protected override void OnInitializeFromTemplate (ProjectCreateInformation projectCreateInfo, XmlElement projectOptions)
{
base.OnInitializeFromTemplate (projectCreateInfo, projectOptions);
if ((projectOptions != null) && (projectOptions.Attributes ["Target"] != null))
CompileTarget = (CompileTarget)Enum.Parse (typeof(CompileTarget), projectOptions.Attributes ["Target"].Value);
else if (IsLibraryBasedProjectType)
CompileTarget = CompileTarget.Library;
if (this.LanguageBinding != null) {
bool externalConsole = false;
string platform = null;
if (!projectOptions.HasAttribute ("Platform")) {
// Clone the element since we are going to change it
platform = GetDefaultTargetPlatform (projectCreateInfo);
projectOptions = (XmlElement)projectOptions.CloneNode (true);
projectOptions.SetAttribute ("Platform", platform);
} else
platform = projectOptions.GetAttribute ("Platform");
if (projectOptions.GetAttribute ("ExternalConsole") == "True")
externalConsole = true;
string platformSuffix = string.IsNullOrEmpty (platform) ? string.Empty : "|" + platform;
DotNetProjectConfiguration configDebug = CreateConfiguration ("Debug" + platformSuffix, ConfigurationKind.Debug) as DotNetProjectConfiguration;
DefineSymbols (configDebug.CompilationParameters, projectOptions, "DefineConstantsDebug");
configDebug.ExternalConsole = externalConsole;
configDebug.PauseConsoleOutput = externalConsole;
Configurations.Add (configDebug);
DotNetProjectConfiguration configRelease = CreateConfiguration ("Release" + platformSuffix, ConfigurationKind.Release) as DotNetProjectConfiguration;
DefineSymbols (configRelease.CompilationParameters, projectOptions, "DefineConstantsRelease");
configRelease.CompilationParameters.RemoveDefineSymbol ("DEBUG");
configRelease.ExternalConsole = externalConsole;
configRelease.PauseConsoleOutput = externalConsole;
Configurations.Add (configRelease);
}
targetFramework = GetTargetFrameworkForNewProject (projectOptions, GetDefaultTargetFrameworkId ());
string binPath;
if (projectCreateInfo != null) {
Name = projectCreateInfo.ProjectName;
binPath = projectCreateInfo.BinPath;
defaultNamespace = SanitisePotentialNamespace (projectCreateInfo.ProjectName);
} else {
binPath = ".";
}
foreach (DotNetProjectConfiguration dotNetProjectConfig in Configurations) {
dotNetProjectConfig.OutputDirectory = Path.Combine (binPath, dotNetProjectConfig.Name);
if ((projectOptions != null) && (projectOptions.Attributes["PauseConsoleOutput"] != null))
dotNetProjectConfig.PauseConsoleOutput = Boolean.Parse (projectOptions.Attributes["PauseConsoleOutput"].Value);
if (projectCreateInfo != null)
dotNetProjectConfig.OutputAssembly = projectCreateInfo.ProjectName;
}
}
void DefineSymbols (DotNetCompilerParameters pars, XmlElement projectOptions, string attributeName)
{
if (projectOptions != null) {
string symbols = projectOptions.GetAttribute (attributeName);
if (!String.IsNullOrEmpty (symbols)) {
pars.AddDefineSymbol (symbols);
}
}
}
TargetFramework GetTargetFrameworkForNewProject (XmlElement projectOptions, TargetFrameworkMoniker defaultMoniker)
{
if (projectOptions == null)
return Runtime.SystemAssemblyService.GetTargetFramework (defaultMoniker);
var att = projectOptions.Attributes ["TargetFrameworkVersion"];
if (att == null) {
att = projectOptions.Attributes ["TargetFramework"];
if (att == null)
return Runtime.SystemAssemblyService.GetTargetFramework (defaultMoniker);
}
var moniker = TargetFrameworkMoniker.Parse (att.Value);
//if the string did not include a framework identifier, use the project's default
var netID = TargetFrameworkMoniker.ID_NET_FRAMEWORK;
if (moniker.Identifier == netID && !att.Value.StartsWith (netID, StringComparison.Ordinal))
moniker = new TargetFrameworkMoniker (defaultMoniker.Identifier, moniker.Version, moniker.Profile);
return Runtime.SystemAssemblyService.GetTargetFramework (moniker);
}
protected override void OnGetTypeTags (HashSet<string> types)
{
base.OnGetTypeTags (types);
types.Add ("DotNet");
types.Add ("DotNetAssembly");
}
DotNetProjectExtension projectExtension;
DotNetProjectExtension ProjectExtension {
get {
if (projectExtension == null)
AssertExtensionChainCreated ();
return projectExtension;
}
}
protected override IEnumerable<WorkspaceObjectExtension> CreateDefaultExtensions ()
{
return base.CreateDefaultExtensions ().Concat (Enumerable.Repeat (new DefaultDotNetProjectExtension (), 1));
}
protected override ProjectItem OnCreateProjectItem (IMSBuildItemEvaluated item)
{
if (item.Name == "Reference" || item.Name == "ProjectReference")
return new ProjectReference ();
return base.OnCreateProjectItem (item);
}
private string languageName;
public string LanguageName {
get { return languageName; }
}
protected override string[] OnGetSupportedLanguages ()
{
return new [] { "", languageName };
}
public bool IsLibraryBasedProjectType {
get { return (flags & DotNetProjectFlags.IsLibrary) != 0; }
}
public bool IsPortableLibrary {
get { return GetService<PortableDotNetProjectFlavor> () != null; }
}
public bool GeneratesDebugInfoFile {
get { return (flags & DotNetProjectFlags.GeneratesDebugInfoFile) != 0; }
}
public bool SupportsRoslyn { get; protected set; }
protected virtual DotNetProjectFlags OnGetDotNetProjectFlags ()
{
return DotNetProjectFlags.GeneratesDebugInfoFile;
}
protected string GetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo)
{
return ProjectExtension.OnGetDefaultTargetPlatform (projectCreateInfo);
}
protected virtual string OnGetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo)
{
if (CompileTarget == CompileTarget.Library)
return string.Empty;
// Guess a good default platform for the project
if (projectCreateInfo.ParentFolder != null && projectCreateInfo.ParentFolder.ParentSolution != null) {
ItemConfiguration conf = projectCreateInfo.ParentFolder.ParentSolution.GetConfiguration (projectCreateInfo.ActiveConfiguration);
if (conf != null)
return conf.Platform;
else {
string curName, curPlatform, bestPlatform = null;
string sconf = projectCreateInfo.ActiveConfiguration.ToString ();
ItemConfiguration.ParseConfigurationId (sconf, out curName, out curPlatform);
foreach (ItemConfiguration ic in projectCreateInfo.ParentFolder.ParentSolution.Configurations) {
if (ic.Platform == curPlatform)
return curPlatform;
if (ic.Name == curName)
bestPlatform = ic.Platform;
}
if (bestPlatform != null)
return bestPlatform;
}
}
return Services.ProjectService.DefaultPlatformTarget;
}
public ProjectReferenceCollection References {
get { return projectReferences; }
}
/// <summary>
/// Checks the status of references. To be called when referenced files may have been deleted or created.
/// </summary>
public void RefreshReferenceStatus ()
{
for (int n = 0; n < References.Count; n++) {
var cp = References [n].GetRefreshedReference ();
if (cp != null)
References [n] = cp;
}
}
public bool CanReferenceProject (DotNetProject targetProject, out string reason)
{
return ProjectExtension.OnGetCanReferenceProject (targetProject, out reason);
}
bool CheckCanReferenceProject (DotNetProject targetProject, out string reason)
{
if (!TargetFramework.CanReferenceAssembliesTargetingFramework (targetProject.TargetFramework)) {
reason = GettextCatalog.GetString ("Incompatible target framework: {0}", targetProject.TargetFramework.Id);
return false;
}
reason = null;
return true;
}
public LanguageBinding LanguageBinding {
get {
if (languageBinding == null) {
languageBinding = FindLanguage (languageName);
//older projects may not have this property but may not support partial types
//so need to verify that the default attribute is OK
if (languageBinding != null && UsePartialTypes && !SupportsPartialTypes) {
LoggingService.LogWarning ("Project '{0}' has been set to use partial types but does not support them.", Name);
UsePartialTypes = false;
}
}
return languageBinding;
}
}
public CompileTarget CompileTarget {
get { return compileTarget; }
set {
if (!Loading && IsLibraryBasedProjectType && value != CompileTarget.Library)
throw new InvalidOperationException ("CompileTarget cannot be changed on library-based project type.");
compileTarget = value;
}
}
/// <summary>
/// Default namespace setting. May be empty, use GetDefaultNamespace to get a usable value.
/// </summary>
public string DefaultNamespace {
get { return defaultNamespace; }
set {
defaultNamespace = value;
NotifyModified ("DefaultNamespace");
}
}
/// <summary>
/// Given a namespace, removes from it the implicit namespace of the project,
/// if there is one. This depends on the target language. For example, in VB.NET
/// the default namespace is implicit.
/// </summary>
public string StripImplicitNamespace (string ns)
{
if (DefaultNamespaceIsImplicit) {
if (DefaultNamespace.Length > 0 && ns.StartsWith (DefaultNamespace + "."))
return ns.Substring (DefaultNamespace.Length + 1);
else if (DefaultNamespace == ns)
return string.Empty;
}
return ns;
}
public bool DefaultNamespaceIsImplicit { get; set; }
TargetFramework targetFramework;
public TargetFramework TargetFramework {
get {
if (targetFramework == null) {
var id = GetDefaultTargetFrameworkId ();
targetFramework = Runtime.SystemAssemblyService.GetTargetFramework (id);
}
return targetFramework;
}
set {
if (!SupportsFramework (value))
throw new ArgumentException ("Project does not support framework '" + value.Id.ToString () +"'");
if (value == null)
value = Runtime.SystemAssemblyService.GetTargetFramework (GetDefaultTargetFrameworkForFormat (ToolsVersion));
if (targetFramework != null && value.Id == targetFramework.Id)
return;
bool updateReferences = targetFramework != null;
targetFramework = value;
if (updateReferences)
UpdateSystemReferences ();
NotifyModified ("TargetFramework");
}
}
public TargetRuntime TargetRuntime {
get { return Runtime.SystemAssemblyService.DefaultRuntime; }
}
/// <summary>
/// Gets the target framework for new projects
/// </summary>
/// <returns>
/// The default target framework identifier.
/// </returns>
public TargetFrameworkMoniker GetDefaultTargetFrameworkId ()
{
return ProjectExtension.OnGetDefaultTargetFrameworkId ();
}
protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkId ()
{
return Services.ProjectService.DefaultTargetFramework.Id;
}
/// <summary>
/// Returns the default framework for a given format
/// </summary>
/// <returns>
/// The default target framework for the format.
/// </returns>
/// <param name='toolsVersion'>
/// MSBuild tools version for which to get the default format
/// </param>
/// <remarks>
/// This method is used to determine what's the correct target framework for a project
/// deserialized using a specific format.
/// </remarks>
public TargetFrameworkMoniker GetDefaultTargetFrameworkForFormat (string toolsVersion)
{
return ProjectExtension.OnGetDefaultTargetFrameworkForFormat (toolsVersion);
}
protected virtual TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (string toolsVersion)
{
// If GetDefaultTargetFrameworkId has been overriden to return something different than the
// default framework, but OnGetDefaultTargetFrameworkForFormat has not been overriden, then
// the framework most likely to be correct is the one returned by GetDefaultTargetFrameworkId.
var fxid = GetDefaultTargetFrameworkId ();
if (fxid == Services.ProjectService.DefaultTargetFramework.Id) {
switch (toolsVersion) {
case "2.0":
return TargetFrameworkMoniker.NET_2_0;
case "4.0":
return TargetFrameworkMoniker.NET_4_0;
}
}
return fxid;
}
public IAssemblyContext AssemblyContext {
get {
if (composedAssemblyContext == null) {
composedAssemblyContext = new ComposedAssemblyContext ();
composedAssemblyContext.Add (PrivateAssemblyContext);
currentRuntimeContext = TargetRuntime.AssemblyContext;
composedAssemblyContext.Add (currentRuntimeContext);
}
return composedAssemblyContext;
}
}
public IAssemblyContext PrivateAssemblyContext {
get {
if (privateAssemblyContext == null)
privateAssemblyContext = new DirectoryAssemblyContext ();
return privateAssemblyContext;
}
}
public bool SupportsFramework (TargetFramework framework)
{
return ProjectExtension.OnGetSupportsFramework (framework);
}
protected virtual bool OnSupportsFramework (TargetFramework framework)
{
// DotNetAssemblyProject can only generate assemblies for the regular framework.
// Special frameworks such as Moonlight or MonoTouch must override SupportsFramework.
if (!framework.CanReferenceAssembliesTargetingFramework (TargetFrameworkMoniker.NET_1_1))
return false;
if (LanguageBinding == null)
return false;
ClrVersion[] versions = OnGetSupportedClrVersions ();
if (versions != null && versions.Length > 0 && framework != null) {
foreach (ClrVersion v in versions) {
if (v == framework.ClrVersion)
return true;
}
}
return false;
}
public bool UsePartialTypes {
get { return usePartialTypes; }
set { usePartialTypes = value; }
}
protected override void OnDispose ()
{
if (composedAssemblyContext != null) {
composedAssemblyContext.Dispose ();
// composedAssemblyContext = null;
}
// languageParameters = null;
// privateAssemblyContext = null;
// currentRuntimeContext = null;
// languageBinding = null;
// projectReferences = null;
Runtime.SystemAssemblyService.DefaultRuntimeChanged -= RuntimeSystemAssemblyServiceDefaultRuntimeChanged;
FileService.FileRemoved -= OnFileRemoved;
base.OnDispose ();
}
public bool SupportsPartialTypes {
get { return LanguageBinding.SupportsPartialTypes; }
}
void CheckReferenceChange (FilePath updatedFile)
{
for (int n=0; n<References.Count; n++) {
ProjectReference pr = References [n];
if (pr.ReferenceType == ReferenceType.Assembly && DefaultConfiguration != null) {
if (pr.GetReferencedFileNames (DefaultConfiguration.Selector).Any (f => f == updatedFile)) {
SetFastBuildCheckDirty ();
pr.NotifyStatusChanged ();
}
} else if (pr.HintPath == updatedFile) {
SetFastBuildCheckDirty ();
var nr = pr.GetRefreshedReference ();
if (nr != null)
References [n] = nr;
}
}
// If a referenced assembly changes, dirtify the project.
/* if (DefaultConfiguration != null) {
foreach (var asm in await GetReferencedAssemblies (DefaultConfiguration.Selector))
if (asm == updatedFile) {
SetFastBuildCheckDirty ();
break;
}
}
Removed for now since it can be a very slow operation
*/
}
internal override void OnFileChanged (object source, MonoDevelop.Core.FileEventArgs e)
{
// The OnFileChanged handler is unsubscibed in the Dispose method, so in theory we shouldn't need
// to check for disposed here. However, it might happen that this project is disposed while the
// FileService.FileChanged event is being dispatched, in which case the event handler list is already
// cached and won't take into account unsubscriptions until the next dispatch
if (Disposed)
return;
base.OnFileChanged (source, e);
foreach (FileEventInfo ei in e)
CheckReferenceChange (ei.FileName);
}
internal void RenameReferences (string oldName, string newName)
{
ArrayList toBeRenamed = new ArrayList ();
foreach (ProjectReference refInfo in this.References) {
if (refInfo.ReferenceType == ReferenceType.Project) {
if (refInfo.Reference == oldName)
toBeRenamed.Add (refInfo);
}
}
foreach (ProjectReference pr in toBeRenamed) {
this.References.Remove (pr);
ProjectReference prNew = ProjectReference.RenameReference (pr, newName);
this.References.Add (prNew);
}
}
internal protected override void PopulateOutputFileList (List<FilePath> list, ConfigurationSelector configuration)
{
base.PopulateOutputFileList (list, configuration);
DotNetProjectConfiguration conf = GetConfiguration (configuration) as DotNetProjectConfiguration;
// Debug info file
if (conf.DebugSymbols) {
string mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (conf.CompiledOutputName);
list.Add (mdbFile);
}
// Generated satellite resource files
FilePath outputDir = conf.OutputDirectory;
string satelliteAsmName = Path.GetFileNameWithoutExtension (conf.CompiledOutputName) + ".resources.dll";
HashSet<string> cultures = new HashSet<string> ();
foreach (ProjectFile finfo in Files) {
if (finfo.Subtype == Subtype.Directory || finfo.BuildAction != BuildAction.EmbeddedResource)
continue;
string culture = GetResourceCulture (finfo.Name);
if (culture != null && cultures.Add (culture)) {
cultures.Add (culture);
FilePath path = outputDir.Combine (culture, satelliteAsmName);
list.Add (path);
}
}
}
[ThreadStatic]
static int supportReferDistance;
[ThreadStatic]
static HashSet<DotNetProject> processedProjects;
internal protected override void PopulateSupportFileList (FileCopySet list, ConfigurationSelector configuration)
{
try {
if (supportReferDistance == 0)
processedProjects = new HashSet<DotNetProject> ();
supportReferDistance++;
PopulateSupportFileListInternal (list, configuration);
} finally {
supportReferDistance--;
if (supportReferDistance == 0)
processedProjects = null;
}
}
void PopulateSupportFileListInternal (FileCopySet list, ConfigurationSelector configuration)
{
if (supportReferDistance <= 2)
base.PopulateSupportFileList (list, configuration);
//rename the app.config file
list.Remove ("app.config");
list.Remove ("App.config");
ProjectFile appConfig = Files.FirstOrDefault (f => f.FilePath.FileName.Equals ("app.config", StringComparison.CurrentCultureIgnoreCase));
if (appConfig != null) {
string output = GetOutputFileName (configuration).FileName;
list.Add (appConfig.FilePath, true, output + ".config");
}
//collect all the "local copy" references and their attendant files
foreach (ProjectReference projectReference in References) {
if (!projectReference.LocalCopy || !projectReference.CanSetLocalCopy)
continue;
if (ParentSolution != null && projectReference.ReferenceType == ReferenceType.Project) {
DotNetProject p = projectReference.ResolveProject (ParentSolution) as DotNetProject;
if (p == null) {
LoggingService.LogWarning ("Project '{0}' referenced from '{1}' could not be found", projectReference.Reference, this.Name);
continue;
}
DotNetProjectConfiguration conf = p.GetConfiguration (configuration) as DotNetProjectConfiguration;
//VS COMPAT: recursively copy references's "local copy" files
//but only copy the "copy to output" files from the immediate references
if (processedProjects.Add (p) || supportReferDistance == 1) {
foreach (var v in p.GetOutputFiles (configuration))
list.Add (v, true, v.CanonicalPath.ToString ().Substring (conf.OutputDirectory.CanonicalPath.ToString ().Length + 1));
foreach (var v in p.GetSupportFileList (configuration))
list.Add (v.Src, v.CopyOnlyIfNewer, v.Target);
}
}
else if (projectReference.ReferenceType == ReferenceType.Assembly) {
// VS COMPAT: Copy the assembly, but also all other assemblies referenced by it
// that are located in the same folder
var visitedAssemblies = new HashSet<string> ();
var referencedFiles = projectReference.GetReferencedFileNames (configuration);
foreach (string file in referencedFiles.SelectMany (ar => GetAssemblyRefsRec (ar, visitedAssemblies))) {
// Indirectly referenced assemblies are only copied if a newer copy doesn't exist. This avoids overwritting directly referenced assemblies
// by indirectly referenced stale copies of the same assembly. See bug #655566.
bool copyIfNewer = !referencedFiles.Contains (file);
list.Add (file, copyIfNewer);
if (File.Exists (file + ".config"))
list.Add (file + ".config", copyIfNewer);
string mdbFile = TargetRuntime.GetAssemblyDebugInfoFile (file);
if (File.Exists (mdbFile))
list.Add (mdbFile, copyIfNewer);
}
}
else {
foreach (string refFile in projectReference.GetReferencedFileNames (configuration))
list.Add (refFile);
}
}
}
//Given a filename like foo.it.resx, get 'it', if its
//a valid culture
//Note: hand-written as this can get called lotsa times
//Note: code duplicated in prj2make/Utils.cs as TrySplitResourceName
internal static string GetResourceCulture (string fname)
{
int last_dot = -1;
int culture_dot = -1;
int i = fname.Length - 1;
while (i >= 0) {
if (fname [i] == '.') {
last_dot = i;
break;
}
i --;
}
if (i < 0)
return null;
i--;
while (i >= 0) {
if (fname [i] == '.') {
culture_dot = i;
break;
}
i --;
}
if (culture_dot < 0)
return null;
string culture = fname.Substring (culture_dot + 1, last_dot - culture_dot - 1);
if (!CultureNamesTable.ContainsKey (culture))
return null;
return culture;
}
static Dictionary<string, string> cultureNamesTable;
static Dictionary<string, string> CultureNamesTable {
get {
if (cultureNamesTable == null) {
cultureNamesTable = new Dictionary<string, string> ();
foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.AllCultures))
cultureNamesTable [ci.Name] = ci.Name;
}
return cultureNamesTable;
}
}
IEnumerable<string> GetAssemblyRefsRec (string fileName, HashSet<string> visited)
{
// Recursivelly finds assemblies referenced by the given assembly
if (!visited.Add (fileName))
yield break;
if (!File.Exists (fileName)) {
string ext = Path.GetExtension (fileName).ToLower ();
if (ext == ".dll" || ext == ".exe")
yield break;
if (File.Exists (fileName + ".dll"))
fileName = fileName + ".dll";
else if (File.Exists (fileName + ".exe"))
fileName = fileName + ".exe";
else
yield break;
}
yield return fileName;
foreach (var reference in SystemAssemblyService.GetAssemblyReferences (fileName)) {
string asmFile = Path.Combine (Path.GetDirectoryName (fileName), reference);
foreach (string refa in GetAssemblyRefsRec (asmFile, visited))
yield return refa;
}
}
public ProjectReference AddReference (string filename)
{
foreach (ProjectReference rInfo in References) {
if (rInfo.Reference == filename) {
return rInfo;
}
}
ProjectReference newReferenceInformation = ProjectReference.CreateAssemblyFileReference (filename);
References.Add (newReferenceInformation);
return newReferenceInformation;
}
protected override IEnumerable<SolutionItem> OnGetReferencedItems (ConfigurationSelector configuration)
{
var items = new List<SolutionItem> (base.OnGetReferencedItems (configuration));
if (ParentSolution == null)
return items;
foreach (ProjectReference pref in References) {
if (pref.ReferenceType == ReferenceType.Project && (string.IsNullOrEmpty (pref.Condition) ||
ConditionParser.ParseAndEvaluate (pref.Condition, new ProjectParserContext (this, (DotNetProjectConfiguration)GetConfiguration (configuration))))) {
Project rp = pref.ResolveProject (ParentSolution);
if (rp != null)
items.Add (rp);
}
}
return items;
}
/// <summary>
/// Returns all assemblies referenced by this project, including assemblies generated
/// by referenced projects.
/// </summary>
/// <param name="configuration">
/// Configuration for which to get the assemblies.
/// </param>
public Task<IEnumerable<string>> GetReferencedAssemblies (ConfigurationSelector configuration)
{
return GetReferencedAssemblies (configuration, true);
}
/// <summary>
/// Returns all assemblies referenced by this project.
/// </summary>
/// <param name="configuration">
/// Configuration for which to get the assemblies.
/// </param>
/// <param name="includeProjectReferences">
/// When set to true, it will include assemblies generated by referenced project. When set to false,
/// it will only include package and direct assembly references.
/// </param>
public Task<IEnumerable<string>> GetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences)
{
return BindTask<IEnumerable<string>> (async ct => {
var res = await ProjectExtension.OnGetReferencedAssemblies (configuration);
if (includeProjectReferences) {
foreach (ProjectReference pref in References.Where (pr => pr.ReferenceType == ReferenceType.Project)) {
foreach (string asm in pref.GetReferencedFileNames (configuration))
res.Add (asm);
}
}
return res;
});
}
/// <summary>
/// Gets the referenced assembly projects, but only projects which output are actually referenced
/// for example references with ReferenceOutputAssembly=false are excluded
/// </summary>
/// <param name="configuration">Configuration.</param>
public IEnumerable<DotNetProject> GetReferencedAssemblyProjects (ConfigurationSelector configuration)
{
return ProjectExtension.OnGetReferencedAssemblyProjects (configuration);
}
internal protected virtual async Task<List<string>> OnGetReferencedAssemblies (ConfigurationSelector configuration)
{
List<string> result = new List<string> ();
if (CheckUseMSBuildEngine (configuration)) {
// Get the references list from the msbuild project
RemoteProjectBuilder builder = await GetProjectBuilder ();
try {
var configs = GetConfigurations (configuration, false);
string [] refs;
using (Counters.ResolveMSBuildReferencesTimer.BeginTiming (GetProjectEventMetadata (configuration)))
refs = await builder.ResolveAssemblyReferences (configs, CancellationToken.None);
foreach (var r in refs)
result.Add (r);
} finally {
builder.ReleaseReference ();
}
} else {
foreach (ProjectReference pref in References) {
if (pref.ReferenceType != ReferenceType.Project) {
foreach (string asm in pref.GetReferencedFileNames (configuration))
result.Add (asm);
}
}
var mscorlib = AssemblyContext.GetAssemblyFullName ("mscorlib", TargetFramework);
var mscorlibPath = AssemblyContext.GetAssemblyLocation (mscorlib, TargetFramework);
if (!result.Contains (mscorlibPath))
result.Add (mscorlibPath);
var core = AssemblyContext.GetAssemblyFullName ("System.Core", TargetFramework);
var corePath = AssemblyContext.GetAssemblyLocation (core, TargetFramework);
if (!string.IsNullOrEmpty (corePath)) {
if (!result.Contains (corePath))
result.Add (corePath);
}
}
var config = (DotNetProjectConfiguration)GetConfiguration (configuration);
bool noStdLib = false;
if (config != null)
noStdLib = config.CompilationParameters.NoStdLib;
// System.Core is an implicit reference
if (!noStdLib) {
var sa = AssemblyContext.GetAssemblies (TargetFramework).FirstOrDefault (a => a.Name == "System.Core" && a.Package.IsFrameworkPackage);
if (sa != null)
result.Add (sa.Location);
}
var addFacadeAssemblies = false;
foreach (var r in GetReferencedAssemblyProjects (configuration)) {
if (r.IsPortableLibrary) {
addFacadeAssemblies = true;
break;
}
}
if (!addFacadeAssemblies) {
foreach (var refFilename in result) {
string fullPath = null;
if (!Path.IsPathRooted (refFilename)) {
fullPath = Path.Combine (Path.GetDirectoryName (FileName), refFilename);
} else {
fullPath = Path.GetFullPath (refFilename);
}
if (SystemAssemblyService.ContainsReferenceToSystemRuntime (fullPath)) {
addFacadeAssemblies = true;
break;
}
}
}
if (addFacadeAssemblies) {
var runtime = TargetRuntime ?? MonoDevelop.Core.Runtime.SystemAssemblyService.DefaultRuntime;
var facades = runtime.FindFacadeAssembliesForPCL (TargetFramework);
foreach (var facade in facades) {
if (!File.Exists (facade))
continue;
result.Add (facade);
}
}
return result;
}
internal protected virtual IEnumerable<DotNetProject> OnGetReferencedAssemblyProjects (ConfigurationSelector configuration)
{
if (ParentSolution == null) {
yield break;
}
foreach (ProjectReference pref in References) {
if (pref.ReferenceType == ReferenceType.Project &&
(string.IsNullOrEmpty (pref.Condition) || ConditionParser.ParseAndEvaluate (pref.Condition, new ProjectParserContext (this, (DotNetProjectConfiguration)GetConfiguration (configuration))))) {
if (!pref.ReferenceOutputAssembly)
continue;
var rp = pref.ResolveProject (ParentSolution) as DotNetProject;
if (rp != null)
yield return rp;
}
}
}
protected override Task<BuildResult> DoBuild (ProgressMonitor monitor, ConfigurationSelector configuration)
{
var handler = new MD1DotNetProjectHandler (this);
return handler.RunTarget (monitor, "Build", configuration);
}
protected override Task<BuildResult> DoClean (ProgressMonitor monitor, ConfigurationSelector configuration)
{
var handler = new MD1DotNetProjectHandler (this);
return handler.RunTarget (monitor, "Clean", configuration);
}
protected internal override Task OnSave (ProgressMonitor monitor)
{
// Make sure the fx version is sorted out before saving
// to avoid changes in project references while saving
if (targetFramework == null)
targetFramework = Runtime.SystemAssemblyService.GetTargetFramework (GetDefaultTargetFrameworkForFormat (ToolsVersion));
return base.OnSave (monitor);
}
LanguageBinding FindLanguage (string name)
{
return LanguageBindingService.GetBindingPerLanguageName (languageName);
}
protected override SolutionItemConfiguration OnCreateConfiguration (string name, ConfigurationKind kind)