Here are the examples of the csharp api System.Reflection.Assembly.Load(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
515 Examples
19
View Source File : ModelClassGeneratorTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 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
View Source File : TableClassGeneratorTest.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 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
View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static Type GetType(string replacedemblyName,string typeFullName)
{
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
return replacedembly.GetType(typeFullName);
}
19
View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static Type GetType(string[] replacedemblyNames,string typeFullName)
{
for (int i = 0; i < replacedemblyNames.Length; i++)
{
var replacedembly = replacedembly.Load(replacedemblyNames[i]);
var type = replacedembly.GetType(typeFullName);
if (null!=type)
{
return type;
}
}
return null;
}
19
View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 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
View Source File : EmpriseDbContext.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 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
View Source File : Startup.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public void ConfigureContainer(ContainerBuilder builder)
{
var replacedemblysServices = replacedembly.Load("Meiam.System.Interfaces");
builder.RegisterreplacedemblyTypes(replacedemblysServices)
.InstancePerDependency()//˲ʱ����
.AsImplementedInterfaces()////�Զ�����ʵ�ֵ����нӿ����ͱ�¶������IDisposable�ӿڣ�
.EnableInterfaceInterceptors(); //����Autofac.Extras.DynamicProxy;
}
19
View Source File : ResourceRepository.cs
License : MIT License
Project Creator : 99x
License : MIT License
Project Creator : 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
View Source File : DevelopTest.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private static Component _AddComponentExt(GameObject obj, string clreplacedName, int trials)
{
//Any script created by user(you)
const string userMadeScript = "replacedembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Rigidbody"
const string builtInScript = "UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Image"
const string builtInScriptUI = "UnityEngine.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "Networking"
const string builtInScriptNetwork = "UnityEngine.Networking, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "replacedyticsTracker"
const string builtInScriptreplacedytics = "UnityEngine.replacedytics, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
//Any script/component that comes with Unity such as "replacedyticsTracker"
const string builtInScriptHoloLens = "UnityEngine.HoloLens, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";
replacedembly asm = null;
try
{
//Decide if to get user script or built-in component
switch (trials)
{
case 0:
asm = replacedembly.Load(userMadeScript);
break;
case 1:
//Get UnityEngine.Component Typical component format
clreplacedName = "UnityEngine." + clreplacedName;
asm = replacedembly.Load(builtInScript);
break;
case 2:
//Get UnityEngine.Component UI format
clreplacedName = "UnityEngine.UI." + clreplacedName;
asm = replacedembly.Load(builtInScriptUI);
break;
case 3:
//Get UnityEngine.Component Video format
clreplacedName = "UnityEngine.Video." + clreplacedName;
asm = replacedembly.Load(builtInScript);
break;
case 4:
//Get UnityEngine.Component Networking format
clreplacedName = "UnityEngine.Networking." + clreplacedName;
asm = replacedembly.Load(builtInScriptNetwork);
break;
case 5:
//Get UnityEngine.Component replacedytics format
clreplacedName = "UnityEngine.replacedytics." + clreplacedName;
asm = replacedembly.Load(builtInScriptreplacedytics);
break;
case 6:
//Get UnityEngine.Component EventSystems format
clreplacedName = "UnityEngine.EventSystems." + clreplacedName;
asm = replacedembly.Load(builtInScriptUI);
break;
case 7:
//Get UnityEngine.Component Audio format
clreplacedName = "UnityEngine.Audio." + clreplacedName;
asm = replacedembly.Load(builtInScriptHoloLens);
break;
case 8:
//Get UnityEngine.Component SpatialMapping format
clreplacedName = "UnityEngine.VR.WSA." + clreplacedName;
asm = replacedembly.Load(builtInScriptHoloLens);
break;
case 9:
//Get UnityEngine.Component AI format
clreplacedName = "UnityEngine.AI." + clreplacedName;
asm = replacedembly.Load(builtInScript);
break;
}
}
catch (Exception e)
{
//Debug.Log("Failed to Load replacedembly" + e.Message);
}
//Return if replacedembly is null
if (asm == null)
{
return null;
}
//Get type then return if it is null
Type type = asm.GetType(clreplacedName);
if (type == null)
return null;
//Finally Add component since nothing is null
Component cmpnt = obj.AddComponent(type);
return cmpnt;
}
19
View Source File : ServerCoreSerializationBinder.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private Type LoadTypeFromreplacedembly(string replacedemblyName, string typeName)
{
if (string.IsNullOrEmpty(replacedemblyName) ||
string.IsNullOrEmpty(typeName))
return null;
var replacedembly = replacedembly.Load(replacedemblyName);
return FormatterServices.GetTypeFromreplacedembly(replacedembly, typeName);
}
19
View Source File : ServerManager.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private replacedembly Missing_replacedemblyResolver(object sender, ResolveEventArgs args)
{
// var asm = args.Name.Split(",")[0];
var asm = args.Requestingreplacedembly.FullName.Split(",")[0];
var a = replacedembly.Load(asm);
return a;
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
private replacedembly CurrentDomain_replacedemblyResolve(object sender, ResolveEventArgs args)
{
if (alreadyInreplacedemblyResolve.Value)
{
// Guard against stack overflow exceptions.
return null;
}
alreadyInreplacedemblyResolve.Value = true;
try
{
return replacedembly.Load(args.Name);
}
catch
{
return null;
}
finally
{
alreadyInreplacedemblyResolve.Value = false;
}
}
19
View Source File : TypeHelpers.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
public static MethodInfo ResolveGenericMethod(string replacedemblyName, string declaringTypeName, string methodName, BindingFlags bindingFlags, IEnumerable<string> typeArguments,
IEnumerable<ParamData> paramTypes)
{
var containingreplacedembly = replacedembly.Load(replacedemblyName);
var declaringType = containingreplacedembly.GetType(declaringTypeName);
var typeArgumentsCount = typeArguments.Count();
var methods = declaringType.GetMethods(bindingFlags)
.Where(c => c.Name == methodName
&& c.IsGenericMethodDefinition
&& c.GetParameters().Length == paramTypes.Count()
&& typeArgumentsCount == c.GetGenericArguments().Length);
if (methods == null)
{
throw new MissingMethodException(declaringTypeName, methodName);
}
var paramTypesArray = paramTypes.ToArray();
foreach (var mc in methods)
{
var parameters = mc.GetParameters();
var found = true;
for (var i = 0; i < parameters.Length; i++)
{
if (!CompareParameters(parameters[i], paramTypesArray[i]))
{
found = false;
break;
}
}
if (found)
{
return mc.MakeGenericMethod(typeArguments.Select(Type.GetType).ToArray());
}
}
return null;
}
19
View Source File : IWhitelistProvider.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private void Whitelistreplacedemblies(Whitelist whitelist)
{
whitelist
.replacedembly(System.Reflection.replacedembly.Load("netstandard"), Trust.Partial)
.replacedembly(System.Reflection.replacedembly.Load("System.Runtime"), Trust.Partial)
.replacedembly(System.Reflection.replacedembly.Load("System.Runtime.Extensions"), Trust.Partial)
.replacedembly(System.Reflection.replacedembly.Load("System.Private.CoreLib"), Trust.Partial)
.replacedembly(System.Reflection.replacedembly.Load("System.ObjectModel"), Trust.Partial)
.replacedembly(System.Reflection.replacedembly.Load("System.Linq"), Trust.Full)
.replacedembly(System.Reflection.replacedembly.Load("System.Collections"), Trust.Full)
.replacedembly(System.Reflection.replacedembly.Load("Google.Protobuf"), Trust.Full)
.replacedembly(typeof(CSharpSmartContract).replacedembly, Trust.Full) // AElf.Sdk.CSharp
.replacedembly(typeof(Address).replacedembly, Trust.Full) // AElf.Types
.replacedembly(typeof(IMethod).replacedembly, Trust.Full) // AElf.CSharp.Core
.replacedembly(typeof(SecretSharingHelper).replacedembly, Trust.Partial) // AElf.Cryptography
.replacedembly(typeof(ISmartContractBridgeContext).replacedembly, Trust.Full) // AElf.Kernel.SmartContract.Shared
;
}
19
View Source File : ContractsDeployer.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private static byte[] GetCode(string dllName, string contractDir, bool isPatched)
{
var dllPath = Directory.Exists(contractDir)
? Path.Combine(contractDir, isPatched ? $"{dllName}.dll.patched" : $"{dllName}.dll")
: replacedembly.Load(dllName).Location;
return File.ReadAllBytes(dllPath);
}
19
View Source File : GameContainerConfig.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
public static IContainer Configure()
{
ContainerBuilder builder = new();
builder.RegisterType<GameServer>()
.replacedelf()
.SingleInstance();
builder.RegisterType<PacketRouter<GameSession>>()
.replacedelf()
.SingleInstance();
builder.RegisterType<GameSession>()
.replacedelf();
builder.RegisterType<FieldManagerFactory>()
.replacedelf()
.SingleInstance();
// Make all packet handlers available to PacketRouter
builder.RegisterreplacedemblyTypes(replacedembly.Load(nameof(MapleServer2)))
.Where(t => typeof(IPacketHandler<GameSession>).IsreplacedignableFrom(t))
.As<IPacketHandler<GameSession>>()
.SingleInstance();
return builder.Build();
}
19
View Source File : LoginContainerConfig.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
public static IContainer Configure()
{
ContainerBuilder builder = new();
builder.RegisterType<LoginServer>()
.replacedelf()
.SingleInstance();
builder.RegisterType<PacketRouter<LoginSession>>()
.As<PacketRouter<LoginSession>>()
.SingleInstance();
builder.RegisterType<LoginSession>()
.replacedelf();
// Make all packet handlers available to PacketRouter
builder.RegisterreplacedemblyTypes(replacedembly.Load(nameof(MapleServer2)))
.Where(t => typeof(IPacketHandler<LoginSession>).IsreplacedignableFrom(t))
.As<IPacketHandler<LoginSession>>()
.SingleInstance();
return builder.Build();
}
19
View Source File : TypeUncapsulator.cs
License : MIT License
Project Creator : albahari
License : MIT License
Project Creator : albahari
public static dynamic Uncapsulate (string fullTypeName, string simplereplacedemblyName)
=> Uncapsulate (fullTypeName, replacedembly.Load (simplereplacedemblyName));
19
View Source File : Language.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public static Language GetLanguage(string languageName)
{
try
{
string languageString = languageName;
replacedembly replacedembly = replacedembly.Load("NClreplaced." + languageString);
foreach (Type type in replacedembly.GetTypes())
{
if (type.IsSubclreplacedOf(typeof(Language)))
{
object languageInstance = type.InvokeMember("Instance",
BindingFlags.Public | BindingFlags.Static | BindingFlags.GetProperty,
null, null, null);
return (languageInstance as Language);
}
}
return null;
}
catch
{
return null;
}
}
19
View Source File : Project.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private void Deserialize(XmlElement node)
{
isUnreplacedled = false;
XmlElement nameElement = node["Name"];
if (nameElement == null || nameElement.InnerText == "")
throw new InvalidDataException("Project's name cannot be empty.");
name = nameElement.InnerText;
foreach (XmlElement itemElement in node.GetElementsByTagName("Projecreplacedem"))
{
XmlAttribute typeAttribute = itemElement.Attributes["type"];
XmlAttribute replacedemblyAttribute = itemElement.Attributes["replacedembly"];
if (typeAttribute == null || replacedemblyAttribute == null)
throw new InvalidDataException("Projecreplacedem's type or replacedembly name is missing.");
string typeName = typeAttribute.InnerText;
string replacedemblyName = replacedemblyAttribute.InnerText;
try
{
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
IProjecreplacedem projecreplacedem = (IProjecreplacedem) replacedembly.CreateInstance(
typeName, false,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, null, null, null);
projecreplacedem.Deserialize(itemElement);
projecreplacedem.Clean();
Add(projecreplacedem);
}
catch (InvalidDataException)
{
throw;
}
catch (Exception ex)
{
throw new InvalidDataException("Invalid type or replacedembly of Projecreplacedem.", ex);
}
}
}
19
View Source File : Project.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private static Project LoadWithPreviousFormat(XmlElement root)
{
Project project = new Project();
project.loading = true;
replacedembly replacedembly = replacedembly.Load("NClreplaced.DiagramEditor");
IProjecreplacedem projecreplacedem = (IProjecreplacedem) replacedembly.CreateInstance(
"NClreplaced.DiagramEditor.ClreplacedDiagram.Diagram", false,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null, null, null, null);
try
{
projecreplacedem.Deserialize(root);
}
catch (Exception ex)
{
throw new InvalidDataException(Strings.ErrorCorruptSaveFile, ex);
}
project.Add(projecreplacedem);
project.loading = false;
project.isReadOnly = true;
return project;
}
19
View Source File : Opcode.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static void Open() {
int p = (int)Environment.OSVersion.Platform;
byte[] rdtscCode;
byte[] cpuidCode;
if (IntPtr.Size == 4) {
rdtscCode = RDTSC_32;
cpuidCode = CPUID_32;
} else {
rdtscCode = RDTSC_64;
if ((p == 4) || (p == 128)) { // Unix
cpuidCode = CPUID_64_LINUX;
} else { // Windows
cpuidCode = CPUID_64_WINDOWS;
}
}
size = (ulong)(rdtscCode.Length + cpuidCode.Length);
if ((p == 4) || (p == 128)) { // Unix
replacedembly replacedembly =
replacedembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " +
"PublicKeyToken=0738eb9f132ed756");
Type syscall = replacedembly.GetType("Mono.Unix.Native.Syscall");
MethodInfo mmap = syscall.GetMethod("mmap");
Type mmapProts = replacedembly.GetType("Mono.Unix.Native.MmapProts");
object mmapProtsParam = Enum.ToObject(mmapProts,
(int)mmapProts.GetField("PROT_READ").GetValue(null) |
(int)mmapProts.GetField("PROT_WRITE").GetValue(null) |
(int)mmapProts.GetField("PROT_EXEC").GetValue(null));
Type mmapFlags = replacedembly.GetType("Mono.Unix.Native.MmapFlags");
object mmapFlagsParam = Enum.ToObject(mmapFlags,
(int)mmapFlags.GetField("MAP_ANONYMOUS").GetValue(null) |
(int)mmapFlags.GetField("MAP_PRIVATE").GetValue(null));
codeBuffer = (IntPtr)mmap.Invoke(null, new object[] { IntPtr.Zero,
size, mmapProtsParam, mmapFlagsParam, -1, 0 });
} else { // Windows
codeBuffer = NativeMethods.VirtualAlloc(IntPtr.Zero,
(UIntPtr)size, AllocationType.COMMIT | AllocationType.RESERVE,
MemoryProtection.EXECUTE_READWRITE);
}
Marshal.Copy(rdtscCode, 0, codeBuffer, rdtscCode.Length);
Rdtsc = Marshal.GetDelegateForFunctionPointer(
codeBuffer, typeof(RdtscDelegate)) as RdtscDelegate;
IntPtr cpuidAddress = (IntPtr)((long)codeBuffer + rdtscCode.Length);
Marshal.Copy(cpuidCode, 0, cpuidAddress, cpuidCode.Length);
Cpuid = Marshal.GetDelegateForFunctionPointer(
cpuidAddress, typeof(CpuidDelegate)) as CpuidDelegate;
}
19
View Source File : Opcode.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public static void Close() {
Rdtsc = null;
Cpuid = null;
int p = (int)Environment.OSVersion.Platform;
if ((p == 4) || (p == 128)) { // Unix
replacedembly replacedembly =
replacedembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, " +
"PublicKeyToken=0738eb9f132ed756");
Type syscall = replacedembly.GetType("Mono.Unix.Native.Syscall");
MethodInfo munmap = syscall.GetMethod("munmap");
munmap.Invoke(null, new object[] { codeBuffer, size });
} else { // Windows
NativeMethods.VirtualFree(codeBuffer, UIntPtr.Zero,
FreeType.RELEASE);
}
}
19
View Source File : ToolManager.cs
License : Apache License 2.0
Project Creator : Algoryx
License : Apache License 2.0
Project Creator : Algoryx
private static Type FindCustomToolType( Type targetType )
{
if ( targetType == null || m_cachedIgnoredTypes.Contains( targetType ) )
return null;
Type customToolType = null;
if ( !m_cachedCustomToolTypeMap.TryGetValue( targetType, out customToolType ) ) {
Type[] types = null;
try {
types = m_replacedembliesWithCustomTools.SelectMany( name => replacedembly.Load( name ).GetTypes() ).ToArray();
}
catch ( Exception ) {
}
if ( types == null )
types = replacedembly.Load( Manager.AGXUnityEditorreplacedemblyName ).GetTypes();
var customToolTypes = new List<Type>();
foreach ( var type in types ) {
// CustomTool attribute can only be used with tools
// inheriting from CustomTargetTool.
if ( !typeof( CustomTargetTool ).IsreplacedignableFrom( type ) )
continue;
var customToolAttribute = type.GetCustomAttribute<CustomToolAttribute>( false );
if ( customToolAttribute == null )
continue;
// Exact match - break search.
if ( customToolAttribute.Type == targetType ) {
customToolTypes.Clear();
customToolTypes.Add( type );
break;
}
// Type of custom tool desired type is replacedignable from current
// target type. Store this if an exact match comes later.
// E.g.: CustomTool( typeof( Shape ) ) and CustomTool( typeof( Box ) ).
else if ( customToolAttribute.Type.IsreplacedignableFrom( targetType ) )
customToolTypes.Add( type );
}
customToolType = customToolTypes.FirstOrDefault();
if ( customToolType != null )
m_cachedCustomToolTypeMap.Add( targetType, customToolType );
}
if ( customToolType == null )
m_cachedIgnoredTypes.Add( targetType );
return customToolType;
}
19
View Source File : AutoMapperExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
public static void RegisterMapper(this IServiceCollection services)
{
var replacedemblyName = "AlonsoAdmin.Services";
// 根据程序集的名字获取程序集对象
replacedembly replacedembly = replacedembly.Load(replacedemblyName);//var replacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(replacedemblyName));
//根据程序集的名字 获取程序集中所有的类型
//var ServiceDll = Path.Combine(basePath, "Admin.Core.Service.dll");
//var replacedembly = replacedembly.LoadFrom(ServiceDll);
services.AddAutoMapper(replacedembly);
}
19
View Source File : ServiceAndRepositoryExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
private static void RegsiterServices(this IServiceCollection services, IWebHostEnvironment env = null, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
var replacedemblyName = "AlonsoAdmin.Services";
// 根据程序集的名字获取程序集对象
replacedembly replacedembly = replacedembly.Load(replacedemblyName);//var replacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(replacedemblyName));
//根据程序集的名字 获取程序集中所有的类型
IEnumerable<Type> types = replacedembly.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && t.FullName.EndsWith("Service"));
foreach (var implType in types)
{
var interfaceList = implType.GetInterfaces().Where(x => x.Name.EndsWith(implType.Name));
if (interfaceList.Any())
{
var interType = interfaceList.First();
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(interType, implType, serviceLifetime);
services.Add(serviceDescriptor);
}
}
}
19
View Source File : ServiceAndRepositoryExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
private static void RegsiterDomains(this IServiceCollection services, IWebHostEnvironment env = null, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped) {
var replacedemblyName = "AlonsoAdmin.Domain";
replacedembly replacedembly = replacedembly.Load(replacedemblyName);
//Type[] types = replacedembly.GetTypes();
//根据程序集的名字 获取程序集中Domain类
IEnumerable<Type> domianTypes = replacedembly.GetTypes().Where(t => t.IsClreplaced && !t.IsAbstract && t.FullName.EndsWith("Domain"));
foreach (var implType in domianTypes)
{
var interfaceList = implType.GetInterfaces().Where(x => x.Name.EndsWith(implType.Name));
if (interfaceList.Any()) {
var interType = interfaceList.First();
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(interType, implType, serviceLifetime);
services.Add(serviceDescriptor);
}
}
}
19
View Source File : ServiceAndRepositoryExtensions.cs
License : MIT License
Project Creator : alonsoalon
License : MIT License
Project Creator : alonsoalon
private static void RegsiterRepositories(this IServiceCollection services, IWebHostEnvironment env = null, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
var ib = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10));
ib.Notice += (_, e) =>
{
if (env != null && env.IsDevelopment())
{
//if (e.NoticeType == IdleBus<IFreeSql>.NoticeType.AutoRelease)
//_logger.LogInformation($"[{DateTime.Now.ToString("g")}] {e.Key} 空闲被回收");
}
};
// FreeSql 实例存储器ib 加入容器
services.AddSingleton(ib);
// 多租户数据工厂添加到容器
services.AddSingleton<IMulreplacedenantDbFactory, MulreplacedenantDbFactory>();
//services.AddScoped<UnitOfWorkManager>(x => new UowManager(x.GetRequiredService<IMulreplacedenantDbFactory>(), Constants.SystemDbKey));
//services.AddScoped<UnitOfWorkManager>(x => new UowManager(x.GetRequiredService<IMulreplacedenantDbFactory>(), Constants.BlogDbKey));
//services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<IMulreplacedenantDbFactory>().Db(Constants.SystemDbKey).CreateUnitOfWork());
//services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<IMulreplacedenantDbFactory>().Db(Constants.BlogDbKey).CreateUnitOfWork());
//services.AddScoped(implementationFactory =>
//{
// Func<string, UowManager> accesor = key =>
// {
// if (key.Equals(Constants.SystemDbKey))
// {
// return new UowManager(implementationFactory.GetRequiredService<IMulreplacedenantDbFactory>(), Constants.SystemDbKey);
// }
// else if (key.Equals(Constants.BlogDbKey))
// {
// return new UowManager(implementationFactory.GetRequiredService<IMulreplacedenantDbFactory>(), Constants.BlogDbKey);
// }
// else
// {
// throw new ArgumentException($"Not Support key : {key}");
// }
// };
// return accesor;
//});
var replacedemblyName = "AlonsoAdmin.Repository";
replacedembly replacedembly = replacedembly.Load(replacedemblyName); // var replacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(replacedemblyName));
//根据程序集的名字 获取程序集中所有的类型
Type[] types = replacedembly.GetTypes();
//IEnumerable<Type> uowManagerTypes = types.Where(t =>
// t.IsClreplaced &&
// !t.IsAbstract &&
// t.FullName.EndsWith("UowManager")
//);
//// 注册各个模块工作单元管理器
////services.AddScoped<IUowManager, Repository.System.UowManager>();
//foreach (var implType in uowManagerTypes)
//{
// //services.AddScoped<IUowManager, Repository.System.UowManager>();
// ServiceDescriptor uowManagerServiceDescriptor = new ServiceDescriptor(typeof(UnitOfWorkManager), implType, ServiceLifetime.Scoped);
// services.Add(uowManagerServiceDescriptor);
//}
//过滤上述程序集 得到仓储实现类
IEnumerable<Type> _types = types.Where(t =>
t.IsClreplaced &&
!t.IsAbstract &&
t.FullName.EndsWith("Repository")
);
foreach (var implType in _types)
{
var interfaceList = implType.GetInterfaces().Where(x => x.Name.EndsWith(implType.Name));
if (interfaceList.Any())
{
var interType = interfaceList.First();
//var interFullName = $"{implType.Namespace}.I{implType.Name}";
//var interType = replacedembly.GetType(interFullName);
ServiceDescriptor serviceDescriptor = new ServiceDescriptor(interType, implType, serviceLifetime);
services.Add(serviceDescriptor);
//switch (serviceLifetime)
//{
// case ServiceLifetime.Transient:
// services.AddTransient(interType, implType);
// break;
// case ServiceLifetime.Scoped:
// services.AddScoped(interType, implType);
// break;
// case ServiceLifetime.Singleton:
// services.AddSingleton(interType, implType);
// break;
//}
}
}
}
19
View Source File : AssemblyFinder.cs
License : MIT License
Project Creator : amolines
License : MIT License
Project Creator : amolines
public replacedembly Getreplacedembly(string name )
{
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
var replacedembly = replacedemblies.FirstOrDefault(a => a.GetName().Name.Equals(name)) ?? replacedembly.Load(name);
return replacedembly;
}
19
View Source File : AutoMapperSetup.cs
License : MIT License
Project Creator : andreluizsecco
License : MIT License
Project Creator : andreluizsecco
public static void AddAutoMapperSetup(this IServiceCollection services)
{
var mapper = AutoMapperConfiguration.ConfigureMappings();
services.AddAutoMapper(x => mapper.CreateMapper(), replacedembly.Load("AspNetCore.Bookstore.Application"));
}
19
View Source File : MediatRSetup.cs
License : MIT License
Project Creator : andreluizsecco
License : MIT License
Project Creator : andreluizsecco
public static void AddMediatRSetup(this IServiceCollection services) =>
services.AddMediatR(replacedembly.Load("AspNetCore.Bookstore.Domain"));
19
View Source File : Plugin.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
void IActPluginV1.InitPlugin(
TabPage pluginScreenSpace,
Label pluginStatusText)
{
replacedembly.Load("FFXIV.Framework");
PluginCore.Initialize(this);
PluginCore.Instance?.InitPluginCore(
pluginScreenSpace,
pluginStatusText);
}
19
View Source File : Plugin.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
void IActPluginV1.InitPlugin(
TabPage pluginScreenSpace,
Label pluginStatusText)
{
replacedembly.Load("FFXIV.Framework");
this.GetPluginLocation();
this.core = new PluginCore();
this.core.PluginDirectory = this.pluginDirectory;
this.core.PluginLocation = this.pluginLocation;
this.core.StartPlugin(
pluginScreenSpace,
pluginStatusText);
}
19
View Source File : Plugin.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
License : BSD 3-Clause "New" or "Revised" License
Project Creator : anoyetta
[MethodImpl(MethodImplOptions.NoInlining)]
public void InitPlugin(
TabPage pluginScreenSpace,
Label pluginStatusText)
{
replacedembly.Load("FFXIV.Framework");
PluginCore.Instance.InitPlugin(
this,
pluginScreenSpace,
pluginStatusText);
}
19
View Source File : CodeSampleExtensions.cs
License : MIT License
Project Creator : ap0llo
License : MIT License
Project Creator : ap0llo
private static MetadataReference[] GetMetadataReferences()
{
return new MetadataReference[]
{
MetadataReference.CreateFromFile(replacedembly.Load("netstandard").Location),
MetadataReference.CreateFromFile(replacedembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(object).replacedembly.Location),
MetadataReference.CreateFromFile(typeof(MdDoreplacedent).replacedembly.Location)
};
}
19
View Source File : NMSConnectionFactory.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
private static Type GetTypeForScheme(string scheme)
{
string[] paths = GetConfigSearchPaths();
string replacedemblyFileName;
string factoryClreplacedName;
Type factoryType = null;
Tracer.DebugFormat("Locating provider for scheme: {0}", scheme);
if (LookupConnectionFactoryInfo(paths, scheme, out replacedemblyFileName, out factoryClreplacedName))
{
replacedembly replacedembly = null;
Tracer.DebugFormat("Attempting to load provider replacedembly: {0}", replacedemblyFileName);
try
{
replacedembly = replacedembly.Load(replacedemblyFileName);
if (null != replacedembly)
{
Tracer.Debug("Succesfully loaded provider.");
}
}
catch (Exception ex)
{
Tracer.ErrorFormat("Exception loading replacedembly failed: {0}", ex.Message);
replacedembly = null;
}
if (null == replacedembly)
{
foreach (string path in paths)
{
string fullpath = Path.Combine(path, replacedemblyFileName) + ".dll";
Tracer.DebugFormat("Looking for: {0}", fullpath);
if (File.Exists(fullpath))
{
Tracer.Debug("\treplacedembly found! Attempting to load...");
try
{
replacedembly = replacedembly.LoadFrom(fullpath);
}
catch (Exception ex)
{
Tracer.ErrorFormat("Exception loading replacedembly failed: {0}", ex.Message);
replacedembly = null;
}
if (null != replacedembly)
{
Tracer.Debug("Successfully loaded provider.");
break;
}
Tracer.Debug("Failed to load provider. Continuing search...");
}
}
}
if (null != replacedembly)
{
#if NETCF
factoryType = replacedembly.GetType(factoryClreplacedName, true);
#else
factoryType = replacedembly.GetType(factoryClreplacedName, true, true);
#endif
if (null == factoryType)
{
Tracer.Fatal("Failed to load clreplaced factory from provider.");
}
}
else
{
Tracer.Fatal("Failed to load provider replacedembly.");
}
}
return factoryType;
}
19
View Source File : SnappyCompression.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static bool TryLoading(out ICompressorFactory? compressorFactory, out IDecompressorFactory? decompressorFactory)
{
try
{
var replacedembly = replacedembly.Load("IronSnappy");
var definedTypes = replacedembly.DefinedTypes.ToArray();
var snappy = FindSnappy(definedTypes);
var methods = snappy.GetMethods(BindingFlags.Public | BindingFlags.Static);
var decode = FindDecode(methods);
var encode = FindEncode(methods);
compressorFactory = new CompressorFactory(PulsarApi.CompressionType.Snappy, () => new Compressor(CreateCompressor(encode)));
decompressorFactory = new DecompressorFactory(PulsarApi.CompressionType.Snappy, () => new Decompressor(CreateDecompressor(decode)));
return true;
}
catch
{
// Ignore
}
compressorFactory = null;
decompressorFactory = null;
return false;
}
19
View Source File : ZstdCompression.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static bool TryLoading(out ICompressorFactory? compressorFactory, out IDecompressorFactory? decompressorFactory)
{
try
{
var replacedembly = replacedembly.Load("ZstdNet");
var definedTypes = replacedembly.DefinedTypes.ToArray();
var decompressorType = Find(definedTypes, "ZstdNet.Decompressor");
var decompressorMethods = decompressorType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
var unwrapMethod = FindUnwrap(decompressorMethods);
var compressorType = Find(definedTypes, "ZstdNet.Compressor");
var compressorMethods = compressorType.GetMethods(BindingFlags.Public | BindingFlags.Instance);
var wrapMethod = FindWrap(compressorMethods);
compressorFactory = new CompressorFactory(PulsarApi.CompressionType.Zstd, () =>
{
var compressor = Activator.CreateInstance(compressorType);
if (compressor is null)
throw new Exception($"Activator.CreateInstance returned null when trying to create a {compressorType.FullName}");
var wrap = (Wrap) wrapMethod.CreateDelegate(typeof(Wrap), compressor);
return new Compressor(CreateCompressor(wrap), (IDisposable) compressor);
});
decompressorFactory = new DecompressorFactory(PulsarApi.CompressionType.Zstd, () =>
{
var decompressor = Activator.CreateInstance(decompressorType);
if (decompressor is null)
throw new Exception($"Activator.CreateInstance returned null when trying to create a {decompressorType.FullName}");
var unwrap = (Unwrap) unwrapMethod.CreateDelegate(typeof(Unwrap), decompressor);
return new Decompressor(CreateDecompressor(unwrap), (IDisposable) decompressor);
});
return true;
}
catch
{
// Ignore
}
compressorFactory = null;
decompressorFactory = null;
return false;
}
19
View Source File : Lz4Compression.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static bool TryLoading(out ICompressorFactory? compressorFactory, out IDecompressorFactory? decompressorFactory)
{
try
{
var replacedembly = replacedembly.Load("K4os.Compression.LZ4");
var definedTypes = replacedembly.DefinedTypes.ToArray();
var lz4Codec = FindLZ4Codec(definedTypes);
var lz4Level = FindLZ4Level(definedTypes);
var methods = lz4Codec.GetMethods(BindingFlags.Public | BindingFlags.Static);
var decode = FindDecode(methods);
var encode = FindEncode(methods, lz4Level);
var maximumOutputSize = FindMaximumOutputSize(methods);
compressorFactory = new CompressorFactory(PulsarApi.CompressionType.Lz4, () => new Compressor(CreateCompressor(encode, maximumOutputSize)));
decompressorFactory = new DecompressorFactory(PulsarApi.CompressionType.Lz4, () => new Decompressor(CreateDecompressor(decode)));
return true;
}
catch
{
// Ignore
}
compressorFactory = null;
decompressorFactory = null;
return false;
}
19
View Source File : ZlibCompression.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static bool TryLoading(out ICompressorFactory? compressorFactory, out IDecompressorFactory? decompressorFactory)
{
try
{
var replacedembly = replacedembly.Load("DotNetZip");
var definedTypes = replacedembly.DefinedTypes.ToArray();
var ZlibStream = FindZlibStream(definedTypes);
var methods = ZlibStream.GetMethods(BindingFlags.Public | BindingFlags.Static);
var compressBuffer = FindCompressBuffer(methods);
var uncompressBuffer = FindUncompressBuffer(methods);
compressorFactory = new CompressorFactory(PulsarApi.CompressionType.Zlib, () => new Compressor(CreateCompressor(compressBuffer)));
decompressorFactory = new DecompressorFactory(PulsarApi.CompressionType.Zlib, () => new Decompressor(CreateDecompressor(uncompressBuffer)));
return true;
}
catch
{
// Ignore
}
compressorFactory = null;
decompressorFactory = null;
return false;
}
19
View Source File : AtlassAutofacDI.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
protected override void Load(ContainerBuilder builder)
{
//builder.RegisterType<IActionResultExecutor<HtmlResult>,HtmlResultExecutor<HtmlResult>>().
//领养AppService注入
builder.RegisterreplacedemblyTypes(replacedembly.Load("Atlreplaced.Framework.AppService"))
.Where(t => t.Name.EndsWith("AppService")).replacedelf().InstancePerLifetimeScope();
//api服务注入
//dbcontext注入
//builder.RegisterType<MySqlDbContext>().As<IAltasDbContext>().InstancePerLifetimeScope();
builder.RegisterType<AtlreplacedRequest>().As<IAtlreplacedRequest>().InstancePerLifetimeScope();
builder.RegisterType<AtlreplacedActionFilterAttribute>().replacedelf().InstancePerLifetimeScope();
builder.RegisterType<IPFilterAttribute>().replacedelf().InstancePerLifetimeScope();
if (Runtime.Windows)
{
builder.RegisterType<WindowsMachineInfo>().As<IMachineInfo>().SingleInstance();
}
else
{
builder.RegisterType<LinuxMachineInfo>().As<IMachineInfo>().SingleInstance();
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
public static Type CreateType(string typeName, string replacedembly)
{
if (string.IsNullOrEmpty(typeName)) return null;
Type type = null;
bool flag = false;
string cacheKey = string.Concat(typeName, ",", replacedembly);
lock (TypeCache)
{
flag = TypeCache.TryGetValue(cacheKey, out type);
}
if (!flag)
{
if (string.IsNullOrEmpty(replacedembly))
{
//从当前程序域里建立类型
type = Type.GetType(typeName, false, true);
if (type == null)
{
//搜索当前程序域里的所有程序集
replacedembly[] replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly asm in replacedemblies)
{
type = asm.GetType(typeName, false, true);
if (type != null) break;
}
}
}
else
{
//从某个程序集里建立类型
replacedembly asm;
if (replacedembly.IndexOf(":") != -1)
{
asm = replacedembly.LoadFrom(replacedembly);
}
else
{
asm = replacedembly.Load(replacedembly);
}
if (asm != null)
{
type = asm.GetType(typeName, false, true);
}
}
//缓存
lock (TypeCache)
{
if (!TypeCache.ContainsKey(cacheKey))
{
TypeCache.Add(cacheKey, type);
}
}
}
return type;
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
private static object GetRenderInstance(string renderInstance)
{
if (string.IsNullOrEmpty(renderInstance)) return null;
string[] k = renderInstance.Split(new char[] { ',' }, 2);
if (k.Length != 2) return null;
string replacedemblyKey = k[1].Trim();
string typeKey = k[0].Trim();
string cacheKey = string.Concat(typeKey, ",", replacedemblyKey);
//从缓存读取
object render;
bool flag = false;
lock (RenderInstanceCache)
{
flag = RenderInstanceCache.TryGetValue(cacheKey, out render);
}
if (!flag || render == null)
{
//重新生成实例
render = null;
//生成实例
replacedembly replacedembly;
if (replacedemblyKey.IndexOf(":") != -1)
{
replacedembly = replacedembly.LoadFrom(replacedemblyKey);
}
else
{
replacedembly = replacedembly.Load(replacedemblyKey);
}
if (replacedembly != null)
{
render = replacedembly.CreateInstance(typeKey, false);
}
if (render != null)
{
//缓存
lock (RenderInstanceCache)
{
if (RenderInstanceCache.ContainsKey(cacheKey))
{
RenderInstanceCache[cacheKey] = render;
}
else
{
RenderInstanceCache.Add(cacheKey, render);
}
}
}
}
return render;
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : ARKlab
License : MIT License
Project Creator : ARKlab
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
var auth0Scheme = "Auth0";
var audience = Configuration["Auth0:Audience"];
var domain = Configuration["Auth0:Domain"];
var swaggerClientId = "SwaggerClientId";
var defaultPolicy = new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(auth0Scheme)
.RequireAuthenticatedUser()
.Build();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = auth0Scheme;
options.DefaultChallengeScheme = auth0Scheme;
})
.AddJwtBearerArkDefault(auth0Scheme, audience, domain, o =>
{
if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "SpecFlow")
{
o.TokenValidationParameters.ValidIssuer = o.Authority;
o.Authority = null;
o.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(ApplicationConstants.ClientSecretSpecFlow));
}
o.TokenValidationParameters.RoleClaimType = "Role";
})
;
services.ArkConfigureSwaggerAuth0(domain, audience, swaggerClientId);
services.ArkConfigureSwaggerUI(c =>
{
c.MaxDisplayedTags(100);
c.DefaultModelRendering(ModelRendering.Model);
c.ShowExtensions();
//c.OAuthAppName("Public API");
});
services.ConfigureSwaggerGen(c =>
{
var dict = new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
},
new[] { "openid" }
}
};
c.AddSecurityRequirement(dict);
//c.AddPolymorphismSupport<Polymorphic>();
c.SchemaFilter<SwaggerExcludeFilter>();
//c.OperationFilter<SecurityRequirementsOperationFilter>();
//c.SchemaFilter<ExampleSchemaFilter<Enreplacedy.V1.Output>>(Examples.GeEnreplacedyPayload()); //Non funziona
});
//OData
services.AddOData();
//MVC
services.AddMvcCore(options =>
{
options.EnableEndpointRouting = false;
foreach (var outputFormatter in options.OutputFormatters.OfType<ODataOutputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
outputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
foreach (var inputFormatter in options.InputFormatters.OfType<ODataInputFormatter>().Where(_ => _.SupportedMediaTypes.Count == 0))
inputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/prs.odatatestxx-odata"));
});
//Add HostedService for Auditable
var replacedemblies = new List<replacedembly>
{
replacedembly.Load("RavenDbSample"),
};
services.AddHostedServiceAuditProcessor(replacedemblies);
var store = new DoreplacedentStore()
{
Database = "RavenDb",
Urls = new[]
{
"http://127.0.0.1:8080"
}
};
services.AddSingleton(store.Initialize());
}
19
View Source File : RuleTileEditor.cs
License : MIT License
Project Creator : Aroueterra
License : MIT License
Project Creator : Aroueterra
private static Type GetType(string TypeName)
{
var type = Type.GetType(TypeName);
if (type != null)
return type;
if (TypeName.Contains("."))
{
var replacedemblyName = TypeName.Substring(0, TypeName.IndexOf('.'));
var replacedembly = replacedembly.Load(replacedemblyName);
if (replacedembly == null)
return null;
type = replacedembly.GetType(TypeName);
if (type != null)
return type;
}
var currentreplacedembly = replacedembly.GetExecutingreplacedembly();
var referencedreplacedemblies = currentreplacedembly.GetReferencedreplacedemblies();
foreach (var replacedemblyName in referencedreplacedemblies)
{
var replacedembly = replacedembly.Load(replacedemblyName);
if (replacedembly != null)
{
type = replacedembly.GetType(TypeName);
if (type != null)
return type;
}
}
return null;
}
19
View Source File : Form1.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
internal static void CreateDriver(string DeviceType, int DeviceNumber, string OutputDirectory, TraceLogger TL)
{
TL.LogMessage("CreateDriver", string.Format("Creating {0} {1} in {2}", DeviceType, DeviceNumber, OutputDirectory));
try
{
// Generate the container unit
CodeCompileUnit program = new CodeCompileUnit();
// Generate the namespace
CodeNamespace ns = new CodeNamespace("ASCOM.Remote");
// Add required imports
ns.Imports.Add(new CodeNamespaceImport("System"));
ns.Imports.Add(new CodeNamespaceImport("System.Runtime.InteropServices"));
// Declare the device clreplaced
CodeTypeDeclaration deviceClreplaced = new CodeTypeDeclaration()
{
Name = DeviceType,
IsClreplaced = true
};
// Add the clreplaced base type
deviceClreplaced.BaseTypes.Add(new CodeTypeReference { BaseType = DeviceType + BASE_CLreplaced_POSTFIX });
TL.LogMessage("CreateDriver", "Created base type");
// Create custom attributes to decorate the clreplaced
CodeAttributeDeclaration guidAttribute = new CodeAttributeDeclaration("Guid", new CodeAttributeArgument(new CodePrimitiveExpression(Guid.NewGuid().ToString())));
CodeAttributeDeclaration progIdAttribute = new CodeAttributeDeclaration("ProgId", new CodeAttributeArgument(new CodeArgumentReferenceExpression("DRIVER_PROGID")));
CodeAttributeDeclaration servedClreplacedNameAttribute = new CodeAttributeDeclaration("ServedClreplacedName", new CodeAttributeArgument(new CodeArgumentReferenceExpression("DRIVER_DISPLAY_NAME")));
CodeAttributeDeclaration clreplacedInterfaceAttribute = new CodeAttributeDeclaration("ClreplacedInterface", new CodeAttributeArgument(new CodeArgumentReferenceExpression("ClreplacedInterfaceType.None")));
CodeAttributeDeclarationCollection customAttributes = new CodeAttributeDeclarationCollection() { guidAttribute, progIdAttribute, servedClreplacedNameAttribute, clreplacedInterfaceAttribute };
TL.LogMessage("CreateDriver", "Created custom attributes");
// Add the custom attributes to the clreplaced
deviceClreplaced.CustomAttributes = customAttributes;
// Create some clreplaced level private constants
CodeMemberField driverNumberConst = new CodeMemberField(typeof(string), "DRIVER_NUMBER");
driverNumberConst.Attributes = MemberAttributes.Private | MemberAttributes.Const;
driverNumberConst.InitExpression = new CodePrimitiveExpression(DeviceNumber.ToString());
CodeMemberField deviceTypeConst = new CodeMemberField(typeof(string), "DEVICE_TYPE");
deviceTypeConst.Attributes = MemberAttributes.Private | MemberAttributes.Const;
deviceTypeConst.InitExpression = new CodePrimitiveExpression(DeviceType);
CodeMemberField driverDisplayNameConst = new CodeMemberField(typeof(string), "DRIVER_DISPLAY_NAME");
driverDisplayNameConst.Attributes = (MemberAttributes.Private | MemberAttributes.Const);
driverDisplayNameConst.InitExpression = new CodeArgumentReferenceExpression(@"SharedConstants.DRIVER_DISPLAY_NAME + "" "" + DRIVER_NUMBER");
CodeMemberField driverProgIDConst = new CodeMemberField(typeof(string), "DRIVER_PROGID");
driverProgIDConst.Attributes = MemberAttributes.Private | MemberAttributes.Const;
driverProgIDConst.InitExpression = new CodeArgumentReferenceExpression(@"SharedConstants.DRIVER_PROGID_BASE + DRIVER_NUMBER + ""."" + DEVICE_TYPE");
// Add the constants to the clreplaced
deviceClreplaced.Members.AddRange(new CodeMemberField[] { driverNumberConst, deviceTypeConst, driverDisplayNameConst, driverProgIDConst });
TL.LogMessage("CreateDriver", "Added constants to clreplaced");
// Declare the clreplaced constructor
CodeConstructor constructor = new CodeConstructor();
constructor.Attributes = MemberAttributes.Public | MemberAttributes.Final;
// Add a call to the base clreplaced with required parameters
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_NUMBER"));
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_DISPLAY_NAME"));
constructor.BaseConstructorArgs.Add(new CodeArgumentReferenceExpression("DRIVER_PROGID"));
deviceClreplaced.Members.Add(constructor);
TL.LogMessage("CreateDriver", "Added base constructor");
// Add the clreplaced to the namespace
ns.Types.Add(deviceClreplaced);
TL.LogMessage("CreateDriver", "Added clreplaced to name space");
// Add the namespace to the program, which is now complete
program.Namespaces.Add(ns);
TL.LogMessage("CreateDriver", "Added name space to program");
// Get a code provider so that we can compile the program
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
TL.LogMessage("CreateDriver", "Created CSharp provider");
// Construct the path to the output DLL
String dllName = String.Format(@"{0}\ASCOM.Remote{1}.{2}.dll", OutputDirectory.TrimEnd('\\'), DeviceNumber, DeviceType);
TL.LogMessage("CreateDriver", string.Format("Output file name: {0}", dllName));
// Create relevant compiler options to shape the compilation
CompilerParameters cp = new CompilerParameters()
{
GenerateExecutable = false, // Specify output of a DLL
Outputreplacedembly = dllName, // Specify the replacedembly file name to generate
GenerateInMemory = false, // Save the replacedembly as a physical file.
TreatWarningsAsErrors = false, // Don't treat warnings as errors.
IncludeDebugInformation = true // Include debug information
};
TL.LogMessage("CreateDriver", "Created compiler parameters");
// Copy required replacedemblies to the application's working directory
replacedembly a = replacedembly.Load(@"ASCOM.Attributes, Version=6.0.0.0, Culture=neutral, PublicKeyToken=565de7938946fba7, processorArchitecture=MSIL");
TL.LogMessage("CreateDriver", string.Format("Copying ASCOM.Attributes replacedembly from {0} to {1}", a.Location, Application.StartupPath));
File.Copy(a.Location, Application.StartupPath + "\\" + Path.GetFileName(a.Location), true);
TL.LogMessage("CreateDriver", string.Format("Copied ASCOM.Attributes replacedembly OK"));
a = replacedembly.Load(@"ASCOM.DeviceInterfaces, Version=6.0.0.0, Culture=neutral, PublicKeyToken=565de7938946fba7, processorArchitecture=MSIL");
TL.LogMessage("CreateDriver", string.Format("Copying ASCOM.DeviceInterfaces replacedembly from {0} to {1}", a.Location, Application.StartupPath));
File.Copy(a.Location, Application.StartupPath + "\\" + Path.GetFileName(a.Location), true);
TL.LogMessage("CreateDriver", string.Format("Copied ASCOM.DeviceInterfaces replacedembly OK"));
// Add required replacedembly references to make sure the compilation succeeds
cp.Referencedreplacedemblies.Add(@"ASCOM.Attributes.dll"); // Has to be copied from the GAC to the local directory because the compiler doesn't use the GAC
cp.Referencedreplacedemblies.Add(@"ASCOM.DeviceInterfaces.dll"); // Has to be copied from the GAC to the local directory because the compiler doesn't use the GAC
cp.Referencedreplacedemblies.Add(@"RestSharp.dll"); // Must be present in the current directory
cp.Referencedreplacedemblies.Add(@"Newtonsoft.Json.dll"); // Must be present in the current directory
cp.Referencedreplacedemblies.Add(@"ASCOM.RemoteClientBaseClreplacedes.dll"); // Must be present in the current directory
cp.Referencedreplacedemblies.Add(@"ASCOM.RemoteClientLocalServer.exe"); // Must be present in the current directory
replacedembly executingreplacedembly = replacedembly.GetExecutingreplacedembly();
cp.Referencedreplacedemblies.Add(executingreplacedembly.Location);
foreach (replacedemblyName replacedemblyName in executingreplacedembly.GetReferencedreplacedemblies())
{
cp.Referencedreplacedemblies.Add(replacedembly.Load(replacedemblyName).Location);
}
TL.LogMessage("CreateDriver", "Added replacedembly references");
// Create formatting options for the generated code that will be logged into the trace logger
CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions()
{
BracingStyle = "C",
IndentString = " ",
VerbatimOrder = true,
BlankLinesBetweenMembers = false
};
// Write the generated code to the trace logger
using (MemoryStream outputStream = new MemoryStream())
{
using (StreamWriter writer = new StreamWriter(outputStream))
{
provider.GenerateCodeFromNamespace(ns, writer, codeGeneratorOptions);
}
MemoryStream actualStream = new MemoryStream(outputStream.ToArray());
using (StreamReader reader = new StreamReader(actualStream))
{
do
{
TL.LogMessage("GeneratedCode", reader.ReadLine());
} while (!reader.EndOfStream);
}
}
// Compile the source contained in the "program" variable
CompilerResults cr = provider.CompilereplacedemblyFromDom(cp, program);
TL.LogMessage("CreateDriver", string.Format("Compiled replacedembly - {0} errors", cr.Errors.Count));
// Report success or errors
if (cr.Errors.Count > 0)
{
// Display compilation errors.
foreach (CompilerError ce in cr.Errors)
{
TL.LogMessage("CreateDriver", string.Format("Compiler error: {0}", ce.ToString()));
}
}
else
{
// Display a successful compilation message.
TL.LogMessage("CreateDriver", "replacedembly compiled OK!");
}
TL.BlankLine();
}
catch (Exception ex)
{
TL.LogMessageCrLf("CreateDriver", ex.ToString());
}
}
19
View Source File : HostingStarterFactory.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private static replacedembly LoadProvider(params string[] names)
{
var innerExceptions = new List<Exception>();
foreach (var name in names)
{
try
{
return replacedembly.Load(name);
}
catch (FileNotFoundException ex)
{
innerExceptions.Add(ex);
}
catch (FileLoadException ex)
{
innerExceptions.Add(ex);
}
catch (BadImageFormatException ex)
{
innerExceptions.Add(ex);
}
}
throw new AggregateException(innerExceptions);
}
19
View Source File : ServerFactoryLoader.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private static replacedembly TryreplacedemblyLoad(string replacedemblyName)
{
try
{
return replacedembly.Load(replacedemblyName);
}
catch (FileNotFoundException)
{
return null;
}
}
19
View Source File : DefaultLoader.cs
License : Apache License 2.0
Project Creator : aspnet
License : Apache License 2.0
Project Creator : aspnet
private static replacedembly TryreplacedemblyLoad(string replacedemblyName)
{
try
{
return replacedembly.Load(replacedemblyName);
}
catch (FileNotFoundException)
{
return null;
}
catch (FileLoadException)
{
return null;
}
}
19
View Source File : AppDomainTypeFinder.cs
License : MIT License
Project Creator : aspnetrun
License : MIT License
Project Creator : aspnetrun
protected virtual void AddConfiguredreplacedemblies(List<string> addedreplacedemblyNames, List<replacedembly> replacedemblies)
{
foreach (var replacedemblyName in replacedemblyNames)
{
var replacedembly = replacedembly.Load(replacedemblyName);
if (addedreplacedemblyNames.Contains(replacedembly.FullName))
continue;
replacedemblies.Add(replacedembly);
addedreplacedemblyNames.Add(replacedembly.FullName);
}
}
See More Examples