コード例 #1
0
        public void Get_list_typeparam()
        {
            var list = new List <DateTime>();
            var type = ReflectionMethods.GetEnumerableItemType(list.GetType());

            Assert.AreEqual(typeof(DateTime), type);
        }
コード例 #2
0
        public void Test_GetEnumerableElementAt()
        {
            var array1 = new[] { "i1", "i2", "i3" };

            Assert.AreEqual("i1", ReflectionMethods.GetItem(array1, 0));
            Assert.AreEqual("i2", ReflectionMethods.GetItem(array1, 1));

            var al1 = new ArrayList(2)
            {
                5, "test2"
            };

            Assert.AreEqual(5, ReflectionMethods.GetItem(al1, 0));
            Assert.AreEqual("test2", ReflectionMethods.GetItem(al1, 1));

            var dict1 = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };

            Assert.IsNotNull(ReflectionMethods.GetItem(dict1, 0));

            var list1 = new List <string> {
                "list1", "list2"
            };

            Assert.AreEqual("list1", ReflectionMethods.GetItem(list1, 0));
            Assert.AreEqual("list2", ReflectionMethods.GetItem(list1, 1));
        }
コード例 #3
0
ファイル: ElementHelper.cs プロジェクト: gitoscc/XenForms
        public static string GetContentPropertyTypeName(Element e)
        {
            var prop = GetContentProperty(e);

            if (prop == null)
            {
                return(null);
            }

            var isEnumerable = ReflectionMethods.ImplementsIEnumerable(prop);

            if (!isEnumerable)
            {
                return(prop.PropertyType.FullName);
            }

            var typeArgs = prop
                           .PropertyType
                           .GenericTypeArguments
                           .Select(a => a.FullName)
                           .ToArray();

            if (typeArgs.Length == 0)
            {
                return(prop.PropertyType.FullName);
            }

            var arg = string.Join(",", typeArgs);

            return($"{typeof(IEnumerable).FullName}<{arg}>");
        }
コード例 #4
0
 public void Test_IsValueType()
 {
     Assert.IsTrue(ReflectionMethods.IsValueType(typeof(DateTime)));
     Assert.IsTrue(ReflectionMethods.IsValueType(typeof(Int32)));
     Assert.IsTrue(ReflectionMethods.IsValueType(typeof(TestValueType)));
     Assert.IsFalse(ReflectionMethods.IsValueType(typeof(string)));
     Assert.IsFalse(ReflectionMethods.IsValueType(typeof(Exception)));
 }
コード例 #5
0
        public void Clone(ComponentEcs jsonToCloneFrom = null)
        {
            //First we create an instance of this specific type.

            if (jsonToCloneFrom == null)
            {
                jsonToCloneFrom = JsonSerializer.LoadFromJson(this);
            }
            ReflectionMethods.Clone(this, jsonToCloneFrom);
        }
コード例 #6
0
        public void Test_GetShortTypeName()
        {
            const string aqtn = @"System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a";

            Assert.AreEqual(string.Empty, ReflectionMethods.GetShortTypeName(null));
            Assert.AreEqual(string.Empty, ReflectionMethods.GetShortTypeName(string.Empty));
            Assert.AreEqual("ClassName", ReflectionMethods.GetShortTypeName("ClassName"));
            Assert.AreEqual("ExceptionMessage", ReflectionMethods.GetShortTypeName("Namespace1.Namespace2.ExceptionMessage"));
            Assert.AreEqual("SqlMembershipProvider", ReflectionMethods.GetShortTypeName(aqtn));
        }
コード例 #7
0
        public void Test_IsNotPrimitiveValueType()
        {
            var v1 = new TestValueType();

            Assert.IsTrue(ReflectionMethods.IsNotPrimitiveValueType(v1));

            var v2 = 0;

            Assert.IsFalse(ReflectionMethods.IsNotPrimitiveValueType(v2));
        }
