Here are the examples of the csharp api System.Reflection.Assembly.GetType(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1270 Examples
19
Source : Compiler.cs
with Apache License 2.0
from bruce-dunwiddie
with Apache License 2.0
from bruce-dunwiddie
public Type Compile(
string clreplacedText,
List<string> referencereplacedemblies,
string replacedemblyName,
string clreplacedName)
{
// https://stackoverflow.com/questions/23907305/roslyn-has-no-reference-to-system-runtime
//The location of the .NET replacedemblies
var replacedemblyPath = Path.GetDirectoryName(typeof(object).replacedembly.Location);
var references = referencereplacedemblies
.Concat(new string[] {
typeof(object).replacedembly.Location,
/*
* Adding some necessary .NET replacedemblies
* These replacedemblies couldn't be loaded correctly via the same construction as above,
* in specific the System.Runtime.
*/
Path.Combine(replacedemblyPath, "mscorlib.dll"),
Path.Combine(replacedemblyPath, "System.dll"),
Path.Combine(replacedemblyPath, "System.Collections.dll"),
Path.Combine(replacedemblyPath, "System.Core.dll"),
Path.Combine(replacedemblyPath, "System.Runtime.dll"),
Path.Combine(replacedemblyPath, "System.Linq.Expressions.dll"),
Path.Combine(replacedemblyPath, "Microsoft.CSharp.dll"),
Path.Combine(replacedemblyPath, "netstandard.dll"),
// adding other standard references for convenience
Path.Combine(replacedemblyPath, "System.Linq.dll")
})
.Select(r => MetadataReference.CreateFromFile(r))
.ToArray();
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(clreplacedText);
CSharpCompilation compilation = CSharpCompilation.Create(
replacedemblyName,
new[] { syntaxTree },
references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
using (MemoryStream ms = new MemoryStream())
{
EmitResult emitResult = compilation.Emit(ms);
if (!emitResult.Success)
{
string exceptionMessage = "Clreplaced failed to compile.";
foreach (var error in emitResult.Diagnostics
.Where(e => e.Severity == DiagnosticSeverity.Error || e.IsWarningAsError)
.OrderBy(e => e.Location.GetLineSpan().StartLinePosition.Line))
{
exceptionMessage += "\n\tLine " + error.Location.GetLineSpan().StartLinePosition.Line.ToString() + ": " + error.GetMessage();
}
throw new CompilationException(exceptionMessage)
{
GeneratedClreplacedCode = clreplacedText
};
}
else
{
replacedembly compiledreplacedembly = replacedembly.Load(ms.ToArray());
return compiledreplacedembly.GetType(clreplacedName);
}
}
}
19
Source : DefaultSerializationBinder.cs
with MIT License
from BrunoS3D
with MIT License
from BrunoS3D
private Type ParseTypeName(string typeName, DebugContext debugContext)
{
Type type;
// Look for custom defined type name lookups defined with the BindTypeNameToTypeAttribute.
if (customTypeNameToTypeBindings.TryGetValue(typeName, out type))
{
return type;
}
// Let's try it the traditional .NET way
type = Type.GetType(typeName);
if (type != null) return type;
// Let's try a short-cut
type = replacedemblyUtilities.GetTypeByCachedFullName(typeName);
if (type != null) return type;
// Generic/array type name handling
type = ParseGenericAndOrArrayType(typeName, debugContext);
if (type != null) return type;
string typeStr, replacedemblyStr;
ParseName(typeName, out typeStr, out replacedemblyStr);
if (!string.IsNullOrEmpty(typeStr) && replacedemblyStr != null && replacedemblyNameLookUp.ContainsKey(replacedemblyStr))
{
var replacedembly = replacedemblyNameLookUp[replacedemblyStr];
type = replacedembly.GetType(typeStr);
if (type != null) return type;
}
type = replacedemblyUtilities.GetTypeByCachedFullName(typeStr);
if (type != null) return type;
return null;
}
19
Source : TestExtensions.cs
with MIT License
from byme8
with MIT License
from byme8
public static async Task<IPropertyInfo[]> ExecutePropertiesTest(this Project project, User user = null)
{
var replacedembly = await project.CompileToRealreplacedembly();
var extension = replacedembly.GetType("Apparatus.AOT.Reflection.Apparatus_AOT_Reflection_Playground_UserExtensions");
replacedert.NotNull(extension);
var method = extension.GetMethod("GetProperties", BindingFlags.Static | BindingFlags.Public);
replacedert.NotNull(method);
var entries = (IReadOnlyDictionary<KeyOf<User>, IPropertyInfo>)method.Invoke(null, new[] { user ?? new User(), });
return entries.Values.ToArray();
}
19
Source : OracleAccessProvider.cs
with GNU Lesser General Public License v3.0
from CarefreeXT
with GNU Lesser General Public License v3.0
from CarefreeXT
static void InitialOracleCompnent(Type factoryType)
{
if (!_IsInitialed)
{
try
{
var dbtypeenum = factoryType.replacedembly.GetType("Oracle.ManagedDataAccess.Client.OracleDbType");
var type = factoryType.replacedembly.GetTypes().Where(a => a.Name == "OraDb_DbTypeTable").FirstOrDefault();
if (type != null)
{
var field = type.GetField("s_table", BindingFlags.NonPublic | BindingFlags.Static);
if (field != null)
{
var s_table = (Hashtable)field.GetValue(null);
if (s_table != null)
{
if (!s_table.ContainsKey(typeof(byte?))) s_table.Add(typeof(byte?), Enum.Parse(dbtypeenum, "Byte"));
if (!s_table.ContainsKey(typeof(char?))) s_table.Add(typeof(char?), Enum.Parse(dbtypeenum, "Varchar2"));
if (!s_table.ContainsKey(typeof(DateTime?))) s_table.Add(typeof(DateTime?), Enum.Parse(dbtypeenum, "TimeStamp"));
if (!s_table.ContainsKey(typeof(short?))) s_table.Add(typeof(short?), Enum.Parse(dbtypeenum, "Int16"));
if (!s_table.ContainsKey(typeof(int?))) s_table.Add(typeof(int?), Enum.Parse(dbtypeenum, "Int32"));
if (!s_table.ContainsKey(typeof(long?))) s_table.Add(typeof(long?), Enum.Parse(dbtypeenum, "Int64"));
if (!s_table.ContainsKey(typeof(float?))) s_table.Add(typeof(float?), Enum.Parse(dbtypeenum, "Single"));
if (!s_table.ContainsKey(typeof(double?))) s_table.Add(typeof(double?), Enum.Parse(dbtypeenum, "Double"));
if (!s_table.ContainsKey(typeof(decimal?))) s_table.Add(typeof(decimal?), Enum.Parse(dbtypeenum, "Decimal"));
if (!s_table.ContainsKey(typeof(TimeSpan?))) s_table.Add(typeof(TimeSpan?), Enum.Parse(dbtypeenum, "IntervalDS"));
if (!s_table.ContainsKey(typeof(bool?))) s_table.Add(typeof(bool?), Enum.Parse(dbtypeenum, "Boolean"));
}
}
}
}
catch (Exception) { }
finally
{
_IsInitialed = true;
}
}
}
19
Source : Symbols.cs
with MIT License
from CatLib
with MIT License
from CatLib
static Type GetSymbolType (SymbolKind kind, string fullname)
{
var type = Type.GetType (fullname);
if (type != null)
return type;
var replacedembly_name = GetSymbolreplacedemblyName (kind);
type = Type.GetType (fullname + ", " + replacedembly_name.FullName);
if (type != null)
return type;
try {
var replacedembly = SR.replacedembly.Load (replacedembly_name);
if (replacedembly != null)
return replacedembly.GetType (fullname);
} catch (FileNotFoundException) {
} catch (FileLoadException) {
}
return null;
}
19
Source : ReplyHandler.cs
with GNU Affero General Public License v3.0
from cc004
with GNU Affero General Public License v3.0
from cc004
public async Task Reloadreplacedembly()
{
await Task.Yield();
Resolvereplacedemblies();
var functions = new Dictionary<string, Function>();
var options = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
false,
null, null, null, null, OptimizationLevel.Release,
false, true, null, null, default, null, Platform.AnyCpu,
ReportDiagnostic.Default, 4, null, true, false, null, null, null, DesktopreplacedemblyIdenreplacedyComparer.Default,
null, false, MetadataImportOptions.Public
);
var options2 = new CSharpParseOptions(LanguageVersion.Latest, DoreplacedentationMode.Parse, SourceCodeKind.Regular);
functions = new Dictionary<string, Function>();
var dict = new Dictionary<string, int>();
int func = 0;
var sb = new StringBuilder();
var usings = new string[]
{
"BandoriBot",
"BandoriBot.Config",
"BandoriBot.Handler",
"System",
"System.Collections.Generic",
"System.Text.RegularExpressions",
"System.Linq"
};
var refs = new List<string>();
foreach (var name in replacedembly.GetExecutingreplacedembly().GetReferencedreplacedemblies())
{
try
{
refs.Add(replacedembly.Load(name).Location);
}
catch { }
}
foreach (var asm1 in AppDomain.CurrentDomain.Getreplacedemblies())
{
try
{
refs.Add(asm1.Location);
}
catch { }
}
foreach (var @using in usings)
sb.Append($"using {@using};\n");
sb.Append("\npublic static clreplaced FunctionHolder\n{\n");
foreach (var pair in data4)
{
foreach (var reply in pair.Value)
{
if (dict.ContainsKey(reply.reply)) continue;
sb.Append($"public static string Function{++func}(Match match, Source source, string message, bool isAdmin, Action<string> callback)\n{{\n");
sb.Append(reply.reply.Decode());
sb.Append("\n}\n");
dict.Add(reply.reply, func);
}
}
sb.Append("\n}\n");
var codeText = sb.ToString();
foreach (Match match in codeReg.Matches(codeText))
{
refs.Add(replacedembly.Load(new replacedemblyName(match.Groups[1].Value)).Location);
}
var references = refs.Where(r => !string.IsNullOrEmpty(r)).Select(r => MetadataReference.CreateFromFile(r));
File.WriteAllText("debug.cs", codeText);
var syntaxTree = SyntaxFactory.ParseSyntaxTree(codeText, options2, "code.cs", Encoding.UTF8, default);
var compilation = CSharpCompilation.Create("Reply", new SyntaxTree[] { syntaxTree }, references, options);
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (!result.Success)
{
var msg = string.Join("\n",
result.Diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Warning).Select(diagnostic =>
{
FileLinePositionSpan lineSpan = diagnostic.Location.GetLineSpan();
return new CompilerError
{
ErrorNumber = diagnostic.Id,
IsWarning = (diagnostic.Severity == DiagnosticSeverity.Warning),
ErrorText = diagnostic.GetMessage(null),
FileName = (lineSpan.Path ?? ""),
Line = lineSpan.StartLinePosition.Line + 1,
Column = lineSpan.StartLinePosition.Character
}.ToString();
}));
if (msg.Length > 1024) msg = msg.Substring(0, 1024);
throw new Exception(msg);
}
var asm = replacedembly.Load(ms.ToArray());
Type holder = asm.GetType("FunctionHolder");
foreach (var pair in dict)
functions.Add(pair.Key, (Function)holder.GetMethod($"Function{pair.Value}").CreateDelegate(typeof(Function), null));
this.functions = functions;
}
19
Source : ClassFactory.cs
with GNU Lesser General Public License v3.0
from ccbpm
with GNU Lesser General Public License v3.0
from ccbpm
public static Type GetBPType(string clreplacedName)
{
Type typ = null;
foreach (replacedembly replaced in BPreplacedemblies)
{
typ = replaced.GetType(clreplacedName);
if (typ != null)
return typ;
}
return typ;
}
19
Source : ClassFactory.cs
with GNU Lesser General Public License v3.0
from ccbpm
with GNU Lesser General Public License v3.0
from ccbpm
public static ArrayList GetBPTypes(string baseEnsName)
{
ArrayList arr = new ArrayList();
Type baseClreplaced = null;
foreach (replacedembly replaced in BPreplacedemblies)
{
if (baseClreplaced == null)
baseClreplaced = replaced.GetType(baseEnsName);
Type[] tps = replaced.GetTypes();
for (int i = 0; i < tps.Length; i++)
{
if (tps[i].IsAbstract
|| tps[i].BaseType == null
|| !tps[i].IsClreplaced
|| !tps[i].IsPublic
)
continue;
Type tmp = tps[i].BaseType;
if (tmp.Namespace == null)
throw new Exception(tmp.FullName);
while (tmp != null && tmp.Namespace.IndexOf("BP") != -1)
{
if (tmp.FullName == baseEnsName)
arr.Add(tps[i]);
tmp = tmp.BaseType;
}
}
}
if (baseClreplaced == null)
{
throw new Exception("@找不到类型:" + baseEnsName + "!");
}
return arr;
}
19
Source : ClassFactory.cs
with GNU Lesser General Public License v3.0
from ccbpm
with GNU Lesser General Public License v3.0
from ccbpm
public static bool IsFromType(string childTypeFullName, string parentTypeFullName)
{
foreach (replacedembly replaced in BPreplacedemblies)
{
Type childType = replaced.GetType(childTypeFullName);
while (childType != null && childType.BaseType != null)
{
if (childType.BaseType.FullName == parentTypeFullName)
return true;
childType = childType.BaseType;
}
}
return false;
}
19
Source : ClassFactory.cs
with GNU Lesser General Public License v3.0
from ccbpm
with GNU Lesser General Public License v3.0
from ccbpm
public static object GetObject_OK(string clreplacedName)
{
if (clreplacedName == "" || clreplacedName == null)
throw new Exception("@要转化类名称为空...");
Type ty = null;
object obj = null;
foreach (replacedembly replaced in BPreplacedemblies)
{
ty = replaced.GetType(clreplacedName);
if (ty == null)
continue;
obj = replaced.CreateInstance(clreplacedName);
if (obj != null)
return obj;
else
throw new Exception("@创建对象实例 " + clreplacedName + " 失败!");
}
if (obj == null)
throw new Exception("@创建对象类型 " + clreplacedName + " 失败,请确定拼写是否错误。");
return obj;
}
19
Source : ClassFactory.cs
with GNU Lesser General Public License v3.0
from ccbpm
with GNU Lesser General Public License v3.0
from ccbpm
public static ArrayList GetObjects(string baseEnsName)
{
ArrayList arr = new ArrayList();
Type baseClreplaced = null;
foreach (replacedembly replaced in BPreplacedemblies)
{
if (baseClreplaced == null)
baseClreplaced = replaced.GetType(baseEnsName);
Type[] tps = null;
try
{
tps = replaced.GetTypes();
}
catch
{
//throw new Exception(replaced.FullName+replaced.Evidence.ToString()+ ex.Message);
continue;
}
for (int i = 0; i < tps.Length; i++)
{
if (tps[i].IsAbstract
|| tps[i].BaseType == null
|| !tps[i].IsClreplaced
|| !tps[i].IsPublic
)
continue;
Type tmp = tps[i].BaseType;
if (tmp.Namespace == null)
throw new Exception(tmp.FullName);
while (tmp != null && tmp.Namespace.IndexOf("BP") != -1)
{
if (tmp.FullName == baseEnsName)
arr.Add(replaced.CreateInstance(tps[i].FullName));
tmp = tmp.BaseType;
}
}
}
if (baseClreplaced == null)
{
throw new Exception("@找不到类型" + baseEnsName + "!");
}
return arr;
}
19
Source : IOCFactory.cs
with Apache License 2.0
from chancezheng
with Apache License 2.0
from chancezheng
public static T2 CreateInstance<T1,T2>(T1 t1 ,string asmName= "DesktopUniversalFrame") where T1 : clreplaced where T2 : clreplaced
{
replacedembly replacedembly = replacedembly.Load(asmName);
Type type = replacedembly.GetType(typeof(T2).Name);
T2 instance = (T2)Activator.CreateInstance(type, new object[] { t1 });
return instance;
}
19
Source : IOCFactory.cs
with Apache License 2.0
from chancezheng
with Apache License 2.0
from chancezheng
public static T CreateInstance<T>(string asmName = "DesktopUniversalFrame")
{
replacedembly replacedembly = replacedembly.Load(asmName);
Type type = replacedembly.GetType(typeof(T).FullName);
T instance = (T)Activator.CreateInstance(type);
return instance;
}
19
Source : Program.cs
with MIT License
from chanjunweimy
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 : VRTK_SupportInfoWindow.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
private void RefreshData()
{
stringBuilder.Length = 0;
replacedembly editorreplacedembly = typeof(VRTK_SDKManagerEditor).replacedembly;
replacedembly replacedembly = typeof(VRTK_SDKManager).replacedembly;
Append(
"Versions",
() =>
{
Append("Unity", InternalEditorUtility.GetFullUnityVersion());
Append("VRTK", VRTK_Defines.CurrentVersion + " (may not be correct if source is GitHub)");
Type steamVRUpdateType = editorreplacedembly.GetType("SteamVR_Update");
if (steamVRUpdateType != null)
{
FieldInfo currentVersionField = steamVRUpdateType.GetField("currentVersion", BindingFlags.NonPublic | BindingFlags.Static);
if (currentVersionField != null)
{
string currentVersion = (string)currentVersionField.GetValue(null);
Append("SteamVR", currentVersion);
}
}
Type ovrPluginType = replacedembly.GetType("OVRPlugin");
if (ovrPluginType != null)
{
Append(
"OVRPlugin (Oculus Utilities)",
() =>
{
FieldInfo wrapperVersionField = ovrPluginType.GetField("wrapperVersion", BindingFlags.Public | BindingFlags.Static);
if (wrapperVersionField != null)
{
Version wrapperVersion = (Version)wrapperVersionField.GetValue(null);
Append("wrapperVersion", wrapperVersion);
}
PropertyInfo versionField = ovrPluginType.GetProperty("version", BindingFlags.Public | BindingFlags.Static);
if (versionField != null)
{
Version version = (Version)versionField.GetGetMethod().Invoke(null, null);
Append("version", version);
}
PropertyInfo nativeSDKVersionField = ovrPluginType.GetProperty("nativeSDKVersion", BindingFlags.Public | BindingFlags.Static);
if (nativeSDKVersionField != null)
{
Version nativeSDKVersion = (Version)nativeSDKVersionField.GetGetMethod().Invoke(null, null);
Append("nativeSDKVersion", nativeSDKVersion);
}
}
);
}
}
);
Append(
"Scripting Define Symbols",
() =>
{
foreach (BuildTargetGroup targetGroup in VRTK_SharedMethods.GetValidBuildTargetGroups())
{
string symbols = string.Join(
";",
PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup)
.Split(';')
.Where(symbol => !symbol.StartsWith(VRTK_Defines.VersionScriptingDefineSymbolPrefix, StringComparison.Ordinal))
.ToArray());
if (!string.IsNullOrEmpty(symbols))
{
Append(targetGroup, symbols);
}
}
}
);
stringBuilder.Length--;
}
19
Source : VRTK_SharedMethods.cs
with MIT License
from charles-river-analytics
with MIT License
from charles-river-analytics
public static Type GetTypeUnknownreplacedembly(string typeName)
{
Type type = Type.GetType(typeName);
if (type != null)
{
return type;
}
#if !UNITY_WSA
replacedembly[] foundreplacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
for (int i = 0; i < foundreplacedemblies.Length; i++)
{
type = foundreplacedemblies[i].GetType(typeName);
if (type != null)
{
return type;
}
}
#endif
return null;
}
19
Source : DirtyScriptsCompilationTool.cs
with MIT License
from chenwansal
with MIT License
from chenwansal
[MenuItem("Tools/DirtyScriptsCompilation/Compile %_T")]
static void CompileDirtyScripts() {
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// 找到触发编译完成的方法
// 以及 out 方法参数 1
MethodInfo invokeMethod = FindInvokerInEditorCompilation(out object invoker);
// 方法参数 2
Type type = System.Reflection.replacedembly.Load("UnityEditor").GetType("UnityEditor.Scripting.Compilers.CompilerMessage");
var list = Activator.CreateInstance(typeof(List<>).MakeGenericType(type));
var model = GetOrCreateAsmCacheModelSo();
List<string> dirties = model.GetDirtyScripts();
List<UnityEditorreplacedembly> compiledList = new List<UnityEditorreplacedembly>();
// 编译
foreach (var path in dirties) {
var asm = model.GetreplacedemblyWithPath(path);
if (compiledList.Contains(asm)) {
continue;
}
// 编译 asm
EditorUtility.CompileCSharp(asm.sourceFiles, asm.allReferences, asm.defines, asm.outputPath);
Debug.Log($"编译 asm: {asm.name}, sourceFilesCount: {asm.sourceFiles.Length.ToString()}, refsCount: {asm.allReferences.Length.ToString()}, outPath: {asm.outputPath}");
invokeMethod.Invoke(invoker, new object[] { asm.outputPath, list });
compiledList.Add(asm);
}
stopwatch.Stop();
// 无脚本
if (dirties.Count == 0) {
Debug.Log($"不存在脏脚本, 无需编译, 耗时: {stopwatch.ElapsedMilliseconds.ToString()}");
} else {
Debug.Log($"合计编译 DirtyScripts 数量: {dirties.Count}, 耗时: {stopwatch.ElapsedMilliseconds.ToString()}");
}
// 清空 DirtyScripts
dirtyHandleQueue.Clear();
model.CleanDirtyScripts();
}
19
Source : TypeRegister.cs
with MIT License
from chexiongsheng
with MIT License
from chexiongsheng
internal Type GetType(string clreplacedName, bool isQualifiedName = false)
{
Type type = Type.GetType(clreplacedName, false);
if (type != null)
{
return type;
}
foreach (replacedembly replacedembly in replacedemblies)
{
type = replacedembly.GetType(clreplacedName);
if (type != null)
{
return type;
}
}
int p1 = clreplacedName.IndexOf('[');
if (p1 > 0 && !isQualifiedName)
{
string qualified_name = clreplacedName.Substring(0, p1 + 1);
string[] generic_params = clreplacedName.Substring(p1 + 1, clreplacedName.Length - qualified_name.Length - 1).Split(',');
for (int i = 0; i < generic_params.Length; i++)
{
Type generic_param = GetType(generic_params[i].Trim());
if (generic_param == null)
{
return null;
}
if (i != 0)
{
qualified_name += ", ";
}
qualified_name = qualified_name + "[" + generic_param.replacedemblyQualifiedName + "]";
}
qualified_name += "]";
return GetType(qualified_name, true);
}
return null;
}
19
Source : DefaultPackageModule.cs
with GNU General Public License v3.0
from chi-rei-den
with GNU General Public License v3.0
from chi-rei-den
private void BindImportService()
{
Bind<IPackageImportService>().To<PackageImportService>().InSingletonScope();
var packageImportService = Kernel.Get<IPackageImportService>();
if (Localizer.Config.ImporBasictAfterSetupContent)
{
packageImportService.RegisterImporter<BasicItemFile>(typeof(BasicImporterPostContentLoad<BasicItemFile>));
packageImportService.RegisterImporter<BasicNPCFile>(typeof(BasicImporterPostContentLoad<BasicNPCFile>));
packageImportService.RegisterImporter<BasicBuffFile>(typeof(BasicImporterPostContentLoad<BasicBuffFile>));
packageImportService.RegisterImporter<BasicProjectileFile>(typeof(BasicImporterPostContentLoad<BasicProjectileFile>));
packageImportService.RegisterImporter<BasicPrefixFile>(typeof(BasicImporterPostContentLoad<BasicPrefixFile>));
}
else
{
packageImportService.RegisterImporter<BasicItemFile>(typeof(BasicImporterBeforeContentLoad<BasicItemFile>));
packageImportService.RegisterImporter<BasicNPCFile>(typeof(BasicImporterBeforeContentLoad<BasicNPCFile>));
packageImportService.RegisterImporter<BasicBuffFile>(typeof(BasicImporterBeforeContentLoad<BasicBuffFile>));
packageImportService.RegisterImporter<BasicProjectileFile>(typeof(BasicImporterBeforeContentLoad<BasicProjectileFile>));
packageImportService.RegisterImporter<BasicPrefixFile>(typeof(BasicImporterBeforeContentLoad<BasicPrefixFile>));
}
packageImportService.RegisterImporter<CustomModTranslationFile>(typeof(CustomModTranslationImporter));
if (!string.IsNullOrWhiteSpace(Localizer.Config.LdstrImporter))
{
packageImportService.RegisterImporter<LdstrFile>(replacedembly.GetExecutingreplacedembly().GetType($"Localizer.Package.Import.{Localizer.Config.LdstrImporter}LdstrImporter"));
}
else
{
packageImportService.RegisterImporter<LdstrFile>(typeof(CecilLdstrImporter));
}
Bind<AutoImportService>().ToSelf().InSingletonScope();
Bind<RefreshLanguageService>().ToSelf().InSingletonScope();
}
19
Source : EditorPluginInterop.cs
with MIT License
from chstetco
with MIT License
from chstetco
private static void DisableSyncSolutionOnceCallBack()
{
// RiderScriptableSingleton.Instance.CsprojProcessedOnce = true;
// Otherwise EditorPlugin regenerates all on every AppDomain reload
var replacedembly = EditorPluginreplacedembly;
if (replacedembly == null) return;
var type = replacedembly.GetType("JetBrains.Rider.Unity.Editor.Utils.RiderScriptableSingleton");
if (type == null) return;
var baseType = type.BaseType;
if (baseType == null) return;
var instance = baseType.GetProperty("Instance");
if (instance == null) return;
var instanceVal = instance.GetValue(null);
var member = type.GetProperty("CsprojProcessedOnce");
if (member==null) return;
member.SetValue(instanceVal, true);
}
19
Source : EditorPluginInterop.cs
with MIT License
from chstetco
with MIT License
from chstetco
public static bool OpenFileDllImplementation(string path, int line, int column)
{
var openResult = false;
// reflection for fast OpenFileLineCol, when Rider is started and protocol connection is established
try
{
var replacedembly = EditorPluginreplacedembly;
if (replacedembly == null) return false;
var type = replacedembly.GetType(ourEntryPointTypeName);
if (type == null) return false;
var field = type.GetField("OpenreplacedetHandler", BindingFlags.NonPublic | BindingFlags.Static);
if (field == null) return false;
var handlerInstance = field.GetValue(null);
var method = handlerInstance.GetType()
.GetMethod("OnOpenedreplacedet", new[] {typeof(string), typeof(int), typeof(int)});
if (method == null) return false;
var replacedetFilePath = path;
if (!string.IsNullOrEmpty(path))
replacedetFilePath = Path.GetFullPath(path);
openResult = (bool) method.Invoke(handlerInstance, new object[] {replacedetFilePath, line, column});
}
catch (Exception e)
{
Debug.Log("Unable to do OpenFile to Rider from dll, fallback to com.unity.ide.rider implementation.");
Debug.LogException(e);
}
return openResult;
}
19
Source : EditorPluginInterop.cs
with MIT License
from chstetco
with MIT License
from chstetco
internal static void InitEntryPoint(replacedembly replacedembly)
{
try
{
if (Version.TryParse(RiderScriptEditorData.instance.currentEditorVersion, out var version))
{
if (version.Major < 192)
DisableSyncSolutionOnceCallBack(); // is require for Rider prior to 2019.2
}
else
DisableSyncSolutionOnceCallBack();
var type = replacedembly.GetType("JetBrains.Rider.Unity.Editor.AfterUnity56.EntryPoint");
if (type == null)
type = replacedembly.GetType("JetBrains.Rider.Unity.Editor.UnitTesting.EntryPoint"); // oldRider
RuntimeHelpers.RunClreplacedConstructor(type.TypeHandle);
}
catch (TypeInitializationException ex)
{
Debug.LogException(ex);
if (ex.InnerException != null)
Debug.LogException(ex.InnerException);
}
}
19
Source : DataCoreDatabase.cs
with GNU General Public License v3.0
from CitizensReactor
with GNU General Public License v3.0
from CitizensReactor
private void InitializereplacedemblyTypes(replacedembly replacedembly)
{
ManagedEnumTypes = new System.Collections.ObjectModel.ObservableCollection<Type>(new Type[RawDatabase.enumDefinitions.Length]);
for (int enumDefinitionIndex = 0; enumDefinitionIndex < RawDatabase.enumDefinitions.Length; enumDefinitionIndex++)
{
var enumDefinition = RawDatabase.enumDefinitions[enumDefinitionIndex];
var enumName = RawDatabase.textBlock.GetString(enumDefinition.NameOffset);
//TODO: Local Types
var replacedemblyType = replacedembly.GetType($"{replacedemblyNamespace}.{enumName}");
if (replacedemblyType != null)
{
ManagedEnumTypes[enumDefinitionIndex] = replacedemblyType;
continue;
}
throw new Exception($"Failed to load Enum type {enumName}");
}
ManagedStructureTypes = new System.Collections.ObjectModel.ObservableCollection<Type>(new Type[RawDatabase.structureDefinitions.Length]);
for (int structureIndex = 0; structureIndex < RawDatabase.structureDefinitions.Length; structureIndex++)
{
var structureDefinition = RawDatabase.structureDefinitions[structureIndex];
var structureName = RawDatabase.textBlock.GetString(structureDefinition.NameOffset);
//TODO: Local Types
var replacedemblyType = replacedembly.GetType($"{replacedemblyNamespace}.{structureName}");
if (replacedemblyType != null)
{
ManagedStructureTypes[structureIndex] = replacedemblyType;
continue;
}
throw new Exception($"Failed to load Structure type: {structureName}");
}
}
19
Source : App.xaml.cs
with GNU General Public License v3.0
from CitizensReactor
with GNU General Public License v3.0
from CitizensReactor
private void RegisterPlugins()
{
foreach (var replacedembly in Plugins)
{
var plugin = replacedembly.GetType("Plugin");
var pluginTypes = replacedembly.GetExportedTypes().Where(type => typeof(IPlugin).IsreplacedignableFrom(type));
foreach (var pluginType in pluginTypes)
{
if (pluginType == null) continue;
var initMethod = pluginType.GetMethod("Registration");
if (initMethod == null) continue;
initMethod.Invoke(null, new object[] { });
}
}
}
19
Source : Reload.cs
with MIT License
from Clancey
with MIT License
from Clancey
async Task HandleEvalRequest (EvalRequestMessage request)
{
Debug.WriteLine ($"Handling request");
EvalResponse evalResponse = new EvalResponse ();
EvalResult result = new EvalResult ();
try {
//var s = await eval.EvaluateCode (request, result);
//Debug.WriteLine ($"Evaluating: {s} - {result.FoundClreplacedes.Count}");
if(!request.Clreplacedes?.Any() ?? false)
{
//Nothing to load
return;
}
var replacedmebly = replacedembly.Load(request.replacedembly, request.Pdb);
var foundTypes = new List<(string, Type)>();
foreach(var c in request.Clreplacedes)
{
var fullName = $"{c.NameSpace}.{c.ClreplacedName}";
var type = replacedmebly.GetType(fullName);
foundTypes.Add((fullName, type));
}
if (!foundTypes.Any())
return;
StartingReload?.Invoke();
foreach (var f in foundTypes)
ReplaceType?.Invoke(f);
FinishedReload?.Invoke();
} catch (Exception ex) {
Debug.WriteLine (ex);
}
}
19
Source : Reflector.cs
with MIT License
from cm-pony
with MIT License
from cm-pony
public Type GetType(string typeName)
{
Type type = null;
string[] names = typeName.Split('.');
if (names.Length > 0)
type = m_asmb.GetType(m_ns + "." + names[0]);
for (int i = 1; i < names.Length; ++i) {
type = type.GetNestedType(names[i], BindingFlags.NonPublic);
}
return type;
}
19
Source : ApplicationDeploymentWrapper.cs
with GNU General Public License v3.0
from ClusterM
with GNU General Public License v3.0
from ClusterM
private static void init()
{
try
{
string runtimeDirectory = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
replacedembly systemDeploymentreplacedembly = replacedembly.LoadFrom(Path.Combine(runtimeDirectory, "System.Deployment.dll"));
applicationDeploymentType = systemDeploymentreplacedembly.GetType("System.Deployment.Application.ApplicationDeployment");
}
catch (FileNotFoundException e)
{
Console.WriteLine("Could not load System.Deployment.dll dynamically: {0}", e.Message);
}
finally
{
inited = true;
}
}
19
Source : BinarySerializationHelper.cs
with GNU Lesser General Public License v3.0
from cnAbp
with GNU Lesser General Public License v3.0
from cnAbp
public override Type BindToType(string replacedemblyName, string typeName)
{
var toreplacedemblyName = replacedemblyName.Split(',')[0];
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (replacedembly.FullName.Split(',')[0] == toreplacedemblyName)
{
return replacedembly.GetType(typeName);
}
}
return Type.GetType(string.Format("{0}, {1}", typeName, replacedemblyName));
}
19
Source : Brute.cs
with GNU General Public License v3.0
from cobbr
with GNU General Public License v3.0
from cobbr
private static void TaskExecute(TaskingMessenger messenger, GruntTaskingMessage message, int Delay)
{
const int MAX_MESSAGE_SIZE = 1048576;
string output = "";
try
{
if (message.Type == GruntTaskingType.replacedembly)
{
string[] pieces = message.Message.Split(',');
if (pieces.Length > 0)
{
object[] parameters = null;
if (pieces.Length > 1) { parameters = new object[pieces.Length - 1]; }
for (int i = 1; i < pieces.Length; i++) { parameters[i - 1] = Encoding.UTF8.GetString(Convert.FromBase64String(pieces[i])); }
byte[] compressedBytes = Convert.FromBase64String(pieces[0]);
byte[] decompressedBytes = Utilities.Decompress(compressedBytes);
replacedembly gruntTask = replacedembly.Load(decompressedBytes);
PropertyInfo streamProp = gruntTask.GetType("Task").GetProperty("OutputStream");
string results = "";
if (streamProp == null)
{
results = (string) gruntTask.GetType("Task").GetMethod("Execute").Invoke(null, parameters);
}
else
{
Thread invokeThread = new Thread(() => results = (string) gruntTask.GetType("Task").GetMethod("Execute").Invoke(null, parameters));
using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable))
{
using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.GetClientHandlereplacedtring()))
{
streamProp.SetValue(null, pipeClient, null);
DateTime lastTime = DateTime.Now;
invokeThread.Start();
using (StreamReader reader = new StreamReader(pipeServer))
{
object synclock = new object();
string currentRead = "";
Thread readThread = new Thread(() => {
int count;
char[] read = new char[MAX_MESSAGE_SIZE];
while ((count = reader.Read(read, 0, read.Length)) > 0)
{
lock (synclock)
{
currentRead += new string(read, 0, count);
}
}
});
readThread.Start();
while (readThread.IsAlive)
{
Thread.Sleep(Delay * 1000);
lock (synclock)
{
try
{
if (currentRead.Length >= MAX_MESSAGE_SIZE)
{
for (int i = 0; i < currentRead.Length; i += MAX_MESSAGE_SIZE)
{
string aRead = currentRead.Substring(i, Math.Min(MAX_MESSAGE_SIZE, currentRead.Length - i));
try
{
GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Progressed, aRead);
messenger.QueueTaskingMessage(response.ToJson(), message.Name);
}
catch (Exception) {}
}
currentRead = "";
lastTime = DateTime.Now;
}
else if (currentRead.Length > 0 && DateTime.Now > (lastTime.Add(TimeSpan.FromSeconds(Delay))))
{
GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Progressed, currentRead);
messenger.QueueTaskingMessage(response.ToJson(), message.Name);
currentRead = "";
lastTime = DateTime.Now;
}
}
catch (ThreadAbortException) { break; }
catch (Exception) { currentRead = ""; }
}
}
output += currentRead;
}
}
}
invokeThread.Join();
}
output += results;
}
}
else if (message.Type == GruntTaskingType.Connect)
{
string[] split = message.Message.Split(',');
bool connected = messenger.Connect(split[0], split[1]);
output += connected ? "Connection to " + split[0] + ":" + split[1] + " succeeded!" :
"Connection to " + split[0] + ":" + split[1] + " failed.";
}
else if (message.Type == GruntTaskingType.Disconnect)
{
bool disconnected = messenger.Disconnect(message.Message);
output += disconnected ? "Disconnect succeeded!" : "Disconnect failed.";
}
}
catch (Exception e)
{
try
{
GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(GruntTaskingStatus.Completed, "Task Exception: " + e.Message + Environment.NewLine + e.StackTrace);
messenger.QueueTaskingMessage(response.ToJson(), message.Name);
}
catch (Exception) { }
}
finally
{
for (int i = 0; i < output.Length; i += MAX_MESSAGE_SIZE)
{
string aRead = output.Substring(i, Math.Min(MAX_MESSAGE_SIZE, output.Length - i));
try
{
GruntTaskingStatus status = i + MAX_MESSAGE_SIZE < output.Length ? GruntTaskingStatus.Progressed : GruntTaskingStatus.Completed;
GruntTaskingMessageResponse response = new GruntTaskingMessageResponse(status, aRead);
messenger.QueueTaskingMessage(response.ToJson(), message.Name);
}
catch (Exception) {}
}
}
}
19
Source : Assembly.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr
with BSD 3-Clause "New" or "Revised" License
from cobbr
public static GenericObjectResult replacedemblyExecute(byte[] replacedemblyBytes, String TypeName = "", String MethodName = "Execute", Object[] Parameters = default(Object[]))
{
Reflect.replacedembly replacedembly = Load(replacedemblyBytes);
Type type = TypeName == "" ? replacedembly.GetTypes()[0] : replacedembly.GetType(TypeName);
Reflect.MethodInfo method = MethodName == "" ? type.GetMethods()[0] : type.GetMethod(MethodName);
var results = method.Invoke(null, Parameters);
return new GenericObjectResult(results);
}
19
Source : SharpShell.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr
with BSD 3-Clause "New" or "Revised" License
from cobbr
static void Main(string[] args)
{
bool printPrompt = true;
List<string> UsingImports = new List<string>();
List<string> lines = new List<string>();
Compiler compiler = new Compiler();
while (true)
{
// Display Prompt
if (printPrompt)
{
Console.Write("SharpShell > ");
}
else
{
Console.Write(">>> ");
}
// Read Input
string line = Console.ReadLine();
// SharpShell Special Commands
if (line.Trim().ToLower() == "exit" || line.Trim().ToLower() == "quit")
{
return;
}
else if (line.Trim() == "")
{
continue;
}
else if (line.Trim().EndsWith("\\"))
{
printPrompt = false;
lines.Add(line.TrimEnd('\\'));
continue;
}
else if (line.Trim().StartsWith("using ") && line.Trim().Split(' ').Length == 2 && line.Trim().EndsWith(";"))
{
Console.WriteLine("Import:\"" + line.Trim() + "\" now being used.");
UsingImports.Add(line.Trim());
continue;
}
try
{
// Concatenation
printPrompt = true;
string source = String.Join(Environment.NewLine, lines.ToArray());
lines.Clear();
source = source + Environment.NewLine + line;
if (!source.Contains("return "))
{
source = "return " + source;
}
// Compilation
string ClreplacedName = RandomString();
Compiler.CompilationRequest request = new Compiler.CompilationRequest
{
Source = String.Format(WrapperFunctionFormat, String.Join(Environment.NewLine, UsingImports.ToArray()), ClreplacedName, source),
replacedemblyName = "SharpShell",
Optimize = true,
TargetDotNetVersion = Compiler.DotNetVersion.Net35,
OutputKind = OutputKind.DynamicallyLinkedLibrary,
Platform = Platform.AnyCpu,
SourceDirectory = Common.SharpShellSourceDirectory,
ResourceDirectory = Common.SharpShellResourcesDirectory,
ReferenceDirectory = Common.SharpShellReferencesDirectory
};
using (TextReader reader = File.OpenText(Common.SharpShellReferencesConfig))
{
var deserializer = new DeserializerBuilder().Build();
request.References = deserializer.Deserialize<List<Compiler.Reference>>(reader)
.Where(R => R.Framework == request.TargetDotNetVersion)
.Where(R => R.Enabled)
.ToList();
}
using (TextReader reader = File.OpenText(Common.SharpShellResourcesConfig))
{
var deserializer = new DeserializerBuilder().Build();
request.EmbeddedResources = deserializer.Deserialize<List<Compiler.EmbeddedResource>>(reader)
.Where(ER => ER.Enabled)
.ToList();
}
byte[] replacedemblyBytes = Compiler.Compile(request);
// Execution
replacedembly replacedembly = replacedembly.Load(replacedemblyBytes);
object result = replacedembly.GetType(ClreplacedName).GetMethod("Execute").Invoke(null, null);
Console.WriteLine(result.ToString());
}
catch (CompilerException e)
{
Console.Error.WriteLine(e.Message);
}
catch (Exception e)
{
Console.Error.WriteLine("RuntimeException: " + e.Message + e.StackTrace);
}
}
}
19
Source : SharpShell.cs
with BSD 3-Clause "New" or "Revised" License
from cobbr
with BSD 3-Clause "New" or "Revised" License
from cobbr
static void Main(string[] args)
{
bool printPrompt = true;
List<string> UsingImports = new List<string>();
List<string> lines = new List<string>();
APICompiler compiler = new APICompiler(args.Length > 0 ? args[0] : "http://localhost:5000/api/SharpShell/compile");
while (true)
{
// Display Prompt
if (printPrompt)
{
Console.Write("SharpShell > ");
}
else
{
Console.Write(">>> ");
}
// Read Input
string line = Console.ReadLine();
// SharpShell Special Commands
if (line.Trim().ToLower() == "exit" || line.Trim().ToLower() == "quit")
{
return;
}
else if (line.Trim() == "")
{
continue;
}
else if (line.Trim().EndsWith("\\"))
{
printPrompt = false;
lines.Add(line.TrimEnd('\\'));
continue;
}
else if (line.Trim().StartsWith("using ") && line.Trim().Split(' ').Length == 2 && line.Trim().EndsWith(";"))
{
Console.WriteLine("Import:\"" + line.Trim() + "\" now being used.");
UsingImports.Add(line.Trim());
continue;
}
try
{
// Concatenation
printPrompt = true;
string source = String.Join(Environment.NewLine, lines.ToArray());
lines.Clear();
source = source + Environment.NewLine + line;
if (!source.Contains("return "))
{
source = "return " + source;
}
// Compilation
string ClreplacedName = RandomString();
byte[] replacedemblyBytes = compiler.Compile(new APICompiler.CompilationRequest
{
Source = String.Format(WrapperFunctionFormat, String.Join(Environment.NewLine, UsingImports.ToArray()), ClreplacedName, source),
replacedemblyName = "SharpShell",
Optimize = true,
TargetDotNetVersion = APICompiler.DotNetVersion.Net35,
OutputKind = APICompiler.OutputKind.DynamicallyLinkedLibrary,
Platform = APICompiler.Platform.AnyCpu
});
// Execution
replacedembly replacedembly = replacedembly.Load(replacedemblyBytes);
object result = replacedembly.GetType(ClreplacedName).GetMethod("Execute").Invoke(null, null);
Console.WriteLine(result.ToString());
}
catch (CompilationException e)
{
Console.Error.WriteLine(e.Message);
}
catch (Exception e)
{
Console.Error.WriteLine("RuntimeException: " + e.Message + e.StackTrace);
}
}
}
19
Source : Serializer.cs
with Apache License 2.0
from CodeZeg
with Apache License 2.0
from CodeZeg
public static void serialize<T>(T value)
{
if (cachedSteam == null)
throw new NullReferenceException();
cachedSteam.index_cell = 0;
cachedSteam.index_group = 0;
var bufferType = typeof(T).replacedembly.GetType(string.Format("xbuffer.{0}Buffer", typeof(T).FullName));
var method = bufferType.GetMethod("serialize", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
var args = new object[] { value, cachedSteam };
method.Invoke(null, args);
}
19
Source : Serializer.cs
with Apache License 2.0
from CodeZeg
with Apache License 2.0
from CodeZeg
public static T deserialize<T>(byte[] buffer, ref uint offset)
{
var bufferType = typeof(T).replacedembly.GetType(string.Format("xbuffer.{0}Buffer", typeof(T).FullName));
var method = bufferType.GetMethod("deserialize", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
var args = new object[] { buffer, offset };
var ret = (T)method.Invoke(null, args);
offset = (uint)args[1];
return ret;
}
19
Source : M.cs
with MIT License
from CoFlows
with MIT License
from CoFlows
public void LoadRaw(List<RawEntry> rawEntries)
{
lock(editLock)
{
this.Timestamp = DateTime.Now;
if(rawEntries == null)
return;
if(permission() == AccessType.Denied)
return;
foreach (var rawEntry in rawEntries)
{
string entryID = rawEntry.EntryID;
string typeName = rawEntry.Type;
string replacedemblyName = rawEntry.replacedembly;
try
{
if (type == null)
{
type = Type.GetType(typeName);
if(type == null)
{
var replacedembly = M._systemreplacedemblies.ContainsKey(typeName) ? M._systemreplacedemblies[typeName] : (M._compiledreplacedemblyNames.ContainsKey(typeName) ? M._compiledreplacedemblies[M._compiledreplacedemblyNames[typeName]] : System.Reflection.replacedembly.Load(replacedemblyName));
type = replacedembly.GetType(M._systemreplacedemblyNames.ContainsKey(typeName) ? M._systemreplacedemblyNames[typeName] : typeName);
}
}
DateTime d1 = DateTime.Now;
object obj = type == typeof(Nullable) || type == typeof(string) ? rawEntry.Entry : Newtonsoft.Json.JsonConvert.DeserializeObject(rawEntry.Entry as string, type);
DateTime d2 = DateTime.Now;
this.AddInternal(entryID, obj, typeName, replacedemblyName);
}
catch (Exception e)
{
this.AddInternal(entryID, rawEntry.Entry, typeName, replacedemblyName);
}
}
this.loaded = true;
}
}
19
Source : assemblymanager.cs
with MIT License
from CoFlows
with MIT License
from CoFlows
public static Type LookupType(string qname)
{
foreach (replacedembly replacedembly in replacedemblies)
{
Type type = replacedembly.GetType(qname);
if (type != null)
{
return type;
}
}
return null;
}
19
Source : MessageBusFactory.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public static IMessageBus GetBusInstance(IServiceProvider serviceProvider, MessageBusOptions options)
{
AbstractProvider provider;
string replacedemblyName = $"Colder.MessageBus.{options.Transport}";
try
{
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
var type = replacedembly.GetType($"{replacedemblyName}.{options.Transport}Provider");
provider = Activator.CreateInstance(type, new object[] { serviceProvider, options }) as AbstractProvider;
}
catch
{
throw new Exception($"请安装nuget包:{replacedemblyName}");
}
return provider.GetBusInstance();
}
19
Source : DbFactory.cs
with Apache License 2.0
from Coldairarrow
with Apache License 2.0
from Coldairarrow
public static AbstractProvider GetProvider(DatabaseType databaseType)
{
string replacedemblyName = $"EFCore.Sharding.{databaseType}";
try
{
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
var type = replacedembly.GetType($"{replacedemblyName}.{databaseType}Provider");
return Activator.CreateInstance(type) as AbstractProvider;
}
catch
{
throw new Exception($"请安装nuget包:{replacedemblyName}");
}
}
19
Source : ExampleSceneLoader.cs
with MIT License
from ConstellationLanguage
with MIT License
from ConstellationLanguage
private void ClearConsole () {
var replacedembly = replacedembly.Getreplacedembly (typeof (SceneView));
var type = replacedembly.GetType ("UnityEditor.LogEntries");
var method = type.GetMethod ("Clear");
method.Invoke (new object (), null);
}
19
Source : JsonHandle.cs
with Apache License 2.0
from coodyer
with Apache License 2.0
from coodyer
public static bool init()
{
if (jsonHandleType != null)
{
return true;
}
try
{
if (jsonHandleType == null)
{
replacedembly replacedembly = DllLoader.loadDll(resourceBytes);
jsonHandleType = replacedembly.GetType("Newtonsoft.Json.JsonConvert");
return true;
}
return false;
}
catch
{
return false;
}
}
19
Source : ServiceReflector.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
internal static Type ResolveTypeFromName(string name)
{
//First check if present in loaded replacedemblies
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (replacedembly.GetType(name) is Type found)
{
return found;
}
}
//If not present in loaded replacedemblies, replacedemblyQualifiedName should be "FooNameSpace.BarInterface,FooNameSpace".
return Type.GetType(name, true);
}
19
Source : HttpTransportBindingElement.cs
with MIT License
from CoreWCF
with MIT License
from CoreWCF
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context));
}
if (typeof(T) == typeof(ITransportServiceBuilder))
{
return (T)(object)new HttpTransportServiceBuilder();
}
//else if (typeof(T) == typeof(ISecurityCapabilities))
//{
// AuthenticationSchemes effectiveAuthenticationSchemes = HttpTransportBindingElement.GetEffectiveAuthenticationSchemes(this.AuthenticationScheme,
// context.BindingParameters);
// return (T)(object)new SecurityCapabilities(this.GetSupportsClientAuthenticationImpl(effectiveAuthenticationSchemes),
// effectiveAuthenticationSchemes == AuthenticationSchemes.Negotiate,
// this.GetSupportsClientWindowsIdenreplacedyImpl(effectiveAuthenticationSchemes),
// ProtectionLevel.None,
// ProtectionLevel.None);
//}
//else if (typeof(T) == typeof(IBindingDeliveryCapabilities))
//{
// return (T)(object)new BindingDeliveryCapabilitiesHelper();
//}
else if (typeof(T) == typeof(TransferMode))
{
return (T)(object)TransferMode;
}
//else if (typeof(T) == typeof(ExtendedProtectionPolicy))
//{
// return (T)(object)this.ExtendedProtectionPolicy;
//}
//else if (typeof(T) == typeof(IAnonymousUriPrefixMatcher))
//{
// if (_anonymousUriPrefixMatcher == null)
// {
// _anonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher();
// }
// return (T)(object)_anonymousUriPrefixMatcher;
//}
else if (typeof(T).FullName.Equals("CoreWCF.Channels.ITransportCompressionSupport"))
{
IApplicationBuilder app = context.BindingParameters.Find<IApplicationBuilder>();
if (app == null)
{
return base.GetProperty<T>(context);
}
object tcs = app.ApplicationServices.GetService(typeof(T).replacedembly.GetType("CoreWCF.Channels.TransportCompressionSupportHelper"));
return (T)tcs;
}
else
{
if (context.BindingParameters.Find<MessageEncodingBindingElement>() == null)
{
context.BindingParameters.Add(new TextMessageEncodingBindingElement());
}
return base.GetProperty<T>(context);
}
}
19
Source : TrainProgram.cs
with MIT License
from Cosmik42
with MIT License
from Cosmik42
public void ActivateAction(TrainProgramEvent e)
{
Hub target = GetTrain(e.TargetDeviceID);
if (target == null && e.Action != TrainProgramEvent.ActionType.Execute_Code && e.Action != TrainProgramEvent.ActionType.Play_Sound)
{
MainBoard.WriteLine($"Target train '{ e.TargetDeviceID}' is not connected");
return;
}
switch (e.Action)
{
case TrainProgramEvent.ActionType.Stop_Motor:
{
MainBoard.WriteLine("Action Tiggered => Stop Port " + e.TargetPort + " of " + target.Name);
target.Stop(e.TargetPort, true);
break;
}
case TrainProgramEvent.ActionType.Set_Speed:
{
MainBoard.WriteLine($"{target.Name} Action Tiggered => Set Motor Speed of Port {e.TargetPort} to {e.Param[0]} for {target.Name}");
target.SetMotorSpeed(e.TargetPort, e.Param[0]);
break;
}
case TrainProgramEvent.ActionType.Invert_Speed:
{
Port targetPort = target.GetPortFromPortId(e.TargetPort);
MainBoard.WriteLine($"{target.Name} Action Tiggered => Invert Speed of Port {e.TargetPort} to {-targetPort.Speed} for {target.Name}");
target.SetMotorSpeed(e.TargetPort, -targetPort.Speed);
break;
}
case TrainProgramEvent.ActionType.Accelerate_Motor_Over_X_Ms:
{
Port targetPort = target.GetPortFromPortId(e.TargetPort);
MainBoard.WriteLine($"{target.Name} Action Tiggered => Accelerate Port {e.TargetPort} to {e.Param[0]} over {e.Param[1]}ms");
target.RampMotorSpeed(e.TargetPort, e.Param[0], e.Param[1]);
break;
}
case TrainProgramEvent.ActionType.Decelerate_Motor_Over_X_Ms:
{
Port targetPort = target.GetPortFromPortId(e.TargetPort);
MainBoard.WriteLine($"{target.Name} Action Tiggered => Decelerate Port {e.TargetPort} to 0 over {e.Param[0]}ms");
target.RampMotorSpeed(e.TargetPort, 0, e.Param[0]);
break;
}
case TrainProgramEvent.ActionType.Wait_X_Ms_And_Set_Speed:
{
MainBoard.WriteLine($"{target.Name} Action Tiggered => Wait {e.Param[0]}ms and Set Speed of Port {e.TargetPort} to {e.Param[1]}");
target.Stop();
System.Timers.Timer t = new System.Timers.Timer();
t.Interval = e.Param[0];
t.Elapsed += (object sender, ElapsedEventArgs ev) =>
{
target.SetMotorSpeed(e.TargetPort, e.Param[1]);
t.Stop();
t.Dispose();
};
t.Start();
break;
}
case TrainProgramEvent.ActionType.Set_Speed_For_X_Ms_And_Stop:
{
MainBoard.WriteLine($"{target.Name} Action Tiggered => Set Speed on Port {e.TargetPort} to {e.Param[0]} And Stop after {e.Param[1]}ms");
target.SetMotorSpeed(e.TargetPort, e.Param[1]);
System.Timers.Timer t = new System.Timers.Timer(e.Param[0]);
t.Elapsed += (object sender, ElapsedEventArgs ev) =>
{
target.Stop(e.TargetPort);
t.Stop();
t.Dispose();
};
t.Start();
break;
}
case TrainProgramEvent.ActionType.Activate_Switch_Left:
case TrainProgramEvent.ActionType.Activate_Switch_Right:
{
Port targetPort = target.GetPortFromPortId(e.TargetPort);
targetPort.TargetSpeed = (e.Action == TrainProgramEvent.ActionType.Activate_Switch_Left) ? -100 : 100;
MainBoard.WriteLine($"{target.Name} Action Tiggered => Activate Switch to the " + ((targetPort.TargetSpeed == -100) ? "Left" : "Right"));
// Then trigger the motor
if (e.Action == TrainProgramEvent.ActionType.Activate_Switch_Left)
target.ActivateSwitchToLeft(e.TargetPort);
else
target.ActivateSwitchToRight(e.TargetPort);
break;
}
case TrainProgramEvent.ActionType.PFx_Light_Fx:
{
PFxHub hub = (PFxHub)target;
MainBoard.WriteLine($"{target.Name} Action Tiggered => Activate PFx Light FX " + e.PFxLightParam.ToString() + " on lights " + e.Lights);
hub.LightFx(e.Lights, (byte)e.PFxLightParam, new byte[0]);
break;
}
case TrainProgramEvent.ActionType.PFx_Play_Sound_With_File_Id:
{
PFxHub hub = (PFxHub)target;
MainBoard.WriteLine($"{target.Name} Action Tiggered => Play PFx Sound from file Id " + e.Param[0]);
hub.PlayAudioFile((byte)e.Param[0]);
break;
}
case TrainProgramEvent.ActionType.Play_Sound:
{
MainBoard.WriteLine($"{target.Name} Action Tiggered => Play Sound " + e.Path);
try
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(e.Path);
player.Play();
}
catch(Exception ex)
{
MainBoard.WriteLine("Error while trying to play a sound: " + ex.Message, Color.Red);
}
break;
}
case TrainProgramEvent.ActionType.Execute_Code:
{
// If we have an internal event code, we execute and stop
if (e.OnEventIsTriggered())
return;
Hub source = GetTrain(e.TrainDeviceID);
int currentTrainIndex = hubs.IndexOf(source);
string code = TrainProgramEvent.Code.Replace("%Code%", e.CodeToRun.Replace("Wait(", "await Task.Delay("));
code = code.Replace("/*%GlobalCode%*/", GlobalCode.CodeToRun.Replace("Wait(", "await Task.Delay("));
code = code.Replace("%CurrentTrainIndex%", currentTrainIndex.ToString());
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
// Reference to System.Drawing library
parameters.Referencedreplacedemblies.Add("System.dll");
parameters.Referencedreplacedemblies.Add("LegoTrainProject.exe");
parameters.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
parameters.Referencedreplacedemblies.Add("System.Drawing.dll");
// True - memory generation, false - external file generation
parameters.GenerateInMemory = true;
// True - exe file generation, false - dll file generation
parameters.GenerateExecutable = false;
// Run the code!
CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);
if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
foreach (CompilerError error in results.Errors)
{
MainBoard.WriteLine(String.Format("Compilation Error ({0}): {1}", error.ErrorNumber, error.ErrorText), Color.Red);
}
}
else
{
replacedembly replacedembly = results.Compiledreplacedembly;
Type program = replacedembly.GetType("LegoTrainProject.DynamicCode");
MethodInfo main = program.GetMethod("ExecuteCode");
try
{
ThreadStart threadMain = delegate () { main.Invoke(null, new object[] { e, this.hubs, sections }); };
new System.Threading.Thread(threadMain).Start();
}
catch (Exception ex)
{
MainBoard.WriteLine("Exception while executing your sequence: " + ex.InnerException);
}
}
break;
}
}
}
19
Source : FormCodeEditor.cs
with MIT License
from Cosmik42
with MIT License
from Cosmik42
private void buttonTestCode_Click(object sender, EventArgs ev)
{
WriteLine($"Compiling code ...", Color.Black);
string code = "";
// We are running code in a normal way
if (GlobalCode != null)
{
code = TrainProgramEvent.Code.Replace("%Code%", CodeEvent.CodeToRun.Replace("Wait(", "await Task.Delay("));
code = code.Replace("/*%GlobalCode%*/", GlobalCode.CodeToRun.Replace("Wait(", "await Task.Delay("));
}
// We are editing the global code
else
{
code = TrainProgramEvent.Code.Replace("%Code%", "");
code = code.Replace("/*%GlobalCode%*/", CodeEvent.CodeToRun.Replace("Wait(", "await Task.Delay("));
}
//var options = new Dictionary<string, string> { { "CompilerVersion", "v5.0" } };
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters parameters = new CompilerParameters();
// Reference to System.Drawing library
parameters.Referencedreplacedemblies.Add("System.dll");
parameters.Referencedreplacedemblies.Add("LegoTrainProject.exe");
parameters.Referencedreplacedemblies.Add("System.Windows.Forms.dll");
parameters.Referencedreplacedemblies.Add("System.Drawing.dll");
// True - memory generation, false - external file generation
parameters.GenerateInMemory = true;
// True - exe file generation, false - dll file generation
parameters.GenerateExecutable = false;
// Run the code!
CompilerResults results = provider.CompilereplacedemblyFromSource(parameters, code);
if (results.Errors.HasErrors)
{
StringBuilder sb = new StringBuilder();
WriteLine($"Compiling failed.", Color.Red);
foreach (CompilerError error in results.Errors)
{
WriteLine(String.Format("Error ({0}): {1}", error.ErrorNumber, error.ErrorText), Color.Red);
}
}
else
{
WriteLine($"Compiling successful!", Color.Green);
// We don't run the code if we are editing the global code itself.
if (GlobalCode != null)
{
replacedembly replacedembly = results.Compiledreplacedembly;
Type program = replacedembly.GetType("LegoTrainProject.DynamicCode");
MethodInfo main = program.GetMethod("ExecuteCode");
WriteLine($"Executing code ...", Color.Black);
try
{
main.Invoke(null, new object[] { CodeEvent, hubs, sections });
}
catch (Exception ex)
{
WriteLine("Exception while executing your sequence: " + ex.Message, Color.Red);
return;
}
WriteLine($"Executing completed!", Color.Green);
}
}
}
19
Source : ILScanner.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
public void Execute(MethodBase aStartMethod, IEnumerable<replacedembly> plugsreplacedemblies)
{
if (aStartMethod == null)
{
throw new ArgumentNullException(nameof(aStartMethod));
}
// TODO: Investigate using MS CCI
// Need to check license, as well as in profiler
// http://cciast.codeplex.com/
#region Description
// Methodology
//
// Ok - we've done the scanner enough times to know it needs to be
// doreplacedented super well so that future changes won't inadvertently
// break undoreplacedented and unseen requirements.
//
// We've tried many approaches including recursive and additive scanning.
// They typically end up being inefficient, overly complex, or both.
//
// -We would like to scan all types/methods so we can plug them.
// -But we can't scan them until we plug them, because we will scan things
// that plugs would remove/change the paths of.
// -Plugs may also call methods which are also plugged.
// -We cannot resolve plugs ahead of time but must do on the fly during
// scanning.
// -TODO: Because we do on the fly resolution, we need to add explicit
// checking of plug clreplacedes and err when public methods are found that
// do not resolve. Maybe we can make a list and mark, or rescan. Can be done
// later or as an optional auditing step.
//
// This why in the past we had repereplacedive scans.
//
// Now we focus on more preplacedes, but simpler execution. In the end it should
// be eaiser to optmize and yield overall better performance. Most of the
// preplacedes should be low overhead versus an integrated system which often
// would need to reiterate over items multiple times. So we do more loops on
// with less repereplacedive replacedysis, instead of fewer loops but more repereplacedion.
//
// -Locate all plug clreplacedes
// -Scan from entry point collecting all types and methods while checking
// for and following plugs
// -For each type
// -Include all ancestors
// -Include all static constructors
// -For each virtual method
// -Scan overloads in descendants until IsFinal, IsSealed or end
// -Scan base in ancestors until top or IsAbstract
// -Go to scan types again, until no new ones found.
// -Because the virtual method scanning will add to the list as it goes, maintain
// 2 lists.
// -Known Types and Methods
// -Types and Methods in Queue - to be scanned
// -Finally, do compilation
#endregion Description
mPlugManager.FindPlugImpls(plugsreplacedemblies);
// Now that we found all plugs, scan them.
// We have to scan them after we find all plugs, because
// plugs can use other plugs
mPlugManager.ScanFoundPlugs();
foreach (var xPlug in mPlugManager.PlugImpls)
{
CompilerHelpers.Debug($"Plug found: '{xPlug.Key.FullName}' in '{xPlug.Key.replacedembly.FullName}'");
}
ILOp.PlugManager = mPlugManager;
// Pull in extra implementations, GC etc.
Queue(RuntimeEngineRefs.InitializeApplicationRef, null, "Explicit Entry");
Queue(RuntimeEngineRefs.FinalizeApplicationRef, null, "Explicit Entry");
Queue(VTablesImplRefs.IsInstanceRef, null, "Explicit Entry");
Queue(VTablesImplRefs.SetTypeInfoRef, null, "Explicit Entry");
Queue(VTablesImplRefs.SetInterfaceInfoRef, null, "Explicit Entry");
Queue(VTablesImplRefs.SetMethodInfoRef, null, "Explicit Entry");
Queue(VTablesImplRefs.SetInterfaceMethodInfoRef, null, "Explicit Entry");
Queue(VTablesImplRefs.GetMethodAddressForTypeRef, null, "Explicit Entry");
Queue(VTablesImplRefs.GetMethodAddressForInterfaceTypeRef, null, "Explicit Entry");
Queue(VTablesImplRefs.GetDeclaringTypeOfMethodForTypeRef, null, "Explicit Entry");
Queue(GCImplementationRefs.IncRefCountRef, null, "Explicit Entry");
Queue(GCImplementationRefs.DecRefCountRef, null, "Explicit Entry");
Queue(GCImplementationRefs.AllocNewObjectRef, null, "Explicit Entry");
// for now, to ease runtime exception throwing
Queue(typeof(ExceptionHelper).GetMethod("ThrowNotImplemented", new Type[] { typeof(string) }, null), null, "Explicit Entry");
Queue(typeof(ExceptionHelper).GetMethod("ThrowOverflow", Type.EmptyTypes, null), null, "Explicit Entry");
Queue(typeof(ExceptionHelper).GetMethod("ThrowInvalidOperation", new Type[] { typeof(string) }, null), null, "Explicit Entry");
Queue(typeof(ExceptionHelper).GetMethod("ThrowArgumentOutOfRange", new Type[] { typeof(string) }, null), null, "Explicit Entry");
// register system types:
Queue(typeof(Array), null, "Explicit Entry");
Queue(typeof(Array).replacedembly.GetType("System.SZArrayHelper"), null, "Explicit Entry");
Queue(typeof(Array).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First(), null, "Explicit Entry");
Queue(typeof(MulticastDelegate).GetMethod("GetInvocationList"), null, "Explicit Entry");
Queue(ExceptionHelperRefs.CurrentExceptionRef, null, "Explicit Entry");
Queue(ExceptionHelperRefs.ThrowInvalidCastExceptionRef, null, "Explicit Entry");
Queue(ExceptionHelperRefs.ThrowNotFiniteNumberExceptionRef, null, "Explicit Entry");
Queue(ExceptionHelperRefs.ThrowDivideByZeroExceptionRef, null, "Explicit Entry");
Queue(ExceptionHelperRefs.ThrowIndexOutOfRangeException, null, "Explicit Entry");
mAsmblr.ProcessField(typeof(string).GetField("Empty", BindingFlags.Static | BindingFlags.Public));
// Start from entry point of this program
Queue(aStartMethod, null, "Entry Point");
ScanQueue();
Updatereplacedemblies();
replacedemble();
mAsmblr.EmitEntrypoint(aStartMethod);
}
19
Source : ILScanner.cs
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
with BSD 3-Clause "New" or "Revised" License
from CosmosOS
protected void ScanType(Type aType)
{
CompilerHelpers.Debug($"ILScanner: ScanType");
CompilerHelpers.Debug($"Type = '{aType}'");
// Add immediate ancestor type
// We dont need to crawl up farther, when the BaseType is scanned
// it will add its BaseType, and so on.
if (aType.BaseType != null)
{
Queue(aType.BaseType, aType, "Base Type");
}
// Queue static ctors
// We always need static ctors, else the type cannot
// be created.
foreach (var xCctor in aType.GetConstructors(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
{
if (xCctor.DeclaringType == aType)
{
Queue(xCctor, aType, "Static Constructor");
}
}
if (aType.BaseType == typeof(Array))
{
var szArrayHelper = typeof(Array).replacedembly.GetType("System.SZArrayHelper"); // We manually add the link to the generic interfaces for an array
foreach (var xMethod in szArrayHelper.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
Queue(xMethod.MakeGenericMethod(new Type[] { aType.GetElementType() }), aType, "Virtual SzArrayHelper");
}
}
// For each new type, we need to scan for possible new virtuals
// in our new type if its a descendant of something in
// mVirtuals.
foreach (var xVirt in mVirtuals)
{
// See if our new type is a subclreplaced of any virt's DeclaringTypes
// If so our new type might have some virtuals
if (aType.IsSubclreplacedOf(xVirt.DeclaringType))
{
var xParams = xVirt.GetParameters();
var xParamTypes = new Type[xParams.Length];
// Dont use foreach, enum generaly keeps order but
// isn't guaranteed.
for (int i = 0; i < xParams.Length; i++)
{
xParamTypes[i] = xParams[i].ParameterType;
}
var xMethod = aType.GetMethod(xVirt.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, xParamTypes, null);
if (xMethod != null)
{
// We need to check IsVirtual, a non virtual could
// "replace" a virtual above it?
if (xMethod.IsVirtual)
{
Queue(xMethod, aType, "Virtual");
}
}
}
else if (!aType.IsGenericParameter && xVirt.DeclaringType.IsInterface && !(aType.BaseType == typeof(Array) && xVirt.DeclaringType.IsGenericType))
{
if (!aType.IsInterface && aType.GetInterfaces().Contains(xVirt.DeclaringType))
{
var xIntfMapping = aType.GetInterfaceMap(xVirt.DeclaringType);
if ((xIntfMapping.InterfaceMethods != null) && (xIntfMapping.TargetMethods != null))
{
var xIdx = Array.IndexOf(xIntfMapping.InterfaceMethods, xVirt);
if (xIdx != -1)
{
Queue(xIntfMapping.TargetMethods[xIdx], aType, "Virtual");
}
}
}
}
}
foreach (var xInterface in aType.GetInterfaces())
{
Queue(xInterface, aType, "Implemented Interface");
}
}
19
Source : InstrumenterHelper.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
async public static Task<CoveragePrepareResult> Run<T>(Func<dynamic, Task> callMethod,
Func<string, string[]> includeFilter = null,
Func<string, string[]> excludeFilter = null,
Func<string, string[]> doesNotReturnAttributes = null,
string persistPrepareResultToFile = null,
bool disableRestoreModules = false,
bool skipAutoProps = false)
{
if (persistPrepareResultToFile is null)
{
throw new ArgumentNullException(nameof(persistPrepareResultToFile));
}
// Rename test file to avoid locks
string location = typeof(T).replacedembly.Location;
string fileName = Path.ChangeExtension($"testgen_{Path.GetFileNameWithoutExtension(Path.GetRandomFileName())}", ".dll");
string logFile = Path.ChangeExtension(fileName, ".log");
string newPath = Path.Combine(Path.GetDirectoryName(location), fileName);
File.Copy(location, newPath);
File.Copy(Path.ChangeExtension(location, ".pdb"), Path.ChangeExtension(newPath, ".pdb"));
SetTestContainer(newPath, disableRestoreModules);
static string[] defaultFilters(string _) => Array.Empty<string>();
CoverageParameters parameters = new CoverageParameters
{
IncludeFilters = (includeFilter is null ? defaultFilters(fileName) : includeFilter(fileName)).Concat(
new string[]
{
$"[{Path.GetFileNameWithoutExtension(fileName)}*]{typeof(T).FullName}*"
}).ToArray(),
IncludeDirectories = Array.Empty<string>(),
ExcludeFilters = (excludeFilter is null ? defaultFilters(fileName) : excludeFilter(fileName)).Concat(new string[]
{
"[xunit.*]*",
"[coverlet.*]*"
}).ToArray(),
ExcludedSourceFiles = Array.Empty<string>(),
ExcludeAttributes = Array.Empty<string>(),
IncludeTestreplacedembly = true,
SingleHit = false,
MergeWith = string.Empty,
UseSourceLink = false,
SkipAutoProps = skipAutoProps,
DoesNotReturnAttributes = doesNotReturnAttributes?.Invoke(fileName)
};
// Instrument module
Coverage coverage = new Coverage(newPath, parameters, new Logger(logFile),
_processWideContainer.GetService<IInstrumentationHelper>(), _processWideContainer.GetService<IFileSystem>(), _processWideContainer.GetService<ISourceRootTranslator>(), _processWideContainer.GetService<ICecilSymbolHelper>());
CoveragePrepareResult prepareResult = coverage.PrepareModules();
replacedert.Single(prepareResult.Results);
// Load new replacedembly
replacedembly asm = replacedembly.LoadFile(newPath);
// Instance type and call method
await callMethod(Activator.CreateInstance(asm.GetType(typeof(T).FullName)));
// Flush tracker
Type tracker = asm.GetTypes().Single(n => n.FullName.Contains("Coverlet.Core.Instrumentation.Tracker"));
// For debugging purpouse
// int[] hitsArray = (int[])tracker.GetField("HitsArray").GetValue(null);
// string hitsFilePath = (string)tracker.GetField("HitsFilePath").GetValue(null);
// Void UnloadModule(System.Object, System.EventArgs)
tracker.GetTypeInfo().GetMethod("UnloadModule").Invoke(null, new object[2] { null, null });
// Persist CoveragePrepareResult
using (FileStream fs = new FileStream(persistPrepareResultToFile, FileMode.Open))
{
await CoveragePrepareResult.Serialize(prepareResult).CopyToAsync(fs);
}
return prepareResult;
}
19
Source : Program.cs
with MIT License
from coverlet-coverage
with MIT License
from coverlet-coverage
private static int Main(string[] args)
{
string replacedemlbyFilePath = args[0];
string typeName = args[1];
string methodName = args[2];
string exceptionFile = args[3];
string[] additionalArgs = args.Length > 4 ?
args.Subarray(4, args.Length - 4) :
Array.Empty<string>();
replacedembly a = null;
Type t = null;
MethodInfo mi = null;
object instance = null;
int exitCode = 0;
try
{
// Create the test clreplaced if necessary
a = replacedemblyLoadContext.Default.LoadFromreplacedemblyPath(replacedemlbyFilePath);
t = a.GetType(typeName);
mi = t.GetTypeInfo().GetDeclaredMethod(methodName);
if (!mi.IsStatic)
{
instance = Activator.CreateInstance(t);
}
// Invoke the test
object result = mi.Invoke(instance, additionalArgs);
if (result is Task<int> task)
{
exitCode = task.GetAwaiter().GetResult();
}
else if (result is int exit)
{
exitCode = exit;
}
}
catch (Exception exc)
{
if (exc is TargetInvocationException && exc.InnerException != null)
exc = exc.InnerException;
var output = new StringBuilder();
output.AppendLine();
output.AppendLine("Child exception:");
output.AppendLine(" " + exc);
output.AppendLine();
output.AppendLine("Child process:");
output.AppendLine(string.Format(" {0} {1} {2}", a, t, mi));
output.AppendLine();
if (additionalArgs.Length > 0)
{
output.AppendLine("Child arguments:");
output.AppendLine(" " + string.Join(", ", additionalArgs));
}
File.WriteAllText(exceptionFile, output.ToString());
ExceptionDispatchInfo.Capture(exc).Throw();
}
finally
{
(instance as IDisposable)?.Dispose();
}
return exitCode;
}
19
Source : RuntimeInspectorUtils.cs
with MIT License
from cr4yz
with MIT License
from cr4yz
public static Type GetType( string typeName )
{
try
{
// Try Type.GetType() first. This will work with types defined
// by the Mono runtime, in the same replacedembly as the caller, etc.
var type = Type.GetType( typeName );
if( type != null )
return type;
// If the TypeName is a full name, then we can try loading the defining replacedembly directly
if( typeName.Contains( "." ) )
{
// Get the name of the replacedembly (replacedumption is that we are using
// fully-qualified type names)
var replacedemblyName = typeName.Substring( 0, typeName.IndexOf( '.' ) );
// Attempt to load the indicated replacedembly
#if UNITY_EDITOR || !NETFX_CORE
replacedembly replacedembly = replacedembly.Load( replacedemblyName );
#else
replacedembly replacedembly = replacedembly.Load( new replacedemblyName( replacedemblyName ) );
#endif
if( replacedembly == null )
return null;
// Ask that replacedembly to return the proper Type
type = replacedembly.GetType( typeName );
if( type != null )
return type;
}
else
{
#if UNITY_EDITOR || !NETFX_CORE
type = replacedembly.Load( "UnityEngine" ).GetType( "UnityEngine." + typeName );
#else
type = replacedembly.Load( new replacedemblyName( "UnityEngine" ) ).GetType( "UnityEngine." + typeName );
#endif
if( type != null )
return type;
}
#if UNITY_EDITOR || !NETFX_CORE
// Credit: https://forum.unity.com/threads/using-type-gettype-with-unity-objects.136580/#post-1799037
// Search all replacedemblies for type
foreach( replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies() )
{
foreach( Type t in replacedembly.GetTypes() )
{
if( t.Name == typeName )
return t;
}
}
#endif
}
catch { }
// The type just couldn't be found...
return null;
}
19
Source : DefaultSerializationBinder.cs
with MIT License
from CragonGame
with MIT License
from CragonGame
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
string replacedemblyName = typeNameKey.replacedemblyName;
string typeName = typeNameKey.TypeName;
if (replacedemblyName != null)
{
replacedembly replacedembly;
#if !(UNITY_WP8 || UNITY_WP_8_1) && !UNITY_WEBPLAYER && (!UNITY_WINRT || UNITY_EDITOR) && !UNITY_ANDROID
// look, I don't like using obsolete methods as much as you do but this is the only way
// replacedembly.Load won't check the GAC for a partial name
#pragma warning disable 618,612
replacedembly = replacedembly.LoadWithPartialName(replacedemblyName);
#pragma warning restore 618,612
#else
replacedembly = replacedembly.Load(replacedemblyName);
#endif
if (replacedembly == null)
throw new JsonSerializationException("Could not load replacedembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, replacedemblyName));
Type type = replacedembly.GetType(typeName);
if (type == null)
throw new JsonSerializationException("Could not find type '{0}' in replacedembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, replacedembly.FullName));
return type;
}
else
{
return Type.GetType(typeName);
}
}
See More Examples