Welcome to mirror list, hosted at ThFree Co, Russian Federation.

DotNetProject.cs « MonoDevelop.Projects « MonoDevelop.Core « core « src « main - github.com/mono/monodevelop.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 5513ee6f5bd4828353d732d4b53f1bab20e81730 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
//  DotNetProject.cs
//
// Author:
//   Lluis Sanchez Gual <lluis@novell.com>
//
// 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.Formats.MD1;
using MonoDevelop.Projects.Extensions;
using MonoDevelop.Projects.Formats.MSBuild;
using MonoDevelop.Core.Assemblies;
using System.Globalization;
using System.Threading.Tasks;
using System.Collections.Immutable;

namespace MonoDevelop.Projects
{
	public class DotNetProject : Project, IAssemblyProject, IDotNetFileContainer
	{
		bool usePartialTypes = true;

		DirectoryAssemblyContext privateAssemblyContext;
		ComposedAssemblyContext composedAssemblyContext;
		IAssemblyContext currentRuntimeContext;

		CompileTarget compileTarget;

		IDotNetLanguageBinding 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 (LanguageBinding != null)
				this.StockIcon = LanguageBinding.ProjectStockIcon;

			if (IsLibraryBasedProjectType)
				CompileTarget = CompileTarget.Library;

			flags = ProjectExtension.OnGetDotNetProjectFlags ();
			usePartialTypes = SupportsPartialTypes;
		}

		protected override void SetShared ()
		{
			base.SetShared ();
			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 != null) {
					projectOptions.SetAttribute ("DefineDebug", "True");
					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) as DotNetProjectConfiguration;
				configDebug.CompilationParameters = LanguageBinding.CreateCompilationParameters (projectOptions);
				DefineSymbols (configDebug.CompilationParameters, projectOptions, "DefineConstantsDebug");
				configDebug.DebugMode = true;
				configDebug.ExternalConsole = externalConsole;
				configDebug.PauseConsoleOutput = externalConsole;
				Configurations.Add (configDebug);

				DotNetProjectConfiguration configRelease = CreateConfiguration ("Release" + platformSuffix) as DotNetProjectConfiguration;

				if (projectOptions != null) {
					XmlElement releaseProjectOptions = (XmlElement)projectOptions.CloneNode (true);
					releaseProjectOptions.SetAttribute ("Release", "True");
					configRelease.CompilationParameters = LanguageBinding.CreateCompilationParameters (releaseProjectOptions);
					DefineSymbols (configRelease.CompilationParameters, projectOptions, "DefineConstantsRelease");
				} else {
					configRelease.CompilationParameters = LanguageBinding.CreateCompilationParameters (null);
				}

