Beispiel #1
0
        public void RawView()
        {
            var source =
                @"using System.Diagnostics;
internal class P
{
    public P(C c)
    {
        this.G = c.F != null;
    }
    public readonly bool G;
}
[DebuggerTypeProxy(typeof(P))]
class C
{
    internal C() : this(new C(null))
    {
    }
    internal C(C f)
    {
        this.F = f;
    }
    internal readonly C F;
}
class Program
{
    static void Main()
    {
        var o = new C();
        System.Diagnostics.Debugger.Break();
    }
}";
            var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source)));

            using (runtime.Load())
            {
                var type = runtime.GetType("C");

                // Non-null value.
                var value      = type.Instantiate();
                var evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw));
                Verify(evalResult,
                       EvalResult("o", "{C}", "C", "o, raw", DkmEvaluationResultFlags.Expandable));
                var children = GetChildren(evalResult);
                Verify(children,
                       EvalResult("F", "{C}", "C", "o.F", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly));
                children = GetChildren(children[0]);
                // ShowValueRaw is not inherited.
                Verify(children,
                       EvalResult("G", "false", "bool", "new P(o.F).G", DkmEvaluationResultFlags.Boolean | DkmEvaluationResultFlags.ReadOnly),
                       EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data));

                // Null value.
                value = CreateDkmClrValue(
                    value: null,
                    type: type);
                evalResult = FormatResult("o", "o, raw", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.ShowValueRaw));
                Verify(evalResult,
                       EvalResult("o", "null", "C", "o, raw"));
            }
        }
Beispiel #2
0
        public void Initialise()
        {
            Simulations basicFile = Utilities.GetRunnableSim();

            IModel simulation = basicFile.FindInScope <Simulation>();
            IModel paddock    = basicFile.FindInScope <Zone>();

            // Add a weather component.
            Models.Climate.Weather weather = new Models.Climate.Weather();
            weather.Name     = "Weather";
            weather.FileName = "asdf.met";
            Structure.Add(weather, simulation);

            // Add a second weather component.
            Models.Climate.Weather weather2 = new Models.Climate.Weather();
            weather2.FileName = "asdf.met";
            weather2.Name     = "Weather2";
            Structure.Add(weather2, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather3 = new Models.Climate.Weather();
            weather3.FileName = "asdf.met";
            weather3.Name     = "Weather3";
            Structure.Add(weather3, simulation);

            // Add a third weather component.
            Models.Climate.Weather weather4 = new Models.Climate.Weather();
            weather4.FileName = "asdf.met";
            weather4.Name     = "Weather4";
            Structure.Add(weather4, simulation);

            // Add a report.
            Models.Report report = new Models.Report();
            report.Name = "Report";
            Structure.Add(report, paddock);

            // Add the wheat model.
            string json  = ReflectionUtilities.GetResourceAsString(typeof(IModel).Assembly, "Models.Resources.Wheat.json");
            Plant  wheat = FileFormat.ReadFromString <IModel>(json, out _).Children[0] as Plant;

            wheat.ResourceName = "Wheat";
            Structure.Add(wheat, paddock);

            Manager manager = new Manager();

            manager.Code = @"using Models.PMF;
using Models.Core;
using System;
namespace Models
{
    [Serializable]
    public class Script : Model
    {
        [Description(""an amount"")]
        public double Amount { get; set; }
    }
}";
            Structure.Add(manager, paddock);

            Physical physical = new Physical();

            physical.BD     = new double[5];
            physical.AirDry = new double[5];
            physical.LL15   = new double[5];
            Structure.Add(physical, paddock);
            Structure.Add(new WaterBalance(), paddock);
            Structure.Add(new SurfaceOrganicMatter(), paddock);

            basicFile.Write(basicFile.FileName);
            fileName = basicFile.FileName;

            // Create a new .apsimx file containing two weather nodes.
            Simulations test = Utilities.GetRunnableSim();
            IModel      sim  = test.FindInScope <Simulation>();

            Models.Climate.Weather w1 = new Models.Climate.Weather();
            w1.FileName = "w1.met";
            w1.Name     = "w1";
            Structure.Add(w1, sim);

            Models.Climate.Weather w2 = new Models.Climate.Weather();
            w2.Name     = "w2";
            w2.FileName = "w2.met";
            Structure.Add(w2, sim);

            extFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".apsimx");
            test.Write(extFile);
        }
Beispiel #3
0
 public UserTemplate CopyFrom(UserTemplate source)
 {
     return(ReflectionUtilities.Copy(source, this));
 }
