Пример #1
0
		// Expanded is passed so that the correct ContentNodes are expanded in the PositionedNode
		PositionedGraph BuildPositionedGraph(ObjectGraph objectGraph, Expanded expanded)
		{
			var positionedNodeFor = new Dictionary<ObjectGraphNode, PositionedNode>();
			var positionedGraph = new PositionedGraph();
			
			// create empty PositionedNodes
			foreach (ObjectGraphNode objectNode in objectGraph.ReachableNodes) {
				var posNode = new PositionedNode(objectNode, expanded);
				posNode.MeasureVisualControl();
				positionedGraph.AddNode(posNode);
				positionedNodeFor[objectNode] = posNode;
			}
			
			// create edges
			foreach (PositionedNode posNode in positionedGraph.Nodes)
			{
				foreach (PositionedNodeProperty property in posNode.Properties)	{
					if (property.ObjectGraphProperty.TargetNode != null) {
						ObjectGraphNode targetObjectNode = property.ObjectGraphProperty.TargetNode;
						PositionedNode edgeTarget = positionedNodeFor[targetObjectNode];
						property.Edge = new PositionedEdge {
							Name = property.Name, Source = property, Target = edgeTarget
						};
					}
				}
			}
			positionedGraph.Root = positionedNodeFor[objectGraph.Root];
			return positionedGraph;
		}
Пример #2
0
		private PositionedGraph buildTreeGraph(ObjectGraph objectGraph, Expanded expanded)
		{
			var resultGraph = new PositionedGraph();
			
			// create empty PosNodes
			foreach (ObjectGraphNode objectGraphNode in objectGraph.ReachableNodes)
			{
				TreeGraphNode posNode = createNewTreeGraphNode(objectGraphNode); 
				resultGraph.AddNode(posNode);
				treeNodeFor[objectGraphNode] = posNode;
				posNode.InitContentFromObjectNode(expanded);
			}
			
			// create edges
			foreach (PositionedGraphNode posNode in resultGraph.Nodes)
			{
				// create edges outgoing from this posNode
				foreach (PositionedNodeProperty property in posNode.Properties)
				{
					//property.IsPropertyExpanded = expanded.Expressions.IsExpanded(property.Expression);
					
					if (property.ObjectGraphProperty.TargetNode != null)
					{
						ObjectGraphNode targetObjectNode = property.ObjectGraphProperty.TargetNode;
						PositionedGraphNode edgeTarget = treeNodeFor[targetObjectNode];
						property.Edge = new TreeGraphEdge 
							{ IsTreeEdge = false, Name = property.Name, Source = property, Target = edgeTarget };
					}
				}
			}
			
			resultGraph.Root = treeNodeFor[objectGraph.Root];
			return resultGraph;
		}
Пример #3
0
            public CacheFixture()
            {
                IdGenerator = new IdGenerator();
                ObjectGraph = new ObjectGraph();
                MaterializationHooks = Enumerable.Empty<IMaterializationHook>();

                Cache = new Cache(IdGenerator, ObjectGraph, MaterializationHooks);
            }
Пример #4
0
		/// <summary>
		/// Calculates layout for given <see cref="ObjectGraph" />.
		/// </summary>
		/// <param name="objectGraph"></param>
		/// <returns></returns>
		public PositionedGraph CalculateLayout(ObjectGraph objectGraph, Expanded expanded)
		{
			var positionedGraph = BuildPositionedGraph(objectGraph, expanded);
			CalculateLayout(positionedGraph);
			this.edgeRouter.RouteEdges(positionedGraph);
			
			return positionedGraph;
		}
Пример #5
0
 // TODO -- come back here and throw an exception if the ctor cannot be found
 // TODO -- check first if the objectGraph ConcreteType already has a constructor
 public virtual void InitializeConcreteType(ObjectGraph objectGraph)
 {
     var ctor = DefaultConstructorAttribute.FindConstructor(objectGraph.ConcreteType.Type) ??
                ConstructorSelector.Select(objectGraph, this);
     if (ctor != null)
     {
         objectGraph.ConcreteType.Constructor = ctor;
     }
 }
Пример #6
0
        public void find_concrete_type_for_a_type_that_is_marked_with_default_constructor()
        {
            var pluginGraph = new PluginGraph();
            var objectGraph = new ObjectGraph(typeof (ClassMarkedWithDefaultConstructor));

            pluginGraph.InitializeConcreteType(objectGraph);

            // Should choose the no arg constructor
            objectGraph.ConcreteType.Constructor.GetParameters().Any().ShouldBeFalse();
        }
Пример #7
0
            public void ReturnsChildObjects()
            {
                var child = new object();
                var parent = new {child};

                var list = new ObjectGraph().Traverse(parent).ToArray();

                Assert.Contains(child, list);
                Assert.Contains(parent, list);
            }
Пример #8
0
            public void HandlesCyclicReferences()
            {
                var v = new Url("a");
                v.OutboundLinks.Add(v);

                var r = new ObjectGraph().Traverse(v).ToArray();

                Assert.Equal(1, r.Length);
                Assert.Contains(v, r);
            }
Пример #9
0
        public ObjectGraphBuilder(ObjectGraph graph, PluginGraph pluginGraph)
        {
            _graph = graph;

            _builder = new Lazy<IInstanceBuilder>(() =>
            {
                graph.InitializeConcreteType(pluginGraph);

                // Move this to pluginGraph.  IBuilderCompiler may need to be pluggable later
                return BuilderCompiler.CreateBuilder(graph.ConcreteType);
            });
        }
