System.Reflection.Assembly.LoadFrom(string)

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

620 Examples 7

19 Source : ExtensionMethods.cs
with GNU Lesser General Public License v2.1
from axiom3d

public static IEnumerable<replacedembly> Neighbors(IEnumerable<string> names)
        {
            replacedembly replacedembly;
            foreach (var name in names)
            {
                try
                {
                    replacedembly = replacedembly.LoadFrom(name);
                }
                catch (BadImageFormatException e)
                {
                    continue;
                }
                if (replacedembly != null)
                {
                    yield return replacedembly;
                }
            }
            yield break;
        }

19 Source : BTModLoader.cs
with The Unlicense
from BattletechModders

public static replacedembly LoadDLL(string path, string methodName = "Init", string typeName = null,
            object[] parameters = null, BindingFlags bFlags = PUBLIC_STATIC_BINDING_FLAGS)
        {
            var fileName = Path.GetFileName(path);

            if (!File.Exists(path))
            {
                LogWithDate($"Failed to load {fileName} at path {path}, because it doesn't exist at that path.");
                return null;
            }

            try
            {
                var replacedembly = replacedembly.LoadFrom(path);
                var name = replacedembly.GetName();
                var version = name.Version;
                var types = new List<Type>();

                // if methodName is null, don't try to run an entry point
                if (methodName == null)
                    return replacedembly;

                // find the type/s with our entry point/s
                if (typeName == null)
                {
                    types.AddRange(replacedembly.GetTypes().Where(x => x.GetMethod(methodName, bFlags) != null));
                }
                else
                {
                    types.Add(replacedembly.GetType(typeName));
                }

                if (types.Count == 0)
                {
                    LogWithDate($"{fileName} (v{version}): Failed to find specified entry point: {typeName ?? "NotSpecified"}.{methodName}");
                    return null;
                }

                // run each entry point
                foreach (var type in types)
                {
                    var entryMethod = type.GetMethod(methodName, bFlags);
                    var methodParams = entryMethod?.GetParameters();

                    if (methodParams == null)
                        continue;

                    if (methodParams.Length == 0)
                    {
                        LogWithDate($"{fileName} (v{version}): Found and called entry point \"{entryMethod}\" in type \"{type.FullName}\"");
                        entryMethod.Invoke(null, null);
                        continue;
                    }

                    // match up the preplaceded in params with the method's params, if they match, call the method
                    if (parameters != null && methodParams.Length == parameters.Length
                        && !methodParams.Where((info, i) => parameters[i]?.GetType() != info.ParameterType).Any())
                    {
                        LogWithDate($"{fileName} (v{version}): Found and called entry point \"{entryMethod}\" in type \"{type.FullName}\"");
                        entryMethod.Invoke(null, parameters);
                        continue;
                    }

                    // failed to call entry method of parameter mismatch
                    // diagnosing problems of this type is pretty hard
                    LogWithDate($"{fileName} (v{version}): Provided params don't match {type.Name}.{entryMethod.Name}");
                    Log("\tPreplaceded in Params:");
                    if (parameters != null)
                    {
                        foreach (var parameter in parameters)
                            Log($"\t\t{parameter.GetType()}");
                    }
                    else
                    {
                        Log("\t\t'parameters' is null");
                    }

                    if (methodParams.Length != 0)
                    {
                        Log("\tMethod Params:");
                        foreach (var prm in methodParams)
                            Log($"\t\t{prm.ParameterType}");
                    }
                }

                return replacedembly;
            }
            catch (Exception e)
            {
                LogException($"{fileName}: While loading a dll, an exception occured", e);
                return null;
            }
        }

19 Source : AssemblyUtil.cs
with The Unlicense
from BattletechModders

public static replacedembly LoadDLL(string path)
        {
            var fileName = Path.GetFileName(path);

            if (!File.Exists(path))
            {
                Log($"\tFailed to load {fileName} at path {path}, because it doesn't exist at that path.");
                return null;
            }

            try
            {
                var replacedembly = replacedembly.LoadFrom(path);
                Log($"\tLoaded replacedembly {replacedembly.GetName().Name} (v{replacedembly.GetName().Version})");
                return replacedembly;
            }
            catch (Exception e)
            {
                Log($"\t{fileName}: While loading a .dll, an exception occured", e);
                return null;
            }
        }

19 Source : Injection.cs
with The Unlicense
from BattletechModders

public static void LoadModTek()
        {
            try
            {
                var path = Path.Combine(
                    Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location) ?? Directory.GetCurrentDirectory(),
                    Path.Combine(Path.Combine("..", ".."), Path.Combine(FilePaths.MODS_DIRECTORY_NAME, Path.Combine(FilePaths.MODTEK_DIRECTORY_NAME, "ModTek.dll")))
                );

                if (File.Exists(path))
                {
                    replacedembly.LoadFrom(path)
                        .GetType("ModTek.ModTek")
                        .GetMethod("Init", BindingFlags.Public | BindingFlags.Static)
                        ?.Invoke(null, null);
                }
            }
            catch
            {
                // ignore
            }
        }

19 Source : AssemblyLoader.cs
with MIT License
from bbepis

private static replacedembly Loadreplacedembly( string file )
      {
         try
         {
            var replacedemblyName = replacedemblyName.GetreplacedemblyName( file );
            var replacedembly = replacedembly.Load( replacedemblyName );
            return replacedembly;
         }
         catch( BadImageFormatException )
         {
            // unmanaged
         }
         catch
         {
            // fallback to legacy API
            try
            {
               var replacedembly = replacedembly.LoadFrom( file );
               return replacedembly;
            }
            catch( BadImageFormatException )
            {
               // unmanaged
            }
         }

         return null;
      }

19 Source : Startup.cs
with MIT License
from Belenar

private void LoadAspnetApplicationPlugins(ApplicationPartManager apm)
        {
            var allPluginDlls = Directory.GetFiles(
                Path.Combine(Environment.ContentRootPath, "bin"), "Axxes.ToyCollector.Plugins.*.dll", 
                SearchOption.AllDirectories);

            var allControllerDlls = allPluginDlls.Where(p => !p.EndsWith("Views.dll"));
            var allRazorViewsDlls = allPluginDlls.Where(p => p.EndsWith("Views.dll"));

            // Add MVC/API controllers from Plugins
            foreach (string controllerDll in allControllerDlls)
            {
                apm.ApplicationParts.Add(
                    new replacedemblyPart(replacedembly.LoadFrom(controllerDll)));
            }

            // Add Razor views from Plugins
            foreach (string razorViewsDll in allRazorViewsDlls)
            {
                apm.ApplicationParts.Add(
                    new CompiledRazorreplacedemblyPart(replacedembly.LoadFrom(razorViewsDll)));
            }
        }

19 Source : Program.cs
with GNU Lesser General Public License v2.1
from BepInEx

private static replacedembly RemoteResolve(object sender, ResolveEventArgs reference)
        {
            var replacedemblyName = new replacedemblyName(reference.Name);

            foreach (var directory in ResolveDirectories)
            {
                if (!Directory.Exists(directory))
                    continue;

                var potentialDirectories = new List<string> { directory };

                potentialDirectories.AddRange(Directory.GetDirectories(directory, "*", SearchOption.AllDirectories));

                var potentialFiles = potentialDirectories.Select(x => Path.Combine(x, $"{replacedemblyName.Name}.dll"))
                                                         .Concat(potentialDirectories.Select(x =>
                                                                     Path
                                                                         .Combine(x,
                                                                             $"{replacedemblyName.Name}.exe")));

                foreach (var path in potentialFiles)
                {
                    if (!File.Exists(path))
                        continue;

                    replacedembly replacedembly;

                    try
                    {
                        replacedembly = replacedembly.LoadFrom(path);
                    }
                    catch (Exception ex)
                    {
                        continue;
                    }

                    if (replacedembly.GetName().Name == replacedemblyName.Name)
                        return replacedembly;
                }
            }

            return null;
        }

19 Source : NetPreloader.cs
with GNU Lesser General Public License v2.1
from BepInEx

