Repository navigation
Expand file tree
/
Copy pathProject.fs
More file actions
2796 lines (2368 loc) · 161 KB
/
Copy pathProject.fs
File metadata and controls
2796 lines (2368 loc) · 161 KB
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
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
#nowarn "40"
namespace rec Microsoft.VisualStudio.FSharp.ProjectSystem
open Helpers
open System
open System.Threading
open System.Reflection
open System.CodeDom
open System.CodeDom.Compiler
open System.Runtime.CompilerServices
open System.Runtime.InteropServices
open System.Runtime.Serialization
open System.Collections.Generic
open System.Collections
open System.ComponentModel
open System.ComponentModel.Design
open System.Text.RegularExpressions
open System.Diagnostics
open System.IO
open System.Drawing
open System.Globalization
open System.Text
open System.Windows.Controls
open Microsoft.Win32
open Microsoft.VisualStudio
open Microsoft.VisualStudio.Shell
open Microsoft.VisualStudio.Shell.Interop
open Microsoft.VisualStudio.Shell.Flavor
open Microsoft.VisualStudio.OLE.Interop
open Microsoft.VisualStudio.FSharp.ProjectSystem
open Microsoft.VisualStudio.FSharp.LanguageService
open Microsoft.VisualStudio.FSharp.ProjectSystem.Automation
open Microsoft.VisualStudio.FSharp.Editor
open Microsoft.VisualStudio.Editors
open Microsoft.VisualStudio.Editors.PropertyPages
open Microsoft.VisualStudio.PlatformUI
open EnvDTE
module internal VSHiveUtilities =
/// For a given sub-hive, check to see if a 3rd party has specified any
/// custom/extended property pages.
/// Generally, we'll find the property page GUIDs in the following locations:
/// HKLM\SOFTWARE\Microsoft\VisualStudio\<VS_VERSION>\<guidFSharpProjectFactoryStringWithCurlies>\ConfigPropertyPages
/// HKLM\SOFTWARE\Microsoft\VisualStudio\<VS_VERSION>\<guidFSharpProjectFactoryStringWithCurlies>\CommonPropertyPages
/// HKLM\SOFTWARE\Microsoft\VisualStudio\<VS_VERSION>\<guidFSharpProjectFactoryStringWithCurlies>\PriorityPropertyPages
let GetExtendedPropertyPages (pphive : RegistryKey) =
if null = pphive then [||]
else
// read the sub keys for the property key hive
let subKeys = pphive.GetSubKeyNames()
// filter out keys that aren't proper GUIDs
let isProperGuidSubKey (g : string) =
try
// we'll accept any kind of guid
System.Guid(g)
with _ -> Unchecked.defaultof<System.Guid>
subKeys |> Array.map isProperGuidSubKey |> Array.filter (fun g -> g <> Unchecked.defaultof<System.Guid>)
let lazyPropertyPages =
lazy (
let vsHive = Microsoft.VisualStudio.Shell.VSRegistry.RegistryRoot(Microsoft.VisualStudio.Shell.Interop.__VsLocalRegistryType.RegType_Configuration)
let fsHive = vsHive.OpenSubKey("Projects").OpenSubKey(GuidList.guidFSharpProjectFactoryStringWithCurlies)
let commonPropertyPages = GetExtendedPropertyPages(fsHive.OpenSubKey("CommonPropertyPages"))
let configPropertyPages = GetExtendedPropertyPages(fsHive.OpenSubKey("ConfigPropertyPages"))
let priorityPropertyPages = GetExtendedPropertyPages(fsHive.OpenSubKey("PriorityPropertyPages"))
commonPropertyPages, configPropertyPages, priorityPropertyPages
)
let getCommonExtendedPropertyPages() = match lazyPropertyPages.Force() with (common,_,_) -> common
let getConfigExtendedPropertyPages() = match lazyPropertyPages.Force() with (_,config,_) -> config
let getPriorityExtendedPropertyPages() = match lazyPropertyPages.Force() with (_,_,priority) -> priority
// An IProjectSite object with hot-swappable inner implementation
type internal DynamicProjectSite(origInnerImpl : Microsoft.VisualStudio.FSharp.Editor.IProjectSite) =
let mutable inner = origInnerImpl
member x.SetImplementation newInner =
inner <- newInner
// This interface is thread-safe, assuming "inner" is thread-safe
interface Microsoft.VisualStudio.FSharp.Editor.IProjectSite with
member _.Description = inner.Description
member _.CompilationSourceFiles = inner.CompilationSourceFiles
member _.CompilationOptions = inner.CompilationOptions
member _.CompilationReferences = inner.CompilationReferences
member _.CompilationBinOutputPath = inner.CompilationBinOutputPath
member _.ProjectFileName = inner.ProjectFileName
member _.AdviseProjectSiteChanges(callbackOwnerKey,callback) = inner.AdviseProjectSiteChanges(callbackOwnerKey, callback)
member _.AdviseProjectSiteCleaned(callbackOwnerKey,callback) = inner.AdviseProjectSiteCleaned(callbackOwnerKey, callback)
member _.AdviseProjectSiteClosed(callbackOwnerKey,callback) = inner.AdviseProjectSiteClosed(callbackOwnerKey, callback)
member _.BuildErrorReporter with get() = inner.BuildErrorReporter and set v = inner.BuildErrorReporter <- v
member _.TargetFrameworkMoniker = inner.TargetFrameworkMoniker
member _.ProjectGuid = inner.ProjectGuid
member _.IsIncompleteTypeCheckEnvironment = false
member _.LoadTime = inner.LoadTime
member _.ProjectProvider = inner.ProjectProvider
override x.ToString() = inner.ProjectFileName
type internal ProjectSiteOptionLifetimeState =
| Opening=1 // The project has been opened, but has not yet called Compile() to compute sources/flags
| Opened=2 // The project is open, has some (possibly stale) sources/flags info
| Closed=3 // The project closed, has stale sources/flags info
type internal ProjectSiteOptionLifetime() =
let mutable state = ProjectSiteOptionLifetimeState.Opening
let mutable projectSite : DynamicProjectSite option = None
// This member is thread-safe
member x.State = state
// This member is thread-safe
member x.GetProjectSite() =
Debug.Assert(state <> ProjectSiteOptionLifetimeState.Opening, "ProjectSite is not available")
projectSite.Value :> Microsoft.VisualStudio.FSharp.Editor.IProjectSite
// This member is thread-safe
member x.TryGetProjectSite() =
match state, projectSite with
| ProjectSiteOptionLifetimeState.Opening, _
| ProjectSiteOptionLifetimeState.Closed, _ -> None
| _, None -> None
| _, Some x -> Some(x :> Microsoft.VisualStudio.FSharp.Editor.IProjectSite)
member x.Open(site) =
Debug.Assert((state = ProjectSiteOptionLifetimeState.Opening), "Called Open, but not in Opening state")
state <- ProjectSiteOptionLifetimeState.Opened
projectSite <- Some(new DynamicProjectSite(site))
member x.Close(site) =
Debug.Assert((state = ProjectSiteOptionLifetimeState.Opened || state = ProjectSiteOptionLifetimeState.Opening), "Called Close, but not in Opened or Opening state")
state <- ProjectSiteOptionLifetimeState.Closed
match projectSite with
| Some ps -> ps.SetImplementation(site)
| None -> projectSite <- Some (new DynamicProjectSite(site))
override x.ToString() =
match projectSite with
| Some ps -> ps.ToString()
| None -> "None"
type internal MyVSConstants =
static member ExploreFolderInWindows = 1635u
type internal Notifier() =
let notificationsDict = new System.Collections.Generic.Dictionary<string,Microsoft.VisualStudio.FSharp.Editor.AdviseProjectSiteChanges>()
member this.Notify() =
for kvp in notificationsDict do
kvp.Value.Invoke()
member this.Advise(callbackOwnerKey, callback) =
notificationsDict.[callbackOwnerKey] <- callback
// // Used to get us sorted appropriately with the other MSFT products in the splash screen and about box
// [<Guid("591E80E4-5F44-11d3-8BDC-00C04F8EC28C")>]
// [<InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>]
// [<ComImport>]
// [<ComVisible(true)>]
// [<System.Runtime.InteropServices.ClassInterface(ClassInterfaceType.None)>]
// [<AbstractClass>]
// type public IVsMicrosoftInstalledProduct =
// interface IVsInstalledProduct
//
// abstract IdBmpSplashM : byref<uint32> -> unit
// abstract OfficialNameM : on : byref<string> -> unit
// abstract ProductIDM : pid : byref<string> -> unit
// abstract ProductDetailsM : pd : byref<string> -> unit
// abstract IdIcoLogoForAboutboxM : byref<uint32> -> unit
// abstract ProductRegistryName : prn : byref<string> -> unit
exception internal ExitedOk
exception internal ExitedWithError
[<Guid(GuidList.guidFSharpProjectPkgString)>]
type internal FSharpProjectPackage() =
inherit ProjectPackage()
/// This method loads a localized string based on the specified resource.
/// <param name="resourceName">Resource to load</param>
/// <returns>String loaded for the specified resource</returns>
member this.GetResourceString(resourceName:string) =
let mutable resourceValue = null
let resourceManager = GetService2<SVsResourceManager,IVsResourceManager>(this :> System.IServiceProvider)
let mutable packageGuid = this.GetType().GUID
let hr = resourceManager.LoadResourceString(&packageGuid, -1, resourceName, &resourceValue)
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr) |> ignore
resourceValue
override this.Initialize() =
Microsoft.VisualStudio.FSharp.LanguageService.UIThread.CaptureSynchronizationContext()
Microsoft.VisualStudio.FSharp.ProjectSystem.UIThread.CaptureSynchronizationContext()
base.Initialize()
// read list of available FSharp.Core versions
do
let nullService =
{ new Microsoft.VisualStudio.FSharp.ProjectSystem.IFSharpCoreVersionLookupService with
member this.ListAvailableFSharpCoreVersions(_) = Array.empty }
let service =
try
// SupportedRuntimes is deployed alongside the ProjectSystem dll
let path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
let supportedRuntimesXml = System.Xml.Linq.XDocument.Load(Path.Combine(path, "SupportedRuntimes.xml"))
let tryGetAttr (el : System.Xml.Linq.XElement) attr =
match el.Attribute(System.Xml.Linq.XName.Get attr) with
| null -> None
| x -> Some x.Value
let flatList =
supportedRuntimesXml.Root.Elements(System.Xml.Linq.XName.Get "TargetFramework")
|> Seq.choose (fun tf ->
match tryGetAttr tf "Identifier", tryGetAttr tf "Version", tryGetAttr tf "Profile" with
| Some key1, Some key2, _
| Some key1, _, Some key2 ->
Some(
key1, // identifier
key2, // version or profile
[|
for asm in tf.Elements(System.Xml.Linq.XName.Get "Assembly") do
let version = asm.Attribute(System.Xml.Linq.XName.Get "Version")
let description = asm.Attribute(System.Xml.Linq.XName.Get "Description")
match version, description with
| null, _ | _, null -> ()
| version, description ->
yield Microsoft.VisualStudio.FSharp.ProjectSystem.FSharpCoreVersion(version.Value, description.Value)
|]
)
| _ -> None
)
|> Seq.toList
let (_, _, v2) = flatList |> List.find(fun (k1, k2, _) -> k1 = FSharpSDKHelper.NETFramework && k2 = FSharpSDKHelper.v20)
let (_, _, v4) = flatList |> List.find(fun (k1, k2, _) -> k1 = FSharpSDKHelper.NETFramework && k2 = FSharpSDKHelper.v40)
let (_, _, v45) = flatList |> List.find(fun (k1, k2, _) -> k1 = FSharpSDKHelper.NETFramework && k2 = FSharpSDKHelper.v45)
{
new Microsoft.VisualStudio.FSharp.ProjectSystem.IFSharpCoreVersionLookupService with
member this.ListAvailableFSharpCoreVersions(targetFramework) =
if targetFramework.Identifier = FSharpSDKHelper.NETFramework
then
// for .NETFramework we distinguish between 2.0, 4.0 and 4.5
if targetFramework.Version.Major < 4 then v2
elif targetFramework.Version.Major = 4 && targetFramework.Version.Minor < 5 then v4
else v45
else
// for other target frameworks we assume that they are distinguished by the profile
let result =
flatList
|> List.tryPick(fun (k1, k2, list) ->
if k1 = targetFramework.Identifier && k2 = targetFramework.Profile then Some list else None
)
match result with
| Some list -> list
| None ->
Debug.Assert(false, sprintf "Unexpected target framework identifier '%O'" targetFramework)
[||]
}
with _ -> nullService
(this :> IServiceContainer).AddService(typeof<Microsoft.VisualStudio.FSharp.ProjectSystem.IFSharpCoreVersionLookupService>, service, promote = true)
this.RegisterProjectFactory(new FSharpProjectFactory(this))
//this.RegisterProjectFactory(new FSharpWPFProjectFactory(this :> IServiceProvider))
// was used to ensure the LS has been initialized, because the TypeProviderSecurityGlobals
// global state was needed for e.g. Tools\Options
//TODO the TypeProviderSecurityGlobals does not exists anymore, remove the initialization?
this.GetService(typeof<FSharpLanguageService>) |> ignore
/// This method is called during Devenv /Setup to get the bitmap to
/// display on the splash screen for this package.
/// This method may be deprecated - IdIcoLogoForAboutbox should now be called instead
// REVIEW: If this turns out to be true, remove the IdBmpSplash resource
member this.getIdBmpSplash(pIdBmp:byref<uint32>) =
pIdBmp <- 0u
VSConstants.S_OK
/// This method is called to get the icon that will be displayed in the
/// Help About dialog when this package is selected.
/// This methods provides the product official name, it will be
/// displayed in the help about dialog.
/// <param name="pbstrName">Out parameter to which to assign the product name</param>
/// <returns>HRESULT, indicating success or failure</returns>
member this.getOfficialName(pbstrName:byref<string>) =
pbstrName <- this.GetResourceString("@ProductName10") ;
VSConstants.S_OK
/// This methods provides the product version, it will be
/// displayed in the help about dialog.
/// <param name="pbstrPID">Out parameter to which to assign the version number</param>
/// <returns>HRESULT, indicating success or failure</returns>
member this.getProductID(pbstrPID:byref<string>) =
pbstrPID <- this.GetResourceString("@ProductID") ;
VSConstants.S_OK
/// This methods provides the product description, it will be
/// displayed in the help about dialog.
/// <param name="pbstrProductDetails">Out parameter to which to assign the description of the package</param>
/// <returns>HRESULT, indicating success or failure</returns>
member this.getProductDetails(pbstrProductDetails:byref<string>) =
pbstrProductDetails <- this.GetResourceString("@ProductDetails10")
VSConstants.S_OK
/// <param name="pIdIco">The resource id corresponding to the icon to display on the Help About dialog</param>
/// <returns>HRESULT, indicating success or failure</returns>
member this.getIdIcoLogoForAboutbox(pIdIco:byref<uint32>) =
pIdIco <- 400u
VSConstants.S_OK
/// Factory for creating our editor, creates FSharp Projects
[<Guid(GuidList.guidFSharpProjectFactoryString)>]
type internal FSharpProjectFactory(package:FSharpProjectPackage ) =
inherit ProjectFactory(package)
override this.CreateProject() =
// Then create the project to load.
let project = new FSharpProjectNode(this.Package :?> FSharpProjectPackage)
project.SetSite(GetService<IOleServiceProvider>(this.Package :> System.IServiceProvider)) |> ignore
(project :> ProjectNode)
/// This class is a 'fake' project factory that is used by WAP to register WAP specific information about
/// FSharp projects.
[<Guid("4EAD5BC6-47F1-4FCB-823D-0CD64302D5B9")>]
type internal WAFSharpProjectFactory() = class end
[<Guid("C15CF2F6-9005-44AD-9991-683808A8E5EA")>]
type internal FSharpProjectNode(package:FSharpProjectPackage) as this =
inherit ProjectNode()
let mutable vsProject : VSLangProj.VSProject = null
let mutable trackDocumentsHandle = 0u
let mutable addFilesNotification : (string array -> unit) option = None // this object is only used for helping re-order newly added files (VS defaults to alphabetical order)
let mutable updateSolnEventsHandle = 0u
let mutable updateSolnEventsHandle2 = 0u
let mutable updateSolnEventsHandle3 = 0u
let mutable updateSolnEventsHandle4 = 0u
let mutable trackProjectRetargetingCookie = 0u
let mutable actuallyBuild = true
let mutable inMidstOfReloading = false
let mutable sourcesAndFlags : option<(string[] * string[])> = None
let mutable normalizedRefs : string[] option = None
#if DEBUG
let logger = new Microsoft.Build.Logging.ConsoleLogger(Microsoft.Build.Framework.LoggerVerbosity.Diagnostic,
(fun s -> Trace.WriteLine("MSBuild: " + s)),
(fun _ -> ()),
(fun _ -> ()) )
#endif
let projectSite = new ProjectSiteOptionLifetime()
let mutable buildErrorReporter = None
let sourcesAndFlagsNotifier = new Notifier()
let cleanNotifier = new Notifier()
let closeNotifier = new Notifier()
[<Microsoft.FSharp.Core.DefaultValue>]
static val mutable private imageOffset : int
#if DEBUG
let uiThreadId = System.Threading.Thread.CurrentThread.ManagedThreadId
let mutable compileWasActuallyCalled = false
#endif
// these get initialized once and for all in SetSite()
let mutable isInCommandLineMode = false
let mutable accessor : IVsBuildManagerAccessor = null
//Store the number of images in ProjectNode so we know the offset of the F# icons.
do FSharpProjectNode.imageOffset <- this.ImageHandler.ImageList.Images.Count
do this.CanFileNodesHaveChilds <- false
do this.OleServiceProvider.AddService(typeof<VSLangProj.VSProject>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
do this.SupportsProjectDesigner <- true
do this.Package <- package
do
// Add in correct order, as defined by the "FSharpImageName" enum
this.ImageHandler.AddImage(FSharpSR.GetObject("4101") :?> System.Drawing.Bitmap) // 4005 = CodeFile
this.ImageHandler.AddImage(FSharpSR.GetObject("4100") :?> System.Drawing.Bitmap) // 4008 = EmptyProject
this.ImageHandler.AddImage(FSharpSR.GetObject("4103") :?> System.Drawing.Bitmap) // 4006 = ScriptFile
this.ImageHandler.AddImage(FSharpSR.GetObject("4102") :?> System.Drawing.Bitmap) // 4007 = Signature
/// Provide mapping from our browse objects and automation objects to our CATIDs
do
// The following properties classes are specific to F# so we can use their GUIDs directly
this.AddCATIDMapping(typeof<FSharpProjectNodeProperties>, typeof<FSharpProjectNodeProperties>.GUID)
this.AddCATIDMapping(typeof<FSharpFileNodeProperties>, typeof<FSharpFileNodeProperties>.GUID)
// This one we use the same as F# file nodes since both refer to files
this.AddCATIDMapping(typeof<FileNodeProperties>, typeof<FSharpFileNodeProperties>.GUID)
this.AddCATIDMapping(typeof<ProjectConfigProperties>, typeof<ProjectConfigProperties>.GUID)
#if DEBUG
this.SetDebugLogger(logger)
#endif
member private this.GetCurrentFrameworkName() =
let tfm = this.GetTargetFrameworkMoniker()
System.Runtime.Versioning.FrameworkName(tfm)
member private this.CheckProjectFrameworkIdentifier(expected) =
let currentFrameworkName = this.GetCurrentFrameworkName()
currentFrameworkName.Identifier = expected
override this.TargetFSharpCoreVersion
with get() : string =
if this.CanUseTargetFSharpCoreReference then
this.GetProjectProperty(ProjectFileConstants.TargetFSharpCoreVersion)
else
let fsharpCoreRef =
this.GetReferenceContainer().EnumReferences()
|> Seq.tryPick (
function
| :? AssemblyReferenceNode as arn when AssemblyReferenceNode.IsFSharpCoreReference arn -> Some arn
| _ -> None
)
match fsharpCoreRef with
| Some arn when arn.ResolvedAssembly <> null-> arn.ResolvedAssembly.Version.ToString()
| _ -> null
and set(v) =
if not this.CanUseTargetFSharpCoreReference then () else
let currentVersion = System.Version(this.TargetFSharpCoreVersion)
let newVersion = System.Version(v)
if not (currentVersion.Equals newVersion) then
let hasSwitchedToLatestOnlyVersionFromLegacy =
let legacyVersions =
["2.3.0.0" // .NET 2 desktop
"4.3.0.0"; "4.3.1.0"; "4.4.0.0" // .NET 4 desktop
"2.3.5.0"; "2.3.5.1"; "3.47.4.0" // portable 47
"3.3.1.0"; "3.7.4.0" // portable 7
"3.78.3.1"; "3.78.4.0" // portable 78
"3.259.3.1"; "3.259.4.0"] // portable 259
|> List.map (fun s -> System.Version(s))
let latestOnlyVersions =
["4.4.3.0" // .NET 4 desktop
"3.47.41.0" // portable 47
"3.7.41.0" // portable 7
"3.78.41.0" // portable 78
"3.259.41.0"] // portable 259
|> List.map (fun s -> System.Version(s))
(legacyVersions |> List.exists ((=) currentVersion)) && (latestOnlyVersions |> List.exists ((=) newVersion))
if hasSwitchedToLatestOnlyVersionFromLegacy then
// we are switching from a legacy version to one that is present only in the latest release
let result =
VsShellUtilities.ShowMessageBox
(
serviceProvider = this.Site,
message = FSharpSR.FSharpCoreVersionIsNotLegacyCompatible(),
title = null,
icon = OLEMSGICON.OLEMSGICON_QUERY,
msgButton = OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
)
if result <> NativeMethods.IDYES then
Marshal.ThrowExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED)
this.SetProjectProperty(ProjectFileConstants.TargetFSharpCoreVersion, v)
let buildResult = this.Build(MsBuildTarget.ResolveAssemblyReferences)
for asmNode in System.Linq.Enumerable.OfType<AssemblyReferenceNode>(this.GetReferenceContainer().EnumReferences()) do
if (AssemblyReferenceNode.IsFSharpCoreReference asmNode) then
asmNode.RebindFSharpCoreAfterUpdatingVersion(buildResult)
this.UpdateTargetFramework(this.InteropSafeIVsHierarchy, this.GetTargetFrameworkMoniker(), this.GetTargetFrameworkMoniker()) |> ignore
this.ComputeSourcesAndFlags()
override this.SendReferencesToFSI(references) =
let shell = this.Site.GetService(typeof<SVsShell>) :?> IVsShell
let packageToBeLoadedGuid = ref (Guid(FSharpConstants.fsiPackageGuidString))
let pkg =
match shell.LoadPackage packageToBeLoadedGuid with
| VSConstants.S_OK, pkg -> pkg :?> Package
| _ -> null
if pkg = null then
nullArg "Can't find FSI Package."
Microsoft.VisualStudio.FSharp.Interactive.Hooks.AddReferencesToFSI pkg references
override x.SetSite(site:IOleServiceProvider) =
base.SetSite(site) |> ignore
let listener = new SolutionEventsListener(this)
let buildMgr = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager
if updateSolnEventsHandle <> 0u then
buildMgr.UnadviseUpdateSolutionEvents(updateSolnEventsHandle) |> ignore
buildMgr.AdviseUpdateSolutionEvents((listener :> IVsUpdateSolutionEvents), &updateSolnEventsHandle) |> ignore
let buildMgr2 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager2
if updateSolnEventsHandle2 <> 0u then
buildMgr2.UnadviseUpdateSolutionEvents(updateSolnEventsHandle2) |> ignore
buildMgr2.AdviseUpdateSolutionEvents((listener :> IVsUpdateSolutionEvents2), &updateSolnEventsHandle2) |> ignore
let buildMgr3 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager3
if updateSolnEventsHandle3 <> 0u then
buildMgr3.UnadviseUpdateSolutionEvents3(updateSolnEventsHandle3) |> ignore
buildMgr3.AdviseUpdateSolutionEvents3((listener :> IVsUpdateSolutionEvents3), &updateSolnEventsHandle3) |> ignore
let buildMgr5 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager5
if updateSolnEventsHandle4 <> 0u then
buildMgr5.UnadviseUpdateSolutionEvents4(updateSolnEventsHandle4) |> ignore
buildMgr5.AdviseUpdateSolutionEvents4((listener :> IVsUpdateSolutionEvents4), &updateSolnEventsHandle4) |> ignore
// Register for project retargeting events
let sTrackProjectRetargeting = this.Site.GetService(typeof<SVsTrackProjectRetargeting>) :?> IVsTrackProjectRetargeting
if trackProjectRetargetingCookie <> 0u then
sTrackProjectRetargeting.UnadviseTrackProjectRetargetingEvents(trackProjectRetargetingCookie) |> ignore
sTrackProjectRetargeting.AdviseTrackProjectRetargetingEvents((listener :> IVsTrackProjectRetargetingEvents), &trackProjectRetargetingCookie) |> ignore
isInCommandLineMode <-
let vsShell = this.Site.GetService(typeof<SVsShell>) :?> IVsShell
let mutable isInCommandLineMode : obj = null
vsShell.GetProperty(int __VSSPROPID.VSSPROPID_IsInCommandLineMode, &isInCommandLineMode) |> ignore
match isInCommandLineMode with
| :? bool as b -> b
| _ -> false
accessor <- this.Site.GetService(typeof<SVsBuildManagerAccessor>) :?> IVsBuildManagerAccessor
VSConstants.S_OK
override x.Close() =
projectSite.Close(x.CreateStaticProjectSite())
let buildMgr = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager
buildMgr.UnadviseUpdateSolutionEvents(updateSolnEventsHandle) |> ignore
let buildMgr2 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager2
buildMgr2.UnadviseUpdateSolutionEvents(updateSolnEventsHandle2) |> ignore
let buildMgr3 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager3
buildMgr3.UnadviseUpdateSolutionEvents3(updateSolnEventsHandle3) |> ignore
let buildMgr5 = this.Site.GetService(typeof<SVsSolutionBuildManager>) :?> IVsSolutionBuildManager5
buildMgr5.UnadviseUpdateSolutionEvents4(updateSolnEventsHandle4) |> ignore
let documentTracker = this.Site.GetService(typeof<SVsTrackProjectDocuments>) :?> IVsTrackProjectDocuments2
documentTracker.UnadviseTrackProjectDocumentsEvents(trackDocumentsHandle) |> ignore
// Unregister for project retargeting events
if trackProjectRetargetingCookie <> 0u then
let sTrackProjectRetargeting = this.Site.GetService(typeof<SVsTrackProjectRetargeting>) :?> IVsTrackProjectRetargeting
sTrackProjectRetargeting.UnadviseTrackProjectRetargetingEvents(trackProjectRetargetingCookie) |> ignore
trackProjectRetargetingCookie <- 0u
if (null <> x.Site) then
match TryGetService<IFSharpLibraryManager>(x.Site) with
| Some(libraryManager) ->
libraryManager.UnregisterHierarchy(this.InteropSafeIVsHierarchy)
| _ -> ()
closeNotifier.Notify()
vsProject <- null
accessor <- null
base.Close()
override x.Load(filename:string, location:string, name:string, flags:uint32, iidProject:byref<Guid>, canceled:byref<int> ) =
base.Load(filename, location, name, flags, &iidProject, &canceled)
// WAP ask the designer service for the CodeDomProvider corresponding to the project node.
this.OleServiceProvider.AddService(typeof<SVSMDCodeDomProvider>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
this.OleServiceProvider.AddService(typeof<System.CodeDom.Compiler.CodeDomProvider>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
match TryGetService<IFSharpLibraryManager>(x.Site) with
| Some(libraryManager) ->
libraryManager.RegisterHierarchy(this.InteropSafeIVsHierarchy)
| _ -> ()
// Listen for changes to files in the project
let documentTracker = this.Site.GetService(typeof<SVsTrackProjectDocuments>) :?> IVsTrackProjectDocuments2
documentTracker.AdviseTrackProjectDocumentsEvents(this, &trackDocumentsHandle) |> ignore
/// Returns the outputfilename based on the output type
member x.OutputFileName =
let assemblyName = this.ProjectMgr.GetProjectProperty(GeneralPropertyPageTag.AssemblyName.ToString(), true)
let outputTypeAsString = this.ProjectMgr.GetProjectProperty(GeneralPropertyPageTag.OutputType.ToString(), false)
let outputType = ParseEnum<OutputType>(outputTypeAsString)
assemblyName + GetOutputExtension(outputType)
/// Get the VSProject corresponding to this project
member this.VSProject : VSLangProj.VSProject =
if (vsProject= null) then
vsProject <- (new OAVSProject(this) :> VSLangProj.VSProject)
vsProject
[<Conditional("DEBUG")>]
override this.EnsureMSBuildAndSolutionExplorerAreInSync() =
let AllSolutionExplorerFilenames() =
let rec Compute (node : HierarchyNode, accum) =
if obj.ReferenceEquals(node,null) then
accum
else
let mutable result = accum
match node with
| :? FSharpFolderNode -> ()
| :? FSharpFileNode -> result <- node.Caption ::accum
| _ -> Debug.Assert(false, "unexpected node type")
if not (obj.ReferenceEquals(node.FirstChild, null)) then
result <- Compute(node.FirstChild, result)
result <- Compute(node.NextSibling, result)
result
let node = this.FirstChild.NextSibling // skip over 'References'
Compute(node, []) |> List.rev
let solnExplorer = AllSolutionExplorerFilenames()
let msBuild = MSBuildUtilities.AllVisibleItemFilenames(this)
Debug.Assert((solnExplorer = msBuild), sprintf "solution explorer view is out of sync with .fsproj file\n\nsolution explorer sees\n%A\n\nmsbuild sees\n%A" solnExplorer msBuild)
static member ImageOffset = FSharpProjectNode.imageOffset
/// Since we appended the F# images to the base image list in the ctor,
/// this should be the offset in the ImageList of the F# project icon.
override x.ImageIndex = FSharpProjectNode.imageOffset + int32 FSharpImageName.FsProject
override x.ProjectGuid = typeof<FSharpProjectFactory>.GUID
override x.ProjectType = "FSharp"
override x.Object = box this.VSProject
// #region overridden methods
override x.CreateReferenceContainerNode() : ReferenceContainerNode =
new FSharpReferenceContainerNode(this) :> ReferenceContainerNode
override x.CreateFolderNode(path, projectElement) =
new FSharpFolderNode(x, path, projectElement) :> FolderNode
override x.CreateFolderNodes(path) =
base.CreateFolderNodes(path)
override x.GetGuidProperty(propid:int, guid:byref<Guid> ) =
if (enum propid = __VSHPROPID.VSHPROPID_PreferredLanguageSID) then
guid <- new Guid(FSharpConstants.languageServiceGuidString)
VSConstants.S_OK
// below is how VS decide 'which templates' to associate with an 'add new item' call in this project
elif (enum propid = __VSHPROPID2.VSHPROPID_AddItemTemplatesGuid) then
guid <- typeof<FSharpProjectFactory>.GUID
VSConstants.S_OK
else
base.GetGuidProperty(propid, &guid)
member fshProjNode.MoveNewlyAddedFileSomehow<'a>(move : FSharpFileNode -> unit, f : unit -> 'a) : 'a =
Debug.Assert(addFilesNotification.IsNone, "bad use of addFilesNotification")
addFilesNotification <- Some (fun files ->
Debug.Assert(files.Length = 1)
let absoluteFileName = files.[0]
match fshProjNode.FindChild absoluteFileName with
| :? FSharpFileNode as fileNode ->
move fileNode
| node ->
let relativeFileName = PackageUtilities.MakeRelativeIfRooted(absoluteFileName, fshProjNode.BaseURI)
Debug.Assert(false, sprintf "Expected to find newly added FSharpFileNode in hierarchy '%s', but found '%O'" relativeFileName node)
)
try
let r = f()
fshProjNode.ComputeSourcesAndFlags()
r
finally
addFilesNotification <- None
member fshProjNode.MoveNewlyAddedFileAbove<'a>(nodeToMoveAbove : HierarchyNode, f : unit -> 'a) : 'a =
fshProjNode.MoveNewlyAddedFileSomehow((fun fileNode ->
FSharpFileNode.MoveToBottomOfGroup(fileNode)
FSharpFileNode.MoveTo(Above, nodeToMoveAbove, fileNode)
MSBuildUtilities.SyncWithHierarchy(fileNode)
), f)
member fshProjNode.MoveNewlyAddedFileBelow<'a>(nodeToMoveBelow : HierarchyNode, f : unit -> 'a) : 'a =
fshProjNode.MoveNewlyAddedFileSomehow((fun fileNode ->
FSharpFileNode.MoveToBottomOfGroup(fileNode)
FSharpFileNode.MoveTo(Below, nodeToMoveBelow, fileNode)
MSBuildUtilities.SyncWithHierarchy(fileNode)
), f)
member fshProjNode.MoveNewlyAddedFileToBottomOfGroup<'a> (f : unit -> 'a) : 'a =
fshProjNode.MoveNewlyAddedFileSomehow((fun fileNode ->
FSharpFileNode.MoveToBottomOfGroup(fileNode)
MSBuildUtilities.SyncWithHierarchy(fileNode)
), f)
override fshProjNode.MoveFileToBottomIfNoOtherPendingMove(fileNode) =
match addFilesNotification with
| None ->
FSharpFileNode.MoveToBottomOfGroup(fileNode)
MSBuildUtilities.SyncWithHierarchy(fileNode)
| Some _ -> ()
override fshProjNode.ExecCommandOnNode(guidCmdGroup:Guid, cmd:uint32, nCmdexecopt:uint32, pvaIn:IntPtr, pvaOut:IntPtr ) =
if guidCmdGroup = VsMenus.guidStandardCommandSet97 then
let cmdEnum : Microsoft.VisualStudio.VSConstants.VSStd97CmdID = enum (int cmd)
match cmdEnum with
| Microsoft.VisualStudio.VSConstants.VSStd97CmdID.AddNewItem ->
let r = fshProjNode.MoveNewlyAddedFileToBottomOfGroup (fun () ->
fshProjNode.AddItemToHierarchy(HierarchyAddType.AddNewItem))
fshProjNode.EnsureMSBuildAndSolutionExplorerAreInSync()
r
| Microsoft.VisualStudio.VSConstants.VSStd97CmdID.AddExistingItem ->
let r = fshProjNode.MoveNewlyAddedFileToBottomOfGroup (fun () ->
fshProjNode.AddItemToHierarchy(HierarchyAddType.AddExistingItem))
fshProjNode.EnsureMSBuildAndSolutionExplorerAreInSync()
r
| _ -> base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut)
elif guidCmdGroup = VsMenus.guidStandardCommandSet2K then
match (cmd |> int32 |> enum) : VSConstants.VSStd2KCmdID with
| _ when cmd = MyVSConstants.ExploreFolderInWindows ->
System.Diagnostics.Process.Start("explorer.exe", fshProjNode.ProjectFolder) |> ignore
VSConstants.S_OK
| _ -> base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut)
else
base.ExecCommandOnNode(guidCmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut)
override fshProjNode.QueryStatusOnNode(guidCmdGroup : Guid, cmd : UInt32, pCmdText : IntPtr, result : byref<QueryStatusResult>) =
if guidCmdGroup = VsMenus.guidStandardCommandSet2K then
match (cmd |> int32 |> enum) : VSConstants.VSStd2KCmdID with
| _ when cmd = MyVSConstants.ExploreFolderInWindows ->
result <- result ||| QueryStatusResult.SUPPORTED ||| QueryStatusResult.ENABLED
VSConstants.S_OK
| _ -> base.QueryStatusOnNode(guidCmdGroup, cmd, pCmdText, &result)
else
base.QueryStatusOnNode(guidCmdGroup, cmd, pCmdText, &result)
/// <summary>
/// Used to sort nodes in the hierarchy.
/// </summary>
override fshProjNode.CompareNodes(node1 : HierarchyNode, node2 : HierarchyNode) =
Debug.Assert(node1 <> null && node2 <> null)
let IsFileOrFolder (n : HierarchyNode) =
match n with
| :? FSharpFileNode -> true
| :? FSharpFolderNode -> true
| :? FileNode -> Debug.Assert(false, "FileNode that's not FSharpFileNode"); true
| :? FolderNode -> Debug.Assert(false, "FolderNode that's not FSharpFolderNode"); true
| _ -> false
if node1.SortPriority = node2.SortPriority then
match IsFileOrFolder node1, IsFileOrFolder node2 with
| true, true -> 0 // all files and folders sort to same equivalence class - no auto-alphabetization
| _ -> String.Compare(node2.Caption, node1.Caption, true, CultureInfo.CurrentCulture)
else
node2.SortPriority - node1.SortPriority
override x.CreatePropertiesObject() : NodeProperties =
(new FSharpProjectNodeProperties(this) :> NodeProperties)
/// Overriding to provide project general property page
override x.GetConfigurationIndependentPropertyPages() =
Array.append
[|
typeof<FSharpApplicationPropPageComClass>.GUID
typeof<FSharpBuildEventsPropPageComClass>.GUID
typeof<FSharpReferencePathsPropPageComClass>.GUID
|] (VSHiveUtilities.getCommonExtendedPropertyPages())
/// Returns the configuration dependent property pages.
override x.GetConfigurationDependentPropertyPages() =
Array.append
[|
typeof<FSharpBuildPropPageComClass>.GUID
typeof<FSharpDebugPropPageComClass>.GUID
|] (VSHiveUtilities.getConfigExtendedPropertyPages())
/// Returns the property pages in a specific order
override x.GetPriorityProjectDesignerPages() =
Array.append
[|
typeof<FSharpApplicationPropPageComClass>.GUID
typeof<FSharpBuildPropPageComClass>.GUID
typeof<FSharpBuildEventsPropPageComClass>.GUID
typeof<FSharpDebugPropPageComClass>.GUID
typeof<FSharpReferencePathsPropPageComClass>.GUID
|] (VSHiveUtilities.getPriorityExtendedPropertyPages())
/// Overriding to provide customization of files on add files.
/// This will replace tokens in the file with actual value (namespace, class name,...)
/// <param name="source">Full path to template file</param>
/// <param name="target">Full path to destination file</param>
override x.AddFileFromTemplate(source:string, target:string ) =
if not (File.Exists(source)) then
raise <| new FileNotFoundException(String.Format(FSharpSR.TemplateNotFound(), source))
// We assume that there is no token inside the file because the only
// way to add a new element should be through the template wizard that
// take care of expanding and replacing the tokens.
// The only task to perform is to copy the source file in the
// target location.
let targetFolder = Path.GetDirectoryName(target)
if not (Directory.Exists(targetFolder)) then
Directory.CreateDirectory(targetFolder) |> ignore
File.Copy(source, target)
static member internal IsCompilingFSharpFile(strFileName:string ) =
if (String.IsNullOrEmpty(strFileName)) then
false
else
// note that .fsx files do not compile in project
(String.Compare(Path.GetExtension(strFileName), ".fs", StringComparison.OrdinalIgnoreCase) = 0)
|| (String.Compare(Path.GetExtension(strFileName), ".fsi", StringComparison.OrdinalIgnoreCase) = 0)
static member internal IsFSharpCodeFileIconwise(strFileName:string ) =
if (String.IsNullOrEmpty(strFileName)) then
false
else
(String.Compare(Path.GetExtension(strFileName), ".fs", StringComparison.OrdinalIgnoreCase) = 0)
static member internal IsFSharpSignatureFileIconwise(strFileName:string ) =
if (String.IsNullOrEmpty(strFileName)) then
false
else
(String.Compare(Path.GetExtension(strFileName), ".fsi", StringComparison.OrdinalIgnoreCase) = 0)
static member internal IsFSharpScriptFileIconwise(strFileName:string ) =
if (String.IsNullOrEmpty(strFileName)) then
false
else
(String.Compare(Path.GetExtension(strFileName), ".fsx", StringComparison.OrdinalIgnoreCase) = 0)
|| (String.Compare(Path.GetExtension(strFileName), ".fsscript", StringComparison.OrdinalIgnoreCase) = 0)
override x.DefaultBuildAction(strFileName:string ) =
// Briefly, we just want out-of-the-box defaults to be like C#, without all their complicated logic, so we just hardcode a few values to be like C# and then otherwise default to NONE
// Compile
if FSharpProjectNode.IsCompilingFSharpFile strFileName then
ProjectFileConstants.Compile
// EmbeddedResource
elif (String.Compare(Path.GetExtension(strFileName), ".resx", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.EmbeddedResource
// Content
elif (String.Compare(Path.GetExtension(strFileName), ".bmp", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".cur", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".ico", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".js", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".txt", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".wsf", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".xml", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".css", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".config", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".map", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Content
elif (String.Compare(Path.GetExtension(strFileName), ".xaml", StringComparison.OrdinalIgnoreCase) = 0) then
ProjectFileConstants.Resource
// None (including .fsx/.fsscript)
else
ProjectFileConstants.None
/// Create a file node based on an msbuild item.
/// <param name="item">The msbuild item to be analyzed</param>
/// <returns>FSharpFileNode</returns>
override x.CreateFileNode(item:ProjectElement, hierarchyId : System.Nullable<uint32>) =
if (item= null) then
raise <| ArgumentNullException("item")
let includ = item.GetMetadata(ProjectFileConstants.Include)
let newNode = new FSharpFileNode(this, item, hierarchyId)
newNode.OleServiceProvider.AddService(typeof<EnvDTE.Project>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
newNode.OleServiceProvider.AddService(typeof<EnvDTE.ProjectItem>, newNode.ServiceCreator, false)
newNode.OleServiceProvider.AddService(typeof<VSLangProj.VSProject>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
if (FSharpProjectNode.IsCompilingFSharpFile(includ)) then
newNode.OleServiceProvider.AddService(typeof<SVSMDCodeDomProvider>, new OleServiceProvider.ServiceCreatorCallback(this.CreateServices), false)
(newNode :> LinkedFileNode)
/// Creates the format list for the open file dialog
/// <param name="formatlist">The formatlist to return</param>
override x.GetFormatList(formatlist:byref<string> ) =
// see docs for IPersistFileFormat.GetFormatList for correct format of this string
formatlist <- sprintf "%s\n*.fsproj\n" (FSharpSR.ProjectFileExtensionFilter())
VSConstants.S_OK
member this.IsCurrentProjectDotNetPortable() = this.CheckProjectFrameworkIdentifier(".NETPortable")
member this.IsCurrentProjectSilverlight() = this.CheckProjectFrameworkIdentifier("Silverlight")
interface IVsFilterAddProjectItemDlg with
member filter.FilterListItemByLocalizedName(_rguidProjectItemTemplates, _pszLocalizedName, _pfFilter) =
VSConstants.S_OK
member filter.FilterListItemByTemplateFile(_rguidProjectItemTemplates, pszLocalizedName, pfFilter) =
pfFilter <- if (this.IsCurrentProjectDotNetPortable() || this.IsCurrentProjectSilverlight()) && pszLocalizedName.Contains(@"\FSharp\FSharpData\") then 1 else 0
VSConstants.S_OK
member filter.FilterTreeItemByLocalizedName(_rguidProjectItemTemplates, _pszLocalizedName, _pfFilter) =
VSConstants.S_OK
member filter.FilterTreeItemByTemplateDir(_rguidProjectItemTemplates, pszTemplateDir, pfFilter) =
pfFilter <- if (this.IsCurrentProjectDotNetPortable() || this.IsCurrentProjectSilverlight()) && pszTemplateDir = @"FSharp\FSharpData" then 1 else 0
VSConstants.S_OK
/// This overrides the base class method to show the VS 2005 style Add reference dialog. The ProjectNode implementation
/// shows the VS 2003 style Add Reference dialog.
override self.AddProjectReference() =
//Add the .NET page
// To properly filter out references, we need to get the target framework moniker
// and then get the right set of directories for the varTabInitInfo field.
// The native project equivalent of this code is in vsproject\langproj\langrefnode.cpp.
let stripEndingSemicolon (sb : StringBuilder) =
let len = sb.Length
if len > 0 && sb.[len - 1] = ';' then sb.Remove(len - 1, 1) |> ignore
()
let targetFrameworkMoniker = this.GetTargetFrameworkMoniker()
let enumComponents = this.Site.GetService(typeof<SCompEnumService>) :?> IVsComponentEnumeratorFactory4
let (hr,componentEnumerator) = enumComponents.GetReferencePathsForTargetFramework(targetFrameworkMoniker)
let paths = new StringBuilder(1024)
if hr = VSConstants.S_OK then
let mutable selData = Array.zeroCreate<VSCOMPONENTSELECTORDATA> 1
let mutable fetched = 0u
while componentEnumerator.Next(1u, selData, &fetched) = VSConstants.S_OK && fetched = 1u do
let _ = paths.Append(selData.[0].bstrFile + ";")
()
stripEndingSemicolon paths
let dialogTitle =
let text = FSharpSR.AddReferenceDialogTitle_Dev11()
String.Format(text, self.VSProject.Project.Name)
let referenceContainerNode = this.GetReferenceContainer() :?> ReferenceContainerNode
let componentDialog = this.Site.GetService(typeof<SVsReferenceManager>) :?> IVsReferenceManager
let providers() = [|
// assembly references
let c =
let c = componentDialog.CreateProviderContext(VSConstants.AssemblyReferenceProvider_Guid)
let assemblyReferenceProviderContext = c :?> IVsAssemblyReferenceProviderContext
assemblyReferenceProviderContext.TargetFrameworkMoniker <- targetFrameworkMoniker
assemblyReferenceProviderContext.SupportsRetargeting <- true
assemblyReferenceProviderContext.AssemblySearchPaths <- this.GetProjectProperty("AssemblySearchPaths")
for r in referenceContainerNode.EnumReferences() do
match r with
| :? AssemblyReferenceNode as arn ->
let newRef = assemblyReferenceProviderContext.CreateReference() :?> IVsAssemblyReference
assemblyReferenceProviderContext.AddReference(newRef)
newRef.Name <- arn.SimpleName
newRef.FullPath <- arn.Url
| _ -> ()
let existingFilter =
match assemblyReferenceProviderContext.ReferenceFilterPaths with
| null -> ResizeArray()
| x -> ResizeArray(x :?> string[])
if self.IsCurrentProjectDotNetPortable() then
// for portable projects AddReference dialog should be adjusted
// taken from vsproject\flavors\portable\package\microsoft.visualstudio.portablelibrary\microsoft\visualstudio\portablelibrary\projectflavoring\referencing\providers\assemblyreferenceprovidercontextprovider.cs
// MSDN: Gets or sets whether the assembly is referenced implicitly
assemblyReferenceProviderContext.IsImplicitlyReferenced <- false
// MSDN: Gets or sets the message to display during retargeting.
assemblyReferenceProviderContext.RetargetingMessage <- FSharpSR.AddReferenceAssemblyPageDialogRetargetingText()
// MSDN: Sets the custom no items message for the specified tab.
assemblyReferenceProviderContext.SetNoItemsMessageForTab(uint32 __VSASSEMBLYPROVIDERTAB.TAB_ASSEMBLY_FRAMEWORK, FSharpSR.AddReferenceAssemblyPageDialogNoItemsText())
// we support only fixed set of portable profiles thus retargeting is prohibited
assemblyReferenceProviderContext.SupportsRetargeting <- false
if self.ImplicitlyExpandTargetFramework then
// since all framework references are included implicitly we should hide them from the Framework page to disallow adding them one more time
// to do this we'll obtain assembly location for the current framework and add it to IVsAssemblyReferenceProviderContext.ReferenceFilterPaths
let multiTargetingService = this.GetService(typeof<SVsFrameworkMultiTargeting>) :?> IVsFrameworkMultiTargeting
let frameworkName = self.GetCurrentFrameworkName()
let mutable frameworkAssemblies = Unchecked.defaultof<_>
multiTargetingService.GetFrameworkAssemblies(frameworkName.FullName, uint32 __VSFRAMEWORKASSEMBLYTYPE.VSFRAMEWORKASSEMBLYTYPE_FRAMEWORK, &frameworkAssemblies)
|> (ErrorHandler.ThrowOnFailure >> ignore)
if frameworkAssemblies.Length <> 0 then
let path = Path.GetDirectoryName (frameworkAssemblies.GetValue(0) :?> string) // all assemblies in the profile are located in the same place - just pick the first one
existingFilter.Add(path)