				configRelease.CompilationParameters.RemoveDefineSymbol ("DEBUG");
				configRelease.DebugMode = false;
				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; }
		}

		protected virtual DotNetProjectFlags OnGetDotNetProjectFlags ()
		{
			var flags = DotNetProjectFlags.GeneratesDebugInfoFile;

			if (LanguageBinding != null) {
				var provider = LanguageBinding.GetCodeDomProvider ();
				if (provider != null && provider.Supports (System.CodeDom.Compiler.GeneratorSupport.PartialTypes))
					flags |= DotNetProjectFlags.SupportsPartialTypes;
			}
			return flags;
		}

		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 IDotNetLanguageBinding 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; }

		IResourceHandler resourceHandler;

		public IResourceHandler ResourceHandler {
			get {
				if (resourceHandler == null) {
					DotNetNamingPolicy pol = Policies.Get<DotNetNamingPolicy> ();
					if (pol.ResourceNamePolicy == ResourceNamePolicy.FileFormatDefault || pol.ResourceNamePolicy == ResourceNamePolicy.MSBuild) {
						resourceHandler = DefaultResourceHandler ?? GetService<IResourceHandler> ();
						if (resourceHandler == null)
							resourceHandler = MSBuildResourceHandler.Instance;
					}
					else
						resourceHandler = MonoDevelop.Projects.Extensions.DefaultResourceHandler.Instance;
				}
				return resourceHandler;
			}
		}

		/// <summary>
		/// The resource handle that will be used when the user selects the format default naming policy
		/// </summary>
		/// <value>The default resource handler.</value>
		public IResourceHandler DefaultResourceHandler {
			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)
		{
			switch (toolsVersion) {
			case "2.0":
				return TargetFrameworkMoniker.NET_2_0;
			case "4.0":
				return TargetFrameworkMoniker.NET_4_0;
			}
			return GetDefaultTargetFrameworkId ();
		}

		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 = LanguageBinding.GetSupportedClrVersions ();
			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; }
		}

		public override void Dispose ()
		{
			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.Dispose ();
		}

		public bool SupportsPartialTypes {
			get { return (flags & DotNetProjectFlags.SupportsPartialTypes) != 0; }
		}

		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))
						pr.NotifyStatusChanged ();
				} else if (pr.HintPath == updatedFile) {
					var nr = pr.GetRefreshedReference ();
					if (nr != null)
						References [n] = nr;
				}
			}
		}

		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.DebugMode) {
				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 = ParentSolution.FindProjectByName (projectReference.Reference) 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 = new ProjectReference (ReferenceType.Assembly, 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) {
					Project rp = ParentSolution.FindProjectByName (pref.Reference);
					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 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 IEnumerable<string> GetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences)
		{
			return ProjectExtension.OnGetReferencedAssemblies (configuration, includeProjectReferences);
		}

		internal protected virtual IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences)
		{
			if (CheckUseMSBuildEngine (configuration)) {
				if (includeProjectReferences) {
					foreach (ProjectReference pref in References.Where (pr => pr.ReferenceType == ReferenceType.Project)) {
						foreach (string asm in pref.GetReferencedFileNames (configuration))
							yield return asm;
					}
				}
				// Get the references list from the msbuild project
				RemoteProjectBuilder builder = GetProjectBuilder ();
				var configs = GetConfigurations (configuration);

				string[] refs;
				using (Counters.ResolveMSBuildReferencesTimer.BeginTiming (GetProjectEventMetadata ()))
					refs = builder.ResolveAssemblyReferences (configs);
				foreach (var r in refs)
					yield return r;
			} else {
				foreach (ProjectReference pref in References) {
					if (includeProjectReferences || pref.ReferenceType != ReferenceType.Project) {
						foreach (string asm in pref.GetReferencedFileNames (configuration))
							yield return asm;
					}
				}
			}

			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)
					yield return sa.Location;
			}
		}

		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);
		}

		IDotNetLanguageBinding FindLanguage (string name)
		{
			IDotNetLanguageBinding binding = LanguageBindingService.GetBindingPerLanguageName (languageName) as IDotNetLanguageBinding;
			return binding;
		}

		protected override SolutionItemConfiguration OnCreateConfiguration (string name)
		{
			DotNetProjectConfiguration conf = new DotNetProjectConfiguration (name);
			string dir;
			if (conf.Platform.Length == 0)
				dir = Path.Combine ("bin", conf.Name);
			else
				dir = Path.Combine (Path.Combine ("bin", conf.Platform), conf.Name);

			conf.OutputDirectory = String.IsNullOrEmpty (BaseDirectory) ? dir : Path.Combine (BaseDirectory, dir);
			conf.OutputAssembly = Name;
			if (LanguageBinding != null) {
				XmlElement xconf = null;
				if (!string.IsNullOrEmpty (conf.Platform)) {
					XmlDocument doc = new XmlDocument ();
					xconf = doc.CreateElement ("Options");
					xconf.SetAttribute ("Platform", conf.Platform);
				}
				conf.CompilationParameters = LanguageBinding.CreateCompilationParameters (xconf);
			}
			return conf;
		}


		protected override FilePath OnGetOutputFileName (ConfigurationSelector configuration)
		{
			DotNetProjectConfiguration conf = (DotNetProjectConfiguration)GetConfiguration (configuration);
			if (conf != null)
				return conf.CompiledOutputName;
			else
				return null;
		}

		protected override bool CheckNeedsBuild (ConfigurationSelector configuration)
		{
			if (base.CheckNeedsBuild (configuration))
				return true;

			// base.CheckNeedsBuild() checks Project references, but not Assembly, Package, or Custom.
			DateTime mtime = GetLastBuildTime (configuration);
			foreach (ProjectReference pref in References) {
				switch (pref.ReferenceType) {
				case ReferenceType.Assembly:
					foreach (var file in GetAssemblyRefsRec (pref.Reference, new HashSet<string> ())) {
						try {
							if (File.GetLastWriteTime (file) > mtime)
								return true;
						} catch (IOException) {
							// Ignore.
						}
					}
					break;
				case ReferenceType.Package:
					if (pref.Package == null) {
						break;
					}
					foreach (var assembly in pref.Package.Assemblies) {
						try {
							if (File.GetLastWriteTime (assembly.Location) > mtime)
								return true;
						} catch (IOException) {
							// Ignore.
						}
					}
					break;
				}
			}

			var config = (DotNetProjectConfiguration) GetConfiguration (configuration);
			return Files.Any (file => file.BuildAction == BuildAction.EmbeddedResource
					&& String.Compare (Path.GetExtension (file.FilePath), ".resx", StringComparison.OrdinalIgnoreCase) == 0
					&& MD1DotNetProjectHandler.IsResgenRequired (file.FilePath, config.IntermediateOutputDirectory.Combine (file.ResourceId)));
		}

		protected internal override DateTime OnGetLastBuildTime (ConfigurationSelector configuration)
		{
			var outputBuildTime = base.OnGetLastBuildTime (configuration);

			//if the debug file is newer than the output file, use that as the build time
			var conf = (DotNetProjectConfiguration) GetConfiguration (configuration);
			if (GeneratesDebugInfoFile && conf != null && conf.DebugMode) {
				string file = GetOutputFileName (configuration);
				if (file != null) {
					file = TargetRuntime.GetAssemblyDebugInfoFile (file);
					var finfo = new FileInfo (file);
					if (finfo.Exists)  {
						var debugFileBuildTime = finfo.LastWriteTime;
						if (debugFileBuildTime > outputBuildTime)
							return debugFileBuildTime;
					}
				}
			}
			return outputBuildTime;
		}

		public IList<string> GetUserAssemblyPaths (ConfigurationSelector configuration)
		{
			if (ParentSolution == null)
				return null;
			//return all projects in the sln in case some are loaded dynamically
			//FIXME: should we do this for the whole workspace?
			return ParentSolution.RootFolder.GetAllBuildableEntries (configuration).OfType<DotNetProject> ()
				.Select (d => (string) d.GetOutputFileName (configuration))
				.Where (d => !string.IsNullOrEmpty (d)).ToList ();
		}

		public ExecutionCommand CreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration)
		{
			return ProjectExtension.OnCreateExecutionCommand (configSel, configuration);
		}

		internal protected virtual ExecutionCommand OnCreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration)
		{
			DotNetExecutionCommand cmd = new DotNetExecutionCommand (configuration.CompiledOutputName);
			cmd.Arguments = configuration.CommandLineParameters;
			cmd.WorkingDirectory = Path.GetDirectoryName (configuration.CompiledOutputName);
			cmd.EnvironmentVariables = configuration.GetParsedEnvironmentVariables ();
			cmd.TargetRuntime = TargetRuntime;
			cmd.UserAssemblyPaths = GetUserAssemblyPaths (configSel);
			return cmd;
		}

		protected override bool OnGetCanExecute (ExecutionContext context, ConfigurationSelector configuration)
		{
			DotNetProjectConfiguration config = (DotNetProjectConfiguration) GetConfiguration (configuration);
			if (config == null)
				return false;
			ExecutionCommand cmd = CreateExecutionCommand (configuration, config);
			if (context.ExecutionTarget != null)
				cmd.Target = context.ExecutionTarget;

			return (compileTarget == CompileTarget.Exe || compileTarget == CompileTarget.WinExe) && context.ExecutionHandler.CanExecute (cmd);
		}

		protected override IEnumerable<FilePath> OnGetItemFiles (bool includeReferencedFiles)
		{
			var baseFiles = base.OnGetItemFiles (includeReferencedFiles);
			if (includeReferencedFiles) {
				List<FilePath> col = new List<FilePath> ();
				foreach (ProjectReference pref in References) {
					if (pref.ReferenceType == ReferenceType.Assembly) {
						foreach (var f in pref.GetReferencedFileNames (DefaultConfiguration.Selector))
							col.Add (f);
					}
				}
				foreach (DotNetProjectConfiguration c in Configurations) {
					if (c.SignAssembly)
						col.Add (c.AssemblyKeyFile);
				}
				baseFiles = baseFiles.Concat (col);
			}
			return baseFiles;
		}

		internal Task<BuildResult> Compile (ProgressMonitor monitor, BuildData buildData)
		{
			return ProjectExtension.OnCompile (monitor, buildData);
		}

		protected virtual Task<BuildResult> OnCompile (ProgressMonitor monitor, BuildData buildData)
		{
			return MD1DotNetProjectHandler.Compile (monitor, this, buildData);
		}

		protected override bool OnGetIsCompileable (string fileName)
		{
			if (LanguageBinding == null)
				return false;
			return LanguageBinding.IsSourceCodeFile (fileName);
		}

		/// <summary>
		/// Gets the default namespace for the file, according to the naming policy.
		/// </summary>
		/// <remarks>Always returns a valid namespace, even if the fileName is null.</remarks>
		public string GetDefaultNamespace (string fileName)
		{
			return OnGetDefaultNamespace (fileName);
		}

		/// <summary>
		/// Gets the default namespace for the file, according to the naming policy.
		/// </summary>
		/// <remarks>Always returns a valid namespace, even if the fileName is null.</remarks>
		protected virtual string OnGetDefaultNamespace (string fileName)
		{
			return GetDefaultNamespace (this, DefaultNamespace, fileName);
		}

		/// <summary>
		/// Gets the default namespace for the file, according to the naming policy.
		/// </summary>
		/// <remarks>Always returns a valid namespace, even if the fileName is null.</remarks>
		internal static string GetDefaultNamespace (Project project, string defaultNamespace, string fileName)
		{
			DotNetNamingPolicy pol = project.Policies.Get<DotNetNamingPolicy> ();

			string root = null;
			string dirNamespc = null;
			string defaultNmspc = !string.IsNullOrEmpty (defaultNamespace)
				? defaultNamespace
				: SanitisePotentialNamespace (project.Name) ?? "Application";

			if (string.IsNullOrEmpty (fileName)) {
				return defaultNmspc;
			}

			string dirname = Path.GetDirectoryName (fileName);
			string relativeDirname = null;
			if (!String.IsNullOrEmpty (dirname)) {
				relativeDirname = project.GetRelativeChildPath (dirname);
				if (string.IsNullOrEmpty (relativeDirname) || relativeDirname.StartsWith (".."))
					relativeDirname = null;
			}

			if (relativeDirname != null) {
				try {
					switch (pol.DirectoryNamespaceAssociation) {
					case DirectoryNamespaceAssociation.PrefixedFlat:
						root = defaultNmspc;
						goto case DirectoryNamespaceAssociation.Flat;
					case DirectoryNamespaceAssociation.Flat:
						//use the last component only
						dirNamespc = SanitisePotentialNamespace (Path.GetFileName (relativeDirname));
						break;

					case DirectoryNamespaceAssociation.PrefixedHierarchical:
						root = defaultNmspc;
						goto case DirectoryNamespaceAssociation.Hierarchical;
					case DirectoryNamespaceAssociation.Hierarchical:
						dirNamespc = SanitisePotentialNamespace (GetHierarchicalNamespace (relativeDirname));
						break;
					}
				} catch (IOException ex) {
					LoggingService.LogError ("Could not determine namespace for file '" + fileName + "'", ex);
				}

			}

			if (dirNamespc != null && root == null)
				return dirNamespc;
			if (dirNamespc != null && root != null)
				return root + "." + dirNamespc;
			return defaultNmspc;
		}

		static string GetHierarchicalNamespace (string relativePath)
		{
			StringBuilder sb = new StringBuilder (relativePath);
			for (int i = 0; i < sb.Length; i++) {
				if (sb[i] == Path.DirectorySeparatorChar)
					sb[i] = '.';
			}
			return sb.ToString ();
		}

		static string SanitisePotentialNamespace (string potential)
		{
			StringBuilder sb = new StringBuilder ();
			foreach (char c in potential) {
				if (char.IsLetter (c) || c == '_' || (sb.Length > 0 && (char.IsLetterOrDigit (sb[sb.Length - 1]) || sb[sb.Length - 1] == '_') && (c == '.' || char.IsNumber (c)))) {
					sb.Append (c);
				}
			}
			if (sb.Length > 0) {
				if (sb[sb.Length - 1] == '.')
					sb.Remove (sb.Length - 1, 1);

				return sb.ToString ();
			} else
				return null;
		}

		void RuntimeSystemAssemblyServiceDefaultRuntimeChanged (object sender, EventArgs e)
		{
			if (composedAssemblyContext != null) {
				composedAssemblyContext.Replace (currentRuntimeContext, TargetRuntime.AssemblyContext);
				currentRuntimeContext = TargetRuntime.AssemblyContext;
			}
			UpdateSystemReferences ();
		}

		// Make sure that the project references are valid for the target clr version.
		void UpdateSystemReferences ()
		{
			foreach (ProjectReference pref in References) {
				if (pref.ReferenceType == ReferenceType.Package) {
					// package name is only relevant if it's not a framework package
					var pkg = pref.Package;
					string packageName = pkg != null && !pkg.IsFrameworkPackage? pkg.Name : null;
					// find the version of the assembly that's valid for the new framework
					var newAsm = AssemblyContext.GetAssemblyForVersion (pref.Reference, packageName, TargetFramework);
					// if it changed, clear assembly resolution caches and update reference
					if (newAsm == null) {
						pref.ResetReference ();
					} else if (newAsm.FullName != pref.Reference) {
						pref.Reference = newAsm.FullName;
					} else if (!pref.IsValid || newAsm.Package != pref.Package) {
						pref.ResetReference ();
					}
				}
			}
		}

		protected override IEnumerable<string> OnGetStandardBuildActions ()
		{
			return BuildAction.DotNetActions;
		}

		protected override IList<string> OnGetCommonBuildActions ()
		{
			return BuildAction.DotNetCommonActions;
		}

		protected override void OnEndLoad ()
		{
			// The resource handler policy may have changed after loading, so reset any
			// previously allocated resource handler
			resourceHandler = null;

			// Just after loading, the resource Ids are using the file format's policy.
			// They have to be converted to the new policy
			IResourceHandler handler = GetService<IResourceHandler> ();
			if (handler != null)
				MigrateResourceIds (handler, ResourceHandler);

			base.OnEndLoad ();
		}

		public void UpdateResourceHandler (bool keepOldIds)
		{
			IResourceHandler oldHandler = resourceHandler;
			resourceHandler = null;
			if (keepOldIds && oldHandler != null)
				MigrateResourceIds (oldHandler, ResourceHandler);
		}

		void MigrateResourceIds (IResourceHandler oldHandler, IResourceHandler newHandler)
		{
			if (oldHandler.GetType () != newHandler.GetType ()) {
				// If the file format has a default resource handler different from the one
				// choosen for this project, then all resource ids must be converted
				foreach (ProjectFile file in Files.Where (f => f.BuildAction == BuildAction.EmbeddedResource)) {
					if (file.Subtype == Subtype.Directory)
						continue;
					string oldId = file.GetResourceId (oldHandler);
					string newId = file.GetResourceId (newHandler);
					string newDefault = newHandler.GetDefaultResourceId (file);
					if (oldId != newId) {
						if (newDefault == oldId)
							file.ResourceId = null;
						else
							file.ResourceId = oldId;
					} else {
						if (newDefault == oldId)
							file.ResourceId = null;
					}
				}
			}
		}

		protected internal override void OnItemsAdded (IEnumerable<ProjectItem> objs)
		{
			base.OnItemsAdded (objs);
			foreach (var pref in objs.OfType<ProjectReference> ()) {
				pref.SetOwnerProject (this);
				NotifyReferenceAddedToProject (pref);
			}
		}

		protected internal override void OnItemsRemoved (IEnumerable<ProjectItem> objs)
		{
			base.OnItemsRemoved (objs);
			foreach (var pref in objs.OfType<ProjectReference> ()) {
				pref.SetOwnerProject (null);
				NotifyReferenceRemovedFromProject (pref);
			}
		}

		internal void NotifyReferenceRemovedFromProject (ProjectReference reference)
		{
			NotifyModified ("References");
			ProjectExtension.OnReferenceRemovedFromProject (new ProjectReferenceEventArgs (this, reference));
		}

		internal void NotifyReferenceAddedToProject (ProjectReference reference)
		{
			NotifyModified ("References");
			ProjectExtension.OnReferenceAddedToProject (new ProjectReferenceEventArgs (this, reference));
		}

		protected virtual void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e)
		{
			if (ReferenceRemovedFromProject != null) {
				ReferenceRemovedFromProject (this, e);
			}
		}

		protected virtual void OnReferenceAddedToProject (ProjectReferenceEventArgs e)
		{
			if (ReferenceAddedToProject != null) {
				ReferenceAddedToProject (this, e);
			}
		}

		public event ProjectReferenceEventHandler ReferenceRemovedFromProject;
		public event ProjectReferenceEventHandler ReferenceAddedToProject;


		private void OnFileRemoved (Object o, FileEventArgs e)
		{
			foreach (FileEventInfo ei in e)
				CheckReferenceChange (ei.FileName);
		}

		protected async override Task DoExecute (ProgressMonitor monitor, ExecutionContext context, ConfigurationSelector configuration)
		{
			DotNetProjectConfiguration dotNetProjectConfig = GetConfiguration (configuration) as DotNetProjectConfiguration;
			monitor.Log.WriteLine (GettextCatalog.GetString ("Running {0} ...", dotNetProjectConfig.CompiledOutputName));

			IConsole console = dotNetProjectConfig.ExternalConsole
				? context.ExternalConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput)
				: context.ConsoleFactory.CreateConsole (!dotNetProjectConfig.PauseConsoleOutput);

			try {
				try {
					ExecutionCommand executionCommand = CreateExecutionCommand (configuration, dotNetProjectConfig);
					if (context.ExecutionTarget != null)
						executionCommand.Target = context.ExecutionTarget;

					if (!context.ExecutionHandler.CanExecute (executionCommand)) {
						monitor.ReportError (GettextCatalog.GetString ("Can not execute \"{0}\". The selected execution mode is not supported for .NET projects.", dotNetProjectConfig.CompiledOutputName), null);
						return;
					}

					ProcessAsyncOperation asyncOp = context.ExecutionHandler.Execute (executionCommand, console);
					var stopper = monitor.CancellationToken.Register (asyncOp.Cancel);

					await asyncOp.Task;

					stopper.Dispose ();

					monitor.Log.WriteLine (GettextCatalog.GetString ("The application exited with code: {0}", asyncOp.ExitCode));
				} finally {
					console.Dispose ();
				}
			} catch (Exception ex) {
				LoggingService.LogError (string.Format ("Cannot execute \"{0}\"", dotNetProjectConfig.CompiledOutputName), ex);
				monitor.ReportError (GettextCatalog.GetString ("Cannot execute \"{0}\"", dotNetProjectConfig.CompiledOutputName), ex);
			}
		}


		protected override void OnReadProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
		{
			base.OnReadProjectHeader (monitor, msproject);

			compileTarget = msproject.EvaluatedProperties.GetValue<CompileTarget> ("OutputType");
			defaultNamespace = msproject.EvaluatedProperties.GetValue ("RootNamespace", string.Empty);
			usePartialTypes = msproject.EvaluatedProperties.GetValue ("UsePartialTypes", true);

			string frameworkIdentifier = msproject.EvaluatedProperties.GetValue ("TargetFrameworkIdentifier");
			string frameworkVersion = msproject.EvaluatedProperties.GetValue ("TargetFrameworkVersion");
			string frameworkProfile = msproject.EvaluatedProperties.GetValue ("TargetFrameworkProfile");

			//determine the default target framework from the project type's default
			//overridden by the components in the project
			var def = GetDefaultTargetFrameworkForFormat (ToolsVersion);
			var targetFx = new TargetFrameworkMoniker (
				string.IsNullOrEmpty (frameworkIdentifier)? def.Identifier : frameworkIdentifier,
				string.IsNullOrEmpty (frameworkVersion)? def.Version : frameworkVersion,
				string.IsNullOrEmpty (frameworkProfile)? def.Profile : frameworkProfile);


			string fx = ExtendedProperties ["InternalTargetFrameworkVersion"] as string;
			if (!string.IsNullOrEmpty (fx)) {
				targetFx = TargetFrameworkMoniker.Parse (fx);
				ExtendedProperties.Remove ("InternalTargetFrameworkVersion");
			}

			TargetFramework = Runtime.SystemAssemblyService.GetTargetFramework (targetFx);
		}

		protected override void OnWriteProjectHeader (ProgressMonitor monitor, MSBuildProject msproject)
		{
			base.OnWriteProjectHeader (monitor, msproject);

			IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup ();

			globalGroup.SetValue ("OutputType", compileTarget);
			globalGroup.SetValue ("RootNamespace", defaultNamespace, string.Empty);
			globalGroup.SetValue ("UsePartialTypes", usePartialTypes, true);
		}

		protected override void OnWriteProject (ProgressMonitor monitor, MSBuildProject msproject)
		{
			base.OnWriteProject (monitor, msproject);

			var moniker = TargetFramework.Id;
			bool supportsMultipleFrameworks = true; // All supported formats support multiple frameworks. // toolsFormat.SupportsMonikers || toolsFormat.SupportedFrameworks.Length > 0;
			var def = GetDefaultTargetFrameworkForFormat (ToolsVersion);

			IMSBuildPropertySet globalGroup = msproject.GetGlobalPropertyGroup ();

			// If the format only supports one fx version, or the version is the default, there is no need to store it.
			// However, is there is already a value set, do not remove it.
			if (supportsMultipleFrameworks) {
				globalGroup.SetValue ("TargetFrameworkVersion", "v" + moniker.Version, "v" + def.Version, true);
			}

			if (MSBuildFileFormat.ToolsSupportMonikers (ToolsVersion)) {
				globalGroup.SetValue ("TargetFrameworkIdentifier", moniker.Identifier, def.Identifier, true);
				globalGroup.SetValue ("TargetFrameworkProfile", moniker.Profile, def.Profile, true);
			}
		}

		protected override void OnWriteConfiguration (ProgressMonitor monitor, ProjectConfiguration config, IMSBuildPropertySet pset)
		{
			base.OnWriteConfiguration (monitor, config, pset);
			if (pset.Project.IsNewProject)
				pset.SetValue ("ErrorReport", "prompt");
			
		}

		internal class DefaultDotNetProjectExtension: DotNetProjectExtension
		{
			internal protected override DotNetProjectFlags OnGetDotNetProjectFlags ()
			{
				return Project.OnGetDotNetProjectFlags ();
			}

			internal protected override bool OnGetCanReferenceProject (DotNetProject targetProject, out string reason)
			{
				return Project.CheckCanReferenceProject (targetProject, out reason);
			}

			internal protected override string OnGetDefaultTargetPlatform (ProjectCreateInformation projectCreateInfo)
			{
				return Project.OnGetDefaultTargetPlatform (projectCreateInfo);
			}

			internal protected override IEnumerable<string> OnGetReferencedAssemblies (ConfigurationSelector configuration, bool includeProjectReferences)
			{
				return Project.OnGetReferencedAssemblies (configuration, includeProjectReferences);
			}

			internal protected override ExecutionCommand OnCreateExecutionCommand (ConfigurationSelector configSel, DotNetProjectConfiguration configuration)
			{
				return Project.OnCreateExecutionCommand (configSel, configuration);
			}

			internal protected override void OnReferenceRemovedFromProject (ProjectReferenceEventArgs e)
			{
				Project.OnReferenceRemovedFromProject (e);
			}

			internal protected override void OnReferenceAddedToProject (ProjectReferenceEventArgs e)
			{
				Project.OnReferenceAddedToProject (e);
			}

			internal protected override Task<BuildResult> OnCompile (ProgressMonitor monitor, BuildData buildData)
			{
				return Project.OnCompile (monitor, buildData);
			}

			#region Framework management

			internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkId ()
			{
				return Project.OnGetDefaultTargetFrameworkId ();
			}

			internal protected override TargetFrameworkMoniker OnGetDefaultTargetFrameworkForFormat (string toolsVersion)
			{
				return Project.OnGetDefaultTargetFrameworkForFormat (toolsVersion);
			}

			internal protected override bool OnGetSupportsFramework (TargetFramework framework)
			{
				return Project.OnSupportsFramework (framework);
			}

			#endregion
		}
	}

	[Flags]
	public enum DotNetProjectFlags
	{
		None = 0,
		SupportsPartialTypes = 1,
		GeneratesDebugInfoFile = 2,
		IsLibrary = 4
	}
}