public static void Start(string[] args)
        {
            var preloaderListener = new PreloaderConsoleListener();
            Logger.Listeners.Add(preloaderListener);

            if (string.IsNullOrEmpty(ConfigEntrypointExecutable.Value))
            {
                Log.LogFatal($"Entry executable was not set. Please set this in your config before launching the application");
                Program.ReadExit();
                return;
            }

            var executablePath = Path.GetFullPath(ConfigEntrypointExecutable.Value);

            if (!File.Exists(executablePath))
            {
                Log.LogFatal($"Unable to locate executable: {ConfigEntrypointExecutable.Value}");
                Program.ReadExit();
                return;
            }


            Paths.SetExecutablePath(executablePath);
            Program.ResolveDirectories.Add(Paths.GameRootPath);

            foreach (var searchDir in Program.ResolveDirectories)
                TypeLoader.SearchDirectories.Add(searchDir);

            if (PlatformHelper.Is(Platform.Windows))
            {
                AddDllDirectory(Paths.GameRootPath);
                SetDllDirectory(Paths.GameRootPath);
            }


            Logger.Sources.Add(TraceLogSource.CreateSource());

            ChainloaderLogHelper.PrintLogInfo(Log);

            Log.LogInfo($"CLR runtime version: {Environment.Version}");

            Log.LogMessage("Preloader started");

            replacedembly entrypointreplacedembly;

            using (var replacedemblyPatcher = new replacedemblyPatcher())
            {
                replacedemblyPatcher.AddPatchersFromDirectory(Paths.PatcherPluginPath);

                Log.LogInfo($"{replacedemblyPatcher.PatcherContext.PatchDefinitions.Count} patcher definition(s) loaded");

                replacedemblyPatcher.LoadreplacedemblyDirectories(new[] { Paths.GameRootPath }, new[] { "dll", "exe" });

                Log.LogInfo($"{replacedemblyPatcher.PatcherContext.Availablereplacedemblies.Count} replacedemblies discovered");

                replacedemblyPatcher.PatchAndLoad();


                var replacedemblyName = replacedemblyName.GetreplacedemblyName(executablePath);

                entrypointreplacedembly =
                    replacedemblyPatcher.PatcherContext.Loadedreplacedemblies.Values.FirstOrDefault(x => x.FullName == replacedemblyName.FullName);

                foreach (var loadedreplacedembly in replacedemblyPatcher.PatcherContext.Loadedreplacedemblies)
                {
                    // TODO: Need full paths for loaded replacedemblies
                    var replacedemblyPath = Path.Combine(Paths.GameRootPath, loadedreplacedembly.Key);

                    Log.LogDebug($"Registering '{replacedemblyPath}' as a loaded replacedembly");
                    replacedemblyFixes.replacedemblyLocations[loadedreplacedembly.Value.FullName] = replacedemblyPath;
                }

                if (entrypointreplacedembly != null)
                {
                    Log.LogDebug("Found patched entrypoint replacedembly! Using it");
                }
                else
                {
                    Log.LogDebug("Using entrypoint replacedembly from disk");
                    entrypointreplacedembly = replacedembly.LoadFrom(executablePath);
                }
            }

            Log.LogMessage("Preloader finished");

            Logger.Listeners.Remove(preloaderListener);

            var chainloader = new NetChainloader();
            chainloader.Initialize();
            chainloader.Execute();


            replacedemblyFixes.Execute(entrypointreplacedembly);

            try
            {
                var argList = new List<object>();

                var paramTypes = entrypointreplacedembly.EntryPoint.GetParameters();

                if (paramTypes.Length == 1 && paramTypes[0].ParameterType == typeof(string[]))
                {
                    argList.Add(args);
                }
                else if (paramTypes.Length == 1 && paramTypes[0].ParameterType == typeof(string))
                {
                    argList.Add(string.Join(" ", args));
                }
                else if (paramTypes.Length != 0)
                {
                    // Only other entrypoint signatures I can think of that .NET supports is Task / Task<int>
                    //   async entrypoints. That's a can of worms for another time though

                    Log.LogFatal($"Could not figure out how to handle entrypoint method with this signature: {entrypointreplacedembly.EntryPoint.FullDescription()}");
                    return;
                }

                entrypointreplacedembly.EntryPoint.Invoke(null, argList.ToArray());
            }
            catch (Exception ex)
            {
                Log.LogFatal($"Unhandled exception: {ex}");
            }
        }

19 Source : AssemblyPatcher.cs
with GNU Lesser General Public License v2.1
from BepInEx