Beispiel #4
0
        public void CreateGraphs()
        {
            Simulations sims = CreateTemplate();

            sims.FileName = Path.ChangeExtension(Path.GetTempFileName(), ".apsimx");

            DataStore storage = Apsim.Find(sims, typeof(DataStore)) as DataStore;

            storage.FileName = Path.ChangeExtension(sims.FileName, ".db");

            // Run the file to populate the datastore.
            Runner           runner = new Runner(sims);
            List <Exception> errors = runner.Run();

            if (errors != null && errors.Count > 0)
            {
                throw errors[0];
            }

            // Open the .apsimx file in the GUI.
            sims.Write(sims.FileName);
            ExplorerPresenter explorer = UITestsMain.MasterPresenter.OpenApsimXFileInTab(sims.FileName, true);

            GtkUtilities.WaitForGtkEvents();

            // Create a graphs folder under the zone.
            IModel paddock = Apsim.Find(sims, typeof(Zone));
            Folder graphs  = new Folder();

            graphs.Name = "Graphs";
            explorer.Add(graphs, Apsim.FullPath(paddock));

            // Add an empty graph to the folder.
            Models.Graph.Graph graph = new Models.Graph.Graph();
            graph.Name = "Graph";
            explorer.Add(graph, Apsim.FullPath(graphs));

            // Add an empty series to the graph.
            Models.Graph.Series series = new Models.Graph.Series();
            series.Name = "Series";
            explorer.Add(series, Apsim.FullPath(graph));

            // click on the series node.
            explorer.SelectNode(Apsim.FullPath(series));
            GtkUtilities.WaitForGtkEvents();

            // Get a reference to the OxyPlot PlotView via reflection.
            SeriesView seriesView = explorer.CurrentRightHandView as SeriesView;
            GraphView  view       = seriesView?.GraphView as GraphView;

            Assert.NotNull(view);

            PlotView plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;

            Assert.NotNull(plot);

            // Series has no table name or x/y series names yet, so there should
            // be nothing shown on the graph.
            Assert.AreEqual(0, plot.Model.Series.Count);

            // Now draw some data on the graph.
            seriesView.DataSource.SelectedValue = "Report";
            seriesView.X.SelectedValue          = "n";
            seriesView.Y.SelectedValue          = "n2";
            seriesView.SeriesType.SelectedValue = "Scatter";

            GtkUtilities.WaitForGtkEvents();

            // There should now be one series showing.
            Assert.AreEqual(1, plot.Model.Series.Count);

            // It should be a line series.
            Assert.True(plot.Model.Series[0] is LineSeries, "Graph series type is set to scatter, but the series object is not a LineSeries.");

            // Series colour should not be white, and should not be the same as the background colour.
            LineSeries line = plot.Model.Series[0] as LineSeries;

            OxyPlot.OxyColor empty = OxyPlot.OxyColor.FromArgb(0, 0, 0, 0);
            OxyPlot.OxyColor white = OxyPlot.OxyColor.FromArgb(0, 255, 255, 255);
            Assert.AreNotEqual(empty, line.Color, "Graph line series default colour is white on white.");
            Assert.AreNotEqual(white, line.Color, "Graph line series default colour is white on white.");

            // Legend should be visible but empty by default.
            Assert.True(plot.Model.IsLegendVisible);
            // todo - ensure legend is empty

            // Next, we want to change the legend position and ensure that the legend actually moves.

            // Click on the 'show in legend' checkbox.
            seriesView.ShowInLegend.IsChecked = true;
            GtkUtilities.WaitForGtkEvents();

            // Double click on the middle of the legend.
            Cairo.Rectangle legendRect = plot.Model.LegendArea.ToRect(true);
            double          x          = (legendRect.X + (legendRect.X + legendRect.Width)) / 2;
            double          y          = (legendRect.Y + (legendRect.Y + legendRect.Height)) / 2;

            GtkUtilities.DoubleClick(plot, x, y, wait: true);

            // Default legend position should be top-left.
            Assert.AreEqual(plot.Model.LegendPosition, OxyPlot.LegendPosition.TopLeft);

            // Now we want to change the legend position. First, get a reference to the legend view
            // via the legend presenter, via the graph presenter, via the series presenter, via the explorer presenter.
            Assert.True(explorer.CurrentPresenter is SeriesPresenter);
            SeriesPresenter seriesPresenter = explorer.CurrentPresenter as SeriesPresenter;
            LegendPresenter legendPresenter = seriesPresenter.GraphPresenter.CurrentPresenter as LegendPresenter;

            // todo: should we add something like a GetView() method to the IPresenter interface?
            // It might be a bit of work to set up but would save us having to use reflection
            LegendView legendView = ReflectionUtilities.GetValueOfFieldOrProperty("view", legendPresenter) as LegendView;

            // The legend options are inside a Gtk expander.
            Assert.IsTrue(legendView.MainWidget.Parent is Expander);
            Expander expander = legendView.MainWidget.Parent as Expander;

            // The expander should be expanded and the options visible.
            Assert.IsTrue(expander.Expanded);
            Assert.IsTrue(legendView.MainWidget.Visible);

            // The legend view contains a combo box with the legend position options (top-right, bottom-left, etc).
            // This should really be refactored to use a public IDropDownView, which is much more convenient to use.
            // First, get a reference to the combo box via reflection.
            ComboBox combo = ReflectionUtilities.GetValueOfFieldOrProperty("combobox1", legendView) as ComboBox;

            // fixme - we should support all valid OxyPlot legend position types.
            foreach (Models.Graph.Graph.LegendPositionType legendPosition in Enum.GetValues(typeof(Models.Graph.Graph.LegendPositionType)))
            {
                string name = legendPosition.ToString();
                GtkUtilities.SelectComboBoxItem(combo, name, wait: true);

                OxyPlot.LegendPosition oxyPlotEquivalent = (OxyPlot.LegendPosition)Enum.Parse(typeof(OxyPlot.LegendPosition), name);
                Assert.AreEqual(plot.Model.LegendPosition, oxyPlotEquivalent);
            }

            // If we change the graph to a box plot then the several unused properties should be disabled.
            // These are x variable dropdown, x cumulative, x on top, marker size/type checkboxes.

            // First, make sure that these options are sensitive to input and can be changed.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);

            // Now change series type to box plot.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Box", wait: true);
            Assert.AreEqual(SeriesType.Box, series.Type);

            // Ensure the box plot is not white in light theme.
            plot = ReflectionUtilities.GetValueOfFieldOrProperty("plot1", view) as PlotView;
            Assert.NotNull(plot);
            BoxPlotSeries boxPlot = plot.Model.Series.OfType <BoxPlotSeries>().FirstOrDefault();

            Assert.NotNull(boxPlot);

            Assert.AreNotEqual(empty, boxPlot.Fill);
            Assert.AreNotEqual(white, boxPlot.Fill);
            Assert.AreNotEqual(empty, boxPlot.Stroke);
            Assert.AreNotEqual(white, boxPlot.Stroke);

            // The controls should no longer be sensitive.
            Assert.IsFalse(seriesView.XCumulative.IsSensitive);
            Assert.IsFalse(seriesView.XOnTop.IsSensitive);
            Assert.IsFalse(seriesView.MarkerSize.IsSensitive);
            Assert.IsFalse(seriesView.MarkerType.IsSensitive);

            // Change the series type back to scatter.
            GtkUtilities.SelectComboBoxItem(seriesView.SeriesType, "Scatter", wait: true);

            // The controls should be sensitive once more.
            Assert.IsTrue(seriesView.X.IsSensitive);
            Assert.IsTrue(seriesView.XCumulative.IsSensitive);
            Assert.IsTrue(seriesView.XOnTop.IsSensitive);
            Assert.IsTrue(seriesView.MarkerSize.IsSensitive);
            Assert.IsTrue(seriesView.MarkerType.IsSensitive);
        }
Beispiel #5
0
 /// <summary>Inject a link into a model</summary>
 public static void InjectLink(object model, string linkFieldName, object linkFieldValue)
 {
     ReflectionUtilities.SetValueOfFieldOrProperty(linkFieldName, model, linkFieldValue);
 }
        public INode RegisterType(Type type)
        {
            if (ReflectionUtilities.IsAnonymousType(type))
            {
                // DevNote: Kinda hacky way to indicate the no-op case.
                return(rootNode);
            }

            INode n = GetAlreadyBoundNode(type);

            if (n != null)
            {
                return(n);
            }

            if (type.BaseType != null)
            {
                RegisterType(type.BaseType);
            }

            foreach (Type interf in type.GetInterfaces())
            {
                RegisterType(ReflectionUtilities.EnsureInterfaceType(interf));
            }

            Type enclosingClass = type.DeclaringType; // this.GetEnclosingClass(type);

            if (enclosingClass != null)
            {
                RegisterType(enclosingClass);
            }

            INode node = RegisterClass(type);

            foreach (Type inner in type.GetNestedTypes())
            {
                RegisterType(inner);
            }

            IClassNode classNode = node as ClassNodeImpl;

            if (classNode != null)
            {
                foreach (IConstructorDef constructorDef in classNode.GetInjectableConstructors())
                {
                    foreach (IConstructorArg constructorArg in constructorDef.GetArgs())
                    {
                        if (constructorArg.Gettype() == null)
                        {
                            Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException("not type in arg"), LOGGER);
                        }
                        RegisterType(constructorArg.Gettype());  // Gettype returns param's Type.fullname
                        if (constructorArg.GetNamedParameterName() != null)
                        {
                            var pn = RegisterType(constructorArg.GetNamedParameterName());

                            if (!(pn is INamedParameterNode))
                            {
                                string message = string.Format(CultureInfo.CurrentCulture,
                                                               "The class {0}, used in the constructor of {1}, should not be defined as a NamedParameter.",
                                                               constructorArg.GetNamedParameterName(),
                                                               constructorDef.GetClassName());
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException(message), LOGGER);
                            }

                            INamedParameterNode np = (INamedParameterNode)RegisterType(constructorArg.GetNamedParameterName());
                            try
                            {
                                if (np.IsSet() || np.IsList())
                                {
                                    // throw new NotImplementedException();
                                }
                                else
                                {
                                    if (!ReflectionUtilities.IsCoercable(ClassForName(constructorArg.Gettype()), ClassForName(np.GetFullArgName())))
                                    {
                                        var e = new ClassHierarchyException(
                                            "Named parameter type mismatch in " + classNode.GetFullName() + ".  Constructor expects a "
                                            + constructorArg.Gettype() + " but " + np.GetName() + " is a "
                                            + np.GetFullArgName());
                                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                                    }
                                }
                            }
                            catch (TypeLoadException e)
                            {
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                                var ex = new ClassHierarchyException("Constructor refers to unknown class "
                                                                     + constructorArg.GetType(), e);
                                Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                            }
                        }
                    }
                }
            }
            else
            {
                INamedParameterNode npNode = node as INamedParameterNode;
                if (npNode != null)
                {
                    RegisterType(npNode.GetFullArgName());
                }
            }

            return(node);
        }