Пример #10
0
        public void use_the_constructor_selector_to_build_a_concrete_type()
        {
            var theCtor = GetType().GetConstructors().First();
            var selector = MockRepository.GenerateMock<IConstructorSelector>();
            var pluginGraph = new PluginGraph{
                ConstructorSelector = selector
            };

            var objectGraph = new ObjectGraph(GetType());

            selector.Stub(x => x.Select(objectGraph, pluginGraph)).Return(theCtor);

            pluginGraph.InitializeConcreteType(objectGraph);

            objectGraph.ConcreteType.Constructor.ShouldBeTheSameAs(theCtor);
        }
        public void build_the_object()
        {
            var objectGraph = new ObjectGraph<ClassWithMultipleCtorArguments>();
            objectGraph.ByType[typeof (Color)] = "Red";
            objectGraph.ByName["name"] = "Jeremy";
            objectGraph.ByType[typeof (int)] = "36";
            objectGraph.ByName["day"] = DateTime.Today;

            var pipeline = new PipelineContext();

            var pluginGraph = new PluginGraph();

            var builder = new ObjectGraphBuilder(objectGraph, pluginGraph);
            var pluginType = pluginGraph.PluginTypeFor(typeof (ClassWithMultipleCtorArguments));
            var target = builder.Build(pluginType, pipeline).ShouldBeOfType<ClassWithMultipleCtorArguments>();

            target.Color.ShouldEqual(Color.Red);
            target.Name.ShouldEqual("Jeremy");
            target.Age.ShouldEqual(36);
            target.Day.ShouldEqual(DateTime.Today);
        }
Пример #12
0
		/// <summary>
		/// Calculates layout for given <see cref="ObjectGraph" />.
		/// </summary>
		/// <param name="objectGraph"></param>
		/// <returns></returns>
		public PositionedGraph CalculateLayout(ObjectGraph objectGraph, LayoutDirection direction, Expanded expanded)
		{
			layoutDirection = direction;

			treeNodeFor = new Dictionary<ObjectGraphNode, PositionedGraphNode>();
			seenNodes = new HashSet<PositionedGraphNode>();
			
			//TreeGraphNode tree = buildTreeRecursive(objectGraph.Root, expandedNodes);
			
			// convert ObjectGraph to PositionedGraph with TreeEdges
			var resultGraph = buildTreeGraph(objectGraph, expanded);
			// first layout pass
			calculateSubtreeSizes((TreeGraphNode)resultGraph.Root);
			// second layout pass
			calculateNodePosRecursive((TreeGraphNode)resultGraph.Root, 0, 0);
			
			//var neatoRouter = new NeatoEdgeRouter();
			//resultGraph = neatoRouter.CalculateEdges(resultGraph);
			resultGraph = new GraphEdgeRouter().RouteEdges(resultGraph);
			
			return resultGraph;
		}
 public void SetUp()
 {
     using var stream = TestDataHelper.OpenResource("Text.nested_object_graph.vdf");
     data             = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize <ObjectGraph>(stream);
 }
Пример #14
0
 public void FromGraph(ObjectGraph graph)
 {
     type = graph["type"].Value;
     block.FromGraph(graph["block"]);
     block.ReturnNull = false;
 }
Пример #15
0
 public void SetUp()
 {
     objectGraph = new ObjectGraph<ObjectGraphTarget>();
 }
Пример #16
0
            public InMemorySetFixture()
            {
                IdGenerator = Substitute.For<IIdGenerator>();
                IdGenerator.Identify(null).ReturnsForAnyArgs(c => c.Args()[0]);

                ObjectGraph = new ObjectGraph();

                MaterializationHooks = new List<IMaterializationHook>();

                Cache = new Cache(IdGenerator, ObjectGraph, MaterializationHooks);
                InMemorySet = new InMemorySet(IdGenerator, Cache, ObjectGraph, MaterializationHooks);
            }
Пример #17
0
 private static ValidState validateIValidatable(Doc self, ObjectGraph graph, IValidatable validatable, ValidState state, string scope)
 => !graph.Visited(validatable) ? validatable.Validate(state, scope) : state;
Пример #18
0
        private static CompareError CompareNodes(ObjectGraph node1, ObjectGraph node2)
        {
            // Compare two nodes - just the nodes //
            // - compare the property name
            // - compare the property value
            object oMode = node1.GetValue(ObjectGraphComparer.CompareModeProperty);

            if (oMode == null)
            {
                oMode = CompareMode.PropertyNameAndValue;
            }

            CompareMode mode = (CompareMode)oMode;

            // default is compare name and value //

            if (mode == CompareMode.PropertyNameAndValue || mode == CompareMode.PropertyName)
            {
                // comapre name //
                if (!node1.Name.Equals(node2.Name))
                {
                    CompareError error = new CompareError(node1, node2, new Exception("Node names do not match"));
                    return(error);
                }
            }

            if (mode == CompareMode.PropertyNameAndValue || mode == CompareMode.PropertyValue)
            {
                // compare values - only compare if they are primitive types, if it is a complex
                // type, its properties will be child nodes in the metadata graph


                if (node1.DataType.IsPrimitive)
                {
                    ValueType value1 = node1.Data as ValueType;
                    ValueType value2 = node2.Data as ValueType;
                    // Need special handling for double and float as well as strings //
                    if (!ObjectGraphComparer.ComparePrimitive(value1, value2))
                    {
                        CompareError error = new CompareError(node1, node2, new Exception("Node values do not match"));
                        return(error);
                    }
                    return(null);
                }

                // string is not a primitive type //
                if (node1.DataType == typeof(String))
                { // for string case //
                    if (node1.Data == null && node2.Data == null)
                    {
                        return(null);
                    }

                    if (node1.Data == null || node2.Data == null)
                    {
                        CompareError error = new CompareError(node1, node2, new Exception("Node values do not match"));
                        return(error);
                    }

                    if (!node1.Data.Equals(node2.Data))
                    {
                        CompareError error = new CompareError(node1, node2, new Exception("Node values do not match"));
                        return(error);
                    }
                }
            }

            return(null);
        }
