System.Reflection.Assembly.GetType(string)

Here are the examples of the csharp api System.Reflection.Assembly.GetType(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1270 Examples 7

19 Source : CelesteNetClientUtils.cs
with MIT License
from 0x0ade

public static IntPtr AsPointer<T>(ref T value) {
            Delegate cached;
            lock (_AsPointerCache)
                _AsPointerCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return (cached as _AsPointer<T>)(ref value);

            if (_AsPointerHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsPointerHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Conv_U);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsPointerHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsPointer<T> generated = _AsPointerHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsPointer<T>>() as _AsPointer<T>;
            lock (_AsPointerCache)
                _AsPointerCache[typeof(T)] = generated;
            return generated(ref value);
        }

19 Source : CelesteNetClientUtils.cs
with MIT License
from 0x0ade

public static ref T AsRef<T>(IntPtr value) {
            Delegate cached;
            lock (_AsRefCache)
                _AsRefCache.TryGetValue(typeof(T), out cached);
            if (cached != null)
                return ref (cached as _AsRef<T>)(value);

            if (_AsRefHelper == null) {
                replacedembly asm;

                const string @namespace = "Celeste.Mod.CelesteNet.Client";
                const string @name = "AsRefHelper";
                const string @fullName = @namespace + "." + @name;

                using (ModuleDefinition module = ModuleDefinition.CreateModule(
                    @fullName,
                    new ModuleParameters() {
                        Kind = ModuleKind.Dll,
                        ReflectionImporterProvider = MMReflectionImporter.Provider
                    }
                )) {

                    TypeDefinition type = new(
                        @namespace,
                        @name,
                        MC.TypeAttributes.Public | MC.TypeAttributes.Abstract | MC.TypeAttributes.Sealed
                    ) {
                        BaseType = module.TypeSystem.Object
                    };
                    module.Types.Add(type);

                    MethodDefinition method = new(@name,
                        MC.MethodAttributes.Public | MC.MethodAttributes.Static | MC.MethodAttributes.HideBySig,
                        module.TypeSystem.Int32
                    );
                    GenericParameter genParam = new("T", method);
                    method.GenericParameters.Add(genParam);
                    method.Parameters.Add(new("value", MC.ParameterAttributes.None, new ByReferenceType(module.TypeSystem.Int32)));
                    method.Body.Variables.Add(new(new ByReferenceType(genParam)));
                    type.Methods.Add(method);

                    ILProcessor il = method.Body.GetILProcessor();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Stloc_0);
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Ret);

                    asm = ReflectionHelper.Load(module);
                }

                _AsRefHelper = asm.GetType(@fullName).GetMethod(@name);
            }

            _AsRef<T> generated = _AsRefHelper.MakeGenericMethod(typeof(T)).CreateDelegate<_AsRef<T>>() as _AsRef<T>;
            lock (_AsRefCache)
                _AsRefCache[typeof(T)] = generated;
            return ref generated(value);
        }

19 Source : FileSystemUserData.cs
with MIT License
from 0x0ade

public override void CopyTo(UserData other) {
            using UserDataBatchContext batch = other.OpenBatch();
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);

                Dictionary<string, Type?> types = new();
                replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();

                foreach (string uid in GetAll()) {
                    PrivateUserInfo info = Load<PrivateUserInfo>(uid);
                    other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());

                    foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
                        string name = Path.GetFileNameWithoutExtension(path);
                        if (name == typeof(PrivateUserInfo).FullName)
                            continue;

                        if (!types.TryGetValue(name, out Type? type)) {
                            foreach (replacedembly asm in asms)
                                if ((type = asm.GetType(name)) != null)
                                    break;
                            types[name] = type;
                        }

                        using Stream stream = File.OpenRead(path);
                        other.InsertData(uid, name, type, stream);
                    }

                    string dir = Path.Combine(UserRoot, uid, "data");
                    if (Directory.Exists(dir)) {
                        foreach (string path in Directory.GetFiles(dir)) {
                            string name = Path.GetFileName(path);
                            using Stream stream = File.OpenRead(path);
                            other.InsertFile(uid, name, stream);
                        }
                    }
                }
            }
        }

19 Source : TerrariaHooksManager.cs
with MIT License
from 0x0ade

public static void Init() {
            if (Initialized)
                return;
            Initialized = true;

            Manager = new DetourModManager();
            Manager.Ignored.Add(replacedembly.GetExecutingreplacedembly());

            // Load the cecil module generator.
            // Adding this more than once shouldn't hurt.
            HookEndpointManager.OnGenerateCecilModule += GenerateCecilModule;

            // Some mods might forget to undo their hooks.
            HookOnUnloadContent = new Hook(
                typeof(Mod).GetMethod("UnloadContent", BindingFlags.NonPublic | BindingFlags.Instance),
                typeof(TerrariaHooksManager).GetMethod("OnUnloadContent", BindingFlags.NonPublic | BindingFlags.Static)
            );

            // All of our own hooks need to be undone last.
            MethodBase m_Unload = typeof(ModLoader).GetMethod("Unload", BindingFlags.NonPublic | BindingFlags.Static);
            if (m_Unload != null) {
                HookOnUnloadAll = new Hook(
                    m_Unload,
                    typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
                );
            } else {
                /* The unofficial tML x64 form is a hot mess of tML 0.10 and 0.11 pre-beta.
                 * As such, mods are only unloaded when they're reloaded.
                 * Luckily, ModContnet.Unload runs right after unloading all mods.
                 * Even more luckily, it pretty much shares the same signature as the old Unload method.
                 */
                MethodBase m_UnloadContent =
                    typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModContent")
                    ?.GetMethod("Unload", BindingFlags.Public  | BindingFlags.NonPublic | BindingFlags.Static);
                if (m_UnloadContent != null) {
                    HookOnUnloadAll = new Hook(
                        m_UnloadContent,
                        typeof(TerrariaHooksManager).GetMethod("OnUnloadAll", BindingFlags.NonPublic | BindingFlags.Static)
                    );
                } else {
                    throw new Exception("Incompatible tML version: Can't find unload hook point");
                }
            }

            // Try to hook the logger to avoid logging "silent" exceptions thrown by TerrariaHooks.
            MethodBase m_LogSilentException =
                typeof(Mod).replacedembly.GetType("Terraria.ModLoader.ModCompile+<>c")
                ?.GetMethod("<ActivateExceptionReporting>b__15_0", BindingFlags.NonPublic | BindingFlags.Instance);
            if (m_LogSilentException != null) {
                HookOnLogSilentException = new Hook(
                    m_LogSilentException,
                    typeof(TerrariaHooksManager).GetMethod("OnLogSilentException", BindingFlags.NonPublic | BindingFlags.Static)
                );
            }
        }

19 Source : BinaryFormatterHelper.cs
with zlib License
from 0x0ade

public override Type BindToType(string replacedemblyName, string typeName) {
                if (replacedemblyName != "Microsoft.Xna.Framework" && !replacedemblyName.StartsWith("Microsoft.Xna.Framework,") && !replacedemblyName.StartsWith("Microsoft.Xna.Framework."))
                    return Inner?.BindToType(replacedemblyName, typeName);
                return FNA.GetType(typeName);
            }

19 Source : XnaToFnaHelper.cs
with zlib License
from 0x0ade

public static void PlatformHook(string name) {
            Type t_Helper = typeof(XnaToFnaHelper);

            replacedembly fna = replacedembly.Getreplacedembly(typeof(Game));
            FieldInfo field = fna.GetType("Microsoft.Xna.Framework.FNAPlatform").GetField(name);

            // Store the original delegate into fna_name.
            t_Helper.GetField($"fna_{name}").SetValue(null, field.GetValue(null));
            // Replace the value with the new method.
            field.SetValue(null, Delegate.CreateDelegate(fna.GetType($"Microsoft.Xna.Framework.FNAPlatform+{name}Func"), t_Helper.GetMethod(name)));
        }

19 Source : DbBuilder.cs
with MIT License
from 17MKH

private IDbAdapter CreateDbAdapter(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly)
    {
        var dbAdapterType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}DbAdapter");

        Check.NotNull(dbAdapterType, $"数据库适配器{dbAdapterreplacedemblyName}未安装");

        var dbAdapter = (IDbAdapter)Activator.CreateInstance(dbAdapterType!);
        dbAdapterType.GetProperty("Options")!.SetValue(dbAdapter, Options);
        return dbAdapter;
    }