Beispiel #7
0
 public WorkflowActor CopyFrom(WorkflowActor source)
 {
     return(ReflectionUtilities.Copy(source, this));
 }
Beispiel #8
0
        public DiscourseUser FromXmlElement(XmlElement element)
        {
            ReflectionUtilities.FromXmlElement(this, element);

            return(this);
        }
        public static Assembly GetAssembly(string source)
        {
            var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source);

            return(ReflectionUtilities.Load(comp.EmitToArray()));
        }
Beispiel #10
0
        public void MangledNames_ExplicitInterfaceImplementation()
        {
            var il = @"
.class interface public abstract auto ansi 'I<>Mangled'
{
  .method public hidebysig newslot specialname abstract virtual 
          instance int32  get_P() cil managed
  {
  }

  .property instance int32 P()
  {
    .get instance int32 'I<>Mangled'::get_P()
  }
} // end of class 'I<>Mangled'

.class public auto ansi beforefieldinit C
       extends [mscorlib]System.Object
       implements 'I<>Mangled'
{
  .method private hidebysig newslot specialname virtual final 
          instance int32  'I<>Mangled.get_P'() cil managed
  {
    .override 'I<>Mangled'::get_P
    ldc.i4.1
    ret
  }

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    ldarg.0
    call       instance void [mscorlib]System.Object::.ctor()
    ret
  }

  .property instance int32 'I<>Mangled.P'()
  {
    .get instance int32 C::'I<>Mangled.get_P'()
  }

  .property instance int32 P()
  {
    .get instance int32 C::'I<>Mangled.get_P'()
  }
} // end of class C
";

            ImmutableArray <byte> assemblyBytes;
            ImmutableArray <byte> pdbBytes;

            CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes);
            var assembly = ReflectionUtilities.Load(assemblyBytes);

            var value = CreateDkmClrValue(assembly.GetType("C").Instantiate());

            var root = FormatResult("instance", value);

            Verify(GetChildren(root),
                   EvalResult("I<>Mangled.P", "1", "int", null, DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private),
                   EvalResult("P", "1", "int", "instance.P", DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.Private));
        }
Beispiel #11
0
 public DiscourseUser CopyFrom(DiscourseUser source)
 {
     return(ReflectionUtilities.Copy(source, this));
 }
Beispiel #12
0
        /// <summary>
        /// Initialize the solver.
        /// </summary>
        public void Init()
        {
            foreach (var set in this.interleavingDependencies.Values)
            {
                var objsByte     = new List <object>();
                var objsShort    = new List <object>();
                var objsUshort   = new List <object>();
                var objsInt      = new List <object>();
                var objsUint     = new List <object>();
                var objsLong     = new List <object>();
                var objsUlong    = new List <object>();
                var objsFixedInt = new Dictionary <int, List <object> >();

                foreach (var elt in set)
                {
                    if (this.ExistingAssignment.ContainsKey(elt))
                    {
                        continue;
                    }

                    var type = elt.GetType();

                    if (type == typeof(ZenArbitraryExpr <byte>))
                    {
                        objsByte.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <short>))
                    {
                        objsShort.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <ushort>))
                    {
                        objsUshort.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <int>))
                    {
                        objsInt.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <uint>))
                    {
                        objsUint.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <long>))
                    {
                        objsLong.Add(elt);
                    }

                    if (type == typeof(ZenArbitraryExpr <ulong>))
                    {
                        objsUlong.Add(elt);
                    }

                    if (type.IsGenericType &&
                        type.GetGenericTypeDefinitionCached() == typeof(ZenArbitraryExpr <>) &&
                        ReflectionUtilities.IsFixedIntegerType(type.GetGenericArgumentsCached()[0]))
                    {
                        var size = CommonUtilities.IntegerSize(type.GetGenericArgumentsCached()[0]);

                        if (!objsFixedInt.TryGetValue(size, out List <object> list))
                        {
                            list = new List <object>();
                            objsFixedInt[size] = list;
                        }

                        list.Add(elt);
                    }
                }

                var bytevars = this.Manager.CreateInterleavedInt8(objsByte.Count);
                for (int i = 0; i < bytevars.Length; i++)
                {
                    this.ExistingAssignment[objsByte[i]] = bytevars[i];
                    this.Variables.Add(bytevars[i]);
                }

                var shortvars = this.Manager.CreateInterleavedInt16(objsShort.Count);
                for (int i = 0; i < shortvars.Length; i++)
                {
                    this.ExistingAssignment[objsShort[i]] = shortvars[i];
                    this.Variables.Add(shortvars[i]);
                }

                var ushortvars = this.Manager.CreateInterleavedInt16(objsUshort.Count);
                for (int i = 0; i < ushortvars.Length; i++)
                {
                    this.ExistingAssignment[objsUshort[i]] = ushortvars[i];
                    this.Variables.Add(ushortvars[i]);
                }

                var intvars = this.Manager.CreateInterleavedInt32(objsInt.Count);
                for (int i = 0; i < intvars.Length; i++)
                {
                    this.ExistingAssignment[objsInt[i]] = intvars[i];
                    this.Variables.Add(intvars[i]);
                }

                var uintvars = this.Manager.CreateInterleavedInt32(objsUint.Count);
                for (int i = 0; i < uintvars.Length; i++)
                {
                    this.ExistingAssignment[objsUint[i]] = uintvars[i];
                    this.Variables.Add(uintvars[i]);
                }

                var longvars = this.Manager.CreateInterleavedInt64(objsLong.Count);
                for (int i = 0; i < longvars.Length; i++)
                {
                    this.ExistingAssignment[objsLong[i]] = longvars[i];
                    this.Variables.Add(longvars[i]);
                }

                var ulongvars = this.Manager.CreateInterleavedInt64(objsUlong.Count);
                for (int i = 0; i < ulongvars.Length; i++)
                {
                    this.ExistingAssignment[objsUlong[i]] = ulongvars[i];
                    this.Variables.Add(ulongvars[i]);
                }

                foreach (var kv in objsFixedInt)
                {
                    var size      = kv.Key;
                    var fixedvars = this.Manager.CreateInterleavedInt(kv.Value.Count, size);

                    for (int i = 0; i < fixedvars.Length; i++)
                    {
                        this.ExistingAssignment[kv.Value[i]] = fixedvars[i];
                        this.Variables.Add(fixedvars[i]);
                    }
                }
            }
        }