Пример #19
0
 public void FromGraph(ObjectGraph graph)
 {
     items        = graph["items"].Children.Select(Item.ItemFromGraph).ToArray();
     variableName = graph["var"].Value;
 }
Пример #20
0
        // TODO: Ignore story //
        public static GraphCompareResults Compare(ObjectGraph root1, ObjectGraph root2)
        {
            // search and set the ignores on root1 //

            return(ObjectGraphComparer.Compare(root1, root2, null));
        }
Пример #21
0
        static void CoalesceContainerShapes(ObjectGraph <Node> graph)
        {
            var containerShapes = graph.CompositionObjectNodes.Where(n => n.Object.Type == CompositionObjectType.CompositionContainerShape).ToArray();

            // If a container is not animated and has no other properties set apart from a transform,
            // and all of its children are also not animated and have no other properties set apart
            // from a transform, the transform can be pushed down to the child, allowing the parent to be removed.
            var elidableContainers = containerShapes.Where(n =>
            {
                var container = (CompositionContainerShape)n.Object;
                if (!container.Properties.IsEmpty ||
                    container.Animators.Count > 0 ||
                    container.CenterPoint != null ||
                    container.Offset != null ||
                    container.RotationAngleInDegrees != null ||
                    container.Scale != null)
                {
                    return(false);
                }

                foreach (var child in container.Shapes)
                {
                    if (!child.Properties.IsEmpty ||
                        child.Animators.Count > 0 ||
                        child.CenterPoint != null ||
                        child.Offset != null ||
                        child.RotationAngleInDegrees != null ||
                        child.Scale != null)
                    {
                        return(false);
                    }
                }

                return(true);
            });

            // Push the transform down to the child.
            foreach (var node in elidableContainers)
            {
                var container = (CompositionContainerShape)node.Object;
                foreach (var child in container.Shapes)
                {
                    // Push the transform down to the child
                    if (container.TransformMatrix.HasValue)
                    {
                        child.TransformMatrix = (child.TransformMatrix ?? Matrix3x2.Identity) * container.TransformMatrix;
                    }
                }

                // Remove the transform from the container.
                container.TransformMatrix = null;
            }

            // If a container is not animated and has no properties set, its children can be inserted into its parent.
            var containersWithNoPropertiesSet = containerShapes.Where(n =>
            {
                var container = (CompositionContainerShape)n.Object;
                if (container.Type != CompositionObjectType.CompositionContainerShape ||
                    container.CenterPoint != null ||
                    container.Offset != null ||
                    container.RotationAngleInDegrees != null ||
                    container.Scale != null ||
                    container.TransformMatrix != null ||
                    container.Animators.Count > 0 ||
                    !container.Properties.IsEmpty)
                {
                    return(false);
                }

                // Container has no properties set.
                return(true);
            }).ToArray();

            foreach (var(Node, Object) in containersWithNoPropertiesSet)
            {
                var container = (CompositionContainerShape)Object;

                // Insert the children into the parent.
                var parent = (IContainShapes)Node.Parent;
                if (parent == null)
                {
                    // The container may have already been removed, or it might be a root.
                    continue;
                }

                // Find the index in the parent of the container.
                // If childCount is 1, just replace the the container in the parent.
                // If childCount is >1, insert into the parent.
                var index = parent.Shapes.IndexOf(container);

                // Get the children from the container.
                var children = container.Shapes.ToArray();
                if (children.Length == 0)
                {
                    // The container has no children. This is rare but can happen if
                    // the container is for a layer type that we don't support.
                    continue;
                }

                // Remove the children from the container.
                container.Shapes.Clear();

                // Insert the first child where the container was.
                parent.Shapes[index] = children[0];

                // Fix the parent pointer in the graph.
                graph[children[0]].Parent = (CompositionObject)parent;

                // Insert the rest of the children.
                for (var i = 1; i < children.Length; i++)
                {
                    parent.Shapes.Insert(index + i, children[i]);

                    // Fix the parent pointer in the graph.
                    graph[children[i]].Parent = (CompositionObject)parent;
                }
            }
        }
Пример #22
0
        static void CoalesceContainerVisuals(ObjectGraph <Node> graph)
        {
            // If a container is not animated and has no properties set, its children can be inserted into its parent.
            var containersWithNoPropertiesSet = graph.CompositionObjectNodes.Where(n =>
            {
                // Find the ContainerVisuals that have no properties set.
                return
                (n.Object is ContainerVisual container &&
                 container.CenterPoint == null &&
                 container.Clip == null &&
                 container.Offset == null &&
                 container.Opacity == null &&
                 container.RotationAngleInDegrees == null &&
                 container.Scale == null &&
                 container.Size == null &&
                 container.TransformMatrix == null &&
                 container.Animators.Count == 0 &&
                 container.Properties.IsEmpty);
            }).ToArray();

            // Pull the children of the container into the parent of the container. Remove the unnecessary containers.
            foreach (var(Node, Object) in containersWithNoPropertiesSet)
            {
                var container = (ContainerVisual)Object;

                // Insert the children into the parent.
                var parent = (ContainerVisual)Node.Parent;
                if (parent == null)
                {
                    // The container may have already been removed, or it might be a root.
                    continue;
                }

                // Find the index in the parent of the container.
                // If childCount is 1, just replace the the container in the parent.
                // If childCount is >1, insert into the parent.
                var index = parent.Children.IndexOf(container);

                // Get the children from the container.
                var children = container.Children.ToArray();
                if (children.Length == 0)
                {
                    // The container has no children. This is rare but can happen if
                    // the container is for a layer type that we don't support.
                    continue;
                }

                // Remove the children from the container.
                container.Children.Clear();

                // Insert the first child where the container was.
                parent.Children[index] = children[0];

                // Fix the parent pointer in the graph.
                graph[children[0]].Parent = parent;

                // Insert the rest of the children.
                for (var i = 1; i < children.Length; i++)
                {
                    parent.Children.Insert(index + i, children[i]);

                    // Fix the parent pointer in the graph.
                    graph[children[i]].Parent = parent;
                }
            }
        }