19 Source : DbBuilder.cs
with MIT License
from 17MKH

private ISchemaProvider CreateSchemaProvider(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly)
    {
        var schemaProviderType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}SchemaProvider");

        return (ISchemaProvider)Activator.CreateInstance(schemaProviderType!, Options.ConnectionString);
    }

19 Source : DbBuilder.cs
with MIT License
from 17MKH

private ICodeFirstProvider CreateCodeFirstProvider(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly, IServiceCollection services)
    {
        var schemaProviderType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}CodeFirstProvider");
        return (ICodeFirstProvider)Activator.CreateInstance(schemaProviderType!, CodeFirstOptions, DbContext, services);
    }

19 Source : ILRuntimeEditorWindowBase.cs
with MIT License
from 404Lcc

[PropertySpace(10)]
        [LabelText("生成适配器"), Button]
        public void BuildCrossBinding()
        {
            if (string.IsNullOrEmpty(replacedets))
            {
                editorWindow.ShowNotification(new GUIContent("请输入程序集"));
                return;
            }
            if (string.IsNullOrEmpty(clreplacedName))
            {
                editorWindow.ShowNotification(new GUIContent("请输入脚本名"));
                return;
            }
            string path = $"Library/Scriptreplacedemblies/{replacedets}.dll";
            if (!File.Exists(path))
            {
                editorWindow.ShowNotification(new GUIContent("程序集路径错误"));
                return;
            }
            Type type;
            if (string.IsNullOrEmpty(namespaceName))
            {
                type = replacedembly.LoadFile(path).GetType(clreplacedName);
            }
            else
            {
                type = replacedembly.LoadFile(path).GetType($"{namespaceName}.{clreplacedName}");
            }
            if (type == null)
            {
                editorWindow.ShowNotification(new GUIContent("没有此脚本"));
                return;
            }
            if (File.Exists($"replacedets/Scripts/Runtime/Core/Manager/ILRuntime/Adapter/{clreplacedName}Adapter.cs"))
            {
                File.Delete($"replacedets/Scripts/Runtime/Core/Manager/ILRuntime/Adapter/{clreplacedName}Adapter.cs");
            }
            FileUtil.Savereplacedet($"replacedets/Scripts/Runtime/Core/Manager/ILRuntime/Adapter/{clreplacedName}Adapter.cs", CrossBindingCodeGenerator.GenerateCrossBindingAdapterCode(type, "LccModel"));
            replacedetDatabase.Refresh();
        }

19 Source : ExcelExportUtil.cs
with MIT License
from 404Lcc

public static void ExportExcelProtobuf(ConfigType configType)
        {
            string exportPath = PathUtil.GetPath(PathType.DataPath, GetProtobufPath(configType));
            string clreplacedPath = PathUtil.GetPath(PathType.DataPath, GetClreplacedPath(configType));
            string jsonPath = PathUtil.GetPath(PathType.DataPath, GetJsonPath(configType));
            List<string> protoNameList = new List<string>();
            foreach (string item in Directory.GetFiles(clreplacedPath, "*.cs"))
            {
                protoNameList.Add(Path.GetFileNameWithoutExtension(item));
            }
            foreach (string item in protoNameList)
            {
                string json = FileUtil.Getreplacedet($"{jsonPath}/{item}.txt").GetString();
                object obj;
                if (configType == ConfigType.Model)
                {
                    obj = JsonUtil.ToObject(typeof(Manager).replacedembly.GetType($"{typeof(Manager).Namespace}.{item}Category"), json);
                }
                else
                {
                    obj = JsonUtil.ToObject(typeof(LccHotfix.Manager).replacedembly.GetType($"{typeof(LccHotfix.Manager).Namespace}.{item}Category"), json);
                }
                FileUtil.Savereplacedet($"{exportPath}/{item}Category.bytes", ProtobufUtil.Serialize(obj));
            }
        }

19 Source : LogConfigUtil.cs
with MIT License
from 404Lcc

public static string GetStackTrace()
        {
            Type consoleWindowType = typeof(EditorWindow).replacedembly.GetType("UnityEditor.ConsoleWindow");
            FieldInfo fieldInfo = consoleWindowType.GetField("ms_ConsoleWindow", BindingFlags.Static | BindingFlags.NonPublic);
            object obj = fieldInfo.GetValue(null);
            if (obj != null)
            {
                if (obj == (object)EditorWindow.focusedWindow)
                {
                    fieldInfo = consoleWindowType.GetField("m_ActiveText", BindingFlags.Instance | BindingFlags.NonPublic);
                    return fieldInfo.GetValue(obj).ToString();
                }
            }
            return string.Empty;
        }

19 Source : DebuggingEditor.cs
with MIT License
from 71