Beispiel #13
0
        public void PointerDereferenceExpansion_NonNull()
        {
            var source   = @"
using System;
using System.Diagnostics;

[DebuggerDisplay(""Value"", Name=""Name"", Type=""Type"")]
unsafe struct Display
{
    public Display* DisplayPointer;
    public NoDisplay* NoDisplayPointer;
}

unsafe struct NoDisplay
{
    public Display* DisplayPointer;
    public NoDisplay* NoDisplayPointer;
}

unsafe class C
{
    Display* DisplayPointer;
    NoDisplay* NoDisplayPointer;

    public C(IntPtr d, IntPtr nd)
    {
        this.DisplayPointer = (Display*)d;
        this.NoDisplayPointer = (NoDisplay*)nd;
    
        this.DisplayPointer->DisplayPointer = this.DisplayPointer;
        this.DisplayPointer->NoDisplayPointer = this.NoDisplayPointer;
    
        this.NoDisplayPointer->DisplayPointer = this.DisplayPointer;
        this.NoDisplayPointer->NoDisplayPointer = this.NoDisplayPointer;
    }
}
";
            var assembly = GetUnsafeAssembly(source);

            unsafe
            {
                var displayType     = assembly.GetType("Display");
                var displayInstance = displayType.Instantiate();
                var displayHandle   = GCHandle.Alloc(displayInstance, GCHandleType.Pinned);
                var displayPtr      = displayHandle.AddrOfPinnedObject();

                var noDisplayType     = assembly.GetType("NoDisplay");
                var noDisplayInstance = noDisplayType.Instantiate();
                var noDisplayHandle   = GCHandle.Alloc(noDisplayInstance, GCHandleType.Pinned);
                var noDisplayPtr      = noDisplayHandle.AddrOfPinnedObject();

                var testType     = assembly.GetType("C");
                var testInstance = ReflectionUtilities.Instantiate(testType, displayPtr, noDisplayPtr);
                var testValue    = CreateDkmClrValue(testInstance, testType, evalFlags: DkmEvaluationResultFlags.None);

                var displayPtrString   = PointerToString(displayPtr);
                var noDisplayPtrString = PointerToString(noDisplayPtr);

                Verify(DepthFirstSearch(FormatResult("c", testValue), maxDepth: 3),
                       EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable),
                       EvalResult("DisplayPointer", displayPtrString, "Display*", "c.DisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("*c.DisplayPointer", "Value", "Type", "*c.DisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.DisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.DisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("*c.NoDisplayPointer", "{NoDisplay}", "NoDisplay", "*c.NoDisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("DisplayPointer", displayPtrString, "Display*", "(*c.NoDisplayPointer).DisplayPointer", DkmEvaluationResultFlags.Expandable),
                       EvalResult("NoDisplayPointer", noDisplayPtrString, "NoDisplay*", "(*c.NoDisplayPointer).NoDisplayPointer", DkmEvaluationResultFlags.Expandable));

                displayHandle.Free();
                noDisplayHandle.Free();
            }
        }
Beispiel #14
0
        public override void Execute(MethodInfo aMethod, ILOpCode aOpCode)
        {
            DoNullReferenceCheck(Assembler, DebugEnabled, 0);
            OpType xType     = ( OpType )aOpCode;
            string BaseLabel = GetLabel(aMethod, aOpCode) + ".";

            string xTypeID = GetTypeIDLabel(xType.Value);

            var xTypeSize = SizeOfType(xType.Value);

            string mReturnNullLabel = BaseLabel + "_ReturnNull";

            new CPUx86.Compare {
                DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceValue = 0
            };
            new CPUx86.ConditionalJump {
                Condition = CPUx86.ConditionalTestEnum.Zero, DestinationLabel = mReturnNullLabel
            };
            new CPUx86.Mov {
                DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true
            };
            new CPUx86.Push {
                DestinationReg = CPUx86.Registers.EAX, DestinationIsIndirect = true
            };
            new CPUx86.Push {
                DestinationRef = Cosmos.Assembler.ElementReference.New(xTypeID), DestinationIsIndirect = true
            };
            System.Reflection.MethodBase xMethodIsInstance = ReflectionUtilities.GetMethodBase(typeof(VTablesImpl), "IsInstance", "System.Int32", "System.Int32");
            new Call(Assembler).Execute(aMethod, new OpMethod(ILOpCode.Code.Call, 0, 0, xMethodIsInstance, aOpCode.CurrentExceptionHandler));

            new Label(BaseLabel + "_After_IsInstance_Call");
            new CPUx86.Pop {
                DestinationReg = CPUx86.Registers.EAX
            };
            new CPUx86.Compare {
                DestinationReg = CPUx86.Registers.EAX, SourceValue = 0
            };
            new CPUx86.ConditionalJump {
                Condition = CPUx86.ConditionalTestEnum.Equal, DestinationLabel = mReturnNullLabel
            };
            new CPUx86.Pop {
                DestinationReg = CPUx86.Registers.EAX
            };
            uint xSize = xTypeSize;

            if (xSize % 4 > 0)
            {
                xSize += 4 - (xSize % 4);
            }
            int xItems = ( int )xSize / 4;

            for (int i = xItems - 1; i >= 0; i--)
            {
                new CPUx86.Push {
                    DestinationReg = CPUx86.Registers.EAX, DestinationIsIndirect = true, DestinationDisplacement = ((i * 4) + ObjectImpl.FieldDataOffset)
                };
            }
            new CPUx86.Jump {
                DestinationLabel = GetLabel(aMethod, aOpCode.NextPosition)
            };
            new Label(mReturnNullLabel);
            new CPUx86.Add {
                DestinationReg = CPUx86.Registers.ESP, SourceValue = 4
            };
            new CPUx86.Push {
                DestinationValue = 0
            };
        }
Beispiel #15
0
 public DocumentTagUser CopyFrom(DocumentTagUser source)
 {
     return(ReflectionUtilities.Copy(source, this));
 }
        public static Assembly GetUnsafeAssembly(string source)
        {
            var comp = CSharpTestBase.CreateCompilationWithMscorlib45AndCSharp(source, options: TestOptions.UnsafeReleaseDll);

            return(ReflectionUtilities.Load(comp.EmitToArray()));
        }
Beispiel #17
0
        public DocumentTagUser FromXmlElement(XmlElement element)
        {
            ReflectionUtilities.FromXmlElement(this, element);

            return(this);
        }
 public FieldDefinitionBuilder Field <TFieldType>(Expression <Func <T, TFieldType> > accessor, string description = null)
 {
     return(this.Field(ReflectionUtilities.GetPropertyInfo(accessor).Name, accessor, description));
 }
        public INode BuildPathToNode(Type type)
        {
            INode parent = GetParentNode(type);

            Type argType = ReflectionUtilities.GetNamedParameterTargetOrNull(type);

            if (argType == null)
            {
                return(NodeFactory.CreateClassNode(parent, type));
            }
            INamedParameterNode np = NodeFactory.CreateNamedParameterNode(parent, type, argType);

            if (Parameterparser.CanParse(ReflectionUtilities.GetAssemblyQualifiedName(argType)))
            {
                if (type.GetCustomAttribute <NamedParameterAttribute>().DefaultClass != null)
                {
                    var e = new ClassHierarchyException("Named parameter " + ReflectionUtilities.GetAssemblyQualifiedName(type) + " defines default implementation for parsable type " + ReflectionUtilities.GetAssemblyQualifiedName(argType));
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }

            if (!string.IsNullOrEmpty(np.GetAlias()))
            {
                IDictionary <string, string> mapping = null;
                _aliasLookupTable.TryGetValue(np.GetAliasLanguage().ToString(), out mapping);
                if (null == mapping)
                {
                    mapping = new Dictionary <string, string>();
                    _aliasLookupTable.Add(np.GetAliasLanguage().ToString(), mapping);
                }
                try
                {
                    mapping.Add(np.GetAlias(), np.GetFullName());
                }
                catch (Exception)
                {
                    var e = new TangApplicationException(string.Format(CultureInfo.CurrentCulture, "Duplicated alias {0} on named parameter {1}.", np.GetAlias(), np.GetFullName()));
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
            }

            string shortName = np.GetShortName();

            if (shortName != null && !shortName.Equals(string.Empty))
            {
                INamedParameterNode oldNode = null;
                shortNames.TryGetValue(shortName, out oldNode);
                if (oldNode != null)
                {
                    if (oldNode.GetFullName().Equals(np.GetFullName()))
                    {
                        var ex = new IllegalStateException("Tried to double bind "
                                                           + oldNode.GetFullName() + " to short name " + shortName);
                        Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(ex, LOGGER);
                    }
                    var e = new ClassHierarchyException("Named parameters " + oldNode.GetFullName()
                                                        + " and " + np.GetFullName() + " have the same short name: "
                                                        + shortName);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(e, LOGGER);
                }
                shortNames.Add(shortName, np);
            }
            return(np);
        }
Beispiel #20
0
        /// <summary>
        /// Attach the view
        /// </summary>
        /// <param name="model">The model</param>
        /// <param name="view">The view to attach</param>
        /// <param name="explorerPresenter">The explorer</param>
        public void Attach(object model, object view, ExplorerPresenter explorerPresenter)
        {
            this.clemModel         = model as ICLEMUI;
            this.explorerPresenter = explorerPresenter;

            this.view = view as ICLEMView;
            if (model != null)
            {
                //Messages
                try
                {
                    if (model is ZoneCLEM)
                    {
                        object newView = new HTMLView(this.view as ViewBase);
                        messagePresenter = new MessagePresenter();
                        if (newView != null && messagePresenter != null)
                        {
                            this.view.AddTabView("Messages", newView);
                            messagePresenter.Attach(model, newView, this.explorerPresenter);
                        }
                    }
                }
                catch (Exception err)
                {
                    this.explorerPresenter.MainPresenter.ShowError(err);
                }
                //HTML Summary
                try
                {
                    object newView = new HTMLView(this.view as ViewBase);
                    summaryPresenter = new CLEMSummaryPresenter();
                    if (newView != null && summaryPresenter != null)
                    {
                        this.view.AddTabView("Summary", newView);
                        summaryPresenter.Attach(model, newView, this.explorerPresenter);
                    }
                }
                catch (Exception err)
                {
                    this.explorerPresenter.MainPresenter.ShowError(err);
                }
                //Properties
                try
                {
                    PresenterNameAttribute presenterName    = ReflectionUtilities.GetAttribute(model.GetType(), typeof(PresenterNameAttribute), false) as PresenterNameAttribute;
                    string[] childDisplayInParentPresenters = { "PropertyTablePresenter", "PropertyTreeTablePresenter" };
                    bool     isTablePresenter = childDisplayInParentPresenters.Contains(presenterName.ToString().Split('.').Last());

                    // check if it has properties
                    if (isTablePresenter ||
                        (model.GetType().GetProperties(
                             BindingFlags.Public |
                             BindingFlags.NonPublic |
                             BindingFlags.Instance
                             ).Where(prop => prop.IsDefined(typeof(DescriptionAttribute), false)).Count() > 0))
                    {
                        ViewNameAttribute viewName = ReflectionUtilities.GetAttribute(model.GetType(), typeof(ViewNameAttribute), false) as ViewNameAttribute;
                        object            newView  = Assembly.GetExecutingAssembly().CreateInstance(viewName.ToString(), false, BindingFlags.Default, null, new object[] { this.view }, null, null);
                        propertyPresenter = Assembly.GetExecutingAssembly().CreateInstance(presenterName.ToString()) as IPresenter;
                        if (newView != null && propertyPresenter != null)
                        {
                            this.view.AddTabView("Properties", newView);
                            propertyPresenter.Attach(model, newView, this.explorerPresenter);
                        }
                    }
                }
                catch (Exception err)
                {
                    this.explorerPresenter.MainPresenter.ShowError(err);
                }
                //Versions
                try
                {
                    var versions = ReflectionUtilities.GetAttributes(model.GetType(), typeof(VersionAttribute), false);
                    if (versions.Count() > 0)
                    {
                        object newView = new HTMLView(this.view as ViewBase);
                        versionPresenter = new VersionsPresenter();
                        if (newView != null && versionPresenter != null)
                        {
                            this.view.AddTabView("Version", newView);
                            versionPresenter.Attach(model, newView, this.explorerPresenter);
                        }
                    }
                }
                catch (Exception err)
                {
                    this.explorerPresenter.MainPresenter.ShowError(err);
                }

                if (clemModel != null)
                {
                    this.view.SelectTabView(clemModel.SelectedTab);
                }
                this.view.TabSelected += OnTabSelected;
            }
        }
Beispiel #21
0
        public WorkflowActor FromXmlElement(XmlElement element)
        {
            ReflectionUtilities.FromXmlElement(this, element);

            return(this);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(
                options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
            })
            .AddNewtonsoftJson(options =>
                               options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                               );

            // Register the Swagger generator, defining one or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version        = "v1",
                    Title          = "Microservice API",
                    Description    = "Microservice API",
                    TermsOfService = null,
                    Contact        = new OpenApiContact {
                        Name = "DINH KHAC HOAI PHUNG", Email = "*****@*****.**", Url = null
                    },
                });

                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header,
                    Type        = SecuritySchemeType.ApiKey
                });

                c.DescribeAllParametersInCamelCase();
            });

            services.AddSingleton(Configuration);

            // Entity framework
            string msSqlConnectionString = Configuration.GetValue <string>("database:msSql:connectionString");

            services.AddDbContext <AppCatalogDbContext>(opt =>
                                                        opt.UseSqlServer(
                                                            msSqlConnectionString,
                                                            options =>
            {
                options.EnableRetryOnFailure();
            }));

            // Health checks
            services.AddHealthChecks()
            .AddSqlServer(msSqlConnectionString);

            services.AddMediatR(ReflectionUtilities.GetAssemblies());
            services.AddAutoMapper(ReflectionUtilities.GetAssemblies());

            services.AddSingleton <IRabbitMQPersistentConnection>(sp =>
            {
                var logger = sp.GetRequiredService <ILogger <DefaultRabbitMQPersistentConnection> >();

                var factory = new ConnectionFactory()
                {
                    HostName = Configuration.GetValue <string>("rabbitmq:hostname"),
                    DispatchConsumersAsync = true
                };

                if (!string.IsNullOrEmpty(Configuration.GetValue <string>("rabbitmq:username")))
                {
                    factory.UserName = Configuration.GetValue <string>("rabbitmq:username");
                }

                if (!string.IsNullOrEmpty(Configuration.GetValue <string>("rabbitmq:password")))
                {
                    factory.Password = Configuration.GetValue <string>("rabbitmq:password");
                }

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration.GetValue <string>("rabbitmq:retycount")))
                {
                    retryCount = int.Parse(Configuration.GetValue <string>("rabbitmq:retycount"));
                }

                return(new DefaultRabbitMQPersistentConnection(factory, logger, retryCount));
            });

            var exchange = Configuration.GetValue <string>("eventbus:exchange");
            var queue    = Configuration.GetValue <string>("eventbus:queue");

            services.AddSingleton <IEventBus, EventBusRabbitMQ>(sp =>
            {
                var rabbitMQPersistentConnection = sp.GetRequiredService <IRabbitMQPersistentConnection>();
                var logger = sp.GetRequiredService <ILogger <EventBusRabbitMQ> >();
                var eventBusSubcriptionsManager = sp.GetRequiredService <IEventBusSubscriptionsManager>();

                var retryCount = 5;
                if (!string.IsNullOrEmpty(Configuration.GetValue <string>("eventbus:retryCount")))
                {
                    retryCount = Configuration.GetValue <int>("eventbus:retryCount");
                }

                return(new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, eventBusSubcriptionsManager, exchange, queue, retryCount));
            });

            services.AddSingleton <IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>();

            // ===== Add Jwt Authentication ========
            services
            .AddAuthentication(options =>
            {
                options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, cfg =>
            {
                cfg.RequireHttpsMetadata      = false;
                cfg.SaveToken                 = true;
                cfg.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidIssuer      = Configuration["JwtIssuer"],
                    ValidAudience    = Configuration["JwtIssuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtKey"])),
                    ClockSkew        = TimeSpan.Zero // remove delay of token when expire
                };
            });

            services.AddCors();
        }
        public static T DeserializeFromData <T>(JSONObject json)
            where T : DataEntry
        {
            DataEntry.DataEntryColumn[] synchronizableColumns = DataEntry.GetSynchronizableColumns <T>();
            string synchronizableName = synchronizableColumns.First <DataEntry.DataEntryColumn>((DataEntry.DataEntryColumn column) => column.DataColumnAttribute.IsPrimaryKey).SynchronizableName;
            int    num      = json[synchronizableName].str.ParseInt();
            T      instance = DataEntry.GetInstance <T>(num);

            DataEntry.DataEntryColumn[] dataEntryColumnArray = synchronizableColumns;
            for (int i = 0; i < (int)dataEntryColumnArray.Length; i++)
            {
                DataEntry.DataEntryColumn dataEntryColumn = dataEntryColumnArray[i];
                if (dataEntryColumn.SynchronizableAttribute.Pull && json.HasField(dataEntryColumn.SynchronizableName))
                {
                    try
                    {
                        dataEntryColumn.SetValue(instance, json[dataEntryColumn.SynchronizableName].str);
                    }
                    catch (FormatException formatException1)
                    {
                        FormatException formatException = formatException1;
                        UnityEngine.Debug.Log("Failed to fill synchronizable property");
                        throw new SynchronizationException(string.Format("Failed to fill synchronizable property '{0}' with value '{1}' for {2} with ID {3}. Exception: {4}", new object[] { dataEntryColumn.SynchronizableName, json[dataEntryColumn.SynchronizableName], ReflectionUtilities.GetTableName <T>(), num, formatException }));
                    }
                }
            }
            return(instance);
        }
