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
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private static ResolveEventHandler GetreplacedemblyResolverForDirectory(string dir) => (asmSender, asmArgs) => {
if (asmArgs.Name == null)
return null;
string name = new replacedemblyName(asmArgs.Name).Name ?? asmArgs.Name;
string path = Path.Combine(dir, name + ".dll");
if (!File.Exists(path))
path = Path.Combine(dir, name + ".exe");
return File.Exists(path) ? replacedembly.LoadFrom(path) : null;
};
19
View Source File : MainActivity.cs
License : Microsoft Public License
Project Creator : 0x0ade
License : Microsoft Public License
Project Creator : 0x0ade
public static void SDL_Main()
{
if (string.IsNullOrEmpty(Instance.GamePath))
{
AlertDialog dialog = null;
Instance.RunOnUiThread(() =>
{
using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("Game not found: ").AppendLine(Game);
foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
{
stringBuilder.AppendLine();
stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
}
dialogBuilder.SetMessage(stringBuilder.ToString());
dialogBuilder.SetCancelable(false);
dialog = dialogBuilder.Show();
}
});
while (dialog == null || dialog.IsShowing)
{
System.Threading.Thread.Sleep(0);
}
dialog.Dispose();
return;
}
// Replace the following with whatever was in your Program.Main method.
/*/
using (TestGame game = new TestGame())
{
game.Run();
}
/*/
replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
/**/
}
19
View Source File : LinkUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void BuildLink()
{
List<replacedembly> replacedemblieList = new List<replacedembly>();
replacedemblieList.Add(typeof(Object).replacedembly);
replacedemblieList.Add(typeof(UnityEngine.Object).replacedembly);
replacedemblieList.Add(typeof(Transform).replacedembly);
replacedemblieList.Add(typeof(GameObject).replacedembly);
replacedemblieList.Add(typeof(Image).replacedembly);
replacedemblieList.Add(typeof(Init).replacedembly);
string[] filePaths = Directory.GetFiles("replacedets", "*.dll", SearchOption.AllDirectories);
foreach (string item in filePaths)
{
if (item.ToLower().Contains("editor") || item.ToLower().Contains("plugins"))
{
continue;
}
replacedemblieList.Add(replacedembly.LoadFrom(item));
}
replacedemblieList = replacedemblieList.Distinct().ToList();
XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
XmlElement linkerElement = xmlDoreplacedent.CreateElement("linker");
foreach (replacedembly item in replacedemblieList)
{
XmlElement replacedemblyElement = xmlDoreplacedent.CreateElement("replacedembly");
replacedemblyElement.SetAttribute("fullname", item.GetName().Name);
foreach (Type typeItem in item.GetTypes())
{
if (typeItem.FullName == "Win32")
{
continue;
}
XmlElement typeElement = xmlDoreplacedent.CreateElement("type");
typeElement.SetAttribute("fullname", typeItem.FullName);
typeElement.SetAttribute("preserve", "all");
//增加子节点
replacedemblyElement.AppendChild(typeElement);
}
linkerElement.AppendChild(replacedemblyElement);
}
xmlDoreplacedent.AppendChild(linkerElement);
string path = "replacedets/link.xml";
if (File.Exists(path))
{
File.Delete(path);
}
xmlDoreplacedent.Save(path);
}
19
View Source File : SCaddins.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
private static ImageSource LoadPNGImageSource(string sourceName, string path)
{
try
{
replacedembly replacedembly = replacedembly.LoadFrom(Path.Combine(path));
var icon = replacedembly.GetManifestResourceStream(sourceName);
var decoder = new PngBitmapDecoder(icon, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
ImageSource source = decoder.Frames[0];
return source;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
return null;
}
}
19
View Source File : Runner.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task<int> ExecuteCommand(CommandSettings command)
{
try
{
VssUtil.InitializeVssClientSettings(HostContext.UserAgents, HostContext.WebProxy);
_inConfigStage = true;
_completedCommand.Reset();
_term.CancelKeyPress += CtrlCHandler;
//register a SIGTERM handler
HostContext.Unloading += Runner_Unloading;
// TODO Unit test to cover this logic
Trace.Info(nameof(ExecuteCommand));
var configManager = HostContext.GetService<IConfigurationManager>();
// command is not required, if no command it just starts if configured
// TODO: Invalid config prints usage
if (command.Help)
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
if (command.Version)
{
_term.WriteLine(BuildConstants.RunnerPackage.Version);
return Constants.Runner.ReturnCode.Success;
}
if (command.Commit)
{
_term.WriteLine(BuildConstants.Source.CommitHash);
return Constants.Runner.ReturnCode.Success;
}
if (command.Check)
{
var url = command.GetUrl();
var pat = command.GetGitHubPersonalAccessToken(required: true);
var checkExtensions = HostContext.GetService<IExtensionManager>().GetExtensions<ICheckExtension>();
var sortedChecks = checkExtensions.OrderBy(x => x.Order);
foreach (var check in sortedChecks)
{
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Check: {check.CheckName}");
_term.WriteLine($"** Description: {check.CheckDescription}");
_term.WriteLine($"**********************************************************************************************************************");
var result = await check.RunCheck(url, pat);
if (!result)
{
_term.WriteLine($"** **");
_term.WriteLine($"** F A I L **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"** Help Doc: {check.HelpLink}");
_term.WriteLine($"**********************************************************************************************************************");
}
else
{
_term.WriteLine($"** **");
_term.WriteLine($"** P A S S **");
_term.WriteLine($"** **");
_term.WriteLine($"**********************************************************************************************************************");
_term.WriteLine($"** Log: {check.CheckLog}");
_term.WriteLine($"**********************************************************************************************************************");
}
_term.WriteLine();
_term.WriteLine();
}
return Constants.Runner.ReturnCode.Success;
}
// Configure runner prompt for args if not supplied
// Unattended configure mode will not prompt for args if not supplied and error on any missing or invalid value.
if (command.Configure)
{
try
{
await configManager.ConfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
// remove config files, remove service, and exit
if (command.Remove)
{
try
{
await configManager.UnconfigureAsync(command);
return Constants.Runner.ReturnCode.Success;
}
catch (Exception ex)
{
Trace.Error(ex);
_term.WriteError(ex.Message);
return Constants.Runner.ReturnCode.TerminatedError;
}
}
_inConfigStage = false;
// warmup runner process (JIT/CLR)
// In scenarios where the runner is single use (used and then thrown away), the system provisioning the runner can call `Runner.Listener --warmup` before the machine is made available to the pool for use.
// this will optimizes the runner process startup time.
if (command.Warmup)
{
var binDir = HostContext.GetDirectory(WellKnownDirectory.Bin);
foreach (var replacedemblyFile in Directory.EnumerateFiles(binDir, "*.dll"))
{
try
{
Trace.Info($"Load replacedembly: {replacedemblyFile}.");
var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
var types = replacedembly.GetTypes();
foreach (Type loadedType in types)
{
try
{
Trace.Info($"Load methods: {loadedType.FullName}.");
var methods = loadedType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
foreach (var method in methods)
{
if (!method.IsAbstract && !method.ContainsGenericParameters)
{
Trace.Verbose($"Prepare method: {method.Name}.");
RuntimeHelpers.PrepareMethod(method.MethodHandle);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
}
catch (Exception ex)
{
Trace.Error(ex);
}
}
return Constants.Runner.ReturnCode.Success;
}
RunnerSettings settings = configManager.LoadSettings();
var store = HostContext.GetService<IConfigurationStore>();
bool configuredreplacedervice = store.IsServiceConfigured();
// Run runner
if (command.Run) // this line is current break machine provisioner.
{
// Error if runner not configured.
if (!configManager.IsConfigured())
{
_term.WriteError("Runner is not configured.");
PrintUsage(command);
return Constants.Runner.ReturnCode.TerminatedError;
}
Trace.Verbose($"Configured as service: '{configuredreplacedervice}'");
//Get the startup type of the runner i.e., autostartup, service, manual
StartupType startType;
var startupTypereplacedtring = command.GetStartupType();
if (string.IsNullOrEmpty(startupTypereplacedtring) && configuredreplacedervice)
{
// We need try our best to make the startup type accurate
// The problem is coming from runner autoupgrade, which result an old version service host binary but a newer version runner binary
// At that time the servicehost won't preplaced --startuptype to Runner.Listener while the runner is actually running as service.
// We will guess the startup type only when the runner is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not
Trace.Info($"Try determine runner startup type base on console redirects.");
startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.Manual;
}
else
{
if (!Enum.TryParse(startupTypereplacedtring, true, out startType))
{
Trace.Info($"Could not parse the argument value '{startupTypereplacedtring}' for StartupType. Defaulting to {StartupType.Manual}");
startType = StartupType.Manual;
}
}
Trace.Info($"Set runner startup type - {startType}");
HostContext.StartupType = startType;
if (command.RunOnce)
{
_term.WriteLine("Warning: '--once' is going to be deprecated in the future, please consider using '--ephemeral' during runner registration.", ConsoleColor.Yellow);
_term.WriteLine("https://docs.github.com/en/actions/hosting-your-own-runners/autoscaling-with-self-hosted-runners#using-ephemeral-runners-for-autoscaling", ConsoleColor.Yellow);
}
// Run the runner interactively or as service
return await RunAsync(settings, command.RunOnce || settings.Ephemeral);
}
else
{
PrintUsage(command);
return Constants.Runner.ReturnCode.Success;
}
}
finally
{
_term.CancelKeyPress -= CtrlCHandler;
HostContext.Unloading -= Runner_Unloading;
_completedCommand.Set();
}
}
19
View Source File : WrappedException.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static replacedembly Resolvereplacedembly(replacedemblyName asmName)
{
//if we get here we are probably in a back compat scenario
//check the version of the asmName, and if it is 14.0, upgrade it to
//the same as this replacedembly version and try it
if (asmName.Version == null || asmName.Version.Major <= c_backCompatVer)
{
//create new instance, don't copy unknown params...
replacedemblyName newName = new replacedemblyName
{
Name = asmName.Name,
CultureInfo = asmName.CultureInfo
};
// DEVNOTE: Do not tack-on the version information, instead let the
// replacedembly load without it so that it may resolve to the appropriate.
// Otherwise, translation down the stack may fail due to version mismatch
// and that end's up creating un-necessary retries on certain user defined exceptions.
// newName.Version = replacedembly.GetExecutingreplacedembly().GetName().Version;
newName.SetPublicKeyToken(asmName.GetPublicKeyToken());
try
{
var ret = replacedembly.Load(newName);
if (ret != null)
{
return ret;
}
}
catch (Exception)
{ }
}
//Next,we look in the same directory, add .dll to the name and do a "LoadFrom" just
//like in the replacedemblyResolve event in other places
//the replacedembly should be in the same directory as this one.
string currentPath = replacedembly.GetExecutingreplacedembly().Location;
if (!String.IsNullOrEmpty(currentPath))
{
string fullPath = Path.Combine(Path.GetDirectoryName(currentPath), asmName.Name + ".dll");
if (File.Exists(fullPath))
{
return replacedembly.LoadFrom(fullPath);
}
}
return null;
}
19
View Source File : KoiInfo.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
{
var name = new replacedemblyName(args.Name).Name;
foreach(var asm in replacedemblies)
if(asm.GetName().Name == name)
return asm;
var folderPath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
var replacedemblyPath = Path.Combine(folderPath, name + ".dll");
if(File.Exists(replacedemblyPath) == false)
return null;
var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return replacedembly;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
{
string folderPath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
string replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
if (!File.Exists(replacedemblyPath)) return null;
replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return replacedembly;
}
19
View Source File : BlockMiningService.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
{
var folderPath = Path.GetDirectoryName(replacedembly.GetCallingreplacedembly().Location);
var replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
if (!File.Exists(replacedemblyPath)) return null;
var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return replacedembly;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private static replacedembly OnreplacedemblyResolve(object sender, ResolveEventArgs args)
{
var folderPath = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
var replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
if (!File.Exists(replacedemblyPath))
{
if (replacedemblyPath.Contains("Contract"))
{
replacedemblyPath = replacedemblyPath.Substring(0,
replacedemblyPath.IndexOf("bin", StringComparison.Ordinal) - 1);
replacedemblyPath = Path.Combine(replacedemblyPath, "contracts", new replacedemblyName(args.Name).Name + ".dll");
}
else
return null;
}
var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return replacedembly;
}
19
View Source File : Model.cs
License : MIT License
Project Creator : AgileoAutomation
License : MIT License
Project Creator : AgileoAutomation
public void Build(DirectoryInfo dir)
{
foreach (FileInfo file in dir.GetFiles())
{
if (file.Extension == ".exe" || file.Extension == ".dll")
{
try
{
inputs.Add(new replacedemblyPointer(replacedembly.LoadFrom(file.FullName)));
}
catch (BadImageFormatException e)
{
Console.WriteLine(e.Message);
}
}
}
foreach (replacedemblyPointer pointer in inputs)
{
LoadAllReferencedreplacedemblies(pointer);
}
AddreplacedemblyPointerGroup("Model Inputs", inputs);
AddreplacedemblyPointerGroup("All replacedemblies", Allreplacedemblies);
}
19
View Source File : RawInputApp.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
private IRecordPolicy CreateRecordPolicy()
{
IRecordPolicy policy = null;
try
{
if (!string.IsNullOrEmpty(Global.Config.RecordPolicy))
{
string path = System.IO.Path.Combine(Application.StartupPath, "Policy.dll");
if (System.IO.File.Exists(path))
{
var replacedembly = System.Reflection.replacedembly.LoadFrom(path);
if (replacedembly != null)
policy = replacedembly.CreateInstance(Global.Config.RecordPolicy) as IRecordPolicy;
}
else
{
var replacedembly = System.Reflection.replacedembly.GetEntryreplacedembly();
if (replacedembly != null)
policy = replacedembly.CreateInstance(Global.Config.RecordPolicy) as IRecordPolicy;
}
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); }
if (policy == null)
policy = new GenericPolicy();
return policy;
}
19
View Source File : PluginManager.cs
License : MIT License
Project Creator : AlexMog
License : MIT License
Project Creator : AlexMog
private void _loadPlugins()
{
var pluginsDirectory = new DirectoryInfo(_pluginsPath);
if (!pluginsDirectory.Exists)
{
pluginsDirectory.Create();
}
foreach (var file in pluginsDirectory.GetFiles("*.dll"))
{
var replacedembly = replacedembly.LoadFrom(file.FullName);
foreach (var type in replacedembly.GetTypes())
{
if (!type.IsSubclreplacedOf(typeof(IPlugin)) || type.IsAbstract) continue;
Longship.Instance.Log.LogInfo($"Loading plugin {file.Name}...");
try
{
_plugins[type] = new LoadedPlugin()
{
Plugin = type.InvokeMember(
null,
BindingFlags.CreateInstance,
null,
null,
null) as IPlugin,
Name = file.Name
};
}
catch (Exception e)
{
Longship.Instance.Log.LogError($"Can't load plugin {file.Name}.");
Longship.Instance.Log.LogError(e);
}
}
}
}
19
View Source File : Document.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
public IDoreplacedent Build(string replacedemblyPath)
{
var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return this.Build(replacedembly);
}
19
View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
public static List<replacedembly> LoadAllFrom(this replacedembly replacedembly, string[] includedFileNames, params string[] excludedFileNames)
{
if (includedFileNames == null)
{
L.Debug("No included files preplaceded to LoadAllFrom() method");
return null;
}
List<replacedembly> replacedemblies = new List<replacedembly>();
bool hasExlusions = excludedFileNames != null;
for (int i = 0; i < includedFileNames.Length; i++)
{
if (hasExlusions && excludedFileNames.Any(f => includedFileNames[i].EndsWith(f)))
{
continue;
}
else if (!File.Exists(includedFileNames[i]))
{
continue;
}
else
{
try
{
replacedemblies.Add(replacedembly.LoadFrom(includedFileNames[i]));
}
catch (Exception e)
{
L.Error(e, "Exception thrown loading replacedembly from file {0}.", includedFileNames[i]);
}
}
}
if (replacedemblies.Count == 0)
{
L.Debug("No replacedemblies matching search pattern loaded.");
return null;
}
else
{
return replacedemblies;
}
}
19
View Source File : ResourceLoader.cs
License : MIT License
Project Creator : AlternateLife
License : MIT License
Project Creator : AlternateLife
internal replacedembly Loadreplacedembly(string path)
{
var reflectionreplacedembly = replacedemblyName.GetreplacedemblyName(path);
if (_loadedreplacedemblies.TryGetValue(reflectionreplacedembly.FullName, out var element))
{
return element;
}
try
{
var loadedreplacedembly = replacedembly.LoadFrom(path);
_loadedreplacedemblies[loadedreplacedembly.GetName().FullName] = loadedreplacedembly;
return loadedreplacedembly;
}
catch (FileLoadException e)
{
_plugin.Logger.Error($"An error occured while loading replacedembly \"{path}\": ", e);
return null;
}
}
19
View Source File : MainForm.cs
License : Mozilla Public License 2.0
Project Creator : amrali-eg
License : Mozilla Public License 2.0
Project Creator : amrali-eg
private static IEnumerable<string> GetSupportedCharsets()
{
//Using reflection, figure out all the charsets that the UtfUnknown framework supports by reflecting
//over all the strings constants in the UtfUnknown.Core.CodepageName clreplaced. These represent all the encodings
//that can be detected by the program.
replacedembly replacedembly = replacedembly.LoadFrom("EncodingUtils.dll");
Type codepageName = replacedembly.GetType("UtfUnknown.Core.CodepageName");
FieldInfo[] charsetConstants = codepageName.GetFields(BindingFlags.GetField | BindingFlags.Static | BindingFlags.NonPublic);
foreach (FieldInfo charsetConstant in charsetConstants)
{
if (charsetConstant.FieldType == typeof(string))
yield return (string)charsetConstant.GetValue(null);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : Analogy-LogViewer
License : MIT License
Project Creator : Analogy-LogViewer
private static replacedembly CurrentDomain_replacedemblyResolve(object sender, ResolveEventArgs args)
{
// missing resources are... missing
if (args.Name.Contains(".resources"))
{
return null;
}
// check for replacedemblies already loaded
replacedembly? replacedembly = AppDomain.CurrentDomain.Getreplacedemblies()
.FirstOrDefault(a => a.GetName().Name == args.Name);
if (replacedembly != null)
{
return replacedembly;
}
// Try to load by filename - split out the filename of the full replacedembly name
// and append the base path of the original replacedembly (ie. look in the same dir)
// NOTE: this doesn't account for special search paths but then that never
// worked before either.
string filename = args.Name.Split(',')[0] + ".dll".ToLower();
var paths = FactoriesManager.Instance.ProbingPaths.Select(Path.GetDirectoryName).Except(new List<string> { replacedemblyLocation }).Distinct()
.ToList();
paths.AddRange(replacedogyNonPersistSettings.Instance.AdditionalreplacedembliesDependenciesLocations);
foreach (var path in paths)
{
string asmFile = FindFileInPath(filename, path);
if (!string.IsNullOrEmpty(asmFile))
{
try
{
string finalPath = Path.GetDirectoryName(asmFile);
if (!string.IsNullOrEmpty(finalPath) && paths.Count == 1)
{
Environment.CurrentDirectory = finalPath;
}
return replacedembly.LoadFrom(asmFile);
}
catch
{
//ignore
}
}
}
return null;
}
19
View Source File : ChronosCoreLocator.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
private void SetupreplacedemblyResolver(string chronosCorePath)
{
string chronosCoreDll = Path.Combine(chronosCorePath, ChronosCoreDllName);
_chronosCorereplacedembly = replacedembly.LoadFrom(chronosCoreDll);
AppDomain.CurrentDomain.replacedemblyResolve += OnreplacedemblyResolve;
}
19
View Source File : ExtensionAssemblyResolver.cs
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
License : GNU General Public License v3.0
Project Creator : AndreiFedarets
private replacedembly Resolve(string path, replacedemblyName replacedemblyName)
{
string simpleName = replacedemblyName.Name;
string replacedemblyPath = Path.Combine(path, simpleName + ".dll");
if (!File.Exists(replacedemblyPath))
{
return null;
}
replacedembly replacedembly;
try
{
replacedembly = replacedembly.LoadFrom(replacedemblyPath);
}
catch (Exception exception)
{
throw new TempException(exception);
}
return replacedembly;
}
19
View Source File : AutofacModuleRegister.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
#region 带有接口层的服务注入
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
if (!(File.Exists(servicesDllFile) && File.Exists(repositoryDllFile)))
{
var msg = "Repository.dll和service.dll 丢失,因为项目解耦了,所以需要先F6编译,再F5运行,请检查 bin 文件夹,并拷贝。";
log.Error(msg);
throw new Exception(msg);
}
// AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
var cacheType = new List<Type>();
if (Appsettings.app(new string[] { "AppSettings", "RedisCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogRedisCacheAOP>();
cacheType.Add(typeof(BlogRedisCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogCacheAOP>();
cacheType.Add(typeof(BlogCacheAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "TranAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogTranAOP>();
cacheType.Add(typeof(BlogTranAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
{
builder.RegisterType<BlogLogAOP>();
cacheType.Add(typeof(BlogLogAOP));
}
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
// 获取 Service.dll 程序集服务,并注册
var replacedemblysServices = replacedembly.LoadFrom(servicesDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.AsImplementedInterfaces()
.InstancePerDependency()
.PropertiesAutowired()
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
.InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
// 获取 Repository.dll 程序集服务,并注册
var replacedemblysRepository = replacedembly.LoadFrom(repositoryDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysRepository)
.AsImplementedInterfaces()
.PropertiesAutowired()
.InstancePerDependency();
#endregion
#region 没有接口层的服务层注入
//因为没有接口层,所以不能实现解耦,只能用 Load 方法。
//注意如果使用没有接口的服务,并想对其使用 AOP 拦截,就必须设置为虚方法
//var replacedemblysServicesNoInterfaces = replacedembly.Load("Blog.Core.Services");
//builder.RegisterreplacedemblyTypes(replacedemblysServicesNoInterfaces);
#endregion
#region 没有接口的单独类,启用clreplaced代理拦截
//只能注入该类中的虚方法,且必须是public
//这里仅仅是一个单独类无接口测试,不用过多追问
builder.RegisterreplacedemblyTypes(replacedembly.Getreplacedembly(typeof(Love)))
.EnableClreplacedInterceptors()
.InterceptedBy(cacheType.ToArray());
#endregion
#region 单独注册一个含有接口的类,启用interface代理拦截
//不用虚方法
//builder.RegisterType<AopService>().As<IAopService>()
// .AsImplementedInterfaces()
// .EnableInterfaceInterceptors()
// .InterceptedBy(typeof(BlogCacheAOP));
#endregion
}
19
View Source File : DI_Test.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
[Fact]
public void DI_Connet_Test()
{
var basePath = AppContext.BaseDirectory;
IServiceCollection services = new ServiceCollection().AddLogging();
services.AddAutoMapper(typeof(Startup));
services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
{
return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
{
ConnectionString = GetMainConnectionDb().Connection,//必填, 数据库连接字符串
DbType = (SqlSugar.DbType)GetMainConnectionDb().DbType,//必填, 数据库类型
IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
IsShardSameThread = true,//共享线程
InitKeyType = SqlSugar.InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如:该属性是不是主键,标识列等等信息
});
});
//services.AddSingleton(new Appsettings(Env));
//实例化 AutoFac 容器
var builder = new ContainerBuilder();
builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
//指定已扫描程序集中的类型注册为提供所有其实现的接口。
//var replacedemblysServices = replacedembly.Load("Blog.Core.Services");
//builder.RegisterreplacedemblyTypes(replacedemblysServices).AsImplementedInterfaces();
//var replacedemblysRepository = replacedembly.Load("Blog.Core.Repository");
//builder.RegisterreplacedemblyTypes(replacedemblysRepository).AsImplementedInterfaces();
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var replacedemblysServices = replacedembly.LoadFrom(servicesDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors();
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
var replacedemblysRepository = replacedembly.LoadFrom(repositoryDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysRepository).AsImplementedInterfaces();
//将services填充到Autofac容器生成器中
builder.Populate(services);
//使用已进行的组件登记创建新容器
var ApplicationContainer = builder.Build();
var blogservice = ApplicationContainer.Resolve<IBlogArticleServices>();
replacedert.True(ApplicationContainer.ComponentRegistry.Registrations.Count() > 0);
}
19
View Source File : DI_Test.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
public IContainer DICollections()
{
var basePath = AppContext.BaseDirectory;
IServiceCollection services = new ServiceCollection();
services.AddAutoMapper(typeof(Startup));
services.AddSingleton(new Appsettings(basePath));
services.AddSingleton(new LogLock(basePath));
services.AddScoped<DBSeed>();
services.AddScoped<MyContext>();
//读取配置文件
var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String;
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var permission = new List<PermissionItem>();
var permissionRequirement = new PermissionRequirement(
"/api/denied",
permission,
ClaimTypes.Role,
Appsettings.app(new string[] { "Audience", "Issuer" }),
Appsettings.app(new string[] { "Audience", "Audience" }),
signingCredentials,//签名凭据
expiration: TimeSpan.FromSeconds(60 * 60)//接口的过期时间
);
services.AddSingleton(permissionRequirement);
//【授权】
services.AddAuthorization(options =>
{
options.AddPolicy(Permissions.Name,
policy => policy.Requirements.Add(permissionRequirement));
});
services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
{
return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
{
ConnectionString = GetMainConnectionDb().Connection,//必填, 数据库连接字符串
DbType = (SqlSugar.DbType)GetMainConnectionDb().DbType,//必填, 数据库类型
IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
IsShardSameThread = true,//共享线程
InitKeyType = SqlSugar.InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如:该属性是不是主键,标识列等等信息
});
});
//实例化 AutoFac 容器
var builder = new ContainerBuilder();
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
//指定已扫描程序集中的类型注册为提供所有其实现的接口。
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var replacedemblysServices = replacedembly.LoadFrom(servicesDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors();
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
var replacedemblysRepository = replacedembly.LoadFrom(repositoryDllFile);
builder.RegisterreplacedemblyTypes(replacedemblysRepository).AsImplementedInterfaces();
//将services填充到Autofac容器生成器中
builder.Populate(services);
//使用已进行的组件登记创建新容器
var ApplicationContainer = builder.Build();
return ApplicationContainer;
}
19
View Source File : AutofacModuleRegister.cs
License : Apache License 2.0
Project Creator : anjoy8
License : Apache License 2.0
Project Creator : anjoy8
protected override void Load(ContainerBuilder builder)
{
var basePath = AppContext.BaseDirectory;
builder.RegisterType<BlogLogAOP>();
builder.RegisterType<BlogCacheAOP>();//可以直接替换其他拦截器
#region Service.dll 注入,有对应接口
try
{
var servicesDllFile = Path.Combine(basePath, "Student.Achieve.Repository.dll");
var replacedemblysServices = replacedembly.LoadFrom(servicesDllFile);
var cacheType = new List<Type>();
if (Appsettings.app(new string[] { "AppSettings", "LogAOP", "Enabled" }).ObjToBool())
{
cacheType.Add(typeof(BlogLogAOP));
}
if (Appsettings.app(new string[] { "AppSettings", "MemoryCachingAOP", "Enabled" }).ObjToBool())
{
cacheType.Add(typeof(BlogCacheAOP));
}
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.EnableInterfaceInterceptors()
.InterceptedBy(cacheType.ToArray());
#endregion
}
catch (Exception ex)
{
throw new Exception("※※★※※ 如果你是第一次下载项目,请先对整个解决方案dotnet build(F6编译),然后再对api层 dotnet run(F5执行),\n因为解耦了,如果你是发布的模式,请检查bin文件夹是否存在Repository.dll和service.dll ※※★※※" + ex.Message + "\n" + ex.InnerException);
}
}
19
View Source File : AssemblyResolver.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private replacedembly CustomreplacedemblyResolve(object sender, ResolveEventArgs e)
{
replacedembly tryLoadreplacedembly(
string directory,
string extension)
{
var asm = new replacedemblyName(e.Name);
var asmPath = Path.Combine(directory, asm.Name + extension);
if (File.Exists(asmPath))
{
return replacedembly.LoadFrom(asmPath);
}
return null;
}
var pluginDirectory = ActGlobals.oFormActMain?.PluginGetSelfData(this.plugin)?.pluginFile.DirectoryName;
if (!string.IsNullOrEmpty(pluginDirectory))
{
if (!this.Directories.Any(x => x == pluginDirectory))
{
this.Directories.Add(pluginDirectory);
this.Directories.Add(Path.Combine(pluginDirectory, "bin"));
var architect = Environment.Is64BitProcess ? "x64" : "x86";
this.Directories.Add(Path.Combine(pluginDirectory, $@"{architect}"));
this.Directories.Add(Path.Combine(pluginDirectory, $@"bin\{architect}"));
}
}
// Directories プロパティで指定されたディレクトリを基準にアセンブリを検索する
foreach (var directory in this.Directories)
{
var asm = tryLoadreplacedembly(directory, ".dll");
if (asm != null)
{
return asm;
}
}
return null;
}
19
View Source File : Plugin.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
private void SetreplacedemblyResolver()
{
AppDomain.CurrentDomain.replacedemblyResolve += (s, e) =>
{
this.GetPluginLocation();
var asm = new replacedemblyName(e.Name);
var pathList = new string[]
{
Path.Combine(this.PluginDirectory, asm.Name + ".dll"),
Path.Combine(this.ACTDefaultPluginDrectory, asm.Name + ".dll"),
};
foreach (var path in pathList)
{
if (File.Exists(path))
{
return replacedembly.LoadFrom(path);
}
}
return null;
};
}
19
View Source File : AssemblyResolver.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
private replacedembly CustomreplacedemblyResolve(object sender, ResolveEventArgs e)
{
replacedembly tryLoadreplacedembly(
string directory,
string extension)
{
var asm = new replacedemblyName(e.Name);
var asmPath = Path.Combine(directory, asm.Name + extension);
if (File.Exists(asmPath))
{
return replacedembly.LoadFrom(asmPath);
}
return null;
}
var location = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
this.Directories.Add(location);
this.Directories.Add(Path.Combine(location, "bin"));
var architect = Environment.Is64BitProcess ? "x64" : "x86";
this.Directories.Add(Path.Combine(location, $@"{architect}"));
this.Directories.Add(Path.Combine(location, $@"bin\{architect}"));
// Directories プロパティで指定されたディレクトリを基準にアセンブリを検索する
foreach (var directory in this.Directories)
{
var asm = tryLoadreplacedembly(directory, ".dll");
if (asm != null)
{
return asm;
}
}
return null;
}
19
View Source File : UpdateChecker.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
public static dynamic GetHojoring()
{
const string HojoringTypeName = "ACT.Hojoring.Common.Hojoring";
var obj = default(object);
lock (Locker)
{
if (hojoringInstance != null)
{
return hojoringInstance;
}
try
{
#if DEBUG
// DEBUGビルド時に依存関係でDLLを配置させるためにタイプを参照する
new ACT.Hojoring.Common.Hojoring();
#endif
var t = Type.GetType(HojoringTypeName);
if (t == null)
{
var cd = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
var hojoring = Path.Combine(cd, "ACT.Hojoring.Common.dll");
if (File.Exists(hojoring))
{
var asm = replacedembly.LoadFrom(hojoring);
t = asm?.GetType(HojoringTypeName);
}
}
if (t != null)
{
obj = Activator.CreateInstance(t);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
obj = null;
}
hojoringInstance = obj;
return obj;
}
}
19
View Source File : ServiceCollectionExtensions.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public static IServiceCollection AddCybtansServices(this IServiceCollection services, string replacedemblyName)
{
return AddCybtansServices(services, replacedembly.LoadFrom(replacedemblyName));
}
19
View Source File : ServiceCollectionExtensions.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public static IServiceCollection AddClients(this IServiceCollection services, string baseUrl, string replacedemblyName, Action<IHttpClientBuilder, Type> configure = null)
{
return AddClients(services, baseUrl, replacedembly.LoadFrom(replacedemblyName), configure);
}
19
View Source File : AssemblyResolver.cs
License : MIT License
Project Creator : anoyetta-academy
License : MIT License
Project Creator : anoyetta-academy
private static replacedembly CurrentDomain_replacedemblyResolve(object sender, ResolveEventArgs args)
{
replacedembly tryLoadreplacedembly(
string directory,
string extension)
{
var asm = new replacedemblyName(args.Name);
var asmPath = Path.Combine(directory, asm.Name + extension);
if (File.Exists(asmPath))
{
return replacedembly.LoadFrom(asmPath);
}
return null;
}
var dir = Path.Combine(
Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location),
"bin");
foreach (var directory in new[] { dir })
{
var asm = tryLoadreplacedembly(directory, ".dll");
if (asm != null)
{
return asm;
}
}
return null;
}
19
View Source File : NMSConnectionFactory.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
private static Type GetTypeForScheme(string scheme)
{
string[] paths = GetConfigSearchPaths();
string replacedemblyFileName;
string factoryClreplacedName;
Type factoryType = null;
Tracer.DebugFormat("Locating provider for scheme: {0}", scheme);
if (LookupConnectionFactoryInfo(paths, scheme, out replacedemblyFileName, out factoryClreplacedName))
{
replacedembly replacedembly = null;
Tracer.DebugFormat("Attempting to load provider replacedembly: {0}", replacedemblyFileName);
try
{
replacedembly = replacedembly.Load(replacedemblyFileName);
if (null != replacedembly)
{
Tracer.Debug("Succesfully loaded provider.");
}
}
catch (Exception ex)
{
Tracer.ErrorFormat("Exception loading replacedembly failed: {0}", ex.Message);
replacedembly = null;
}
if (null == replacedembly)
{
foreach (string path in paths)
{
string fullpath = Path.Combine(path, replacedemblyFileName) + ".dll";
Tracer.DebugFormat("Looking for: {0}", fullpath);
if (File.Exists(fullpath))
{
Tracer.Debug("\treplacedembly found! Attempting to load...");
try
{
replacedembly = replacedembly.LoadFrom(fullpath);
}
catch (Exception ex)
{
Tracer.ErrorFormat("Exception loading replacedembly failed: {0}", ex.Message);
replacedembly = null;
}
if (null != replacedembly)
{
Tracer.Debug("Successfully loaded provider.");
break;
}
Tracer.Debug("Failed to load provider. Continuing search...");
}
}
}
if (null != replacedembly)
{
#if NETCF
factoryType = replacedembly.GetType(factoryClreplacedName, true);
#else
factoryType = replacedembly.GetType(factoryClreplacedName, true, true);
#endif
if (null == factoryType)
{
Tracer.Fatal("Failed to load clreplaced factory from provider.");
}
}
else
{
Tracer.Fatal("Failed to load provider replacedembly.");
}
}
return factoryType;
}
19
View Source File : Init.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public async Task<Run> HandleRequest(HttpContext httpContext)
{
await _initSemapreplacedSlim.WaitAsync();
try
{
if (Initialized)
{
await httpContext.Response.WriteError("Cannot initialize the action more than once.");
Console.Error.WriteLine("Cannot initialize the action more than once.");
return (new Run(Type, Method, Constructor, AwaitableMethod));
}
string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
JObject inputObject = JObject.Parse(body);
if (!inputObject.ContainsKey("value"))
{
await httpContext.Response.WriteError("Missing main/no code to execute.");
return (null);
}
JToken message = inputObject["value"];
if (message["main"] == null || message["binary"] == null || message["code"] == null)
{
await httpContext.Response.WriteError("Missing main/no code to execute.");
return (null);
}
string main = message["main"].ToString();
bool binary = message["binary"].ToObject<bool>();
if (!binary)
{
await httpContext.Response.WriteError("code must be binary (zip file).");
return (null);
}
string[] mainParts = main.Split("::");
if (mainParts.Length != 3)
{
await httpContext.Response.WriteError("main required format is \"replacedembly::Type::Function\".");
return (null);
}
string tempPath = Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString());
string base64Zip = message["code"].ToString();
try
{
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Zip)))
{
using (ZipArchive archive = new ZipArchive(stream))
{
archive.ExtractToDirectory(tempPath);
}
}
}
catch (Exception)
{
await httpContext.Response.WriteError("Unable to decompress package.");
return (null);
}
Environment.CurrentDirectory = tempPath;
string replacedemblyFile = $"{mainParts[0]}.dll";
string replacedemblyPath = Path.Combine(tempPath, replacedemblyFile);
if (!File.Exists(replacedemblyPath))
{
await httpContext.Response.WriteError($"Unable to locate requested replacedembly (\"{replacedemblyFile}\").");
return (null);
}
try
{
replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
Type = replacedembly.GetType(mainParts[1]);
if (Type == null)
{
await httpContext.Response.WriteError($"Unable to locate requested type (\"{mainParts[1]}\").");
return (null);
}
Method = Type.GetMethod(mainParts[2]);
Constructor = Type.GetConstructor(Type.EmptyTypes);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
await httpContext.Response.WriteError(ex.Message
#if DEBUG
+ ", " + ex.StackTrace
#endif
);
return (null);
}
if (Method == null)
{
await httpContext.Response.WriteError($"Unable to locate requested method (\"{mainParts[2]}\").");
return (null);
}
if (Constructor == null)
{
await httpContext.Response.WriteError($"Unable to locate appropriate constructor for (\"{mainParts[1]}\").");
return (null);
}
Initialized = true;
AwaitableMethod = (Method.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null);
return (new Run(Type, Method, Constructor, AwaitableMethod));
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.StackTrace);
await httpContext.Response.WriteError(ex.Message
#if DEBUG
+ ", " + ex.StackTrace
#endif
);
Startup.WriteLogMarkers();
return (null);
}
finally
{
_initSemapreplacedSlim.Release();
}
}
19
View Source File : Init.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public async Task<Run> HandleRequest(HttpContext httpContext)
{
await _initSemapreplacedSlim.WaitAsync();
try
{
if (Initialized)
{
await httpContext.Response.WriteError("Cannot initialize the action more than once.");
Console.Error.WriteLine("Cannot initialize the action more than once.");
return (new Run(Type, Method, Constructor, AwaitableMethod));
}
string body = await new StreamReader(httpContext.Request.Body).ReadToEndAsync();
JObject inputObject = JObject.Parse(body);
if (!inputObject.ContainsKey("value"))
{
await httpContext.Response.WriteError("Missing main/no code to execute.");
return (null);
}
JToken message = inputObject["value"];
if (message["main"] == null || message["binary"] == null || message["code"] == null)
{
await httpContext.Response.WriteError("Missing main/no code to execute.");
return (null);
}
string main = message["main"].ToString();
bool binary = message["binary"].ToObject<bool>();
if (!binary)
{
await httpContext.Response.WriteError("code must be binary (zip file).");
return (null);
}
string[] mainParts = main.Split("::");
if (mainParts.Length != 3)
{
await httpContext.Response.WriteError("main required format is \"replacedembly::Type::Function\".");
return (null);
}
string tempPath = Path.Combine(Environment.CurrentDirectory, Guid.NewGuid().ToString());
string base64Zip = message["code"].ToString();
try
{
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Zip)))
{
using (ZipArchive archive = new ZipArchive(stream))
{
archive.ExtractToDirectory(tempPath);
}
}
}
catch (Exception)
{
await httpContext.Response.WriteError("Unable to decompress package.");
return (null);
}
Environment.CurrentDirectory = tempPath;
string replacedemblyFile = $"{mainParts[0]}.dll";
string replacedemblyPath = Path.Combine(tempPath, replacedemblyFile);
if (!File.Exists(replacedemblyPath))
{
await httpContext.Response.WriteError($"Unable to locate requested replacedembly (\"{replacedemblyFile}\").");
return (null);
}
try
{
// Export init arguments as environment variables
if (message["env"] != null && message["env"].HasValues)
{
Dictionary<string, string> dictEnv = message["env"].ToObject<Dictionary<string, string>>();
foreach (KeyValuePair<string, string> entry in dictEnv) {
// See https://docs.microsoft.com/en-us/dotnet/api/system.environment.setenvironmentvariable
// If entry.Value is null or the empty string, the variable is not set
Environment.SetEnvironmentVariable(entry.Key, entry.Value);
}
}
replacedembly replacedembly = replacedembly.LoadFrom(replacedemblyPath);
Type = replacedembly.GetType(mainParts[1]);
if (Type == null)
{
await httpContext.Response.WriteError($"Unable to locate requested type (\"{mainParts[1]}\").");
return (null);
}
Method = Type.GetMethod(mainParts[2]);
Constructor = Type.GetConstructor(Type.EmptyTypes);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
await httpContext.Response.WriteError(ex.Message
#if DEBUG
+ ", " + ex.StackTrace
#endif
);
return (null);
}
if (Method == null)
{
await httpContext.Response.WriteError($"Unable to locate requested method (\"{mainParts[2]}\").");
return (null);
}
if (Constructor == null)
{
await httpContext.Response.WriteError($"Unable to locate appropriate constructor for (\"{mainParts[1]}\").");
return (null);
}
Initialized = true;
AwaitableMethod = (Method.ReturnType.GetMethod(nameof(Task.GetAwaiter)) != null);
return (new Run(Type, Method, Constructor, AwaitableMethod));
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.StackTrace);
await httpContext.Response.WriteError(ex.Message
#if DEBUG
+ ", " + ex.StackTrace
#endif
);
Startup.WriteLogMarkers();
return (null);
}
finally
{
_initSemapreplacedSlim.Release();
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
private static object GetRenderInstance(string renderInstance)
{
if (string.IsNullOrEmpty(renderInstance)) return null;
string[] k = renderInstance.Split(new char[] { ',' }, 2);
if (k.Length != 2) return null;
string replacedemblyKey = k[1].Trim();
string typeKey = k[0].Trim();
string cacheKey = string.Concat(typeKey, ",", replacedemblyKey);
//从缓存读取
object render;
bool flag = false;
lock (RenderInstanceCache)
{
flag = RenderInstanceCache.TryGetValue(cacheKey, out render);
}
if (!flag || render == null)
{
//重新生成实例
render = null;
//生成实例
replacedembly replacedembly;
if (replacedemblyKey.IndexOf(":") != -1)
{
replacedembly = replacedembly.LoadFrom(replacedemblyKey);
}
else
{
replacedembly = replacedembly.Load(replacedemblyKey);
}
if (replacedembly != null)
{
render = replacedembly.CreateInstance(typeKey, false);
}
if (render != null)
{
//缓存
lock (RenderInstanceCache)
{
if (RenderInstanceCache.ContainsKey(cacheKey))
{
RenderInstanceCache[cacheKey] = render;
}
else
{
RenderInstanceCache.Add(cacheKey, render);
}
}
}
}
return render;
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
public static Type CreateType(string typeName, string replacedembly)
{
if (string.IsNullOrEmpty(typeName)) return null;
Type type = null;
bool flag = false;
string cacheKey = string.Concat(typeName, ",", replacedembly);
lock (TypeCache)
{
flag = TypeCache.TryGetValue(cacheKey, out type);
}
if (!flag)
{
if (string.IsNullOrEmpty(replacedembly))
{
//从当前程序域里建立类型
type = Type.GetType(typeName, false, true);
if (type == null)
{
//搜索当前程序域里的所有程序集
replacedembly[] replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly asm in replacedemblies)
{
type = asm.GetType(typeName, false, true);
if (type != null) break;
}
}
}
else
{
//从某个程序集里建立类型
replacedembly asm;
if (replacedembly.IndexOf(":") != -1)
{
asm = replacedembly.LoadFrom(replacedembly);
}
else
{
asm = replacedembly.Load(replacedembly);
}
if (asm != null)
{
type = asm.GetType(typeName, false, true);
}
}
//缓存
lock (TypeCache)
{
if (!TypeCache.ContainsKey(cacheKey))
{
TypeCache.Add(cacheKey, type);
}
}
}
return type;
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
License : GNU General Public License v3.0
Project Creator : architecture-building-systems
private static replacedembly LoadRhinoLibraries(object sender, ResolveEventArgs args)
{
var folderPath = @"C:\Program Files\Rhino 6\System";
var replacedemblyPath = Path.Combine(folderPath, new replacedemblyName(args.Name).Name + ".dll");
if (!File.Exists(replacedemblyPath)) return null;
var replacedembly = replacedembly.LoadFrom(replacedemblyPath);
return replacedembly;
}
19
View Source File : LocalServer.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
private static bool LoadComObjectreplacedemblies()
{
s_ComObjectreplacedys = new ArrayList();
s_ComObjectTypes = new ArrayList();
// put everything into one folder, the same as the server.
string replacedyPath = replacedembly.GetEntryreplacedembly().Location;
replacedyPath = Path.GetDirectoryName(replacedyPath);
DirectoryInfo d = new DirectoryInfo(replacedyPath);
foreach (FileInfo fi in d.GetFiles("*.dll"))
{
string aPath = fi.FullName;
//
// First try to load the replacedembly and get the types for
// the clreplaced and the clreplaced factory. If this doesn't work ????
//
try
{
replacedembly so = replacedembly.LoadFrom(aPath);
//PWGS Get the types in the replacedembly
Type[] types = so.GetTypes();
foreach (Type type in types)
{
// PWGS Now checks the type rather than the replacedembly
// Check to see if the type has the ServedClreplacedName attribute, only use it if it does.
MemberInfo info = type;
object[] attrbutes = info.GetCustomAttributes(typeof(ServedClreplacedNameAttribute), false);
if (attrbutes.Length > 0)
{
//MessageBox.Show("Adding Type: " + type.Name + " " + type.FullName);
s_ComObjectTypes.Add(type); //PWGS - much simpler
s_ComObjectreplacedys.Add(so);
}
}
}
catch (BadImageFormatException)
{
// Probably an attempt to load a Win32 DLL (i.e. not a .net replacedembly)
// Just swallow the exception and continue to the next item.
continue;
}
catch (Exception e)
{
MessageBox.Show("Failed to load served COM clreplaced replacedembly " + fi.Name + " - " + e.Message,
"Remote", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return false;
}
}
return true;
}
19
View Source File : worker.cs
License : GNU General Public License v3.0
Project Creator : ashr
License : GNU General Public License v3.0
Project Creator : ashr
private MethodInfo findInjectionMethod(string filename, string payloadURI, string payloadMethod, string payloadClreplaced)
{
MethodInfo mi = null;
try
{
replacedembly origreplacedy = replacedembly.LoadFrom(filename);
Console.WriteLine("[+] Loading modules");
Dictionary<int, Module> internalModules = new Dictionary<int, Module>();
int counter = 1;
//Enumerate modules
foreach (Module m in origreplacedy.GetLoadedModules())
{
internalModules.Add(counter, m);
Console.WriteLine("[*] " + counter.ToString() + " " + m.Name);
counter++;
}
int moduleNumber = -1;
//User chooses module
while (!internalModules.ContainsKey(moduleNumber)) {
moduleNumber = chooseNumber("Please choose module number for type enumeration");
}
Console.WriteLine("[*] Enumerating Module " + internalModules[moduleNumber].FullyQualifiedName);
Dictionary<int, Type> internalModuleTypes = new Dictionary<int, Type>();
counter = 1;
//Enumerate Types on chosen module
foreach (Type t in internalModules[moduleNumber].GetTypes())
{
internalModuleTypes.Add(counter, t);
Console.WriteLine("[*] " + counter.ToString() + " " + t.Name);
counter++;
}
int clreplacedNumber = -1;
//User chooses type
while (!internalModuleTypes.ContainsKey(clreplacedNumber))
{
clreplacedNumber = chooseNumber("Please choose type number for method enumeration");
}
Console.WriteLine("[*] Enumerating Type " + internalModuleTypes[clreplacedNumber].FullName);
Dictionary<int, MethodInfo> internalMethods = new Dictionary<int, MethodInfo>();
counter = 1;
//Enumerate Methods
foreach(MethodInfo imi in internalModuleTypes[clreplacedNumber].GetRuntimeMethods())
{
internalMethods.Add(counter, imi);
Console.WriteLine("[*] " + counter.ToString() + " " + imi.Name);
counter++;
foreach (ParameterInfo pi in imi.GetParameters())
{
Console.WriteLine("[*]\t" + pi.Name + ":" + pi.ParameterType.FullName);
}
}
int methodNumber = -1;
while (!internalMethods.ContainsKey(methodNumber))
{
methodNumber = chooseNumber("Please choose method number for injection");
}
Console.WriteLine("[!!] Will try inject payload into:");
Console.WriteLine("\tModule:" + internalModules[moduleNumber].FullyQualifiedName);
Console.WriteLine("\tClreplaced:" + internalModuleTypes[clreplacedNumber].FullName);
Console.WriteLine("\tMethod:" + internalMethods[methodNumber].Name);
//injectBadStuffLame(internalModules[moduleNumber], internalModuleTypes[clreplacedNumber], internalMethods[methodNumber]);
injectBadStuff(internalModules[moduleNumber], internalModuleTypes[clreplacedNumber], internalMethods[methodNumber], payloadURI, payloadMethod, payloadClreplaced);
}
catch(Exception e)
{
Console.WriteLine(e.Message + ":" + e.StackTrace);
}
return mi;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : askguanyu
License : MIT License
Project Creator : askguanyu
private replacedembly Resolve(object sender, ResolveEventArgs args)
{
string replacedemblyFile = this.FindreplacedemblyName(args.Name);
if (replacedemblyFile != null)
{
return replacedembly.LoadFrom(replacedemblyFile);
}
return null;
}
19
View Source File : CrossAppDomainAssemblyResolver.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
public System.Reflection.replacedembly Resolve (object sender, ResolveEventArgs args)
{
var location = parent.GetreplacedemblyPath (args.Name);
if (location != null)
return System.Reflection.replacedembly.LoadFrom (location);
return null;
}
19
View Source File : CompiledTemplate.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
replacedembly ResolveReferencedreplacedemblies (object sender, ResolveEventArgs args)
{
replacedemblyName asmName = new replacedemblyName (args.Name);
foreach (var asmFile in replacedemblyFiles) {
if (asmName.Name == System.IO.Path.GetFileNameWithoutExtension (asmFile))
return replacedembly.LoadFrom (asmFile);
}
var path = host.ResolvereplacedemblyReference (asmName.Name + ".dll");
if (System.IO.File.Exists (path))
return replacedembly.LoadFrom (path);
return null;
}
19
View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : atifaziz
License : MIT License
Project Creator : atifaziz
protected virtual Type ResolveDirectiveProcessor (string processorName)
{
KeyValuePair<string,string> value;
if (!directiveProcessors.TryGetValue (processorName, out value))
throw new Exception (string.Format ("No directive processor registered as '{0}'", processorName));
var asmPath = ResolvereplacedemblyReference (value.Value);
if (asmPath == null)
throw new Exception (string.Format ("Could not resolve replacedembly '{0}' for directive processor '{1}'", value.Value, processorName));
var asm = replacedembly.LoadFrom (asmPath);
return asm.GetType (value.Key, true);
}
19
View Source File : ReflectionFacade.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet
License : Apache License 2.0
Project Creator : AutomateThePlanet
public replacedembly GetreplacedemblyFromFile(string fullFilePath)
{
var replacedembly = replacedembly.LoadFrom(fullFilePath);
return replacedembly;
}
19
View Source File : NativeTestsRunnerTestCasesPluginService.cs
License : Apache License 2.0
Project Creator : AutomateThePlanet
License : Apache License 2.0
Project Creator : AutomateThePlanet
private replacedembly GetreplacedemblyFromFile(string fullFilePath)
{
var replacedembly = replacedembly.LoadFrom(fullFilePath);
return replacedembly;
}
19
View Source File : AssemblyResolver.Desktop.cs
License : MIT License
Project Creator : AvaloniaCommunity
License : MIT License
Project Creator : AvaloniaCommunity
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.replacedembly.LoadFrom")]
private replacedembly CurrentDomain_replacedemblyResolve(object sender, ResolveEventArgs args)
{
replacedemblyName replacedemblyName = new replacedemblyName(args.Name);
replacedemblyInfo replacedemblyInfo = this.registeredreplacedemblies.FirstOrDefault(a => replacedemblyName.ReferenceMatchesDefinition(replacedemblyName, a.replacedemblyName));
if (replacedemblyInfo != null)
{
if (replacedemblyInfo.replacedembly == null)
{
replacedemblyInfo.replacedembly = replacedembly.LoadFrom(replacedemblyInfo.replacedemblyUri.LocalPath);
}
return replacedemblyInfo.replacedembly;
}
return null;
}
19
View Source File : SelectAssemblyPage.xaml.cs
License : MIT License
Project Creator : avestura
License : MIT License
Project Creator : avestura
private void Button_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Filter = "replacedembly (*.exe, *.dll)|*.dll;*.exe",
CheckFileExists = true,
CheckPathExists = true,
Multiselect = false,
replacedle = "Select replacedembly"
};
if(dialog.ShowDialog() == true)
{
try
{
var asm = replacedembly.LoadFrom(dialog.FileName);
ParentFrame.Navigate(new InspectorPage(asm, ParentFrame));
}
catch(Exception ex)
{
MessageBox.Show($"File not valid, Reason: {ex.Message}" + ((ex.InnerException != null) ? $"\nInner{ex.InnerException.Message}" : ""));
}
}
}
19
View Source File : GenerationSources.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public (replacedembly replacedembly, XmlDoreplacedent Ndoc, IEnumerable<string> Dependencies) Load(string baseName, bool addAsReference = true)
{
if (string.IsNullOrEmpty(SdkreplacedembliesFolder))
{
throw new InvalidOperationException("Expected 'SdkNugetFolder' to have been set prior to calling Load(...)");
}
SdkVersionsUtils.EnsureSdkLibraryIsAvailable(baseName, SdkreplacedembliesFolder, PlatformsToExtractLibrariesFor);
var dependencies = SdkVersionsUtils.GetDependencies(SdkreplacedembliesFolder, baseName);
if (addAsReference)
{
var replacedemblyFile = Path.Combine(SdkreplacedembliesFolder, DotNetPlatformNetStandard20, $"{baseName}.dll");
var ndocFile = Path.Combine(SdkreplacedembliesFolder, DotNetPlatformNetStandard20, $"{baseName}.xml");
try
{
var replacedembly = replacedembly.LoadFrom(replacedemblyFile);
var ndoc = new XmlDoreplacedent();
ndoc.Load(ndocFile);
Add(baseName, replacedembly, ndoc);
return (replacedembly, ndoc, dependencies);
}
catch (Exception)
{
Console.WriteLine("An exception occured while processing files {0} and {1}.", replacedemblyFile, ndocFile);
throw;
}
}
return (null, null, null);
}
19
View Source File : Generator.cs
License : Apache License 2.0
Project Creator : aws
License : Apache License 2.0
Project Creator : aws
public void Execute(GeneratorOptions options)
{
// this is just to record the run duration, so we can monitor and optimize
// build-time perf
_startTimeTicks = DateTime.Now.Ticks;
if (options.Tasks == null || options.Tasks.Count == 0)
throw new Exception("No tasks specified for the generator to run");
if (options.Verbose)
{
// todo: echo out generator options
}
#if DEBUG
var configuration = "Debug";
#else
var configuration = "Release";
#endif
BinSubFolder = Path.Combine("bin", configuration, options.TargetFramework);
var fqRootPath = options.RootPath;
var sdkreplacedembliesFolder = options.SdkreplacedembliesFolder;
var awsPowerShellSourcePath = Path.Combine(fqRootPath, ModulesSubFolder, AWSPowerShellModuleName);
var deploymentArtifactsPath = Path.Combine(fqRootPath, options.GetEditionOutputFolder(DeploymentArtifactsSubFolder));
if (options.ShouldRunTask(GeneratorTasknames.GenerateCmdlets))
{
Console.WriteLine("Executing task 'GenerateCmdlets'");
var cmdletGenerator = new CmdletGenerator
{
SdkreplacedembliesFolder = sdkreplacedembliesFolder,
OutputFolder = awsPowerShellSourcePath,
Options = options
};
cmdletGenerator.Generate();
// Note: the remaining tasks rely on having a built copy of the AWSPowerShell module,
// so we exit so that a build can take place and the generator then re-run with the
// new tasks
Console.WriteLine("Task 'GenerateCmdlets' complete, exiting...");
return;
}
var basePath = string.IsNullOrEmpty(options.BuiltModulesLocation) ? Path.Combine(awsPowerShellSourcePath, BinSubFolder)
: options.BuiltModulesLocation;
var awsPsXmlPath = Path.Combine(basePath, options.replacedemblyName + ".XML");
var awsPsDllPath = Path.Combine(basePath, options.replacedemblyName + ".dll");
var awsPowerShellreplacedembly = replacedembly.LoadFrom(awsPsDllPath);
if (options.ShouldRunTask(GeneratorTasknames.GenerateFormats))
{
Console.WriteLine("Executing task 'GenerateFormats'");
bool includeCore = options.replacedemblyName.Equals(AWSPowerShellDllName, StringComparison.OrdinalIgnoreCase) ||
options.replacedemblyName.Equals(AWSPowerShellCommonDllName, StringComparison.OrdinalIgnoreCase);
var targetreplacedemblies = new List<replacedembly> { awsPowerShellreplacedembly };
var sdkreplacedemblies = awsPowerShellreplacedembly.GetReferencedreplacedemblies()
.Where(replacedembly => replacedembly.Name.StartsWith("AWSSDK.", StringComparison.OrdinalIgnoreCase) &&
(includeCore || !replacedembly.Name.Equals("AWSSDK.Core", StringComparison.OrdinalIgnoreCase)))
.ToArray();
targetreplacedemblies.AddRange(sdkreplacedemblies.Select(replacedembly => replacedembly.LoadFrom(Path.Combine(sdkreplacedembliesFolder, GenerationSources.DotNetPlatformNetStandard20, replacedembly.Name + ".dll"))));
targetreplacedemblies.AddRange(AppDomain.CurrentDomain.Getreplacedemblies().Where(replacedembly => sdkreplacedemblies.Contains(replacedembly.GetName())));
var formatsGenerator = new FormatGenerator
{
OutputFolder = basePath,
Name = options.replacedemblyName,
Targetreplacedemblies = targetreplacedemblies,
Options = options
};
formatsGenerator.Generate();
}
if (options.ShouldRunTask(GeneratorTasknames.GeneratePsHelp))
{
Console.WriteLine("Executing task 'GeneratePshelp'");
var cmdletDoreplacedentation = new XmlDoreplacedent();
cmdletDoreplacedentation.Load(awsPsXmlPath);
var pshelpGenerator = new PsHelpGenerator
{
Cmdletreplacedembly = awsPowerShellreplacedembly,
replacedemblyDoreplacedentation = cmdletDoreplacedentation,
Name = options.replacedemblyName,
OutputFolder = basePath,
Options = options
};
pshelpGenerator.Generate();
}
if (options.ShouldRunTask(GeneratorTasknames.GenerateWebHelp))
{
Console.WriteLine("Executing task 'GenerateWebhelp'");
var cmdletDoreplacedentation = new XmlDoreplacedent();
cmdletDoreplacedentation.Load(awsPsXmlPath);
string docOutputFolder;
if (string.IsNullOrEmpty(options.DocOutputFolder))
docOutputFolder = Path.Combine(fqRootPath, DocBuildOutputSubFolder);
else
docOutputFolder = options.DocOutputFolder;
var webhelpGenerator = new WebHelpGenerator
{
Cmdletreplacedembly = awsPowerShellreplacedembly,
replacedemblyDoreplacedentation = cmdletDoreplacedentation,
Name = AWSPowerShellModuleName,
OutputFolder = docOutputFolder,
CNNorth1RegionDocsDomain = options.CNNorth1RegionDocsDomain,
Options = options
};
webhelpGenerator.Generate();
}
}
19
View Source File : DynamicLoader.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d
public replacedembly Getreplacedembly()
{
if (this._replacedembly == null)
{
lock (_mutex)
{
if (String.IsNullOrEmpty(this._replacedemblyFilename))
{
this._replacedembly = replacedembly.GetExecutingreplacedembly();
}
else
{
Debug.WriteLine(String.Format("Loading {0}", this._replacedemblyFilename));
#if SILVERLIGHT
_replacedembly = replacedembly.Load(_replacedemblyFilename);
#else
this._replacedembly = replacedembly.LoadFrom(this._replacedemblyFilename);
#endif
}
}
}
return this._replacedembly;
}
See More Examples