Example #1
0
        /// <summary>
        /// Resets the overrides attached to this node and its descendants, recursively.
        /// </summary>
        /// <param name="indexToReset">The index of the override to reset in this node, if relevant.</param>
        public void ResetOverride(Index indexToReset)
        {
            if (indexToReset.IsEmpty)
            {
                OverrideContent(false);
            }
            else
            {
                OverrideItem(false, indexToReset);
            }
            var visitor = PropertyGraph.CreateReconcilierVisitor();

            visitor.SkipRootNode = true;
            visitor.Visiting    += (node, path) =>
            {
                var childNode = (AssetNode)node;
                childNode.OverrideContent(false);
                foreach (var overrideItem in childNode.GetOverriddenItemIndices())
                {
                    childNode.OverrideItem(false, overrideItem);
                }
                foreach (var overrideKey in childNode.GetOverriddenKeyIndices())
                {
                    childNode.OverrideKey(false, overrideKey);
                }
            };
            visitor.Visit(this);

            PropertyGraph.ReconcileWithBase(this);
        }
Example #2
0
        private static void CreateObjectPropertyGraphs(TypeInfo cls, ObjectGraph obj)
        {
            foreach (var p in cls.GetProperties().Where(w => w.MemberType == MemberTypes.Property))
            {
                var pg = new PropertyGraph
                {
                    Name          = _nullableRegex.IsMatch(p.Name) ? _nullableRegex.Match(p.Name).Value : p.Name,
                    SourceType    = p.PropertyType.GetFormattedName(true),
                    IsKeyProperty = p.Name.EndsWith("Id", StringComparison.CurrentCultureIgnoreCase), //NOTE: cheesy
                };

                foreach (var m in p.GetAccessors())
                {
                    if (m.Name.StartsWith("get_"))
                    {
                        pg.GetterVisibility = (m.IsPublic) ? MethodVisibilities.Public :
                                              m.IsPrivate ? MethodVisibilities.Private : MethodVisibilities.Protected;
                    }

                    if (m.Name.StartsWith("set_"))
                    {
                        pg.SetterVisibility = (m.IsPublic) ? MethodVisibilities.Public :
                                              m.IsPrivate ? MethodVisibilities.Private : MethodVisibilities.Protected;
                    }
                }

                obj.Properties.Add(pg);
                Text.GrayLine(
                    $"\tProperty: {p.Name}, Type: {p.PropertyType.GetFormattedName()}, Get: {Enum.GetName(typeof(MethodVisibilities), pg.GetterVisibility)}, Set: {Enum.GetName(typeof(MethodVisibilities), pg.SetterVisibility)}");
            }
        }
        public void GraphInitializerConstructorTest()
        {

            var graph = new PropertyGraph(g => g.SetProperty("hello", "world!"));

            Assert.IsNotNull(graph);
            Assert.IsNotNull(graph.IdKey);
            Assert.IsNotNull(graph.RevIdKey);
            Assert.IsNotNull(graph.DescriptionKey);
            Assert.IsNull   (graph.Description);

        }