Пример #23
0
        public override async Task <IGenesisExecutionResult> Execute(GenesisContext genesis, string[] args)
        {
            Text.WhiteLine($"Downloading from [{Config.Address}]");

            //https://swagger.io/docs/specification/basic-structure/
            var gen = await OpenApiDocument.FromUrlAsync(Config.Address);

            gen.GenerateOperationIds();

            var usings = new[] {
                "System",
                "System.Text",
                "System.Collections",
                "System.Collections.Generic",
                "System.Threading.Tasks",
                "System.Linq",
                "System.Net.Http",
                "System.ComponentModel.DataAnnotations",
                "Newtonsoft.Json",
            };

            var settings = new CSharpClientGeneratorSettings
            {
                GenerateDtoTypes = true,
                AdditionalContractNamespaceUsages = usings,
                AdditionalNamespaceUsages         = usings
            };

            settings.CodeGeneratorSettings.InlineNamedAny = true;
            settings.CSharpGeneratorSettings.Namespace    = Config.OutputNamespace;
            settings.CSharpGeneratorSettings.ClassStyle   = CSharpClassStyle.Inpc;

            var generator = new NSwag.CodeGeneration.OperationNameGenerators.MultipleClientsFromFirstTagAndPathSegmentsOperationNameGenerator();

            var csgen = new CSharpClientGenerator(gen, settings);

            csgen.Settings.GenerateOptionalParameters = true;
            csgen.Settings.GenerateResponseClasses    = true;
            csgen.Settings.SerializeTypeInformation   = true;
            csgen.Settings.OperationNameGenerator     = generator;

            Text.White($"Processing contents... ");
            var code = csgen.GenerateFile(ClientGeneratorOutputType.Full);

            Text.GreenLine("OK");

            var trustedAssembliesPaths = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")).Split(Path.PathSeparator);
            var neededLibs             = new [] {
                "mscorlib",
                "netstandard",
                "System.Core",
                "System.Runtime",
                "System.IO",
                "System.ObjectModel",
                "System.Linq",
                "System.Net.Http",
                "System.Collections",
                "System.CodeDom.Compiler",
                "System.ComponentModel",
                "System.ComponentModel.Annotations",
                "System.Net.Primitives",
                "System.Runtime.Serialization",
                "System.Runtime.Serialization.Primitives",
                "System.Runtime.Extensions",
                "System.Private.Uri",
                "System.CodeDom",
                "System.Composition.AttributedModel",
                "System.Composition.Convention",
                "System.Composition.Runtime",
                "System.Diagnostics.Tools",
                "Microsoft.CodeAnalysis.CSharp",
                "NJsonSchema",
                "Newtonsoft.Json",
            };

            Text.WhiteLine($"Determining dependencies");

            var refs = trustedAssembliesPaths
                       .Where(p => neededLibs.Contains(Path.GetFileNameWithoutExtension(p)))
                       .Select(p => MetadataReference.CreateFromFile(p))
                       .ToList();

            refs.Add(MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location));

            var options = new CSharpParseOptions(LanguageVersion.CSharp8, DocumentationMode.Parse, SourceCodeKind.Regular);

            Text.WhiteLine("Defining entry point");
            var    rdr   = new StringReader(code);
            var    lines = new StringBuilder();
            var    i     = 0;
            string line;

            while ((line = await rdr.ReadLineAsync()) != null)
            {
                lines.AppendLine(line);
                if (i == 26) //lol lame
                {
                    lines.AppendLine(ENTRY_POINT);
                }
                i++;
            }

            code = lines.ToString();
            File.WriteAllText(@"C:\Temp\GeneratedCode.cs", code);

            Text.WhiteLine("Creating Syntax Tree");
            var syntax = CSharpSyntaxTree.ParseText(code, options: options);

            Text.WhiteLine("Preprocessing");
            var comp = CSharpCompilation.Create("swag-gen-temp.dll", new[] { syntax }, refs.ToArray());

            await using var stream = new MemoryStream();

            Text.White("Creating temporary objects... ");
            var result = comp.Emit(stream);

            Text.GreenLine("OK");

            if (!result.Success)
            {
                Text.RedLine("Unable to build temp library");
                var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);

                foreach (var diagnostic in failures)
                {
                    Text.RedLine($@"\t{diagnostic.Id}: {diagnostic.GetMessage()}");
                }

                return(new InputGenesisExecutionResult {
                    Success = false, Message = "Errors occurred"
                });
            }

            stream.Seek(0, SeekOrigin.Begin);

            var tmpAss = AssemblyLoadContext.Default.LoadFromStream(stream);

            // loop classes
            foreach (var c in tmpAss.GetTypes().Where(w => w.IsClass))
            {
                Text.GrayLine($"Class: {c.Name}");

                var obj = new ObjectGraph {
                    Name      = c.Name,
                    Namespace = Config.OutputNamespace,
                    GraphType = GraphTypes.Object,
                };

                foreach (var p in c.GetProperties().Where(w => w.MemberType == MemberTypes.Property))
                {
                    if (!p.CanWrite || !p.GetSetMethod(/*nonPublic*/ true).IsPublic)
                    {
                        continue; //for now;
                    }
                    var pg = new PropertyGraph {
                        Name          = p.Name,
                        SourceType    = p.PropertyType.Name,
                        IsKeyProperty = p.Name.EndsWith("Id", StringComparison.CurrentCultureIgnoreCase), //NOTE: cheesy
                        Accesibility  = (p.CanWrite &&
                                         p.GetSetMethod(/*nonPublic*/ true).IsPublic)
                                        ? "public"
                                        : "protected"
                    };

                    obj.Properties.Add(pg);
                    Text.GrayLine($"\tProperty: {c.Name}");
                }

                foreach (var m in c.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                {
                    var meth = new MethodGraph
                    {
                        Name             = m.Name.Replace("get_", string.Empty),
                        MethodVisibility = MethodVisibilities.Public,
                        ReturnDataType   = m.ReturnType,
                        HasGenericParams = m.ContainsGenericParameters,
                        IsGeneric        = m.IsGenericMethod,
                    };

                    foreach (var par in m.GetParameters().Where(w => w.IsIn).OrderBy(o => o.Position))
                    {
                        var mp = new ParameterGraph {
                            DataType   = par.ParameterType,
                            Name       = par.Name,
                            IsOut      = par.IsOut,
                            IsOptional = par.IsOptional,
                            Position   = par.Position
                        };

                        meth.Parameters.Add(mp);

                        Text.GrayLine($"\tMethod: {c.Name}");
                    }
                }
                genesis.Objects.Add(obj);
            }

            Text.SuccessGraffiti();

            return(await base.Execute(genesis, args)); //TODO: fix the whole IGenesisExecutionResult "stuff"
        }
