Here are the examples of the csharp api System.Reflection.Assembly.GetTypes() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3019 Examples
19
Source : CelesteNetUtils.cs
with MIT License
from 0x0ade
with MIT License
from 0x0ade
private static IEnumerable<Type> _GetTypes(replacedembly asm) {
try {
return asm.GetTypes();
} catch (ReflectionTypeLoadException e) {
#pragma warning disable CS8619 // Compiler thinks this could be <Type?> even though we check for t != null
return e.Types.Where(t => t != null);
#pragma warning restore CS8619
}
}
19
Source : XnaToFnaUtil.Processor.cs
with zlib License
from 0x0ade
with zlib License
from 0x0ade
public void SetupHooks() {
// To use XnaToFnaGame properly, the actual game override needs to call XnaToFnaGame::.ctor as "base" instead.
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.Game::.ctor()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", "System.Void .ctor()");
Modder.ForceCallMap["System.Void XnaToFna.XnaToFnaGame::.ctor()"] = OpCodes.Call;
foreach (MethodInfo method in typeof(XnaToFnaGame).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
Modder.RelinkMap[method.GetFindableID(type: "Microsoft.Xna.Framework.Game")] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", method.GetFindableID(withType: false));
Modder.ForceCallMap[method.GetFindableID(withType: true)] = OpCodes.Call;
}
// XNA games expect a WinForms handle. Give it a "proxy" handle instead.
if (HookCompat) {
Modder.RelinkMap["System.IntPtr Microsoft.Xna.Framework.GameWindow::get_Handle()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr GetProxyFormHandle(Microsoft.Xna.Framework.GameWindow)");
}
// X360 games can be larger than the screen. Allow the user to "fix" this by forcing a display resolution via env vars.
if (HookHacks) {
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.GraphicsDeviceManager::ApplyChanges()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.Void ApplyChanges(Microsoft.Xna.Framework.GraphicsDeviceManager)");
}
// Let's just completely wreck everything.
foreach (Type type in typeof(Form).replacedembly.GetTypes()) {
string name = type.FullName;
// Subsreplacedute WinForms for ProxyForms
if (HookCompat && name.StartsWith("XnaToFna.ProxyForms."))
Modder.RelinkMap["System.Windows.Forms." + name.Substring(9 + 11)] = name;
// Subsreplacedute common Drawing clreplacedes (f.e. Rectangle) with our own for Drawing-less environments (f.e. Android)
else if (HookCompat && name.StartsWith("XnaToFna.ProxyDrawing."))
Modder.RelinkMap["System.Drawing." + name.Substring(9 + 13)] = name;
// Some XNA games use DInput... let's just subsreplacedute all DInput references with our ProxyDInput.
else if (name.StartsWith("XnaToFna.ProxyDInput."))
Modder.RelinkMap[/* no namespace */ name.Substring(9 + 12)] = name;
// Some X360 games use Microsoft.Xna.Framework.Xdk; let's just stub whatever's required in XTF.
else if (name.StartsWith("XnaToFna.StubXDK.")) {
string nameXDK = "Microsoft.Xna.Framework." + name.Substring(9 + 8);
Modder.RelinkMap[nameXDK] = name;
// Unfortunately, the signatures refer to GamerServices, while XnaToFna itself can't refer to that.
// Let's abuse the MonoModHook attribtue.
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = method.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, method.GetFindableID(withType: false));
}
}
foreach (ConstructorInfo ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = ctor.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, ctor.GetFindableID(withType: false));
}
}
}
}
if (HookHacks)
Modder.RelinkMap["System.Boolean Microsoft.Xna.Framework.GamerServices.Guide::get_IsTrialMode()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr get_IsTrialMode()");
if (HookBinaryFormatter) {
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create()");
// The longest relink mapping ever seen...
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)");
Modder.RelinkMap["System.Runtime.Serialization.SerializationBinder System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::get_Binder()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.SerializationBinder get_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)");
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::set_Binder(System.Runtime.Serialization.SerializationBinder)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Void set_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,System.Runtime.Serialization.SerializationBinder)");
}
if (HookReflection) {
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String,System.Reflection.BindingFlags)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String,System.Reflection.BindingFlags)");
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String)");
}
// X360 uses the ".NET Compact Framework", which actually ships with some additional stuff...
Modder.RelinkMap["System.Void System.Threading.Thread::SetProcessorAffinity(System.Int32[])"] =
new RelinkMapEntry("XnaToFna.X360Helper", "System.Void SetProcessorAffinity(System.Threading.Thread,System.Int32[])");
}
19
Source : ColumnPropertyTypeParserTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void Test()
{
var allTypes = typeof(TableColumn).replacedembly.GetTypes().Where(t => typeof(TableColumn).IsreplacedignableFrom(t)).ToList();
foreach (var type in allTypes)
{
if (type.Name != nameof(TableColumn))
{
replacedert.AreEqual("Success", ColumnPropertyTypeParser.Parse(type.Name, this, "Success"));
}
}
}
19
Source : TableClassGeneratorTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public async Task BasicTest()
{
using var dbManager = new DbManager(new DbManagerTest(),
new SqlConnection("Initial Catalog=_1_2_3tbl;"),
new GenTablesOptions(ConnectionType.MsSql, "fake", "Tab", "", "MyTables", verbosity: Verbosity.Quiet));
var tables = await dbManager.SelectTables();
replacedert.AreEqual(2, tables.Count);
var tableMap = tables.ToDictionary(t => t.DbName);
IReadOnlyDictionary<TableRef, ClreplacedDeclarationSyntax> existingCode =
new Dictionary<TableRef, ClreplacedDeclarationSyntax>();
var generator =
new TableClreplacedGenerator(tableMap, "MyCompany.MyProject.Tables", existingCode);
var trees = tables.Select(t => CSharpSyntaxTree.Create(generator.Generate(t, out _))).ToList();
var compilation = CSharpCompilation.Create("Tables",
trees,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
compilation = compilation.AddReferences(
MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
MetadataReference.CreateFromFile(replacedembly
.Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
.Location),
MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));
MemoryStream ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
if (!emitResult.Success)
{
replacedert.Fail(emitResult.Diagnostics.FirstOrDefault()?.GetMessage());
}
var replacedembly = replacedembly.Load(ms.ToArray());
var allTypes = replacedembly.GetTypes();
var table1 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[0].Name));
replacedert.NotNull(table1);
var table2 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[1].Name));
replacedert.NotNull(table2);
string table1ExpectedSql =
"CREATE TABLE [dbo].[TableZ]([Id] int NOT NULL IDENreplacedY (1, 1) DEFAULT (0),[ValueA] [nvarchar](255) NOT NULL DEFAULT (''),[Value_A] decimal(2,6),CONSTRAINT [PK_dbo_TableZ] PRIMARY KEY ([Id]));";
replacedert.AreEqual(table1ExpectedSql, TSqlExporter.Default.ToSql(table1.Script.Create()));
string table2ExpectedSql =
"CREATE TABLE [dbo].[TableA]([Id] int NOT NULL IDENreplacedY (1, 1) DEFAULT (0),[Value] datetime NOT NULL DEFAULT (GETUTCDATE()),CONSTRAINT [PK_dbo_TableA] PRIMARY KEY ([Id]),CONSTRAINT [FK_dbo__TableA_to_dbo__TableZ] FOREIGN KEY ([Id]) REFERENCES [dbo].[TableZ]([Id]),INDEX [IX_dbo_TableA_Value_DESC] UNIQUE([Value] DESC));";
replacedert.AreEqual(table2ExpectedSql, TSqlExporter.Default.ToSql(table2.Script.Create()));
}
19
Source : ModelClassGeneratorTest.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
[Test]
public void BasicTest()
{
TestFileSystem fileSystem = new TestFileSystem();
fileSystem.AddFile("A\\table1.cs", TestTable1Text);
var generated = ExistingCodeExplorer
.EnumerateTableDescriptorsModelAttributes("A", fileSystem)
.ParseAttribute(true)
.Createreplacedysis()
.Select(meta=> ModelClreplacedGenerator.Generate(meta, "Org", "", true, fileSystem, out _).SyntaxTree)
.ToList();
var trees = new List<SyntaxTree>();
foreach (var syntaxTree in generated)
{
trees.Add(CSharpSyntaxTree.ParseText(syntaxTree.ToString()));
}
trees.Add(CSharpSyntaxTree.ParseText(TestTable1Text));
var compilation = CSharpCompilation.Create("SqModels",
trees,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable));
compilation = compilation.AddReferences(
MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
MetadataReference.CreateFromFile(replacedembly
.Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
.Location),
MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));
MemoryStream ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
if (!emitResult.Success)
{
Diagnostic first = emitResult.Diagnostics.First();
var sourceCode = first.Location.SourceTree?.ToString();
var s = sourceCode?.Substring(first.Location.SourceSpan.Start, first.Location.SourceSpan.Length);
Console.WriteLine(sourceCode);
replacedert.Fail(first.GetMessage()+ (string.IsNullOrEmpty(s)?null:$" \"{s}\""));
}
var replacedembly = replacedembly.Load(ms.ToArray());
var allTypes = replacedembly.GetTypes();
replacedert.AreEqual(21, allTypes.Length);
}
19
Source : MethodJitter.cs
with MIT License
from 0xd4d
with MIT License
from 0xd4d
static IEnumerable<Type> GetTypes(replacedembly asm) {
Type?[] allTypes;
try {
allTypes = asm.GetTypes();
}
catch (ReflectionTypeLoadException ex) {
allTypes = ex.Types ?? Array.Empty<Type>();
Console.WriteLine("Failed to load one or more types");
}
bool ignoredTypeMessage = false;
foreach (var type in allTypes) {
if (!(type is null)) {
if (type.IsGenericTypeDefinition) {
if (!ignoredTypeMessage) {
ignoredTypeMessage = true;
Console.WriteLine("Ignoring all generic types");
}
continue;
}
yield return type;
}
}
}
19
Source : MelonMain.cs
with GNU General Public License v3.0
from 1330-Studios
with GNU General Public License v3.0
from 1330-Studios
internal void Set(bool val = false) {
#if AGGRESSIVE_TACTICS
//IL2CPP.ResolveICall<intIntPtrDelegate>("UnityEngine.QualitySettings::set_vSyncCount")(0);
var mods = AppDomain.CurrentDomain.Getreplacedemblies();
GC = GCTime();
MelonCoroutines.Start(GC);
#else
var mods = MelonHandler.Mods.Select(a=>a.replacedembly).ToArray();
#endif
if (!val) return;
var sw = new Stopwatch();
sw.Start();
var methodCount = 0;
#region RuntimeHelpers
for (var i = 0; i < mods.Count(); i++) {
var asm = mods[i];
var types = asm.GetTypes();
for (var j = 0; j < types.Length; j++)
try {
var type = types[j];
var methods = AccessTools.GetDeclaredMethods(type);
for (var k = 0; k < methods.Count; k++) {
RuntimeHelpers.PrepareMethod(methods[k].MethodHandle);
methodCount += 1;
}
} catch {}
}
#endregion
sw.Stop();
MelonLogger.Msg($"Optimized {methodCount:N0} methods in {sw.Elapsed.Milliseconds:N0} milliseconds!");
}
19
Source : DbBuilder.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
private void LoadRepositories()
{
if (_repositoryreplacedemblies.IsNullOrEmpty())
return;
foreach (var replacedembly in _repositoryreplacedemblies)
{
/*
* 仓储约定:
* 1、仓储统一放在Repositories目录中
* 2、仓储默认使用SqlServer数据库,如果数据库之间有差异无法通过ORM规避时,采用以下方式解决:
* a)将对应的方法定义为虚函数
* b)假如当前方法在MySql中实现有差异,则在Repositories新建一个MySql目录
* c)在MySql目录中新建一个仓储(我称之为兼容仓储)并继承默认仓储
* d)在新建的兼容仓储中使用MySql语法重写对应的方法
*/
var repositoryTypes = replacedembly.GetTypes()
.Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
//排除兼容仓储
.Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase("Repositories"))
.ToList();
//兼容仓储列表
var compatibilityRepositoryTypes = replacedembly.GetTypes()
.Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
//根据数据库类型来过滤
.Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase(Options.Provider.ToString()))
.ToList();
foreach (var type in repositoryTypes)
{
//按照框架约定,仓储的第三个接口类型就是所需的仓储接口
var interfaceType = type.GetInterfaces()[2];
//按照约定,仓储接口的第一个接口的泛型参数即为对应实体类型
var enreplacedyType = interfaceType.GetInterfaces()[0].GetGenericArguments()[0];
//保存实体描述符
DbContext.EnreplacedyDescriptors.Add(new EnreplacedyDescriptor(DbContext, enreplacedyType));
//优先使用兼容仓储
var implementationType = compatibilityRepositoryTypes.FirstOrDefault(m => m.Name == type.Name) ?? type;
Services.AddScoped(interfaceType, sp =>
{
var instance = Activator.CreateInstance(implementationType);
var initMethod = implementationType.GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic);
initMethod!.Invoke(instance, new Object[] { DbContext });
//保存仓储实例
var manager = sp.GetService<IRepositoryManager>();
manager?.Add((IRepository)instance);
return instance;
});
//保存仓储描述符
DbContext.RepositoryDescriptors.Add(new RepositoryDescriptor(enreplacedyType, interfaceType, implementationType));
}
}
}
19
Source : TestSite.cs
with MIT License
from 188867052
with MIT License
from 188867052
public IList<RouteInfo> GetAllRouteInfo()
{
var dllFile = Directory.GetFiles(Environment.CurrentDirectory, $"{this.projectName}.dll", SearchOption.AllDirectories).FirstOrDefault();
if (string.IsNullOrEmpty(dllFile))
{
throw new ArgumentException($"No {this.projectName}.dll file found under the directory: {Environment.CurrentDirectory}.");
}
Console.WriteLine($"the project name:{this.projectName}.");
Console.WriteLine($"find dll file:{dllFile}.");
replacedembly replacedembly = replacedembly.LoadFile(dllFile);
Type type = replacedembly.GetTypes().FirstOrDefault(o => o.Name == "Startup");
if (type == null)
{
throw new ArgumentException($"No Startup.cs clreplaced found under the dll file: {dllFile}.");
}
var builder = new WebHostBuilder()
.UseEnvironment("Development")
.UseContentRoot(AppContext.BaseDirectory)
.UseStartup(type);
TestServer server = new TestServer(builder);
IRoutereplacedyzer services = (IRoutereplacedyzer)server.Host.Services.GetService(typeof(IRoutereplacedyzer));
var client = server.CreateClient();
return services.GetAllRouteInfo();
}
19
Source : ServiceCollectionExtensions.cs
with MIT License
from 17MKH
with MIT License
from 17MKH
public static IServiceCollection AddServicesFromreplacedembly(this IServiceCollection services, replacedembly replacedembly)
{
foreach (var type in replacedembly.GetTypes())
{
#region ==单例注入==
var singletonAttr = (SingletonAttribute)Attribute.GetCustomAttribute(type, typeof(SingletonAttribute));
if (singletonAttr != null)
{
//注入自身类型
if (singletonAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddSingleton(i, type);
}
}
else
{
services.AddSingleton(type);
}
continue;
}
#endregion
#region ==瞬时注入==
var transientAttr = (TransientAttribute)Attribute.GetCustomAttribute(type, typeof(TransientAttribute));
if (transientAttr != null)
{
//注入自身类型
if (transientAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddTransient(i, type);
}
}
else
{
services.AddTransient(type);
}
continue;
}
#endregion
#region ==Scoped注入==
var scopedAttr = (ScopedAttribute)Attribute.GetCustomAttribute(type, typeof(ScopedAttribute));
if (scopedAttr != null)
{
//注入自身类型
if (scopedAttr.Itself)
{
services.AddSingleton(type);
continue;
}
var interfaces = type.GetInterfaces().Where(m => m != typeof(IDisposable)).ToList();
if (interfaces.Any())
{
foreach (var i in interfaces)
{
services.AddScoped(i, type);
}
}
else
{
services.AddScoped(type);
}
}
#endregion
}
return services;
}
19
Source : DotNetToJScript.cs
with MIT License
from 1y0n
with MIT License
from 1y0n
static HashSet<string> GetValidClreplacedes(byte[] replacedembly)
{
replacedembly asm = replacedembly.Load(replacedembly);
return new HashSet<string>(asm.GetTypes().Where(t => t.IsPublic && t.GetConstructor(new Type[0]) != null).Select(t => t.FullName));
}
19
Source : Function.cs
with GNU Affero General Public License v3.0
from 3CORESec
with GNU Affero General Public License v3.0
from 3CORESec
private void initConfig()
{
_alerts = new List<ISender>();
config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
if (string.IsNullOrEmpty(config.SlackPath))
config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
if (string.IsNullOrEmpty(config.WebhookChannel))
config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
if (string.IsNullOrEmpty(config.WebHookToken))
config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
if (string.IsNullOrEmpty(config.PostUrl))
config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
var type = typeof(ISender);
var types = AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
types.ToList().ForEach(type => {
ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
_alerts.Add(instance);
});
}
19
Source : LinkUtil.cs
with MIT License
from 404Lcc
with MIT License
from 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
Source : RegisterCrossBindingAdaptorHelper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static void RegisterCrossBindingAdaptor(AppDomain appdomain)
{
foreach (Type item in typeof(Init).replacedembly.GetTypes().ToList().FindAll(item => item.IsSubclreplacedOf(typeof(CrossBindingAdaptor))))
{
object obj = Activator.CreateInstance(item);
if (!(obj is CrossBindingAdaptor))
{
continue;
}
appdomain.RegisterCrossBindingAdaptor((CrossBindingAdaptor)obj);
}
}
19
Source : Manager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public void InitManager()
{
foreach (Type item in GetType().replacedembly.GetTypes())
{
if (!types.ContainsKey(item.Name))
{
types.Add(item.Name, item);
}
}
}
19
Source : MonoManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public void LoadHotfixreplacedembly()
{
Textreplacedet dllreplacedet = replacedetManager.Instance.Loadreplacedet<Textreplacedet>("Unity.Hotfix.dll", ".bytes", false, true, replacedetType.DLL);
#if Release
replacedembly = AppDomain.CurrentDomain.Load(RijndaelUtil.RijndaelDecrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", dllreplacedet.bytes));
#else
Textreplacedet pdbreplacedet = replacedetManager.Instance.Loadreplacedet<Textreplacedet>("Unity.Hotfix.pdb", ".bytes", false, true, replacedetType.DLL);
replacedembly = AppDomain.CurrentDomain.Load(RijndaelUtil.RijndaelDecrypt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", dllreplacedet.bytes), pdbreplacedet.bytes);
#endif
typeList = replacedembly.GetTypes().ToList();
OnHotfixLoaded();
}
19
Source : ResponsePacketProcessor.cs
with MIT License
from 499116344
with MIT License
from 499116344
public IPacketCommand Process()
{
var receivePackageCommandAttributes = _receivePacketType.GetCustomAttributes<ReceivePacketCommand>();
if (receivePackageCommandAttributes.Any())
{
var packetCommand = receivePackageCommandAttributes.First().Command;
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes<ResponsePacketCommand>();
if (!attributes.Any())
{
continue;
}
var responseCommand = attributes.First().Command;
if (responseCommand == packetCommand)
{
return Activator.CreateInstance(type, _args) as IPacketCommand;
}
}
}
return new DefaultResponseCommand(new QQEventArgs<ReceivePacket>(_args.Service, _args.User,
_args.ReceivePacket));
}
19
Source : ReceivePacket.cs
with MIT License
from 499116344
with MIT License
from 499116344
internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
{
if (_tlvTypes == null)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
_tlvTypes = new Dictionary<int, Type>();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is TlvTagAttribute))
{
continue;
}
var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
_tlvTypes.Add((int) attribute.Tag, type);
}
}
foreach (var tlv in tlvs)
{
if (_tlvTypes.ContainsKey(tlv.Tag))
{
var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
}
}
}
19
Source : DispatchPacketToCommand.cs
with MIT License
from 499116344
with MIT License
from 499116344
public IPacketCommand dispatch_receive_packet(QQCommand command)
{
var types = replacedembly.GetExecutingreplacedembly().GetTypes();
foreach (var type in types)
{
var attributes = type.GetCustomAttributes();
if (!attributes.Any(attr => attr is ReceivePacketCommand))
{
continue;
}
var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
if (attribute.Command == command)
{
var receivePacket =
Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
return receivePacket;
}
}
return new DefaultReceiveCommand(_data, _service, _transponder, _user);
}
19
Source : Server.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void RegisterRoutes() {
if (registeredRoutes == null) {
registeredRoutes = new List<RouteAttribute>();
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
foreach (Type type in replacedembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
RouteAttribute[] attrs = method.GetCustomAttributes(typeof(RouteAttribute), true) as RouteAttribute[];
if (attrs.Length == 0)
continue;
RouteAttribute.Callback cbm = Delegate.CreateDelegate(typeof(RouteAttribute.Callback), method, false) as RouteAttribute.Callback;
if (cbm == null) {
Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console route.", type, method.Name));
continue;
}
// try with a bare action
foreach (RouteAttribute route in attrs) {
if (route.m_route == null) {
Debug.LogError(string.Format("Method {0}.{1} needs a valid route regexp.", type, method.Name));
continue;
}
route.m_callback = cbm;
registeredRoutes.Add(route);
}
}
}
}
RegisterFileHandlers();
}
}
19
Source : Shell.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void RegisterAttributes() {
#if !NETFX_CORE
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
// HACK: IL2CPP crashes if you attempt to get the methods of some clreplacedes in these replacedemblies.
if (replacedembly.FullName.StartsWith("System") || replacedembly.FullName.StartsWith("mscorlib")) {
continue;
}
foreach (Type type in replacedembly.GetTypes()) {
// FIXME add support for non-static methods (FindObjectByType?)
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.Static)) {
CommandAttribute[] attrs = method.GetCustomAttributes(typeof(CommandAttribute), true) as CommandAttribute[];
if (attrs.Length == 0)
continue;
CommandAttribute.Callback cb = Delegate.CreateDelegate(typeof(CommandAttribute.Callback), method, false) as CommandAttribute.Callback;
if (cb == null) {
CommandAttribute.CallbackSimple cbs = Delegate.CreateDelegate(typeof(CommandAttribute.CallbackSimple), method, false) as CommandAttribute.CallbackSimple;
if (cbs != null) {
cb = delegate (string[] args) {
cbs();
};
}
}
if (cb == null) {
Debug.LogError(string.Format("Method {0}.{1} takes the wrong arguments for a console command.", type, method.Name));
continue;
}
// try with a bare action
foreach (CommandAttribute cmd in attrs) {
if (string.IsNullOrEmpty(cmd.m_command)) {
Debug.LogError(string.Format("Method {0}.{1} needs a valid command name.", type, method.Name));
continue;
}
cmd.m_callback = cb;
m_commands.Add(cmd);
}
}
}
}
#endif
}
19
Source : Utility.Reflection.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static Type[] GetImplTypes(string replacedemblyName,Type typeBase)
{
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
if (null != replacedembly)
{
List<Type> list = new List<Type>();
var types = replacedembly.GetTypes();
if (null != types)
for (int i = 0; i < types.Length; i++)
{
if (types[i].IsClreplaced && !types[i].IsAbstract && typeBase.IsreplacedignableFrom(types[i]))
{
list.Add(types[i]);
}
}
return list.ToArray();
}
return null;
}
19
Source : ServiceCollectionExtension.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
public static void AutoRegister(this IServiceCollection services)
{
#region 自动注入
var allreplacedemblies = replacedembly.GetEntryreplacedembly().GetReferencedreplacedemblies().Select(replacedembly.Load);
foreach (var serviceAsm in allreplacedemblies)
{
var serviceList = serviceAsm.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && !t.IsInterface);
foreach (Type serviceType in serviceList.Where(t => typeof(IScoped).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddScoped(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => typeof(ISingleton).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddSingleton(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => typeof(ITransient).IsreplacedignableFrom(t)))
{
var interfaceTypes = serviceType.GetInterfaces();
foreach (var interfaceType in interfaceTypes)
{
services.AddTransient(interfaceType, serviceType);
}
}
foreach (Type serviceType in serviceList.Where(t => t.IsSubclreplacedOf(typeof(BackgroundService))))
{
services.AddTransient(typeof(IHostedService), serviceType);
}
}
#endregion
}
19
Source : EmpriseDbContext.cs
with GNU Lesser General Public License v3.0
from 8720826
with GNU Lesser General Public License v3.0
from 8720826
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var typesToRegister = replacedembly.Load("Emprise.Domain").GetTypes().Where(type => !string.IsNullOrEmpty(type.Namespace) && type.BaseType == typeof(BaseEnreplacedy));
foreach (var enreplacedyType in typesToRegister)
{
if (modelBuilder.Model.FindEnreplacedyType(enreplacedyType) != null)
{
continue;
}
modelBuilder.Model.AddEnreplacedyType(enreplacedyType);
}
}
19
Source : ResourceRepository.cs
with MIT License
from 99x
with MIT License
from 99x
internal static void Initialize(replacedembly callingreplacedembly)
{
Repo = new ResourceRepository();
var ignorereplacedemblies = new string[] {"RadiumRest", "RadiumRest.Core", "RadiumRest.Selfhost", "mscorlib"};
var referencedreplacedemblies = callingreplacedembly.GetReferencedreplacedemblies();
var currentAsm = replacedembly.GetExecutingreplacedembly().GetName();
var scanreplacedemblies = new List<replacedemblyName>() { callingreplacedembly.GetName()};
foreach (var asm in referencedreplacedemblies)
{
if (asm == currentAsm)
continue;
if (!ignorereplacedemblies.Contains(asm.Name))
scanreplacedemblies.Add(asm);
}
foreach (var refAsm in scanreplacedemblies)
{
try
{
var asm = replacedembly.Load(refAsm.FullName);
foreach (var typ in asm.GetTypes())
{
if (typ.IsSubclreplacedOf(typeof(RestResourceHandler)))
{
var clreplacedAttribObj = typ.GetCustomAttributes(typeof(RestResource), false).FirstOrDefault();
string baseUrl;
if (clreplacedAttribObj != null)
{
var clreplacedAttrib = (RestResource)clreplacedAttribObj;
baseUrl = clreplacedAttrib.Path;
baseUrl = baseUrl.StartsWith("/") ? baseUrl : "/" + baseUrl;
}
else baseUrl = "";
var methods = typ.GetMethods();
foreach (var method in methods)
{
var methodAttribObject = method.GetCustomAttributes(typeof(RestPath), false).FirstOrDefault();
if (methodAttribObject != null)
{
var methodAttrib = (RestPath)methodAttribObject;
string finalUrl = baseUrl + (methodAttrib.Path ?? "");
var finalMethod = methodAttrib.Method;
PathExecutionInfo exeInfo = new PathExecutionInfo
{
Type = typ,
Method = method
};
AddExecutionInfo(finalMethod, finalUrl, exeInfo);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
19
Source : RtmpServerBuilder.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
public RtmpServer Build()
{
_options = _options ?? new RtmpServerOptions();
_options.Startup = _startup;
var types = replacedembly.GetCallingreplacedembly().GetTypes();
var registerInternalControllers = true;
_websocketOptions._serverOptions = _options;
foreach (var type in types)
{
var neverRegister = type.GetCustomAttribute<NeverRegisterAttribute>();
if (neverRegister != null)
{
continue;
}
if (typeof(NetStream).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_options.RegisterStream(type);
}
else if (typeof(RtmpController).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_options.RegisterController(type);
}
if (typeof(LivingController).IsreplacedignableFrom(type))
{
registerInternalControllers = false;
}
if (_useWebSocket)
{
if (typeof(WebSocketController).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_websocketOptions.RegisterController(type);
}
if (typeof(WebSocketPlayController).IsreplacedignableFrom(type))
{
registerInternalControllers = false;
}
}
}
if (registerInternalControllers)
{
_options.RegisterController<LivingController>();
_options.RegisterStream<LivingStream>();
_options.RegisterStream<RecordStream>();
_options.RegisterController<RecordController>();
if (_useWebSocket)
{
_websocketOptions.RegisterController<WebSocketPlayController>();
}
}
if (_useSsl)
{
_options.Cert = _cert;
}
_options.CleanupRpcRegistration();
_options.BuildContainer();
var ret = new RtmpServer(_options, _websocketOptions);
return ret;
}
19
Source : ServiceCollectionExtension.cs
with MIT License
from a34546
with MIT License
from a34546
private static void AddRepository(this IServiceCollection services, IEnumerable<replacedembly> replacedemblies, Type baseType)
{
foreach (var replacedembly in replacedemblies)
{
var types = replacedembly.GetTypes()
.Where(x => x.IsClreplaced
&& !x.IsAbstract
&& x.BaseType != null
&& x.HasImplementedRawGeneric(baseType));
foreach (var type in types)
{
var interfaces = type.GetInterfaces();
var interfaceType = interfaces.FirstOrDefault(x => x.Name == $"I{type.Name}");
if (interfaceType == null) interfaceType = type;
var serviceDescriptor = new ServiceDescriptor(interfaceType, type, ServiceLifetime.Transient);
if (!services.Contains(serviceDescriptor)) services.Add(serviceDescriptor);
}
}
}
19
Source : UMARecipeBase.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public static Type[] GetRecipeFormats()
{
if (recipeFormats == null)
{
var formats = new List<Type>(20);
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (var replacedembly in replacedemblies)
{
var types = replacedembly.GetTypes();
for (int i = 0; i < types.Length; i++)
{
var type = types[i];
if (type.IsSubclreplacedOf(typeof(UMARecipeBase)) && !type.IsAbstract)
{
formats.Add(type);
}
}
}
recipeFormats = formats.ToArray();
}
return recipeFormats;
}
19
Source : UserModule.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
[Command("help")]
[Description("List of all commands")]
//RU: Выводит список команд
public async Task Helpsync()
{
var sb = new StringBuilder();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
{
continue;
}
foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
{
DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();
if (!string.IsNullOrEmpty(desc.Description))
{
// !OC help:
sb.Append(Program.PX + ' ');
sb.Append(cmd.Text);
sb.Append(": ");
sb.Append(desc.Description);
sb.AppendLine();
}
}
}
await ReplyAsync(sb.ToString());
}
19
Source : Program.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public async Task RunBotAsync(string botToken)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
_discordClient = new DiscordSocketClient();
_commands = new CommandService();
var optionsBuilder = new DbContextOptionsBuilder<BotDataContext>();
var options = optionsBuilder
.UseSqlite(PathToDb)
.Options;
var services = new ServiceCollection()
.AddSingleton<DiscordSocketClient>(_discordClient)
.AddSingleton<ApplicationContext>()
.AddSingleton<BotDataContext>(new BotDataContext(options))
.AddSingleton<CommandService>(_commands)
.AddSingleton<OCUserRepository>()
.AddSingleton<Chanel2ServerRepository>()
.AddSingleton<DiscordManager>()
.AddSingleton<IRepository<OCUser>>(x => x.GetService<OCUserRepository>())
.AddSingleton<IRepository<Chanel2Server>>(x => x.GetService<Chanel2ServerRepository>());
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(ICommand)))
{
services.AddSingleton(type);
}
}
_services = services
.AddSingleton<Listener>()
.BuildServiceProvider();
_discordClient.Log += _discordClient_Log;
_discordClient.ChannelDestroyed += _discordClient_ChannelDestroyed;
await RegisterCommandAsync();
await _discordClient.LoginAsync(Discord.TokenType.Bot, botToken);
await _discordClient.StartAsync();
var listener = _services.GetService<Listener>();
const int WAIT_LOGIN_DISCORD_TIME = 5000;
const int REFRESH_TIME = 5000;
var t = new System.Threading.Timer((a) => { listener.UpdateChats(); }, null, WAIT_LOGIN_DISCORD_TIME, REFRESH_TIME);
await Task.Delay(-1);
}
19
Source : Service.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
private static void DependencyInjection()
{
//may better way use a native .Net Core DI
var d = new Dictionary<int, IGenerateResponseContainer>();
foreach (var type in replacedembly.GetEntryreplacedembly().GetTypes())
{
if (!type.IsClreplaced)
{
continue;
}
if (type.GetInterfaces().Any(x => x == typeof(IGenerateResponseContainer)))
{
var t = (IGenerateResponseContainer)Activator.CreateInstance(type);
d[t.RequestTypePackage] = t;
}
}
ServiceDictionary = d;
}
19
Source : LogManager.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
public static void RegisterAllEnumsFrom(replacedembly replacedembly)
{
if (replacedembly == null)
throw new ArgumentNullException(nameof(replacedembly));
foreach (var type in replacedembly.GetTypes().Where(t => t.IsEnum))
RegisterEnum(type);
}
19
Source : AssemblyExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static IEnumerable<Type> GetLoadableTypes(this replacedembly @this)
{
try
{
return @this.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
return e.Types.Where(t => t != null);
}
}
19
Source : TypeExtensions.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static List<Type> GetAllSubClreplacedesOf(this Type rootType, replacedembly[] searchreplacedemblies = null)
{
if (!rootType.IsClreplaced) return null;
if (searchreplacedemblies == null) { searchreplacedemblies = AppDomain.CurrentDomain.Getreplacedemblies(); }
var results = new List<Type>();
Parallel.ForEach(searchreplacedemblies, (replacedembly) =>
{
Parallel.ForEach(replacedembly.GetTypes(), (type) =>
{
if (type != null && type.IsClreplaced && !type.IsAbstract && type.IsSubclreplacedOf(rootType))
{
results.Add(type);
}
});
});
return results;
}
19
Source : SceneInfoUtils.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void RefreshCachedTypes()
{
if (EditorApplication.isCompiling || BuildPipeline.isBuildingPlayer)
{ // Don't refresh cached types if we're in the middle of something important
return;
}
cachedComponentTypes.Clear();
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
foreach (Type t in replacedembly.GetTypes().Where(t => t.IsSubclreplacedOf(typeof(Component))))
{
foreach (FieldInfo f in t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))
{
if (fieldTypesToSearch.Contains(f.FieldType))
{
cachedComponentTypes.Add(new Tuple<Type, FieldInfo>(t, f));
}
}
}
}
}
19
Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private Type GetEncoderType()
{
var type = AppDomain.CurrentDomain
.Getreplacedemblies()
.SelectMany(replacedembly => replacedembly.GetTypes())
.FirstOrDefault(replacedemblyType => replacedemblyType.Name == _clreplaced &&
replacedemblyType.Namespace == _namespace);
return type;
}
19
Source : DatTests.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
[TestMethod]
public void UnpackCellDatFiles_NoExceptions()
{
var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();
if (types.Count == 0)
throw new Exception("Failed to locate any types with DatFileTypeAttribute.");
DatDatabase dat = new DatDatabase(cellDatLocation);
foreach (var kvp in dat.AllFiles)
{
if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
continue;
if (kvp.Value.FileSize == 0) // DatFileType.LandBlock files can be empty
continue;
var fileType = kvp.Value.GetFileType(DatDatabaseType.Cell);
if ((kvp.Key & 0xFFFF) == 0xFFFE) fileType = DatFileType.LandBlockInfo;
if ((kvp.Key & 0xFFFF) == 0xFFFF) fileType = DatFileType.LandBlock;
//replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");
var type = types
.SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
.Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
.Select(t => t.m);
var first = type.FirstOrDefault();
if (first == null)
throw new Exception($"Failed to Unpack fileType: {fileType}");
var obj = Activator.CreateInstance(first);
var unpackable = obj as IUnpackable;
if (unpackable == null)
throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");
var datReader = new DatReader(cellDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);
using (var memoryStream = new MemoryStream(datReader.Buffer))
using (var reader = new BinaryReader(memoryStream))
{
unpackable.Unpack(reader);
if (memoryStream.Position != kvp.Value.FileSize)
throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
}
}
}
19
Source : DatTests.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
[TestMethod]
public void UnpackPortalDatFiles_NoExceptions()
{
var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();
if (types.Count == 0)
throw new Exception("Failed to locate any types with DatFileTypeAttribute.");
DatDatabase dat = new DatDatabase(portalDatLocation);
foreach (var kvp in dat.AllFiles)
{
if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
continue;
var fileType = kvp.Value.GetFileType(DatDatabaseType.Portal);
//replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");
// These file types aren't converted yet
if (fileType == DatFileType.KeyMap) continue;
if (fileType == DatFileType.RenderMaterial) continue;
if (fileType == DatFileType.MaterialModifier) continue;
if (fileType == DatFileType.MaterialInstance) continue;
if (fileType == DatFileType.ActionMap) continue;
if (fileType == DatFileType.MasterProperty) continue;
if (fileType == DatFileType.DbProperties) continue;
var type = types
.SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new {m, a})
.Where(t => ((DatFileTypeAttribute) t.a).FileType == fileType)
.Select(t => t.m);
var first = type.FirstOrDefault();
if (first == null)
throw new Exception($"Failed to Unpack fileType: {fileType}");
var obj = Activator.CreateInstance(first);
var unpackable = obj as IUnpackable;
if (unpackable == null)
throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");
var datReader = new DatReader(portalDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);
using (var memoryStream = new MemoryStream(datReader.Buffer))
using (var reader = new BinaryReader(memoryStream))
{
unpackable.Unpack(reader);
if (memoryStream.Position != kvp.Value.FileSize)
throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
}
}
}
19
Source : DatTests.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
[TestMethod]
public void UnpackLocalEnglishDatFiles_NoExceptions()
{
var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();
if (types.Count == 0)
throw new Exception("Failed to locate any types with DatFileTypeAttribute.");
DatDatabase dat = new DatDatabase(localEnglishDatLocation);
foreach (var kvp in dat.AllFiles)
{
if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
continue;
var fileType = kvp.Value.GetFileType(DatDatabaseType.Language);
//replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");
// These file types aren't converted yet
if (fileType == DatFileType.UiLayout) continue;
var type = types
.SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
.Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
.Select(t => t.m);
var first = type.FirstOrDefault();
if (first == null)
throw new Exception($"Failed to Unpack fileType: {fileType}");
var obj = Activator.CreateInstance(first);
var unpackable = obj as IUnpackable;
if (unpackable == null)
throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");
var datReader = new DatReader(localEnglishDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);
using (var memoryStream = new MemoryStream(datReader.Buffer))
using (var reader = new BinaryReader(memoryStream))
{
unpackable.Unpack(reader);
if (memoryStream.Position != kvp.Value.FileSize)
throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
}
}
}
19
Source : CommandManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static void Initialize()
{
commandHandlers = new Dictionary<string, CommandHandlerInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
foreach (var method in type.GetMethods())
{
foreach (var attribute in method.GetCustomAttributes<CommandHandlerAttribute>())
{
var commandHandler = new CommandHandlerInfo()
{
Handler = (CommandHandler)Delegate.CreateDelegate(typeof(CommandHandler), method),
Attribute = attribute
};
commandHandlers[attribute.Command] = commandHandler;
}
}
}
if (NonInteractiveConsole)
{
log.Info("ACEmulator command prompt disabled - Environment.GetEnvironmentVariable(ACE_NONINTERACTIVE_CONSOLE) was true");
return;
}
var thread = new Thread(new ThreadStart(CommandThread));
thread.Name = "Command Manager";
thread.IsBackground = true;
thread.Start();
}
19
Source : LootSwap.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static Dictionary<string, Type> GetTypes(string prefix)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var types = replacedembly.GetTypes();
return types.Where(i => i.FullName.StartsWith(prefix)).ToDictionary(i => i.FullName.Substring(i.FullName.LastIndexOf('.') + 1), i => i);
}
19
Source : InboundMessageManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void DefineMessageHandlers()
{
messageHandlers = new Dictionary<GameMessageOpcode, MessageHandlerInfo>();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
foreach (var methodInfo in type.GetMethods())
{
foreach (var messageHandlerAttribute in methodInfo.GetCustomAttributes<GameMessageAttribute>())
{
var messageHandler = new MessageHandlerInfo()
{
Handler = (MessageHandler)Delegate.CreateDelegate(typeof(MessageHandler), methodInfo),
Attribute = messageHandlerAttribute
};
messageHandlers[messageHandlerAttribute.Opcode] = messageHandler;
}
}
}
}
19
Source : InboundMessageManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
private static void DefineActionHandlers()
{
actionHandlers = new Dictionary<GameActionType, ActionHandlerInfo>();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
foreach (var methodInfo in type.GetMethods())
{
foreach (var actionHandlerAttribute in methodInfo.GetCustomAttributes<GameActionAttribute>())
{
var actionhandler = new ActionHandlerInfo()
{
Handler = (ActionHandler)Delegate.CreateDelegate(typeof(ActionHandler), methodInfo),
Attribute = actionHandlerAttribute
};
actionHandlers[actionHandlerAttribute.Opcode] = actionhandler;
}
}
}
}
19
Source : Runner.cs
with MIT License
from actions
with MIT License
from 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
Source : WrappedException.cs
with MIT License
from actions
with MIT License
from actions
private static void UpdateExceptionAttributeMappingCache()
{
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies().Where(a => !s_replacedembliesCheckedForExceptionMappings.Contains(a)))
{
if (DoesreplacedemblyQualify(replacedembly)) // only look at replacedemblies that match this binary's major version and public key token
{
try
{
IEnumerable<Type> types;
try
{
// calling GetTypes has side effect of loading direct dependancies of the replacedembly.
types = replacedembly.GetTypes();
}
catch (ReflectionTypeLoadException ex)
{
// if dependant replacedembly fails to load, we should still be able to get all the exceptions, since it would be unlikely,
// that an exception is referencing a type from the replacedembly that failed to load.
types = ex.Types.Where<Type>(t => t != null);
}
foreach (TypeInfo typeInfo in types)
{
foreach (ExceptionMappingAttribute attribute in typeInfo.GetCustomAttributes<ExceptionMappingAttribute>())
{
Tuple<Version, Type> cachedValue;
// Check if the TypeName already exists in cache and add it if not. if it does exist, update if it has a higher ExclusiveMaxApiVersion.
// (In theory an old exception could be mapped to more then one type in the case we want the latest server
// to send different older types to different versions of older clients. This method is used only on client when converting a type
// from an older server, so we want the latest mapping of the older type.)
if (!s_exceptionsWithAttributeMapping.TryGetValue(attribute.TypeName, out cachedValue) || attribute.ExclusiveMaxApiVersion > cachedValue.Item1)
{
s_exceptionsWithAttributeMapping[attribute.TypeName] = new Tuple<Version, Type>(attribute.ExclusiveMaxApiVersion, typeInfo.AsType());
}
}
}
}
catch (Exception)
{
// if for any reason we can't get the defined types, we don't want an exception here to mask the real exception.
}
}
s_replacedembliesCheckedForExceptionMappings.Add(replacedembly); // keep track of all replacedemblies we have either ruled out or cached mappings for, so we don't have to consider them again
}
}
19
Source : RoslynDiagnosticService.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private static Type GetInternalRoslynServiceType()
{
Type diagnosticreplacedyzerServiceType = (from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
where replacedembly.FullName.StartsWith(RoslynDiagnosticServicereplacedemblyName)
from type in replacedembly.GetTypes()
where type.IsInterface && type.Name == RoslynDiagnosticServiceTypeName
select type)
.FirstOrDefault();
return diagnosticreplacedyzerServiceType;
}
19
Source : OutOfProcessSettingValueProvider.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
internal static bool IsOutOfProcessEnabled(this AreplacedinatorVSPackage package, Workspace workspace)
{
package.ThrowOnNull(nameof(package));
package.VSVersion.ThrowOnNull($"{nameof(AreplacedinatorVSPackage)}.{nameof(AreplacedinatorVSPackage.VSVersion)}");
if (!package.VSVersion.IsVS2019)
return false;
// Faster version gets setting OOP64Bit from the VS session store. If it is true then the OOP is enabled
bool? outOfProcessFromSettingsStore = GetOutOfProcessSettingFromSessionStore(package);
if (outOfProcessFromSettingsStore == true)
return true;
// If OOP is false or its retrieval failed then we need to resort to the internal Roslyn helper RemoteHostOptions.IsUsingServiceHubOutOfProcess
if (workspace?.Services != null)
{
Type remoteHostOptionsType = (from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
where replacedembly.GetName().Name == "Microsoft.Codereplacedysis.Remote.Workspaces"
from type in replacedembly.GetTypes()
where type.IsClreplaced && type.IsAbstract && type.IsSealed && !type.IsPublic && type.Name == "RemoteHostOptions"
select type)
.SingleOrDefault();
MethodInfo isUsingServiceHubOutOfProcess = remoteHostOptionsType?.GetMethod("IsUsingServiceHubOutOfProcess",
BindingFlags.Static | BindingFlags.Public);
object isOutOfProcessFromRoslynInternalsObj = isUsingServiceHubOutOfProcess?.Invoke(null, new object[] { workspace.Services });
if (isOutOfProcessFromRoslynInternalsObj is bool isOutOfProcessFromRoslynInternals)
return isOutOfProcessFromRoslynInternals;
}
return false;
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterTransientDependency()
{
var types = replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
RegisterRpcServer(types);
RegisterSubscriber(types);
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterRpcServer(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(RpcServerAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
RpcServerMethodList = dicMethod.Select(d => d.Value).ToList();
var first = RpcServerMethodList.Select(d => d.GetCustomAttribute<RpcServerAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"RpcServr Key 重复:{first.Key}");
}
19
Source : DependencyRegistrator.cs
with MIT License
from ad313
with MIT License
from ad313
private void RegisterSubscriber(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(SubscriberAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
SubscriberMethodList = dicMethod.Select(d => d.Value).ToList();
var first = SubscriberMethodList.Select(d => d.GetCustomAttribute<SubscriberAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"Subscriber Key 重复:{first.Key}");
}
See More Examples