コード例 #8
0
        private static Socket CreateSocketFromFd(int fd, ReflectionMethods reflectionMethods)
        {
            // set CLOEXEC
            fcntl(fd, F_SETFD, FD_CLOEXEC);

            // static unsafe SafeCloseSocket CreateSocket(IntPtr fileDescriptor)
            var fileDescriptor  = new IntPtr(fd);
            var safeCloseSocket = reflectionMethods.SafeCloseSocketCreate.Invoke(null, new object [] { fileDescriptor });

            // private Socket(SafeCloseSocket fd)
            var socket = reflectionMethods.SocketConstructor.Invoke(new[] { safeCloseSocket });

            // private bool _isListening = false;
            bool listening = GetSockOpt(fd, SO_ACCEPTCONM) != 0;

            reflectionMethods.IsListening.SetValue(socket, listening);

            EndPoint      endPoint;
            AddressFamily addressFamily = ConvertAddressFamily(GetSockOpt(fd, SO_DOMAIN));

            if (addressFamily == AddressFamily.InterNetwork)
            {
                endPoint = new IPEndPoint(IPAddress.Any, 0);
            }
            else if (addressFamily == AddressFamily.InterNetworkV6)
            {
                endPoint = new IPEndPoint(IPAddress.Any, 0);
            }
            else if (addressFamily == AddressFamily.Unix)
            {
                // public UnixDomainSocketEndPoint(string path)
                endPoint = (EndPoint)reflectionMethods.UnixDomainSocketEndPointConstructor.Invoke(new[] { "/" });
            }
            else
            {
                throw new NotSupportedException($"Unknown address family: {addressFamily}.");
            }
            // internal EndPoint _rightEndPoint;
            reflectionMethods.RightEndPoint.SetValue(socket, endPoint);
            // private AddressFamily _addressFamily;
            reflectionMethods.AddressFamily.SetValue(socket, addressFamily);

            SocketType sockType = ConvertSocketType(GetSockOpt(fd, SO_TYPE));

            // private SocketType _socketType;
            reflectionMethods.SocketType.SetValue(socket, sockType);

            ProtocolType protocolType = ConvertProtocolType(GetSockOpt(fd, SO_PROTOCOL));

            // private ProtocolType _protocolType;
            reflectionMethods.ProtocolType.SetValue(socket, protocolType);

            return((Socket)socket);
        }
コード例 #9
0
        public void Test_GetIndexerValue()
        {
            var nullArg = ReflectionMethods.GetIndexerValue(null);

            Assert.IsNull(nullArg);

            var noIndexer = ReflectionMethods.GetIndexerValue("TextColor");

            Assert.IsNull(noIndexer);

            var yesIndexer = ReflectionMethods.GetIndexerValue("Rows[555]");

            Assert.AreEqual(555, yesIndexer);
        }
コード例 #10
0
        protected override void OnExecute(UIMessageContext ctx)
        {
            if (ctx.Request == null)
            {
                return;
            }

            var req = ctx.Get <GetObjectRequest>();

            if (req == null)
            {
                return;
            }

            var props = GetUIProperties(req.WidgetId, true, req.Path);

            if (!props.Any())
            {
                return;
            }

            var prop = props[0];

            if (prop.UIType.Descriptor.HasFlag(UIPropertyDescriptors.Enumerable))
            {
                if (prop.UIType.Descriptor.HasFlag(UIPropertyDescriptors.Enumerable))
                {
                    // grab index value; if null, return without creating an ObjectResponse.
                    var index = ReflectionMethods.GetIndexerValue(req.Path[0]);
                    if (index == null)
                    {
                        return;
                    }

                    var item = ReflectionMethods.GetItem(prop.Value, index.Value);
                    prop.Value = GetUIProperties(item);
                }
            }

            prop.Path = req.Path?.Union(prop.Path)?.ToArray();
            var cantCast = SetPath(prop.Value, req.Path);

            ctx.SetResponse <ObjectResponse>(res =>
            {
                res.UnknownCondition = cantCast;
                res.Property         = prop;
                res.WidgetId         = req.WidgetId;
                res.ObjectName       = UIProperty.GetLastPath(req.Path);
            });
        }
コード例 #11
0
        public void Test_StripIndexer()
        {
            var nullArg = ReflectionMethods.StripIndexer(null);

            Assert.IsNull(nullArg);

            var noIndexer = ReflectionMethods.StripIndexer("MyTest");

            Assert.AreEqual("MyTest", noIndexer);

            var yesIndexer = ReflectionMethods.StripIndexer("Rows[5]");

            Assert.AreEqual("Rows", yesIndexer);
        }
コード例 #12
0
 // internal for testing
 internal static Socket[] GetListenSockets(string myPid, string listenPid, int startFd, int fdCount)
 {
     Socket[] sockets = Array.Empty <Socket>();
     if (myPid == listenPid)
     {
         ReflectionMethods reflectionMethods = LookupMethods();
         sockets = new Socket[fdCount];
         for (int i = 0; i < fdCount; i++)
         {
             sockets[i] = CreateSocketFromFd(startFd + i, reflectionMethods);
         }
     }
     Environment.SetEnvironmentVariable(LISTEN_FDS, null);
     Environment.SetEnvironmentVariable(LISTEN_PID, null);
     return(sockets);
 }
コード例 #13
0
ファイル: ElementHelper.cs プロジェクト: gitoscc/XenForms
        public static bool IsCollectionOfViews(PropertyInfo prop)
        {
            var isEnumerable = ReflectionMethods.ImplementsIEnumerable(prop);

            if (!isEnumerable)
            {
                return(false);
            }

            var hasViewArg = prop
                             .PropertyType
                             .GenericTypeArguments
                             .Any(a => a.IsAssignableFrom(typeof(View)));

            return(hasViewArg);
        }