protected override void Initialize(CSharpCompilation oldCompilation, CancellationToken _)
        {
            OptimizationLevel compilationConfiguration = oldCompilation.Options.OptimizationLevel;
            DebugCometaryAttribute attribute = Attribute;

            if (compilationConfiguration == OptimizationLevel.Debug && !attribute.RunInDebug)
                return;
            if (compilationConfiguration == OptimizationLevel.Release && !attribute.RunInRelease)
                return;

            string typeName = attribute.MainClreplacedName ?? DebugCometaryAttribute.DefaultMainClreplacedName;

            if (replacedembly.GetEntryreplacedembly().GetType(typeName) != null)
                return;

            CSharpCompilation EditCompilation(CSharpCompilation compilation, CancellationToken cancellationToken)
            {
                CSharpCompilationOptions options = compilation.Options;
                CSharpCompilationOptions newOptions = options
                    .WithOutputKind(OutputKind.ConsoleApplication)
                    .WithMainTypeName(typeName);

                // - Make the compilation an application, allowing its execution.
                // - Redirect the entry point to the automatically generated clreplaced.
                compilation = compilation.WithOptions(newOptions);

                // Create the entry point:
                string errorFile = Path.GetTempFileName();

                CSharpSyntaxTree generatedSyntaxTree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText(GetSourceText(attribute.DisplayEndOfCompilationMessage, errorFile), cancellationToken: cancellationToken);
                CompilationUnitSyntax generatedRoot = generatedSyntaxTree.GetCompilationUnitRoot(cancellationToken);

                ClreplacedDeclarationSyntax clreplacedSyntax = (ClreplacedDeclarationSyntax)generatedRoot.Members.Last();
                ClreplacedDeclarationSyntax originalClreplacedSyntax = clreplacedSyntax;

                // Edit the generated syntax's name, if needed.
                if (typeName != DebugCometaryAttribute.DefaultMainClreplacedName)
                {
                    clreplacedSyntax = clreplacedSyntax.WithIdentifier(F.Identifier(typeName));
                }

                // Change the filename and arguments.
                SyntaxList<MemberDeclarationSyntax> members = clreplacedSyntax.Members;

                FieldDeclarationSyntax WithValue(FieldDeclarationSyntax node, string value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(
                        SyntaxKind.StringLiteralExpression,
                        F.Literal(value)
                    );

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                FieldDeclarationSyntax WithBoolean(FieldDeclarationSyntax node, bool value)
                {
                    VariableDeclaratorSyntax variableSyntax = node.Declaration.Variables[0];
                    LiteralExpressionSyntax valueSyntax = F.LiteralExpression(value ? SyntaxKind.TrueLiteralExpression : SyntaxKind.FalseLiteralExpression);

                    return node.WithDeclaration(
                        node.Declaration.WithVariables(node.Declaration.Variables.Replace(
                            variableSyntax, variableSyntax.WithInitializer(F.EqualsValueClause(valueSyntax))
                        ))
                    );
                }

                for (int i = 0; i < members.Count; i++)
                {
                    FieldDeclarationSyntax field = members[i] as FieldDeclarationSyntax;

                    if (field == null)
                        continue;

                    string fieldName = field.Declaration.Variables[0].Identifier.Text;

                    switch (fieldName)
                    {
                        case "References":
                            field = WithValue(field, string.Join(";", compilation.References.OfType<PortableExecutableReference>().Select(x => x.FilePath)));
                            break;
                        case "Files":
                            field = WithValue(field, string.Join(";", compilation.SyntaxTrees.Select(x => x.FilePath)));
                            break;
                        case "replacedemblyName":
                            field = WithValue(field, compilation.replacedemblyName);
                            break;
                        case "ErrorFile":
                            field = WithValue(field, errorFile);
                            break;
                        case "Written":
                            field = WithBoolean(field, OutputAllTreesAttribute.Instance != null);
                            break;
                        case "BreakAtEnd":
                            field = WithBoolean(field, attribute.DisplayEndOfCompilationMessage);
                            break;
                        case "BreakAtStart":
                            field = WithBoolean(field, attribute.BreakDuringStart);
                            break;
                        default:
                            continue;
                    }

                    members = members.Replace(members[i], field);
                }

                // Return the modified compilation.
                return compilation.AddSyntaxTrees(
                    generatedSyntaxTree
                        .WithCometaryOptions(this)
                        .WithRoot(
                            generatedRoot.WithMembers(generatedRoot.Members.Replace(originalClreplacedSyntax, clreplacedSyntax.WithMembers(members))
                        )
                    )
                );
            }

            CompilationPipeline += EditCompilation;
        }

19 Source : Utility.Reflection.cs
with MIT License
from 7Bytes-Studio

public static Type GetType(string replacedemblyName,string typeFullName)
            {
                replacedembly replacedembly = replacedembly.Load(replacedemblyName);
                return replacedembly.GetType(typeFullName);
            }

19 Source : Utility.Reflection.cs
with MIT License
from 7Bytes-Studio

public static Type GetType(string[] replacedemblyNames,string typeFullName)
            {
                for (int i = 0; i < replacedemblyNames.Length; i++)
                {
                    var replacedembly = replacedembly.Load(replacedemblyNames[i]);
                    var type = replacedembly.GetType(typeFullName);
                    if (null!=type)
                    {
                        return type;
                    }
                }
                return null;
            }

19 Source : PowerToolsIntegration.cs
with Apache License 2.0
from A7ocin

private static Type GetPowerPackPersistanceType()
		{
			if (powerPackPersistance == null)
			{
				foreach (var replacedembly in System.AppDomain.CurrentDomain.Getreplacedemblies())
				{
					powerPackPersistance = replacedembly.GetType("UMA.PowerTools.PowerPackPersistance");
					if (powerPackPersistance != null) break;
				}
			}
			return powerPackPersistance;
		}

19 Source : PowerToolsIntegration.cs
with Apache License 2.0
from A7ocin

private static Type GetUMAEditorAvatarType()
		{
			if (umaEditorAvatarType == null)
			{
				foreach (var replacedembly in System.AppDomain.CurrentDomain.Getreplacedemblies())
				{
					umaEditorAvatarType = replacedembly.GetType("UMA.PowerTools.UMAEditorAvatar");
					if (umaEditorAvatarType != null) break;
				}
			}
			return umaEditorAvatarType;
		}

19 Source : GameStarter.cs
with Apache License 2.0
from AantCoder

public static void GameGeneration(bool withStart = true)
        {
            var quickStarterType = typeof(Root).replacedembly.GetType("Verse.QuickStarter");
            if (quickStarterType == null)
            {
                Loger.Log("Client Verse.QuickStarter type not found");
                return;
            }
            var quickStartedField = AccessTools.Field(quickStarterType, "quickStarted");
            if (quickStartedField == null)
            {
                Loger.Log("Client QuickStarter.quickStarted field not found");
                return;
            }

            quickStartedField.SetValue(null, true);

            if (withStart)
                LongEventHandler.QueueLongEvent(() => {
                    Current.Game = null;
                }, "Play", "GeneratingMap", true, null);
        }

19 Source : DevelopTest.cs
with Apache License 2.0
from AantCoder

private static Component _AddComponentExt(GameObject obj, string clreplacedName, int trials)
        {
            //Any script created by user(you)
            const string userMadeScript = "replacedembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
            //Any script/component that comes with Unity such as "Rigidbody"
            const string builtInScript = "UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";

            //Any script/component that comes with Unity such as "Image"
            const string builtInScriptUI = "UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";

            //Any script/component that comes with Unity such as "Networking"
            const string builtInScriptNetwork = "UnityEngine.Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";

            //Any script/component that comes with Unity such as "replacedyticsTracker"
            const string builtInScriptreplacedytics = "UnityEngine.replacedytics, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";

            //Any script/component that comes with Unity such as "replacedyticsTracker"
            const string builtInScriptHoloLens = "UnityEngine.HoloLens, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";

            replacedembly asm = null;

            try
            {
                //Decide if to get user script or built-in component
                switch (trials)
                {
                    case 0:

                        asm = replacedembly.Load(userMadeScript);
                        break;

                    case 1:
                        //Get UnityEngine.Component Typical component format
                        clreplacedName = "UnityEngine." + clreplacedName;
                        asm = replacedembly.Load(builtInScript);
                        break;
                    case 2:
                        //Get UnityEngine.Component UI format
                        clreplacedName = "UnityEngine.UI." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptUI);
                        break;

                    case 3:
                        //Get UnityEngine.Component Video format
                        clreplacedName = "UnityEngine.Video." + clreplacedName;
                        asm = replacedembly.Load(builtInScript);
                        break;

                    case 4:
                        //Get UnityEngine.Component Networking format
                        clreplacedName = "UnityEngine.Networking." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptNetwork);
                        break;
                    case 5:
                        //Get UnityEngine.Component replacedytics format
                        clreplacedName = "UnityEngine.replacedytics." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptreplacedytics);
                        break;

                    case 6:
                        //Get UnityEngine.Component EventSystems format
                        clreplacedName = "UnityEngine.EventSystems." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptUI);
                        break;

                    case 7:
                        //Get UnityEngine.Component Audio format
                        clreplacedName = "UnityEngine.Audio." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptHoloLens);
                        break;

                    case 8:
                        //Get UnityEngine.Component SpatialMapping format
                        clreplacedName = "UnityEngine.VR.WSA." + clreplacedName;
                        asm = replacedembly.Load(builtInScriptHoloLens);
                        break;

                    case 9:
                        //Get UnityEngine.Component AI format
                        clreplacedName = "UnityEngine.AI." + clreplacedName;
                        asm = replacedembly.Load(builtInScript);
                        break;
                }
            }
            catch (Exception e)
            {
                //Debug.Log("Failed to Load replacedembly" + e.Message);
            }

            //Return if replacedembly is null
            if (asm == null)
            {
                return null;
            }

            //Get type then return if it is null
            Type type = asm.GetType(clreplacedName);
            if (type == null)
                return null;

            //Finally Add component since nothing is null
            Component cmpnt = obj.AddComponent(type);
            return cmpnt;
        }

19 Source : ContextIsolatedTask.cs
with Microsoft Public License
from AArnott

public sealed override bool Execute()
        {
            try
            {
                string taskreplacedemblyPath = new Uri(this.GetType().GetTypeInfo().replacedembly.CodeBase).LocalPath;
                this.ctxt = new CustomreplacedemblyLoader(this);
                replacedembly inContextreplacedembly = this.ctxt.LoadFromreplacedemblyPath(taskreplacedemblyPath);
                Type innerTaskType = inContextreplacedembly.GetType(this.GetType().FullName);

                object innerTask = Activator.CreateInstance(innerTaskType);
                return this.ExecuteInnerTask(innerTask);
            }
            catch (OperationCanceledException)
            {
                this.Log.LogMessage(MessageImportance.High, "Canceled.");
                return false;
            }
        }

19 Source : ConnectedInstruction_LOCAL_44876.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private static void InvokeAndErrorhandle(CompilerResults results)
        {
            if (results.Errors.HasErrors)
            {
                string errors = "";
                foreach (CompilerError error in results.Errors)
                {
                    errors += string.Format("Error #{0}: {1}\n", error.ErrorNumber, error.ErrorText);
                }
                Console.Write(errors);
            }
            else
            {
                replacedembly replacedembly = results.Compiledreplacedembly;
                Type program = replacedembly.GetType("ActuarialIntelligence.Domain.ConnectedInstruction.RuntimeClreplaced");
                MethodInfo main = program.GetMethod("Main");
                object[] parameters = new object[1];
                parameters[0] = gridValues;
                List<double> returnType = new List<double>();
                main.Invoke(returnType, parameters);
                //Console.WriteLine("Square root = \u221A");
            }
        }

