コード例 #1
0
        public override ProfilerModuleViewController CreateDetailsViewController()
        {
            ProfilerModuleViewController detailsViewController = null;

            // Try to get a view controller from the Memory Profiler package first.
            if (IsMemoryProfilerPackageInstalled())
            {
                // Old versions of the Memory Profiler package (before 1.0) will use reflection to bind their MemoryProfilerModuleBridge.CreateDetailsViewController callback to MemoryProfilerOverrides.CreateDetailsViewController. New versions of the Memory Profiler package (1.0+) cannot use reflection so instead wait to be called. Therefore, we call MemoryProfilerModuleBridge.CreateDetailsViewController callback manually from here, supporting both old and new versions. Note the callback itself cannot be cached, due to the Editor setting for enabling the functionality being respected in the package providing this callback or not.
                Func <ProfilerWindow, ProfilerModuleViewController> createDetailsViewControllerCallback = null;
                if (s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter == null)
                {
                    try
                    {
                        var type     = Type.GetType("Unity.MemoryProfiler.Editor.MemoryProfilerModule.MemoryProfilerModuleBridge, Unity.MemoryProfiler.Editor.MemoryProfilerModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null");
                        var property = type.GetProperty("CreateDetailsViewController");
                        s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter = property.GetMethod;
                    }
                    catch (Exception) { }
                }

                createDetailsViewControllerCallback = s_MemoryProfilerModuleBridgeCreateDetailsViewControllerPropertyGetter?.Invoke(null, null) as Func <ProfilerWindow, ProfilerModuleViewController>;
                detailsViewController = createDetailsViewControllerCallback?.Invoke(ProfilerWindow);
            }

            // Fall back to the built-in view controller.
            if (detailsViewController == null)
            {
                detailsViewController = new MemoryProfilerModuleViewController(ProfilerWindow, this);
            }

            return(detailsViewController);
        }
        /// <summary>
        /// Specify the startup type to be used by the host.
        /// </summary>
        /// <typeparam name="TStartup">The type containing an optional constructor with
        /// an <see cref="IConfiguration"/> parameter. The implementation should contain a public
        /// method named ConfigureServices with <see cref="IServiceCollection"/> parameter.</typeparam>
        /// <param name="hostBuilder">The <see cref="IHostBuilder"/> to initialize with TStartup.</param>
        /// <returns>The same instance of the <see cref="IHostBuilder"/> for chaining.</returns>
        public static IHostBuilder UseStartup <TStartup>(
            this IHostBuilder hostBuilder) where TStartup : class
        {
            hostBuilder = hostBuilder ?? throw new ArgumentNullException(nameof(hostBuilder));
            // Invoke the ConfigureServices method on IHostBuilder...
            hostBuilder.ConfigureServices((ctx, serviceCollection) =>
            {
                // Find a method that has this signature: ConfigureServices(IServiceCollection)
                System.Reflection.MethodInfo cfgServicesMethod = typeof(TStartup).GetMethod(
                    ConfigureServicesMethodName, new Type[] { typeof(IServiceCollection) });

                // Check if TStartup has a ctor that takes a IConfiguration parameter
                bool hasConfigCtor = typeof(TStartup).GetConstructor(
                    new Type[] { typeof(IConfiguration) }) != null;

                // create a TStartup instance based on ctor
                TStartup startUpObj = hasConfigCtor ?
                                      (TStartup)Activator.CreateInstance(typeof(TStartup), ctx.Configuration) :
                                      (TStartup)Activator.CreateInstance(typeof(TStartup), null);

                // finally, call the ConfigureServices implemented by the TStartup object
                cfgServicesMethod?.Invoke(startUpObj, new object[] { serviceCollection });
            });

            // chain the response
            return(hostBuilder);
        }
コード例 #3
0
        public override Task OnDisconnectedAsync(Exception exception)
        {
            try
            {
                // we don't know which instances care, so let all running instances know
                var pluginInstances = BackgroundThreadPluginManager.Instance.Registrations
                                      .SelectMany(reg => reg.GetLoadedInstances(), (reg, inst) => new { Reg = reg, Instance = inst })
                                      .ToList();

                Parallel.ForEach(pluginInstances, pi =>
                {
                    try
                    {
                        PluginOnDisconnectedFromHubMethod?.Invoke(pi.Instance.Plugin, new object[] { Context.ConnectionId, exception });
                    }
                    catch (System.Exception ee)
                    {
                        ExceptionLogger.LogExceptionThrottled(ee, $"BackgroundPluginHub::OnDisconnectedAsync - failed to invoke Plugin's OnDisconnected method. ${pi.Reg.PluginName} (${pi.Reg.PluginGuid})", 5);
                    }
                });
            }
            catch (Exception ex)
            {
                ExceptionLogger.LogExceptionThrottled(ex, "BackgroundPluginHub::OnDisconnectedAsync", 5);
            }


            return(base.OnDisconnectedAsync(exception));
        }
コード例 #4
0
        private static void PreserveStackTrace(Exception exception)
        {
            // TODO Need to sort this out for core
#if !NewReflection
            System.Reflection.MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
                                                                                          System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            preserveStackTrace?.Invoke(exception, null);
#endif
        }
コード例 #5
0
ファイル: MenuItemData.cs プロジェクト: huangdonghai/titan3d
 public void ClickOperation(object sender, System.Windows.RoutedEventArgs e)
 {
     if (Method.ReturnType == typeof(void))
     {
         Method?.Invoke(null, null);
     }
     else
     {
         var    retVal = Method?.Invoke(null, null);
         string str    = System.Convert.ToString(retVal);
         if (!string.IsNullOrEmpty(str))
         {
             var item = sender as MenuItem;
             if (item != null)
             {
                 item.Header = str;
             }
         }
     }
 }