public void PatchAndLoad()
        {
            // First, create a copy of the replacedembly dictionary as the initializer can change them
            var replacedemblies =
                new Dictionary<string, replacedemblyDefinition>(PatcherContext.Availablereplacedemblies,
                                                           StringComparer.InvariantCultureIgnoreCase);

            // Next, initialize all the patchers
            foreach (var replacedemblyPatcher in PatcherPluginsSafe)
                try
                {
                    replacedemblyPatcher.Initialize();
                }
                catch (Exception ex)
                {
                    Logger.LogError($"Failed to run initializer of {replacedemblyPatcher.Info.GUID}: {ex}");
                }

            // Then, perform the actual patching

            var patchedreplacedemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            var resolvedreplacedemblies = new Dictionary<string, string>();

            // TODO: Maybe instead reload the replacedembly and repatch with other valid patchers?
            var invalidreplacedemblies = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);

            Logger.LogMessage($"Executing {PatcherContext.PatchDefinitions.Count} patch(es)");

            foreach (var patchDefinition in PatcherContext.PatchDefinitions.ToList())
            {
                string targetDll = patchDefinition.Targetreplacedembly?.Targetreplacedembly ??
                                   patchDefinition.TargetType.Targetreplacedembly;

                bool isreplacedemblyPatch = patchDefinition.Targetreplacedembly != null;

                if (targetDll == TargetreplacedemblyAttribute.Allreplacedemblies)
                {
                    foreach (var kv in PatcherContext.Availablereplacedemblies.ToList())
                    {
                        if (invalidreplacedemblies.Contains(kv.Key))
                            continue;

                        RunPatcher(kv.Value, kv.Key);
                    }
                }
                else
                {
                    if (!PatcherContext.Availablereplacedemblies.TryGetValue(targetDll, out var replacedembly)
                     || invalidreplacedemblies.Contains(targetDll))
                        continue;

                    RunPatcher(replacedembly, targetDll);
                }


                bool RunPatcher(replacedemblyDefinition replacedembly, string targetDll)
                {
                    try
                    {
                        var arguments = new object[patchDefinition.MethodInfo.GetParameters().Length];

                        if (!isreplacedemblyPatch)
                        {
                            var targetType =
                                replacedembly.MainModule.Types.FirstOrDefault(x => x.FullName ==
                                                                              patchDefinition.TargetType.TargetType);

                            if (targetType == null)
                            {
                                Logger
                                    .LogWarning($"Unable to find type [{patchDefinition.TargetType.TargetType}] defined in {patchDefinition.MethodInfo.Name}. Skipping patcher"); //TODO: Proper name
                                return false;
                            }

                            arguments[0] = targetType;
                        }
                        else
                        {
                            arguments[0] = replacedembly;
                        }

                        if (arguments.Length > 1)
                            arguments[1] = targetDll;

                        var result = patchDefinition.MethodInfo.Invoke(patchDefinition.Instance, arguments);

                        if (patchDefinition.MethodInfo.ReturnType == typeof(void)
                         || patchDefinition.MethodInfo.ReturnType == typeof(bool) && (bool)result)
                        {
                            if (isreplacedemblyPatch)
                            {
                                replacedembly = (replacedemblyDefinition)arguments[0];
                                PatcherContext.Availablereplacedemblies[targetDll] = replacedembly;
                            }

                            patchedreplacedemblies.Add(targetDll);
                        }

                        return true;
                    }
                    catch (Exception e)
                    {
                        Logger.LogError($"Failed to run [{patchDefinition.FullName}] when patching [{replacedembly.Name.Name}]. This replacedembly will not be patched. Error: {e}");
                        patchedreplacedemblies.Remove(targetDll);
                        invalidreplacedemblies.Add(targetDll);
                        return false;
                    }
                }


                foreach (var resolvedreplaced in AppDomain.CurrentDomain.Getreplacedemblies())
                {
                    var name = Utility.TryParsereplacedemblyName(resolvedreplaced.FullName, out var replacedName)
                                   ? replacedName.Name
                                   : resolvedreplaced.FullName;

                    // Report only the first type that caused the replacedembly to load, because any subsequent ones can be false positives
                    if (!resolvedreplacedemblies.ContainsKey(name))
                        resolvedreplacedemblies[name] = patchDefinition.MethodInfo.DeclaringType.ToString();
                }
            }

            // Check if any patched replacedemblies have been already resolved by the CLR
            // If there are any, they cannot be loaded by the preloader
            var patchedreplacedemblyNames =
                new
                    HashSet<string>(replacedemblies.Where(kv => patchedreplacedemblies.Contains(kv.Key)).Select(kv => kv.Value.Name.Name),
                                    StringComparer.InvariantCultureIgnoreCase);
            var earlyLoadreplacedemblies = resolvedreplacedemblies.Where(kv => patchedreplacedemblyNames.Contains(kv.Key)).ToList();

            if (earlyLoadreplacedemblies.Count != 0)
                Logger.LogWarning(new StringBuilder()
                                  .AppendLine("The following replacedemblies have been loaded too early and will not be patched by preloader:")
                                  .AppendLine(string.Join(Environment.NewLine,
                                                          earlyLoadreplacedemblies
                                                              .Select(kv =>
                                                                          $"* [{kv.Key}] (first loaded by [{kv.Value}])")
                                                              .ToArray()))
                                  .AppendLine("Expect unexpected behavior and issues with plugins and patchers not being loaded.")
                                  .ToString());

            var dumpedreplacedemblyPaths = new Dictionary<string, string>();
            // Finally, load patched replacedemblies into memory
            if (ConfigDumpreplacedemblies.Value || ConfigLoadDumpedreplacedemblies.Value)
            {
                if (!Directory.Exists(PatcherContext.DumpedreplacedembliesPath))
                    Directory.CreateDirectory(PatcherContext.DumpedreplacedembliesPath);

                foreach (var kv in replacedemblies)
                {
                    var filename = kv.Key;
                    var name = Path.GetFileNameWithoutExtension(filename);
                    var ext = Path.GetExtension(filename);
                    var replacedembly = kv.Value;

                    if (!patchedreplacedemblies.Contains(filename))
                        continue;
                    for (var i = 0;; i++)
                    {
                        var postfix = i > 0 ? $"_{i}" : "";
                        var path = Path.Combine(PatcherContext.DumpedreplacedembliesPath, $"{name}{postfix}{ext}");
                        if (!Utility.TryOpenFileStream(path, FileMode.Create, out var fs))
                            continue;
                        replacedembly.Write(fs);
                        fs.Dispose();
                        dumpedreplacedemblyPaths[filename] = path;
                        break;
                    }
                }
            }

            if (ConfigBreakBeforeLoadreplacedemblies.Value)
            {
                Logger.LogInfo($"BepInEx is about load the following replacedemblies:\n{string.Join("\n", patchedreplacedemblies.ToArray())}");
                Logger.LogInfo($"The replacedemblies were dumped into {PatcherContext.DumpedreplacedembliesPath}");
                Logger.LogInfo("Load any replacedemblies into the debugger, set breakpoints and continue execution.");
                Debugger.Break();
            }

            foreach (var kv in replacedemblies)
            {
                var filename = kv.Key;
                var replacedembly = kv.Value;

                // Note that since we only *load* replacedemblies, they shouldn't trigger dependency loading
                // Not loading all replacedemblies is very important not only because of memory reasons,
                // but because some games *rely* on that because of messed up internal dependencies.
                if (patchedreplacedemblies.Contains(filename))
                {
                    replacedembly loadedreplacedembly;

                    if (ConfigLoadDumpedreplacedemblies.Value &&
                        dumpedreplacedemblyPaths.TryGetValue(filename, out var dumpedreplacedemblyPath))
                        loadedreplacedembly = replacedembly.LoadFrom(dumpedreplacedemblyPath);
                    else
                    {
                        using var replacedemblyStream = new MemoryStream();
                        replacedembly.Write(replacedemblyStream);
                        loadedreplacedembly = replacedembly.Load(replacedemblyStream.ToArray());
                    }

                    PatcherContext.Loadedreplacedemblies.Add(filename, loadedreplacedembly);

                    Logger.LogDebug($"Loaded '{replacedembly.FullName}' into memory");
                }

                // Though we have to dispose of all replacedemblies regardless of them being patched or not
                replacedembly.Dispose();
            }

            // Finally, run all finalizers
            foreach (var replacedemblyPatcher in PatcherPluginsSafe)
                try
                {
                    replacedemblyPatcher.Finalizer();
                }
                catch (Exception ex)
                {
                    Logger.LogError($"Failed to run finalizer of {replacedemblyPatcher.Info.GUID}: {ex}");
                }
        }

19 Source : PluginManager.cs
with GNU General Public License v3.0
from BepInEx