Beispiel #24
0
        /// <summary>Writes PDF for specified auto-doc commands.</summary>
        /// <param name="section">The writer to write to.</param>
        /// <param name="tags">The autodoc tags.</param>
        private void TagsToMigraDoc(Section section, List <AutoDocumentation.ITag> tags)
        {
            int figureNumber = 0;

            foreach (AutoDocumentation.ITag tag in tags)
            {
                if (tag is AutoDocumentation.Heading)
                {
                    AutoDocumentation.Heading heading = tag as AutoDocumentation.Heading;
                    if (heading.headingLevel > 0 && heading.headingLevel <= 6)
                    {
                        Paragraph para = section.AddParagraph(heading.text, "Heading" + heading.headingLevel);
                        para.Format.KeepWithNext = true;
                        int posSpace = heading.text.IndexOf(' ');
                        if (posSpace > 0)
                        {
                            para.AddBookmark(heading.text.Substring(posSpace + 1));
                        }
                        if (heading.headingLevel == 1)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level1;
                        }
                        else if (heading.headingLevel == 2)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level2;
                        }
                        else if (heading.headingLevel == 3)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level3;
                        }
                        else if (heading.headingLevel == 4)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level4;
                        }
                        else if (heading.headingLevel == 5)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level5;
                        }
                        else if (heading.headingLevel == 6)
                        {
                            para.Format.OutlineLevel = OutlineLevel.Level6;
                        }
                    }
                }
                else if (tag is AutoDocumentation.Paragraph)
                {
                    AutoDocumentation.Paragraph paragraph = tag as AutoDocumentation.Paragraph;
                    if (paragraph.text.Contains("![Alt Text]"))
                    {
                        figureNumber++;
                    }
                    paragraph.text = paragraph.text.Replace("[FigureNumber]", figureNumber.ToString());
                    AddFormattedParagraphToSection(section, paragraph);
                }
                else if (tag is AutoDocumentation.GraphAndTable)
                {
                    CreateGraphPDF(section, tag as AutoDocumentation.GraphAndTable);
                }
                else if (tag is GraphPage)
                {
                    CreateGraphPage(section, tag as GraphPage);
                }
                else if (tag is AutoDocumentation.NewPage)
                {
                    section.AddPageBreak();
                    if ((tag as AutoDocumentation.NewPage).Portrait)
                    {
                        section.PageSetup.Orientation = Orientation.Portrait;
                    }
                    else
                    {
                        section.PageSetup.Orientation = Orientation.Landscape;
                    }
                }
                else if (tag is AutoDocumentation.PageSetup)
                {
                    if ((tag as AutoDocumentation.PageSetup).Portrait)
                    {
                        section.PageSetup.Orientation = Orientation.Portrait;
                    }
                    else
                    {
                        section.PageSetup.Orientation = Orientation.Landscape;
                    }
                }
                else if (tag is AutoDocumentation.Table)
                {
                    CreateTable(section, tag as AutoDocumentation.Table);
                }
                else if (tag is Graph)
                {
                    GraphPresenter graphPresenter = new GraphPresenter();
                    explorerPresenter.ApsimXFile.Links.Resolve(graphPresenter);
                    GraphView graphView = new GraphView();
                    graphView.BackColor        = OxyPlot.OxyColors.White;
                    graphView.ForegroundColour = OxyPlot.OxyColors.Black;
                    graphView.FontSize         = 12;
                    graphView.Width            = 500;
                    graphView.Height           = 500;
                    graphPresenter.Attach(tag, graphView, explorerPresenter);
                    string pngFileName = graphPresenter.ExportToPNG(WorkingDirectory);
                    section.AddImage(pngFileName);
                    string caption = (tag as Graph).Caption;
                    if (caption != null)
                    {
                        section.AddParagraph(caption);
                    }
                    graphPresenter.Detach();
                    graphView.MainWidget.Destroy();
                }
                else if (tag is Map && (tag as Map).GetCoordinates().Count > 0)
                {
                    MapPresenter mapPresenter = new MapPresenter();
                    MapView      mapView      = new MapView(null);
                    mapPresenter.Attach(tag, mapView, explorerPresenter);
                    string pngFileName = mapPresenter.ExportToPNG(WorkingDirectory);
                    if (!String.IsNullOrEmpty(pngFileName))
                    {
                        section.AddImage(pngFileName);
                    }
                    mapPresenter.Detach();
                    mapView.MainWidget.Destroy();
                }
                else if (tag is AutoDocumentation.Image)
                {
                    AutoDocumentation.Image imageTag = tag as AutoDocumentation.Image;
                    if (imageTag.image.Width > 700)
                    {
                        imageTag.image = ImageUtilities.ResizeImage(imageTag.image, 700, 500);
                    }
                    string pngFileName = Path.Combine(WorkingDirectory, imageTag.name);
                    imageTag.image.Save(pngFileName, System.Drawing.Imaging.ImageFormat.Png);
                    section.AddImage(pngFileName);
                    figureNumber++;
                }
                else if (tag is AutoDocumentation.ModelView)
                {
                    AutoDocumentation.ModelView modelView     = tag as AutoDocumentation.ModelView;
                    ViewNameAttribute           viewName      = ReflectionUtilities.GetAttribute(modelView.model.GetType(), typeof(ViewNameAttribute), false) as ViewNameAttribute;
                    PresenterNameAttribute      presenterName = ReflectionUtilities.GetAttribute(modelView.model.GetType(), typeof(PresenterNameAttribute), false) as PresenterNameAttribute;
                    if (viewName != null && presenterName != null)
                    {
                        ViewBase owner = ViewBase.MasterView as ViewBase;
                        if (viewName.ToString() == "UserInterface.Views.MapView")
                        {
                            owner = null;
                        }

                        ViewBase   view      = Assembly.GetExecutingAssembly().CreateInstance(viewName.ToString(), false, BindingFlags.Default, null, new object[] { owner }, null, null) as ViewBase;
                        IPresenter presenter = Assembly.GetExecutingAssembly().CreateInstance(presenterName.ToString()) as IPresenter;

                        if (view != null && presenter != null)
                        {
                            explorerPresenter.ApsimXFile.Links.Resolve(presenter);
                            presenter.Attach(modelView.model, view, explorerPresenter);

                            Gtk.Window popupWin = new Gtk.Window(Gtk.WindowType.Popup);
                            popupWin.SetSizeRequest(800, 800);
                            popupWin.Add(view.MainWidget);

                            if (view is IMapView map)
                            {
                                map.HideZoomControls();
                            }

                            popupWin.ShowAll();

                            while (Gtk.Application.EventsPending())
                            {
                                Gtk.Application.RunIteration();
                            }

                            // From MapView:
                            // With WebKit, it appears we need to give it time to actually update the display
                            // Really only a problem with the temporary windows used for generating documentation
                            if (view is MapView)
                            {
                                var watch = new System.Diagnostics.Stopwatch();
                                watch.Start();
                                while (watch.ElapsedMilliseconds < 1000)
                                {
                                    Gtk.Application.RunIteration();
                                }
                            }

                            string pngFileName = (presenter as IExportable).ExportToPNG(WorkingDirectory);
                            section.AddImage(pngFileName);
                            presenter.Detach();
                            view.MainWidget.Destroy();
                            popupWin.Destroy();
                        }
                    }
                }
            }
        }