コード例 #6
0
        /// <summary>
        /// HACK: makes Unity Editor execute continuations in edit mode.
        /// </summary>
        private static void ExecuteContinuations()
        {
            if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            if (executionMethod == null)
            {
                executionMethod = SynchronizationContext.Current.GetType().GetMethod("Exec", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            }

            UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
            executionMethod?.Invoke(SynchronizationContext.Current, null);
        }
コード例 #7
0
        static void InvalidateOutAndError()
        {
            Type type = typeof(System.Console);

            System.Reflection.FieldInfo _out = type.GetField("_out",
                                                             System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            System.Reflection.FieldInfo _error = type.GetField("_error",
                                                               System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            System.Reflection.MethodInfo _InitializeStdOutError = type.GetMethod("InitializeStdOutError",
                                                                                 System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
            // Debug.Assert(_out != null);
            // Debug.Assert(_error != null);
            // Debug.Assert(_InitializeStdOutError != null);
            _out?.SetValue(null, null);
            _error?.SetValue(null, null);
            _InitializeStdOutError?.Invoke(null, new object[] { true });
        }
コード例 #8
0
 /// <summary>
 /// This is called from the compile/run appdomain to convert objects within an expression block to a string
 /// </summary>
 public string ToStringWithCulture(object objectToConvert)
 {
     if ((objectToConvert == null))
     {
         throw new global::System.ArgumentNullException("objectToConvert");
     }
     System.Type t = objectToConvert.GetType();
     System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
         typeof(System.IFormatProvider)
     });
     if ((method == null))
     {
         return(objectToConvert.ToString());
     }
     else
     {
         return((string)(method?.Invoke(objectToConvert, new object[] {
             this.formatProviderField
         })));
     }
 }
コード例 #9
0
 protected void UpdatePanel1_Unload(object sender, EventArgs e)
 {
     System.Reflection.MethodInfo methodInfo = typeof(ScriptManager).GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).Where(i => i.Name.Equals("System.Web.UI.IScriptManagerInternal.RegisterUpdatePanel")).First();
     methodInfo.Invoke(ScriptManager.GetCurrent(Page), new object[] { sender as UpdatePanel });
 }
コード例 #10
0
        public void AddDataOfType(Object o, Type rettype, string name, int depth)
        {
            if (depth < 0)       // 0, list, class, object, .. limit depth
            {
                return;
            }

            //System.Diagnostics.Debug.WriteLine("Object " + name + " " + rettype.Name);

            System.Globalization.CultureInfo ct = System.Globalization.CultureInfo.InvariantCulture;

            try // just to make sure a strange type does not barfe it
            {
                if (rettype.UnderlyingSystemType.FullName.Contains("System.Collections.Generic.Dictionary"))
                {
                    if (o == null)
                    {
                        values[name + "Count"] = "0";                           // we always get a NameCount so we can tell..
                    }
                    else
                    {
                        var data = (System.Collections.IDictionary)o;           // lovely to work out

                        values[name + "Count"] = data.Count.ToString(ct);       // purposely not putting a _ to distinguish it from the entries

                        foreach (Object k in data.Keys)
                        {
                            if (k is string)
                            {
                                Object v = data[k as string];
                                AddDataOfType(v, v.GetType(), name + "_" + (string)k, depth - 1);
                            }
                        }
                    }
                }
                else if (rettype.UnderlyingSystemType.FullName.Contains("System.Collections.Generic.List"))
                {
                    if (o == null)
                    {
                        values[name + "Count"] = "0";                           // we always get a NameCount so we can tell..
                    }
                    else
                    {
                        var data = (System.Collections.IList)o;           // lovely to work out

                        values[name + "Count"] = data.Count.ToString(ct); // purposely not putting a _ to distinguish it from the entries

                        for (int i = 0; i < data.Count; i++)
                        {
                            AddDataOfType(data[i], data[i].GetType(), name + "[" + (i + 1).ToString(ct) + "]", depth - 1);
                        }
                    }
                }
                else if (rettype.IsArray)
                {
                    if (o == null)
                    {
                        values[name + "_Length"] = "0";                         // always get a length
                    }
                    else
                    {
                        Array b = o as Array;
                        if (b != null)  // should not fail but just in case..
                        {
                            values[name + "_Length"] = b.Length.ToString(ct);

                            for (int i = 0; i < b.Length; i++)
                            {
                                object oa = b.GetValue(i);
                                AddDataOfType(oa, oa.GetType(), name + "[" + i.ToString(ct) + "]", depth - 1);
                            }
                        }
                    }
                }
                else if (o == null)
                {
                    values[name] = "";
                }
                else if (o is string)     // string is a class, so intercept first
                {
                    values[name] = o as string;
                }
                else if (rettype.IsClass)
                {
                    foreach (System.Reflection.PropertyInfo pi in rettype.GetProperties())
                    {
                        if (pi.GetIndexParameters().GetLength(0) == 0 && pi.PropertyType.IsPublic)      // only properties with zero parameters are called
                        {
                            System.Reflection.MethodInfo getter = pi.GetGetMethod();
                            AddDataOfType(getter.Invoke(o, null), pi.PropertyType, name + "_" + pi.Name, depth - 1);
                        }
                    }

                    foreach (System.Reflection.FieldInfo fi in rettype.GetFields())
                    {
                        AddDataOfType(fi.GetValue(o), fi.FieldType, name + "_" + fi.Name, depth - 1);
                    }
                }
                else if (o is bool)
                {
                    values[name] = ((bool)o) ? "1" : "0";
                }
                else if (!rettype.IsGenericType || rettype.GetGenericTypeDefinition() != typeof(Nullable <>))
                {
                    var v = Convert.ChangeType(o, rettype);

                    if (v is Double)
                    {
                        values[name] = ((double)v).ToString(ct);
                    }
                    else if (v is int)
                    {
                        values[name] = ((int)v).ToString(ct);
                    }
                    else if (v is long)
                    {
                        values[name] = ((long)v).ToString(ct);
                    }
                    else if (v is DateTime)
                    {
                        values[name] = ((DateTime)v).ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
                    }
                    else
                    {
                        values[name] = v.ToString();
                    }
                }
                else
                {                                                                         // generic, get value type
                    System.Reflection.PropertyInfo pvalue = rettype.GetProperty("Value"); // value is second property of a nullable class

                    Type nulltype = pvalue.PropertyType;                                  // its type and value are found..
                    var  value    = pvalue.GetValue(o);
                    AddDataOfType(value, nulltype, name, depth - 1);                      // recurse to decode it
                }
            }
            catch { }
        }
コード例 #11
0
ファイル: Main.cs プロジェクト: jfmiguez/AutoMarket
        private void butTestBases_Click(object sender, EventArgs e)
        {
            API.ApiYahoo apiYahoo = new API.ApiYahoo();

            //get historical quotes from yahoo
            // List<API.Candle> mCandle = new List<API.Candle>();
            DateTime dtStart = System.Convert.ToDateTime(dtDateFrom.Text);
            DateTime dtEnd   = System.Convert.ToDateTime(dtDateTo.Text);

            lstRealTimeQuotes.Items.Clear();
            lstTestGoogle.Items.Clear();

            //Convert interval to seconds
            string sFactor = cboInterval.Text.Substring(cboInterval.Text.Length - 1, 1);
            int    seconds = 0;

            if (sFactor == "m")
            {
                seconds = System.Convert.ToInt32(cboInterval.Text.Replace("m", "")) * 60;
            }
            else if (sFactor == "h")
            {
                seconds = System.Convert.ToInt32(cboInterval.Text.Replace("h", "")) * 60 * 60;
            }
            else if (sFactor == "d")
            {
                seconds = System.Convert.ToInt32(cboInterval.Text.Replace("d", "")) * 60 * 60 * 24;
            }
            else if (sFactor == "k")
            {
                seconds = System.Convert.ToInt32(cboInterval.Text.Replace("wk", "")) * 60 * 60 * 24 * 5;
            }
            else if (sFactor == "o")
            {
                seconds = System.Convert.ToInt32(cboInterval.Text.Replace("mo", "")) * 60 * 60 * 24 * 5 * 4;
            }

            //pass variables to the historical price.
            IEnumerable <API.Candle> candleSticks = apiYahoo.GetHistoricalPrice(txtSymbol.Text, seconds, dtStart, dtEnd);



            //NOTE: THIS WILL BE PART OF THE EXECUTION ENGINE



            BaseData oData = new BaseData();

            //Generate a base finder and get all the DERIVED CLASSES of the base class.
            Base          baseFinder     = new Base();
            List <String> DerivedClasses = baseFinder.FindDerivedClasses();

            // Let's just get one of the classes and dynamically create an instance of the class
            // of the derived type!
            String strClass    = DerivedClasses[0];
            Type   DerivedType = baseFinder.DerivedClass(strClass);
            Object mClass      = (object)Activator.CreateInstance(DerivedType);

            //Call methods inside the class, first method will return something by value
            // second method will take parameters and return something from the dynamically created object.
            //System.Reflection.MethodInfo method = DerivedType.GetMethod("FindBase");
            //var somereturnvalue = method.Invoke(mClass, new object[0]);
            System.Reflection.MethodInfo method = DerivedType.GetMethod("FindBase");
            oData = (BaseData)method.Invoke(mClass, new object[] { candleSticks });
            System.Reflection.MethodInfo method2 = DerivedType.GetMethod("Findsomething");
            String param1           = "testing number ";
            int    param2           = 7;
            var    somereturnvalue2 = method2.Invoke(mClass, new object[] { param1, param2 });

            Console.WriteLine("> " + somereturnvalue2);

            // Generate a list of all derived classes (no, not method we are not going to over-populate)
            for (int i = 0; i < DerivedClasses.Count(); i++)
            {
                lstRealTimeQuotes.Items.Add(DerivedClasses[i]);
            }
        }
コード例 #12
0
        void OnBookmarkCallback(NativeActivityContext context, Bookmark bookmark, object obj)
        {
            bool waitforcompleted = WaitForCompleted.Get(context);

            if (!waitforcompleted)
            {
                return;
            }
            // keep bookmark, incase workflow dies, and need to pickup more data when started again
            // context.RemoveBookmark(bookmark.Name);
            var command = Newtonsoft.Json.JsonConvert.DeserializeObject <Interfaces.mq.RobotCommand>(obj.ToString());

            if (command.data == null)
            {
                return;
            }
            if (command.command == "invokefailed" || command.command == "error")
            {
                if (string.IsNullOrEmpty(command.data.ToString()))
                {
                    throw new Exception("Invoke failed");
                }
                Exception ex = null;
                try
                {
                    ex = Newtonsoft.Json.JsonConvert.DeserializeObject <Exception>(command.data.ToString());
                }
                catch (Exception)
                {
                }
                if (ex != null)
                {
                    throw ex;
                }
                throw new Exception(command.data.ToString());
            }
            if (command.command == "timeout")
            {
                throw new Exception("request timed out, no robot picked up the message in a timely fashion");
            }
            if (string.IsNullOrEmpty(command.data.ToString()))
            {
                return;
            }
            var           payload = JObject.Parse(command.data.ToString());
            List <string> keys    = payload.Properties().Select(p => p.Name).ToList();

            if (Arguments == null || Arguments.Count == 0)
            {
                foreach (var key in keys)
                {
                    var myVar = context.DataContext.GetProperties().Find(key, true);
                    if (myVar != null)
                    {
                        if (myVar.PropertyType.Name == "DataTable")
                        {
                            var json = payload[key].ToString();
                            if (!string.IsNullOrEmpty(json))
                            {
                                var jarray = JArray.Parse(json);
                                myVar.SetValue(context.DataContext, jarray.ToDataTable());
                            }
                            else
                            {
                                myVar.SetValue(context.DataContext, null);
                            }
                        }
                        else if (myVar.PropertyType.Name == "JArray")
                        {
                            var json = payload[key].ToString();
                            var jobj = JArray.Parse(json);
                            myVar.SetValue(context.DataContext, jobj);
                        }
                        else if (myVar.PropertyType.Name == "JObject")
                        {
                            var json = payload[key].ToString();
                            var jobj = JObject.Parse(json);
                            myVar.SetValue(context.DataContext, jobj);
                        }
                        else
                        {
                            myVar.SetValue(context.DataContext, payload[key].ToString());
                        }
                    }
                }
            }
            else
            {
                Dictionary <string, object> arguments = (from argument in Arguments
                                                         where argument.Value.Direction != ArgumentDirection.In
                                                         select argument).ToDictionary((KeyValuePair <string, Argument> argument) => argument.Key, (KeyValuePair <string, Argument> argument) => argument.Value.Get(context));
                foreach (var a in arguments)
                {
                    if (keys.Contains(a.Key))
                    {
                        if (Arguments[a.Key].ArgumentType == typeof(System.Data.DataTable))
                        {
                            try
                            {
                                var json = payload[a.Key].ToString();
                                if (!string.IsNullOrEmpty(json))
                                {
                                    var jarray = JArray.Parse(json);
                                    Arguments[a.Key].Set(context, jarray.ToDataTable());
                                }
                                else
                                {
                                    Arguments[a.Key].Set(context, null);
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                        else
                        {
                            JToken t        = payload[a.Key];
                            var    testtest = t.Value <string>();
                            System.Reflection.MethodInfo method  = typeof(JToken).GetMethod(nameof(JToken.Value)); // typeof(JToken).GetMethod(nameof(JToken.Value));
                            System.Reflection.MethodInfo generic = method.MakeGenericMethod(Arguments[a.Key].ArgumentType);
                            var value = generic.Invoke(t, new object[] {  });
                            Arguments[a.Key].Set(context, value);
                        }
                    }
                    else
                    {
                        try
                        {
                            if (Arguments[a.Key].ArgumentType.IsValueType)
                            {
                                Arguments[a.Key].Set(context, Activator.CreateInstance(Arguments[a.Key].ArgumentType));
                            }
                            else
                            {
                                Arguments[a.Key].Set(context, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Error setting " + a.Key + ": " + ex.Message);
                        }
                    }
                }
            }
        }
コード例 #13
0
        public void StartProcess(SVGAsset asset)
        {
            if (UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode)
            {
                return;
            }

            if (errors == null)
            {
                errors = new List <SVGError>();
            }
            else
            {
                errors.Clear();
            }
            _importingSVG = true;

            UnityEditor.SerializedObject   svgAsset      = new UnityEditor.SerializedObject(asset);
            UnityEditor.SerializedProperty sharedMesh    = svgAsset.FindProperty("_sharedMesh");
            UnityEditor.SerializedProperty sharedShaders = svgAsset.FindProperty("_sharedShaders");

            // clean up
            SVGParser.Clear();
            SVGParser.Init();
            SVGGraphics.Clear();
            SVGGraphics.Init();

            SVGElement _rootSVGElement = null;

#if IGNORE_EXCEPTIONS
            try {
#else
            Debug.LogWarning("Exceptions are turned on!");
#endif
                // Create new Asset
                CreateEmptySVGDocument();
                _rootSVGElement = this._svgDocument.rootElement;
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                _rootSVGElement = null;
                errors.Add(SVGError.Syntax);
                Debug.LogError("SVG Document Exception: " + exception.Message, asset);
            }
#endif

                if (_rootSVGElement == null)
                {
                    Debug.LogError("SVG Document is corrupted! " + UnityEditor.AssetDatabase.GetAssetPath(asset), asset);
                    return;
                }

                SVGGraphics.depthTree = new SVGDepthTree(_rootSVGElement.paintable.viewport);

#if IGNORE_EXCEPTIONS
                try {
#endif
                _rootSVGElement.Render();

                // Handle gradients
                bool hasGradients = (useGradients == SVGUseGradients.Always);
                SVGAtlas atlas    = SVGAtlas.Instance;
                if (useGradients != SVGUseGradients.Never)
                {
                    atlas.hideFlags = HideFlags.DontSave;
                    if (SVGAtlas.Instance.gradients != null && atlas.gradients.Count > 1)
                    {
                        int gradientCount  = atlas.gradients.Count;
                        int gradientWidth  = atlas.gradientWidth;
                        int gradientHeight = atlas.gradientHeight;
                        atlas.atlasTextureWidth  = gradientWidth * 2;
                        atlas.atlasTextureHeight = Mathf.CeilToInt((gradientCount * gradientWidth) / atlas.atlasTextureWidth) * gradientHeight + gradientHeight;
                        atlas.RebuildAtlas();

                        hasGradients = true;
                    }
                }

                // Create actual Mesh
                Material[] outputMaterials;
                Mesh mesh = SVGMesh.CreateMesh(out outputMaterials);
                if (mesh == null)
                {
                    return;
                }

                // Delete gradients if needed
                if (!hasGradients)
                {
                    mesh.uv  = new Vector2[0];
                    mesh.uv2 = new Vector2[0];
                }

                Vector3[] vertices = mesh.vertices;
                Vector2 offset;
                Bounds bounds = mesh.bounds;
                Rect viewport = _rootSVGElement.paintable.viewport;
                viewport.x    *= SVGMesh.meshScale;
                viewport.y    *= SVGMesh.meshScale;
                viewport.size *= SVGMesh.meshScale;

                if (asset.ignoreSVGCanvas)
                {
                    offset = new Vector2(bounds.min.x + bounds.size.x * asset.pivotPoint.x,
                                         bounds.min.y + bounds.size.y * asset.pivotPoint.y);
                }
                else
                {
                    offset = new Vector2(viewport.min.x + viewport.size.x * asset.pivotPoint.x,
                                         viewport.min.y + viewport.size.y * asset.pivotPoint.y);
                }

                // Apply pivot point and Flip Y Axis
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i].x = vertices[i].x - offset.x;
                    vertices[i].y = (vertices[i].y - offset.y) * -1f;
                }

                mesh.vertices = vertices;
                mesh.RecalculateBounds();
                sharedMesh.objectReferenceValue = AddObjectToAsset <Mesh>(mesh, asset, HideFlags.HideInHierarchy);

//                Material sharedMaterial;
                if (outputMaterials != null && outputMaterials.Length > 0)
                {
                    sharedShaders.arraySize = outputMaterials.Length;
                    if (hasGradients)
                    {
                        for (int i = 0; i < outputMaterials.Length; i++)
                        {
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputMaterials[i].shader.name;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < outputMaterials.Length; i++)
                        {
                            if (outputMaterials[i].shader.name == SVGShader.GradientColorAlphaBlended.name)
                            {
                                outputMaterials[i].shader = SVGShader.SolidColorAlphaBlended;
                            }
                            else if (outputMaterials[i].shader.name == SVGShader.GradientColorOpaque.name)
                            {
                                outputMaterials[i].shader = SVGShader.SolidColorOpaque;
                            }
                            sharedShaders.GetArrayElementAtIndex(i).stringValue = outputMaterials[i].shader.name;
                        }
                    }
                }

                // Serialize the Asset
                svgAsset.ApplyModifiedProperties();

                // Handle Canvas Rectangle
                System.Reflection.MethodInfo _editor_SetCanvasRectangle = typeof(SVGAsset).GetMethod("_editor_SetCanvasRectangle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                _editor_SetCanvasRectangle.Invoke(asset, new object[] { new Rect(viewport.x, viewport.y, viewport.size.x, viewport.size.y) });

                if (asset.generateCollider)
                {
                    // Create polygon contour
                    if (SVGGraphics.paths != null && SVGGraphics.paths.Count > 0)
                    {
                        List <List <Vector2> > polygons = new List <List <Vector2> >();
                        for (int i = 0; i < SVGGraphics.paths.Count; i++)
                        {
                            Vector2[] points = SVGGraphics.paths[i].points;
                            for (int j = 0; j < points.Length; j++)
                            {
                                points[j].x = points[j].x * SVGMesh.meshScale - offset.x;
                                points[j].y = (points[j].y * SVGMesh.meshScale - offset.y) * -1f;
                            }

                            polygons.Add(new List <Vector2>(points));
                        }

                        polygons = SVGGeom.MergePolygon(polygons);

                        SVGPath[] paths = new SVGPath[polygons.Count];
                        for (int i = 0; i < polygons.Count; i++)
                        {
                            paths[i] = new SVGPath(polygons[i].ToArray());
                        }

                        System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                        if (paths != null && paths.Length > 0)
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { paths });
                        }
                        else
                        {
                            _editor_SetColliderShape.Invoke(asset, new object[] { null });
                        }
                    }
                }
                else
                {
                    System.Reflection.MethodInfo _editor_SetColliderShape = typeof(SVGAsset).GetMethod("_editor_SetColliderShape", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    _editor_SetColliderShape.Invoke(asset, new object[] { null });
                }

                if (hasGradients)
                {
                    System.Reflection.MethodInfo _editor_SetGradients = typeof(SVGAsset).GetMethod("_editor_SetGradients", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    if (atlas.gradients != null && atlas.gradients.Count > 0)
                    {
                        _editor_SetGradients.Invoke(asset, new object[] { atlas.gradients.ToArray() });
                    }
                    else
                    {
                        _editor_SetGradients.Invoke(asset, new object[] { null });
                    }
                }
#if IGNORE_EXCEPTIONS
            } catch (System.Exception exception) {
                Debug.LogWarning("Asset: " + UnityEditor.AssetDatabase.GetAssetPath(asset) + " Failed to import\n" + exception.Message, asset);
                errors.Add(SVGError.CorruptedFile);
            }
#endif

                SVGAtlas.ClearAll();
                SVGGraphics.Clear();
                if (_svgDocument != null)
                {
                    _svgDocument.Clear();
                }

                UnityEditor.EditorUtility.SetDirty(asset);
                _importingSVG = false;
            }
コード例 #14
0
ファイル: NodeEditorGUI.cs プロジェクト: siverson101/xNode
        private void DrawNodes()
        {
            Event e = Event.current;

            if (e.type == EventType.Layout)
            {
                selectionCache = new List <UnityEngine.Object>(Selection.objects);
            }
            if (e.type == EventType.Repaint)
            {
                portConnectionPoints.Clear();
                nodeWidths.Clear();
            }

            //Active node is hashed before and after node GUI to detect changes
            int nodeHash = 0;

            System.Reflection.MethodInfo onValidate = null;
            if (Selection.activeObject != null && Selection.activeObject is XNode.Node)
            {
                onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
                if (onValidate != null)
                {
                    nodeHash = Selection.activeObject.GetHashCode();
                }
            }

            BeginZoomed(position, zoom);

            Vector2 mousePos = Event.current.mousePosition;

            if (e.type != EventType.Layout)
            {
                hoveredNode = null;
                hoveredPort = null;
            }

            List <UnityEngine.Object> preSelection = preBoxSelection != null ? new List <UnityEngine.Object>(preBoxSelection) : new List <UnityEngine.Object>();

            // Selection box stuff
            Vector2 boxStartPos = GridToWindowPositionNoClipped(dragBoxStart);
            Vector2 boxSize     = mousePos - boxStartPos;

            if (boxSize.x < 0)
            {
                boxStartPos.x += boxSize.x; boxSize.x = Mathf.Abs(boxSize.x);
            }
            if (boxSize.y < 0)
            {
                boxStartPos.y += boxSize.y; boxSize.y = Mathf.Abs(boxSize.y);
            }
            Rect selectionBox = new Rect(boxStartPos, boxSize);

            //Save guiColor so we can revert it
            Color guiColor = GUI.color;

            for (int n = 0; n < graph.nodes.Count; n++)
            {
                // Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
                if (graph.nodes[n] == null)
                {
                    continue;
                }
                if (n >= graph.nodes.Count)
                {
                    return;
                }
                XNode.Node node = graph.nodes[n];

                NodeEditor nodeEditor = NodeEditor.GetEditor(node);
                NodeEditor.portPositions = new Dictionary <XNode.NodePort, Vector2>();

                //Get node position
                Vector2 nodePos = GridToWindowPositionNoClipped(node.position);

                GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000)));

                bool selected = selectionCache.Contains(graph.nodes[n]);

                if (selected)
                {
                    GUIStyle style          = new GUIStyle(NodeEditorResources.styles.nodeBody);
                    GUIStyle highlightStyle = new GUIStyle(NodeEditorResources.styles.nodeHighlight);
                    highlightStyle.padding = style.padding;
                    style.padding          = new RectOffset();
                    GUI.color = nodeEditor.GetTint();
                    GUILayout.BeginVertical(new GUIStyle(style));
                    GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
                    GUILayout.BeginVertical(new GUIStyle(highlightStyle));
                }
                else
                {
                    GUIStyle style = NodeEditorResources.styles.nodeBody;
                    GUI.color = nodeEditor.GetTint();
                    GUILayout.BeginVertical(new GUIStyle(style));
                }

                GUI.color = guiColor;
                EditorGUI.BeginChangeCheck();

                //Draw node contents
                nodeEditor.OnNodeGUI();

                //Apply
                nodeEditor.serializedObject.ApplyModifiedProperties();

                //If user changed a value, notify other scripts through onUpdateNode
                if (EditorGUI.EndChangeCheck())
                {
                    if (NodeEditor.onUpdateNode != null)
                    {
                        NodeEditor.onUpdateNode(node);
                    }
                }

                if (e.type == EventType.Repaint)
                {
                    nodeWidths.Add(node, nodeEditor.GetWidth());

                    foreach (var kvp in NodeEditor.portPositions)
                    {
                        Vector2 portHandlePos = kvp.Value;
                        portHandlePos += node.position;
                        Rect rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
                        portConnectionPoints.Add(kvp.Key, rect);
                    }
                }

                GUILayout.EndVertical();
                if (selected)
                {
                    GUILayout.EndVertical();
                }

                if (e.type != EventType.Layout)
                {
                    //Check if we are hovering this node
                    Vector2 nodeSize   = GUILayoutUtility.GetLastRect().size;
                    Rect    windowRect = new Rect(nodePos, nodeSize);
                    if (windowRect.Contains(mousePos))
                    {
                        hoveredNode = node;
                    }

                    //If dragging a selection box, add nodes inside to selection
                    if (currentActivity == NodeActivity.DragGrid)
                    {
                        if (windowRect.Overlaps(selectionBox))
                        {
                            preSelection.Add(node);
                        }
                    }

                    //Check if we are hovering any of this nodes ports
                    //Check input ports
                    foreach (XNode.NodePort input in node.Inputs)
                    {
                        //Check if port rect is available
                        if (!portConnectionPoints.ContainsKey(input))
                        {
                            continue;
                        }
                        Rect r = GridToWindowRectNoClipped(portConnectionPoints[input]);
                        if (r.Contains(mousePos))
                        {
                            hoveredPort = input;
                        }
                    }
                    //Check all output ports
                    foreach (XNode.NodePort output in node.Outputs)
                    {
                        //Check if port rect is available
                        if (!portConnectionPoints.ContainsKey(output))
                        {
                            continue;
                        }
                        Rect r = GridToWindowRectNoClipped(portConnectionPoints[output]);
                        if (r.Contains(mousePos))
                        {
                            hoveredPort = output;
                        }
                    }
                }

                GUILayout.EndArea();
            }

            if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
            {
                Selection.objects = preSelection.ToArray();
            }
            EndZoomed(position, zoom);

            //If a change in hash is detected in the selected node, call OnValidate method.
            //This is done through reflection because OnValidate is only relevant in editor,
            //and thus, the code should not be included in build.
            if (nodeHash != 0)
            {
                if (onValidate != null && nodeHash != Selection.activeObject.GetHashCode())
                {
                    onValidate.Invoke(Selection.activeObject, null);
                }
            }
        }
コード例 #15
0
        private void DrawNodes()
        {
            var e = Event.current;

            if (e.type == EventType.Layout)
            {
                this.selectionCache = new List <UnityEngine.Object>(Selection.objects);
            }

            System.Reflection.MethodInfo onValidate = null;
            if (Selection.activeObject != null && Selection.activeObject is xNode.Node)
            {
                onValidate = Selection.activeObject.GetType().GetMethod("OnValidate");
                if (onValidate != null)
                {
                    EditorGUI.BeginChangeCheck();
                }
            }

            BeginZoomed(this.position, this.zoom, this.topPadding);

            var mousePos = Event.current.mousePosition;

            if (e.type != EventType.Layout)
            {
                this.hoveredNode = null;
                this.hoveredPort = null;
            }

            var preSelection = this.preBoxSelection != null
                ? new List <UnityEngine.Object>(this.preBoxSelection)
                : new List <UnityEngine.Object>();

            // Selection box stuff
            var boxStartPos = this.GridToWindowPositionNoClipped(this.dragBoxStart);
            var boxSize     = mousePos - boxStartPos;

            if (boxSize.x < 0)
            {
                boxStartPos.x += boxSize.x;
                boxSize.x      = Mathf.Abs(boxSize.x);
            }

            if (boxSize.y < 0)
            {
                boxStartPos.y += boxSize.y;
                boxSize.y      = Mathf.Abs(boxSize.y);
            }

            var selectionBox = new Rect(boxStartPos, boxSize);

            //Save guiColor so we can revert it
            var guiColor = GUI.color;

            var removeEntries = new List <xNode.NodePort>();

            if (e.type == EventType.Layout)
            {
                this.culledNodes = new List <xNode.Node>();
            }

            for (var n = 0; n < this.graph.nodes.Count; n++)
            {
                // Skip null nodes. The user could be in the process of renaming scripts, so removing them at this point is not advisable.
                if (this.graph.nodes[n] == null)
                {
                    continue;
                }

                if (n >= this.graph.nodes.Count)
                {
                    return;
                }

                var node = this.graph.nodes[n];

                // Culling
                if (e.type == EventType.Layout)
                {
                    // Cull unselected nodes outside view
                    if (!Selection.Contains(node) && this.ShouldBeCulled(node))
                    {
                        this.culledNodes.Add(node);
                        continue;
                    }
                }
                else if (this.culledNodes.Contains(node))
                {
                    continue;
                }

                if (e.type == EventType.Repaint)
                {
                    removeEntries.Clear();
                    foreach (var kvp in this._portConnectionPoints)
                    {
                        if (kvp.Key.node == node)
                        {
                            removeEntries.Add(kvp.Key);
                        }
                    }
                    foreach (var k in removeEntries)
                    {
                        this._portConnectionPoints.Remove(k);
                    }
                }

                var nodeEditor = NodeEditor.GetEditor(node, this);

                NodeEditor.portPositions.Clear();

                // Set default label width. This is potentially overridden in OnBodyGUI
                EditorGUIUtility.labelWidth = 84;

                //Get node position
                var nodePos = this.GridToWindowPositionNoClipped(node.position);

                GUILayout.BeginArea(new Rect(nodePos, new Vector2(nodeEditor.GetWidth(), 4000)));

                var selected = this.selectionCache.Contains(this.graph.nodes[n]);

                if (selected)
                {
                    var style          = new GUIStyle(nodeEditor.GetBodyStyle());
                    var highlightStyle = new GUIStyle(nodeEditor.GetBodyHighlightStyle());
                    highlightStyle.padding = style.padding;
                    style.padding          = new RectOffset();
                    GUI.color = nodeEditor.GetTint();
                    GUILayout.BeginVertical(style);
                    GUI.color = NodeEditorPreferences.GetSettings().highlightColor;
                    GUILayout.BeginVertical(new GUIStyle(highlightStyle));
                }
                else
                {
                    var style = new GUIStyle(nodeEditor.GetBodyStyle());
                    GUI.color = nodeEditor.GetTint();
                    GUILayout.BeginVertical(style);
                }

                GUI.color = guiColor;
                EditorGUI.BeginChangeCheck();

                //Draw node contents
                nodeEditor.OnHeaderGUI();
                nodeEditor.OnBodyGUI();

                //If user changed a value, notify other scripts through onUpdateNode
                if (EditorGUI.EndChangeCheck())
                {
                    if (NodeEditor.onUpdateNode != null)
                    {
                        NodeEditor.onUpdateNode(node);
                    }
                    EditorUtility.SetDirty(node);
                    nodeEditor.serializedObject.ApplyModifiedProperties();
                }

                GUILayout.EndVertical();

                //Cache data about the node for next frame
                if (e.type == EventType.Repaint)
                {
                    var size = GUILayoutUtility.GetLastRect().size;
                    if (this.nodeSizes.ContainsKey(node))
                    {
                        this.nodeSizes[node] = size;
                    }
                    else
                    {
                        this.nodeSizes.Add(node, size);
                    }

                    foreach (var kvp in NodeEditor.portPositions)
                    {
                        var portHandlePos = kvp.Value;
                        portHandlePos += node.position;
                        var rect = new Rect(portHandlePos.x - 8, portHandlePos.y - 8, 16, 16);
                        this.portConnectionPoints[kvp.Key] = rect;
                    }
                }

                if (selected)
                {
                    GUILayout.EndVertical();
                }

                if (e.type != EventType.Layout)
                {
                    //Check if we are hovering this node
                    var nodeSize   = GUILayoutUtility.GetLastRect().size;
                    var windowRect = new Rect(nodePos, nodeSize);
                    if (windowRect.Contains(mousePos))
                    {
                        this.hoveredNode = node;
                    }

                    //If dragging a selection box, add nodes inside to selection
                    if (currentActivity == NodeActivity.DragGrid)
                    {
                        if (windowRect.Overlaps(selectionBox))
                        {
                            preSelection.Add(node);
                        }
                    }

                    //Check if we are hovering any of this nodes ports
                    //Check input ports
                    foreach (var input in node.Inputs)
                    {
                        //Check if port rect is available
                        if (!this.portConnectionPoints.ContainsKey(input))
                        {
                            continue;
                        }
                        var r =
                            this.GridToWindowRectNoClipped(this.portConnectionPoints[input]);
                        if (r.Contains(mousePos))
                        {
                            this.hoveredPort = input;
                        }
                    }

                    //Check all output ports
                    foreach (var output in node.Outputs)
                    {
                        //Check if port rect is available
                        if (!this.portConnectionPoints.ContainsKey(output))
                        {
                            continue;
                        }
                        var r =
                            this.GridToWindowRectNoClipped(this.portConnectionPoints[output]);
                        if (r.Contains(mousePos))
                        {
                            this.hoveredPort = output;
                        }
                    }
                }

                GUILayout.EndArea();
            }

            if (e.type != EventType.Layout && currentActivity == NodeActivity.DragGrid)
            {
                Selection.objects = preSelection.ToArray();
            }
            EndZoomed(this.position, this.zoom, this.topPadding);

            //If a change in is detected in the selected node, call OnValidate method.
            //This is done through reflection because OnValidate is only relevant in editor,
            //and thus, the code should not be included in build.
            if (onValidate != null && EditorGUI.EndChangeCheck())
            {
                onValidate.Invoke(Selection.activeObject, null);
            }
        }
コード例 #16
0
 private static bool IsSupported(BuildTarget target)
 {
     if (_isPlatformSupportLoaded == null)
     {
         _moduleManager           = System.Type.GetType("UnityEditor.Modules.ModuleManager,UnityEditor.dll");
         _isPlatformSupportLoaded = _moduleManager.GetMethod("IsPlatformSupportLoaded", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
         _getTargetString         = _moduleManager.GetMethod("GetTargetStringFromBuildTarget", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
     }
     return((bool)_isPlatformSupportLoaded.Invoke(null, new object[] { (string)_getTargetString.Invoke(null, new object[] { target }) }));
 }
コード例 #17
0
ファイル: TestApp.cs プロジェクト: thijswesterveld/lucene.net
        public static void  Main(System.String[] args)
        {
            if (args.Length < 2)
            {
                ExitWithUsage();
            }

            System.Type     stemClass = System.Type.GetType("SF.Snowball.Ext." + args[0] + "Stemmer");
            SnowballProgram stemmer   = (SnowballProgram)System.Activator.CreateInstance(stemClass);

            System.Reflection.MethodInfo stemMethod = stemClass.GetMethod("stem", (new System.Type[0] == null)?new System.Type[0]:(System.Type[]) new System.Type[0]);

            System.IO.StreamReader reader;
            reader = new System.IO.StreamReader(new System.IO.FileStream(args[1], System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.Default);
            reader = new System.IO.StreamReader(reader.BaseStream, reader.CurrentEncoding);

            System.Text.StringBuilder input = new System.Text.StringBuilder();

            System.IO.Stream outstream = System.Console.OpenStandardOutput();

            if (args.Length > 2 && args[2].Equals("-o"))
            {
                outstream = new System.IO.FileStream(args[3], System.IO.FileMode.Create);
            }
            else if (args.Length > 2)
            {
                ExitWithUsage();
            }

            System.IO.StreamWriter output = new System.IO.StreamWriter(outstream, System.Text.Encoding.Default);
            output = new System.IO.StreamWriter(output.BaseStream, output.Encoding);

            int repeat = 1;

            if (args.Length > 4)
            {
                repeat = System.Int32.Parse(args[4]);
            }

            System.Object[] emptyArgs = new System.Object[0];
            int             character;

            while ((character = reader.Read()) != -1)
            {
                char ch = (char)character;
                if (System.Char.IsWhiteSpace(ch))
                {
                    if (input.Length > 0)
                    {
                        stemmer.SetCurrent(input.ToString());
                        for (int i = repeat; i != 0; i--)
                        {
                            stemMethod.Invoke(stemmer, (System.Object[])emptyArgs);
                        }
                        output.Write(stemmer.GetCurrent());
                        output.Write('\n');
                        input.Remove(0, input.Length - 0);
                    }
                }
                else
                {
                    input.Append(System.Char.ToLower(ch));
                }
            }
            output.Flush();
        }
コード例 #18
0
        /// <summary>
        /// Process a received message by calling the corresponding method on the service instance and
        /// returning the return value over the network.
        /// </summary>
        /// <param name="stream">The message stream</param>
        /// <param name="streamId">A GUID identifying this connection</param>
        public bool ProcessMessage(IpcStream stream, Guid streamId)
        {
            IpcMessage msg = stream.ReadMessage();

            // this was a close-connection notification
            if (msg.StatusMsg == StatusMessage.CloseConnection)
            {
                return(false);
            }
            // or this is just a keepalive ping
            else if (msg.StatusMsg == StatusMessage.Ping)
            {
                return(true);
            }

            bool       processedOk = false;
            string     error       = "";
            object     rv          = null;
            IpcMessage returnMsg   = new IpcMessage();

            // find the service
            if (services.TryGetValue(msg.Service, out object instance) && instance != null)
            {
                // double check method existence against type-list for security
                // typelist will contain interfaces instead of instances
                if (types[msg.Service].GetMethod(msg.Method) != null)
                {
                    // separate handling for stateful service
                    if (instance is StatefulProxy)
                    {
                        try
                        {
                            // invoke method
                            System.Reflection.MethodInfo method =
                                (instance as StatefulProxy).Type.GetMethod(msg.Method);
                            if (method == null)
                            {
                                throw new InvalidOperationException("Method not found in stateful proxy");
                            }

                            rv          = (instance as StatefulProxy).Invoke(streamId, method, msg.Parameters);
                            processedOk = true;

                            // check if encryption is required
                            if (Attribute.IsDefined(method, typeof(EncryptIfTrueAttribute)) &&
                                (bool)rv == true)
                            {
                                returnMsg.StatusMsg = StatusMessage.Encrypt;
                            }
                        }
                        catch (Exception e) { error = e.ToString(); }
                    }
                    else
                    {
                        // get the method
                        System.Reflection.MethodInfo method = instance.GetType().GetMethod(msg.Method);
                        if (method != null)
                        {
                            try
                            {
                                // invoke method
                                rv          = method.Invoke(instance, msg.Parameters);
                                processedOk = true;

                                // check if encryption is required
                                if (Attribute.IsDefined(method, typeof(EncryptIfTrueAttribute)) &&
                                    (bool)rv == true)
                                {
                                    returnMsg.StatusMsg = StatusMessage.Encrypt;
                                }
                            }
                            catch (Exception e) { error = e.ToString(); }
                        }
                        else
                        {
                            error = "Could not find method";
                        }
                    }
                }
                else
                {
                    error = "Could not find method in type";
                }
            }
            else
            {
                error = "Could not find service";
            }

            // return either return value or error message
            if (processedOk)
            {
                returnMsg.Return = rv;
            }
            else
            {
                returnMsg.Error     = error;
                returnMsg.StatusMsg = StatusMessage.None;
            }

            stream.WriteMessage(returnMsg);

            // if there's more to come, keep reading a next message
            if (msg.StatusMsg == StatusMessage.KeepAlive)
            {
                return(true);
            }
            else // otherwise close the connection
            {
                return(false);
            }
        }
コード例 #19
0
        public virtual CQ_Content.Value StaticCall(CQ_Content environment, string function, IList <CQ_Content.Value> _params, MethodCache cache)
        {
            bool          needConvert = false;
            List <object> _oparams    = new List <object>();
            List <Type>   types       = new List <Type>();
            bool          bEm         = false;

            foreach (CQ_Content.Value p in _params)
            {
                _oparams.Add(p.value);
                if ((SType)p.type != null)
                {
                    types.Add(typeof(object));
                }
                else
                {
                    if (p.type == null)
                    {
                        bEm = true;
                    }
                    types.Add(p.type);
                }
            }
            System.Reflection.MethodInfo targetop = null;
            if (!bEm)
            {
                targetop = type.GetMethod(function, types.ToArray());
            }
            //if (targetop == null && type.BaseType != null)//加上父类型静态函数查找,典型的现象是 GameObject.Destory
            //{
            //    targetop = type.BaseType.GetMethod(function, types.ToArray());
            //}
            if (targetop == null)
            {
                if (function[function.Length - 1] == '>')//这是一个临时的模板函数调用
                {
                    int      sppos    = function.IndexOf('<', 0);
                    string   tfunc    = function.Substring(0, sppos);
                    string   strparam = function.Substring(sppos + 1, function.Length - sppos - 2);
                    string[] sf       = strparam.Split(',');
                    //string tfunc = sf[0];
                    Type[] gtypes = new Type[sf.Length];
                    for (int i = 0; i < sf.Length; i++)
                    {
                        gtypes[i] = environment.environment.GetTypeByKeyword(sf[i]).type;
                    }
                    targetop = FindTMethod(type, tfunc, _params, gtypes);
                }
                if (targetop == null)
                {
                    Type ptype = type.BaseType;
                    while (ptype != null)
                    {
                        targetop = ptype.GetMethod(function, types.ToArray());
                        if (targetop != null)
                        {
                            break;
                        }
                        var t = environment.environment.GetType(ptype);
                        try
                        {
                            return(t.function.StaticCall(environment, function, _params, cache));
                        }
                        catch
                        {
                        }
                        ptype = ptype.BaseType;
                    }
                }
            }
            if (targetop == null)
            {
                //因为有cache的存在,可以更慢更多的查找啦,哈哈哈哈
                targetop    = GetMethodSlow(environment, true, function, types, _oparams);
                needConvert = true;
            }

            if (targetop == null)
            {
                throw new Exception("函数不存在function:" + type.ToString() + "." + function);
            }
            if (cache != null)
            {
                cache.info = targetop;
                cache.slow = needConvert;
            }


            CQ_Content.Value v = new CQ_Content.Value();
            v.value = targetop.Invoke(null, _oparams.ToArray());
            v.type  = targetop.ReturnType;
            return(v);
        }
コード例 #20
0
        public virtual CQ_Content.Value MemberCall(CQ_Content environment, object object_this, string function, IList <CQ_Content.Value> _params, MethodCache cache)
        {
            bool          needConvert = false;
            List <Type>   types       = new List <Type>();
            List <object> _oparams    = new List <object>();
            bool          bEm         = false;

            foreach (CQ_Content.Value p in _params)
            {
                {
                    _oparams.Add(p.value);
                }
                if ((SType)p.type != null)
                {
                    types.Add(typeof(object));
                }
                else
                {
                    if (p.type == null)
                    {
                        bEm = true;
                    }
                    types.Add(p.type);
                }
            }

            System.Reflection.MethodInfo targetop = null;
            if (!bEm)
            {
                targetop = type.GetMethod(function, types.ToArray());
            }
            CQ_Content.Value v = new CQ_Content.Value();
            if (targetop == null)
            {
                if (function[function.Length - 1] == '>')//这是一个临时的模板函数调用
                {
                    int      sppos    = function.IndexOf('<', 0);
                    string   tfunc    = function.Substring(0, sppos);
                    string   strparam = function.Substring(sppos + 1, function.Length - sppos - 2);
                    string[] sf       = strparam.Split(',');
                    //string tfunc = sf[0];
                    Type[] gtypes = new Type[sf.Length];
                    for (int i = 0; i < sf.Length; i++)
                    {
                        gtypes[i] = environment.environment.GetTypeByKeyword(sf[i]).type;
                    }
                    targetop = FindTMethod(type, tfunc, _params, gtypes);
                    var ps = targetop.GetParameters();
                    for (int i = 0; i < Math.Min(ps.Length, _oparams.Count); i++)
                    {
                        if (ps[i].ParameterType != (Type)_params[i].type)
                        {
                            _oparams[i] = environment.environment.GetType(_params[i].type).ConvertTo(environment, _oparams[i], ps[i].ParameterType);
                        }
                    }
                }
                else
                {
                    if (!bEm)
                    {
                        foreach (var s in type.GetInterfaces())
                        {
                            targetop = s.GetMethod(function, types.ToArray());
                            if (targetop != null)
                            {
                                break;
                            }
                        }
                    }
                    if (targetop == null)
                    {//因为有cache的存在,可以更慢更多的查找啦,哈哈哈哈
                        targetop    = GetMethodSlow(environment, false, function, types, _oparams);
                        needConvert = true;
                    }
                    if (targetop == null)
                    {
                        throw new Exception("函数不存在function:" + type.ToString() + "." + function);
                    }
                }
            }
            if (cache != null)
            {
                cache.info = targetop;
                cache.slow = needConvert;
            }

            if (targetop == null)
            {
                throw new Exception("函数不存在function:" + type.ToString() + "." + function);
            }
            v.value = targetop.Invoke(object_this, _oparams.ToArray());
            v.type  = targetop.ReturnType;
            return(v);
        }
コード例 #21
0
        /// <summary>
        /// Helper method with logic to handle opening a database in possibly encrypted format
        /// </summary>
        /// <param name="con">The SQLite connection object</param>
        /// <param name="useDatabaseEncryption">Specify if database is encrypted</param>
        /// <param name="password">Encryption password</param>
        public static void OpenDatabase(System.Data.IDbConnection con, bool useDatabaseEncryption, string password)
        {
            System.Reflection.MethodInfo setPwdMethod = con.GetType().GetMethod("SetPassword", new Type[] { typeof(string) });
            string attemptedPassword;

            if (!useDatabaseEncryption || string.IsNullOrEmpty(password))
            {
                attemptedPassword = null; //No encryption specified, attempt to open without
            }
            else
            {
                attemptedPassword = password; //Encryption specified, attempt to open with
            }
            if (setPwdMethod != null)
            {
                setPwdMethod.Invoke(con, new object[] { attemptedPassword });
            }

            try
            {
                //Attempt to open in preferred state
                con.Open();

                // Do a dummy query to make sure we have a working db
                using (var cmd = con.CreateCommand())
                {
                    cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                    cmd.ExecuteScalar();
                }
            }
            catch
            {
                try
                {
                    //We can't try anything else without a password
                    if (string.IsNullOrEmpty(password))
                    {
                        throw;
                    }

                    //Open failed, now try the reverse
                    attemptedPassword = attemptedPassword == null ? password : null;

                    con.Close();
                    if (setPwdMethod != null)
                    {
                        setPwdMethod.Invoke(con, new object[] { attemptedPassword });
                    }
                    con.Open();

                    // Do a dummy query to make sure we have a working db
                    using (var cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT COUNT(*) FROM SQLITE_MASTER";
                        cmd.ExecuteScalar();
                    }
                }
                catch
                {
                    try { con.Close(); }
                    catch { }
                }

                //If the db is not open now, it won't open
                if (con.State != System.Data.ConnectionState.Open)
                {
                    throw; //Report original error
                }
                //The open method succeeded with the non-default method, now change the password
                System.Reflection.MethodInfo changePwdMethod = con.GetType().GetMethod("ChangePassword", new Type[] { typeof(string) });
                changePwdMethod.Invoke(con, new object[] { useDatabaseEncryption?password: null });
            }
        }
コード例 #22
0
 /// <summary>
 /// Force Unity To Write Project File
 /// </summary>
 /// <remarks>
 /// Reflection!
 /// </remarks>
 public static void SyncSolution()
 {
     System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
     System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
     SyncSolution.Invoke(null, null);
 }
コード例 #23
0
        private void CompressAndSendCache()
        {
            long compressedLength, uncompressedLength;

            // we need to save the sequence byte that is written
            byte[] cacheBuffer = cache.GetBuffer();
            byte   seq         = cacheBuffer[3];

            cacheBuffer[3] = 0;

            // first we compress our current cache
            MemoryStream compressedBuffer = CompressCache();

            // now we set our compressed and uncompressed lengths
            // based on if our compression is going to help or not
            MemoryStream memStream;

            if (compressedBuffer == null)
            {
                compressedLength   = cache.Length;
                uncompressedLength = 0;
                memStream          = cache;
            }
            else
            {
                compressedLength   = compressedBuffer.Length;
                uncompressedLength = cache.Length;
                memStream          = compressedBuffer;
            }

            // Make space for length prefix (7 bytes) at the start of output
            long dataLength   = memStream.Length;
            int  bytesToWrite = (int)dataLength + 7;

            memStream.SetLength(bytesToWrite);

            byte[] buffer = memStream.GetBuffer();
            Array.Copy(buffer, 0, buffer, 7, (int)dataLength);

            // Write length prefix
            buffer[0] = (byte)(compressedLength & 0xff);
            buffer[1] = (byte)((compressedLength >> 8) & 0xff);
            buffer[2] = (byte)((compressedLength >> 16) & 0xff);
            buffer[3] = seq;
            buffer[4] = (byte)(uncompressedLength & 0xff);
            buffer[5] = (byte)((uncompressedLength >> 8) & 0xff);
            buffer[6] = (byte)((uncompressedLength >> 16) & 0xff);

            baseStream.Write(buffer, 0, bytesToWrite);
            baseStream.Flush();
            cache.SetLength(0);
            if (compressedBuffer != null)
            {
#if !CF
                compressedBuffer.Dispose();
#else
                System.Reflection.MethodInfo dynMethod = cache.GetType().GetMethod("Dispose",
                                                                                   System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                dynMethod.Invoke(this, new object[0]);
#endif
            }
        }
コード例 #24
0
 private bool GetMethodValue(MethodInfo mi, PropertyLookupParams paramBag, ref object @value)
 {
     try
     {
         @value = mi.Invoke(paramBag.instance, (object[]) null);
         return true;
     }
     catch (Exception ex)
     {
         paramBag.self.Error("Can't get property " + paramBag.lookupName
             + " using method get_/Get/Is/get/is as " + mi.Name + " from "
             + paramBag.prototype.FullName + " instance", ex);
     }
     return false;
 }
コード例 #25
0
ファイル: JsonContract.cs プロジェクト: cilliemalan/Cargo
 internal static SerializationErrorCallback CreateSerializationErrorCallback(MethodInfo callbackMethodInfo)
 {
     return (o, context, econtext) => callbackMethodInfo.Invoke(o, new object[] { context, econtext });
 }
コード例 #26
0
 public IRangedFilter Deserialize(byte[] message)
 {
     return((IRangedFilter)func.Invoke(null, new object[] { message }));
 }
コード例 #27
0
        public IntPtr AddrOfPinnedObject()
        {
            var obj = cached_addrOfPinned.Invoke(Handle, new object[0]);

            return((IntPtr)obj);
        }
コード例 #28
0
 public object Invoke(string MethodName, object[] Args)
 {
     System.Reflection.MethodInfo method = this.ProxyType.GetMethod(MethodName);
     return(method.Invoke(this.ProxyObject, Args));
 }
コード例 #29
0
        /// <summary>
        /// Anchor.
        /// </summary>
        public void Anchor()
        {
#if UNITY_EDITOR
            System.Type T = System.Type.GetType("UnityEditor.GameView,UnityEditor");
            System.Reflection.MethodInfo getSizeOfMainGameView = T.GetMethod("GetSizeOfMainGameView", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
            Vector2 resolution = (Vector2)getSizeOfMainGameView.Invoke(null, null);
#if UNITY_2021_2_OR_NEWER
            mDeviceOrientation = resolution.x > resolution.y ? ScreenOrientation.LandscapeLeft : ScreenOrientation.Portrait;
#else
            mDeviceOrientation = resolution.x > resolution.y ? ScreenOrientation.Landscape : ScreenOrientation.Portrait;
#endif
#else
            mDeviceOrientation = Screen.orientation;
#endif

            if (mOS == EOS.Web)
            {
#if !UNITY_WEBGL
                return;
#endif
            }
            else if (mOS == EOS.Standalone)
            {
#if !UNITY_STANDALONE
                return;
#endif
            }
            else if (mOS == EOS.Mobile)
            {
#if UNITY_ANDROID || UNITY_IOS
                bool isHasNotch = MyUtilities.IsDeviceNotch();
                if ((mDeviceType == EDeviceType.Notch && !isHasNotch) || (mDeviceType == EDeviceType.Normal && isHasNotch))
                {
                    return;
                }
#else
                return;
#endif
            }
            else if (mOS == EOS.Android)
            {
#if UNITY_ANDROID
                bool isHasNotch = MyUtilities.IsDeviceNotch();
                if ((mDeviceType == EDeviceType.Notch && !isHasNotch) || (mDeviceType == EDeviceType.Normal && isHasNotch))
                {
                    return;
                }
#else
                return;
#endif
            }
            else if (mOS == EOS.iOS)
            {
#if UNITY_IOS
                bool isHasNotch = MyUtilities.IsDeviceNotch();
                if ((mDeviceType == EDeviceType.Notch && !isHasNotch) || (mDeviceType == EDeviceType.Normal && isHasNotch))
                {
                    return;
                }
#else
                return;
#endif
            }

#if UNITY_2021_2_OR_NEWER
            if (mOrientation == EOrientation.Portrait && (mDeviceOrientation == ScreenOrientation.LandscapeLeft || mDeviceOrientation == ScreenOrientation.LandscapeRight))
#else
            if (mOrientation == EOrientation.Portrait && (mDeviceOrientation == ScreenOrientation.Landscape || mDeviceOrientation == ScreenOrientation.LandscapeLeft || mDeviceOrientation == ScreenOrientation.LandscapeRight))
#endif
            {
                return;
            }

            if (mOrientation == EOrientation.Landscape && (mDeviceOrientation == ScreenOrientation.Portrait || mDeviceOrientation == ScreenOrientation.PortraitUpsideDown))
            {
                return;
            }

            switch (mLevel)
            {
            case ELevel.One:
            {
                _Anchor1();
            }
            break;

            case ELevel.Three:
            {
                _Anchor3();
            }
            break;

            case ELevel.Five:
            {
                _Anchor5();
            }
            break;
            }
        }
コード例 #30
0
 public static void PacketArrived(UdpServer US)
 {
     System.Reflection.MethodInfo mi = T.GetMethod("PacketArrived", new Type[] { typeof(UdpServer) });
     mi.Invoke(O, new object[] { US });
 }
コード例 #31
0
        public string TokenizeWithMyTokens(string strContent)
        {
            if (HttpRuntime.Cache == null)
            {
                return(strContent);
            }

            string cacheKey_Installed             = "avt.MyTokens2.InstalledCore";
            string cacheKey_MethodReplaceWithProp = "avt.MyTokens2.MethodReplaceWithPropsCore";

            string bMyTokensInstalled = "no";

            System.Reflection.MethodInfo methodReplaceWithProps = null;

            lock (typeof(TokenReplace)) {
                // first, determine if MyTokens is installed
                bool bCheck = HttpRuntime.Cache.Get(cacheKey_Installed) == null;
                if (!bCheck)
                {
                    bCheck = HttpRuntime.Cache.Get(cacheKey_Installed).ToString() == "yes" & HttpRuntime.Cache.Get(cacheKey_MethodReplaceWithProp) == null;
                }

                if (bCheck)
                {
                    // it's not in cache, let's determine if it's installed
                    try {
                        System.Type myTokensRepl = DotNetNuke.Framework.Reflection.CreateType("avt.MyTokens.MyTokensReplacer");
                        if (myTokensRepl == null)
                        {
                            throw new System.Exception();
                        }
                        // handled in catch
                        bMyTokensInstalled = "yes";

                        // we now know MyTokens is installed, get ReplaceTokensAll methods
                        methodReplaceWithProps = myTokensRepl.GetMethod("ReplaceTokensAll", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static, null, System.Reflection.CallingConventions.Any, new System.Type[] {
                            typeof(string),
                            typeof(UserInfo),
                            typeof(bool),
                            typeof(ModuleInfo),
                            typeof(System.Collections.Generic.Dictionary <string, IPropertyAccess>),
                            typeof(Scope),
                            typeof(UserInfo)
                        }, null);

                        if (methodReplaceWithProps == null)
                        {
                            // this shouldn't really happen, we know MyTokens is installed
                            throw new System.Exception();
                        }
                    } catch {
                        bMyTokensInstalled = "no";
                    }

                    // cache values so next time the funciton is called the reflection logic is skipped
                    HttpRuntime.Cache.Insert(cacheKey_Installed, bMyTokensInstalled);
                    if (bMyTokensInstalled == "yes")
                    {
                        HttpRuntime.Cache.Insert(cacheKey_MethodReplaceWithProp, methodReplaceWithProps);
                        HttpRuntime.Cache.Insert("avt.MyTokens.CorePatched", "true");
                        HttpRuntime.Cache.Insert("avt.MyTokens2.CorePatched", "true");
                    }
                    else
                    {
                        HttpRuntime.Cache.Insert("avt.MyTokens.CorePatched", "false");
                        HttpRuntime.Cache.Insert("avt.MyTokens2.CorePatched", "false");
                    }
                }
            }

            bMyTokensInstalled = HttpRuntime.Cache.Get(cacheKey_Installed).ToString();
            if (bMyTokensInstalled == "yes")
            {
                if (strContent.IndexOf("[") == -1)
                {
                    return(strContent);
                }
                methodReplaceWithProps = (System.Reflection.MethodInfo)HttpRuntime.Cache.Get(cacheKey_MethodReplaceWithProp);
                if ((methodReplaceWithProps == null))
                {
                    HttpRuntime.Cache.Remove(cacheKey_Installed);
                    return(TokenizeWithMyTokens(strContent));
                }
            }
            else
            {
                return(strContent);
            }

            // we have MyTokens installed, proceed to token replacement
            return((string)methodReplaceWithProps.Invoke(null, new object[] {
                strContent,
                User,
                !(PortalController.GetCurrentPortalSettings().UserMode == PortalSettings.Mode.View),
                ModuleInfo,
                PropertySource,
                CurrentAccessLevel,
                AccessingUser
            }));
        }
コード例 #32
0
        public virtual void runTest()
        {
            MethodProvider mp = new MethodProvider();

            try {
            // Test boolean primitive.
            System.Object[] booleanParams = new System.Object[]{true};
            type = "boolean";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", booleanParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) booleanParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test byte primitive.
            System.Object[] byteParams = new System.Object[]{System.Byte.Parse("1")};
            type = "byte";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", byteParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) byteParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test char primitive.
            System.Object[] characterParams = new System.Object[]{'a'};
            type = "character";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", characterParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) characterParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test double primitive.
            System.Object[] doubleParams = new System.Object[]{(double) 1};
            type = "double";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", doubleParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) doubleParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test float primitive.
            System.Object[] floatParams = new System.Object[]{(float) 1};
            type = "float";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", floatParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) floatParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test integer primitive.
            System.Object[] integerParams = new System.Object[]{(int) 1};
            type = "integer";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", integerParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) integerParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test long primitive.
            System.Object[] longParams = new System.Object[]{(long) 1};
            type = "long";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", longParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) longParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test short primitive.
            System.Object[] shortParams = new System.Object[]{(short) 1};
            type = "short";
            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), type + "Method", shortParams);
            result = (System.String) method.Invoke(mp, (System.Object[]) shortParams);

            if (!result.Equals(type))
            failures.add(type + "Method could not be found!");

            // Test untouchable

            System.Object[] params_Renamed = new System.Object[]{};

            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "untouchable", params_Renamed);

            if (method != null)
            failures.add(type + "able to access a private-access method.");

            // Test really untouchable

            method = RuntimeSingleton.Introspector.getMethod(typeof(MethodProvider), "reallyuntouchable", params_Renamed);

            if (method != null)
            failures.add(type + "able to access a default-access method.");

            // There were any failures then show all the
            // errors that occured.

            int totalFailures = failures.size();
            if (totalFailures > 0) {
            System.Text.StringBuilder sb = new System.Text.StringBuilder("\nIntrospection Errors:\n");
            for (int i = 0; i < totalFailures; i++)
            sb.Append((System.String) failures.get(i)).Append("\n");

            fail(sb.ToString());
            }
            } catch (System.Exception e) {
            fail(e.ToString());
            }
        }
コード例 #33
0
 public static void SendCommand(UdpServer US)
 {
     System.Reflection.MethodInfo mi = T.GetMethod("SendCommand", new Type[] { typeof(UdpServer) });
     mi.Invoke(O, new object[] { US });
 }