private static IEnumerable<IPlugin> LoadPluginsFromFile(string file, string exeName)
        {
            var plugins = new List<IPlugin>();

            if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
                return plugins;

            try
            {
                var replacedembly = replacedembly.LoadFrom(file);

                foreach (var t in GetTypesSafe(replacedembly))
                    if (typeof(IPlugin).IsreplacedignableFrom(t))
                        try
                        {
                            var pluginInstance = Activator.CreateInstance(t) as IPlugin;

                            if (pluginInstance == null)
                            {
                                IPALoader.Logger.LogWarning($"[WRN] Could not load {t.FullName} because types mismatch. Please check if you have multiple instances of IPA installed.");
                                continue;
                            }

                            string[] filter = null;

                            if (pluginInstance is IEnhancedPlugin plugin)
                                filter = plugin.Filter;

                            var exeNameTrimmed = exeName.ToLower().Replace(".exe", "").Trim();
                            if (filter == null || filter.Any(f => f.ToLower().Replace(".exe", "").Trim() == exeNameTrimmed))
                                plugins.Add(pluginInstance);
                        }
                        catch (Exception e)
                        {
                            IPALoader.Logger.LogWarning($"[WARN] Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
                        }
            }
            catch (Exception e)
            {
                IPALoader.Logger.LogError($"[ERROR] Could not load {Path.GetFileName(file)}! {e}");
            }

            return plugins;
        }

19 Source : DGJMain.cs
with GNU General Public License v3.0
from Bililive

private static replacedembly OnResolvereplacedembly(object sender, ResolveEventArgs args)
        {
            replacedembly executingreplacedembly = replacedembly.GetExecutingreplacedembly();
            replacedemblyName replacedemblyName = new replacedemblyName(args.Name);

            var path = replacedemblyName.Name + ".dll";
            string filepath = Path.Combine(Utilities.BinDirectoryPath, path);

            if (replacedemblyName.CultureInfo?.Equals(CultureInfo.InvariantCulture) == false)
            { path = string.Format(@"{0}\{1}", replacedemblyName.CultureInfo, path); }

            using (Stream stream = executingreplacedembly.GetManifestResourceStream(path))
            {
                if (stream == null) { return null; }

                var replacedemblyRawBytes = new byte[stream.Length];
                stream.Read(replacedemblyRawBytes, 0, replacedemblyRawBytes.Length);
                try
                {
                    File.WriteAllBytes(filepath, replacedemblyRawBytes);
                }
                catch (Exception) { }
            }

            return replacedembly.LoadFrom(filepath);
        }

19 Source : SimplePluginManager.cs
with GNU General Public License v3.0
from BlowaXD

public IPlugin[] LoadPlugin(FileInfo file)
        {
            try
            {
                if (file == null)
                {
                    throw new ArgumentNullException(nameof(file));
                }

                replacedembly replacedembly = replacedembly.LoadFrom(file.FullName);

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

                Type[] types = replacedembly.GetTypes();
                Type pluginType = typeof(IPlugin);
                ICollection<Type> pluginTypes = types.Where(type => !type.IsInterface && !type.IsAbstract && type.GetInterface(pluginType.FullName) != null).ToArray();
                ICollection<IPlugin> plugins = new List<IPlugin>(pluginTypes.Count);
                foreach (Type type in pluginTypes)
                {
                    var plugin = (IPlugin)Activator.CreateInstance(type);
                    Log.Info($"{plugin.Name} Loaded !");
                    plugins.Add(plugin);
                }

                return plugins.ToArray();
            }
            catch
            {
                return null;
            }
        }

19 Source : SimplePluginManager.cs
with GNU General Public License v3.0
from BlowaXD

public IPlugin[] LoadPlugin(FileInfo file)
        {
            try
            {
                if (file == null)
                {
                    throw new ArgumentNullException(nameof(file));
                }

                replacedembly replacedembly = replacedembly.LoadFrom(file.FullName);

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

                Type[] types = replacedembly.GetTypes();
                Type pluginType = typeof(IPlugin);
                ICollection<Type> pluginTypes = types.Where(type => !type.IsInterface && !type.IsAbstract && type.GetInterface(pluginType.FullName) != null).ToArray();
                ICollection<IPlugin> plugins = new List<IPlugin>(pluginTypes.Count);
                foreach (Type type in pluginTypes)
                {
                    var plugin = (IPlugin)Activator.CreateInstance(type);
                    Log.Info($"{plugin.Name} Loaded !");
                    plugin.OnLoad();
                    plugins.Add(plugin);
                }

                return plugins.ToArray();
            }
            catch
            {
                return null;
            }
        }

19 Source : ConfigurationHelper.cs
with MIT License
from bonsai-rx

public static void SetreplacedemblyResolve(PackageConfiguration configuration)
        {
            var platform = GetEnvironmentPlatform();
            var configurationRoot = GetConfigurationRoot(configuration);
            foreach (var libraryFolder in configuration.LibraryFolders)
            {
                if (libraryFolder.Platform == platform)
                {
                    var libraryPath = libraryFolder.Path;
                    if (!Path.IsPathRooted(libraryPath))
                    {
                        libraryPath = Path.Combine(configurationRoot, libraryPath);
                    }
                    AddLibraryPath(libraryPath);
                }
            }

            Dictionary<string, replacedembly> replacedemblyLoadCache = null;
            ResolveEventHandler replacedemblyResolveHandler = (sender, args) =>
            {
                var replacedemblyName = new replacedemblyName(args.Name).Name;
                var replacedemblyLocation = GetreplacedemblyLocation(configuration, replacedemblyName);
                if (replacedemblyLocation != null)
                {
                    if (replacedemblyLocation.StartsWith(Uri.UriSchemeFile) && Uri.TryCreate(replacedemblyLocation, UriKind.Absolute, out Uri uri))
                    {
                        replacedemblyLoadCache ??= new Dictionary<string, replacedembly>();
                        if (!replacedemblyLoadCache.TryGetValue(uri.LocalPath, out replacedembly replacedembly))
                        {
                            var replacedemblyBytes = File.ReadAllBytes(uri.LocalPath);
                            replacedembly = replacedembly.Load(replacedemblyBytes);
                            replacedemblyLoadCache.Add(uri.LocalPath, replacedembly);
                        }
                        return replacedembly;
                    }

                    if (!Path.IsPathRooted(replacedemblyLocation))
                    {
                        replacedemblyLocation = Path.Combine(configurationRoot, replacedemblyLocation);
                    }

                    if (File.Exists(replacedemblyLocation))
                    {
                        return replacedembly.LoadFrom(replacedemblyLocation);
                    }
                }

                return null;
            };

            AppDomain.CurrentDomain.replacedemblyResolve += replacedemblyResolveHandler;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from bosima

private static JobBase CreateJobInstance(string jobClreplacedInfo, JobWrapper jobWrapper)
        {
            var jobClreplaced = jobClreplacedInfo.Split(',');
            var jobClreplacedFile = Path.Combine(jobWrapper.CurrentJobProgramPath, jobClreplaced[0]);
            var jobClreplacedName = jobClreplaced[1];
            replacedembly replacedembly = System.Reflection.replacedembly.LoadFrom(jobClreplacedFile);
            Type type = replacedembly.GetType(jobClreplacedName);
            object obj = Activator.CreateInstance(type, true);
            var job = (JobBase)obj;
            job.CopyMetaFrom(jobWrapper);
            return job;
        }

19 Source : Plugins.cs
with GNU General Public License v3.0
from brhinescot

public static ImageOutputCollection Load()
        {
            ImageOutputCollection imageOutputCollection = new ImageOutputCollection();

            foreach (string path in LoadValidreplacedemblies())
                try
                {
                    replacedembly replacedembly = replacedembly.LoadFrom(path);
                    IPersistableImageFormat imageFormatPlugin = Examinereplacedembly(replacedembly);
                    if (imageFormatPlugin != null)
                        imageOutputCollection.Add(imageFormatPlugin);
                }
                catch (FileLoadException e)
                {
                    Debug.WriteLine(e.Message);
                }
            return imageOutputCollection;
        }

19 Source : Program.cs
with MIT License
from btcpayserver

static void Main(string[] args)
        {
            if (args.Length < 3)
            {
                Console.WriteLine("Usage: btcpay-plugin [directory of compiled plugin] [name of plugin] [packed plugin output directory]");
                return;
            }
            var directory = args[0];
            var name = args[1];
            var outputDir = args[2];
            var outputFile = Path.Combine(outputDir, name);
            var rootDLLPath = Path.Combine(directory, name +".dll");
            if (!File.Exists(rootDLLPath) )
            {
                throw new Exception($"{rootDLLPath} could not be found");
            }

            var replacedembly = replacedembly.LoadFrom(rootDLLPath);
            var extension = GetAllExtensionTypesFromreplacedembly(replacedembly).FirstOrDefault();
            if (extension is null)
            {
                throw new Exception($"{rootDLLPath} is not a valid plugin");
            }

            var loadedPlugin = (IBTCPayServerPlugin)Activator.CreateInstance(extension);
            var json = JsonSerializer.Serialize(loadedPlugin);
            Directory.CreateDirectory(outputDir);
            if (File.Exists(outputFile + ".btcpay"))
            {
                File.Delete(outputFile + ".btcpay");
            }
            ZipFile.CreateFromDirectory(directory, outputFile + ".btcpay", CompressionLevel.Optimal, false);
            File.WriteAllText(outputFile + ".btcpay.json", json);
            Console.WriteLine($"Created {outputFile}.btcpay at {directory}");
        }

19 Source : ExtensionsAssembly.cs
with GNU General Public License v3.0
from caioavidal

[MethodImpl(MethodImplOptions.NoInlining)]
        public static void LoadFromDll(string replacedemblyName)
        {
            if (string.IsNullOrWhiteSpace(replacedemblyName)) return;
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, replacedemblyName);

            if (!File.Exists(path)) return;

            replacedembly.LoadFrom(path);
        }

19 Source : AutomationFactory.cs
with MIT License
from CamSoper

public static IEnumerable<IAutomation> GetAutomations(HubEvent evt, HomeAutomationPlatform hub)
        {
            /*
             *  Get the types from the replacedembly
             *      where the type implements IAutomation and
             *          the type has trigger attributes
             *              where the trigger attribute names a mapped device that matches the device that caused the event
             *                  and the attribute also names a Capability that matches the device that caused the event
             *          and the count of the matching trigger attributes is greater than 0
             */
            IEnumerable<Type> typeCollection = replacedembly.LoadFrom(_automationreplacedembly).GetTypes() 
                .Where(t => typeof(IAutomation).IsreplacedignableFrom(t) && 
                    (t.GetCustomAttributes<TriggerDeviceAttribute>() 
                        .Where(a => hub.LookupDeviceId(a.DeviceMappedName) == evt.DeviceId &&
                            a.Capability.ToString().ToLower() == evt.Name.ToLower()))
                    .Count() > 0);
            foreach (Type automation in typeCollection)
            {
                var thing = Activator.CreateInstance(automation, new Object[] { hub, evt });
                if (thing is IAutomation automationSource)
                    yield return automationSource;
            }
        }

19 Source : AlgorithmNameConverter.cs
with Apache License 2.0
from Capnode

public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));

            var model = context.Instance as StrategyModel;
            string replacedemblyPath = MainService.FullExePath(model?.AlgorithmLocation);
            if (string.IsNullOrEmpty(replacedemblyPath)) return null;

            try
            {
                replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);

                //Get the list of extention clreplacedes in the library: 
                List<string> extended = Loader.GetExtendedTypeNames(replacedembly);
                List<string> list = replacedembly.ExportedTypes
                    .Where(m => extended.Contains(m.FullName))
                    .Select(m => m.Name)
                    .ToList();
                list.Sort();
                return new StandardValuesCollection(list);
            }
            catch (Exception)
            {
            }

            string algorithm = Path.GetFileNameWithoutExtension(replacedemblyPath);
            var algorithms = new List<string>() { algorithm };
            return new StandardValuesCollection(algorithms);
        }