Пример #24
0
 Optimizer(ObjectGraph <ObjectData> graph)
 {
     _graph = graph;
 }
Пример #25
0
        private static void Main(string[] args)
        {
            /*using(var fileStream = File.OpenRead(@"E:\workspace\tre\patch_05.tre"))
             * {
             *   var treReader = new TREFileReader();
             *   var treeFile = treReader.Load(fileStream);
             *
             *   var found = treeFile.InfoFiles.FirstOrDefault(cur => cur.Name.ToLower().Contains("shared_base_object.iff"));
             *
             *   if (found != null)
             *   {
             *       var treeStream = found.Open(fileStream);
             *       var iffReader = new IFFFileReader();
             *       var iffFile = iffReader.Load(treeStream);
             *       //var root = iffFile.Root.Children.ToList();
             *
             *       var sharedObject = new SharedObjectTemplate(iffFile);
             *
             *   }
             * }*/

            //var repo = new ArchiveRepository(@"D:\SWGTrees");
            //repo.LoadArchives();

            //var templateRepo = new TemplateRepository
            //{
            //    ArchiveRepo = repo,
            //};



            //var tmp = repo.LoadCrCMap("misc/object_template_crc_string_table.iff");

            //var last = tmp.CRCMap.Last();

            //var stringFile = repo.LoadStf("string/en/city/city.stf");

            //Console.WriteLine("Enter to end;");
            //Console.ReadLine();
            //return;

            //var addrToConnect = "swgemutest";
            //var connectToServerName = "swgemutest";


            LogAbstraction.LogManagerFacad.ManagerImplementaiton = new NlogLogManagerImplementaion();

            var graph = new ObjectGraph {
                ConnectTimeout = TimeSpan.FromMilliseconds(30000)
            };

            graph.ResolveMessageFactories();
            graph.ResolveFallbackMessageFactory();
            graph.RegisterMessagesInFacories();
            graph.RegisterMessagesInFallbackFactory();

            var connector = new SessionLogin
            {
                Server   = "login.swgemu.com",
                Password = "******",
                Username = "******"
            };

            Console.WriteLine("Connecting to login server");
            connector.ConnectToLoginServer();
            Console.WriteLine("Logging in to login server");
            connector.LoginToServer();

            var serverToConnect = connector.AvailableServers.First(cur => cur.Name.Contains("Nova"));

            Console.WriteLine("Establishing connecting to game server: {0}:{1}", serverToConnect.ServerIP, serverToConnect.ServerPort);


            graph.EstablishConnection(connector.UserId, connector.SessionKey, IPAddress.Parse(serverToConnect.ServerIP),
                                      serverToConnect.ServerPort);
            Console.WriteLine("Logging in character");
            graph.LoginCharacter(serverToConnect.Characters.First().CharacterID);
            Console.WriteLine("Press enter to exit");
            Console.ReadLine();
        }
Пример #26
0
 private async Task LoadCompanyAsync()
 {
     Company = await CompanyService.GetDemoCompanyObjectGraph();
 }