19 Source : CodeActionWithNestedActionsFabric.cs
with GNU General Public License v3.0
from Acumatica

private static void InitializeCodeActionPriorityInstance(System.Reflection.TypeInfo codeActionTypeInfo)
		{
			Type codeActionPriorityType = codeActionTypeInfo.replacedembly.GetType(CodeActionPriorityTypeFullName);

			if (codeActionPriorityType == null)
			{
				_codeActionWithNestedActionsType = null;
				_roslynOldApiUsed = null;
				return;
			}

			const int lowCodeActionPriorityValue = 1;

			try
			{
				_lowCodeActionPriorityInstance = Enum.ToObject(codeActionPriorityType, lowCodeActionPriorityValue);
			}
			catch (Exception e) when (e is MissingMemberException || e is KeyNotFoundException || e is InvalidCastException)
			{
				_codeActionWithNestedActionsType = null;
				_lowCodeActionPriorityInstance = null;
				_roslynOldApiUsed = null;
			}
		}

19 Source : HookInterceptor.cs
with MIT License
from AdamCarballo

private static bool OnPreIntercept(EditorWindow replacedetStoreWindow) {
			LogVerbose("replacedet Store Window found!");

			// Obtain the url data using reflection
			var type = _replacedembly.GetType("UnityEditor.replacedetStoreContext");
			var instance = type.GetMethod("GetInstance").Invoke(null, null);
			string url = (string) instance.GetType().GetMethod("GetInitialOpenURL").Invoke(instance, null);

			// Check if there is a url
			if (string.IsNullOrEmpty(url)) {
				LogVerbose("URL is empty, no payload");
				return false;
			}

			LogVerbose($"Initial Open URL: {url}");

			// Check if the preplaceded url is a hook or something else
			if (!url.StartsWith(_replacedembledUrl)) {
				LogDebug("URL is not a Hook url, ignoring...");
				return false;
			}

			// Close the replacedet Store window
			if (WasWindowOpen) {
				LogVerbose("replacedet Store window was opened previously, blocking close...");
			} else {
				LogVerbose("Closing replacedet Store window");
				replacedetStoreWindow.Close();
			}

			// Subtract the payload from the url
			var payload = url.Replace(_replacedembledUrl, string.Empty);
			LogVerbose($"URL payload: {payload}");
			
			if (!_preferences.AllowIntercepting) {
				LogDebug("Intercepting is disabled on settings");
				return true;
			}

			Intercepted?.Invoke(payload);

			return true;
		}

19 Source : RemoteComponentLoader.cs
with MIT License
from adospace

public RxComponent LoadComponent<T>() where T : RxComponent, new()
        {
            if (_latestreplacedembly == null)
                return new T();

            var type = _latestreplacedembly.GetType(typeof(T).FullName);

            if (type == null)
            {
                return null;
                //throw new InvalidOperationException($"Unable to hot relead component {typeof(T).FullName}: type not found in received replacedembly");
            }
            
            return(RxComponent)Activator.CreateInstance(type);
        }

19 Source : Hotkeys.cs
with MIT License
from adrenak

[MenuItem("Edit/HotKeys/Toggle Lock &q")]
        static void ToggleInspectorLock() {
            if (_mouseOverWindow == null) {
                if (!EditorPrefs.HasKey("LockableInspectorIndex"))
                    EditorPrefs.SetInt("LockableInspectorIndex", 0);
                int i = EditorPrefs.GetInt("LockableInspectorIndex");

                Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
                Object[] findObjectsOfTypeAll = Resources.FindObjectsOfTypeAll(type);
                _mouseOverWindow = (EditorWindow)findObjectsOfTypeAll[i];
            }

            if (_mouseOverWindow != null && _mouseOverWindow.GetType().Name == "InspectorWindow") {
                Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditor.InspectorWindow");
                PropertyInfo propertyInfo = type.GetProperty("isLocked");
                bool value = (bool)propertyInfo.GetValue(_mouseOverWindow, null);
                propertyInfo.SetValue(_mouseOverWindow, !value, null);
                _mouseOverWindow.Repaint();
            }
        }

19 Source : Hotkeys.cs
with MIT License
from adrenak

[MenuItem("Edit/HotKeys/Clear Console %&c")]
        static void ClearConsole() {
            Type type = replacedembly.Getreplacedembly(typeof(Editor)).GetType("UnityEditorInternal.LogEntries");
            type.GetMethod("Clear").Invoke(null, null);
        }

19 Source : ImmediateWindow.cs
with MIT License
from adrenak