19 Source : StrategyViewModel.cs
with Apache License 2.0
from Capnode

private void AlgorithmNameChanged(string algorithmName)
        {
            StrategyNameChanged();
            RaiseCommands();
            if (string.IsNullOrEmpty(algorithmName)) return;

            string replacedemblyPath = MainService.FullExePath(Model.AlgorithmLocation);
            if (string.IsNullOrEmpty(replacedemblyPath)) return;

            Parameters.Clear();
            try
            {
                replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
                if (replacedembly == null) return;

                IEnumerable<Type> type = replacedembly
                    .GetTypes()
                    .Where(m => m.Name.Equals(algorithmName, StringComparison.OrdinalIgnoreCase));
                if (type == null || !type.Any()) return;

                foreach (KeyValuePair<string, string> parameter in ParameterAttribute.GetParametersFromType(type.First()))
                {
                    string parameterName = parameter.Key;
                    string parameterType = parameter.Value;

                    if (_exclude.Contains(parameterName)) continue;

                    ParameterModel parameterModel = Model
                        .Parameters
                        .FirstOrDefault(m => m.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase));
                    if (parameterModel == null)
                    {
                        parameterModel = new ParameterModel() { Name = parameterName };
                    }

                    var parameterViewModel = new ParameterViewModel(parameterModel);
                    Parameters.Add(parameterViewModel);
                }
            }
            catch (Exception)
            {
            }

            RaisePropertyChanged(() => Parameters);
        }

19 Source : StrategyViewModel.cs
with Apache License 2.0
from Capnode

private void DoCloneAlgorithm()
        {
            try
            {
                IsBusy = true;
                DataToModel();

                // Load replacedemblies of algorithms
                string replacedemblyPath = MainService.FullExePath(Model.AlgorithmLocation);
                replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
                if (string.IsNullOrEmpty(Model.Name))
                {
                    Model.Name = replacedembly.ManifestModule.Name;
                }

                //Get the list of extention clreplacedes in the library: 
                List<string> extended = Loader.GetExtendedTypeNames(replacedembly);
                List<string> list = replacedembly.ExportedTypes
                    .Where(m => extended.Contains(m.FullName))
                    .Select(m => m.Name)
                    .ToList();
                list.Sort();

                // Iterate and clone strategies
                foreach (string algorithm in list)
                {
                    if (algorithm.Equals(Model.AlgorithmName, StringComparison.OrdinalIgnoreCase))
                        continue; // Skip this algorithm

                    var strategyModel = new StrategyModel(Model)
                    {
                        AlgorithmName = algorithm,
                        Name = null
                    };
                    var strategy = new StrategyViewModel(this, strategyModel, _markets, _settings);
                    Strategies.Add(strategy);
                }
            }
            finally
            {
                IsBusy = false;
            }
        }

19 Source : Loader.cs
with Apache License 2.0
from Capnode

private bool TryCreateILAlgorithm(string replacedemblyPath, out IAlgorithm algorithmInstance, out string errorMessage)
        {
            errorMessage = "";
            algorithmInstance = null;

            try
            {
                //Load the replacedembly:
                Log.Trace("Loader.TryCreateILAlgorithm(): Loading only the algorithm replacedembly");
                replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
                if (replacedembly == null)
                {
                    errorMessage = "replacedembly is null.";
                    Log.Error("Loader.TryCreateILAlgorithm(): replacedembly is null");
                    return false;
                }

                //Get the list of extention clreplacedes in the library:
                var types = GetExtendedTypeNames(replacedembly);
                Log.Debug("Loader.TryCreateILAlgorithm(): replacedembly types: " + string.Join(",", types));

                //No extensions, nothing to load.
                if (types.Count == 0)
                {
                    errorMessage = "Algorithm type was not found.";
                    Log.Error("Loader.TryCreateILAlgorithm(): Types array empty, no algorithm type found.");
                    return false;
                }

                if (types.Count > 1)
                {
                    // reshuffle type[0] to the resolved typename
                    types[0] = _multipleTypeNameResolverFunction.Invoke(types);

                    if (string.IsNullOrEmpty(types[0]))
                    {
                        errorMessage = "Algorithm type name not found, or unable to resolve multiple algorithm types to a single type. Please verify algorithm type name matches the algorithm name in the configuration file and that there is one and only one clreplaced derived from QCAlgorithm.";
                        Log.Error($"Loader.TryCreateILAlgorithm(): {errorMessage}");
                        return false;
                    }
                }
                //Load the replacedembly into this AppDomain:
                algorithmInstance = (IAlgorithm)replacedembly.CreateInstance(types[0], true);

                if (algorithmInstance != null)
                {
                    Log.Trace("Loader.TryCreateILAlgorithm(): Loaded " + algorithmInstance.GetType().Name);
                }

            }
            catch (ReflectionTypeLoadException err)
            {
                Log.Error(err);
                Log.Error("Loader.TryCreateILAlgorithm(1): " + err.LoaderExceptions[0]);
                if (err.InnerException != null) errorMessage = err.InnerException.Message;
            }
            catch (Exception err)
            {
                errorMessage = "Algorithm type name not found, or unable to resolve multiple algorithm types to a single type. Please verify algorithm type name matches the algorithm name in the configuration file and that there is one and only one clreplaced derived from QCAlgorithm.";
                Log.Error($"Loader.TryCreateILAlgorithm(): {errorMessage}\n{err.InnerException ?? err}");
                return false;
            }

            return true;
        }

19 Source : Loader.cs
with GNU General Public License v3.0
from cc004

private static replacedembly Load(string filename)
        {
            Log($"loading plugin from {filename}");
            return replacedembly.LoadFrom(filename);
        }

19 Source : CustomAutofacModule.cs
with Apache License 2.0
from ccnetcore

private replacedembly GetDll(string replaced)
        {
            var basePath = AppContext.BaseDirectory;
            var servicesDllFile = Path.Combine(basePath, replaced);
            if (!(File.Exists(servicesDllFile)))
            {
                var msg = "service.dll 丢失,请编译后重新生成。";
                throw new Exception(msg);
            }
            return   replacedembly.LoadFrom(servicesDllFile); ;
        }

19 Source : CompressUnitManager.cs
with Apache License 2.0
from cdy816

public void Init()
        {
            string cfgpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "Compress.cfg");
            if (System.IO.File.Exists(cfgpath))
            {
                XElement xx = XElement.Load(cfgpath);
                foreach (var vv in xx.Elements())
                {
                    try
                    {
                        string dll = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), vv.Attribute("File").Value);
                        string main = vv.Attribute("MainClreplaced").Value;
                        if (System.IO.File.Exists(dll))
                        {
                            var driver = replacedembly.LoadFrom(dll).CreateInstance(main) as CompressUnitbase;
                            if(driver!=null)
                            Registor(driver);
                        }
                        else
                        {
                            LoggerService.Service.Warn("CompressUnitManager", dll + " is not exist.");

                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerService.Service.Erro("DriverManager", ex.StackTrace);
                    }
                }
            }
        }

19 Source : CompressUnitManager2.cs
with Apache License 2.0
from cdy816

