/
RecordableCommands.cs
2720 lines (2281 loc) · 98.9 KB
/
RecordableCommands.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Dynamo.Graph;
using Dynamo.Graph.Nodes;
using Dynamo.Properties;
using Dynamo.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
using System.Globalization;
namespace Dynamo.Models
{
public partial class DynamoModel
{
/// <summary>
/// This is the base class of all recordable commands. It provides the
/// contract between a UI event handler (e.g. delegate command method or
/// a button event handler) and the actual command handler in the
/// DynamoViewModel. It is mandatory for each RecordableCommand-derived
/// class to be serializable to/deserializable from an XmlElement.
/// </summary>
[DataContract]
public abstract class RecordableCommand
{
#region Class Data Members
// See property for more details.
protected bool redundant = false;
/// <summary>
/// Settings that is used for serializing commands
/// </summary>
protected static JsonSerializerSettings jsonSettings;
/// <summary>
/// Initialize commands serializing settings
/// </summary>
static RecordableCommand()
{
jsonSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Culture = CultureInfo.InvariantCulture
};
}
#endregion
#region Public Class Operational Methods
/// <summary>
/// Constructs an instance of RecordableCommand derived class. This
/// constructor is made protected to indicate that the class instance
/// can only be instantiated through a derived class.
/// </summary>
protected RecordableCommand()
: this(string.Empty) { }
/// <summary>
/// Constructs an instance of RecordableCommand derived class,
/// assigning a new tag to it.
/// </summary>
/// <param name="tag">A string tag to be assigned to the command.
/// This parameter can be any string, even an empty one. However,
/// it should not be null. A null "tag" parameter causes the
/// ArgumentNullException to be thrown.</param>
protected RecordableCommand(string tag)
{
if (tag == null)
throw new ArgumentNullException("tag");
Tag = tag;
IsInPlaybackMode = false;
}
/// <summary>
/// Call this method to execute a RecordableCommand. A RecordableCommand
/// must be executed in the context of an existing DynamoViewModel.
/// </summary>
/// <param name="dynamoModel">The DynamoModel object this
/// RecordableCommand is targeting.</param>
///
internal void Execute(DynamoModel dynamoModel)
{
ExecuteCore(dynamoModel);
}
/// <summary>
/// This method serializes the RecordableCommand object in the form of
/// XmlElement for storage. The resulting XmlElement contains all the
/// arguments that are required by this command.
/// </summary>
/// <param name="document">The XmlDocument from which an XmlElement can
/// be created.</param>
/// <returns>The XmlElement representation of this RecordableCommand
/// object. It will be used in RecordableCommand.Deserialize method to
/// completely reconstruct the RecordableCommand it represents.</returns>
///
internal XmlElement Serialize(XmlDocument document)
{
string commandName = GetType().Name;
XmlElement element = document.CreateElement(commandName);
SerializeCore(element);
return element;
}
/// <summary>
/// This method serializes the RecordableCommand object in the json form.
/// The resulting string contains command type name and all the
/// arguments that are required by this command.
/// </summary>
/// <returns>The string can be used for reconstructing RecordableCommand
/// using Deserialize method</returns>
internal string Serialize()
{
return JsonConvert.SerializeObject(this, jsonSettings);
}
/// <summary>
/// Call this static method to reconstruct a RecordableCommand-derived
/// object given an XmlElement that was previously saved with Serialize
/// method. This method simply redirects the XmlElement to respective
/// RecordableCommand-derived classes based on its type.
/// </summary>
/// <param name="element">The XmlElement from which the RecordableCommand
/// can be reconstructed.</param>
/// <returns>Returns the reconstructed RecordableCommand object. If a
/// RecordableCommand cannot be reconstructed, this method throws a
/// relevant exception.</returns>
internal static RecordableCommand Deserialize(XmlElement element)
{
if (string.IsNullOrEmpty(element.Name))
throw new ArgumentException("XmlElement without name");
RecordableCommand command = null;
switch (element.Name)
{
case nameof(OpenFileCommand):
command = OpenFileCommand.DeserializeCore(element);
break;
case nameof(OpenFileFromJsonCommand):
command = OpenFileFromJsonCommand.DeserializeCore(element);
break;
case nameof(PausePlaybackCommand):
command = PausePlaybackCommand.DeserializeCore(element);
break;
case nameof(RunCancelCommand):
command = RunCancelCommand.DeserializeCore(element);
break;
case nameof(CreateNodeCommand):
command = CreateNodeCommand.DeserializeCore(element);
break;
case nameof(SelectModelCommand):
command = SelectModelCommand.DeserializeCore(element);
break;
case nameof(CreateNoteCommand):
command = CreateNoteCommand.DeserializeCore(element);
break;
case nameof(SelectInRegionCommand):
command = SelectInRegionCommand.DeserializeCore(element);
break;
case nameof(DragSelectionCommand):
command = DragSelectionCommand.DeserializeCore(element);
break;
case nameof(MakeConnectionCommand):
command = MakeConnectionCommand.DeserializeCore(element);
break;
case nameof(DeleteModelCommand):
command = DeleteModelCommand.DeserializeCore(element);
break;
case nameof(UndoRedoCommand):
command = UndoRedoCommand.DeserializeCore(element);
break;
case nameof(ModelEventCommand):
command = ModelEventCommand.DeserializeCore(element);
break;
case nameof(UpdateModelValueCommand):
command = UpdateModelValueCommand.DeserializeCore(element);
break;
case nameof(ConvertNodesToCodeCommand):
command = ConvertNodesToCodeCommand.DeserializeCore(element);
break;
case nameof(CreateCustomNodeCommand):
command = CreateCustomNodeCommand.DeserializeCore(element);
break;
case nameof(SwitchTabCommand):
command = SwitchTabCommand.DeserializeCore(element);
break;
case nameof(CreateAnnotationCommand):
command = CreateAnnotationCommand.DeserializeCore(element);
break;
case nameof(UngroupModelCommand):
command = UngroupModelCommand.DeserializeCore(element);
break;
case nameof(AddPresetCommand):
command = AddPresetCommand.DeserializeCore(element);
break;
case nameof(ApplyPresetCommand):
command = ApplyPresetCommand.DeserializeCore(element);
break;
case nameof(CreateAndConnectNodeCommand):
command = CreateAndConnectNodeCommand.DeserializeCore(element);
break;
}
if (null != command)
{
command.IsInPlaybackMode = true;
command.Tag = element.GetAttribute("Tag");
return command;
}
string message = string.Format("Unknown command: {0}", element.Name);
throw new ArgumentException(message);
}
/// <summary>
/// Call this static method to reconstruct a RecordableCommand from json
/// string that contains command name - name of corresponding class inherited
/// from RecordableCommand, - and all the arguments that are required by this
/// command.
/// </summary>
/// <param name="jsonString">Json string that contains command name and all
/// its arguments.</param>
/// <returns>Reconstructed RecordableCommand</returns>
internal static RecordableCommand Deserialize(string jsonString)
{
RecordableCommand command = null;
try
{
command = JsonConvert.DeserializeObject(jsonString, jsonSettings) as RecordableCommand;
command.IsInPlaybackMode = true;
return command;
}
catch
{
throw new ApplicationException("Invalid jsonString for creating RecordableCommand");
}
}
#endregion
#region Public Command Properties
/// <summary>
/// Some commands are fired at high frequency (e.g. dragging and window
/// selection related commands), and can be simulated during playback by
/// issuing the final occurrence of the command. For example, window
/// selection command is fired for each mouse-move event, but the end
/// result will be same if only the final selection command is recorded.
/// If this property is set to 'true', then only the last occurrence will
/// be recorded for playback.
/// </summary>
internal bool Redundant { get { return redundant; } }
/// <summary>
/// This flag will be set to true only during playback. Derived classes
/// can use this to decide their actions accordingly. For example,
/// UpdateModelValueCommand doesn't change the value of a property
/// during recording time, it is created for the sole purpose of being
/// recorded. During playback, then UpdateModelValueCommand will update
/// the property that it is bound to. This is a runtime flag, it is not
/// serialized in anyway.
/// </summary>
[DataMember]
internal bool IsInPlaybackMode { get; private set; }
/// <summary>
/// This is an optional tag for each of the recorded commands in a
/// command Xml file. A command can only be tagged from within a
/// command Xml file manually, and a tag is useful for unit test
/// verification passes. See PlaybackStateChangedEventArgs class for
/// possible usage of command tags. If a command is not tagged, its
/// default tag value is an empty string.
/// </summary>
[DataMember]
internal string Tag { get; private set; }
#endregion
#region Protected Overridable Methods
/// <summary>
/// Derived classes must implement this method to perform the actual
/// command execution. A typical implementation of this method involves
/// calling a corresponding method on DynamoModel by passing itself as
/// the only argument.
/// </summary>
/// <param name="dynamoModel">The DynamoModel object on which
/// this command should be executed.</param>
///
protected abstract void ExecuteCore(DynamoModel dynamoModel);
/// <summary>
/// Derived classes must implement this method to serialize all relevant
/// information into the XmlElement supplied to it. Typically the method
/// is a direct mirror of DeserializeCore.
/// </summary>
/// <param name="element">All arguments that are required for this
/// command are written into this XmlElement. The information written
/// here must be exactly what DeserializeCore method expects.</param>
///
protected abstract void SerializeCore(XmlElement element);
/// <summary>
/// This method provides derived class implementation of analytics
/// tracking, and only gets called if analytics tracking is enabled.
/// </summary>
internal virtual void TrackAnalytics() { }
#endregion
}
/// <summary>
/// This class is base for those RecordableCommands that should have
/// Guid that causes the problems during deserialization
/// </summary>
[DataContract]
public abstract class ModelBasedRecordableCommand : RecordableCommand
{
/// <summary>
/// The first <see cref="Guid"/> in the <seealso cref="ModelGuid"/> collection, or an empty <see cref="Guid"/>.
/// </summary>
public Guid ModelGuid
{
get
{
return ModelGuids.Any() ? ModelGuids.First() : Guid.Empty;
}
}
/// <summary>
/// A collection of <see cref="Guid"/>.
/// </summary>
public IEnumerable<Guid> ModelGuids { get; private set; }
/// <summary>
/// A collection of <see cref="Guid"/> identifying the objects on which to operate.
/// </summary>
/// <param name="guids"></param>
protected ModelBasedRecordableCommand(IEnumerable<Guid> guids)
{
ModelGuids = guids;
}
protected override void SerializeCore(XmlElement element)
{
var document = element.OwnerDocument;
foreach (var modelGuid in ModelGuids)
{
var childNode = document.CreateElement("ModelGuid");
childNode.InnerText = modelGuid.ToString();
element.AppendChild(childNode);
}
}
protected static IEnumerable<Guid> DeserializeGuid(XmlElement element, XmlElementHelper helper)
{
// Deserialize old type of commands
if (helper.HasAttribute("ModelGuid"))
{
Guid modelGuid = helper.ReadGuid("ModelGuid", Guid.Empty);
return new[] { modelGuid };
}
if (helper.HasAttribute("NodeId"))
{
Guid modelGuid = helper.ReadGuid("NodeId", Guid.Empty);
return new[] { modelGuid };
}
return (from XmlNode xmlNode in element.ChildNodes
where xmlNode.Name.Equals("ModelGuid")
select Guid.Parse(xmlNode.InnerText)).ToArray();
}
}
/// <summary>
/// A command used to pause command playback.
/// </summary>
[DataContract]
public class PausePlaybackCommand : RecordableCommand
{
#region Public Class Methods
/// <summary>
///
/// </summary>
/// <param name="pauseDurationInMs">The duration to pause the playback in milliseconds.</param>
public PausePlaybackCommand(int pauseDurationInMs)
: base(GenerateRandomTag())
{
PauseDurationInMs = pauseDurationInMs;
}
internal static PausePlaybackCommand DeserializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
var pauseDurationInMs = helper.ReadInteger("PauseDurationInMs");
return new PausePlaybackCommand(pauseDurationInMs);
}
#endregion
#region Public Command Properties
[DataMember]
internal int PauseDurationInMs { get; private set; }
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
// A PausePlaybackCommand should never be executed.
throw new NotImplementedException();
}
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
helper.SetAttribute("Tag", Tag);
helper.SetAttribute("PauseDurationInMs", PauseDurationInMs);
}
#endregion
#region Private Class Helper Methods
private static string GenerateRandomTag()
{
// Given a GUID in the form AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE,
// extract out only the AAAAAAAA part (we don't want the tag name
// to be that long, considering the chances of collision in the
// same recorded XML file is near zero, and that these tags are
// usually renamed after they are recorded by a test developer).
//
string guid = Guid.NewGuid().ToString();
guid = guid.Substring(0, guid.IndexOf('-'));
return string.Format("Tag-{0}", guid);
}
#endregion
}
/// <summary>
/// A command to open a file.
/// </summary>
[DataContract]
public class OpenFileCommand : RecordableCommand
{
#region Public Class Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="filePath">The path to the file.</param>
/// <param name="forceManualExecutionMode">Should the file be opened in manual execution mode?</param>
public OpenFileCommand(string filePath, bool forceManualExecutionMode = false)
{
FilePath = filePath;
ForceManualExecutionMode = forceManualExecutionMode;
IsTemplate = false;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="filePath">The path to the file.</param>
/// <param name="forceManualExecutionMode">Should the file be opened in manual execution mode?</param>
/// <param name="isTemplate">Is Dynamo opening a template file?</param>
public OpenFileCommand(string filePath, bool forceManualExecutionMode, bool isTemplate)
{
FilePath = filePath;
ForceManualExecutionMode = forceManualExecutionMode;
IsTemplate = isTemplate;
}
private static string TryFindFile(string xmlFilePath, string uriString = null)
{
if (File.Exists(xmlFilePath))
return xmlFilePath;
var xmlFileName = Path.GetFileName(xmlFilePath);
if (uriString != null)
{
// Try to find the file right next to the command XML file.
Uri uri = new Uri(uriString);
string directory = Path.GetDirectoryName(uri.AbsolutePath);
xmlFilePath = Path.Combine(directory, xmlFileName);
// If it still cannot be resolved, fall back to system search.
if (!File.Exists(xmlFilePath))
xmlFilePath = Path.GetFullPath(xmlFileName);
if (File.Exists(xmlFilePath))
return xmlFilePath;
}
var message = "Target file cannot be found!";
throw new FileNotFoundException(message, xmlFileName);
}
internal static OpenFileCommand DeserializeCore(XmlElement element)
{
XmlElementHelper helper = new XmlElementHelper(element);
string xmlFilePath = TryFindFile(helper.ReadString("XmlFilePath"), element.OwnerDocument.BaseURI);
return new OpenFileCommand(xmlFilePath);
}
#endregion
#region Public Command Properties
[DataMember]
internal string FilePath { get; private set; }
internal bool ForceManualExecutionMode { get; private set; }
internal bool IsTemplate { get; private set; }
private DynamoModel dynamoModel;
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
this.dynamoModel = dynamoModel;
if (IsTemplate)
{
dynamoModel.OpenTemplateImpl(this);
}
else
{
dynamoModel.OpenFileImpl(this);
}
}
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
helper.SetAttribute("XmlFilePath", FilePath);
}
internal override void TrackAnalytics()
{
// Log file open action and the number of nodes in the opened workspace
Dynamo.Logging.Analytics.TrackTaskFileOperationEvent(
FilePath,
Logging.Actions.Open,
dynamoModel.CurrentWorkspace.Nodes.Count());
// If there are unresolved nodes in the opened workspace, log the node names and count
var unresolvedNodes = dynamoModel.CurrentWorkspace.Nodes.OfType<DummyNode>();
if (unresolvedNodes != null && unresolvedNodes.Any())
{
Dynamo.Logging.Analytics.TrackEvent(
Logging.Actions.Unresolved,
Logging.Categories.NodeOperations,
unresolvedNodes.Select(n => string.Format("{0}:{1}", n.LegacyAssembly, n.LegacyFullName))
.Aggregate((x, y) => string.Format("{0}, {1}", x, y)),
unresolvedNodes.Count());
}
}
#endregion
}
/// <summary>
/// A command to open a file.
/// </summary>
[DataContract]
public class InsertFileCommand : RecordableCommand
{
#region Public Class Methods
/// <summary>
/// Insert Graph or Custom Node from a file path into the current Workspace
/// </summary>
/// <param name="filePath">The path to the file.</param>
/// <param name="forceManualExecutionMode">Should the file be opened in manual execution mode?</param>
public InsertFileCommand(string filePath, bool forceManualExecutionMode = false)
{
FilePath = filePath;
ForceManualExecutionMode = forceManualExecutionMode;
}
private static string TryFindFile(string xmlFilePath, string uriString = null)
{
if (File.Exists(xmlFilePath))
return xmlFilePath;
var xmlFileName = Path.GetFileName(xmlFilePath);
if (uriString != null)
{
// Try to find the file right next to the command XML file.
Uri uri = new Uri(uriString);
string directory = Path.GetDirectoryName(uri.AbsolutePath);
xmlFilePath = Path.Combine(directory, xmlFileName);
// If it still cannot be resolved, fall back to system search.
if (!File.Exists(xmlFilePath))
xmlFilePath = Path.GetFullPath(xmlFileName);
if (File.Exists(xmlFilePath))
return xmlFilePath;
}
var message = "Target file cannot be found!";
throw new FileNotFoundException(message, xmlFileName);
}
internal static InsertFileCommand DeserializeCore(XmlElement element)
{
XmlElementHelper helper = new XmlElementHelper(element);
string xmlFilePath = TryFindFile(helper.ReadString("XmlFilePath"), element.OwnerDocument.BaseURI);
return new InsertFileCommand(xmlFilePath);
}
#endregion
#region Public Command Properties
[DataMember]
internal string FilePath { get; private set; }
internal bool ForceManualExecutionMode { get; private set; }
private DynamoModel dynamoModel;
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
this.dynamoModel = dynamoModel;
dynamoModel.InsertFileImpl(this);
}
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
helper.SetAttribute("XmlFilePath", FilePath);
}
internal override void TrackAnalytics()
{
// Log file open action and the number of nodes in the opened workspace
Dynamo.Logging.Analytics.TrackTaskFileOperationEvent(
FilePath,
Logging.Actions.Open,
dynamoModel.CurrentWorkspace.Nodes.Count());
// If there are unresolved nodes in the opened workspace, log the node names and count
var unresolvedNodes = dynamoModel.CurrentWorkspace.Nodes.OfType<DummyNode>();
if (unresolvedNodes != null && unresolvedNodes.Any())
{
Dynamo.Logging.Analytics.TrackEvent(
Logging.Actions.Unresolved,
Logging.Categories.NodeOperations,
unresolvedNodes.Select(n => string.Format("{0}:{1}", n.LegacyAssembly, n.LegacyFullName))
.Aggregate((x, y) => string.Format("{0}, {1}", x, y)),
unresolvedNodes.Count());
}
}
#endregion
}
/// <summary>
/// A command to open a file from Json content.
/// </summary>
[DataContract]
public class OpenFileFromJsonCommand : RecordableCommand
{
#region Public Class Methods
/// <summary>
///
/// </summary>
/// <param name="fileContents">The Json content of a file.</param>
/// <param name="forceManualExecutionMode">Should the file be opened in manual execution mode?</param>
public OpenFileFromJsonCommand(string fileContents, bool forceManualExecutionMode = false)
{
FileContents = fileContents;
ForceManualExecutionMode = forceManualExecutionMode;
}
internal static OpenFileFromJsonCommand DeserializeCore(XmlElement element)
{
XmlElementHelper helper = new XmlElementHelper(element);
string xmlFileContents = helper.ReadString("XmlFileContents");
return new OpenFileFromJsonCommand(xmlFileContents);
}
#endregion
#region Public Command Properties
[DataMember]
internal string FileContents { get; private set; }
internal bool ForceManualExecutionMode { get; private set; }
private DynamoModel dynamoModel;
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
this.dynamoModel = dynamoModel;
dynamoModel.OpenFileFromJsonImpl(this);
}
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
helper.SetAttribute("XmlFileContents", FileContents);
}
internal override void TrackAnalytics()
{
// Log file open action and the number of nodes in the opened workspace
Dynamo.Logging.Analytics.TrackTaskFileOperationEvent(
"In memory json file",
Logging.Actions.Open,
dynamoModel.CurrentWorkspace.Nodes.Count());
// If there are unresolved nodes in the opened workspace, log the node names and count
var unresolvedNodes = dynamoModel.CurrentWorkspace.Nodes.OfType<DummyNode>();
if (unresolvedNodes != null && unresolvedNodes.Any())
{
Dynamo.Logging.Analytics.TrackEvent(
Logging.Actions.Unresolved,
Logging.Categories.NodeOperations,
unresolvedNodes.Select(n => string.Format("{0}:{1}", n.LegacyAssembly, n.LegacyFullName))
.Aggregate((x, y) => string.Format("{0}, {1}", x, y)),
unresolvedNodes.Count());
}
}
#endregion
}
/// <summary>
/// A command used to execute or cancel execution.
/// </summary>
[DataContract]
public class RunCancelCommand : RecordableCommand
{
#region Public Class Methods
/// <summary>
///
/// </summary>
/// <param name="showErrors">Should errors be shown?</param>
/// <param name="cancelRun">True to cancel execution. False to execute.</param>
public RunCancelCommand(bool showErrors, bool cancelRun)
{
ShowErrors = showErrors;
CancelRun = cancelRun;
}
internal static RunCancelCommand DeserializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
bool showErrors = helper.ReadBoolean("ShowErrors");
bool cancelRun = helper.ReadBoolean("CancelRun");
return new RunCancelCommand(showErrors, cancelRun);
}
#endregion
#region Public Command Properties
[DataMember]
internal bool ShowErrors { get; private set; }
[DataMember]
internal bool CancelRun { get; private set; }
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
dynamoModel.RunCancelImpl(this);
}
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
helper.SetAttribute("ShowErrors", ShowErrors);
helper.SetAttribute("CancelRun", CancelRun);
}
#endregion
}
/// <summary>
/// A command used to force cancellation of execution.
/// </summary>
[DataContract]
public class ForceRunCancelCommand : RunCancelCommand
{
/// <summary>
///
/// </summary>
/// <param name="showErrors">Should errors be shown?</param>
/// <param name="cancelRun">True to cancel execution. False to execute.</param>
public ForceRunCancelCommand(bool showErrors, bool cancelRun)
: base(showErrors, cancelRun) { }
protected override void ExecuteCore(DynamoModel dynamoModel)
{
dynamoModel.ForceRunCancelImpl(this);
}
}
/// <summary>
/// A command used to mutate commands during testing.
/// </summary>
public class MutateTestCommand : RecordableCommand
{
protected override void ExecuteCore(DynamoModel dynamoModel) { }
protected override void SerializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
}
}
/// <summary>
/// A command used to create a node.
/// </summary>
[DataContract]
public class CreateNodeCommand : ModelBasedRecordableCommand
{
private void SetProperties(double x, double y, bool defaultPosition, bool transformCoordinates)
{
X = x;
Y = y;
DefaultPosition = defaultPosition;
TransformCoordinates = transformCoordinates;
}
#region Public Class Methods
/// <summary>
/// </summary>
/// <param name="node">The node.</param>
/// <param name="x">The x location.</param>
/// <param name="y">The y location.</param>
/// <param name="defaultPosition"></param>
/// <param name="transformCoordinates"></param>
public CreateNodeCommand(
NodeModel node, double x, double y, bool defaultPosition, bool transformCoordinates)
: base(node != null ? new[] { node.GUID } : new[] { Guid.Empty })
{
Node = node;
SetProperties(x, y, defaultPosition, transformCoordinates);
}
/// <summary>
///
/// </summary>
/// <param name="node"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="defaultPosition"></param>
/// <param name="transformCoordinates"></param>
private CreateNodeCommand(
XmlElement node, double x, double y, bool defaultPosition, bool transformCoordinates)
: base(new[] { Guid.Empty })
{
NodeXml = node;
SetProperties(x, y, defaultPosition, transformCoordinates);
}
/// <summary>
///
/// </summary>
/// <param name="nodeId"></param>
/// <param name="nodeName"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="defaultPosition"></param>
/// <param name="transformCoordinates"></param>
public CreateNodeCommand(IEnumerable<Guid> nodeId, string nodeName,
double x, double y, bool defaultPosition, bool transformCoordinates)
: base(nodeId)
{
Name = nodeName;
SetProperties(x, y, defaultPosition, transformCoordinates);
}
/// <summary>
///
/// </summary>
/// <param name="nodeId"></param>
/// <param name="nodeName"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="defaultPosition"></param>
/// <param name="transformCoordinates"></param>
[JsonConstructor]
public CreateNodeCommand(string nodeId, string nodeName,
double x, double y, bool defaultPosition, bool transformCoordinates)
: base(new[] { Guid.Parse(nodeId) })
{
Name = nodeName;
SetProperties(x, y, defaultPosition, transformCoordinates);
}
internal static CreateNodeCommand DeserializeCore(XmlElement element)
{
var helper = new XmlElementHelper(element);
double x = helper.ReadDouble("X");
double y = helper.ReadDouble("Y");
bool defaultPos = helper.ReadBoolean("DefaultPosition");
bool transformCoords = helper.ReadBoolean("TransformCoordinates");
var nodeElement = element.ChildNodes.OfType<XmlElement>().FirstOrDefault(el => el.Name != "ModelGuid");
if (nodeElement == null)
{
// Get the old NodeId and NodeName attributes
var nodeId = DeserializeGuid(element, helper);
string name = helper.ReadString("NodeName");
return new CreateNodeCommand(nodeId, name, x, y, defaultPos, transformCoords);
}
return new CreateNodeCommand(nodeElement, x, y, defaultPos, transformCoords);
}
#endregion
#region Public Command Properties
// Faster, direct creation
internal NodeModel Node { get; private set; }
// If it was deserialized
internal XmlElement NodeXml { get; private set; }
[DataMember]
internal double X { get; private set; }
[DataMember]
internal double Y { get; private set; }
[DataMember]
internal bool DefaultPosition { get; private set; }
[DataMember]
internal bool TransformCoordinates { get; private set; }
[DataMember]
//Legacy properties
public string Name { get; private set; }
#endregion
#region Protected Overridable Methods
protected override void ExecuteCore(DynamoModel dynamoModel)
{
dynamoModel.CreateNodeImpl(this);
}
protected override void SerializeCore(XmlElement element)
{
base.SerializeCore(element);
var helper = new XmlElementHelper(element);
helper.SetAttribute("X", X);
helper.SetAttribute("Y", Y);
helper.SetAttribute("DefaultPosition", DefaultPosition);
helper.SetAttribute("TransformCoordinates", TransformCoordinates);
if (Node != null)
{
var nodeElement = Node.Serialize(element.OwnerDocument, SaveContext.Save);
element.AppendChild(nodeElement);
}
else if (NodeXml != null)
{
element.AppendChild(NodeXml);
}
else
{
helper.SetAttribute("NodeName", Name);