forked from DynamoDS/Dynamo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathManager.cs
More file actions
1090 lines (932 loc) · 42.6 KB
/
Copy pathPathManager.cs
File metadata and controls
1090 lines (932 loc) · 42.6 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml;
using Dynamo.Configuration;
using Dynamo.Graph.Workspaces;
using Dynamo.Interfaces;
using Dynamo.Properties;
using DynamoUtilities;
using Dynamo.Models;
namespace Dynamo.Core
{
struct PathManagerParams
{
/// <summary>
/// Major version number to be used to form various data file paths.
/// If both this and MinorFileVersion are 0, then version information
/// is retrieved from DynamoCore.dll.
/// </summary>
internal int MajorFileVersion { get; set; }
/// <summary>
/// Minor version number to be used to form various data file paths.
/// If both this and MajorFileVersion are 0, then version information
/// is retrieved from DynamoCore.dll.
/// </summary>
internal int MinorFileVersion { get;set; }
/// <summary>
/// The full path of the directory that contains DynamoCore.dll.
/// </summary>
internal string CorePath { get; set; }
/// <summary>
/// The full path of the host application such as DynamoRevit or DynamoStudio
/// </summary>
internal string HostPath { get; set; }
/// <summary>
/// Reference of an IPathResolver object that supplies
/// additional path information. This argument is optional.
/// </summary>
internal IPathResolver PathResolver { get; set; }
}
internal class PathManager : IPathManager
{
private static Lazy<PathManager> lazy;
private static readonly object lockObject = new object();
/// <summary>
/// Initialize the PathManager singleton passing as a parameter a PathManagerParams object (which contains the Major and Minor version values).
/// </summary>
/// <param name="parameters"></param>
public static void Initialize(PathManagerParams parameters)
{
lock (lockObject)
{
//If is already initialized then do nothing
if (lazy == null)
{
lazy = new Lazy<PathManager>(() => new PathManager(parameters));
}
}
}
/// <summary>
/// Instance is the property used as an access point to the PathManager singleton (if is not created will be created with default parameters).
/// </summary>
public static PathManager Instance
{
get
{
if (lazy == null)
{
lock (lockObject)
{
if (lazy == null)
{
// Fallback to default if not initialized
lazy = new Lazy<PathManager>(() => new PathManager(new PathManagerParams()));
}
}
}
return lazy.Value;
}
}
#region Class Private Data Members
public const string PackagesDirectoryName = "packages";
public const string LogsDirectoryName = "Logs";
public const string NodesDirectoryName = "nodes";
public const string ExtensionsDirectoryName = "extensions";
public const string ViewExtensionsDirectoryName = "viewExtensions";
public const string DefinitionsDirectoryName = "definitions";
public const string BackupDirectoryName = "backup";
public const string PreferenceSettingsFileName = "DynamoSettings.xml";
public const string PythonTemplateFileName = "PythonTemplate.py";
private readonly int majorFileVersion;
private readonly int minorFileVersion;
private Updates.BinaryVersion productVersion;
private readonly string dynamoCoreDir;
private string hostApplicationDirectory;
private string userDataDir;
private string commonDataDir;
private string logDirectory;
private string samplesDirectory;
private string templatesDirectory;
private string defaultTemplatesDirectory;
private string backupDirectory;
private string defaultBackupDirectory;
private string preferenceFilePath;
private string pythonTemplateFilePath;
private List<string> rootDirectories;
private HashSet<string> nodeDirectories;
private HashSet<string> additionalResolutionPaths;
private HashSet<string> preloadedLibraries;
private readonly HashSet<string> extensionsDirectories;
private readonly HashSet<string> viewExtensionsDirectories;
private IPathResolver pathResolver;
#endregion
internal IPreferences Preferences { get; set; }
/// <summary>
/// PathResolver is used to resolve paths for custom nodes, packages, and preloaded libraries.
/// </summary>
public IPathResolver PathResolver
{
get { return pathResolver; }
}
private IEnumerable<string> RootDirectories
{
get
{
return Preferences != null ?
Preferences.CustomPackageFolders.Select(path => path == DynamoModel.BuiltInPackagesToken ? BuiltinPackagesDirectory : path)
: rootDirectories;
}
}
private const string builtinPackagesDirName = @"Built-In Packages";
private static string builtinPackagesDirectory = null;
//Todo in Dynamo 3.0, Add this to the IPathManager interface
/// <summary>
/// The Built-In Packages directory is located in the same directory as the DynamoCore.dll
/// Property should only be set during testing. During testing, keep in mind that previous tests
/// may have altered this static property, and it may need to be restored.
/// </summary>
internal static string BuiltinPackagesDirectory
{
get
{
if (builtinPackagesDirectory == null)
{
builtinPackagesDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof(PathManager)).Location), builtinPackagesDirName, @"Packages");
}
return builtinPackagesDirectory;
}
set
{
if (builtinPackagesDirectory != value)
{
builtinPackagesDirectory = value;
}
}
}
#region IPathManager Interface Implementation
public string DynamoCoreDirectory
{
get { return dynamoCoreDir; }
}
public string HostApplicationDirectory
{
get { return hostApplicationDirectory; }
}
public string UserDataDirectory
{
get { return userDataDir; }
}
public string CommonDataDirectory
{
get { return commonDataDir; }
}
public string DefaultUserDefinitions
{
get
{
if (Preferences is PreferenceSettings preferences)
{
return TransformPath(preferences.SelectedPackagePathForInstall, DefinitionsDirectoryName);
}
return TransformPath(RootDirectories.First(), DefinitionsDirectoryName);
}
}
public IEnumerable<string> DefinitionDirectories
{
get
{
var definitionDirectories = RootDirectories.Select(path => TransformPath(path, DefinitionsDirectoryName)).ToList();
var commonDefinitionsDirectory = Path.Combine(commonDataDir, DefinitionsDirectoryName);
if (Directory.Exists(commonDefinitionsDirectory) &&
!definitionDirectories.Contains(commonDefinitionsDirectory, StringComparer.OrdinalIgnoreCase))
{
definitionDirectories.Add(commonDefinitionsDirectory);
}
else if (!Directory.Exists(commonDefinitionsDirectory))
{
// Diagnostic only: log the missing shared definitions folder so the omission
// is visible. Does not change the returned directories.
Trace.TraceWarning("Expected shared definitions folder not found at: " + commonDefinitionsDirectory);
}
return definitionDirectories;
}
}
[Obsolete("This property will be removed in a future version of Dynamo.", false)]
public string CommonDefinitions
{
get { return string.Empty; }
}
public string LogDirectory
{
get { return logDirectory; }
}
/// <summary>
/// The enum will contain the possible values for Preference Item
/// </summary>
public enum PreferenceItem
{
Backup,
Templates,
Samples
}
/// <summary>
/// Default directory where new packages are downloaded to.
/// This directory path is user configurable and if set to something other than the default,
/// the currently selected path can be obtained from preference settings.
/// </summary>
public string DefaultPackagesDirectory
{
get
{
if (Preferences is PreferenceSettings preferences)
{
return TransformPath(preferences.SelectedPackagePathForInstall, PackagesDirectoryName);
}
return TransformPath(RootDirectories.First(), PackagesDirectoryName);
}
}
public IEnumerable<string> PackagesDirectories
{
get { return RootDirectories.Select(path => TransformPath(path, PackagesDirectoryName)); }
}
public IEnumerable<string> ExtensionsDirectories
{
get { return extensionsDirectories; }
}
public IEnumerable<string> ViewExtensionsDirectories
{
get { return viewExtensionsDirectories; }
}
public string SamplesDirectory
{
get
{
if (samplesDirectory == null)
{
var preferences = Preferences as PreferenceSettings;
var locale = preferences?.Locale ?? CultureInfo.CurrentUICulture.Name;
if (string.Equals(locale, "Default", StringComparison.OrdinalIgnoreCase))
{
// When locale is "Default", resolve from process cultures in priority order:
// 1. DefaultThreadCurrentCulture (explicitly set by host/application)
// 2. CurrentUICulture (current thread's UI culture)
// 3. FallbackUiCulture (Dynamo's default: "en-US")
var effectiveCulture = CultureInfo.DefaultThreadCurrentCulture
?? CultureInfo.CurrentUICulture
?? new CultureInfo(Configurations.FallbackUiCulture);
locale = effectiveCulture.Name;
}
samplesDirectory = GetSamplesFolder(commonDataDir, locale);
}
return samplesDirectory;
}
}
/// <summary>
/// Dynamo Templates folder
/// </summary>
public string TemplatesDirectory
{
get { return templatesDirectory; }
}
/// <summary>
/// Default templates directory, it is used when the user resets the custom template path
/// </summary>
public string DefaultTemplatesDirectory
{
get { return defaultTemplatesDirectory; }
}
public string BackupDirectory
{
get { return backupDirectory; }
}
public string DefaultBackupDirectory
{
get { return defaultBackupDirectory; }
}
public string PreferenceFilePath
{
get { return preferenceFilePath; }
}
public string PythonTemplateFilePath
{
get { return pythonTemplateFilePath; }
}
public IEnumerable<string> NodeDirectories
{
get { return nodeDirectories; }
}
public IEnumerable<string> PreloadedLibraries
{
get { return preloadedLibraries; }
}
public int MajorFileVersion
{
get { return majorFileVersion; }
}
public int MinorFileVersion
{
get { return minorFileVersion; }
}
/// <summary>
/// This function indicates if there is an already assigned Path Resolver , otherwise it will take from the ctor config
/// </summary>
public bool HasPathResolver
{
get { return pathResolver != null; }
}
public void AddResolutionPath(string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException("path");
if (!additionalResolutionPaths.Contains(path))
{
if (!Directory.Exists(path))
{
throw new Exception(String.Format(Resources.DirectoryNotFound, path));
}
additionalResolutionPaths.Add(path);
}
}
/// <summary>
/// Given an initial file path with the file name, resolve the full path
/// to the target file. The search happens in the following order:
///
/// 1. If the provided file path is valid and points to an existing file,
/// the file path is return as-is.
/// 2. The file is searched alongside DynamoCore.dll for a match.
/// 3. The file is searched within AdditionalResolutionPaths.
/// 4. The search is left to system path resolution.
///
/// </summary>
/// <param name="library">The initial library file path.</param>
/// <returns>Returns true if the requested file can be located, or false
/// otherwise.</returns>
///
public bool ResolveLibraryPath(ref string library)
{
if (PathHelper.IsValidPath(library)) // Absolute path, we're done here.
return true;
library = LibrarySearchPaths(library).FirstOrDefault(PathHelper.IsValidPath);
return library != default(string);
}
public bool ResolveDocumentPath(ref string document)
{
if (string.IsNullOrEmpty(document))
{
throw new ArgumentNullException("document");
}
try
{
document = Path.GetFullPath(document);
if (PathHelper.IsValidPath(document)) // "document" is already an absolute path.
return true;
// Restore "document" back to just its file name first...
document = Path.GetFileName(document);
// Search alongside the main assembly location...
var executingAssemblyPathName = Assembly.GetExecutingAssembly().Location;
var rootModuleDirectory = Path.GetDirectoryName(executingAssemblyPathName);
document = Path.Combine(rootModuleDirectory, document);
return PathHelper.IsValidPath(document);
}
catch
{
return false;
}
}
#endregion
#region Public Class Operational Methods
/// <summary>
/// Assigns a hostPath and IPathResolver on demand with the same behavior as the Ctor.
/// </summary>
/// <param name="hostPath"></param>
/// /// <param name="resolver"></param>
internal void AssignHostPathAndIPathResolver(string hostPath, IPathResolver resolver)
{
pathResolver = resolver;
BuildHostDirectories(hostPath);
BuildUserSpecificDirectories();
BuildCommonDirectories();
LoadPathsFromResolver();
}
/// <summary>
/// Constructs an instance of PathManager object.
/// </summary>
/// <param name="pathManagerParams">Parameters to configure the new
/// instance of PathManager. See PathManagerParams for details of each
/// field.</param>
///
internal PathManager(PathManagerParams pathManagerParams)
{
var corePath = pathManagerParams.CorePath;
pathResolver = pathManagerParams.PathResolver;
if (string.IsNullOrEmpty(corePath) || !Directory.Exists(corePath))
{
// If the caller does not provide an alternative core path,
// use the default folder in which DynamoCore.dll resides.
var dynamoCorePath = Assembly.GetExecutingAssembly().Location;
corePath = Path.GetDirectoryName(dynamoCorePath);
}
dynamoCoreDir = corePath;
extensionsDirectories = new HashSet<string>();
viewExtensionsDirectories = new HashSet<string>();
extensionsDirectories.Add(Path.Combine(dynamoCoreDir, ExtensionsDirectoryName));
viewExtensionsDirectories.Add(Path.Combine(dynamoCoreDir, ViewExtensionsDirectoryName));
BuildHostDirectories(pathManagerParams.HostPath);
// If both major/minor versions are zero, get from assembly.
majorFileVersion = pathManagerParams.MajorFileVersion;
minorFileVersion = pathManagerParams.MinorFileVersion;
if (majorFileVersion == 0 && (minorFileVersion == 0))
{
var assemblyPath = TraverseForExecutableAssembly();
var v = FileVersionInfo.GetVersionInfo(assemblyPath);
majorFileVersion = v.FileMajorPart;
minorFileVersion = v.FileMinorPart;
}
BuildUserSpecificDirectories();
BuildCommonDirectories();
LoadPathsFromResolver();
}
/// <summary>
/// Resolves the assembly path used for data-folder version discovery.
///
/// Starting from Dynamo 4.0, data folders are no longer versioned from
/// DynamoCore.dll by default. Instead, the version is derived from a selected
/// host-facing assembly file version.
///
/// Resolution order:
/// 1) First assembly on the current managed call stack under hostApplicationDirectory.
/// 2) If a host directory is configured, first non-system, non-test assembly on
/// the current managed call stack that resides outside the DynamoCore directory.
/// Skipped when no host directory is set (e.g. standalone Sandbox).
/// 3) If no host directory is configured, first non-system, non-test assembly
/// on the current managed call stack that resides outside the DynamoCore directory.
/// 4) DynamoCore assembly location (preferred over external process assemblies).
/// 5) Entry assembly location.
/// 6) Current process main module path.
/// </summary>
/// <returns>
/// The file path of the assembly used to determine the data directory version.
/// </returns>
private string TraverseForExecutableAssembly()
{
// Option 1: Prefer an assembly discovered on the current call stack that
// physically resides under the host application directory.
if (TryGetAssemblyPathFromHostDirectory(out var hostAssemblyPath))
return hostAssemblyPath;
// Option 2: Use the first non-system, non-test assembly on the current
// managed call stack that resides outside the DynamoCore directory.
// Only attempt this when a host directory is configured, as a fallback
// for integrations where Option 1 didn't match (e.g. host directory
// assigned but no matching assembly on the stack yet). For standalone
// Sandbox there is no host, and the stack walk may pick up unrelated
// assemblies (e.g. .NET runtime) with misleading version numbers.
if (!string.IsNullOrEmpty(hostApplicationDirectory))
{
var currentAssembly = typeof(PathManager).Assembly;
var stackTrace = new StackTrace(skipFrames: 1, fNeedFileInfo: false);
foreach (var frame in stackTrace.GetFrames() ?? Array.Empty<StackFrame>())
{
var assembly = frame.GetMethod()?.DeclaringType?.Assembly;
if (assembly == null || assembly == currentAssembly || assembly.IsDynamic)
continue;
var assemblyName = assembly.GetName().Name;
if (string.IsNullOrEmpty(assemblyName))
continue;
if (assemblyName.StartsWith("System", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase) ||
assemblyName.Equals("mscorlib", StringComparison.OrdinalIgnoreCase) ||
assemblyName.Equals("netstandard", StringComparison.OrdinalIgnoreCase) ||
assemblyName.IndexOf("test", StringComparison.OrdinalIgnoreCase) >= 0)
{
continue;
}
var candidatePath = assembly.Location;
// Skip assemblies that live in the same directory as DynamoCore.
// Host assemblies (e.g. Civil3D, Revit) reside in their own install
// directories; anything co-located with DynamoCore (e.g. nunit.framework)
// is not a host and may carry an unrelated version.
if (IsPathUnderDirectory(candidatePath, dynamoCoreDir))
continue;
if (HasNonZeroFileVersion(candidatePath))
return candidatePath;
}
}
// Option 3: When there is no configured host directory yet, still try
// to discover a likely host integration assembly on the current call stack.
if (string.IsNullOrEmpty(hostApplicationDirectory))
{
var currentAssembly = typeof(PathManager).Assembly;
var stackTrace = new StackTrace(skipFrames: 1, fNeedFileInfo: false);
foreach (var frame in stackTrace.GetFrames() ?? Array.Empty<StackFrame>())
{
var assembly = frame.GetMethod()?.DeclaringType?.Assembly;
if (assembly == null || assembly == currentAssembly || assembly.IsDynamic)
continue;
var assemblyName = assembly.GetName().Name;
if (string.IsNullOrEmpty(assemblyName))
continue;
if (assemblyName.StartsWith("System", StringComparison.OrdinalIgnoreCase) ||
assemblyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase) ||
assemblyName.Equals("mscorlib", StringComparison.OrdinalIgnoreCase) ||
assemblyName.Equals("netstandard", StringComparison.OrdinalIgnoreCase) ||
assemblyName.IndexOf("test", StringComparison.OrdinalIgnoreCase) >= 0)
{
continue;
}
// Without a configured host directory, only consider likely
// Dynamo integration assemblies to avoid selecting framework
// assemblies (e.g. WPF/.NET) that can carry unrelated versions
// such as 10.0 for Sandbox startup.
if (assemblyName.IndexOf("Dynamo", StringComparison.OrdinalIgnoreCase) < 0)
continue;
var candidatePath = assembly.Location;
// Skip assemblies that live in the same directory as DynamoCore.
if (IsPathUnderDirectory(candidatePath, dynamoCoreDir))
continue;
if (HasNonZeroFileVersion(candidatePath))
return candidatePath;
}
}
// Option 4: Prefer DynamoCore assembly over external process assemblies
// (e.g. testhost.exe, dotnet.exe) which may carry unrelated versions.
var dynamoCoreAssemblyPath = Assembly.GetExecutingAssembly().Location;
if (HasNonZeroFileVersion(dynamoCoreAssemblyPath))
return dynamoCoreAssemblyPath;
// Option 5: Use the process entry assembly when available and versioned.
var entryAssemblyPath = Assembly.GetEntryAssembly()?.Location;
if (HasNonZeroFileVersion(entryAssemblyPath))
return entryAssemblyPath;
// Option 6: Use the current process main module path as a hosted fallback.
var processMainModulePath = TryGetCurrentProcessMainModulePath();
if (HasNonZeroFileVersion(processMainModulePath))
return processMainModulePath;
if (PathHelper.IsValidPath(dynamoCoreAssemblyPath))
return dynamoCoreAssemblyPath;
if (PathHelper.IsValidPath(entryAssemblyPath))
return entryAssemblyPath;
if (PathHelper.IsValidPath(processMainModulePath))
return processMainModulePath;
// Final fallback (should not be reached).
return dynamoCoreAssemblyPath;
}
private bool TryGetAssemblyPathFromHostDirectory(out string hostAssemblyPath)
{
hostAssemblyPath = null;
if (!PathHelper.IsValidPath(hostApplicationDirectory))
return false;
var currentAssembly = typeof(PathManager).Assembly;
var stackTrace = new StackTrace(skipFrames: 1, fNeedFileInfo: false);
foreach (var frame in stackTrace.GetFrames() ?? Array.Empty<StackFrame>())
{
var assembly = frame.GetMethod()?.DeclaringType?.Assembly;
if (assembly == null || assembly == currentAssembly || assembly.IsDynamic)
continue;
var candidatePath = assembly.Location;
if (IsPathUnderDirectory(candidatePath, hostApplicationDirectory) &&
HasNonZeroFileVersion(candidatePath))
{
hostAssemblyPath = candidatePath;
return true;
}
}
return false;
}
private static bool HasNonZeroFileVersion(string candidatePath)
{
if (!PathHelper.IsValidPath(candidatePath))
return false;
var fileVersion = FileVersionInfo.GetVersionInfo(candidatePath);
return fileVersion.FileMajorPart > 0 || fileVersion.FileMinorPart > 0;
}
private static string TryGetCurrentProcessMainModulePath()
{
try
{
return Process.GetCurrentProcess().MainModule?.FileName;
}
catch (Exception)
{
return null;
}
}
private static bool IsPathUnderDirectory(string candidatePath, string directoryPath)
{
if (string.IsNullOrEmpty(candidatePath) || string.IsNullOrEmpty(directoryPath))
return false;
if (!File.Exists(candidatePath) && !Directory.Exists(candidatePath))
return false;
if (!Directory.Exists(directoryPath))
return false;
var fullCandidatePath = Path.GetFullPath(candidatePath);
var fullDirectoryPath = Path.GetFullPath(directoryPath);
if (!fullDirectoryPath.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
fullDirectoryPath += Path.DirectorySeparatorChar;
return fullCandidatePath.StartsWith(fullDirectoryPath, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Call this method to force PathManager to create folders that it
/// is referring to. This method call throws exception if any creation
/// fails.
/// </summary>
/// <param name="exceptions">The output list of exception, if any of
/// the target directories cannot be created during this call.</param>
internal void EnsureDirectoryExistence(List<Exception> exceptions)
{
if (!RootDirectories.Any())
{
throw new InvalidOperationException(
"At least one custom package directory must be specified");
}
if (exceptions == null)
throw new ArgumentNullException("exceptions");
exceptions.Clear();
// User specific data folders.
exceptions.Add(PathHelper.CreateFolderIfNotExist(userDataDir));
exceptions.Add(PathHelper.CreateFolderIfNotExist(DefaultUserDefinitions));
exceptions.Add(PathHelper.CreateFolderIfNotExist(logDirectory));
exceptions.Add(PathHelper.CreateFolderIfNotExist(DefaultPackagesDirectory));
exceptions.Add(PathHelper.CreateFolderIfNotExist(backupDirectory));
exceptions.Add(PathHelper.CreateFolderIfNotExist(DefaultTemplatesDirectory));
// Common data folders for all users.
exceptions.Add(PathHelper.CreateFolderIfNotExist(commonDataDir));
exceptions.RemoveAll(x => x == null); // Remove all null entries.
}
internal bool UpdatePreferenceItemPath(PreferenceItem item, string newLocation)
{
bool isValidFolder = PathHelper.CreateFolderIfNotExist(newLocation) == null;
if (!isValidFolder)
return false;
switch (item)
{
case PreferenceItem.Backup:
backupDirectory = newLocation;
break;
case PreferenceItem.Templates:
templatesDirectory = newLocation;
break;
}
return true;
}
/// <summary>
/// Returns the backup file path for a workspace
/// </summary>
/// <param name="workspace"></param>
/// <returns></returns>
internal string GetBackupFilePath(WorkspaceModel workspace)
{
string fileName;
if (string.IsNullOrEmpty(workspace.FileName))
{
if (workspace is HomeWorkspaceModel)
{
fileName = Configurations.BackupFileNamePrefix + ".DYN";
}
else
{
fileName = workspace.Name + ".DYF";
}
}
else
{
fileName = Path.GetFileName(workspace.FileName);
}
return Path.Combine(BackupDirectory, fileName);
}
/// <summary>
/// Backup the XML file.
/// </summary>
/// <param name="xmlDoc">The XML document.</param>
/// <param name="filePath">The file path.</param>
/// <returns></returns>
internal bool BackupXMLFile(XmlDocument xmlDoc, string filePath)
{
try
{
var fileName = Path.GetFileNameWithoutExtension(filePath) + "_xml";
var extension = Path.GetExtension(filePath);
var savePath = Path.Combine(this.BackupDirectory, fileName + extension);
xmlDoc.Save(savePath);
return true;
}
catch (Exception)
{
return false;
}
}
#endregion
#region Private Class Helper Methods
/// <summary>
/// Build the Extensions and ViewExtensions directories based on the Host.
/// </summary>
/// <param name="hostPath"></param>
private void BuildHostDirectories(string hostPath)
{
hostApplicationDirectory = hostPath;
if (!string.IsNullOrEmpty(hostApplicationDirectory))
{
extensionsDirectories.Add(Path.Combine(hostApplicationDirectory, ExtensionsDirectoryName));
viewExtensionsDirectories.Add(Path.Combine(hostApplicationDirectory, ViewExtensionsDirectoryName));
}
}
/// <summary>
/// Build directories based on the User.
/// </summary>
private void BuildUserSpecificDirectories()
{
// Current user specific directories.
userDataDir = GetUserDataFolder();
// When running as a headless process, put the logs directory in a consistent
// location that doesn't change every time the version number changes.
var userDataDirNoVersion = Directory.GetParent(userDataDir).FullName;
logDirectory = Path.Combine(Dynamo.Models.DynamoModel.IsHeadless ? userDataDirNoVersion : userDataDir,
LogsDirectoryName);
preferenceFilePath = Path.Combine(userDataDir, PreferenceSettingsFileName);
pythonTemplateFilePath = Path.Combine(userDataDir, PythonTemplateFileName);
backupDirectory = Path.Combine(userDataDirNoVersion, BackupDirectoryName);
defaultBackupDirectory = backupDirectory;
}
/// <summary>
/// Build common Directories.
/// </summary>
private void BuildCommonDirectories()
{
// Common directories.
commonDataDir = GetCommonDataFolder();
defaultTemplatesDirectory = GetTemplateFolder(commonDataDir);
rootDirectories = new List<string> { userDataDir };
nodeDirectories = new HashSet<string>
{
Path.Combine(dynamoCoreDir, NodesDirectoryName)
};
preloadedLibraries = new HashSet<string>();
additionalResolutionPaths = new HashSet<string>();
}
/// <summary>
/// Load the Paths based on the Resolver
/// </summary>
/// <exception cref="DirectoryNotFoundException"></exception>
private void LoadPathsFromResolver()
{
if (pathResolver == null) // No optional path resolver is specified...
return;
foreach (var directory in pathResolver.AdditionalNodeDirectories)
{
if (!Directory.Exists(directory))
throw new DirectoryNotFoundException(directory);
if (!nodeDirectories.Contains(directory))
nodeDirectories.Add(directory);
}
foreach (var directory in pathResolver.AdditionalResolutionPaths)
{
if (!Directory.Exists(directory))
throw new DirectoryNotFoundException(directory);
if (!additionalResolutionPaths.Contains(directory))
additionalResolutionPaths.Add(directory);
}
foreach (var path in pathResolver.PreloadedLibraryPaths)
{
if (!preloadedLibraries.Contains(path))
preloadedLibraries.Add(path);
}
}
internal string GetUserDataFolder()
{
if (pathResolver != null && !string.IsNullOrEmpty(pathResolver.UserDataRootFolder))
return GetDynamoDataFolder(pathResolver.UserDataRootFolder);
if (!string.IsNullOrEmpty(userDataDir))
return userDataDir; //Return the cached userDataDir if we have one.
var folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
return GetDynamoDataFolder(Path.Combine(folder, Configurations.DynamoAsString, "Dynamo Core"));
}
/// <summary>
/// Returns the current Dynamo product version.
/// </summary>
/// <returns></returns>
public Updates.BinaryVersion GetProductVersion()
{
if (null != productVersion) return productVersion;
var executingAssemblyName = Assembly.GetExecutingAssembly().GetName();
productVersion = Updates.BinaryVersion.FromString(executingAssemblyName.Version.ToString());
return productVersion;
}
private string GetCommonDataFolder()
{
//This piece of code is only executed if we are running a host like Revit or Civil3D due that pathResolver is not null
if (pathResolver != null && !string.IsNullOrEmpty(pathResolver.CommonDataRootFolder))
return GetDynamoDataFolder(pathResolver.CommonDataRootFolder);
//This piece of code is only executed if we are running DynamoSandbox
return DynamoCoreDirectory;
}
private string GetDynamoDataFolder(string folder)
{
return Path.Combine(folder,
String.Format("{0}.{1}", majorFileVersion, minorFileVersion));
}
// This method is used to get the locations of packages folder or custom
// nodes folder given the root path. This is necessary because the packages
// may be in the root folder or in a packages subfolder of the root folder.
private string TransformPath(string root, string extension)
{
if (root.StartsWith(GetUserDataFolder()))
return Path.Combine(root, extension);
try
{
var subFolder = Path.Combine(root, extension);
if (Directory.Exists(subFolder))
return subFolder;
}
catch (IOException) { }
catch (ArgumentException) { }
catch (UnauthorizedAccessException) { }
return root;
}
private static string GetSamplesFolder(string dataRootDirectory, string locale)
{
var versionedDirectory = dataRootDirectory;
if (!Directory.Exists(versionedDirectory))
{
// Try to see if folder "%ProgramData%\{...}\{major}.{minor}" exists, if it
// does not, then root directory would be "%ProgramData%\{...}".
//
dataRootDirectory = Directory.GetParent(versionedDirectory).FullName;
}
else if (!Directory.Exists(Path.Combine(versionedDirectory, Configurations.SamplesAsString)))
{
// If the folder "%ProgramData%\{...}\{major}.{minor}" exists, then try to see
// if the folder "%ProgramData%\{...}\{major}.{minor}\samples" exists. If it
// doesn't exist, then root directory would be "%ProgramData%\{...}".
//
dataRootDirectory = Directory.GetParent(versionedDirectory).FullName;
}