public void Init()
        {
            mCompressUnit.Clear();
            string cfgpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "Compress.cfg");
            if (System.IO.File.Exists(cfgpath))
            {
                XElement xx = XElement.Load(cfgpath);
                foreach (var vv in xx.Elements())
                {
                    try
                    {
                        string dll = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), vv.Attribute("File").Value);
                        string main = vv.Attribute("MainClreplaced").Value;
                        if (System.IO.File.Exists(dll))
                        {
                            var driver = replacedembly.LoadFrom(dll).CreateInstance(main) as CompressUnitbase2;
                            if(driver!=null)
                            Registor(driver);
                        }
                        else
                        {
                            LoggerService.Service.Warn("CompressUnitManager", dll + " is not exist.");
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerService.Service.Erro("DriverManager", ex.StackTrace);
                    }
                }
            }
        }

19 Source : DataFileSeriserManager.cs
with Apache License 2.0
from cdy816

public void Init()
        {
            mDataFiles.Clear();
            string cfgpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "DataFileSerise.cfg");
            if (System.IO.File.Exists(cfgpath))
            {
                XElement xx = XElement.Load(cfgpath);
                foreach (var vv in xx.Elements())
                {
                    try
                    {
                        string dll = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), vv.Attribute("File").Value);
                        string main = vv.Attribute("MainClreplaced").Value;
                        if (System.IO.File.Exists(dll))
                        {
                            var driver = replacedembly.LoadFrom(dll).CreateInstance(main) as DataFileSeriserbase;
                            Registe(driver.Name,driver);
                        }
                        else
                        {
                            LoggerService.Service.Warn("CompressUnitManager", dll + " is not exist.");

                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerService.Service.Erro("DriverManager", ex.StackTrace);
                    }
                }
            }
        }

19 Source : DriverManager.cs
with Apache License 2.0
from cdy816

public void Init()
        {
            string cfgpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),"Config", "Driver.cfg");
            if(System.IO.File.Exists(cfgpath))
            {
                XElement xx = XElement.Load(cfgpath);
                foreach(var vv in xx.Elements())
                {
                    try
                    {
                        string dll = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),vv.Attribute("File").Value);
                        string main = vv.Attribute("MainClreplaced").Value;
                        if (System.IO.File.Exists(dll))
                        {
                            var driver = replacedembly.LoadFrom(dll).CreateInstance(main) as IProducterDriver;
                            if (!mDrivers.ContainsKey(driver.Name))
                            {
                                mDrivers.Add(driver.Name, driver);
                                driver.Init();
                            }
                        }
                        else
                        {
                            LoggerService.Service.Warn("DriverManager", dll+" is not exist.");

                        }
                    }
                    catch(Exception ex)
                    {
                        LoggerService.Service.Erro("DriverManager", ex.StackTrace);
                    }
                }
            }
        }

19 Source : ChannelFactory.cs
with Apache License 2.0
from cdy816

public void LoadForDevelop()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "ChannelDevelop.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as ICommChannelDevelopForFactory;

                        if (asb!=null && !mDevelopManagers.ContainsKey(asb.TypeName))
                        {
                            mDevelopManagers.Add(asb.TypeName, asb);
                        }

                    }
                }
            }
        }

19 Source : ChannelFactory2.cs
with Apache License 2.0
from cdy816

public void LoadForRun()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "ChannelRuntime.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as ICommChannel2ForFactory;

                        if (!mRuntimeManagers.ContainsKey(asb.TypeName))
                        {
                            mRuntimeManagers.Add(asb.TypeName, asb);
                        }

                    }
                }
            }
        }

19 Source : DriverManager.cs
with Apache License 2.0
from cdy816

public void Init(IRealTagProduct tagDriverService,ITagHisValueProduct hisValueService)
        {
            mTagDriverService = tagDriverService;
            mHisValueDriverService = hisValueService;
            string cfgpath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),"Config", "Driver.cfg");
            if(System.IO.File.Exists(cfgpath))
            {
                XElement xx = XElement.Load(cfgpath);
                foreach(var vv in xx.Elements())
                {
                    try
                    {
                        string dll = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),vv.Attribute("File").Value);
                        string main = vv.Attribute("MainClreplaced").Value;
                        if (System.IO.File.Exists(dll))
                        {
                            var driver = replacedembly.LoadFrom(dll).CreateInstance(main) as IProducterDriver;
                            if (!mDrivers.ContainsKey(driver.Name))
                            {
                                mDrivers.Add(driver.Name, driver);
                            }
                        }
                        else
                        {
                            LoggerService.Service.Warn("DriverManager", dll+" is not exist.");

                        }
                    }
                    catch(Exception ex)
                    {
                        LoggerService.Service.Erro("DriverManager", ex.StackTrace);
                    }
                }
            }
        }

19 Source : DriverFactory.cs
with Apache License 2.0
from cdy816

public void LoadForRun()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "DriverRuntime.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as IDriverForFactory;
                        if (!mRuntimeManagers.ContainsKey(asb.TypeName))
                        {
                            mRuntimeManagers.Add(asb.TypeName, asb);
                        }
                    }
                }
            }
        }

19 Source : LinkFactory.cs
with Apache License 2.0
from cdy816

public void LoadForDevelop()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),"Config", "LinkDevelop.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        try
                        {
                            var asb = replacedembly.LoadFrom(afile);
                            var css = asb.CreateInstance(cls) as ILinkDevelopForFactory;

                            if (!mDevelopManagers.ContainsKey(css.TypeName))
                            {
                                mDevelopManagers.Add(css.TypeName, css);
                            }
                        }
                        catch(Exception ex)
                        {
                            Debug.Print(ex.Message);
                        }

                    }
                }
            }
        }

19 Source : ApiFactory.cs
with Apache License 2.0
from cdy816

public void LoadForRun()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "ApiRuntime.cfg");
            if(System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as IApiForFactory;
                        
                        if(!mRuntimeManagers.ContainsKey(asb.TypeName))
                        {
                            mRuntimeManagers.Add(asb.TypeName, asb);
                        }

                    }
                }
            }
        }

19 Source : ApiFactory.cs
with Apache License 2.0
from cdy816

public void LoadForDevelop()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location),"Config", "ApiDevelop.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        try
                        {
                            var asb = replacedembly.LoadFrom(afile);
                            var css = asb.CreateInstance(cls) as IApiDevelopForFactory;

                            if (!mDevelopManagers.ContainsKey(css.TypeName))
                            {
                                mDevelopManagers.Add(css.TypeName, css);
                            }
                        }
                        catch(Exception ex)
                        {
                            Debug.Print(ex.Message);
                        }

                    }
                }
            }
        }

19 Source : ChannelFactory.cs
with Apache License 2.0
from cdy816

public void LoadForRun()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "ChannelRuntime.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as ICommChannelForFactory;

                        if (!mRuntimeManagers.ContainsKey(asb.TypeName))
                        {
                            mRuntimeManagers.Add(asb.TypeName, asb);
                        }

                    }
                }
            }
        }

19 Source : DriverFactory.cs
with Apache License 2.0
from cdy816

public void LoadForDevelop()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "DriverDevelop.cfg");
            if (System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as IDriverDevelopForFactory;
                        if (!mDevelopManagers.ContainsKey(asb.TypeName))
                        {
                            mDevelopManagers.Add(asb.TypeName, asb);
                        }
                    }
                }
            }
        }

19 Source : LinkFactory.cs
with Apache License 2.0
from cdy816

public void LoadForRun()
        {
            string sfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().replacedembly.Location), "Config", "LinkRuntime.cfg");
            if(System.IO.File.Exists(sfile))
            {
                XElement xx = XElement.Load(sfile);
                foreach (var vv in xx.Elements())
                {
                    string replaced = vv.Attribute("replacedembly").Value;
                    string cls = vv.Attribute("Clreplaced").Value;
                    var afile = GetreplacedemblyPath(replaced);
                    if (System.IO.File.Exists(afile) && !string.IsNullOrEmpty(cls))
                    {
                        var asb = replacedembly.LoadFrom(afile).CreateInstance(cls) as ILinkForFactory;
                        
                        if(!mRuntimeManagers.ContainsKey(asb.TypeName))
                        {
                            mRuntimeManagers.Add(asb.TypeName, asb);
                        }

                    }
                }
            }
        }

19 Source : ClrTypeOptions.cs
with MIT License
from ch-robinson