コード例 #14
0
ファイル: ElementHelper.cs プロジェクト: gitoscc/XenForms
        public static IEnumerable <AttachedPropertyInfo> GetAttachedProperties(BindableObject obj)
        {
            var apis = new List <AttachedPropertyInfo>();

            var dps = obj
                      .GetType()
                      .GetFields(BindingFlags.Static | BindingFlags.Public)
                      .Where(t => t.FieldType.IsAssignableFrom(typeof(BindableProperty)))
                      .ToArray();

            foreach (var dp in dps)
            {
                if (!dp.Name.EndsWith("Property", StringComparison.CurrentCultureIgnoreCase))
                {
                    continue;
                }

                var index     = dp.Name.LastIndexOf("Property", StringComparison.CurrentCultureIgnoreCase);
                var shortName = dp.Name.Substring(0, index);

                var getMethod = obj.GetType().GetMethod("Get" + shortName);
                var setMethod = obj.GetType().GetMethod("Set" + shortName);

                if (getMethod != null && setMethod != null)
                {
                    var typeName = ReflectionMethods.GetShortTypeName(obj.GetType().FullName);

                    var api = new AttachedPropertyInfo
                    {
                        PropertyName     = dp.Name,
                        XamlPropertyName = $"{typeName}.{shortName}",
                        Value            = getMethod.Invoke(null, new object[] { obj }),
                        Field            = dp,
                        GetMethod        = getMethod,
                        SetMethod        = setMethod,
                        Target           = obj
                    };

                    apis.Add(api);
                }
            }

            return(apis.ToArray());
        }
コード例 #15
0
        public void Test_ParseEnumerableProperty()
        {
            // Doesn't have an indexer
            int?   nIndex;
            string nStripped;
            var    noIndexer = ReflectionMethods.ParseIndexer("Normal", out nIndex, out nStripped);

            Assert.IsFalse(noIndexer);
            Assert.IsNull(nIndex);
            Assert.AreEqual("Normal", nStripped);

            // Has an indexer
            int?   yIndex;
            string yStripped;
            var    yesIndexer = ReflectionMethods.ParseIndexer("Columns[5]", out yIndex, out yStripped);

            Assert.IsTrue(yesIndexer);
            Assert.AreEqual(5, yIndex);
            Assert.AreEqual("Columns", yStripped);
        }