Beispiel #25
0
        public static T ReadFromResource <T>(string resourceName, Action <Exception> errorHandler) where T : IModel
        {
            string json = ReflectionUtilities.GetResourceAsString(resourceName);

            return(FileFormat.ReadFromString <T>(json, errorHandler, false));
        }
Beispiel #26
0
 /// <summary>
 /// Return an attribute
 /// </summary>
 /// <param name="attributeType">Type of attribute to find</param>
 /// <returns>The attribute or null if not found</returns>
 public override Attribute GetAttribute(Type attributeType)
 {
     return(ReflectionUtilities.GetAttribute(this.property, attributeType, false));
 }
Beispiel #27
0
        /// <summary>
        /// The view wants us to return a list of menu descriptions for the
        /// currently selected Node.
        /// </summary>
        /// <param name="nodePath">The path to the node</param>
        public void PopulateContextMenu(string nodePath)
        {
            List <MenuDescriptionArgs> descriptions = new List <MenuDescriptionArgs>();

            // Get the selected model.
            object selectedModel = Apsim.Get(this.ApsimXFile, nodePath);

            // Go look for all [UserInterfaceAction]
            foreach (MethodInfo method in typeof(ContextMenu).GetMethods())
            {
                ContextMenuAttribute contextMenuAttr = ReflectionUtilities.GetAttribute(method, typeof(ContextMenuAttribute), false) as ContextMenuAttribute;
                if (contextMenuAttr != null)
                {
                    bool ok = true;
                    if (contextMenuAttr.AppliesTo != null && selectedModel != null)
                    {
                        ok = false;
                        foreach (Type t in contextMenuAttr.AppliesTo)
                        {
                            if (t.IsAssignableFrom(selectedModel.GetType()))
                            {
                                ok = true;
                            }
                        }
                    }

                    if (ok)
                    {
                        MenuDescriptionArgs desc = new MenuDescriptionArgs();
                        desc.Name = contextMenuAttr.MenuName;
                        desc.ResourceNameForImage = "ApsimNG.Resources.MenuImages." + desc.Name + ".png";
                        desc.ShortcutKey          = contextMenuAttr.ShortcutKey;
                        desc.ShowCheckbox         = contextMenuAttr.IsToggle;

                        // Check for an enable method
                        MethodInfo enableMethod = typeof(ContextMenu).GetMethod(method.Name + "Enabled");
                        if (enableMethod != null)
                        {
                            desc.Enabled = (bool)enableMethod.Invoke(this.contextMenu, null);
                        }
                        else
                        {
                            desc.Enabled = true;
                        }

                        // Check for an checked method
                        MethodInfo checkMethod = typeof(ContextMenu).GetMethod(method.Name + "Checked");
                        if (checkMethod != null)
                        {
                            desc.Checked = (bool)checkMethod.Invoke(this.contextMenu, null);
                        }
                        else
                        {
                            desc.Checked = false;
                        }

                        EventHandler handler = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), this.contextMenu, method);
                        desc.OnClick = handler;

                        descriptions.Add(desc);
                    }
                }
            }

            this.view.PopulateContextMenu(descriptions);
        }
