diff --git a/src/DynamoCore/Models/DynamoModel.cs b/src/DynamoCore/Models/DynamoModel.cs index 05e5b4721e3..23b0fc842a0 100644 --- a/src/DynamoCore/Models/DynamoModel.cs +++ b/src/DynamoCore/Models/DynamoModel.cs @@ -135,7 +135,7 @@ public partial class DynamoModel : IDynamoModel, IDisposable, IEngineControllerM private readonly PathManager pathManager; private WorkspaceModel currentWorkspace; private Timer backupFilesTimer; - private Dictionary backupFilesDict = new Dictionary(); + private Dictionary backupFilesDict = new(); internal readonly Stopwatch stopwatch = Stopwatch.StartNew(); /// @@ -385,7 +385,7 @@ public ConnectorType ConnectorType /// /// The private collection of visible workspaces in Dynamo /// - private readonly List _workspaces = new List(); + private readonly List _workspaces = new(); /// /// Returns collection of visible workspaces in Dynamo @@ -686,7 +686,7 @@ protected DynamoModel(IStartConfiguration config) pathManager = CreatePathManager(config); // Ensure we have all directories in place. - var exceptions = new List(); + List exceptions = []; pathManager.EnsureDirectoryExistence(exceptions); Context = config.Context; @@ -830,7 +830,7 @@ protected DynamoModel(IStartConfiguration config) // is no additional location specified. Otherwise, update pathManager.PackageDirectories to include // PackageFolders if (PreferenceSettings.CustomPackageFolders.Count == 0) - PreferenceSettings.CustomPackageFolders = new List { BuiltInPackagesToken, pathManager.UserDataDirectory }; + PreferenceSettings.CustomPackageFolders = [BuiltInPackagesToken, pathManager.UserDataDirectory]; if (!PreferenceSettings.CustomPackageFolders.Contains(BuiltInPackagesToken)) { @@ -865,7 +865,7 @@ protected DynamoModel(IStartConfiguration config) if (!string.IsNullOrEmpty(templatePath) && File.Exists(templatePath)) { PreferenceSettings.PythonTemplateFilePath = templatePath; - Logger.Log(Resources.PythonTemplateDefinedByHost + " : " + PreferenceSettings.PythonTemplateFilePath); + Logger.Log($"{Resources.PythonTemplateDefinedByHost} : {PreferenceSettings.PythonTemplateFilePath}"); } // Otherwise fallback to the default @@ -885,7 +885,7 @@ protected DynamoModel(IStartConfiguration config) else { // A custom python template path already exists in the DynamoSettings.xml - Logger.Log(Resources.PythonTemplateUserFile + " : " + PreferenceSettings.PythonTemplateFilePath); + Logger.Log($"{Resources.PythonTemplateUserFile} : {PreferenceSettings.PythonTemplateFilePath}"); } pathManager.Preferences = PreferenceSettings; PreferenceSettings.RequestUserDataFolder += pathManager.GetUserDataFolder; @@ -924,7 +924,7 @@ protected DynamoModel(IStartConfiguration config) if (this.dynamoReady) { DynamoReadyExtensionHandler(new ReadyParams(this), - new List() { extension }); + [extension]); }; }; @@ -956,8 +956,7 @@ protected DynamoModel(IStartConfiguration config) AddHomeWorkspace(); AuthenticationManager = new AuthenticationManager(config.AuthProvider); - Logger.Log(string.Format("Dynamo -- Build {0}", - Assembly.GetExecutingAssembly().GetName().Version)); + Logger.Log($"Dynamo -- Build {Assembly.GetExecutingAssembly().GetName().Version}"); DynamoModel.OnRequestUpdateLoadBarStatus(new SplashScreenLoadEventArgs(Resources.SplashScreenLoadNodeLibrary, 50)); InitializeNodeLibrary(); @@ -1032,7 +1031,7 @@ protected DynamoModel(IStartConfiguration config) LuceneUtility.DisposeWriter(); } - GraphChecksumDictionary = new Dictionary>(); + GraphChecksumDictionary = new(); // This event should only be raised at the end of this method. DynamoReady(new ReadyParams(this)); @@ -1041,7 +1040,7 @@ protected DynamoModel(IStartConfiguration config) { if (trustedLoc.StartsWith(programDataPath)) { - Logger.Log(("An unsafe path has been detected in Trusted Locations: " + trustedLoc)); + Logger.Log($"An unsafe path has been detected in Trusted Locations: {trustedLoc}"); } } } @@ -1193,7 +1192,7 @@ private void SetDefaultPythonTemplate() if (!string.IsNullOrEmpty(pathManager.PythonTemplateFilePath) && File.Exists(pathManager.PythonTemplateFilePath)) { PreferenceSettings.PythonTemplateFilePath = pathManager.PythonTemplateFilePath; - Logger.Log(Resources.PythonTemplateAppData + " : " + PreferenceSettings.PythonTemplateFilePath); + Logger.Log($"{Resources.PythonTemplateAppData} : {PreferenceSettings.PythonTemplateFilePath}"); } // Otherwise the OOTB hard-coded template is applied @@ -1248,7 +1247,7 @@ public bool AddPackagePath(string path, string file = "") private IEnumerable LoadExtensions() { - var extensions = new List(); + List extensions = []; foreach (var dir in pathManager.ExtensionsDirectories) { extensions.AddRange(ExtensionManager.ExtensionLoader.LoadDirectory(dir)); @@ -1260,8 +1259,7 @@ private void RemoveExtension(IExtension ext) { ExtensionManager.Remove(ext); - var logSource = ext as ILogSource; - if (logSource != null) + if (ext is ILogSource logSource) logSource.MessageLogged -= LogMessage; } @@ -1293,7 +1291,7 @@ internal static void RaiseIExtensionStorageAccessWorkspaceOpened(HomeWorkspaceMo } catch (Exception ex) { - logger.Log(ex.Message + " : " + ex.StackTrace); + logger.Log($"{ex.Message} : {ex.StackTrace}"); return; } } @@ -1311,7 +1309,7 @@ internal static void RaiseIExtensionStorageAccessWorkspaceSaving(HomeWorkspaceMo } catch (Exception ex) { - logger.Log(ex.Message + " : " + ex.StackTrace); + logger.Log($"{ex.Message} : {ex.StackTrace}"); return; } @@ -1426,16 +1424,15 @@ private void LibraryLoaded(object sender, LibraryServices.LibraryLoadedEventArgs /// private void OnAsyncTaskStateChanged(DynamoScheduler sender, TaskStateChangedEventArgs e) { - var updateTask = e.Task as UpdateGraphAsyncTask; switch (e.CurrentState) { case TaskStateChangedEventArgs.State.ExecutionStarting: - if (updateTask != null) + if (e.Task is UpdateGraphAsyncTask updateTask) ExecutionEvents.OnGraphPreExecution(new ExecutionSession(updateTask, this, geometryFactoryPath)); break; case TaskStateChangedEventArgs.State.ExecutionCompleted: - if (updateTask != null) + if (e.Task is UpdateGraphAsyncTask updateTask2) { // Record execution time for update graph task. long start = e.Task.ExecutionStartTime.TickCount; @@ -1445,10 +1442,10 @@ private void OnAsyncTaskStateChanged(DynamoScheduler sender, TaskStateChangedEve //don't attempt to send these events unless GA is active or ADP will actually record these events. if (Logging.Analytics.ReportingAnalytics) { - if (updateTask.ModifiedNodes != null && updateTask.ModifiedNodes.Any()) + if (updateTask2.ModifiedNodes != null && updateTask2.ModifiedNodes.Any()) { // Send analytics for each of modified nodes so they are counted individually - foreach (var node in updateTask.ModifiedNodes) + foreach (var node in updateTask2.ModifiedNodes) { // Tracking node execution as generic event // it is distinguished with the legacy aggregated performance event @@ -1462,7 +1459,7 @@ private void OnAsyncTaskStateChanged(DynamoScheduler sender, TaskStateChangedEve Debug.WriteLine(String.Format(Resources.EvaluationCompleted, executionTimeSpan)); - ExecutionEvents.OnGraphPostExecution(new ExecutionSession(updateTask, this, geometryFactoryPath)); + ExecutionEvents.OnGraphPostExecution(new ExecutionSession(updateTask2, this, geometryFactoryPath)); } break; } @@ -1792,8 +1789,9 @@ internal void LoadNodeLibrary(Assembly assem, bool suppressZeroTouchLibraryLoad return; } - var nodes = new List(); - Loader.LoadNodesFromAssembly(assem, Context, nodes, new List()); + List nodes = []; + List errors = []; + Loader.LoadNodesFromAssembly(assem, Context, nodes, errors); LoadNodeModels(nodes, true); } @@ -2443,8 +2441,7 @@ private void SetPeriodicEvaluation(WorkspaceModel ws) // The following logic to start periodic evaluation will need to be moved // inside of the HomeWorkspaceModel's constructor. It cannot be there today // as it causes an immediate crash due to the above ResetEngine call. - var hws = ws as HomeWorkspaceModel; - if (hws != null) + if (ws is HomeWorkspaceModel hws) { // TODO: #4258 // Remove this ResetEngine call when multiple home workspaces is supported. @@ -2491,8 +2488,8 @@ internal bool OpenJsonFile( CustomNodeManager, this.LinterManager); - workspace.FileName = string.IsNullOrEmpty(filePath)? string.Empty : filePath; - workspace.FromJsonGraphId = string.IsNullOrEmpty(filePath) ? WorkspaceModel.ComputeGraphIdFromJson(fileContents) : string.Empty; + workspace.FileName = string.IsNullOrEmpty(filePath) ? "" : filePath; + workspace.FromJsonGraphId = string.IsNullOrEmpty(filePath) ? WorkspaceModel.ComputeGraphIdFromJson(fileContents) : ""; workspace.ScaleFactor = dynamoPreferences.ScaleFactor; workspace.IsTemplate = isTemplate; if (!IsTestMode && !IsHeadless) @@ -2689,7 +2686,7 @@ protected void SaveBackupFiles(object state) // when the last auto-save operation happens. Now the IDs will be used to know // whether some workspaces have already been backed up. If so, those workspaces won't be // backed up again. - var tempDict = new Dictionary(backupFilesDict); + Dictionary tempDict = new(backupFilesDict); backupFilesDict.Clear(); PreferenceSettings.BackupFiles.Clear(); foreach (var workspace in Workspaces) @@ -2710,7 +2707,7 @@ protected void SaveBackupFiles(object state) var savePath = pathManager.GetBackupFilePath(workspace); OnRequestWorkspaceBackUpSave(savePath, true); backupFilesDict[workspace.Guid] = savePath; - Logger.Log(Resources.BackupSavedMsg + ": " + savePath); + Logger.Log($"{Resources.BackupSavedMsg}: {savePath}"); } PreferenceSettings.BackupFiles.AddRange(backupFilesDict.Values); }); @@ -2801,7 +2798,7 @@ internal void DeleteModelInternal(List modelsToDelete) internal void UngroupModel(List modelsToUngroup) { - var emptyGroup = new List(); + List emptyGroup = []; var annotations = Workspaces.SelectMany(ws => ws.Annotations); foreach (var model in modelsToUngroup) { @@ -2880,7 +2877,7 @@ internal void AddGroupsToGroup(List modelsToAdd, Guid hostGroupGuid) var selectedGroup = workspaceAnnotations.FirstOrDefault(x => x.GUID == hostGroupGuid); if (selectedGroup is null) return; - var modelsToModify = new List(); + List modelsToModify = []; modelsToModify.AddRange(modelsToAdd); modelsToModify.Add(selectedGroup); @@ -3108,15 +3105,17 @@ var el in if (!(el is NodeModel)) continue; - var node = el as NodeModel; - var connectors = - node.InPorts.Concat(node.OutPorts).SelectMany(port => port.Connectors) - .Where( - connector => - connector.End != null && connector.End.Owner.IsSelected - && !ClipBoard.Contains(connector)); + if (el is NodeModel node) + { + var connectors = + node.InPorts.Concat(node.OutPorts).SelectMany(port => port.Connectors) + .Where( + connector => + connector.End != null && connector.End.Owner.IsSelected + && !ClipBoard.Contains(connector)); - ClipBoard.AddRange(connectors); + ClipBoard.AddRange(connectors); + } } } @@ -3159,11 +3158,11 @@ public void Paste(Point2D targetPoint, bool useOffset = true) //make a lookup table to store the guids of the //old models and the guids of their pasted versions - var modelLookup = new Dictionary(); + Dictionary modelLookup = []; //make a list of all newly created models so that their //creations can be recorded in the undo recorder. - var createdModels = new List(); + List createdModels = []; var nodes = ClipBoard.OfType(); var connectors = ClipBoard.OfType(); @@ -3177,7 +3176,7 @@ public void Paste(Point2D targetPoint, bool useOffset = true) var xmlDoc = new XmlDocument(); // Create the new NodeModel's - var newNodeModels = new List(); + List newNodeModels = []; using (CurrentWorkspace.BeginDelayedGraphExecution()) { foreach (var node in nodes) @@ -3212,7 +3211,7 @@ public void Paste(Point2D targetPoint, bool useOffset = true) } // Create the new NoteModel's - var newNoteModels = new List(); + List newNoteModels = []; foreach (var note in notes) { var noteModel = new NoteModel(note.X, note.Y, note.Text, Guid.NewGuid()); @@ -3285,7 +3284,7 @@ from c in connectors //Grouping depends on the selected node models. //so adding the group after nodes / notes are added to workspace. //select only those nodes that are part of a group. - var newAnnotations = new List(); + List newAnnotations = []; foreach (var annotation in annotations.OrderByDescending(a => a.HasNestedGroups)) { if (modelLookup.ContainsKey(annotation.GUID)) @@ -3341,9 +3340,9 @@ from c in connectors private AnnotationModel CreateAnnotationModel( AnnotationModel model, Dictionary modelLookup) { - var annotationNodeModel = new List(); - var annotationNoteModel = new List(); - var annotationAnnotationModels = new List(); + List annotationNodeModel = []; + List annotationNoteModel = []; + List annotationAnnotationModels = []; // some models can be deleted after copying them, // so they need to be in pasted annotation as well var modelsToRestore = model.DeletedModelBases.Intersect(ClipBoard); @@ -3396,8 +3395,7 @@ private AnnotationModel CreateAnnotationModel( /// The object to add to the selection. public void AddToSelection(object parameters) { - var selectable = parameters as ISelectable; - if (selectable != null) + if (parameters is ISelectable selectable) { DynamoSelection.Instance.Selection.AddUnique(selectable); } @@ -3471,7 +3469,7 @@ where function.IsVisibleInLibrary where !displayString.Contains("GetType") select string.IsNullOrEmpty(function.Namespace) ? "" - : function.Namespace + "." + function.Signature + "\n")); + : $"{function.Namespace}.{function.Signature}\n")); var sb = string.Join("\n", descriptions); @@ -3764,7 +3762,7 @@ private void InsertNodes(IEnumerable nodes, double offsetX, double of private void InsertConnectors(IEnumerable connectors) { - List newConnectors = new List(); + List newConnectors = []; foreach (var connectorModel in connectors) { @@ -3787,7 +3785,7 @@ private void InsertConnectors(IEnumerable connectors) private List GetInsertedNotes(IEnumerable viewInfoAnnotations) { - List result = new List(); + List result = []; foreach (var annotation in viewInfoAnnotations) { @@ -3808,7 +3806,7 @@ private List GetInsertedNotes(IEnumerable vi internal static void RecordUndoModels(WorkspaceModel workspace, List undoItems) { - var userActionDictionary = new Dictionary(); + Dictionary userActionDictionary = []; //Add models that were newly created foreach (var undoItem in undoItems) {