Example #4
0
 /// <inheritdoc/>
 public void ResetOverride(Index indexToReset)
 {
     if (indexToReset.IsEmpty)
     {
         OverrideContent(false);
     }
     else
     {
         OverrideItem(false, indexToReset);
     }
     PropertyGraph.ResetOverride(this, indexToReset);
 }
        public static IPropertyGraph CreateTinkerGraph()
        {

            var _TinkerGraph = new PropertyGraph() as IPropertyGraph;

            _TinkerGraph.OnVertexAddition.OnVoting += (graph, vertex, vote) => {
                Console.WriteLine("I like all vertices!");
            };

            _TinkerGraph.OnVertexAddition.OnVoting += (graph, vertex, vote) =>
            {
                if (vertex.Id == 5) {
                    Console.WriteLine("I'm a Jedi!");
                    vote.Deny();
                }
            };

            var marko  = _TinkerGraph.AddVertex(v => v.SetProperty("name", "marko"). SetProperty("age",   29));
            var vadas  = _TinkerGraph.AddVertex(v => v.SetProperty("name", "vadas"). SetProperty("age",   27));
            var lop    = _TinkerGraph.AddVertex(v => v.SetProperty("name", "lop").   SetProperty("lang", "java"));
            var josh   = _TinkerGraph.AddVertex(v => v.SetProperty("name", "josh").  SetProperty("age",   32));
            var vader  = _TinkerGraph.AddVertex(v => v.SetProperty("name", "darth vader"));
            var ripple = _TinkerGraph.AddVertex(v => v.SetProperty("name", "ripple").SetProperty("lang", "java"));
            var peter  = _TinkerGraph.AddVertex(v => v.SetProperty("name", "peter"). SetProperty("age",   35));

            Console.WriteLine("Number of vertices added: " + _TinkerGraph.Vertices().Count());

            marko.OnPropertyChanging += (sender, Key, oldValue, newValue, vote) =>
                Console.WriteLine("'" + Key + "' property changing: '" + oldValue + "' -> '" + newValue + "'");

            marko.OnPropertyChanged  += (sender, Key, oldValue, newValue)       =>
                Console.WriteLine("'" + Key + "' property changed: '"  + oldValue + "' -> '" + newValue + "'");


            var _DynamicMarko = marko.AsDynamic();
            _DynamicMarko.age  += 100;
            _DynamicMarko.doIt  = (Action<String>) ((text) => Console.WriteLine("Some infos: " + text + "!"));
            _DynamicMarko.doIt(_DynamicMarko.name + "/" + marko.GetProperty("age") + "/");


            var e7  = _TinkerGraph.AddEdge(marko, vadas,  7,  "knows",   e => e.SetProperty("weight", 0.5));
            var e8  = _TinkerGraph.AddEdge(marko, josh,   8,  "knows",   e => e.SetProperty("weight", 1.0));
            var e9  = _TinkerGraph.AddEdge(marko, lop,    9,  "created", e => e.SetProperty("weight", 0.4));

            var e10 = _TinkerGraph.AddEdge(josh,  ripple, 10, "created", e => e.SetProperty("weight", 1.0));
            var e11 = _TinkerGraph.AddEdge(josh,  lop,    11, "created", e => e.SetProperty("weight", 0.4));

            var e12 = _TinkerGraph.AddEdge(peter, lop,    12, "created", e => e.SetProperty("weight", 0.2));

            return _TinkerGraph;

        }
        public void GraphIdConstructorTest()
        {

            var graph = new PropertyGraph(123, null);

            Assert.IsNotNull(graph);
            Assert.IsNotNull(graph.IdKey);
            Assert.AreEqual(123UL, graph.Id);
            Assert.IsNotNull(graph.RevIdKey);
            Assert.IsNotNull(graph.DescriptionKey);
            Assert.IsNull   (graph.Description);

        }
        public void CopyGraphTest()
        {

            var _SourceGraph = TinkerGraphFactory.CreateTinkerGraph() as IPropertyGraph;

            var _NumberOfVertices = _SourceGraph.NumberOfVertices();
            var _NumberOfEdges    = _SourceGraph.NumberOfEdges();

            var _DestinationGraph = new PropertyGraph() as IPropertyGraph;
            //_SourceGraph.CopyGraph(_DestinationGraph);

            Assert.AreEqual(_NumberOfVertices, _DestinationGraph.NumberOfVertices());
            Assert.AreEqual(_NumberOfEdges,    _DestinationGraph.NumberOfEdges());

        }
        public void GraphIdAndHashCodeTest()
        {

            var graph1 = new PropertyGraph(123, null) { Description = "The first graph." };
            var graph2 = new PropertyGraph(256, null) { Description = "The second graph." };
            var graph3 = new PropertyGraph(123, null) { Description = "The third graph." };

            Assert.IsNotNull(graph1.Id);
            Assert.IsNotNull(graph2.Id);
            Assert.IsNotNull(graph3.Id);

            Assert.IsNotNull(graph1.Description);
            Assert.IsNotNull(graph2.Description);
            Assert.IsNotNull(graph3.Description);

            Assert.IsNotNull(graph1.GetHashCode());
            Assert.IsNotNull(graph2.GetHashCode());
            Assert.IsNotNull(graph3.GetHashCode());

            Assert.AreEqual(graph1.Id, graph1.GetHashCode());
            Assert.AreEqual(graph2.Id, graph2.GetHashCode());
            Assert.AreEqual(graph3.Id, graph3.GetHashCode());

            Assert.AreEqual(graph1.Id, graph3.Id);
            Assert.AreEqual(graph1.GetHashCode(), graph3.GetHashCode());

            Assert.AreNotEqual(graph1.Description, graph2.Description);
            Assert.AreNotEqual(graph2.Description, graph3.Description);
            Assert.AreNotEqual(graph3.Description, graph1.Description);

        }
        public void IPropertiesExtensionMethodsTest()
        {

            var graph = new PropertyGraph(123UL, g => g.SetProperty  (new KeyValuePair<String, Object>("hello",  "world!")).
                                                        SetProperties(new List<KeyValuePair<String, Object>>() { new KeyValuePair<String, Object>("graphs", "are cool!"),
                                                                                                                 new KeyValuePair<String, Object>("Keep",   "it simple!")}).
                                                        SetProperties(new Dictionary<String, Object>() { { "a", "b" }, { "c", "d" } }).
                                                        SetProperty  ("e", "f"));


            Assert.AreEqual(123UL,        graph.GetProperty("Id"));
            Assert.AreEqual("world!",     graph.GetProperty("hello"));
            Assert.AreEqual("are cool!",  graph.GetProperty("graphs"));
            Assert.AreEqual("it simple!", graph.GetProperty("Keep"));
            Assert.AreEqual("b",          graph.GetProperty("a"));
            Assert.AreEqual("d",          graph.GetProperty("c"));

            Assert.AreEqual(123UL,        graph.GetProperty("Id",     typeof(UInt64)));
            Assert.AreEqual("world!",     graph.GetProperty("hello",  typeof(String)));
            Assert.AreEqual("are cool!",  graph.GetProperty("graphs", typeof(String)));
            Assert.AreEqual("it simple!", graph.GetProperty("Keep",   typeof(String)));

            Assert.AreNotEqual("world!",  graph.GetProperty("hello",  typeof(UInt64)));


            // --[Action<TValue>]--------------------------------------------------------------

            Nullable<Boolean> check;
            check = null;
            graph.UseProperty("false",  OnSuccess_PropertyValue => check = true);
            Assert.IsNull(check);

            check = null;
            graph.UseProperty("Id",     OnSuccess_PropertyValue => check = true);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("hello",  OnSuccess_PropertyValue => check = true);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("graphs", OnSuccess_PropertyValue => check = true);
            Assert.IsTrue(check.Value);

            // --[Action<TKey, TValue>]--------------------------------------------------------

            check = null;
            graph.UseProperty("false",  (OnSuccess_PropertyKey, PropertyValue) => check = true);
            Assert.IsNull(check);

            check = null;
            graph.UseProperty("Id",     (OnSuccess_PropertyKey, PropertyValue) => check = true);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("hello",  (OnSuccess_PropertyKey, PropertyValue) => check = true);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("graphs", (OnSuccess_PropertyKey, PropertyValue) => check = true);
            Assert.IsTrue(check.Value);

            // --[Action<TValue>]--[Error]-----------------------------------------------------

            check = null;
            graph.UseProperty("false",  OnSuccess_PropertyValue => check = true, OnError => check = false);
            Assert.IsFalse(check.Value);

            check = null;
            graph.UseProperty("Id",     OnSuccess_PropertyValue => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("hello",  OnSuccess_PropertyValue => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("graphs", OnSuccess_PropertyValue => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);

            // --[Action<TKey, TValue>]--[Error]-----------------------------------------------

            check = null;
            graph.UseProperty("false",  (OnSuccess_PropertyKey, PropertyValue) => check = true, OnError => check = false);
            Assert.IsFalse(check.Value);

            check = null;
            graph.UseProperty("Id",     (OnSuccess_PropertyKey, PropertyValue) => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("hello",  (OnSuccess_PropertyKey, PropertyValue) => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);

            check = null;
            graph.UseProperty("graphs", (OnSuccess_PropertyKey, PropertyValue) => check = true, OnError => check = false);
            Assert.IsTrue(check.Value);


            // --[Func<TValue, TResult>]-------------------------------------------------------
#if !__MonoCS__
            Assert.AreEqual("world!?",      graph.PropertyFunc("hello",                 PropertyValue => { return (PropertyValue as String) + "?"; }));
            Assert.AreEqual(124UL,          graph.PropertyFunc("Id",                    PropertyValue => { return ( (UInt64) PropertyValue ) + 1; }));
            Assert.AreEqual(0,              graph.PropertyFunc("XYZ",                   PropertyValue => { return ( (UInt64) PropertyValue ) + 1; }));
            Assert.AreEqual(null,           graph.PropertyFunc("XYZ",                   PropertyValue => { return ( (String) PropertyValue ); }));
#endif
            Assert.AreEqual("world!?",      graph.PropertyFunc("hello", typeof(String), PropertyValue => { return (PropertyValue as String) + "?"; }));
            Assert.AreEqual(124UL,          graph.PropertyFunc("Id",    typeof(UInt64), PropertyValue => { return ( (UInt64) PropertyValue ) + 1; }));
            Assert.AreEqual(null,           graph.PropertyFunc("XYZ",   typeof(UInt64), PropertyValue => { return ( (UInt64) PropertyValue ) + 1; }));
            Assert.AreEqual(null,           graph.PropertyFunc("XYZ",   typeof(String), PropertyValue => { return ( (String) PropertyValue ); }));

#if !__MonoCS__
            // --[Func<TKey, TValue, TResult>]-------------------------------------------------
            Assert.AreEqual("hello world!", graph.PropertyFunc("hello",                 (OnSuccess_PropertyKey, PropertyValue) => { return OnSuccess_PropertyKey + " " + (PropertyValue as String); }));
            Assert.AreEqual("Id124",        graph.PropertyFunc("Id",                    (OnSuccess_PropertyKey, PropertyValue) => { return OnSuccess_PropertyKey + ((UInt64) PropertyValue + 1); }));
#endif
            Assert.AreEqual("hello world!", graph.PropertyFunc("hello", typeof(String), (OnSuccess_PropertyKey, PropertyValue) => { return OnSuccess_PropertyKey + " " + (PropertyValue as String); }));
            Assert.AreEqual("Id124",        graph.PropertyFunc("Id",    typeof(UInt64), (OnSuccess_PropertyKey, PropertyValue) => { return OnSuccess_PropertyKey + ((UInt64) PropertyValue + 1); }));


            // Filtered Keys/Values
            var FilteredKeys1   = graph.FilteredKeys  ((k, v) => true).ToList();
            Assert.NotNull(FilteredKeys1);
            Assert.AreEqual(8, FilteredKeys1.Count);

            var FilteredKeys2   = graph.FilteredKeys  ((k, v) => { if ((v as String).IsNotNullAndContains("!")) return true; else return false;}).ToList();
            Assert.NotNull(FilteredKeys2);
            Assert.AreEqual(3, FilteredKeys2.Count);


            var FilteredValues1 = graph.FilteredValues((k, v) => true).ToList();
            Assert.NotNull(FilteredValues1);
            Assert.AreEqual(8, FilteredValues1.Count);

            var FilteredValues2 = graph.FilteredValues((k, v) => { if ((v as String).IsNotNullAndContains("!")) return true; else return false; }).ToList();
            Assert.NotNull(FilteredValues2);
            Assert.AreEqual(3, FilteredValues2.Count);

        }
Example #10
0
 /// <inheritdoc/>
 public void ResetOverride(Index indexToReset)
 {
     PropertyGraph.ResetOverride(this, indexToReset);
 }
 public void RemoveRevIdTest3()
 {
     var graph = new PropertyGraph(123UL);
     graph.Remove((k, v) => k == "RevId");
 }
 public void RemoveRevIdTest2()
 {
     var graph = new PropertyGraph(123UL);
     graph.Remove("RevId", 0);
 }
 public void RemoveIdTest2()
 {
     var graph = new PropertyGraph(123UL);
     graph.Remove("Id", 123UL);
 }
 public void ChangeRevIdTest1()
 {
     var graph = new PropertyGraph(123UL);
     graph.SetProperty("RevId", 256UL);
 }
        public void GraphDescriptionTest()
        {

            var graph = new PropertyGraph(g => g.SetProperty("hello", "world!"));

            Assert.IsNotNull(graph);
            Assert.IsNotNull(graph.IdKey);
            Assert.IsNotNull(graph.RevIdKey);
            Assert.IsNotNull(graph.DescriptionKey);
            Assert.IsNull(graph.Description);

            graph.Description = "This is a property graph!";
            Assert.IsNotNull(graph.Description);
            Assert.AreEqual("This is a property graph!", graph.Description);

        }
Example #16
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"
        }
Example #17
0
        internal void ProcessReplacements()
        {
            foreach (var t in rewriteAssembly.GetTypes())
            {
                bool forceImplRewrite = t.Name.StartsWith("<PrivateImplementationDetails>");
                var  repl             = t.GetCustomAttribute <RewriteAttribute>(false);

                TypeGraph   typeTarget  = null;
                TypeRewrite typeRewrite = null;
                if (repl != null)
                {
                    if (repl.action == RewriteAction.Add)
                    {
                        typeTarget = new TypeGraph(t, null, _graph._modules.First());
                        if (repl.typeName != null)
                        {
                            typeTarget.FullName = repl.typeName;
                        }
                        continue;
                    }

                    typeTarget = (from x in Graph.Modules
                                  from y in x.TypeGraphs
                                  where y.FullName == repl.typeName
                                  select y).Single();

                    if (repl.action == RewriteAction.Replace)
                    {
                        typeTarget._replacementType = t;
                    }

                    _typeRewrites.Add(typeRewrite = new TypeRewrite()
                    {
                        MemberInfo = t, Rewrite = repl, Graph = typeTarget
                    });
                }

                foreach (var m in t.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                {
                    if (forceImplRewrite)
                    {
                        if (m is MethodInfo)
                        {
                            _staticImplCache.Add(m as MethodInfo);
                        }
                    }

                    var mRep = m.GetCustomAttribute <RewriteAttribute>();
                    if (mRep == null)
                    {
                        continue;
                    }

                    var mTypeTarget = mRep.typeName == null || (repl != null && repl.typeName == mRep.typeName) ? typeTarget : (from x in Graph.Modules
                                                                                                                                from y in x.TypeGraphs
                                                                                                                                where y.FullName == mRep.typeName
                                                                                                                                select y).Single();

                    if (typeRewrite == null)
                    {
                        _typeRewrites.Add(typeRewrite = new TypeRewrite()
                        {
                            MemberInfo = t
                        });
                    }

                    var name = mRep.targetName ?? m.Name;

                    if (m is MethodBase)
                    {
                        var         mb        = m as MethodBase;
                        var         target    = mTypeTarget.Methods.FirstOrDefault(x => x.Name == name);
                        MethodGraph newTarget = null;

                        if (mRep.action == RewriteAction.Add)
                        {
                            newTarget = new MethodGraph(mb, mTypeTarget);
                        }
                        else if (mRep.action == RewriteAction.Remove)
                        {
                            target.DeclaringObject = null;
                        }
                        else if (mRep.action != RewriteAction.None)
                        {
                            newTarget = target.SwitchImpl(mb, mRep.newName, mRep.oldName);
                            if (mRep.action == RewriteAction.Replace)
                            {
                                target.DeclaringObject = null;
                            }
                            else if (mRep.action == RewriteAction.Swap && newTarget.Name == target.Name)
                            {
                                target.Name += "_Orig";
                            }
                        }

                        if (mRep.contentHandler != null)
                        {
                            t.GetMethod(mRep.contentHandler).Invoke(null, new object[] { target, newTarget });
                        }

                        typeRewrite.MethodRewrites.Add(new RewriteInfo <MethodBase, MethodGraph>()
                        {
                            MemberInfo = mb,
                            Rewrite    = mRep,
                            Graph      = mRep.action == RewriteAction.Replace || mRep.stubAction == StubAction.UseNew ? (newTarget ?? target) : (target ?? newTarget)
                        });
                    }
                    else if (m is PropertyInfo)
                    {
                        var           p = m as PropertyInfo;
                        var           target = mTypeTarget.Properties.FirstOrDefault(x => x.Name == name);
                        PropertyGraph newTarget = null;
                        MethodGraph   newGet = null, newSet = null;
                        MethodGraph   oldGet = null, oldSet = null;

                        if (mRep.action == RewriteAction.Add)
                        {
                            newTarget = new PropertyGraph(p, mTypeTarget);
                            if (newTarget._getAccessor != null)
                            {
                                newGet = new MethodGraph(newTarget._getAccessor, mTypeTarget);
                            }
                            if (newTarget._setAccessor != null)
                            {
                                newSet = new MethodGraph(newTarget._setAccessor, mTypeTarget);
                            }
                        }
                        else
                        {
                            oldGet = target._getAccessor != null?mTypeTarget.Methods.FirstOrDefault(x => x._sourceObject == target._getAccessor) : null;

                            oldSet = target._setAccessor != null?mTypeTarget.Methods.FirstOrDefault(x => x._sourceObject == target._setAccessor) : null;

                            if (mRep.action == RewriteAction.Remove)
                            {
                                if (oldGet != null)
                                {
                                    oldGet.DeclaringObject = null;
                                }

                                if (oldSet != null)
                                {
                                    oldSet.DeclaringObject = null;
                                }

                                target.DeclaringObject = null;
                            }
                            else if (mRep.action != RewriteAction.None)
                            {
                                newTarget        = new PropertyGraph(p, mTypeTarget);
                                newTarget.Source = target.Source;

                                if (newTarget._getAccessor != null)
                                {
                                    newGet = oldGet.SwitchImpl(newTarget._getAccessor);
                                }
                                if (newTarget._setAccessor != null)
                                {
                                    newSet = oldSet.SwitchImpl(newTarget._setAccessor);
                                }

                                if (mRep.action == RewriteAction.Replace)
                                {
                                    if (oldGet != null)
                                    {
                                        oldGet.DeclaringObject = null;
                                    }

                                    if (oldSet != null)
                                    {
                                        oldSet.DeclaringObject = null;
                                    }

                                    target.DeclaringObject = null;
                                }
                                else if (mRep.action == RewriteAction.Swap && newTarget.Name == target.Name)
                                {
                                    target.Name += "_Orig";
                                    if (oldGet != null)
                                    {
                                        oldGet.Name += "_Orig";
                                    }
                                    if (oldSet != null)
                                    {
                                        oldSet.Name += "_Orig";
                                    }
                                }
                            }
                        }

                        if (mRep.contentHandler != null)
                        {
                            t.GetMethod(mRep.contentHandler).Invoke(null, new object[] { target, newTarget });
                        }

                        typeRewrite.PropertyRewrites.Add(new PropertyRewrite()
                        {
                            MemberInfo = p,
                            Rewrite    = mRep,
                            Graph      = mRep.action == RewriteAction.Replace || mRep.stubAction == StubAction.UseNew ? (newTarget ?? target) : (target ?? newTarget),
                            GetGraph   = mRep.action == RewriteAction.Replace || mRep.stubAction == StubAction.UseNew ? (newGet ?? oldGet) : (oldGet ?? newGet),
                            SetGraph   = mRep.action == RewriteAction.Replace || mRep.stubAction == StubAction.UseNew ? (newSet ?? oldSet) : (oldSet ?? newSet)
                        });
                    }
                    else if (m is FieldInfo)
                    {
                        var        f         = m as FieldInfo;
                        var        target    = mTypeTarget.Fields.FirstOrDefault(x => x.Name == name);
                        FieldGraph newTarget = null;

                        if (mRep.action == RewriteAction.Remove)
                        {
                            target.DeclaringObject = null;
                        }
                        else if (mRep.action != RewriteAction.None)
                        {
                            newTarget = new FieldGraph(f, mTypeTarget);

                            if (mRep.action == RewriteAction.Replace)
                            {
                                newTarget.Source       = target.Source;
                                target.DeclaringObject = null;
                            }
                            else if (mRep.action == RewriteAction.Swap)
                            {
                                target.Name += "_Orig";
                            }
                        }

                        if (mRep.contentHandler != null)
                        {
                            t.GetMethod(mRep.contentHandler).Invoke(null, new object[] { target, newTarget });
                        }

                        typeRewrite.FieldRewrites.Add(new RewriteInfo <FieldInfo, FieldGraph>()
                        {
                            MemberInfo = f,
                            Rewrite    = mRep,
                            Graph      = mRep.action == RewriteAction.Replace || mRep.stubAction == StubAction.UseNew ? (newTarget ?? target) : (target ?? newTarget)
                        });
                    }
                }
            }
        }
        public void ChangePropertyEventTest()
        {

            Nullable<Boolean> check = null;

            var graph = new PropertyGraph(123UL, g => g.SetProperty("key", "value").
                                                        SetProperty("nokey", "value"));

            graph.OnPropertyChanging += (g, key, oldvalue, newvalue, vote) => { if (key.StartsWith("ke")) vote.Ok(); else vote.Deny(); };
            graph.OnPropertyChanged  += (g, key, oldvalue, newvalue)       => check = true;

            graph.SetProperty("nokey", "value");
            Assert.IsNull(check);

            graph.SetProperty("key", "value");
            Assert.IsTrue(check.Value);

        }
Example #19
0
 /// <inheritdoc/>
 public void ResetOverrideRecursively(Index indexToReset)
 {
     OverrideItem(false, indexToReset);
     PropertyGraph.ResetAllOverridesRecursively(node, indexToReset);
 }
        public void RemovePropertyEventTest()
        {

            Nullable<Boolean> check = null;

            var graph = new PropertyGraph(123UL, g => g.SetProperty("key",   "value").
                                                        SetProperty("nokey", "value"));

            graph.OnPropertyRemoving += (g, key, value, vote) => { if (key.StartsWith("ke")) vote.Ok(); else vote.Deny(); };
            graph.OnPropertyRemoved  += (g, key, value)       => check = true;

            graph.Remove("nokey", "value");
            Assert.IsNull(check);
            Assert.IsTrue(graph.ContainsKey("nokey"));

            graph.Remove("key", "value");
            Assert.IsTrue(check.Value);
            Assert.IsFalse(graph.ContainsKey("key"));

        }