Beispiel #28
0
        /// <summary>
        /// Parse a string into documentation tags
        /// </summary>
        /// <param name="stringToParse">The string to parse</param>
        /// <param name="model">The associated model where the string came from</param>
        /// <param name="tags">The list of tags to add to</param>
        /// <param name="headingLevel">The current heading level</param>
        /// <param name="indent">The current indent level</param>
        /// <param name="doNotTrim">If true, don't trim the lines</param>
        /// <param name="documentAllChildren">Ensure all children are documented?</param>
        public static void ParseTextForTags(string stringToParse, IModel model, List <ITag> tags, int headingLevel, int indent, bool documentAllChildren, bool doNotTrim = false)
        {
            if (string.IsNullOrEmpty(stringToParse) || model == null)
            {
                return;
            }
            List <IModel> childrenDocumented   = new List <Core.IModel>();
            int           numSpacesStartOfLine = -1;
            string        paragraphSoFar       = string.Empty;

            if (stringToParse.StartsWith("\r\n"))
            {
                stringToParse = stringToParse.Remove(0, 2);
            }
            StringReader reader             = new StringReader(stringToParse);
            string       line               = reader.ReadLine();
            int          targetHeadingLevel = headingLevel;

            while (line != null)
            {
                if (!doNotTrim)
                {
                    line = line.Trim();
                }

                // Adjust heading levels.
                if (line.StartsWith("#"))
                {
                    int currentHeadingLevel = line.Count(c => c == '#');
                    targetHeadingLevel = headingLevel + currentHeadingLevel - 1; // assumes models start numbering headings at 1 '#' character
                    string hashString = new string('#', targetHeadingLevel);
                    line = hashString + line.Replace("#", "") + hashString;
                }

                if (line != string.Empty && !doNotTrim)
                {
                    {
                        if (numSpacesStartOfLine == -1)
                        {
                            int preLineLength = line.Length;
                            line = line.TrimStart();
                            numSpacesStartOfLine = preLineLength - line.Length - 1;
                        }
                        else
                        {
                            line = line.Remove(0, numSpacesStartOfLine);
                        }
                    }
                }

                if (line.StartsWith("[DocumentMathFunction"))
                {
                    StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);
                    var operatorChar = line["[DocumentMathFunction".Length + 1];
                    childrenDocumented.AddRange(DocumentMathFunction(model, operatorChar, tags, headingLevel, indent));
                }
                else
                {
                    // Remove expression macros and replace with values.
                    line = RemoveMacros(model, line);

                    string heading;
                    int    thisHeadingLevel;
                    if (GetHeadingFromLine(line, out heading, out thisHeadingLevel))
                    {
                        StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);
                        tags.Add(new Heading(heading, thisHeadingLevel));
                    }
                    else if (line.StartsWith("[Document "))
                    {
                        StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);

                        // Find child
                        string childName = line.Replace("[Document ", "").Replace("]", "");
                        IModel child     = model.FindByPath(childName)?.Value as IModel;
                        if (child == null)
                        {
                            paragraphSoFar += "<b>Unknown child name: " + childName + " </b>\r\n";
                        }
                        else
                        {
                            DocumentModel(child, tags, targetHeadingLevel + 1, indent);
                            childrenDocumented.Add(child);
                        }
                    }
                    else if (line.StartsWith("[DocumentType "))
                    {
                        StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);

                        // Find children
                        string childTypeName = line.Replace("[DocumentType ", "").Replace("]", "");
                        Type   childType     = ReflectionUtilities.GetTypeFromUnqualifiedName(childTypeName);
                        foreach (IModel child in model.FindAllChildren().Where(c => childType.IsAssignableFrom(c.GetType())))
                        {
                            DocumentModel(child, tags, targetHeadingLevel + 1, indent);
                            childrenDocumented.Add(child);
                        }
                    }
                    else if (line == "[DocumentView]")
                    {
                        tags.Add(new ModelView(model));
                    }
                    else if (line.StartsWith("[DocumentChart "))
                    {
                        StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);
                        var words = line.Replace("[DocumentChart ", "").Split(',');
                        if (words.Length == 4)
                        {
                            var xypairs = model.FindByPath(words[0])?.Value as XYPairs;
                            if (xypairs != null)
                            {
                                childrenDocumented.Add(xypairs);
                                var xName = words[2];
                                var yName = words[3].Replace("]", "");
                                tags.Add(new GraphAndTable(xypairs, words[1], xName, yName, indent));
                            }
                        }
                    }
                    else if (line.StartsWith("[DontDocument"))
                    {
                        string childName = line.Replace("[DontDocument ", "").Replace("]", "");
                        IModel child     = model.FindByPath(childName)?.Value as IModel;
                        if (childName != null)
                        {
                            childrenDocumented.Add(child);
                        }
                    }
                    else
                    {
                        paragraphSoFar += line + "\r\n";
                    }
                }
                line = reader.ReadLine();
            }

            StoreParagraphSoFarIntoTags(tags, indent, ref paragraphSoFar);

            if (documentAllChildren)
            {
                // write children.
                foreach (IModel child in model.FindAllChildren <IModel>())
                {
                    if (!childrenDocumented.Contains(child))
                    {
                        DocumentModel(child, tags, headingLevel + 1, indent, documentAllChildren);
                    }
                }
            }
        }