public static Type ResolveType(this IClrTypeOptions options)
        {
            var replacedemblies = options.replacedemblyNames
                .Select(name =>
                {
                    try
                    {
                        return replacedembly.Load(name);
                    }
                    catch (FileNotFoundException)
                    {
                        // nbd
                    }
                    catch (FileLoadException)
                    {
                        // also nbd
                    }

                    try
                    {
                        return replacedembly.LoadFrom(Path.GetFullPath(name));
                    }
                    catch (FileNotFoundException)
                    {
                        throw new ProgramException(message: $"{name} could not be found. Make sure that you’ve provided either a recognizable name (e.g. System.Runtime) or a valid replacedembly path.");
                    }
                    catch (BadImageFormatException)
                    {
                        throw new ProgramException(message: $"{name} is not valid. Check that the path you’re providing points to a valid replacedembly file.");
                    }
                })
                .Append(typeof(object).replacedembly) // ensure System.Runtime is included by default
                .ToDictionary(replacedembly => replacedembly.GetName());

            try
            {
                return Type.GetType(
                    options.TypeName,
                    replacedemblyResolver: name => replacedemblies.GetValueOrDefault(name),
                    typeResolver: (replacedembly, name, ignoreCase) =>
                    {
                        if (replacedembly == null)
                        {
                            foreach (var candidate in replacedemblies.Values)
                            {
                                if (candidate.GetType(name, ignoreCase: ignoreCase, throwOnError: false) is Type result)
                                {
                                    return result;
                                }
                            }

                            return null;
                        }

                        return replacedembly.GetType(name, ignoreCase: ignoreCase, throwOnError: false);
                    },
                    ignoreCase: true,
                    throwOnError: true
                );
            }
            catch (TypeLoadException)
            {
                throw new ProgramException(message: "The type could not be found. You may need to provide additional replacedemblies.");
            }
        }

19 Source : Program.cs
with MIT License
from chanjunweimy

private static void DownloadPlugins(string[] args)
        {
            var downloaderPath = "downloader/Todo.PluginDownloader.dll";
            if (!File.Exists(downloaderPath))
            {
                return;
            }

            var downloaderreplacedembly = replacedembly.LoadFrom(Path.GetFullPath(downloaderPath));
            var type = downloaderreplacedembly.GetType("Todo.PluginDownloader.Program");
            var m = type.GetMethod("Execute");
            m.Invoke(null, new object[] {args});
        }

19 Source : Neo4JSourceGenerator.TypeInitialization.cs
with MIT License
from ChilliCream

private static replacedembly? CurrentDomainOnreplacedemblyResolve(
            object sender,
            ResolveEventArgs args)
        {
            try
            {
                var replacedemblyName = new replacedemblyName(args.Name);
                var path = Combine(_location, replacedemblyName.Name + _dll);
                return replacedembly.LoadFrom(path);
            }
            catch
            {
                return null;
            }
        }

19 Source : CSharpClientGenerator.cs
with MIT License
from ChilliCream

private static replacedembly? CurrentDomainOnreplacedemblyResolve(
            object sender,
            ResolveEventArgs args)
        {
            try
            {
                var replacedemblyName = new replacedemblyName(args.Name);
                var path = IOPath.Combine(_location, replacedemblyName.Name + ".dll");
                return replacedembly.LoadFrom(path);
            }
            catch
            {
                return null;
            }
        }

19 Source : AppDomainTypeFinder.cs
with MIT License
from chinabeacon

public IEnumerable<replacedembly> FindreplacedembliesWithAttribute<T>(DirectoryInfo replacedemblyPath)
        {
            var replacedemblies = (from f in Directory.GetFiles(replacedemblyPath.FullName, "*.dll")
                              select replacedembly.LoadFrom(f)
                                  into replacedembly
                              let customAttributes = replacedembly.GetCustomAttributes(typeof(T), false)
                              where customAttributes.Any()
                              select replacedembly).ToList();
            return FindreplacedembliesWithAttribute<T>(replacedemblies);
        }

19 Source : Init.cs
with MIT License
from chrisnas

private static void ForcereplacedemblyLoad(replacedemblyName replacedemblyName)
        {
            var codeBase = replacedemblyName.CodeBase;

            if (codeBase.StartsWith("file://"))
            {
                codeBase = codeBase.Substring(8).Replace('/', '\\');
            }

            ResolveEventHandler replacedemblyResolve = (sender, args) => args.Name == replacedemblyName.FullName ? replacedembly.LoadFrom(codeBase) : null;

            AppDomain.CurrentDomain.replacedemblyResolve += replacedemblyResolve;

            replacedembly.Load(replacedemblyName.FullName);

            AppDomain.CurrentDomain.replacedemblyResolve -= replacedemblyResolve;
        }

19 Source : Program.cs
with MIT License
from chsienki

private static void EnsureOtherreplacedembliesLoad()
        {
            // force load msbuild and get its location
            using var workspace = MSBuildWorkspace.Create();
            var msbuild = replacedemblyLoadContext.Default.replacedemblies.Single(a => a.GetName().Name == "Microsoft.Build");
            var msBuildLocation = Path.GetDirectoryName(msbuild.Location) ?? string.Empty;

            // add a loader that will try and find the replacedembly in the same location if we didn't find it
            replacedemblyLoadContext.Default.Resolving += (replacedemblyLoadContext arg1, System.Reflection.replacedemblyName arg2) =>
            {
                var attemptedLocation = Path.Combine(msBuildLocation, arg2.Name + ".dll");
                if (File.Exists(attemptedLocation))
                {
                    return replacedembly.LoadFrom(attemptedLocation);
                }
                return null;
            };
        }

19 Source : ManagerProxyBuilder.cs
with MIT License
from Ciastex

public Type WriteDynamicreplacedemblyAndLoadProxyType()
        {
            var asmLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var targetAsmPath = Path.Combine(asmLocation!, Resources.Proxy.replacedemblyFileName);

            if (File.Exists(targetAsmPath))
            {
                File.Delete(targetAsmPath);
            }

            ProxyreplacedemblyDefinition.Write(targetAsmPath);

            var asm = replacedembly.LoadFrom(targetAsmPath);
            return asm.GetTypes().First();
        }

19 Source : Bootstrap.cs
with MIT License
from Ciastex