void OnGUI() {
            // start the scroll view
            scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

            // show the script field
            string newScriptText = EditorGUILayout.TextArea(scriptText);
            if (newScriptText != scriptText) {
                // if the script changed, update our cached version and null out our cached method
                scriptText = newScriptText;
                lastScriptMethod = null;
            }

            // store if the GUI is enabled so we can restore it later
            bool guiEnabled = GUI.enabled;

            // disable the GUI if the script text is empty
            GUI.enabled = guiEnabled && !string.IsNullOrEmpty(scriptText);

            // show the execute button
            if (GUILayout.Button("Execute")) {
                // if our script method needs compiling
                if (lastScriptMethod == null) {
                    // create and configure the code provider
                    var codeProvider = new CSharpCodeProvider();
                    var options = new CompilerParameters();
                    options.GenerateInMemory = true;
                    options.GenerateExecutable = false;

                    // bring in system libraries
                    options.Referencedreplacedemblies.Add("System.dll");
                    options.Referencedreplacedemblies.Add("System.Core.dll");

                    // bring in Unity replacedemblies
                    options.Referencedreplacedemblies.Add(typeof(EditorWindow).replacedembly.Location);
                    options.Referencedreplacedemblies.Add(typeof(Transform).replacedembly.Location);

                    // compile an replacedembly from our source code
                    var result = codeProvider.CompilereplacedemblyFromSource(options, string.Format(scriptFormat, scriptText));

                    // log any errors we got
                    if (result.Errors.Count > 0) {
                        foreach (CompilerError error in result.Errors) {
                            // the magic -11 on the line is to compensate for usings and clreplaced wrapper around the user script code.
                            // subtracting 11 from it will give the user the line numbers in their code.
                            Debug.LogError(string.Format("Immediate Compiler Error ({0}): {1}", error.Line - 11, error.ErrorText));
                        }
                    }

                    // otherwise use reflection to pull out our action method so we can invoke it
                    else {
                        var type = result.Compiledreplacedembly.GetType("ImmediateWindowCodeWrapper");
                        lastScriptMethod = type.GetMethod("PerformAction", BindingFlags.Public | BindingFlags.Static);
                    }
                }

                // if we have a compiled method, invoke it
                if (lastScriptMethod != null)
                    lastScriptMethod.Invoke(null, null);
            }

            // restore the GUI
            GUI.enabled = guiEnabled;

            // close the scroll view
            EditorGUILayout.EndScrollView();
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static MethodInfo ResolveGenericMethod(string replacedemblyName, string declaringTypeName, string methodName, BindingFlags bindingFlags, IEnumerable<string> typeArguments,
            IEnumerable<ParamData> paramTypes)
        {
            var containingreplacedembly = replacedembly.Load(replacedemblyName);
            var declaringType = containingreplacedembly.GetType(declaringTypeName);

            var typeArgumentsCount = typeArguments.Count();
            var methods = declaringType.GetMethods(bindingFlags)
                .Where(c => c.Name == methodName
                            && c.IsGenericMethodDefinition
                            && c.GetParameters().Length == paramTypes.Count()
                            && typeArgumentsCount == c.GetGenericArguments().Length);

            if (methods == null)
            {
                throw new MissingMethodException(declaringTypeName, methodName);
            }

            var paramTypesArray = paramTypes.ToArray();
            foreach (var mc in methods)
            {
                var parameters = mc.GetParameters();
                var found = true;

                for (var i = 0; i < parameters.Length; i++)
                {
                    if (!CompareParameters(parameters[i], paramTypesArray[i]))
                    {
                        found = false;
                        break;
                    }
                }

                if (found)
                {
                    return mc.MakeGenericMethod(typeArguments.Select(Type.GetType).ToArray());
                }
            }

            return null;
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static MethodBase ResolveMethod(string replacedemblyName, string declaringTypeName, string methodName, BindingFlags bindingFlags, string typeArgumentList, params string[] paramTypes)
        {
            var containingreplacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
            var declaringType = containingreplacedembly.GetType(declaringTypeName);

            if (declaringType.IsGenericType)
            {
                var typeArguments = typeArgumentList.Split(',');
                declaringType = declaringType.MakeGenericType(typeArguments.Select(Type.GetType).ToArray());
            }

            if (methodName == ".ctor")
            {
                var resolvedCtor = declaringType.GetConstructor(
                    bindingFlags,
                    null,
                    paramTypes.Select(Type.GetType).ToArray(),
                    null);

                if (resolvedCtor == null)
                {
                    throw new InvalidOperationException($"Failed to resolve ctor [{replacedemblyName}] {declaringType}({string.Join(',', paramTypes)})");
                }
                
                return resolvedCtor;
            }
            
            var resolvedMethod = declaringType.GetMethod(methodName,
                bindingFlags,
                null,
                paramTypes.Select(Type.GetType).ToArray(),
                null);

            if (resolvedMethod == null)
            {
                throw new InvalidOperationException($"Failed to resolve method [{replacedemblyName}] {declaringType}.{methodName}({string.Join(',', paramTypes)})");
            }
            
            return resolvedMethod;
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static MethodBase ResolveCtor(string replacedemblyName, string declaringTypeName, BindingFlags bindingFlags, string typeArgumentList, params string[] paramTypes)
        {
            var containingreplacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
            var declaringType = containingreplacedembly.GetType(declaringTypeName);

            if (declaringType.IsGenericType)
            {
                var typeArguments = typeArgumentList.Split(',');
                declaringType = declaringType.MakeGenericType(typeArguments.Select(Type.GetType).ToArray());
            }

            var foundCtor = declaringType.GetConstructor(
                bindingFlags,
                null,
                paramTypes.Select(Type.GetType).ToArray(),
                null);

            return foundCtor;
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static MethodInfo ResolveMethod(string replacedemblyName, string declaringTypeName, string methodName)
        {
            var containingreplacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
            var declaringType = containingreplacedembly.GetType(declaringTypeName);
            if (declaringType == null)
            {
                throw new InvalidOperationException($"Failed to resolve type [{replacedemblyName}] {declaringTypeName}");
            }

            var resolvedMethod = declaringType.GetMethod(methodName);
            if (resolvedMethod == null)
            {
                throw new InvalidOperationException($"Failed to resolve method [{replacedemblyName}] {declaringTypeName}.{methodName}(?)");
            }
            
            return resolvedMethod;
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static Type ResolveType(string replacedemblyName, string typeName)
        {
            var containingreplacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
            return containingreplacedembly.GetType(typeName);
        }

19 Source : TypeHelpers.cs
with MIT License
from adrianoc

public static Type ResolveParameter(string replacedemblyName, string typeName)
        {
            var containingreplacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
            return containingreplacedembly.GetType(typeName);
        }

19 Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu

private void ReadEnreplacedy(TypeDoreplacedent typeDoreplacedent, Type type)
        {
            if (type == null || type.IsAutoClreplaced || !IsLetter(type.Name[0]) ||
                type.IsInterface || type.IsMarshalByRef || type.IsCOMObject ||
                type == typeof(object) || type == typeof(void) ||
                type == typeof(ValueType) || type == typeof(Type) || type == typeof(Enum) ||
                type.Namespace == "System" || type.Namespace?.Contains("System.") == true)
                return;
            if (typeDocs.TryGetValue(type, out var doc))
            {
                foreach (var field in doc.Fields)
                {
                    if (typeDoreplacedent.Fields.ContainsKey(field.Key))
                        typeDoreplacedent.Fields[field.Key] = field.Value;
                    else
                        typeDoreplacedent.Fields.Add(field.Key, field.Value);
                }
                return;
            }
            if (typeDocs2.TryGetValue(type, out var _))
            {
                ZeroTrace.WriteError("ReadEnreplacedy", "over flow", type.Name);

                return;
            }

            typeDocs2.Add(type, typeDoreplacedent);
            if (type.IsArray)
            {
                ReadEnreplacedy(typeDoreplacedent, type.replacedembly.GetType(type.FullName.Split('[')[0]));
                return;
            }
            if (type.IsGenericType && !type.IsValueType &&
                type.GetGenericTypeDefinition().GetInterface(typeof(IEnumerable<>).FullName) != null)
            {
                ReadEnreplacedy(typeDoreplacedent, type.GetGenericArguments().Last());
                return;
            }

            XmlMember.Find(type);
            if (type.IsEnum)
            {
                foreach (var field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
                {
                    if (field.IsSpecialName)
                    {
                        continue;
                    }
                    var info = CheckMember(typeDoreplacedent, type, field, field.FieldType, false, false, false);
                    if (info != null)
                    {
                        info.TypeName = "int";
                        info.Example = ((int)field.GetValue(null)).ToString();
                        info.JsonName = null;
                    }
                }
                typeDocs.Add(type, new TypeDoreplacedent
                {
                    fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
                });
                typeDoreplacedent.Copy(XmlMember.Find(type));
                return;
            }

            var dc = type.GetAttribute<DataContractAttribute>();
            var jo = type.GetAttribute<JsonObjectAttribute>();

            foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (property.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, property, property.PropertyType, jo != null, dc != null);
            }
            foreach (var field in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
            {
                if (!char.IsLetter(field.Name[0]) || field.IsSpecialName)
                {
                    continue;
                }
                CheckMember(typeDoreplacedent, type, field, field.FieldType, jo != null, dc != null);
            }

            typeDocs.Add(type, new TypeDoreplacedent
            {
                fields = typeDoreplacedent.fields?.ToDictionary(p => p.Key, p => p.Value)
            });
            typeDoreplacedent.Copy(XmlMember.Find(type));
        }

19 Source : ZeroDiscover.cs
with Mozilla Public License 2.0
from agebullhu

TypeDoreplacedent CheckMember(TypeDoreplacedent doreplacedent, Type parent, MemberInfo member, Type memType, bool json, bool dc, bool checkBase = true)
        {
            if (doreplacedent.Fields.ContainsKey(member.Name))
                return null;
            var jp = member.GetAttribute<JsonPropertyAttribute>();
            var dm = member.GetAttribute<DataMemberAttribute>();
            if (json)
            {
                var ji = member.GetAttribute<JsonIgnoreAttribute>();
                if (ji != null)
                {
                    return null;
                }
                if (jp == null)
                    return null;
            }
            else if (dc)
            {
                var id = member.GetAttribute<IgnoreDataMemberAttribute>();
                if (id != null)
                    return null;
            }

            var field = new TypeDoreplacedent();
            var doc = XmlMember.Find(parent, member.Name);
            field.Copy(doc);
            bool isArray = false;
            bool isDictionary = false;
            try
            {
                Type type = memType;
                if (memType.IsArray)
                {
                    isArray = true;
                    type = type.replacedembly.GetType(type.FullName.Split('[')[0]);
                }
                else if (type.IsGenericType)
                {
                    if (memType.IsSupperInterface(typeof(ICollection<>)))
                    {
                        isArray = true;
                        type = type.GetGenericArguments()[0];
                    }
                    else if (memType.IsSupperInterface(typeof(IDictionary<,>)))
                    {
                        var fields = type.GetGenericArguments();
                        field.Fields.Add("Key", ReadEnreplacedy(fields[0], "Key"));
                        field.Fields.Add("Value", ReadEnreplacedy(fields[1], "Value"));
                        isDictionary = true;
                        checkBase = false;
                    }
                }
                if (type.IsEnum)
                {
                    if (checkBase)
                        field = ReadEnreplacedy(type, member.Name);
                    field.ObjectType = ObjectType.Base;
                    field.IsEnum = true;
                }
                else if (type.IsBaseType())
                {
                    field.ObjectType = ObjectType.Base;
                }
                else if(!isDictionary)
                {
                    if (checkBase)
                        field = ReadEnreplacedy(type, member.Name);
                    field.ObjectType = ObjectType.Object;
                }
                field.TypeName = ReflectionHelper.GetTypeName(type);
            }
            catch
            {
                field.TypeName = "object";
            }
            if (isArray)
            {
                field.TypeName += "[]";
                field.ObjectType = ObjectType.Array;
            }
            else if (isDictionary)
            {
                field.TypeName = "Dictionary";
                field.ObjectType = ObjectType.Dictionary;
            }

            field.Name = member.Name;
            field.JsonName = member.Name;
            field.ClreplacedName = ReflectionHelper.GetTypeName(memType);

            if (!string.IsNullOrWhiteSpace(dm?.Name))
                field.JsonName = dm.Name;
            if (!string.IsNullOrWhiteSpace(jp?.PropertyName))
                field.JsonName = jp.PropertyName;
            var rule = member.GetAttribute<DataRuleAttribute>();
            if (rule != null)
            {
                field.CanNull = rule.CanNull;
                field.Regex = rule.Regex;
                if (rule.Min != long.MinValue)
                    field.Min = rule.Min;
                if (rule.Max != long.MinValue)
                    field.Max = rule.Max;
                if (rule.MinDate != DateTime.MinValue)
                    field.MinDate = rule.MinDate;
                if (rule.MaxDate != DateTime.MaxValue)
                    field.MaxDate = rule.MaxDate;
            }
            doreplacedent.Fields.Add(member.Name, field);

            return field;
        }

19 Source : StickerEditor.cs
with MIT License
from agens-no

public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
        {
            if (textureEditors == null || textureEditors.Count == 0)
            {
                CreateTextureEditor();
            }

            if (currentTextureEditor != null)
            {
                currentTextureEditor.OnInteractivePreviewGUI(r, background);
            }

            if (playing && Sequence.boolValue && Frames.arraySize > 1)
            {
                if (RepaintMethod == null)
                {
                    var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                    var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                    GUIView = prop.GetValue(null, null);
                    RepaintMethod = GUIView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
                }

                RepaintMethod.Invoke(GUIView, null);
            }
        }

19 Source : StickerPackEditor.cs
with MIT License
from agens-no

private void RepaintView()
        {
            if (repaintMethod == null)
            {
                var type = typeof(Editor).replacedembly.GetType("UnityEditor.GUIView");
                var prop = type.GetProperty("current", BindingFlags.Static | BindingFlags.Public);
                guiView = prop.GetValue(null, null);
                repaintMethod = guiView.GetType().GetMethod("Repaint", BindingFlags.Public | BindingFlags.Instance);
            }
            repaintMethod.Invoke(guiView, null);
        }

19 Source : JsonFsCheck.cs
with BSD 3-Clause "New" or "Revised" License
from agocke

[Fact]
        public async Task CheckPrimitiveEquivalentsAsync()
        {
            // Generates test cases, each of which has multiple generated clreplacedes
            var testCases = Gen.Sample(4, 100, Gen.Sized(TestTypeGenerators.GenTypeDef));
            var wrappers = new MemberDeclarationSyntax[testCases.Length];
            int wrapperIndex = 0;
            foreach (var type in testCases)
            {
                var clreplacedDecls = ToMembers((TestTypeDef)type);
                // Wrap the clreplacedes used by each test case in an outer clreplaced to
                // prevent name collision
                wrappers[wrapperIndex] = ClreplacedDeclaration(
                    attributeLists: default,
                    modifiers: TokenList(Token(SyntaxKind.PartialKeyword)),
                    identifier: Identifier("TestCase" + wrapperIndex),
                    typeParameterList: null,
                    baseList: null,
                    constraintClauses: default,
                    members: List(clreplacedDecls)).NormalizeWhitespace();
                wrapperIndex++;
            }

            var serializeStatements = new List<string>();
            serializeStatements.Add("var results = new List<(string, string)>();");
            serializeStatements.Add("var options = new System.Text.Json.JsonSerializerOptions() { IncludeFields = true };");
            for (int i = 0; i < wrappers.Length; i++)
            {
                var localName = "t" + i;
                serializeStatements.Add($"var {localName} = new TestCase{i}.Clreplaced0();");
                serializeStatements.Add($@"results.Add(
(Serde.Json.JsonSerializer.Serialize({localName}),
 System.Text.Json.JsonSerializer.Serialize({localName}, options)));");
            }
            serializeStatements.Add("return results;");

            var body = string.Join(Environment.NewLine, serializeStatements);
            var mainTree = SyntaxFactory.ParseSyntaxTree($@"
using System;
using System.Collections.Generic;

public static clreplaced Runner
{{
    public static List<(string Serde, string SystemText)> Run()
    {{
        {body}
    }}
}}");

            var allTypes = SyntaxTree(CompilationUnit(
                externs: default,
                usings: List(new [] {
                    UsingDirective(IdentifierName("System")),
                    UsingDirective(QualifiedName(
                        QualifiedName(IdentifierName("System"), IdentifierName("Collections")),
                        IdentifierName("Generic"))),
                    UsingDirective(IdentifierName("Serde"))
                    }),
                attributeLists: default,
                List(wrappers)).NormalizeWhitespace());

            var comp = CSharpCompilation.Create(
               Guid.NewGuid().ToString("N"),
               syntaxTrees: new[] { mainTree, allTypes },
               references: (await Config.LatestTfRefs.ResolveAsync(null, default))
                    .Append(MetadataReference.CreateFromFile(typeof(Serde.ISerialize).replacedembly.Location)),
               new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            var driver = CSharpGeneratorDriver.Create(new Generator());
            driver.RunGeneratorsAndUpdateCompilation(
                comp,
                out var newComp,
                out var diagnostics);

            replacedert.Empty(diagnostics);

            var peStream = new MemoryStream();
            var result = newComp.Emit(peStream,
                pdbStream: null,
                xmlDoreplacedentationStream: null,
                win32Resources: null,
                manifestResources: null,
                options: s_emitOptions,
                cancellationToken: default);

            replacedert.True(result.Success,
                string.Join(Environment.NewLine, result.Diagnostics.Select(d => d.GetMessage())));
            var loaded = replacedembly.Load(peStream.GetBuffer());
            var testResults = (List<(string Serde, string SystemText)>)loaded.GetType("Runner")!.GetMethod("Run")!.Invoke(null, null)!;
            foreach (var (serde, systemText) in testResults)
            {
                replacedert.Equal(systemText, serde);
            }
        }

19 Source : ExternalProvider.cs
with Apache License 2.0
from Aguafrommars

private static Type GetOptionsType(Enreplacedy.ExternalProvider externalProvider)
        {            
            var typeName = $"{typeof(RemoteAuthenticationOptions).Namespace}.{externalProvider.KindName}Options";
            var replacedembly = AppDomain.CurrentDomain.Getreplacedemblies().First(a => a.GetType(typeName) != null);
            return replacedembly.GetType(typeName);
        }

19 Source : ProfileService.cs
with Apache License 2.0
from Aguafrommars

protected virtual Task<IEnumerable<Claim>> GetClaimsFromResource(Resource resource, ClaimsPrincipal subject, Client client, string caller, string providerTypeName)
        {
            var provider = _claimsProvider.FirstOrDefault(p => p.GetType().FullName == providerTypeName);

            if (provider == null)
            {
                var path = resource.Properties[ProfileServiceProperties.ClaimProviderreplacedemblyPathKey];
#pragma warning disable S3885 // "replacedembly.Load" should be used
                var replacedembly = replacedembly.LoadFrom(path);
#pragma warning restore S3885 // "replacedembly.Load" should be used
                var type = replacedembly.GetType(providerTypeName);
                provider = Activator.CreateInstance(type) as IProvideClaims;
            }

            return provider.ProvideClaims(subject, client, caller, resource);
        }

19 Source : ProxyClaimsProvider.cs
with Apache License 2.0
from Aguafrommars

private Task<IEnumerable<Claim>> GetClaimsFromResource(Resource resource, ClaimsPrincipal subject, Client client, string caller, string providerTypeName)
        {
            var provider = _claimsProviders.FirstOrDefault(p => p.GetType().FullName == providerTypeName);

            if (provider == null)
            {
                var path = resource.Properties[ProfileServiceProperties.ClaimProviderreplacedemblyPathKey];
#pragma warning disable S3885 // "replacedembly.Load" should be used
                var replacedembly = replacedembly.LoadFrom(path);
#pragma warning restore S3885 // "replacedembly.Load" should be used
                var type = replacedembly.GetType(providerTypeName);
                provider = Activator.CreateInstance(type) as IProvideClaims;
            }

            return provider.ProvideClaims(subject, client, caller, resource);
        }

19 Source : NodeParamGenerator.cs
with MIT License
from aillieo

internal static bool IsTypeNameValid(string typeName)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                return false;
            }

            if (csTypes.Contains(typeName))
            {
                return true;
            }

            Type t = null;
            var replaced = AppDomain.CurrentDomain.Getreplacedemblies();
            foreach (var a in replaced)
            {
                t = a.GetType(typeName);
                if (t != null)
                {
                    break;
                }
            }
            return t != null;
        }

19 Source : DefaultSerializationBinder.cs
with MIT License
from akaskela

private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
        {
            string replacedemblyName = typeNameKey.replacedemblyName;
            string typeName = typeNameKey.TypeName;

            if (replacedemblyName != null)
            {
                replacedembly replacedembly;

#if !(DOTNET || PORTABLE40 || PORTABLE)
                // look, I don't like using obsolete methods as much as you do but this is the only way
                // replacedembly.Load won't check the GAC for a partial name
#pragma warning disable 618,612
                replacedembly = replacedembly.LoadWithPartialName(replacedemblyName);
#pragma warning restore 618,612
#elif DOTNET || PORTABLE
                replacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
#else
                replacedembly = replacedembly.Load(replacedemblyName);
#endif

#if !(PORTABLE40 || PORTABLE || DOTNET)
                if (replacedembly == null)
                {
                    // will find replacedemblies loaded with replacedembly.LoadFile outside of the main directory
                    replacedembly[] loadedreplacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
                    foreach (replacedembly a in loadedreplacedemblies)
                    {
                        if (a.FullName == replacedemblyName)
                        {
                            replacedembly = a;
                            break;
                        }
                    }
                }
#endif

                if (replacedembly == null)
                {
                    throw new JsonSerializationException("Could not load replacedembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, replacedemblyName));
                }

                Type type = replacedembly.GetType(typeName);
                if (type == null)
                {
                    throw new JsonSerializationException("Could not find type '{0}' in replacedembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, replacedembly.FullName));
                }

                return type;
            }
            else
            {
                return Type.GetType(typeName);
            }
        }

19 Source : FSharpUtils.cs
with MIT License
from akaskela

public static void EnsureInitialized(replacedembly fsharpCorereplacedembly)
        {
            if (!_initialized)
            {
                lock (Lock)
                {
                    if (!_initialized)
                    {
                        FSharpCorereplacedembly = fsharpCorereplacedembly;

                        Type fsharpType = fsharpCorereplacedembly.GetType("Microsoft.FSharp.Reflection.FSharpType");

                        MethodInfo isUnionMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "IsUnion", BindingFlags.Public | BindingFlags.Static);
                        IsUnion = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(isUnionMethodInfo);

                        MethodInfo getUnionCasesMethodInfo = GetMethodWithNonPublicFallback(fsharpType, "GetUnionCases", BindingFlags.Public | BindingFlags.Static);
                        GetUnionCases = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(getUnionCasesMethodInfo);

                        Type fsharpValue = fsharpCorereplacedembly.GetType("Microsoft.FSharp.Reflection.FSharpValue");

                        PreComputeUnionTagReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionTagReader");
                        PreComputeUnionReader = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionReader");
                        PreComputeUnionConstructor = CreateFSharpFuncCall(fsharpValue, "PreComputeUnionConstructor");

                        Type unionCaseInfo = fsharpCorereplacedembly.GetType("Microsoft.FSharp.Reflection.UnionCaseInfo");

                        GetUnionCaseInfoName = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Name"));
                        GetUnionCaseInfoTag = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("Tag"));
                        GetUnionCaseInfoDeclaringType = JsonTypeReflector.ReflectionDelegateFactory.CreateGet<object>(unionCaseInfo.GetProperty("DeclaringType"));
                        GetUnionCaseInfoFields = JsonTypeReflector.ReflectionDelegateFactory.CreateMethodCall<object>(unionCaseInfo.GetMethod("GetFields"));

                        Type listModule = fsharpCorereplacedembly.GetType("Microsoft.FSharp.Collections.ListModule");
                        _ofSeq = listModule.GetMethod("OfSeq");

                        _mapType = fsharpCorereplacedembly.GetType("Microsoft.FSharp.Collections.FSharpMap`2");

#if !(DOTNET || PORTABLE)
                        Thread.MemoryBarrier();
#endif
                        _initialized = true;
                    }
                }
            }
        }

19 Source : AssetBundleFilesAnalyzeObject.cs
with MIT License
from akof1314

public static AnimationClipStatsInfo GetAnimationClipStats(AnimationClip clip)
            {
                if (getAnimationClipStats == null)
                {
                    getAnimationClipStats = typeof(AnimationUtility).GetMethod("GetAnimationClipStats", BindingFlags.Static | BindingFlags.NonPublic);
                    var aniclipstats = typeof(AnimationUtility).replacedembly.GetType("UnityEditor.AnimationClipStats");
                    sizeInfo = aniclipstats.GetField("size", BindingFlags.Public | BindingFlags.Instance);
                    totalCurvesInfo = aniclipstats.GetField("totalCurves", BindingFlags.Public | BindingFlags.Instance);
                    constantCurvesInfo = aniclipstats.GetField("constantCurves", BindingFlags.Public | BindingFlags.Instance);
                    denseCurvesInfo = aniclipstats.GetField("denseCurves", BindingFlags.Public | BindingFlags.Instance);
                    streamCurvesInfo = aniclipstats.GetField("streamCurves", BindingFlags.Public | BindingFlags.Instance);
                }

                var stats = getAnimationClipStats.Invoke(null, new object[] { clip });
                var stats2 = new AnimationClipStatsInfo
                {
                    size = (int)sizeInfo.GetValue(stats),
                    totalCurves = (int)totalCurvesInfo.GetValue(stats),
                    constantCurves = (int)constantCurvesInfo.GetValue(stats),
                    denseCurves = (int)denseCurvesInfo.GetValue(stats),
                    streamCurves = (int)streamCurvesInfo.GetValue(stats),
                };
                return stats2;
            }

19 Source : NodeEditorReflection.cs
with MIT License
from aksyr

public static void OpenPreferences() {
            try {
#if UNITY_2018_3_OR_NEWER
                SettingsService.OpenUserPreferences("Preferences/Node Editor");
#else
                //Open preferences window
                replacedembly replacedembly = replacedembly.Getreplacedembly(typeof(UnityEditor.EditorWindow));
                Type type = replacedembly.GetType("UnityEditor.PreferencesWindow");
                type.GetMethod("ShowPreferencesWindow", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);

                //Get the window
                EditorWindow window = EditorWindow.GetWindow(type);

                //Make sure custom sections are added (because waiting for it to happen automatically is too slow)
                FieldInfo refreshField = type.GetField("m_RefreshCustomPreferences", BindingFlags.NonPublic | BindingFlags.Instance);
                if ((bool) refreshField.GetValue(window)) {
                    type.GetMethod("AddCustomSections", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(window, null);
                    refreshField.SetValue(window, false);
                }

                //Get sections
                FieldInfo sectionsField = type.GetField("m_Sections", BindingFlags.Instance | BindingFlags.NonPublic);
                IList sections = sectionsField.GetValue(window) as IList;

                //Iterate through sections and check contents
                Type sectionType = sectionsField.FieldType.GetGenericArguments() [0];
                FieldInfo sectionContentField = sectionType.GetField("content", BindingFlags.Instance | BindingFlags.Public);
                for (int i = 0; i < sections.Count; i++) {
                    GUIContent sectionContent = sectionContentField.GetValue(sections[i]) as GUIContent;
                    if (sectionContent.text == "Node Editor") {
                        //Found contents - Set index
                        FieldInfo sectionIndexField = type.GetField("m_SelectedSectionIndex", BindingFlags.Instance | BindingFlags.NonPublic);
                        sectionIndexField.SetValue(window, i);
                        return;
                    }
                }
#endif
            } catch (Exception e) {
                Debug.LogError(e);
                Debug.LogWarning("Unity has changed around internally. Can't open properties through reflection. Please contact xNode developer and supply unity version number.");
            }
        }

19 Source : MixtureNodeView.cs
with MIT License
from alelievr

protected bool MaterialPropertiesGUI(Material material, bool fromInspector, bool autoLabelWidth = true)
		{
			if (material == null || material.shader == null)
				return false;

			if (autoLabelWidth)
			{
				EditorGUIUtility.wideMode = false;
				EditorGUIUtility.labelWidth = nodeTarget.nodeWidth / 3.0f;
			}

			MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new []{material});
			var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));

			MaterialEditor  editor;
			if (!materialEditors.TryGetValue(material, out editor))
			{
				foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
				{
					var editorType = replacedembly.GetType("UnityEditor.MaterialEditor");
					if (editorType != null)
					{
						editor = materialEditors[material] = Editor.CreateEditor(material, editorType) as MaterialEditor;
						MixturePropertyDrawer.RegisterEditor(editor, this, owner.graph);
						break ;
					}
				}

			}

			bool propertiesChanged = CheckPropertyChanged(material, properties);

			foreach (var property in properties)
			{
				if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
					continue;

				int idx = material.shader.FindPropertyIndex(property.name);
				var propertyAttributes = material.shader.GetPropertyAttributes(idx);
				if (!fromInspector && propertyAttributes.Contains("ShowInInspector"))
					continue;

				// Retrieve the port view from the property name
				var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
				if (portView != null && portView.connected)
					continue;
				
				// We only display textures that are excluded from the filteredOutProperties (i.e they are not exposed as ports)
				if (property.type == MaterialProperty.PropType.Texture && nodeTarget is ShaderNode sn)
				{
					if (!sn.GetFilterOutProperties().Contains(property.name))
						continue;
				}

				// TODO: cache to improve the performance of the UI
				var visibleIfAtribute = propertyAttributes.FirstOrDefault(s => s.Contains("VisibleIf"));
				if (!string.IsNullOrEmpty(visibleIfAtribute))
				{
					var match = visibleIfRegex.Match(visibleIfAtribute);
					if (match.Success)
					{
						string propertyName = match.Groups[1].Value;
						string[] accpectedValues = match.Groups[2].Value.Split(',');

						if (material.HasProperty(propertyName))
						{
							float f = material.GetFloat(propertyName);

							bool show = false;
							foreach (var value in accpectedValues)
							{
								float f2 = float.Parse(value);

								if (f == f2)
									show = true;
							}

							if (!show)
								continue;
						}
						else
							continue;
					}
				}

				// Hide all the properties that are not supported in the current dimension
				var currentDimension = nodeTarget.settings.GetResolvedTextureDimension(owner.graph);
				string displayName = property.displayName;

				bool is2D = displayName.Contains(MixtureUtils.texture2DPrefix);
				bool is3D = displayName.Contains(MixtureUtils.texture3DPrefix);
				bool isCube = displayName.Contains(MixtureUtils.textureCubePrefix);

				if (is2D || is3D || isCube)
				{
					if (currentDimension == TextureDimension.Tex2D && !is2D)
						continue;
					if (currentDimension == TextureDimension.Tex3D && !is3D)
						continue;
					if (currentDimension == TextureDimension.Cube && !isCube)
						continue;
					displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
				}

				// In ShaderGraph we can put [Inspector] in the name of the property to show it only in the inspector and not in the node
				if (property.displayName.ToLower().Contains("[inspector]"))
				{
					if (fromInspector)
						displayName = Regex.Replace(property.displayName, @"\[inspector\]\s*", "", RegexOptions.IgnoreCase);
					else
						continue;
				}

				float h = editor.GetPropertyHeight(property, displayName);

				// We always display textures on a single line without scale or offset because they are not supported
				if (property.type == MaterialProperty.PropType.Texture)
					h = EditorGUIUtility.singleLineHeight;

				Rect r = EditorGUILayout.GetControlRect(true, h);
				if (property.name.Contains("Vector2"))
					property.vectorValue = (Vector4)EditorGUI.Vector2Field(r, displayName, (Vector2)property.vectorValue);
				else if (property.name.Contains("Vector3"))
					property.vectorValue = (Vector4)EditorGUI.Vector3Field(r, displayName, (Vector3)property.vectorValue);
				else if (property.type == MaterialProperty.PropType.Range)
				{
					if (material.shader.GetPropertyAttributes(idx).Any(a => a.Contains("IntRange")))
						property.floatValue = EditorGUI.IntSlider(r, displayName, (int)property.floatValue, (int)property.rangeLimits.x, (int)property.rangeLimits.y);
					else
						property.floatValue = EditorGUI.Slider(r, displayName, property.floatValue, property.rangeLimits.x, property.rangeLimits.y);
				}
				else if (property.type == MaterialProperty.PropType.Texture)
					property.textureValue = (Texture)EditorGUI.ObjectField(r, displayName, property.textureValue, typeof(Texture), false);
				else
					editor.ShaderProperty(r, property, displayName);
			}

			return propertiesChanged;
		}

19 Source : MixtureInspector.cs
with MIT License
from alelievr

protected virtual void LoadInspectorFor(Type typeForEditor, Object[] targets)
		{
			string editorTypeName;
			if (defaultTextureInspectors.TryGetValue(typeForEditor, out editorTypeName))
			{
				foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
				{
					var editorType = replacedembly.GetType(editorTypeName);
					if (editorType != null)
					{
						Editor.CreateCachedEditor(targets, editorType, ref defaultTextureEditor);

						if (variantEditor != null)
							(variantEditor as MixtureVariantInspector).SetDefaultTextureEditor(defaultTextureEditor);

						return ;
					}
				}
			}
		}

19 Source : MixtureVariantInspector.cs
with MIT License
from alelievr

protected void OnEnable()
		{
            variant = target as MixtureVariant;
            graph = variant.parentGraph;
            if (graph != null)
			{
				graph.onExposedParameterListChanged += UpdateParameters;
				graph.onExposedParameterModified += UpdateParameters;
				graph.onExposedParameterValueChanged += UpdateParameters;
                Undo.undoRedoPerformed += UpdateParameters;
			}

            variant.variantTexturesUpdated += UpdateIsDirtyAndPreview;

            MixtureVariant parent = variant.parentVariant;
            while (parent != null)
            {
                parent.parameterValueChanged += UpdateParameters;
                parent = parent.parentVariant;
            }

            // TODO: create a temp render texture to copy the result of the graph we process
            // it will be used to display in real time how the parameter changes affects the texture

            // Update serialized parameters (for the inspector)
            SyncParameters();
            exposedParameterFactory = new ExposedParameterFieldFactory(graph, visibleParameters);

            overrideParameterView = Resources.Load<VisualTreereplacedet>("UI Blocks/MixtureVariantParameter");

            foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
            {
                renderTextureEditorType = replacedembly.GetType("UnityEditor.RenderTextureEditor");
                if (renderTextureEditorType != null)
                    break;
            }

            variantPreview = new RenderTexture(1, 1, 0);
		}

19 Source : LogEntry.cs
with MIT License
from alen-smajic

static void Initialize()
        {
            if (_type == null)
            {
                var flags = BindingFlags.Instance | BindingFlags.Public;

                var replacedembly = replacedembly.Getreplacedembly(typeof(Editor));
                _type = replacedembly.GetType("UnityEditorInternal.LogEntry");
                if (_type == null) // 2017 Fix
                {
                    _type = replacedembly.GetType("UnityEditor.LogEntry");
                }

                _condition = _type.GetField("condition", flags);
                _errorNum = _type.GetField("errorNum", flags);
                _file = _type.GetField("file", flags);
                _line = _type.GetField("line", flags);
                _mode = _type.GetField("mode", flags);
                _instanceID = _type.GetField("instanceID", flags);
                _identifier = _type.GetField("identifier", flags);
                _isWorldPlaying = _type.GetField("isWorldPlaying", flags);

                instance = Activator.CreateInstance(_type);
            }
        }

See More Examples