Пример #27
0
        /// <summary>
        /// Demonstration Mode
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="msg"></param>
        /// <param name="output"></param>
        /// <returns></returns>
        private QueryFeedbackState QueryObjectiveGraph(object obj, out string msg, out object output)
        {
            output = null;
            msg    = null;

            if (ObjectGraph == null)
            {
                msg = "You do not select the answer successfully.";
                QueriedKnowledge = null;
                return(QueryFeedbackState.QueryFailed);
            }

            if (ObjectGraph.Nodes.Count == 0 || ObjectGraph.Nodes.Count == 1)
            {
                msg = "No internal procedural knowledge to present.";
                QueriedKnowledge = null;
                return(QueryFeedbackState.QueryFailed);
            }

            if (obj != null)
            {
                //verify user's own step
                var matchedNode = ObjectGraph.SearchInnerLoopNode(obj);

                msg = matchedNode == null ?
                      AGTutorMessage.VerifyWrong : AGTutorMessage.VerifyCorrect;

                if (matchedNode == null)
                {
                    return(QueryFeedbackState.DemonQueryVerify);
                }

                Debug.Assert(matchedNode != null);

                var nextTuple1 = ObjectGraph.SearchNextInnerLoopNode(matchedNode);
                if (nextTuple1 == null)
                {
                    msg = AGTutorMessage.SolvedProblem;
                }
                CurrentStateNode = matchedNode;
                return(QueryFeedbackState.DemonQueryVerify);
            }

            if (CurrentStateNode == null) // QueryNotStart
            {
                CurrentStateNode = ObjectGraph.RetrieveInitInnerNode();

                /*                object obj2 = ObjectGraph.SearchInnerLoopNode(parentNode);
                 *              var behaviorNode = obj2 as BehaviorGraphNode;
                 *              var lstNode = obj2 as List<BehaviorGraphNode>;
                 *              if (behaviorNode != null)
                 *              {
                 *                  _currentStateNode = behaviorNode;
                 *              }
                 *              if (lstNode != null)
                 *              {
                 *                  //TODO
                 *                  _currentStateNode = lstNode[0];
                 *              }*/

                Debug.Assert(_currentStateNode != null);

                msg = AGDemonstrationMessage.QueryAnswer;

                var lst    = ObjectGraph.SearchAllOuterEdgeInfos();
                int number = ObjectGraph.PathFinding(CurrentStateNode);

                output = new Tuple <object, object>(lst, number);

                return(QueryFeedbackState.DemonQueryStarted);
            }

            Debug.Assert(_currentStateNode != null);

            //direct query without verification
            object            edgeInfo = null;
            BehaviorGraphNode nextNode = null;
            var nextTuple2             = ObjectGraph.SearchNextInnerLoopNode(_currentStateNode);

            if (nextTuple2 == null) // query-end
            {
                msg = AGDemonstrationMessage.QueryEnd;
                return(QueryFeedbackState.DemonQueryEnded);
            }
            var tuple22    = nextTuple2 as Tuple <object, object>;
            var tuple22Lst = nextTuple2 as List <Tuple <object, object> >;

            if (tuple22 != null)
            {
                edgeInfo = tuple22.Item1;
                nextNode = tuple22.Item2 as BehaviorGraphNode;
            }
            if (tuple22Lst != null)
            {
                var tupleTemp = tuple22Lst[0];
                edgeInfo = tupleTemp.Item1;
                nextNode = tupleTemp.Item2 as BehaviorGraphNode;
            }

            Debug.Assert(nextNode != null);
            var nodeState = nextNode.State as InnerLoopBehaviorState;

            Debug.Assert(nodeState != null);
            var    expr          = IKnowledgeGenerator.Generate(nodeState.UserKnowledge);
            var    innerEdgeProp = edgeInfo as InnerLoopEdgeProperty;
            var    outerEdgeProp = edgeInfo as OuterLoopEdgeProperty;
            string appliedRule   = null;

            if (innerEdgeProp != null)
            {
                appliedRule = innerEdgeProp.AppliedRule;
            }
            if (outerEdgeProp != null)
            {
                appliedRule = outerEdgeProp.Strategy;
            }
            int leftTraceCount = ObjectGraph.PathFinding(nextNode);

            int parentIndex = ObjectGraph.SearchOuterLoopNodeIndex(nextNode);
            var lst1        = ObjectGraph.SearchAllOuterEdgeInfos();
            var tuple1      = new Tuple <object, object>(lst1, parentIndex);

            output = new Tuple <object, object, object, object>(appliedRule, expr, leftTraceCount, tuple1);

            CurrentStateNode = nextNode;
            return(QueryFeedbackState.DemonQueryProcessed);
        }
Пример #28
0
 public void ReturnsTheRoot()
 {
     var i = new {};
     var list = new ObjectGraph().Traverse(i);
     Assert.Contains(i, list);
 }
Пример #29
0
        private static string FormatChild(string path, object childValue, bool useLineBreaks, ObjectGraph graph)
        {
            try
            {
                if (string.IsNullOrEmpty(path))
                {
                    throw new ArgumentNullException(nameof(path), "Formatting a child value requires a path");
                }

                if (!graph.TryPush(path, childValue))
                {
                    return($"{{Cyclic reference to type {childValue.GetType()} detected}}");
                }
                else if (graph.Depth > MaxDepth)
                {
                    return("{Maximum recursion depth was reached…}");
                }
                else
                {
                    var context = new FormattingContext
                    {
                        Depth         = graph.Depth,
                        UseLineBreaks = useLineBreaks
                    };

                    return(Format(childValue, context, (x, y) => FormatChild(x, y, useLineBreaks, graph)));
                }
            }
            finally
            {
                graph.Pop();
            }
        }
Пример #30
0
 public static IEnumerable <T> EnumFromGraph <T>(this ObjectGraph graph, Func <ObjectGraph, T> func) => graph.Children.Select(func);
Пример #31
0
 CanonicalizerWorker(ObjectGraph <TNode> graph, bool ignoreCommentProperties)
 {
     _graph = graph;
     _ignoreCommentProperties = ignoreCommentProperties;
 }
Пример #32
0
 internal static void Canonicalize <T>(ObjectGraph <T> graph, bool ignoreCommentProperties)
     where T : CanonicalizedNode <T>, new()
 {
     CanonicalizerWorker <T> .Canonicalize(graph, ignoreCommentProperties);
 }
