public void SetUp() { nodeFactory = new NodeFactory(ModelType.Truss2D); node1 = nodeFactory.CreateFor2DTruss(0, 0); node2 = nodeFactory.CreateFor2DTruss(0, 1); SUT = new ElementFactory(ModelType.Truss2D); }
/// <summary> /// Load a WorkspaceModel from json. If the WorkspaceModel is a HomeWorkspaceModel /// it will be set as the current workspace. /// </summary> /// <param name="json"></param> public static WorkspaceModel LoadWorkspaceFromJson(string json, LibraryServices libraryServices, EngineController engineController, DynamoScheduler scheduler, NodeFactory factory, bool isTestMode, bool verboseLogging, CustomNodeManager manager) { var settings = new JsonSerializerSettings { Error = (sender, args) => { args.ErrorContext.Handled = true; Console.WriteLine(args.ErrorContext.Error); }, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, TypeNameHandling = TypeNameHandling.Auto, Formatting = Formatting.Indented, Converters = new List<JsonConverter>{ new ConnectorConverter(), new AnnotationConverter(), new WorkspaceConverter(engineController, scheduler, factory, isTestMode, verboseLogging), new NodeModelConverter(manager, libraryServices), }, ReferenceResolverProvider = () => { return new IdReferenceResolver(); } }; var result = ReplaceTypeDeclarations(json, true); var ws = JsonConvert.DeserializeObject<WorkspaceModel>(result, settings); return ws; }
public static int Main() { NodeFactory f = new NodeFactory(); Node notNode = new Node("NotNode"); notNode.NodeType = NodeType.Not; notNode.Child = new Node("otherNode"); notNode.Child.NodeType = NodeType.Other; Node trueNode = new Node("True"); Node falseNode = new Node("False"); Node resultNode = f.Conditional(notNode, trueNode, falseNode); if (resultNode.name == "True") { System.Console.WriteLine("pass"); return 100; } else { System.Console.WriteLine("Failed"); return -1; } }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder objData = new ObjectDataBuilder(factory); objData.RequirePointerAlignment(); objData.DefinedSymbols.Add(this); ObjectAndOffsetSymbolNode startNode = new ObjectAndOffsetSymbolNode(this, 0, "__modules_a"); ObjectAndOffsetSymbolNode endNode = new ObjectAndOffsetSymbolNode(this, 0, "__modules_z"); if (factory.Target.OperatingSystem != Internal.TypeSystem.TargetOS.Windows) { // Temporary work-around for Linux / OSX until CLI is updated objData.DefinedSymbols.Add(startNode); } objData.EmitPointerReloc(factory.ReadyToRunHeader); if (factory.Target.OperatingSystem != Internal.TypeSystem.TargetOS.Windows) { // Temporary work-around for Linux / OSX until CLI is updated endNode.SetSymbolOffset(objData.CountBytes); objData.DefinedSymbols.Add(endNode); objData.EmitZeroPointer(); } return objData.ToObjectData(); }
public void UpdateNode(NodeFactory.Node node) { lock (this) { // validate sitemap BuildSiteMap(); SiteMapNode n; if (!m_nodes.ContainsKey(node.Id.ToString())) { n = createNode(node.Id.ToString(), node.Name, node.GetProperty(m_defaultDescriptionAlias) != null ? node.GetProperty(m_defaultDescriptionAlias).Value : "", node.Url, findRoles(node.Id, node.Path)); string parentNode = node.Parent == null ? "-1" : node.Parent.Id.ToString(); try { AddNode(n, m_nodes[parentNode]); } catch (Exception ex) { BusinessLogic.Log.Add( LogTypes.Error, -1, String.Format("Error adding node with url '{0}' to SiteMapProvider: {1}", node.Name, ex)); } } else { n = m_nodes[node.Id.ToString()]; n.Url = node.Url; n.Description = node.GetProperty(m_defaultDescriptionAlias) != null ? node.GetProperty(m_defaultDescriptionAlias).Value : ""; n.Title = node.Name; n.Roles = findRoles(node.Id, node.Path).Split(",".ToCharArray()); } } }
private void CreateFiniteElement1D(double startX, double startY, double startZ, double endX, double endY, double endZ) { nodeFactory = new NodeFactory(ModelType.Truss3D); start = nodeFactory.Create(startX, startY, startZ); end = nodeFactory.Create(endX, endY, endZ); elementFactory = new ElementFactory(ModelType.Truss3D); SUT = elementFactory.CreateLinearConstantSpring(start, end, 0); }
/// <summary> /// Initializes a new instance of the <see cref="CustomNodeWorkspaceModel"/> class /// by given information about it and node factory /// </summary> /// <param name="info">Information for creating custom node workspace</param> /// <param name="factory">Node factory to create nodes</param> public CustomNodeWorkspaceModel(WorkspaceInfo info, NodeFactory factory) : this(factory, Enumerable.Empty<NodeModel>(), Enumerable.Empty<NoteModel>(), Enumerable.Empty<AnnotationModel>(), Enumerable.Empty<PresetModel>(), new ElementResolver(), info) { }
public Calc() { m_NodeFactory = new NodeFactory(); m_NodeFactory.Register("+", typeof(AdditionNode)); m_NodeFactory.Register("*", typeof(MultiplicationNode)); m_NodeFactory.Register("-", typeof(SubtractionNode)); m_NodeFactory.Register("/", typeof(DivisionNode)); }
public void CanCreateAndAddtoTheRepository() { NodeRepository repository = new NodeRepository(ModelType.Truss1D); this.SUT = new NodeFactory(ModelType.Truss1D, repository); Assert.AreEqual(0, repository.Count); this.SUT.Create(0); Assert.AreEqual(1, repository.Count); }
public CustomNodeWorkspaceModel( WorkspaceInfo info, NodeFactory factory) : this( factory, Enumerable.Empty<NodeModel>(), Enumerable.Empty<NoteModel>(), Enumerable.Empty<AnnotationModel>(), info) { }
private static IEnumerable<NodeModel> LoadNodesFromXml(XmlDocument xmlDoc, NodeFactory nodeFactory, ElementResolver resolver) { XmlNodeList elNodes = xmlDoc.GetElementsByTagName("Elements"); if (elNodes.Count == 0) elNodes = xmlDoc.GetElementsByTagName("dynElements"); XmlNode elNodesList = elNodes[0]; return from XmlElement elNode in elNodesList.ChildNodes select LoadNodeFromXml(elNode, SaveContext.File, nodeFactory, resolver); }
public void SetUp() { this.nodeFactory = new NodeFactory(ModelType.Truss1D); this.start = nodeFactory.Create(0); this.end = nodeFactory.Create(1); this.elementFactory = new ElementFactory(ModelType.Truss1D); this.spring = elementFactory.CreateLinearConstantSpring(start, end, 2); this.SUT = new LinearTrussStiffnessMatrixBuilder(spring); }
protected void CreateAndStore2DSpringFromOriginTo(double x, double z) { this.nodeFactory = new NodeFactory(ModelType.Truss2D); this.start = nodeFactory.CreateFor2DTruss(0, 0); this.end = nodeFactory.CreateFor2DTruss(x, z); this.elementFactory = new ElementFactory(ModelType.Truss2D); this.spring = elementFactory.CreateLinearConstantSpring(this.start, this.end, 1); this.SUT = new LinearTrussStiffnessMatrixBuilder(this.spring); }
protected void CreateAndStore3DSpringFromOriginTo(double x, double y, double z) { nodeFactory = new NodeFactory(ModelType.Truss3D); start = nodeFactory.Create(0, 0, 0); end = nodeFactory.Create(x, y, z); elementFactory = new ElementFactory(ModelType.Truss3D); this.spring = elementFactory.CreateLinearConstantSpring(start, end, 1); this.SUT = new LinearTrussStiffnessMatrixBuilder(this.spring); }
public void SetUp() { nodeFactory = new NodeFactory(ModelType.Frame2D); start = nodeFactory.CreateFor2DTruss(0, 0); end = nodeFactory.CreateFor2DTruss(1, 0); elementFactory = new ElementFactory(ModelType.Frame2D); material = new GenericElasticMaterial(0, 1, 0, 1); section = new GenericCrossSection(1, 1, 1, 1); beam = elementFactory.CreateLinear3DBeam(start, end, material, section); SUT = new Linear3DBernoulliBeamStiffnessMatrixBuilder(beam); }
private static Tree BuildTree(IEnumerable<Type> types, string rootName) { var nodeFactory = new NodeFactory(); var tree = new Tree(nodeFactory, rootName); foreach (var type in types) { var fullName = type.FullName; tree.Add(fullName); } return tree; }
private void TestWriteToStoreDatasetsHandler(IGenericIOManager manager) { NodeFactory factory = new NodeFactory(); INode a = factory.CreateUriNode(new Uri("http://example.org/a")); INode b = factory.CreateUriNode(new Uri("http://example.org/b")); INode c = factory.CreateUriNode(new Uri("http://example.org/c")); INode d = factory.CreateUriNode(new Uri("http://example.org/d")); Uri graphB = new Uri("http://example.org/graphs/b"); Uri graphD = new Uri("http://example.org/graphs/d"); //Try to ensure that the target Graphs do not exist if (manager.DeleteSupported) { manager.DeleteGraph(TestGraphUri); manager.DeleteGraph(graphB); manager.DeleteGraph(graphD); } else { Graph g = new Graph(); g.BaseUri = TestGraphUri; manager.SaveGraph(g); g.BaseUri = graphB; manager.SaveGraph(g); g.BaseUri = graphD; manager.SaveGraph(g); } //Do the parsing and thus the loading WriteToStoreHandler handler = new WriteToStoreHandler(manager, TestGraphUri); NQuadsParser parser = new NQuadsParser(); parser.Load(handler, new StreamParams("writetostore.nq")); //Load the expected Graphs Graph def = new Graph(); manager.LoadGraph(def, TestGraphUri); Graph gB = new Graph(); manager.LoadGraph(gB, graphB); Graph gD = new Graph(); manager.LoadGraph(gD, graphD); Assert.AreEqual(2, def.Triples.Count, "Should be two triples in the default Graph"); Assert.IsTrue(def.ContainsTriple(new Triple(a, a, a)), "Default Graph should have the a triple"); Assert.AreEqual(1, gB.Triples.Count, "Should be one triple in the b Graph"); Assert.IsTrue(gB.ContainsTriple(new Triple(b, b, b)), "b Graph should have the b triple"); Assert.IsTrue(def.ContainsTriple(new Triple(c, c, c)), "Default Graph should have the c triple"); Assert.AreEqual(1, gD.Triples.Count, "Should be one triple in the d Graph"); Assert.IsTrue(gD.ContainsTriple(new Triple(d, d, d)), "d Graph should have the d triple"); }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder objData = new ObjectDataBuilder(factory); objData.RequirePointerAlignment(); objData.DefinedSymbols.Add(this); if (factory.Target.OperatingSystem == Internal.TypeSystem.TargetOS.OSX) { objData.EmitPointerReloc(factory.JumpThunk((ExternSymbolNode)factory.ExternSymbol("RegisterReadyToRunModule"), factory.ReadyToRunHeader)); } else { objData.EmitPointerReloc(factory.ReadyToRunHeader); } return objData.ToObjectData(); }
public CustomNodeWorkspaceModel( NodeFactory factory, IEnumerable<NodeModel> e, IEnumerable<NoteModel> n, IEnumerable<AnnotationModel> a, IEnumerable<PresetModel> presets, ElementResolver elementResolver, WorkspaceInfo info) : base(e, n,a, info, factory,presets, elementResolver) { HasUnsavedChanges = false; CustomNodeId = Guid.Parse(info.ID); Category = info.Category; Description = info.Description; PropertyChanged += OnPropertyChanged; }
public CustomNodeWorkspaceModel( NodeFactory factory, IEnumerable<NodeModel> nodes, IEnumerable<NoteModel> notes, IEnumerable<AnnotationModel> annotations, IEnumerable<PresetModel> presets, ElementResolver elementResolver, WorkspaceInfo info) : base(nodes, notes,annotations, info, factory,presets, elementResolver) { HasUnsavedChanges = false; CustomNodeId = Guid.Parse(info.ID); Category = info.Category; Description = info.Description; IsVisibleInDynamoLibrary = info.IsVisibleInDynamoLibrary; PropertyChanged += OnPropertyChanged; }
public CustomNodeWorkspaceModel( NodeFactory factory, IEnumerable<NodeModel> e, IEnumerable<NoteModel> n, IEnumerable<AnnotationModel> a, WorkspaceInfo info, ElementResolver elementResolver = null) : base(e, n,a,info, factory) { HasUnsavedChanges = false; CustomNodeId = Guid.Parse(info.ID); Category = info.Category; Description = info.Description; if (elementResolver != null) { ElementResolver.CopyResolutionMap(elementResolver); } PropertyChanged += OnPropertyChanged; }
protected DependencyAnalyzerBase <NodeFactory> CreateDependencyGraph(NodeFactory factory, IComparer <DependencyNodeCore <NodeFactory> > comparer = null) { return(_dependencyTrackingLevel.CreateDependencyGraph(factory, comparer)); }
/// <summary> /// Constructs a new instance of <see cref="DelegateCreationInfo"/> set up to construct a delegate of type /// '<paramref name="delegateType"/>' pointing to '<paramref name="targetMethod"/>'. /// </summary> public static DelegateCreationInfo Create(TypeDesc delegateType, MethodDesc targetMethod, NodeFactory factory) { var context = (CompilerTypeSystemContext)delegateType.Context; var systemDelegate = targetMethod.Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; int paramCountTargetMethod = targetMethod.Signature.Length; if (!targetMethod.Signature.IsStatic) { paramCountTargetMethod++; } DelegateInfo delegateInfo = context.GetDelegateInfo(delegateType.GetTypeDefinition()); int paramCountDelegateClosed = delegateInfo.Signature.Length + 1; bool closed = false; if (paramCountDelegateClosed == paramCountTargetMethod) { closed = true; } else { Debug.Assert(paramCountDelegateClosed == paramCountTargetMethod + 1); } if (targetMethod.Signature.IsStatic) { MethodDesc invokeThunk; MethodDesc initMethod; if (!closed) { // Open delegate to a static method if (targetMethod.IsNativeCallable) { // If target method is native callable, create a reverse PInvoke delegate initMethod = systemDelegate.GetKnownMethod("InitializeReversePInvokeThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ReversePinvokeThunk]; // You might hit this when the delegate is generic: you need to make the delegate non-generic. // If the code works on Project N, it's because the delegate is used in connection with // AddrOf intrinsic (please validate that). We don't have the necessary AddrOf expansion in // the codegen to make this work without actually constructing the delegate. You can't construct // the delegate if it's generic, even on Project N. // TODO: Make this throw something like "TypeSystemException.InvalidProgramException"? Debug.Assert(invokeThunk != null, "Delegate with a non-native signature for a NativeCallable method"); } else { initMethod = systemDelegate.GetKnownMethod("InitializeOpenStaticThunk", null); invokeThunk = delegateInfo.Thunks[DelegateThunkKind.OpenStaticThunk]; } } else { // Closed delegate to a static method (i.e. delegate to an extension method that locks the first parameter) invokeThunk = delegateInfo.Thunks[DelegateThunkKind.ClosedStaticThunk]; initMethod = systemDelegate.GetKnownMethod("InitializeClosedStaticThunk", null); } var instantiatedDelegateType = delegateType as InstantiatedType; if (instantiatedDelegateType != null) { invokeThunk = context.GetMethodForInstantiatedType(invokeThunk, instantiatedDelegateType); } return(new DelegateCreationInfo( factory.MethodEntrypoint(initMethod), factory.MethodEntrypoint(targetMethod), factory.MethodEntrypoint(invokeThunk))); } else { if (!closed) { throw new NotImplementedException("Open instance delegates"); } bool useUnboxingStub = targetMethod.OwningType.IsValueType; string initializeMethodName = "InitializeClosedInstance"; if (targetMethod.HasInstantiation) { Debug.Assert(!targetMethod.IsVirtual, "TODO: delegate to generic virtual method"); // Closed delegates to generic instance methods need to be constructed through a slow helper that // checks for the fat function pointer case (function pointer + instantiation argument in a single // pointer) and injects an invocation thunk to unwrap the fat function pointer as part of // the invocation if necessary. initializeMethodName = "InitializeClosedInstanceSlow"; } return(new DelegateCreationInfo( factory.MethodEntrypoint(systemDelegate.GetKnownMethod(initializeMethodName, null)), factory.MethodEntrypoint(targetMethod, useUnboxingStub))); } }
public override void RegisterAtFactory(NodeFactory factory) { factory.AddNodeType("Not", this); }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { // This node does not trigger generation of other nodes. if (relocsOnly) { return(new ObjectData(Array.Empty <byte>(), Array.Empty <Relocation>(), 1, new ISymbolDefinitionNode[] { this })); } List <CustomAttributeEntry> customAttributeEntries = GetCustomAttributeEntries(); int countOfEntries = customAttributeEntries.Count; if (countOfEntries == 0) { return(new ObjectData(Array.Empty <byte>(), Array.Empty <Relocation>(), 1, new ISymbolDefinitionNode[] { this })); } // Buckets have 8 entries uint minTableBucketCount = (uint)(countOfEntries / 8) + 1; uint bucketCount = 1; // Bucket count must be power of two while (bucketCount < minTableBucketCount) { bucketCount *= 2; } // Resize the array. bool tryAgainWithBiggerTable = false; int countOfRetries = 0; ushort[] pTable; do { tryAgainWithBiggerTable = false; uint actualSizeOfTable = bucketCount * 8; // Buckets have 8 entries in them pTable = new ushort[actualSizeOfTable]; uint[] state = new uint[] { 729055690, 833774698, 218408041, 493449127 }; // Attempt to fill table foreach (var customAttributeEntry in customAttributeEntries) { string name = customAttributeEntry.TypeNamespace + "." + customAttributeEntry.TypeName; // This hashing algorithm MUST match exactly the logic in NativeCuckooFilter int hashOfAttribute = ReadyToRunHashCode.NameHashCode(name); uint hash = unchecked ((uint)ReadyToRunHashCode.CombineTwoValuesIntoHash((uint)hashOfAttribute, (uint)customAttributeEntry.Parent)); ushort fingerprint = (ushort)(hash >> 16); if (fingerprint == 0) { fingerprint = 1; } uint bucketAIndex = hash % bucketCount; uint fingerprintHash = (uint)fingerprint; uint bucketBIndex = (bucketAIndex ^ (fingerprintHash % bucketCount)); Debug.Assert(bucketAIndex == (bucketBIndex ^ (fingerprintHash % bucketCount))); if ((XorShift128(state) & 1) != 0) // Randomly choose which bucket to attempt to fill first { uint temp = bucketAIndex; bucketAIndex = bucketBIndex; bucketBIndex = temp; } Func <uint, ushort, bool> hasEntryInBucket = (uint bucketIndex, ushort fprint) => { for (int i = 0; i < 8; i++) { if (pTable[(bucketIndex * 8) + i] == fprint) { return(true); } } return(false); }; Func <uint, bool> isEmptyEntryInBucket = (uint bucketIndex) => { for (int i = 0; i < 8; i++) { if (pTable[(bucketIndex * 8) + i] == 0) { return(true); } } return(false); }; Action <uint, ushort> fillEmptyEntryInBucket = (uint bucketIndex, ushort fprint) => { for (int i = 0; i < 8; i++) { if (pTable[(bucketIndex * 8) + i] == 0) { pTable[(bucketIndex * 8) + i] = fprint; return; } } Debug.Assert(false, "Not possible to reach here"); }; // Scan for pre-existing fingerprint entry in buckets if (hasEntryInBucket(bucketAIndex, fingerprint) || hasEntryInBucket(bucketBIndex, fingerprint)) { continue; } // Determine if there is space in a bucket to add a new entry if (isEmptyEntryInBucket(bucketAIndex)) { fillEmptyEntryInBucket(bucketAIndex, fingerprint); continue; } if (isEmptyEntryInBucket(bucketBIndex)) { fillEmptyEntryInBucket(bucketBIndex, fingerprint); continue; } bool success = false; int MaxNumKicks = 256; // Note, that bucketAIndex itself was chosen randomly above. for (int n = 0; !success && n < MaxNumKicks; n++) { // Randomly swap an entry in bucket bucketAIndex with fingerprint uint entryIndexInBucket = XorShift128(state) & 0x7; ushort temp = fingerprint; fingerprint = pTable[(bucketAIndex * 8) + entryIndexInBucket]; pTable[(bucketAIndex * 8) + entryIndexInBucket] = temp; // Find other bucket fingerprintHash = (uint)fingerprint; bucketAIndex = bucketAIndex ^ (fingerprintHash % bucketCount); if (isEmptyEntryInBucket(bucketAIndex)) { fillEmptyEntryInBucket(bucketAIndex, fingerprint); success = true; } } if (success) { continue; } tryAgainWithBiggerTable = true; } if (tryAgainWithBiggerTable) { // bucket entry kicking path requires bucket counts to be power of two in size due to use of xor to retrieve second hash bucketCount *= 2; } }while(tryAgainWithBiggerTable && ((countOfRetries++) < 2)); byte[] result; if (tryAgainWithBiggerTable) { result = Array.Empty <byte>(); } else { result = new byte[pTable.Length * 2]; for (int i = 0; i < pTable.Length; i++) { result[i * 2] = (byte)(pTable[i] % 256); result[i * 2 + 1] = (byte)(pTable[i] >> 8); } } ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialAlignment(16); builder.AddSymbol(this); builder.EmitBytes(result); return(builder.ToObjectData());; }
public static IElement GetInstance(string value) { return(new Description(NodeFactory.GetInstanceFromString(value))); }
public MetadataGeneration(NodeFactory factory) { _nodeFactory = factory; }
protected WorkspaceModel( IEnumerable<NodeModel> e, IEnumerable<NoteModel> n, IEnumerable<AnnotationModel> a, WorkspaceInfo info, NodeFactory factory, IEnumerable<PresetModel> presets) { guid = Guid.NewGuid(); nodes = new ObservableCollection<NodeModel>(e); notes = new ObservableCollection<NoteModel>(n); annotations = new ObservableCollection<AnnotationModel>(a); // Set workspace info from WorkspaceInfo object Name = info.Name; X = info.X; Y = info.Y; FileName = info.FileName; Zoom = info.Zoom; HasUnsavedChanges = false; LastSaved = DateTime.Now; WorkspaceVersion = AssemblyHelper.GetDynamoVersion(); undoRecorder = new UndoRedoRecorder(this); NodeFactory = factory; this.presets = new List<PresetModel>(presets); // Update ElementResolver from nodeGraph.Nodes (where node is CBN) ElementResolver = new ElementResolver(); foreach (var node in nodes) { RegisterNode(node); var cbn = node as CodeBlockNodeModel; if (cbn != null && cbn.ElementResolver != null) { ElementResolver.CopyResolutionMap(cbn.ElementResolver); } } foreach (var connector in Connectors) RegisterConnector(connector); SetModelEventOnAnnotation(); }
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, TypeDesc type) { TypeMetadataNode.GetMetadataDependencies(ref dependencies, factory, type, "Reflectable type"); // If we don't have precise field usage information, apply policy that all fields that // are eligible to have metadata get metadata. if (!_hasPreciseFieldUsageInformation) { TypeDesc typeDefinition = type.GetTypeDefinition(); foreach (FieldDesc field in typeDefinition.GetFields()) { if ((GetMetadataCategory(field) & MetadataCategory.Description) != 0) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.FieldMetadata(field), "Field of a reflectable type"); } } } }
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(); } }
public RootingServiceProvider(NodeFactory factory, RootAdder rootAdder) { _factory = factory; _rootAdder = rootAdder; }
internal ILScanResults(DependencyAnalyzerBase <NodeFactory> graph, NodeFactory factory) : base(graph, factory) { }
internal CompilationResults(DependencyAnalyzerBase <NodeFactory> graph, NodeFactory factory) { _graph = graph; _factory = factory; }
public bool HasFixedSlotVTable(TypeDesc type) { return(NodeFactory.VTable(type).HasFixedSlots); }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { // This node does not trigger generation of other nodes. if (relocsOnly) { return(new ObjectData(Array.Empty <byte>(), Array.Empty <Relocation>(), 1, new ISymbolDefinitionNode[] { this })); } Dictionary <EcmaMethod, HashSet <EcmaMethod> > inlineeToInliners = new Dictionary <EcmaMethod, HashSet <EcmaMethod> >(); // Build a map from inlinee to the list of inliners // We are only interested in the generic definitions of these. foreach (MethodWithGCInfo methodNode in factory.EnumerateCompiledMethods()) { MethodDesc[] inlinees = methodNode.InlinedMethods; MethodDesc inliner = methodNode.Method; EcmaMethod inlinerDefinition = (EcmaMethod)inliner.GetTypicalMethodDefinition(); if (inlinerDefinition.Module != _module) { // Only encode inlining info for inliners within the active module continue; } foreach (MethodDesc inlinee in inlinees) { MethodDesc inlineeDefinition = inlinee.GetTypicalMethodDefinition(); if (!(inlineeDefinition is EcmaMethod ecmaInlineeDefinition)) { // We don't record non-ECMA methods because they don't have tokens that // diagnostic tools could reason about anyway. continue; } if (!factory.CompilationModuleGroup.VersionsWithMethodBody(inlinee)) { // We cannot record inlining info across version bubble as cross-bubble assemblies // are not guaranteed to preserve token values. Only non-versionable methods may be // inlined across the version bubble. Debug.Assert(inlinee.IsNonVersionable()); continue; } if (!inlineeToInliners.TryGetValue(ecmaInlineeDefinition, out HashSet <EcmaMethod> inliners)) { inliners = new HashSet <EcmaMethod>(); inlineeToInliners.Add(ecmaInlineeDefinition, inliners); } inliners.Add((EcmaMethod)inlinerDefinition); } } // Serialize the map as a hash table NativeWriter writer = new NativeWriter(); Section section = writer.NewSection(); VertexHashtable hashtable = new VertexHashtable(); section.Place(hashtable); foreach (var inlineeWithInliners in inlineeToInliners) { EcmaMethod inlinee = inlineeWithInliners.Key; int inlineeRid = MetadataTokens.GetRowNumber(inlinee.Handle); int hashCode = ReadyToRunHashCode.ModuleNameHashCode(inlinee.Module); hashCode ^= inlineeRid; // Format of the sequence: // Inlinee RID with flag in the lowest bit // - if flag is set, followed by module ID // Followed by inliner RIDs deltas with flag in the lowest bit // - if flag is set, followed by module ID var sig = new VertexSequence(); bool isForeignInlinee = inlinee.Module != _module; sig.Append(new UnsignedConstant((uint)(inlineeRid << 1 | (isForeignInlinee ? 1 : 0)))); if (isForeignInlinee) { sig.Append(new UnsignedConstant((uint)factory.ManifestMetadataTable.ModuleToIndex(inlinee.Module))); } List <EcmaMethod> sortedInliners = new List <EcmaMethod>(inlineeWithInliners.Value); sortedInliners.Sort((a, b) => { if (a == b) { return(0); } int aRid = MetadataTokens.GetRowNumber(a.Handle); int bRid = MetadataTokens.GetRowNumber(b.Handle); if (aRid < bRid) { return(-1); } else if (aRid > bRid) { return(1); } int result = a.Module.CompareTo(b.Module); Debug.Assert(result != 0); return(result); }); int baseRid = 0; foreach (EcmaMethod inliner in sortedInliners) { int inlinerRid = MetadataTokens.GetRowNumber(inliner.Handle); int ridDelta = inlinerRid - baseRid; baseRid = inlinerRid; Debug.Assert(ridDelta >= 0); bool isForeignInliner = inliner.Module != _module; sig.Append(new UnsignedConstant((uint)(ridDelta << 1 | (isForeignInliner ? 1 : 0)))); if (isForeignInliner) { sig.Append(new UnsignedConstant((uint)factory.ManifestMetadataTable.ModuleToIndex(inliner.Module))); } } hashtable.Append((uint)hashCode, section.Place(sig)); } MemoryStream writerContent = new MemoryStream(); writer.Save(writerContent); return(new ObjectData( data: writerContent.ToArray(), relocs: null, alignment: 8, definedSymbols: new ISymbolDefinitionNode[] { this })); }
public UserDefinedTypeDescriptor(ITypesDebugInfoWriter objectWriter, NodeFactory nodeFactory) { _objectWriter = objectWriter; _nodeFactory = nodeFactory; }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { ObjectDataBuilder builder = new ObjectDataBuilder(factory, relocsOnly); builder.RequireInitialPointerAlignment(); builder.AddSymbol(this); BlobReader reader = _module.PEReader.GetEntireImage().GetReader(); reader.Offset = _module.PEReader.PEHeaders.CorHeaderStartOffset; // Header Size int headerSize = reader.ReadInt32(); builder.EmitInt(headerSize); // Runtime major, minor version builder.EmitUShort(reader.ReadUInt16()); builder.EmitUShort(reader.ReadUInt16()); // Metadata Directory ReadDirectoryEntry(ref reader); var metadataBlob = factory.CopiedMetadataBlob(_module); builder.EmitReloc(metadataBlob, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitInt(metadataBlob.Size); // Flags builder.EmitUInt((uint)(((CorFlags)reader.ReadUInt32() & ~CorFlags.ILOnly) | CorFlags.ILLibrary)); // Entrypoint builder.EmitInt(reader.ReadInt32()); // Resources Directory if (ReadDirectoryEntry(ref reader).Size > 0) { var managedResources = factory.CopiedManagedResources(_module); builder.EmitReloc(managedResources, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitInt(managedResources.Size); } else { WriteEmptyDirectoryEntry(ref builder); } // Strong Name Signature Directory if (ReadDirectoryEntry(ref reader).Size > 0) { var strongNameSignature = factory.CopiedStrongNameSignature(_module); builder.EmitReloc(strongNameSignature, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitInt(strongNameSignature.Size); } else { WriteEmptyDirectoryEntry(ref builder); } // Code Manager Table Directory ReadDirectoryEntry(ref reader); WriteEmptyDirectoryEntry(ref builder); // VTable Fixups Directory ReadDirectoryEntry(ref reader); WriteEmptyDirectoryEntry(ref builder); // Export Address Table Jumps Directory ReadDirectoryEntry(ref reader); WriteEmptyDirectoryEntry(ref builder); // Managed Native (ReadyToRun) Header Directory ReadDirectoryEntry(ref reader); builder.EmitReloc(factory.Header, RelocType.IMAGE_REL_BASED_ADDR32NB); builder.EmitReloc(factory.Header, RelocType.IMAGE_REL_SYMBOL_SIZE); // Did we fully read the header? Debug.Assert(reader.Offset - headerSize == _module.PEReader.PEHeaders.CorHeaderStartOffset); Debug.Assert(builder.CountBytes == headerSize); Debug.Assert(headerSize == Size); return(builder.ToObjectData()); }
/// <summary> /// Loads NodeModels, ConnectorModels, and NoteModels from an XmlDocument. /// </summary> /// <param name="xmlDoc">An XmlDocument representing a serialized Dynamo workspace.</param> /// <param name="nodeFactory">A NodeFactory, used to load and instantiate nodes.</param> /// <param name="elementResolver"></param> /// <returns></returns> public static NodeGraph LoadGraphFromXml(XmlDocument xmlDoc, NodeFactory nodeFactory) { var elementResolver = LoadElementResolverFromXml(xmlDoc); var nodes = LoadNodesFromXml(xmlDoc, nodeFactory, elementResolver).ToList(); var connectors = LoadConnectorsFromXml(xmlDoc, nodes.ToDictionary(node => node.GUID)).ToList(); var notes = LoadNotesFromXml(xmlDoc).ToList(); var annotations = LoadAnnotationsFromXml(xmlDoc, nodes, notes).ToList(); var presets = LoadPresetsFromXml(xmlDoc,nodes).ToList(); return new NodeGraph { Nodes = nodes, Connectors = connectors, Notes = notes, Annotations = annotations, Presets = presets, ElementResolver = elementResolver }; }
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
/// <summary> /// Creates and initializes a NodeModel from its Xml representation. /// </summary> /// <param name="elNode">XmlElement for a NodeModel.</param> /// <param name="context">The serialization context for initialization.</param> /// <param name="nodeFactory">A NodeFactory, to be used to create the node.</param> /// <returns></returns> public static NodeModel LoadNodeFromXml( XmlElement elNode, SaveContext context, NodeFactory nodeFactory, ElementResolver resolver) { return nodeFactory.CreateNodeFromXml(elNode, context, resolver); }
public override ObjectData GetData(NodeFactory factory, bool relocsOnly = false) { // This node does not trigger generation of other nodes. if (relocsOnly) { return(new ObjectData(Array.Empty <byte>(), Array.Empty <Relocation>(), 1, new ISymbolDefinitionNode[] { this })); } NativeWriter writer = new NativeWriter(); Section section = writer.NewSection(); VertexArray vertexArray = new VertexArray(section); section.Place(vertexArray); Dictionary <byte[], BlobVertex> blobCache = new Dictionary <byte[], BlobVertex>(ByteArrayComparer.Instance); foreach (MethodWithGCInfo method in factory.EnumerateCompiledMethods()) { MemoryStream methodDebugBlob = new MemoryStream(); byte[] bounds = method.DebugLocInfos; byte[] vars = method.DebugVarInfos; NibbleWriter nibbleWriter = new NibbleWriter(); nibbleWriter.WriteUInt((uint)(bounds?.Length ?? 0)); nibbleWriter.WriteUInt((uint)(vars?.Length ?? 0)); byte[] header = nibbleWriter.ToArray(); methodDebugBlob.Write(header, 0, header.Length); if (bounds?.Length > 0) { methodDebugBlob.Write(bounds, 0, bounds.Length); } if (vars?.Length > 0) { methodDebugBlob.Write(vars, 0, vars.Length); } byte[] debugBlobArrayKey = methodDebugBlob.ToArray(); if (!blobCache.TryGetValue(debugBlobArrayKey, out BlobVertex debugBlob)) { debugBlob = new BlobVertex(methodDebugBlob.ToArray()); blobCache.Add(debugBlobArrayKey, debugBlob); } vertexArray.Set(factory.RuntimeFunctionsTable.GetIndex(method), new DebugInfoVertex(debugBlob)); } vertexArray.ExpandLayout(); MemoryStream writerContent = new MemoryStream(); writer.Save(writerContent); return(new ObjectData( data: writerContent.ToArray(), relocs: null, alignment: 8, definedSymbols: new ISymbolDefinitionNode[] { this })); }
public void Setup() { factory = new NodeFactory(ModelType.Truss1D); }
/// <summary> /// This function creates CustomNodeManager /// </summary> /// <param name="nodeFactory">NodeFactory</param> /// <param name="migrationManager">MigrationManager</param> public CustomNodeManager(NodeFactory nodeFactory, MigrationManager migrationManager) { this.nodeFactory = nodeFactory; this.migrationManager = migrationManager; }
public override void GetDependenciesDueToLdToken(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { // In order for the RuntimeMethodHandle data structure to be usable at runtime, ensure the method // is generating metadata. if ((GetMetadataCategory(method) & MetadataCategory.Description) == MetadataCategory.Description) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.MethodMetadata(method.GetTypicalMethodDefinition()), "LDTOKEN method"); } }
/// <summary> /// Attempts to migrate a workspace to the current version of Dynamo. /// </summary> /// <param name="workspaceInfo"></param> /// <param name="xmlDoc"></param> /// <returns></returns> public bool ProcessWorkspace(WorkspaceInfo workspaceInfo, XmlDocument xmlDoc, bool isTestMode, NodeFactory factory) { Version fileVersion = VersionFromString(workspaceInfo.Version); var currentVersion = AssemblyHelper.GetDynamoVersion(includeRevisionNumber: false); if (fileVersion > currentVersion) { bool resume = displayFutureFileMessage( workspaceInfo.FileName, fileVersion, currentVersion); if (!resume) return false; } var decision = ProcessWorkspace( xmlDoc, fileVersion, currentVersion, workspaceInfo.FileName, isTestMode, factory); if (decision != Decision.Abort) return true; displayObsoleteFileMessage(workspaceInfo.FileName, fileVersion, currentVersion); return false; }
public X64Emitter(NodeFactory factory, bool relocsOnly) { Builder = new ObjectDataBuilder(factory, relocsOnly); TargetRegister = new TargetRegisterMap(factory.Target.OperatingSystem); }
public void ProcessNodesInWorkspace( XmlDocument xmlDoc, Version workspaceVersion, Version currentVersion, NodeFactory nodeFactory) { if (DynamoModel.EnableMigrationLogging) { // For each new file opened, create a new migration report migrationReport = new MigrationReport(); } XmlNodeList elNodes = xmlDoc.GetElementsByTagName("Elements"); if (elNodes.Count == 0) elNodes = xmlDoc.GetElementsByTagName("dynElements"); // A new list to store migrated nodes. var migratedNodes = new List<XmlElement>(); XmlNode elNodesList = elNodes[0]; foreach (XmlElement elNode in elNodesList.ChildNodes) { string typeName = elNode.Attributes["type"].Value; typeName = Nodes.Utilities.PreprocessTypeName(typeName); Type type; if (!nodeFactory.ResolveType(typeName, out type) && !nodeMigrationLookup.TryGetValue(typeName, out type)) { // If we are not able to resolve the type given its name, // turn it into a deprecated node so that user is aware. migratedNodes.Add(CreateMissingNode(elNode, 1, 1)); continue; // Error displayed in console, continue on. } // Migrate the given node into one or more new nodes. var migrationData = MigrateXmlNode(currentVersion, elNode, type, workspaceVersion); migratedNodes.AddRange(migrationData.MigratedNodes); } if (DynamoModel.EnableMigrationLogging) { string dynFilePath = xmlDoc.BaseURI; migrationReport.WriteToXmlFile(dynFilePath); } // Replace the old child nodes with the migrated nodes. Note that // "RemoveAll" also remove all attributes, but since we don't have // any attribute here, it is safe. Added an assertion to make sure // we revisit this codes if we do add attributes to 'elNodesList'. // Debug.Assert(elNodesList.Attributes.Count == 0); elNodesList.RemoveAll(); foreach (XmlElement migratedNode in migratedNodes) elNodesList.AppendChild(migratedNode); }
private NodeFactory DecorateFactory(NodeFactory nodeFactory) { return((h, p) => ObserveNode(nodeFactory(h, p))); }
public static void Serialize(CHR0Node node, bool bake, string output) { MDL0Node model; OpenFileDialog dlgOpen = new OpenFileDialog { Filter = "MDL0 Model (*.mdl0)|*.mdl0", Title = "Select the model this animation is for..." }; if (dlgOpen.ShowDialog() != DialogResult.OK || (model = (MDL0Node)NodeFactory.FromFile(null, dlgOpen.FileName)) == null) { return; } using (StreamWriter file = new StreamWriter(output)) { file.WriteLine("animVersion 1.1;"); file.WriteLine("mayaVersion 2015;"); file.WriteLine("timeUnit ntsc;"); file.WriteLine("linearUnit cm;"); file.WriteLine("angularUnit deg;"); file.WriteLine("startTime 1;"); file.WriteLine(string.Format("endTime {0};", node.FrameCount)); foreach (CHR0EntryNode e in node.Children) { MDL0BoneNode bone = model.FindChild("Bones/" + e.Name, true) as MDL0BoneNode; if (bone == null) { continue; } KeyframeCollection c = e.Keyframes; for (int index = 0; index < 9; index++) { KeyframeArray array = c._keyArrays[index]; if (array._keyCount <= 0) { continue; } file.WriteLine(string.Format("anim {0}.{0}{1} {0}{1} {2} {3} {4} {5}", types[index / 3], axes[index % 3], e.Name, 0, bone.Children.Count, index < 6 ? index + 3 : index - 6)); file.WriteLine("animData {"); file.WriteLine(" input time;"); file.WriteLine(string.Format(" output {0};", index > 2 && index < 6 ? "angular" : "linear")); file.WriteLine(" weighted 0;"); file.WriteLine(" preInfinity constant;"); file.WriteLine(" postInfinity constant;"); file.WriteLine(" keys {"); for (KeyframeEntry entry = array._keyRoot._next; entry != array._keyRoot; entry = entry._next) { bool single = entry._next._index < 0 && entry._prev._index < 0; //float angle = (float)Math.Atan(entry._tangent) * Maths._rad2degf; //if (single) { file.WriteLine(string.Format(" {0} {1} {2} {2} {3} {4} {5};", entry._index + 1, entry._value.ToString(CultureInfo.InvariantCulture.NumberFormat), "auto", //single ? "auto" : "fixed", "1", "1", "0")); } } file.WriteLine(" }"); file.WriteLine("}"); } } } }
protected override void GetRuntimeMappingDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, TypeDesc type) { // If we precisely track field usage, we don't need the logic below. if (_hasPreciseFieldUsageInformation) { return; } const string reason = "Reflection"; // This logic is applying policy: if a type is reflectable (has a runtime mapping), all of it's fields // are reflectable (with a runtime mapping) as well. // This is potentially overly broad (we don't know if any of the fields will actually be eligile // for metadata - e.g. they could all be reflection blocked). This is fine since lack of // precise field usage information is already not ideal from a size on disk perspective. // The more precise way to do this would be to go over each field, check that it's eligible for RuntimeMapping // according to the policy (e.g. it's not blocked), and only then root the base of the field. if (type is MetadataType metadataType && !type.IsGenericDefinition) { Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Any)); if (metadataType.GCStaticFieldSize.AsInt > 0) { dependencies.Add(factory.TypeGCStaticsSymbol(metadataType), reason); } if (metadataType.NonGCStaticFieldSize.AsInt > 0 || _typeSystemContext.HasLazyStaticConstructor(metadataType)) { dependencies.Add(factory.TypeNonGCStaticsSymbol(metadataType), reason); } // TODO: tread static fields } }
/// <summary> /// Default constructor for DynamoModel /// </summary> /// <param name="config">Start configuration</param> protected DynamoModel(IStartConfiguration config) { ClipBoard = new ObservableCollection<ModelBase>(); pathManager = new PathManager(new PathManagerParams { CorePath = config.DynamoCorePath, HostPath = config.DynamoHostPath, PathResolver = config.PathResolver }); // Ensure we have all directories in place. var exceptions = new List<Exception>(); pathManager.EnsureDirectoryExistence(exceptions); Context = config.Context; IsTestMode = config.StartInTestMode; var config2 = config as IStartConfiguration2; IsHeadless = (config2 != null) ? config2.IsHeadless : false; DebugSettings = new DebugSettings(); Logger = new DynamoLogger(DebugSettings, pathManager.LogDirectory); foreach (var exception in exceptions) { Logger.Log(exception); // Log all exceptions. } MigrationManager = new MigrationManager(DisplayFutureFileMessage, DisplayObsoleteFileMessage); MigrationManager.MessageLogged += LogMessage; MigrationManager.MigrationTargets.Add(typeof(WorkspaceMigrations)); var thread = config.SchedulerThread ?? new DynamoSchedulerThread(); Scheduler = new DynamoScheduler(thread, config.ProcessMode); Scheduler.TaskStateChanged += OnAsyncTaskStateChanged; geometryFactoryPath = config.GeometryFactoryPath; IPreferences preferences = CreateOrLoadPreferences(config.Preferences); var settings = preferences as PreferenceSettings; if (settings != null) { PreferenceSettings = settings; PreferenceSettings.PropertyChanged += PreferenceSettings_PropertyChanged; } InitializeInstrumentationLogger(); if (!IsTestMode && PreferenceSettings.IsFirstRun) { DynamoMigratorBase migrator = null; try { var dynamoLookup = config.UpdateManager != null && config.UpdateManager.Configuration != null ? config.UpdateManager.Configuration.DynamoLookUp : null; migrator = DynamoMigratorBase.MigrateBetweenDynamoVersions(pathManager, dynamoLookup); } catch (Exception e) { Logger.Log(e.Message); } if (migrator != null) { var isFirstRun = PreferenceSettings.IsFirstRun; PreferenceSettings = migrator.PreferenceSettings; // Preserve the preference settings for IsFirstRun as this needs to be set // only by UsageReportingManager PreferenceSettings.IsFirstRun = isFirstRun; } } InitializePreferences(PreferenceSettings); // At this point, pathManager.PackageDirectories only has 1 element which is the directory // in AppData. If list of PackageFolders is empty, add the folder in AppData to the list since there // is no additional location specified. Otherwise, update pathManager.PackageDirectories to include // PackageFolders if (PreferenceSettings.CustomPackageFolders.Count == 0) PreferenceSettings.CustomPackageFolders = new List<string> {pathManager.UserDataDirectory}; //Make sure that the default package folder is added in the list if custom packages folder. var userDataFolder = pathManager.GetUserDataFolder(); //Get the default user data path if (Directory.Exists(userDataFolder) && !PreferenceSettings.CustomPackageFolders.Contains(userDataFolder)) { PreferenceSettings.CustomPackageFolders.Add(userDataFolder); } pathManager.Preferences = PreferenceSettings; SearchModel = new NodeSearchModel(); SearchModel.ItemProduced += node => ExecuteCommand(new CreateNodeCommand(node, 0, 0, true, true)); NodeFactory = new NodeFactory(); NodeFactory.MessageLogged += LogMessage; CustomNodeManager = new CustomNodeManager(NodeFactory, MigrationManager); InitializeCustomNodeManager(); extensionManager = new ExtensionManager(); extensionManager.MessageLogged += LogMessage; var extensions = config.Extensions ?? LoadExtensions(); Loader = new NodeModelAssemblyLoader(); Loader.MessageLogged += LogMessage; // Create a core which is used for parsing code and loading libraries var libraryCore = new ProtoCore.Core(new Options()); libraryCore.Compilers.Add(Language.Associative, new Compiler(libraryCore)); libraryCore.Compilers.Add(Language.Imperative, new ProtoImperative.Compiler(libraryCore)); libraryCore.ParsingMode = ParseMode.AllowNonAssignment; LibraryServices = new LibraryServices(libraryCore, pathManager, PreferenceSettings); LibraryServices.MessageLogged += LogMessage; LibraryServices.LibraryLoaded += LibraryLoaded; ResetEngineInternal(); AddHomeWorkspace(); AuthenticationManager = new AuthenticationManager(config.AuthProvider); UpdateManager = config.UpdateManager ?? new DefaultUpdateManager(null); // config.UpdateManager has to be cast to IHostUpdateManager in order to extract the HostVersion and HostName // see IHostUpdateManager summary for more details var hostUpdateManager = config.UpdateManager as IHostUpdateManager; if (hostUpdateManager != null) { HostName = hostUpdateManager.HostName; HostVersion = hostUpdateManager.HostVersion == null ? null : hostUpdateManager.HostVersion.ToString(); } else { HostName = string.Empty; HostVersion = null; } UpdateManager.Log += UpdateManager_Log; if (!IsTestMode && !IsHeadless) { DefaultUpdateManager.CheckForProductUpdate(UpdateManager); } Logger.Log(string.Format("Dynamo -- Build {0}", Assembly.GetExecutingAssembly().GetName().Version)); InitializeNodeLibrary(PreferenceSettings); if (extensions.Any()) { var startupParams = new StartupParams(config.AuthProvider, pathManager, new ExtensionLibraryLoader(this), CustomNodeManager, GetType().Assembly.GetName().Version, PreferenceSettings); foreach (var ext in extensions) { var logSource = ext as ILogSource; if (logSource != null) logSource.MessageLogged += LogMessage; try { ext.Startup(startupParams); } catch (Exception ex) { Logger.Log(ex.Message); } ExtensionManager.Add(ext); } } LogWarningMessageEvents.LogWarningMessage += LogWarningMessage; StartBackupFilesTimer(); TraceReconciliationProcessor = this; foreach (var ext in ExtensionManager.Extensions) { try { ext.Ready(new ReadyParams(this)); } catch (Exception ex) { Logger.Log(ex.Message); } } }
public GeneratedTypesAndCodeMetadataPolicy(MetadataBlockingPolicy blockingPolicy, NodeFactory factory) { _blockingPolicy = blockingPolicy; _factory = factory; _explicitScopeMixin = new ExplicitScopeAssemblyPolicyMixin(); }
private Decision ProcessWorkspace( XmlDocument xmlDoc, Version fileVersion, Version currentVersion, string xmlPath, bool isTestMode, NodeFactory factory) { switch (ShouldMigrateFile(fileVersion, currentVersion, isTestMode)) { case Decision.Abort: return Decision.Abort; case Decision.Migrate: string backupPath = String.Empty; if (!isTestMode && BackupOriginalFile(xmlPath, ref backupPath)) { string message = String.Format( Properties.Resources.BackUpOriginalFileMessage, Path.GetFileName(xmlPath), backupPath); Log(message); } //Hardcode the file version to 0.6.0.0. The file whose version is 0.7.0.x //needs to be forced to be migrated. The version number needs to be changed from //0.7.0.x to 0.6.0.0. if (fileVersion == new Version(0, 7, 0, 0)) fileVersion = new Version(0, 6, 0, 0); ProcessWorkspaceMigrations(currentVersion, xmlDoc, fileVersion); ProcessNodesInWorkspace(xmlDoc, fileVersion, currentVersion, factory); return Decision.Migrate; case Decision.Retain: return Decision.Retain; default: throw new ArgumentOutOfRangeException(); } }
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, TypeDesc type) { TypeMetadataNode.GetMetadataDependencies(ref dependencies, factory, type, "Reflectable type"); // If we don't have precise field usage information, apply policy that all fields that // are eligible to have metadata get metadata. if (!_hasPreciseFieldUsageInformation) { TypeDesc typeDefinition = type.GetTypeDefinition(); foreach (FieldDesc field in typeDefinition.GetFields()) { if ((GetMetadataCategory(field) & MetadataCategory.Description) != 0) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.FieldMetadata(field), "Field of a reflectable type"); } } } // If anonymous type heuristic is turned on and this is an anonymous type, make sure we have // method bodies for all properties. It's common to have anonymous types used with reflection // and it's hard to specify them in RD.XML. if ((_generationOptions & UsageBasedMetadataGenerationOptions.AnonymousTypeHeuristic) != 0) { if (type is MetadataType metadataType && metadataType.HasInstantiation && !metadataType.IsGenericDefinition && metadataType.HasCustomAttribute("System.Runtime.CompilerServices", "CompilerGeneratedAttribute") && metadataType.Name.Contains("AnonymousType")) { foreach (MethodDesc method in type.GetMethods()) { if (!method.Signature.IsStatic && method.IsSpecialName) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.CanonicalEntrypoint(method), "Anonymous type accessor"); } } } } // If a type is marked [Serializable], make sure a couple things are also included. if (type.IsSerializable && !type.IsGenericDefinition) { foreach (MethodDesc method in type.GetAllMethods()) { MethodSignature signature = method.Signature; if (method.IsConstructor && signature.Length == 2 && signature[0] == _serializationInfoType /* && signature[1] is StreamingContext */) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.CanonicalEntrypoint(method), "Binary serialization"); } // Methods with these attributes can be called during serialization if (signature.Length == 1 && !signature.IsStatic && signature.ReturnType.IsVoid && (method.HasCustomAttribute("System.Runtime.Serialization", "OnSerializingAttribute") || method.HasCustomAttribute("System.Runtime.Serialization", "OnSerializedAttribute") || method.HasCustomAttribute("System.Runtime.Serialization", "OnDeserializingAttribute") || method.HasCustomAttribute("System.Runtime.Serialization", "OnDeserializedAttribute"))) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.CanonicalEntrypoint(method), "Binary serialization"); } } } }
public ISymbolNode GetFieldRvaData(FieldDesc field) => NodeFactory.CopiedFieldRva(field);
public Cluster(Configuration configuration, ILogger logger, NodeFactory nodeFactory, ProducerFactory producerFactory, ConsumerFactory consumerFactory, IStatistics statistics = null) { _configuration = configuration; _seeds = configuration.Seeds; Logger = logger; Statistics = statistics ?? new Statistics(); _timeoutScheduler = new TimeoutScheduler(configuration.ClientRequestTimeoutMs / 2); _pools = InitPools(Statistics, configuration); // Producer init ProduceRouter = producerFactory != null?producerFactory() : new ProduceRouter(this, configuration, _pools.MessageBuffersPool); ProduceRouter.MessageExpired += (t, m) => { Statistics.UpdateExpired(); UpdateExited(1); }; ProduceRouter.MessagesAcknowledged += (t, c) => { Statistics.UpdateSuccessfulSent(c); UpdateExited(c); SignalSeenTopic(t); }; ProduceRouter.MessageDiscarded += (t, m) => { Statistics.UpdateDiscarded(); UpdateExited(1); }; RoutingTableChange += ProduceRouter.ChangeRoutingTable; ProduceRouter.BrokerTimeoutError += Statistics.UpdateBrokerTimeoutError; ProduceRouter.MessageReEnqueued += Statistics.UpdateMessageRetry; ProduceRouter.MessagePostponed += Statistics.UpdateMessagePostponed; // Consumer init ConsumeRouter = consumerFactory != null?consumerFactory() : new ConsumeRouter(this, configuration); ConsumeRouter.MessageReceived += _ => Statistics.UpdateReceived(); if (ConsumeRouter is ConsumeRouter) { (ConsumeRouter as ConsumeRouter).InternalError += ex => Logger.LogError("An unexpected error occured in the consumer: " + ex); } RoutingTableChange += ConsumeRouter.ChangeRoutingTable; // Node factory var clientId = Encoding.UTF8.GetBytes(configuration.ClientId); var serializer = new Node.Serialization(configuration.SerializationConfig, configuration.Compatibility, _pools.RequestsBuffersPool, clientId, configuration.RequiredAcks, configuration.RequestTimeoutMs, configuration.CompressionCodec, configuration.FetchMinBytes, configuration.FetchMaxWaitTime); _nodeFactory = nodeFactory ?? ((h, p) => new Node(string.Format("[{0}:{1}]", h, p), () => new Connection(h, p, ep => new RealSocket(ep), _pools.SocketBuffersPool, _pools.RequestsBuffersPool, configuration.SendBufferSize, configuration.ReceiveBufferSize), serializer, configuration, _timeoutScheduler, _resolution)); _nodeFactory = DecorateFactory(_nodeFactory); // Inner actor _agent = new ActionBlock <ClusterMessage>(r => ProcessMessage(r), new ExecutionDataflowBlockOptions { TaskScheduler = configuration.TaskScheduler }); // Bootstrap BuildNodesFromSeeds(); if (_nodes.Count == 0) { throw new ArgumentException("Invalid seeds: " + _seeds); } }
protected WorkspaceModel( IEnumerable<NodeModel> nodes, IEnumerable<NoteModel> notes, IEnumerable<AnnotationModel> annotations, WorkspaceInfo info, NodeFactory factory, IEnumerable<PresetModel> presets, ElementResolver resolver) { guid = Guid.NewGuid(); this.nodes = new List<NodeModel>(nodes); this.notes = new List<NoteModel>(notes); this.annotations = new List<AnnotationModel>(annotations); // Set workspace info from WorkspaceInfo object Name = info.Name; Description = info.Description; X = info.X; Y = info.Y; FileName = info.FileName; Zoom = info.Zoom; HasUnsavedChanges = false; LastSaved = DateTime.Now; WorkspaceVersion = AssemblyHelper.GetDynamoVersion(); undoRecorder = new UndoRedoRecorder(this); NodeFactory = factory; this.presets = new List<PresetModel>(presets); ElementResolver = resolver; foreach (var node in this.nodes) RegisterNode(node); foreach (var connector in Connectors) RegisterConnector(connector); SetModelEventOnAnnotation(); }
/// <summary> /// Gets the vtable slot that holds the generic dictionary of this type. /// </summary> public static int GetGenericDictionarySlot(NodeFactory factory, TypeDesc type) { Debug.Assert(type.HasGenericDictionarySlot()); return(GetNumberOfBaseSlots(factory, type)); }
public CustomNodeManager(NodeFactory nodeFactory, MigrationManager migrationManager) { this.nodeFactory = nodeFactory; this.migrationManager = migrationManager; }
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, MethodDesc method) { dependencies = dependencies ?? new DependencyList(); dependencies.Add(factory.MethodMetadata(method.GetTypicalMethodDefinition()), "Reflectable method"); }