public static void Initialize()
        {
            foreach (var arg in Environment.GetCommandLineArgs())
            {
                if (arg == StartupArguments.DisableFancyColors)
                {
                    ConsoleAllocator.FancyColorsEnabled = false;
                }
                
                if (arg == StartupArguments.AllocateConsole)
                {
                    ConsoleAllocator.Redirect();
                    ConsoleEnabled = true;
                }
            }

            var version = FileVersionInfo.GetVersionInfo(replacedembly.GetExecutingreplacedembly().Location).FileVersion;

            EarlyLog.Info($"Centrifuge bootstrap for Reactor Mod Loader and API. Version {version}. Unity {ApplicationBridge.UnityVersion}");

            if (ConsoleEnabled)
                EarlyLog.Info($"Diagnostics mode enabled. Remove '{StartupArguments.AllocateConsole}' command line argument to disable.");

            if (ApplicationBridge.GetRunningUnityGeneration() == UnityGeneration.Unity4OrOlder)
            {
                EarlyLog.Error("Centrifuge requires Unity 5 or newer. Terminating.");
                return;
            }

            EarlyLog.Info("Trying to find Centrifuge Reactor DLL...");
            var reactorPath = GetCrossPlatformCompatibleReactorPath();
            if (!File.Exists(reactorPath))
            {
                EarlyLog.Error($"Centrifuge Reactor DLL could not be found at '{reactorPath}'. Mods will not be loaded.");
                return;
            }

            Type proxyType;
            try
            {
                EarlyLog.Info("Validating and loading Centrifuge Reactor DLL...");
                replacedembly.LoadFrom(reactorPath);

                EarlyLog.Info("Building manager proxy component for Unity Engine...");
                proxyType = new ManagerProxyBuilder().WriteDynamicreplacedemblyAndLoadProxyType();

                if (proxyType == null)
                {
                    EarlyLog.Info("Failed.");
                    return;
                }
            }
            catch (ReflectionTypeLoadException rtle)
            {
                EarlyLog.Exception(rtle);

                EarlyLog.Info(" --- LOADER EXCEPTIONS FOLLOW --- ");
                foreach (var lex in rtle.LoaderExceptions)
                {
                    EarlyLog.Exception(lex);
                }
                return;
            }
            catch (Exception ex)
            {
                EarlyLog.Exception(ex);
                return;
            }

            try
            {
                EarlyLog.Info("Creating Reactor Manager GameObject...");
                ReactorManagerObject = GameObjectBridge.CreateGameObject("com.github.ciastex/ReactorModLoaderProxy");
            }
            catch (Exception e)
            {
                EarlyLog.Exception(e);
                return;
            }

            EarlyLog.Info("About to add component to Reactor Manager GameObject.");
            object proxyComponent;
            try
            {
                proxyComponent = GameObjectBridge.AttachComponentTo(ReactorManagerObject, proxyType);
            }
            catch (Exception e)
            {
                EarlyLog.Exception(e);
                return;
            }

            if (proxyComponent == null)
            {
                EarlyLog.Error("Manager proxy component has failed to attach when it wasn't really supposed to fail on Unity 5+.");

                EarlyLog.Info("Report this stuff to https://github.com/Ciastex/Centrifuge/issues.");
                EarlyLog.Info("Make sure to check for and - if existing - include your game's output_log.txt (and/or Player.log) in the report.");
                EarlyLog.Info("Definitely include this entire log as well.");
                EarlyLog.Info("Otherwise I'll be very angry and ask you for this stuff in a very rude manner.");

                if (Platform.IsUnix())
                {
                    EarlyLog.Info("Look in ~/.config/unity3d/<CompanyName>/<GameName>/ for any .log and/or .txt files.");
                }
                else
                {
                    var path = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "\\AppData\\LocalLow");
                    EarlyLog.Info($"Look in {path}\\<CompanyName>\\<GameName> for any .log and/or .txt files.");
                }
            }

            EarlyLog.Info(" --- BOOTSTRAPPER FINISHED --- ");
        }

19 Source : GameSupportLoader.cs
with MIT License
from Ciastex

public void Initialize()
        {
            Log.Info("Looking for GSLs...");

            var gameSupportLibs = Directory.GetFiles(Defaults.ManagerGameSupportDirectory, "*.dll");

            if (gameSupportLibs.Any())
            {
                Log.Info("GSLs found. Trying to initialize...");
            }

            foreach (var libPath in gameSupportLibs)
            {
                Log.Debug(libPath);

                try
                {
                    var asm = replacedembly.LoadFrom(libPath);

                    if (InitializeGameSupport(asm))
                    {
                        Log.Info($"GSL '{libPath}' initialized.");
                    }
                }
                catch (ReflectionTypeLoadException rtle)
                {
                    Log.ReflectionTypeLoadException(rtle);
                }
                catch (Exception e)
                {
                    Log.Error($"Failed to initialize game support: {e.Message}");
                    Log.Exception(e);
                }
            }
            
            Manager.OnGslInitFinished();
        }

19 Source : ModLoader.cs
with MIT License
from Ciastex

private void LoadMod(LoadData data)
        {
            var rootPath = data.RootDirectory;
            var manifest = data.Manifest;

            var targetModulePath = Path.Combine(rootPath, manifest.ModuleFileName);
            Log.Info($"Now trying to load '{targetModulePath}'");

            if (!File.Exists(targetModulePath))
            {
                Log.Error($"That was quick... Target DLL file does not exist.");
                return;
            }

            if (manifest.RequiredGSLs != null && manifest.RequiredGSLs.Length > 0)
            {
                foreach (var id in manifest.RequiredGSLs)
                {
                    if (!GameSupportLoader.IsGameSupportLibraryPresent(id))
                    {
                        Log.Error($"The mod requires a GSL with ID that is not present: {id}");
                        Log.Error("This mod will not be loaded. You need to install that GSL before loading that mod.");

                        return;
                    }
                }
            }

            if (manifest.Dependencies != null && manifest.Dependencies.Length > 0)
            {
                if (!LoadDependenciesForMod(rootPath, manifest.Dependencies))
                {
                    Log.Error("Failed to load dependencies.");
                    return;
                }
            }

            replacedembly modreplacedembly;
            try
            {
                modreplacedembly = replacedembly.LoadFrom(targetModulePath);
            }
            catch (ReflectionTypeLoadException rtle)
            {
                Log.ReflectionTypeLoadException(rtle);
                return;
            }
            catch (Exception e)
            {
                Log.Exception(e);
                return;
            }

            EnsureSingleEntryPoint(modreplacedembly);

            Type[] types;
            try
            {
                types = modreplacedembly.GetTypes();
            }
            catch (ReflectionTypeLoadException rtle)
            {
                Log.ReflectionTypeLoadException(rtle);
                return;
            }

            var entryPointType = FindEntryPointType(types);
            var entryPointInfo = GetEntryPointAttribute(entryPointType);

            EnsureModIdValid(entryPointInfo.ModID);

            var initMethodInfo = entryPointType.GetMethod(entryPointInfo.InitializerName, new Type[] { typeof(IManager) });
            if (initMethodInfo == null)
            {
                Log.Error($"Initializer method '{entryPointInfo.InitializerName}' accepting parameter of type 'IManager' not found.");
                return;
            }

            var messageHandlers = FindMessageHandlers(types);
            foreach (var messageHandler in messageHandlers)
            {
                Messenger.RegisterHandlerFor(messageHandler.ModID, messageHandler.MessageName, messageHandler.Method);
                Log.Info($"Registered message handler <{messageHandler.Method.Name}> for '{messageHandler.ModID}:{messageHandler.MessageName}'");
            }

            var modHost = new ModHost
            {
                replacedembly = modreplacedembly,
                ModID = entryPointInfo.ModID,
                LoadData = data,
                Instance = null,
                GameObject = null
            };

            var dealingWithGameObject = MonoBehaviourBridge.MonoBehaviourType.IsreplacedignableFrom(entryPointType);
            if (dealingWithGameObject)
            {
                modHost.GameObject = GameObjectBridge.CreateGameObject(entryPointInfo.ModID);
                GameObjectBridge.DontDestroyOnLoad(modHost.GameObject);

                if (entryPointInfo.AwakeAfterInitialize)
                {
                    GameObjectBridge.SetActive(modHost.GameObject, false);
                }

                modHost.Instance = GameObjectBridge.AttachComponentTo(modHost.GameObject, entryPointType);
            }
            else
            {
                var instance = Activator.CreateInstance(entryPointType);
                modHost.Instance = instance;
            }

            var initializer = entryPointType.GetMethod(
                entryPointInfo.InitializerName,
                new Type[] { typeof(IManager) }
            );

            modHost.replacedetLoaderMethod = entryPointType.GetMethod(
                entryPointInfo.LoaderMethodName,
                new Type[] { }
            );

            if (initializer != null)
            {
                Log.Info($"Now calling initializer method '{initializer.Name}' in '{modHost.replacedembly.GetName().Name}'");

                try
                {
                    var args = new object[] { Manager };

                    if (initializer.IsStatic)
                    {
                        initializer.Invoke(null, args);
                    }
                    else
                    {
                        initializer.Invoke(modHost.Instance, args);
                    }
                }
                catch (Exception e)
                {
                    Log.Error("The initializer method has exploded spectacularly. Centrifuge and other mods will still work, though.");
                    Log.Exception(e);

                    if (dealingWithGameObject)
                        GameObjectBridge.Destroy(modHost.GameObject);

                    return;
                }
            }
            else
            {
                Log.Warning($"Did not find the initializer method '{entryPointInfo.InitializerName}' for Mod ID '{modHost.ModID}'. Seems like it doesn't exist. Loaded the mod anyway.");
            }

            if (dealingWithGameObject && entryPointInfo.AwakeAfterInitialize)
                GameObjectBridge.SetActive(modHost.GameObject, true);

            Registry.RegisterMod(modHost);
            Log.Info("Mod has been initialized and registered sucessfully.");

            Manager.OnModInitialized(modHost.ToExchangeableApiObject());
        }

See More Examples