Пример #33
0
            internal static void Canonicalize(ObjectGraph <TNode> graph, bool ignoreCommentProperties)
            {
                var canonicalizer = new CanonicalizerWorker <TNode>(graph, ignoreCommentProperties);

                canonicalizer.Canonicalize();
            }
Пример #34
0
 /// <summary>
 /// Performs Injection into target fields decorated with [Inject] attribute
 /// </summary>
 public void InjectInto(object target)
 {
     target.NonNull(nameof(target));
     ObjectGraph.Scope(nameof(ApplicationDependencyInjector), target, body);
 }
Пример #35
0
        public ObjectGraph Parse(string[] source, int position = 0)
        {
            singleParser.Source          = source;
            groupParser.Source           = source;
            singleCharacterParser.Source = source;
            replacementParser.Source     = source;
            macroParser.Source           = source;
            arrayItemParser.Source       = source;

            var result = new ObjectGraph(name, "", type, key);
            var length = source.Length;

            while (position < length)
            {
                if (source[position].IsEmpty())
                {
                    position++;
                    continue;
                }

                var lineNumber = position + 1;
                var lineSource = source[position];
                if (singleParser.Parse(source, position, replacer))
                {
                    position = update(singleParser, result, lineNumber, lineSource);
                }
                else if (singleCharacterParser.Parse(source, position, replacer))
                {
                    position = update(singleCharacterParser, result, lineNumber, lineSource);
                }
                else if (macroParser.Parse(source, position, replacer))
                {
                    position = macroParser.Position;
                }
                else if (replacementParser.Parse(source, position, replacer))
                {
                    position = replacementParser.Position;
                }
                else if (arrayItemParser.Parse(source, position, replacer))
                {
                    position = update(arrayItemParser, result, lineNumber, lineSource);
                }
                else if (groupParser.Parse(source, position, replacer))
                {
                    position = update(groupParser, result, lineNumber, lineSource);
                }
                else if (BaseParser.TabCount > -1)
                {
                    BaseParser.TabCount--;
                    position--;
                    break;
                }
                else
                {
                    break;
                }
            }

            Position = position;
            return(result);
        }
Пример #36
0
        public void Testout()
        {
            ConfigurationLayer cl = new ConfigurationLayer();

            ConfigurationItem item1 = new ConfigurationItem();
            cl.Items.AddConfigurationItem("plugin1", ConfigurationStatus.Running);

            Assert.That( item1.Status == ConfigurationStatus.Running );
            Assert.That( item1.ServiceOrPluginName == "plugin1" );

            ConfigurationItem item2 = new ConfigurationItem();
            cl.Items.AddConfigurationItem( "service1", ConfigurationStatus.Running );

            Assert.That( item1.Status == ConfigurationStatus.Running );
            Assert.That( item1.ServiceOrPluginName == "service1" );

            ConfigurationManager cm = new ConfigurationManager();

            cm.AddLayer( cl );

            Objectgraph Og = new ObjectGraph( cm );

            Og.Resolve();

            Og.Release();
        }
        XDocument ToXDocument(CompositionObject compositionObject)
        {
            // Build the graph of objects.
            _objectGraph = ObjectGraph <ObjectData> .FromCompositionObject(compositionObject, includeVertices : true);

            // Give names to each object.
            foreach ((var node, var name) in CodeGen.NodeNamer <ObjectData> .GenerateNodeNames(_objectGraph.Nodes))
            {
                node.Name = name;
            }

            // Initialize each node.
            foreach (var n in _objectGraph.Nodes)
            {
                n.Initialize(this);
            }

            // Second stage initialization - relies on all nodes having had the first stage of initialization.
            foreach (var n in _objectGraph.Nodes)
            {
                n.Initialize2();
            }

            var rootNode = _objectGraph[compositionObject];

            // Give the root object a special name and category.
            rootNode.Name     = $"{rootNode.Name} (Root)";
            rootNode.Category = CategoryRoot;

            // Get the groups.
            var groups = GroupTree(rootNode, null).ToArray();

            // Get the Nodes for the objects that are going to show up in the DGML.
            var objectNodes = _objectGraph.Nodes.Where(n => n.IsDgmlNode).ToArray();

            // Create the DGML nodes.
            var nodes =
                from n in objectNodes
                select CreateNodeXml(id : n.Id !, label : n.Name, category : n.Category?.Id);

            // Create the DGML nodes for the groups.
            nodes = nodes.Concat(
                from gn in groups
                select CreateNodeXml(id: gn.Id !, label: gn.GroupName, @group: "Expanded"));

            // Create the categories used by object nodes.
            var categories =
                (from n in objectNodes
                 select n.Category).Distinct();

            // Create the links between the nodes.
            var links =
                from n in objectNodes
                from otherNode in n.Children
                select new XElement(
                    ns + "Link",
                    new XAttribute("Source", n.Id),
                    new XAttribute("Target", otherNode.Id));

            // Create the "contains" links for the nodes contained in groups.
            var containsLinks =
                (from g in groups
                 from member in g.ItemsInGroup
                 select new XElement(
                     ns + "Link",
                     new XAttribute("Source", g.Id),
                     new XAttribute("Target", member.Id),
                     new XAttribute("Category", "Contains"))).ToArray();

            // Create the "contains" links for the groups contained in groups
            var groupContainsGroupsLinks =
                (from g in groups
                 from member in g.GroupsInGroup
                 select new XElement(
                     ns + "Link",
                     new XAttribute("Source", g.Id),
                     new XAttribute("Target", member.Id),
                     new XAttribute("Category", "Contains"))).ToArray();

            containsLinks = containsLinks.Concat(groupContainsGroupsLinks).ToArray();

            // Create the XML
            return(new XDocument(
                       new XElement(
                           ns + "DirectedGraph",
                           new XElement(ns + "Nodes", nodes),
                           new XElement(ns + "Links", links.Concat(containsLinks)),
                           new XElement(
                               ns + "Categories",
                               categories.Select(c => c.ToXElement()).Append(
                                   new XElement(
                                       ns + "Category",
                                       new XAttribute("Id", "Contains"),
                                       new XAttribute("Label", "Contains"),
                                       new XAttribute("Description", "Whether the source of the link contains the target object"),
                                       new XAttribute("CanBeDataDriven", "False"),
                                       new XAttribute("CanLinkedNodesBeDataDriven", "True"),
                                       new XAttribute("IncomingActionLabel", "Contained By"),
                                       new XAttribute("IsContainment", "True"),
                                       new XAttribute("OutgoingActionLabel", "Contains")))
                               ),
                           new XElement(
                               ns + "Properties",
                               CreatePropertyXml(id: "Bounds", dataType: "System.Windows.Rect"),
                               CreatePropertyXml(id: "CanBeDataDriven", label: "CanBeDataDriven", description: "CanBeDataDriven", dataType: "System.Boolean"),
                               CreatePropertyXml(id: "CanLinkedNodesBeDataDriven", label: "CanLinkedNodesBeDataDriven", description: "CanLinkedNodesBeDataDriven", dataType: "System.Boolean"),
                               CreatePropertyXml(id: "Group", label: "Group", description: "Display the node as a group", dataType: "Microsoft.VisualStudio.GraphModel.GraphGroupStyle"),
                               CreatePropertyXml(id: "IncomingActionLabel", label: "IncomingActionLabel", description: "IncomingActionLabel", dataType: "System.String"),
                               CreatePropertyXml(id: "IsContainment", dataType: "System.Boolean"),
                               CreatePropertyXml(id: "Label", label: "Label", description: "Displayable label of an Annotatable object", dataType: "System.String"),
                               CreatePropertyXml(id: "Layout", dataType: "System.String"),
                               CreatePropertyXml(id: "OutgoingActionLabel", label: "OutgoingActionLabel", description: "OutgoingActionLabel", dataType: "System.String"),
                               CreatePropertyXml(id: "UseManualLocation", dataType: "System.Boolean"),
                               CreatePropertyXml(id: "ZoomLevel", dataType: "System.String")
                               )
                           )
                       ));
        }
