-
Notifications
You must be signed in to change notification settings - Fork 635
/
SerializationConverters.cs
1490 lines (1296 loc) · 59.6 KB
/
SerializationConverters.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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Dynamo.Configuration;
using Dynamo.Core;
using Dynamo.Engine;
using Dynamo.Extensions;
using Dynamo.Graph.Annotations;
using Dynamo.Graph.Connectors;
using Dynamo.Graph.Nodes;
using Dynamo.Graph.Nodes.CustomNodes;
using Dynamo.Graph.Nodes.NodeLoaders;
using Dynamo.Graph.Nodes.ZeroTouch;
using Dynamo.Graph.Notes;
using Dynamo.Graph.Presets;
using Dynamo.Library;
using Dynamo.Linting;
using Dynamo.Logging;
using Dynamo.Properties;
using Dynamo.Scheduler;
using Dynamo.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using ProtoCore;
using ProtoCore.Namespace;
using Type = System.Type;
namespace Dynamo.Graph.Workspaces
{
/// <summary>
/// The NodeModelConverter is used to serialize and deserialize NodeModels.
/// These nodes require a CustomNodeDefinition which can only be supplied
/// by looking it up in the CustomNodeManager.
/// </summary>
public class NodeReadConverter : JsonConverter
{
private CustomNodeManager manager;
private LibraryServices libraryServices;
private NodeFactory nodeFactory;
private bool isTestMode;
public ElementResolver ElementResolver { get; set; }
// Map of all loaded assemblies including LoadFrom context assemblies
private Dictionary<string, List<Assembly>> loadedAssemblies;
private CodeBlockNodeModel DeserializeAsCBN(string code, JObject obj, Guid guid)
{
var codeBlockNode = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver);
// If the code block node is in an error state read the extra port data
// and initialize the input and output ports
if (codeBlockNode.IsInErrorState)
{
List<string> inPortNames = new List<string>();
var inputs = obj["Inputs"];
foreach (var input in inputs)
{
inPortNames.Add(input["Name"].ToString());
}
// NOTE: This could be done in a simpler way, but is being implemented
// in this manner to allow for possible future port line number
// information being available in the file
List<int> outPortLineIndexes = new List<int>();
var outputs = obj["Outputs"];
int outputLineIndex = 0;
foreach (var output in outputs)
{
outPortLineIndexes.Add(outputLineIndex++);
}
codeBlockNode.SetErrorStatePortData(inPortNames, outPortLineIndexes);
}
return codeBlockNode;
}
public NodeReadConverter(CustomNodeManager manager, LibraryServices libraryServices, NodeFactory nodeFactory, bool isTestMode = false)
{
this.manager = manager;
this.libraryServices = libraryServices;
this.nodeFactory = nodeFactory;
this.isTestMode = isTestMode;
// We only do this in test mode because it should not be required-
// see comment below in NodeReadConverter.ReadJson - and it could be slow.
if (this.isTestMode)
{
this.loadedAssemblies = this.buildMapOfLoadedAssemblies();
}
}
private Dictionary<string,List<Assembly>> buildMapOfLoadedAssemblies()
{
var allAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var dict = new Dictionary<string, List<Assembly>>();
foreach(var assembly in allAssemblies)
{
if (!dict.ContainsKey(assembly.GetName().Name))
{
dict[assembly.GetName().Name] = new List<Assembly>() { assembly };
}
else{
dict[assembly.GetName().Name].Add(assembly);
}
}
return dict;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(NodeModel);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
NodeModel node = null;
String typeName = String.Empty;
String functionName = String.Empty;
String assemblyName = String.Empty;
var obj = JObject.Load(reader);
Type type = null;
try
{
type = Type.GetType(obj["$type"].Value<string>());
typeName = obj["$type"].Value<string>().Split(',').FirstOrDefault();
if (typeName.Equals("Dynamo.Graph.Nodes.ZeroTouch.DSFunction"))
{
// If it is a zero touch node, then get the whole function name including the namespace.
functionName = obj["FunctionSignature"].Value<string>().Split('@').FirstOrDefault().Trim();
}
// we get the assembly name from the type string for the node model nodes.
else
{
assemblyName = obj["$type"].Value<string>().Split(',').Skip(1).FirstOrDefault().Trim();
}
}
catch(Exception e)
{
nodeFactory?.AsLogger().Log(e);
}
// If we can't find this type - try to look in our load from assemblies,
// but only during testing - this is required during testing because some dlls are loaded
// using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context -
// dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should
// not be an issue during normal dynamo use but if it is we can enable this code.
if(type == null && this.isTestMode == true)
{
List<Assembly> resultList;
// This assemblyName does not usually contain version information...
assemblyName = obj["$type"].Value<string>().Split(',').Skip(1).FirstOrDefault().Trim();
if (assemblyName != null)
{
if(this.loadedAssemblies.TryGetValue(assemblyName, out resultList))
{
var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList();
type = matchingTypes.FirstOrDefault();
}
}
}
// Check for and attempt to resolve an unknown type before proceeding
if (type == null)
{
// Attempt to resolve the type using `AlsoKnownAs`
var unresolvedName = obj["$type"].Value<string>().Split(',').FirstOrDefault();
Type newType;
nodeFactory.ResolveType(unresolvedName, out newType);
// If resolved update the type
if (newType != null)
{
type = newType;
}
}
// If the id is not a guid, makes a guid based on the id of the node
var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value<string>());
var replication = obj["Replication"].Value<string>();
var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject<PortModel>()).ToArray();
var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject<PortModel>()).ToArray();
var resolver = (IdReferenceResolver)serializer.ReferenceResolver;
string assemblyLocation = objectType.Assembly.Location;
bool remapPorts = true;
if (type == null)
{
// If type is still null at this point return a dummy node
node = CreateDummyNode(obj, typeName, assemblyName, functionName, inPorts, outPorts);
}
// Attempt to create a valid node using the type
else if (type == typeof(Function))
{
var functionId = Guid.Parse(obj["FunctionSignature"].Value<string>());
CustomNodeDefinition def = null;
CustomNodeInfo info = null;
// Skip deserializing the Description Json property as the original one in dyf may
// already be updated without syncing with the dyn
bool isUnresolved = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info);
Function function = manager.CreateCustomNodeInstance(functionId, null, false, def, info);
node = function;
if (isUnresolved)
function.UpdatePortsForUnresolved(inPorts, outPorts);
}
else if (type == typeof(CodeBlockNodeModel))
{
var code = obj["Code"].Value<string>();
node = DeserializeAsCBN(code, obj, guid);
}
else if (typeof(DSFunctionBase).IsAssignableFrom(type))
{
var mangledName = obj["FunctionSignature"].Value<string>();
var lookupSignature = libraryServices.GetFunctionSignatureFromFunctionSignatureHint(mangledName) ?? mangledName;
var functionDescriptor = libraryServices.GetFunctionDescriptor(lookupSignature);
// Use the functionDescriptor to try and restore the proper node if possible
if (functionDescriptor == null)
{
node = CreateDummyNode(obj, assemblyName, functionName, inPorts, outPorts);
}
else
{
if (type == typeof(DSVarArgFunction))
{
node = new DSVarArgFunction(functionDescriptor);
// The node syncs with the function definition.
// Then we need to make the inport count correct
var varg = (DSVarArgFunction)node;
varg.VarInputController.SetNumInputs(inPorts.Count());
}
else if (type == typeof(DSFunction))
{
node = new DSFunction(functionDescriptor);
}
}
}
else if (type == typeof(DSVarArgFunction))
{
var functionId = Guid.Parse(obj["FunctionSignature"].Value<string>());
node = manager.CreateCustomNodeInstance(functionId);
}
else if (type.ToString() == "CoreNodeModels.Formula")
{
var code = obj["Formula"].Value<string>();
var formulaConverter = new MigrateFormulaToDS();
string convertedCode = string.Empty;
bool conversionFailed = false;
try
{
convertedCode = formulaConverter.ConvertFormulaToDS(code);
}
catch (BuildHaltException)
{
node = DeserializeAsCBN(code + ";", obj, guid);
(node as CodeBlockNodeModel).FormulaMigrationWarning(Resources.FormulaDSConversionFailure);
conversionFailed = true;
}
if (!conversionFailed)
{
node = DeserializeAsCBN(convertedCode + ";", obj, guid);
(node as CodeBlockNodeModel).FormulaMigrationWarning(Resources.FormulaMigrated);
}
}
else
{
node = (NodeModel)obj.ToObject(type);
// We don't need to remap ports for any nodes with json constructors which pass ports
remapPorts = false;
}
if (remapPorts)
{
RemapPorts(node, inPorts, outPorts, resolver, manager.AsLogger());
}
// Cannot set Lacing directly as property is protected
node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication));
node.GUID = guid;
// Add references to the node and the ports to the reference resolver,
// so that they are available for entities which are deserialized later.
serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node);
foreach (var p in node.InPorts)
serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
foreach (var p in node.OutPorts)
serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p);
return node;
}
private DummyNode CreateDummyNode(JObject obj, string legacyAssembly, string functionName, PortModel[] inPorts, PortModel[] outPorts)
{
var inputcount = inPorts.Count();
var outputcount = outPorts.Count();
return new DummyNode(
obj["Id"].ToString(),
inputcount,
outputcount,
legacyAssembly,
functionName,
obj);
}
private DummyNode CreateDummyNode(JObject obj, string typeName, string legacyAssembly, string functionName, PortModel[] inPorts, PortModel[] outPorts)
{
var inputcount = inPorts.Count();
var outputcount = outPorts.Count();
return new DummyNode(
obj["Id"].ToString(),
inputcount,
outputcount,
legacyAssembly,
functionName,
typeName,
obj);
}
/// <summary>
/// Map old Guids to new Models in the IdReferenceResolver.
/// This method also sets portData from the deserialized ports onto the
/// newly created ports.
/// </summary>
/// <param name="node">The newly created node.</param>
/// <param name="inPorts">The deserialized input ports.</param>
/// <param name="outPorts">The deserialized output ports.</param>
/// <param name="resolver">The IdReferenceResolver used during deserialization.</param>
/// <param name="logger"></param>
private static void RemapPorts(NodeModel node, PortModel[] inPorts, PortModel[] outPorts, IdReferenceResolver resolver, ILogger logger)
{
foreach (var p in node.InPorts)
{
// Check that the port index is not out of range of the loaded ports
if (p.Index < inPorts.Length)
{
var deserializedPort = inPorts[p.Index];
resolver.AddToReferenceMap(deserializedPort.GUID, p);
setPortDataOnNewPort(p, deserializedPort);
}
else
{
if (logger != null)
{
logger.Log(
string.Format("while loading node {0} we could not find a port for the parameter {1} at index {2}",node.Name,p.Name,p.Index)
);
}
}
}
foreach (var p in node.OutPorts)
{
// Check that the port index is not out of range of the loaded ports
if (p.Index < outPorts.Length)
{
var deserializedPort = outPorts[p.Index];
resolver.AddToReferenceMap(deserializedPort.GUID, p);
setPortDataOnNewPort(p, deserializedPort);
}
else
{
if (logger != null)
{
logger.Log(
string.Format("while loading node {0} we could not find a port for the retrunkey {1} at index {2}", node.Name, p.Name, p.Index)
);
}
}
}
}
private static void setPortDataOnNewPort(PortModel newPort, PortModel deserializedPort )
{
// Set the appropriate properties on the new port.
newPort.GUID = deserializedPort.GUID;
newPort.UseLevels = deserializedPort.UseLevels;
newPort.Level = deserializedPort.Level;
newPort.KeepListStructure = deserializedPort.KeepListStructure;
newPort.UsingDefaultValue = deserializedPort.UsingDefaultValue;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanRead
{
get
{
return true;
}
}
public override bool CanWrite
{
get
{
return false;
}
}
}
///<Summary>
/// Converter for Description property in the NodeModel class.
///</Summary>
public class DescriptionConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(String));
}
/// When deserializing, we do not want to read this property from the file
/// so null is being returned. This is to convert the Description property
/// to the localized language.
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return null;
}
/// Serializing the description property.
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
}
/// <summary>
/// The WorkspaceConverter is used to serialize and deserialize WorkspaceModels.
/// Construction of a WorkspaceModel requires things like an EngineController,
/// a NodeFactory, and a Scheduler. These must be supplied at the time of
/// construction and should not be serialized.
/// </summary>
public class WorkspaceReadConverter : JsonConverter
{
LinterManager linterManager;
DynamoScheduler scheduler;
EngineController engine;
NodeFactory factory;
bool isTestMode;
bool verboseLogging;
internal readonly static string NodeLibraryDependenciesPropString = "NodeLibraryDependencies";
internal const string EXTENSION_WORKSPACE_DATA = "ExtensionWorkspaceData";
internal const string LINTING_PROP_STRING = "Linting";
public WorkspaceReadConverter(EngineController engine,
DynamoScheduler scheduler, NodeFactory factory, bool isTestMode, bool verboseLogging)
{
this.scheduler = scheduler;
this.engine = engine;
this.factory = factory;
this.isTestMode = isTestMode;
this.verboseLogging = verboseLogging;
}
public WorkspaceReadConverter(EngineController engine,
DynamoScheduler scheduler, NodeFactory factory, bool isTestMode, bool verboseLogging, LinterManager linterManager) :
this(engine, scheduler, factory, isTestMode, verboseLogging)
{
this.linterManager = linterManager;
}
public override bool CanConvert(Type objectType)
{
return typeof(WorkspaceModel).IsAssignableFrom(objectType);
}
public override bool CanWrite
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var isCustomNode = obj["IsCustomNode"].Value<bool>();
var description = obj["Description"].Value<string>();
var guidStr = obj["Uuid"].Value<string>();
var guid = Guid.Parse(guidStr);
var name = obj["Name"].Value<string>();
var elementResolver = obj["ElementResolver"].ToObject<ElementResolver>(serializer);
var nrc = (NodeReadConverter)serializer.Converters.First(c => c is NodeReadConverter);
nrc.ElementResolver = elementResolver;
var nodes = obj["Nodes"].ToObject<IEnumerable<NodeModel>>(serializer);
// Setting Inputs
// Required in headless mode by Dynamo Player that certain view properties are set back to NodeModel
var inputsToken = obj["Inputs"];
if (inputsToken != null)
{
var inputs = inputsToken.ToArray().Select(x =>
{
try
{ return x.ToObject<NodeInputData>(); }
catch (Exception ex)
{
engine?.AsLogger().Log(ex);
return null;
}
//dump nulls
}).Where(x => !(x is null)).ToList();
// Use the inputs to set the correct properties on the nodes.
foreach (var inputData in inputs)
{
var matchingNode = nodes.Where(x => x.GUID == inputData.Id).FirstOrDefault();
if (matchingNode != null)
{
matchingNode.IsSetAsInput = true;
matchingNode.Name = inputData.Name;
}
}
}
// Setting Outputs
var outputsToken = obj["Outputs"];
if (outputsToken != null)
{
var outputs = outputsToken.ToArray().Select(x => x.ToObject<NodeOutputData>()).ToList();
// Use the outputs to set the correct properties on the nodes.
foreach (var outputData in outputs)
{
var matchingNode = nodes.Where(x => x.GUID == outputData.Id).FirstOrDefault();
if (matchingNode != null)
{
matchingNode.IsSetAsOutput = true;
matchingNode.Name = outputData.Name;
}
}
}
#region Setting Inputs based on view layer info
// TODO: It is currently duplicating the effort with Input Block parsing which should be cleaned up once
// Dynamo supports both selection and drop down nodes in Inputs block
var view = obj["View"];
if (view != null && view["NodeViews"] != null)
{
var nodeViews = view["NodeViews"].ToList();
foreach (var nodeview in nodeViews)
{
Guid nodeGuid;
try
{
nodeGuid = Guid.Parse(nodeview["Id"].Value<string>());
var matchingNode = nodes.Where(x => x.GUID == nodeGuid).FirstOrDefault();
if (matchingNode != null)
{
matchingNode.IsSetAsInput = nodeview["IsSetAsInput"].Value<bool>();
matchingNode.IsSetAsOutput = nodeview["IsSetAsOutput"].Value<bool>();
matchingNode.IsFrozen = nodeview["Excluded"].Value<bool>();
matchingNode.Name = nodeview["Name"].Value<string>();
}
}
catch
{
continue;
}
}
}
#endregion
// notes
//TODO: Check this when implementing ReadJSON in ViewModel.
//var notes = obj["Notes"].ToObject<IEnumerable<NoteModel>>(serializer);
//if (notes.Any())
//{
// foreach(var n in notes)
// {
// serializer.ReferenceResolver.AddReference(serializer.Context, n.GUID.ToString(), n);
// }
//}
// connectors
// Although connectors are not used in the construction of the workspace
// we need to deserialize this collection, so that they connect to their
// relevant ports.
var connectors = obj["Connectors"].ToObject<IEnumerable<ConnectorModel>>(serializer);
IEnumerable<INodeLibraryDependencyInfo> workspaceReferences;
var nodeLibraryDependencies = new List<INodeLibraryDependencyInfo>();
var nodeLocalDefinitions = new List<INodeLibraryDependencyInfo>();
var externalFiles = new List<INodeLibraryDependencyInfo>();
if (obj[NodeLibraryDependenciesPropString] != null)
{
workspaceReferences = obj[NodeLibraryDependenciesPropString].ToObject<IEnumerable<INodeLibraryDependencyInfo>>(serializer);
//if deserialization failed, reset to empty.
if (workspaceReferences == null)
{
workspaceReferences = new List<INodeLibraryDependencyInfo>();
}
}
else
{
workspaceReferences = new List<INodeLibraryDependencyInfo>();
}
foreach(INodeLibraryDependencyInfo depInfo in workspaceReferences)
{
if (depInfo is PackageDependencyInfo)
{
nodeLibraryDependencies.Add(depInfo);
}
else if (depInfo is DependencyInfo && (depInfo.ReferenceType == ReferenceType.ZeroTouch || depInfo.ReferenceType == ReferenceType.DYFFile))
{
nodeLocalDefinitions.Add(depInfo);
}
else if (depInfo is DependencyInfo && depInfo.ReferenceType == ReferenceType.External)
{
externalFiles.Add(depInfo);
}
}
var info = new WorkspaceInfo(guid.ToString(), name, description, Dynamo.Models.RunType.Automatic);
// IsVisibleInDynamoLibrary and Category should be set explicitly for custom node workspace
if (obj["View"] != null && obj["View"]["Dynamo"] != null && obj["View"]["Dynamo"]["IsVisibleInDynamoLibrary"] != null)
{
info.IsVisibleInDynamoLibrary = obj["View"]["Dynamo"]["IsVisibleInDynamoLibrary"].Value<bool>();
}
if (obj["Category"] != null)
{
info.Category = obj["Category"].Value<string>();
}
// Build an empty annotations. Annotations are defined in the view block. If the file has View block
// serialize view block first and build the annotations.
var annotations = new List<AnnotationModel>();
// Build an empty notes. Notes are defined in the view block. If the file has View block
// serialize view block first and build the notes.
var notes = new List<NoteModel>();
#region Restore trace data
// Trace Data
Dictionary<Guid, List<CallSite.RawTraceData>> loadedTraceData = new Dictionary<Guid, List<CallSite.RawTraceData>>();
bool containsLegacyTraceData = false;
// Restore trace data if bindings are present in json
if (obj["Bindings"] != null && obj["Bindings"].Children().Count() > 0)
{
var wrc = serializer.Converters.First(c => c is WorkspaceReadConverter) as WorkspaceReadConverter;
if (wrc.engine.CurrentWorkspaceVersion < new Version(3, 0, 0))
{
containsLegacyTraceData = true;
}
else
{
JEnumerable<JToken> bindings = obj["Bindings"].Children();
// Iterate through bindings to extract nodeID's and bindingData (callsiteId & traceData)
foreach (JToken entity in bindings)
{
Guid nodeId = Guid.Parse(entity["NodeId"].ToString());
string bindingString = entity["Binding"].ToString();
// Key(callsiteId) : Value(traceData)
Dictionary<string, string> bindingData =
JsonConvert.DeserializeObject<Dictionary<string, string>>(bindingString);
List<CallSite.RawTraceData> callsiteTraceData = new List<CallSite.RawTraceData>();
foreach (KeyValuePair<string, string> pair in bindingData)
{
callsiteTraceData.Add(new CallSite.RawTraceData(pair.Key, pair.Value));
}
loadedTraceData.Add(nodeId, callsiteTraceData);
}
}
}
#endregion
WorkspaceModel ws;
if (isCustomNode)
{
ws = new CustomNodeWorkspaceModel(factory, nodes, notes, annotations,
Enumerable.Empty<PresetModel>(), elementResolver, info);
}
else
{
var homeWorkspace = new HomeWorkspaceModel(guid, engine, scheduler, factory,
loadedTraceData, nodes, notes, annotations,
Enumerable.Empty<PresetModel>(), elementResolver,
info, verboseLogging, isTestMode, linterManager);
// EnableLegacyPolyCurveBehavior
var enable = obj[nameof(HomeWorkspaceModel.EnableLegacyPolyCurveBehavior)];
homeWorkspace.EnableLegacyPolyCurveBehavior = enable?.Value<bool?>();
// Thumbnail
if (obj.TryGetValue(nameof(HomeWorkspaceModel.Thumbnail), StringComparison.OrdinalIgnoreCase, out JToken thumbnail))
homeWorkspace.Thumbnail = thumbnail.ToString();
// GraphDocumentationLink
if (obj.TryGetValue(nameof(HomeWorkspaceModel.GraphDocumentationURL), StringComparison.OrdinalIgnoreCase, out JToken helpLink))
{
if (Uri.TryCreate(helpLink.ToString(), UriKind.Absolute, out Uri uri))
homeWorkspace.GraphDocumentationURL = uri;
}
// ExtensionData
homeWorkspace.ExtensionData = GetExtensionData(serializer, obj);
// If there is a active linter serialized in the graph we set it to the active linter else set the default None.
SetActiveLinter(obj);
ws = homeWorkspace;
}
ws.NodeLibraryDependencies = nodeLibraryDependencies;
ws.NodeLocalDefinitions = nodeLocalDefinitions;
ws.ExternalFiles = externalFiles;
if (obj.TryGetValue(nameof(WorkspaceModel.Author), StringComparison.OrdinalIgnoreCase, out JToken author))
ws.Author = author.ToString();
ws.ContainsLegacyTraceData = containsLegacyTraceData;
return ws;
}
private void SetActiveLinter(JObject obj)
{
while (true)
{
if (linterManager is null ||
!obj.TryGetValue(LINTING_PROP_STRING, StringComparison.OrdinalIgnoreCase, out JToken linter))
break;
if (!linter.HasValues)
break;
var activeLinterId = linter.Value<string>(LinterManagerConverter.ACTIVE_LINTER_ID_OBJECT_NAME);
if (activeLinterId is null)
break;
var linterDescriptor = linterManager.AvailableLinters
.Where(x => x.Id == activeLinterId)
.FirstOrDefault();
if (linterDescriptor is null)
break;
linterManager.SetActiveLinter(linterDescriptor, false);
return;
}
linterManager?.SetDefaultLinter();
}
private static List<ExtensionData> GetExtensionData(JsonSerializer serializer, JObject obj)
{
if (!obj.TryGetValue(EXTENSION_WORKSPACE_DATA, StringComparison.OrdinalIgnoreCase, out JToken extensionData))
return new List<ExtensionData>();
if (!(extensionData is JArray array))
return new List<ExtensionData>();
return array.ToObject<List<ExtensionData>>(serializer);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
/// <summary>
/// WorkspaceWriteConverter is used for serializing Workspaces to JSON.
/// </summary>
public class WorkspaceWriteConverter : JsonConverter
{
private EngineController engine;
public WorkspaceWriteConverter(EngineController engine = null)
{
if (engine != null)
{
this.engine = engine;
}
}
public override bool CanConvert(Type objectType)
{
return typeof(WorkspaceModel).IsAssignableFrom(objectType);
}
public override bool CanRead
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ws = (WorkspaceModel)value;
bool isCustomNode = value is CustomNodeWorkspaceModel;
writer.WriteStartObject();
writer.WritePropertyName("Uuid");
if (isCustomNode)
writer.WriteValue((ws as CustomNodeWorkspaceModel).CustomNodeId.ToString());
else
writer.WriteValue(ws.Guid.ToString());
// TODO: revisit IsCustomNode during DYN/DYF convergence
writer.WritePropertyName("IsCustomNode");
writer.WriteValue(value is CustomNodeWorkspaceModel ? true : false);
if (isCustomNode)
{
writer.WritePropertyName("Category");
writer.WriteValue(((CustomNodeWorkspaceModel)value).Category);
}
// Description
writer.WritePropertyName("Description");
if (isCustomNode)
writer.WriteValue(((CustomNodeWorkspaceModel)ws).Description);
else
writer.WriteValue(ws.Description);
writer.WritePropertyName("Name");
writer.WriteValue(ws.Name);
// Element resolver
writer.WritePropertyName("ElementResolver");
serializer.Serialize(writer, ws.ElementResolver);
// Inputs
writer.WritePropertyName("Inputs");
// Find nodes which are inputs and get their inputData if its not null.
var inputNodeDatas = ws.Nodes.Where((node) => node.IsSetAsInput == true && node.InputData != null)
.Select(inputNode => inputNode.InputData).ToList();
serializer.Serialize(writer, inputNodeDatas);
// Outputs
writer.WritePropertyName("Outputs");
// Find nodes which are outputs and get their outputData if its not null.
var outputNodeDatas = ws.Nodes.Where((node) => node.IsSetAsOutput == true && node.OutputData != null)
.Select(outputNode => outputNode.OutputData).ToList();
serializer.Serialize(writer, outputNodeDatas);
// Nodes
writer.WritePropertyName("Nodes");
serializer.Serialize(writer, ws.Nodes);
// Connectors
writer.WritePropertyName("Connectors");
serializer.Serialize(writer, ws.Connectors);
// Dependencies
writer.WritePropertyName("Dependencies");
writer.WriteStartArray();
var functions = ws.Nodes.Where(n => n is Function);
if (functions.Any())
{
var deps = functions.Cast<Function>().Select(f => f.Definition.FunctionId).Distinct();
foreach (var d in deps)
{
writer.WriteValue(d);
}
}
writer.WriteEndArray();
// Join NodeLibraryDependencies & NodeLocalDefinitions and serialze them.
writer.WritePropertyName(WorkspaceReadConverter.NodeLibraryDependenciesPropString);
IEnumerable<INodeLibraryDependencyInfo> referencesList = ws.NodeLibraryDependencies;
referencesList = referencesList.Concat(ws.NodeLocalDefinitions).Concat(ws.ExternalFiles);
foreach (INodeLibraryDependencyInfo item in referencesList)
{
string refName = string.Empty;
string refExtension = System.IO.Path.GetExtension(item.Name);
Actions refType = Actions.ExternalReferences;
if (item.ReferenceType == ReferenceType.Package)
{
refName = item.Name + (item.Version != null ? " " + item.Version.ToString(3) : null);
refType = Actions.PackageReferences;
}
else if (item.ReferenceType == ReferenceType.ZeroTouch || item.ReferenceType == ReferenceType.DYFFile || item.ReferenceType == ReferenceType.NodeModel || item.ReferenceType == ReferenceType.DSFile)
{
refName = refExtension;
refType = Actions.LocalReferences;
}
else
{
refName = refExtension;
}
Logging.Analytics.TrackEvent(refType, Categories.WorkspaceReferences, refName);
}
serializer.Serialize(writer, referencesList);
if (!isCustomNode && ws is HomeWorkspaceModel hws)
{
// EnableLegacyPolyCurveBehavior
writer.WritePropertyName(nameof(HomeWorkspaceModel.EnableLegacyPolyCurveBehavior));
serializer.Serialize(writer, hws.EnableLegacyPolyCurveBehavior);
// Thumbnail
writer.WritePropertyName(nameof(HomeWorkspaceModel.Thumbnail));
writer.WriteValue(hws.Thumbnail);
// GraphDocumentaionLink
writer.WritePropertyName(nameof(HomeWorkspaceModel.GraphDocumentationURL));
writer.WriteValue(hws.GraphDocumentationURL);
// ExtensionData
writer.WritePropertyName(WorkspaceReadConverter.EXTENSION_WORKSPACE_DATA);
serializer.Serialize(writer, hws.ExtensionData);
}
// Graph Author
writer.WritePropertyName(nameof(WorkspaceModel.Author));
writer.WriteValue(ws.Author);
// Linter
if(!(ws.linterManager is null))
{
serializer.Serialize(writer, ws.linterManager);
}
if (engine != null)
{
// Bindings
writer.WritePropertyName(Configurations.BindingsTag);
writer.WriteStartArray();
// Selecting all nodes that are either a DSFunction,
// a DSVarArgFunction or a CodeBlockNodeModel into a list.
var nodeGuids =
ws.Nodes.Where(
n => n is DSFunction || n is DSVarArgFunction || n is CodeBlockNodeModel || n is Function ||
n.GetType().GetCustomAttributes(typeof(DynamoServices.RegisterForTraceAttribute),false).Any() )
.Select(n => n.GUID);
var nodeTraceDataList = engine.LiveRunnerRuntimeCore.RuntimeData.GetTraceDataForNodes(nodeGuids,
this.engine.LiveRunnerRuntimeCore.DSExecutable);
// Serialize given node-data-list pairs into an Json.
if (nodeTraceDataList.Any())
{
foreach (var pair in nodeTraceDataList)
{
writer.WriteStartObject();
writer.WritePropertyName(Configurations.NodeIdAttribName);
// Set the node ID attribute for this element.
var nodeGuid = pair.Key.ToString();
writer.WriteValue(nodeGuid);
writer.WritePropertyName(Configurations.BingdingTag);
// D4R binding
writer.WriteStartObject();
foreach (var data in pair.Value)
{
writer.WritePropertyName(data.ID);
writer.WriteValue(data.Data);
}
writer.WriteEndObject();
writer.WriteEndObject();
}
}
writer.WriteEndArray();
writer.WriteEndObject();
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class LinterManagerConverter : JsonConverter
{
private ILogger logger;