Beispiel #29
0
        public XmlElement ToXmlElement(XmlDocument document)
        {
            var element = ReflectionUtilities.ToXmlElement(document, this);

            return(element);
        }
Beispiel #30
0
        public void NoQuotes_String()
        {
            var runtime           = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib());
            var inspectionContext = CreateDkmInspectionContext(DkmEvaluationFlags.NoQuotes);
            var stringType        = runtime.GetType(typeof(string));

            // null
            var value      = CreateDkmClrValue(null, type: stringType);
            var evalResult = FormatResult("s", value, inspectionContext: inspectionContext);

            Verify(evalResult,
                   EvalResult("s", "null", "string", "s", editableValue: null, flags: DkmEvaluationResultFlags.None));

            // ""
            value      = CreateDkmClrValue(string.Empty, type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "", "string", "s", editableValue: "\"\"", flags: DkmEvaluationResultFlags.RawString));

            // "'"
            value      = CreateDkmClrValue("'", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "'", "string", "s", editableValue: "\"'\"", flags: DkmEvaluationResultFlags.RawString));

            // "\""
            value      = CreateDkmClrValue("\"", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "\"", "string", "s", editableValue: "\"\\\"\"", flags: DkmEvaluationResultFlags.RawString));

            // "\\"
            value      = CreateDkmClrValue("\\", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "\\", "string", "s", editableValue: "\"\\\\\"", flags: DkmEvaluationResultFlags.RawString));

            // "a\r\n\t\v\b\u001eb"
            value      = CreateDkmClrValue("a\r\n\tb\v\b\u001ec", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "a\r\n\tb\v\b\u001ec", "string", "s", editableValue: "\"a\\r\\n\\tb\\v\\b\\u001ec\"", flags: DkmEvaluationResultFlags.RawString));

            // "a\0b"
            value      = CreateDkmClrValue("a\0b", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "a\0b", "string", "s", editableValue: "\"a\\0b\"", flags: DkmEvaluationResultFlags.RawString));

            // "\u007f\u009f"
            value      = CreateDkmClrValue("\u007f\u009f", type: stringType);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "\u007f\u009f", "string", "s", editableValue: "\"\\u007f\\u009f\"", flags: DkmEvaluationResultFlags.RawString));

            // " " with alias
            value      = CreateDkmClrValue(" ", type: stringType, alias: "$1", evalFlags: DkmEvaluationResultFlags.HasObjectId);
            evalResult = FormatResult("s", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("s", "  {$1}", "string", "s", editableValue: "\" \"", flags: DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.HasObjectId));

            // array
            value      = CreateDkmClrValue(new string[] { "1" }, type: stringType.MakeArrayType());
            evalResult = FormatResult("a", value, inspectionContext: inspectionContext);
            Verify(evalResult,
                   EvalResult("a", "{string[1]}", "string[]", "a", editableValue: null, flags: DkmEvaluationResultFlags.Expandable));
            var children = GetChildren(evalResult);

            // DkmInspectionContext should not be inherited.
            Verify(children,
                   EvalResult("[0]", "\"1\"", "string", "a[0]", editableValue: "\"1\"", flags: DkmEvaluationResultFlags.RawString));
        }