Пример #38
0
 public CollisionMessageManager(ObjectGraph objectGraph)
 {
     this.objectGraph = objectGraph;
     channels         = new Dictionary <int, CollisionMessageChannel>();
 }
Пример #39
0
        /// <summary> Looks for the connected components and extracts data
        /// </summary>
        private void FindConnectedComponents()
        {
            graph = new ObjectGraph();

            switch (connectivity)
            {
                case eConnectivity.TWOD_4: detect4(); break;
                case eConnectivity.THREED_6: detect6(); break;
                case eConnectivity.TWOD_8: detect8(); break;
                case eConnectivity.TWOD_24: detect24(); break;
                case eConnectivity.THREED_26: detect26(); break;
                default: throw new Exception("Connectivity must be 4, 6, 8, 24 or 26");
            }

            /* determine the final labels */
            int numCom = 0;
            int index = -1;

            Dictionary<int, ConnectedVoxels> hm = new Dictionary<int, ConnectedVoxels>();
            int key;
            for (int k = 0; k < depth; k++)
                for (int j = 0; j < height; j++)
                    for (int i = 0; i < width; i++)
                        if (labeledOutput[++index] != 0f)
                        {
                            key = graph.getAncestorLabel((int)labeledOutput[index]);

                            if (!hm.ContainsKey(key)) hm.Add(key, new ConnectedVoxels(++numCom,
                                                                                    labeledOutputImage,
                                                                                    image,
                                                                                    connectivity));

                            labeledOutput[index] = hm[key].Label;
                            hm[key].Add(index, i, j, k);
                        }

            //display(labeledOutput);
            if (numCom == 0) return;

            /* use the volume constraint */
            ConnectedVoxels[] foundObjectsBefore = new ConnectedVoxels[numCom];
            ArrayList foundObjectsAfter = new ArrayList();
            foreach (ConnectedVoxels fo in hm.Values)
                foundObjectsBefore[fo.Label - 1] = fo;
            int[] relb = new int[numCom]; // relabel array
            for (int i = 0; i < numCom; i++)
                relb[i] = i + 1;
            int reNumCom = numCom;
            for (int i = 0; i < numCom; i++)
                if (foundObjectsBefore[i].Volume < min || foundObjectsBefore[i].Volume > max)// || coarr[i].IsOnEdge)
                {
                    relb[i] = 0;
                    for (int j = i + 1; j < numCom; j++)
                    {
                        relb[j]--;
                        foundObjectsBefore[j].Label--;
                    }
                    reNumCom--;
                }
                else
                {
                    foundObjectsAfter.Add(foundObjectsBefore[i]);
                }

            // relabel with the constraint
            for (int i = 0; i < labeledOutput.Length; i++)
            {
                index = (int)labeledOutput[i];
                if (index > 0 && index != relb[index - 1])
                    labeledOutput[i] = relb[index - 1];
            }

            if (reNumCom == 0) return;

            this.cc = (ConnectedVoxels[])foundObjectsAfter.ToArray(typeof(ConnectedVoxels));
        }