コード例 #16
0
        private string GetCommandLine()
        {
            string commandLine = String.Empty;

            if (commandLineStartIndex != -1)
            {
                commandLine = this.Text.Substring(this.commandLineStartIndex);
            }
            // Start index of the next command line is unknown
            commandLineStartIndex = -1;
            if (string.IsNullOrEmpty(commandLine))
            {
                commandLine = GetCurrentLine();
            }
            // Handle built-in commands
            if (ReflectionMethods.ExecuteInternalCommand(commandLine))
            {
                commandLine = String.Empty;
            }
            return(commandLine);
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: Morigun/TestReflecsion
        public static void Main(string[] args)
        {
            IntPtr ptr = WinAPI.FindWindow(null, "CORE");

            Console.WriteLine(ptr.ToString());
            if (ptr.ToInt32() != 0)
            {
                IntPtr        chld  = WinAPI.GetWindow(ptr, WinAPI.GetWindowType.GW_CHILD);
                StringBuilder title = new StringBuilder();
                WinAPI.SendMessage(chld, Convert.ToInt32(WinAPI.GetWindowType.WM_GETTEXT), (IntPtr)20, title);
                Console.WriteLine(chld.ToString() + " " + title.ToString());
            }
            setObjectName();
            Console.WriteLine(ReflectionMethods.getAssembltInfo(Type.GetType(ClassNames[0])).ToString());
            Console.WriteLine(ReflectionMethods.getConstructorInfo(Type.GetType(ClassNames[0])));
            poolObjects = new List <object>();
            Thread th = new Thread(Update);

            CreateMoreObjects(ClassNames[0], (new[] { Type.GetType(IntType) }));
            for (int i = 0; i < poolObjects.First().GetType().GetMethods().Length; i++)
            {
                Console.WriteLine(poolObjects.First().GetType().GetMethods()[i].ToString());
            }
            if (poolObjects.First().GetType().BaseType.Name == BaseClassName)
            {
                /*onStartGenerate();
                 * th.Start();*/
            }
            if (Console.ReadLine().ToUpper() == StopThreadString)
            {
                th.Abort();
            }
            if (Console.ReadLine().ToUpper() == UpdateFunctionName.ToUpper())
            {
                onUpdateGenerate();
            }
            Console.Read();
        }
コード例 #18
0
 static Program()
 {
     reflectionMethods = LookupMethods();
 }
コード例 #19
0
    private MethodInfo GetCachedMethod(MonoBehaviour monob, ReflectionMethods methodType)
    {
        Type type = monob.GetType();
        if (!this.cachedMethods.ContainsKey(type))
        {
            Dictionary<ReflectionMethods, MethodInfo> newMethodsDict = new Dictionary<ReflectionMethods, MethodInfo>();
            this.cachedMethods.Add(type, newMethodsDict);
        }

        // Get method type list
        Dictionary<ReflectionMethods, MethodInfo> methods = this.cachedMethods[type];
        if (!methods.ContainsKey(methodType))
        {
            // Load into cache
            Type[] argTypes;
            if (methodType == ReflectionMethods.OnPhotonSerializeView)
            {
                argTypes = new Type[2];
                argTypes[0] = typeof(PhotonStream);
                argTypes[1] = typeof(PhotonMessageInfo);
            }
            else if (methodType == ReflectionMethods.OnPhotonInstantiate)
            {
                argTypes = new Type[1];
                argTypes[0] = typeof(PhotonMessageInfo);
            }
            else
            {
                Debug.LogError("Invalid ReflectionMethod!");
                return null;
            }

            MethodInfo metInfo = monob.GetType().GetMethod(
                methodType + string.Empty,
                BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                argTypes,
                null);
            if (metInfo != null)
            {
                methods.Add(methodType, metInfo);
            }
        }

        if (methods.ContainsKey(methodType))
        {
            return methods[methodType];
        }
        else
        {
            return null;
        }
    }
コード例 #20
0
        protected void SetPropertyValue(string rWidgetId, string[] rPath, object rValue, bool rIsBase64, bool rIsAttachedProperty)
        {
            var ignoreSet      = false;
            var targetPropName = XenProperty.GetLastPath(rPath);
            var pair           = Surface[rWidgetId];

            AttachedPropertyInfo  targetAttachedProp = null;
            XenReflectionProperty targetProp;

            if (rIsAttachedProperty)
            {
                var apAncestors = ElementHelper.GetParents(pair.XenWidget);
                var apInfos     = new List <AttachedPropertyInfo>();

                foreach (var ancestor in apAncestors)
                {
                    var aView = Surface[ancestor.Id];
                    if (aView == null)
                    {
                        continue;
                    }
                    apInfos.AddRange(ElementHelper.GetAttachedProperties(aView.VisualElement));
                }

                if (apInfos.Count == 0)
                {
                    return;
                }
                targetAttachedProp = apInfos.LastOrDefault(a => a.PropertyName == targetPropName);
                if (targetAttachedProp == null)
                {
                    return;
                }

                object apParent      = null;
                object apGrandParent = null;

                if (apAncestors.ElementAtOrDefault(0) != null)
                {
                    apParent = Surface[apAncestors[0].Id].VisualElement;
                }

                if (apAncestors.ElementAtOrDefault(1) != null)
                {
                    apGrandParent = Surface[apAncestors[1].Id].VisualElement;
                }

                targetProp = targetAttachedProp.Convert(apParent, apGrandParent);
            }
            else
            {
                targetProp = pair?
                             .VisualElement?
                             .GetXenRefProperties(rPath)
                             .FirstOrDefault();

                if (targetProp == null)
                {
                    return;
                }
            }

            if (targetPropName != null && targetPropName.Contains("Color"))
            {
                rValue = Color.FromHex(rValue.ToString());
            }

            // todo: make into a serializer
            if (targetPropName != null && targetPropName.Contains("Source"))
            {
                if (!rIsBase64)
                {
                    return;
                }
                var bytes = Convert.FromBase64String(rValue.ToString());

                var src = new XenImageSource(ImageSource.FromStream(() => new MemoryStream(bytes)))
                {
                    FileName = _req.Metadata?.ToString()
                };

                rValue = src;
            }

            // get enumeration value
            if (targetProp.IsTargetEnum)
            {
                var eval = ReflectionMethods.CreateEnum(targetProp.TargetType, rValue);

                if (eval == null)
                {
                    ignoreSet = true;
                }
                else
                {
                    rValue = eval;
                }
            }

            if (!ignoreSet)
            {
                DesignThread.Invoke(() =>
                {
                    // if target property is part of a structure and we're modifying its properties
                    // 1) make a copy of the current value
                    // 2) change the property value
                    // 3) reassign it
                    if (ReflectionMethods.IsValueType(targetProp.ParentObject))
                    {
                        var childProp = targetProp
                                        .ParentObject
                                        .GetXenRefProperties()
                                        .FirstOrDefault(p => p.TargetName == targetPropName);

                        childProp?.SetTargetObject(rValue);
                        var copy = childProp?.ParentObject;

                        var parentInfo = targetProp
                                         .GrandParentObject?
                                         .GetType()
                                         .GetProperty(targetProp.ParentName);

                        parentInfo?.SetValue(targetProp.GrandParentObject, copy);

                        // supporting View -> Struct -> Struct -> Target (valuetype or ref)
                        if (ReflectionMethods.IsValueType(targetProp.GrandParentObject))
                        {
                            if (rPath.Length == 3)
                            {
                                targetProp
                                .GrandParentObject?
                                .GetType()
                                .GetProperty(targetProp.ParentName)
                                .SetValue(targetProp.GrandParentObject, targetProp.ParentObject);

                                pair.VisualElement
                                .GetType()
                                .GetProperty(rPath[0])
                                .SetValue(pair.VisualElement, targetProp.GrandParentObject);
                            }
                        }
                    }
                    // this is assinging a field
                    else if (targetProp.IsTargetStruct && rValue is string)
                    {
                        var fieldName = rValue.ToString() ?? string.Empty;
                        var fieldInfo = targetProp.TargetType.GetStaticFields().FirstOrDefault(f => f.Name == fieldName);

                        if (fieldInfo == null)
                        {
                            if (rIsAttachedProperty)
                            {
                                SetAttachedProperty(rValue, targetAttachedProp, pair);
                            }
                            else
                            {
                                targetProp.SetTargetObject(rValue);
                            }
                        }
                        else
                        {
                            var copy = fieldInfo.GetValue(null);

                            if (rIsAttachedProperty)
                            {
                                SetAttachedProperty(copy, targetAttachedProp, pair);
                            }
                            else
                            {
                                targetProp.SetTargetObject(copy);
                            }
                        }
                    }
                    else
                    {
                        // one last attempt
                        if (rIsAttachedProperty)
                        {
                            SetAttachedProperty(rValue, targetAttachedProp, pair);
                        }
                        else
                        {
                            targetProp.SetTargetObject(rValue);
                        }
                    }
                });
            }
        }
コード例 #21
0
        public static Dialog Create(PropertyEditorModel <object> model, VisualTreeNode treeNode)
        {
            var widgetId     = treeNode.Widget.Id;
            var propertyName = model.Property.PropertyName;
            var pv           = model.Property.XenType.PossibleValues;

            var grid = new PropertyEditorGridView();

            var dlg = new ConnectedDialog
            {
                Title   = $"Edit {model.DisplayName}",
                Padding = AppStyles.WindowPadding,
                Width   = 650,
                Height  = 475
            };

            var collection = new ListBox();

            var footer = new TableLayout(4, 1)
            {
                Padding = new Padding(0, 10, 0, 0),
                Spacing = new Size(5, 5)
            };

            var ok = new Button {
                Text = "Ok"
            };
            var add = new Button {
                Text = "Add"
            };
            var del = new Button {
                Text = "Delete"
            };

            footer.Add(del, 0, 0, false, false);
            footer.Add(add, 1, 0, false, false);
            footer.Add(null, 2, 0, true, false);
            footer.Add(ok, 3, 0, false, false);

            var splitter = new Splitter
            {
                SplitterWidth    = 5,
                FixedPanel       = SplitterFixedPanel.Panel1,
                Panel1           = collection,
                Panel2           = grid,
                RelativePosition = dlg.Width * .35
            };

            var container = new TableLayout(1, 2);

            container.Add(splitter, 0, 0, true, true);
            container.Add(footer, 0, 1, true, false);

            dlg.Content       = container;
            dlg.AbortButton   = ok;
            dlg.DefaultButton = ok;

            ok.Click += (s, e) => { dlg.Close(); };

            dlg.Shown += (sender, args) =>
            {
                ToolboxApp.Log.Trace($"Showing {nameof(ObjectEditDialog)} for {treeNode.DisplayName}.");
            };

            dlg.Closing += (sender, args) =>
            {
                ToolboxApp.Bus.StopListening <CollectionPropertiesReceived>();
                ToolboxApp.Bus.StopListening <EditCollectionResponseReceived>();
                ToolboxApp.Bus.StopListening <ReplacedWidgetCollection>();

                ToolboxApp.Log.Trace($"Closing {nameof(ObjectEditDialog)} for {treeNode.DisplayName}.");
            };

            del.Click += (sender, args) =>
            {
                var item = collection.SelectedValue as ListItem;
                var path = (string)item?.Tag;
                if (string.IsNullOrWhiteSpace(path))
                {
                    return;
                }

                var res = MessageBox.Show(Application.Instance.MainForm,
                                          $"Are you sure you want to remove {path}?",
                                          AppResource.Title, MessageBoxButtons.YesNo, MessageBoxType.Question);

                if (res == DialogResult.Yes)
                {
                    ToolboxApp
                    .Designer
                    .EditCollection(treeNode.Widget.Id, EditCollectionType.Delete, path);
                }
            };

            add.Click += (sender, args) =>
            {
                ToolboxApp
                .AppEvents
                .Designer
                .EditCollection(treeNode.Widget.Id, EditCollectionType.Add, model.Property.PropertyName);
            };

            collection.SelectedIndexChanged += (sender, args) =>
            {
                grid.Clear();
                var item = collection.SelectedValue as ListItem;

                if (item != null)
                {
                    var path = (string)item.Tag;
                    ToolboxApp.Designer.GetObjectProperties(widgetId, path);
                }
            };

            ToolboxApp.AppEvents.Bus.Listen <CollectionPropertiesReceived>(args =>
            {
                var index = ReflectionMethods.GetIndexerValue(args.WidgetName);
                if (index == null)
                {
                    return;
                }

                Application.Instance.Invoke(() =>
                {
                    grid.ShowEditors(treeNode, args.Properties);
                });
            });

            ToolboxApp.AppEvents.Bus.Listen <ReplacedWidgetCollection>(args =>
            {
                Application.Instance.Invoke(() =>
                {
                    var length = GetCollectionCount(args.Widget, propertyName);
                    CreateListItems(collection, propertyName, length);
                });
            });

            ToolboxApp.AppEvents.Bus.Listen <EditCollectionResponseReceived>(args =>
            {
                Application.Instance.Invoke(() =>
                {
                    if (!args.Successful)
                    {
                        MessageBox.Show(Application.Instance.MainForm,
                                        $"There was an error performing the '{args.Type}' operation. Check the log for more information.",
                                        AppResource.Title, MessageBoxButtons.OK, MessageBoxType.Error);

                        ToolboxApp.Log.Error(args.Message);
                    }
                });
            });

            // populate list box
            if (pv != null)
            {
                int length;
                var parsed = int.TryParse(pv[0], out length);

                if (parsed)
                {
                    CreateListItems(collection, propertyName, length);
                }
            }

            return(dlg);
        }
コード例 #22
0
        public XenProperty[] GetXenProperties(XenReflectionProperty[] refProps, bool includeValues = false)
        {
            if (refProps == null)
            {
                return(null);
            }
            if (SupportingTypes.Types == null)
            {
                return(null);
            }

            var result = new List <XenProperty>();

            // The properties are in an intermediate state, right here.
            // a XenReflectionProperty is not meant to be returned in a request.

            // build xen properties.
            foreach (var curRef in refProps)
            {
                if (curRef.IsTargetEnum && SupportingTypes.IsRegistered(typeof(Enum)))
                {
                    if (!SupportingTypes.IsRegistered(curRef, RegistrarMatches.TypeName | RegistrarMatches.Enum))
                    {
                        continue;
                    }
                }
                else
                {
                    if (!SupportingTypes.IsRegistered(curRef, RegistrarMatches.TypeName))
                    {
                        continue;
                    }
                }

                var xenProp = new XenProperty
                {
                    Path     = new[] { curRef.TargetName },
                    Value    = curRef.GetTargetObject(),
                    CanRead  = curRef.CanReadTarget,
                    CanWrite = curRef.CanWriteTarget
                };

                // is the current property an enumeration?
                if (curRef.IsTargetEnum && SupportingTypes.IsRegistered(typeof(Enum)))
                {
                    var value = curRef.As <Enum>();
                    if (value != null)
                    {
                        Descriptor.SetPossibleValues(curRef, xenProp, value);

                        if (xenProp.Value != null)
                        {
                            xenProp.Value = Enum.GetName(xenProp.Value.GetType(), value);
                        }
                    }
                }
                else
                {
                    Descriptor.SetPossibleValues(curRef, xenProp);

                    // non-primitive structures (not System.DateTime, but Xamarin.Forms.Point)
                    if (ReflectionMethods.IsNotPrimitiveValueType(xenProp.Value))
                    {
                        xenProp.XenType.Descriptor |= XenPropertyDescriptors.ValueType;

                        var vtProps = XenPropertyMethods
                                      .GetPrimitiveValueTypeProperties(xenProp.Value)
                                      .ToArray();

                        if (vtProps.Length != 0)
                        {
                            foreach (var vtProp in vtProps)
                            {
                                Descriptor.SetPossibleValues(vtProp);

                                if (vtProp.Value.GetType() != typeof(string))
                                {
                                    var tmp = Convert.ToString(vtProp.Value ?? string.Empty);
                                    vtProp.Value = tmp;
                                }
                            }

                            // don't return values to the toolbox that will never be used.
                            xenProp.Value = includeValues ? vtProps : null;
                        }
                    }

                    // enumerables, collections, list.
                    if (curRef.TargetType.IsKindOf(typeof(ICollection <>)))
                    {
                        xenProp.XenType.Descriptor |= XenPropertyDescriptors.Collection;
                    }

                    if (curRef.TargetType.IsKindOf(typeof(IList <>)))
                    {
                        xenProp.XenType.Descriptor |= XenPropertyDescriptors.List;
                    }

                    if (curRef.TargetType.IsKindOf(typeof(IEnumerable <>)))
                    {
                        xenProp.XenType.Descriptor |= XenPropertyDescriptors.Enumerable;
                        var collection = xenProp.Value as IEnumerable <object>;

                        if (collection != null)
                        {
                            var count = collection.Count();
                            xenProp.XenType.PossibleValues = new[] { count.ToString() };

                            if (includeValues == false)
                            {
                                // don't send the value back to the toolbox
                                xenProp.Value = null;
                            }
                        }
                    }

                    /*
                     * obj support?
                     * if (!curRef.TargetType.GetTypeInfo().IsValueType && !curRef.TargetType.GetTypeInfo().IsPrimitive)
                     * {
                     *  if (!curRef.TargetType.Namespace.StartsWith("System"))
                     *  {
                     *      var oProps = XenPropertyMethods
                     *      .GetObjectProperties(xenProp.Value)
                     *      .ToArray();
                     *
                     *      if (oProps.Length != 0)
                     *      {
                     *          foreach (var oProp in oProps)
                     *          {
                     *              Descriptor.SetPossibleValues(oProp);
                     *
                     *              if (oProp.Value != null && oProp.Value.GetType() != typeof(string))
                     *              {
                     *                  var tmp = Convert.ToString(oProp.Value ?? string.Empty);
                     *                  oProp.Value = tmp;
                     *              }
                     *          }
                     *
                     *          // don't return values to the toolbox that will never be used.
                     *          xenProp.Value = includeValues ? oProps : null;
                     *      }
                     *  }
                     * }
                     */
                }

                result.Add(xenProp);
            }

            return(result.ToArray());
        }
コード例 #23
0
        /// <summary>
        ///		Loads the next node in the given binary reader and returns it.
        /// </summary>
        /// <param name="reader">Binary reader to read node from.</param>
        /// <param name="getProgress">If set to true this node is used to judge the current progress.</param>
        /// <returns>Scene node that was loaded from the binary reader.</returns>
        private SceneNode LoadNode(BinaryReader reader, bool getProgress)
        {
            // Read in the name of this node's class.
            string name = reader.ReadString();

            //HighPreformanceTimer timer = new HighPreformanceTimer();

            // Create a new instance of this entity and tell it to load itself.
            // (See if its a known object first as its quicker to get it without reflection)
            SceneNode node = null;

            if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.entitynode"))
            {
                node = new EntityNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.scriptedentitynode"))
            {
                node = new ScriptedEntityNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.scenenode"))
            {
                node = new SceneNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.groupnode"))
            {
                node = new GroupNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.emitternode"))
            {
                node = new EmitterNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.tilemapsegmentnode"))
            {
                node = new TilemapSegmentNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.pathmarkernode"))
            {
                node = new PathMarkerNode();
            }
            else if (name.ToLower().EndsWith("binaryphoenix.fusion.engine.entitys.tilenode"))
            {
                node = new TileNode();
            }
            else
            {
                node = (SceneNode)ReflectionMethods.CreateObject(name);
            }

            //DebugLogger.WriteLog("Created scene graph node " + name + " in " + timer.DurationMillisecond + ".\n");
            //timer.Restart();

            // Load in this nodes details.
            node.UniqueID = (_uniqueIDTracker++);
            node.Load(reader);

            //DebugLogger.WriteLog("Loaded scene graph node " + name + " in " + timer.DurationMillisecond + ".\n");

            // Read in all the children of this node, and attach
            // them to this node.
            DebugLogger.IncreaseIndent();
            int childCount = reader.ReadInt32();

            for (int i = 0; i < childCount; i++)
            {
                SceneNode childNode = LoadNode(reader);
                node.AddChild(childNode);

                if (getProgress == true)
                {
                    _loadingProgress = (int)(((float)(i + 1) / (float)childCount) * 100.0f);
                }
            }
            DebugLogger.DecreaseIndent();

            return(node);
        }
コード例 #24
0
        protected override void OnExecute(UIMessageContext ctx)
        {
            var r = ctx.Get <EditCollectionRequest>();

            if (r == null)
            {
                return;
            }

            var pair = Surface[r.WidgetId];
            var prop = pair?.VisualElement.GetRefProperties(r.Path).FirstOrDefault();

            var target = prop?.GetTargetObject();

            if (target == null)
            {
                return;
            }

            var successful = false;
            var message    = string.Empty;

            if (target.IsKindOf(typeof(IList <>)))
            {
                var colType = target.GetType();
                if (colType == null)
                {
                    return;
                }

                var itemType = ReflectionMethods.GetEnumerableItemType(colType);
                if (itemType == null)
                {
                    return;
                }

                if (r.Type == EditCollectionType.Delete)
                {
                    try
                    {
                        var index = ReflectionMethods.GetIndexerValue(r.Path.Last());
                        if (index == null || index < 0)
                        {
                            return;
                        }

                        colType.GetMethod("RemoveAt").Invoke(target, new[] { (object)index.Value });
                        successful = true;
                    }
                    catch (Exception e)
                    {
                        message    = e.Message;
                        successful = false;
                    }
                }

                if (r.Type == EditCollectionType.Add)
                {
                    try
                    {
                        object newItem;

                        if (colType.GetTypeInfo().IsGenericTypeDefinition)
                        {
                            newItem = Activator.CreateInstance(colType.MakeGenericType(itemType));
                        }
                        else
                        {
                            newItem = Activator.CreateInstance(itemType);
                        }

                        colType.GetMethod("Add").Invoke(target, new[] { newItem });
                        successful = true;
                    }
                    catch (Exception e)
                    {
                        message    = e.Message;
                        successful = false;
                    }
                }
            }

            ctx.SetResponse <EditCollectionResponse>(c =>
            {
                if (successful)
                {
                    c.Suggest <GetWidgetPropertiesRequest>();
                }

                c.WidgetId   = r.WidgetId;
                c.Type       = r.Type;
                c.Successful = successful;
                c.Message    = message;
            });
        }
コード例 #25
0
        /// <summary>
        ///		Called by the base engine class when its safe to begin initialization.
        /// </summary>
        protected override bool Begin()
        {
            // We alwasy want to run with the editor state!
            ScriptExecutionProcess.DefaultToEditorState = true;

            // Bind all function sets to the global virtual machine.
            NativeFunctionSet.RegisterCommandSetsToVirtualMachine(VirtualMachine.GlobalInstance);

            // Set the output file.
            DebugLogger.OutputFile = _logPath + "\\Editor " + DateTime.Now.Day + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + " " + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + ".log";

            // Ahhhh, no game given!!
            if (_gameName == "")
            {
                MessageBox.Show("No game was specified. Please pass a command line of -game:<ident> when running this application.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
                return(true);
            }

            // Make sure this game has not already been compiled.
            if (_gameConfigFile["resources:usepakfiles", "0"] == "1")
            {
                DebugLogger.WriteLog("Unable to edit game, game's media has already been compiled into pak files.", LogAlertLevel.FatalError);
            }

            _fpsLimit = int.Parse(_engineConfigFile["graphics:fpslimit", _fpsLimit.ToString()]);

            // Disable all resource caching.
            //ResourceManager.ResourceCacheEnabled = false;

            // Create the editor's window.
            _window              = new EditorWindow();
            _window.FormClosing += new FormClosingEventHandler(OnClosing);
            _window.Show();
            AudioManager.Driver.AttachToControl(_window);
            InputManager.Driver.AttachToControl(_window);

            // Load in the default tileset if it exists and add it to the tileset list.
            if (ResourceManager.ResourceExists(_tilesetPath + "\\default.xml") == true)
            {
                DebugLogger.WriteLog("Found default tileset, loading...");
                Tileset.AddToTilesetPool(new Tileset(_tilesetPath + "\\default.xml"));
            }

            // Load in the default font if it exists.
            if (ResourceManager.ResourceExists(_fontPath + "\\default.xml") == true)
            {
                DebugLogger.WriteLog("Found default bitmap font, loading...");
                GraphicsManager.DefaultBitmapFont = new BitmapFont(_fontPath + "\\default.xml");
            }

            // Load in the required language pack.
            string languageFile = _languagePath + "\\" + _language + ".xml";

            if (ResourceManager.ResourceExists(languageFile) == true)
            {
                DebugLogger.WriteLog("Loading language pack for language " + _language + ".");
                LanguageManager.LoadLanguagePack(_languagePath + "\\" + _language + ".xml", _language);
            }
            else
            {
                DebugLogger.WriteLog("Unable to find language pack for language " + _language + ".", LogAlertLevel.FatalError);
            }

            // Setup a camera that we can view the scene from.
            _camera = new CameraNode("Root Camera");
            _map.SceneGraph.AttachCamera(_camera);
            _camera.BackgroundImage = new Image(ReflectionMethods.GetEmbeddedResourceStream("grid.png"), 0);
            _camera.ClearColor      = unchecked ((int)0xFFACACAC);

            // Show the tip-of-the-day window.
            if (_engineConfigFile["editor:showtipsonstartup", "1"] == "1")
            {
                (new TipOfTheDayWindow()).ShowDialog();
            }

            // Disable collision processing.
            CollisionManager.Enabled = false;

            return(false);
        }