Here are the examples of the csharp api System.AppDomain.GetAssemblies() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1645 Examples
19
View Source File : FileSystemUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void CopyTo(UserData other) {
using UserDataBatchContext batch = other.OpenBatch();
lock (GlobalLock) {
Global global = LoadRaw<Global>(GlobalPath);
Dictionary<string, Type?> types = new();
replacedembly[] asms = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (string uid in GetAll()) {
PrivateUserInfo info = Load<PrivateUserInfo>(uid);
other.Insert(uid, info.Key, info.KeyFull, !info.KeyFull.IsNullOrEmpty());
foreach (string path in Directory.GetFiles(Path.Combine(UserRoot, uid))) {
string name = Path.GetFileNameWithoutExtension(path);
if (name == typeof(PrivateUserInfo).FullName)
continue;
if (!types.TryGetValue(name, out Type? type)) {
foreach (replacedembly asm in asms)
if ((type = asm.GetType(name)) != null)
break;
types[name] = type;
}
using Stream stream = File.OpenRead(path);
other.InsertData(uid, name, type, stream);
}
string dir = Path.Combine(UserRoot, uid, "data");
if (Directory.Exists(dir)) {
foreach (string path in Directory.GetFiles(dir)) {
string name = Path.GetFileName(path);
using Stream stream = File.OpenRead(path);
other.InsertFile(uid, name, stream);
}
}
}
}
}
19
View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
[RCEndpoint(true, "/asms", null, null, "replacedembly List", "List of all loaded replacedemblies.")]
public static void ASMs(Frontend f, HttpRequestEventArgs c) {
f.RespondJSON(c, AppDomain.CurrentDomain.Getreplacedemblies().Select(asm => new {
asm.GetName().Name,
Version = asm.GetName().Version?.ToString() ?? "",
Context =
#if NETCORE
(replacedemblyLoadContext.GetLoadContext(asm) ?? replacedemblyLoadContext.Default)?.Name ?? "Unknown",
#else
AppDomain.CurrentDomain.FriendlyName
#endif
}).ToList());
}
19
View Source File : CelesteNetUtils.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
private static IEnumerable<replacedembly> _Getreplacedemblies()
=> (Everest.Modules?.Select(m => m.GetType().replacedembly) ?? new replacedembly[0])
.Concat(AppDomain.CurrentDomain.Getreplacedemblies())
.Distinct();
19
View Source File : MelonMain.cs
License : GNU General Public License v3.0
Project Creator : 1330-Studios
License : GNU General Public License v3.0
Project Creator : 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
View Source File : ApiHelperController.cs
License : MIT License
Project Creator : 279328316
License : MIT License
Project Creator : 279328316
[HttpPost]
[AllowAnonymous]
[Route("[action]")]
public IActionResult GetApiVersion()
{
Robj<string> robj = new Robj<string>();
List<replacedembly> replacedemblyList = AppDomain.CurrentDomain.Getreplacedemblies().ToList();
AppDomain currentDomain = AppDomain.CurrentDomain;
replacedembly replacedembly = replacedemblyList.FirstOrDefault(a=>a.GetName().Name==currentDomain.FriendlyName);
if (replacedembly != null)
{
//replacedemblyFileVersionAttribute fileVersionAttr = replacedembly.GetCustomAttribute<replacedemblyFileVersionAttribute>();
replacedemblyInformationalVersionAttribute versionAttr = replacedembly.GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
robj.Result = versionAttr?.InformationalVersion;
}
return new JsonResult(robj);
}
19
View Source File : Function.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 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
View Source File : Server.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 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
View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 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
View Source File : Utility.Reflection.cs
License : MIT License
Project Creator : 7Bytes-Studio
License : MIT License
Project Creator : 7Bytes-Studio
public static bool Hasreplacedembly(string asmName)
{
foreach (replacedembly replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (replacedembly.GetName().Name == asmName)
return true;
}
return false;
}
19
View Source File : AutoMapperExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public static void AddAutoMapper(this IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
//添加服务
//可以添加筛选
services.AddAutoMapper(AppDomain.CurrentDomain.Getreplacedemblies().Where(t => t.GetName().ToString().StartsWith("Emprise.")));
//启动配置
AutoMapperConfig.RegisterMappings();
}
19
View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private static Type GetPowerPackPersistanceType()
{
if (powerPackPersistance == null)
{
foreach (var replacedembly in System.AppDomain.CurrentDomain.Getreplacedemblies())
{
powerPackPersistance = replacedembly.GetType("UMA.PowerTools.PowerPackPersistance");
if (powerPackPersistance != null) break;
}
}
return powerPackPersistance;
}
19
View Source File : PowerToolsIntegration.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private static Type GetUMAEditorAvatarType()
{
if (umaEditorAvatarType == null)
{
foreach (var replacedembly in System.AppDomain.CurrentDomain.Getreplacedemblies())
{
umaEditorAvatarType = replacedembly.GetType("UMA.PowerTools.UMAEditorAvatar");
if (umaEditorAvatarType != null) break;
}
}
return umaEditorAvatarType;
}
19
View Source File : UMARecipeBase.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : 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
View Source File : AppenderFactory.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
private static Type? GetAppenderType(AppenderDefinition definition)
{
if (string.IsNullOrEmpty(definition.AppenderTypeName))
return null;
// Check if we have an replacedembly-qualified name of a type
if (definition.AppenderTypeName!.Contains(","))
return Type.GetType(definition.AppenderTypeName, true, false);
return AppDomain.CurrentDomain.Getreplacedemblies()
.Select(x => x.GetType(definition.AppenderTypeName))
.FirstOrDefault(x => x != null);
}
19
View Source File : TypeExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : 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
View Source File : MixedRealityProfileCloneWindow.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static System.Type FindProfileType(string profileTypeName)
{
System.Type type = null;
foreach (replacedembly replacedembly in System.AppDomain.CurrentDomain.Getreplacedemblies())
{
foreach (System.Type checkType in replacedembly.GetLoadableTypes())
{
if (checkType.Name == profileTypeName)
{
type = checkType;
break;
}
}
}
return type;
}
19
View Source File : SceneInfoUtils.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : 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
View Source File : TypeReferencePropertyDrawer.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static List<Type> GetFilteredTypes(SystemTypeAttribute filter)
{
var types = new List<Type>();
var excludedTypes = ExcludedTypeCollectionGetter?.Invoke();
// We prefer using this over CompilationPipeline.Getreplacedemblies() because
// some types may come from plugins and other sources that have already
// been compiled.
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (var replacedembly in replacedemblies)
{
FilterTypes(replacedembly, filter, excludedTypes, types);
}
types.Sort((a, b) => string.Compare(a.FullName, b.FullName, StringComparison.Ordinal));
return types;
}
19
View Source File : MixedRealityInspectorUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static Type[] GetAllDerivedTypes(this AppDomain appDomain, Type aType)
{
var result = new List<Type>();
var replacedemblies = appDomain.Getreplacedemblies();
foreach (var replacedembly in replacedemblies)
{
var types = replacedembly.GetLoadableTypes();
result.AddRange(types.Where(type => type.IsSubclreplacedOf(aType)));
}
return result.ToArray();
}
19
View Source File : ServiceFacadeInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static void InitializeServiceInspectorLookup()
{
if (initializedServiceInspectorLookup)
{
return;
}
inspectorTypeLookup.Clear();
var typesWithMyAttribute =
from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies().AsParallel()
from clreplacedType in replacedembly.GetLoadableTypes()
let attribute = clreplacedType.GetCustomAttribute<MixedRealityServiceInspectorAttribute>(true)
where attribute != null
select new { ClreplacedType = clreplacedType, Attribute = attribute };
foreach (var result in typesWithMyAttribute)
{
inspectorTypeLookup.Add(result.Attribute.ServiceType, result.ClreplacedType);
}
initializedServiceInspectorLookup = true;
}
19
View Source File : ObjectManipulatorInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public override void OnInspectorGUI()
{
EditorGUILayout.PropertyField(hostTransform);
EditorGUILayout.PropertyField(manipulationType);
EditorGUILayout.PropertyField(allowFarManipulation);
var handedness = (ManipulationHandFlags)manipulationType.intValue;
EditorGUILayout.Space();
GUIStyle style = EditorStyles.foldout;
FontStyle previousStyle = style.fontStyle;
style.fontStyle = FontStyle.Bold;
oneHandedFoldout = EditorGUILayout.Foldout(oneHandedFoldout, "One Handed Manipulation", true);
if (oneHandedFoldout)
{
if (handedness.HasFlag(ManipulationHandFlags.OneHanded))
{
EditorGUILayout.PropertyField(oneHandRotationModeNear);
EditorGUILayout.PropertyField(oneHandRotationModeFar);
}
else
{
EditorGUILayout.HelpBox("One handed manipulation disabled. If you wish to enable one handed manipulation select it as a Manipulation Type above.", MessageType.Info);
}
}
EditorGUILayout.Space();
twoHandedFoldout = EditorGUILayout.Foldout(twoHandedFoldout, "Two Handed Manipulation", true);
if (twoHandedFoldout)
{
if (handedness.HasFlag(ManipulationHandFlags.TwoHanded))
{
EditorGUILayout.PropertyField(twoHandedManipulationType);
}
else
{
EditorGUILayout.HelpBox("Two handed manipulation disabled. If you wish to enable two handed manipulation select it as a Manipulation Type above.", MessageType.Info);
}
}
var mh = (ObjectManipulator)target;
var rb = mh.HostTransform.GetComponent<Rigidbody>();
EditorGUILayout.Space();
constraintsFoldout = EditorGUILayout.Foldout(constraintsFoldout, "Constraints", true);
if (constraintsFoldout)
{
if (EditorGUILayout.DropdownButton(new GUIContent("Add Constraint"), FocusType.Keyboard))
{
// create the menu and add items to it
GenericMenu menu = new GenericMenu();
var type = typeof(TransformConstraint);
var types = AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(s => s.GetLoadableTypes())
.Where(p => type.IsreplacedignableFrom(p));
foreach (var derivedType in types)
{
menu.AddItem(new GUIContent(derivedType.Name), false, t => mh.gameObject.AddComponent((Type)t), derivedType);
}
menu.ShowAsContext();
}
var constraints = mh.GetComponents<TransformConstraint>();
foreach (var constraint in constraints)
{
EditorGUILayout.BeginHorizontal();
string constraintName = constraint.GetType().Name;
EditorGUILayout.LabelField(constraintName);
if (GUILayout.Button("Go to component"))
{
Highlighter.Highlight("Inspector", $"{ObjectNames.NicifyVariableName(constraintName)} (Script)");
EditorGUIUtility.ExitGUI();
}
EditorGUILayout.EndHorizontal();
}
}
EditorGUILayout.Space();
physicsFoldout = EditorGUILayout.Foldout(physicsFoldout, "Physics", true);
if (physicsFoldout)
{
if (rb != null)
{
EditorGUILayout.PropertyField(releaseBehavior);
}
else
{
EditorGUILayout.HelpBox("Physics options disabled. If you wish to enable physics options, add a Rigidbody component to this object.", MessageType.Info);
}
}
EditorGUILayout.Space();
smoothingFoldout = EditorGUILayout.Foldout(smoothingFoldout, "Smoothing", true);
if (smoothingFoldout)
{
EditorGUILayout.PropertyField(smoothingActive);
EditorGUILayout.PropertyField(moveLerpTime);
EditorGUILayout.PropertyField(rotateLerpTime);
EditorGUILayout.PropertyField(scaleLerpTime);
}
EditorGUILayout.Space();
eventsFoldout = EditorGUILayout.Foldout(eventsFoldout, "Manipulation Events", true);
if (eventsFoldout)
{
EditorGUILayout.PropertyField(onManipulationStarted);
EditorGUILayout.PropertyField(onManipulationEnded);
EditorGUILayout.PropertyField(onHoverEntered);
EditorGUILayout.PropertyField(onHoverExited);
}
// reset foldouts style
style.fontStyle = previousStyle;
serializedObject.ApplyModifiedProperties();
}
19
View Source File : SyncUsageHelper.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private Type GetEncoderType()
{
var type = AppDomain.CurrentDomain
.Getreplacedemblies()
.SelectMany(replacedembly => replacedembly.GetTypes())
.FirstOrDefault(replacedemblyType => replacedemblyType.Name == _clreplaced &&
replacedemblyType.Namespace == _namespace);
return type;
}
19
View Source File : WrappedException.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : 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
View Source File : SyntaxEditorHelper.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public static void AddCommonDotNetSystemreplacedemblyReferences(IProjectreplacedembly projectreplacedembly) {
if (projectreplacedembly is null)
throw new ArgumentNullException(nameof(projectreplacedembly));
// Iterate the replacedemblies in the AppDomain and load all "System" replacedemblies
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
if ((replacedembly.FullName.StartsWith("System", StringComparison.OrdinalIgnoreCase)) ||
(replacedembly.FullName.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase))) {
projectreplacedembly.replacedemblyReferences.Add(replacedembly);
}
}
}
19
View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private void BindProducts() {
// Manually reference these type to ensure the related replacedemblies are loaded since they may not yet have been loaded by default
var srTypes = new Type[] {
// None: typeof(ActiproSoftware.Products.SyntaxEditor.Addons.JavaScript.SR),
typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Python.SR),
typeof(ActiproSoftware.Products.SyntaxEditor.Addons.Xml.SR),
typeof(ActiproSoftware.Products.Text.Addons.JavaScript.SR),
typeof(ActiproSoftware.Products.Text.Addons.Python.SR),
typeof(ActiproSoftware.Products.Text.Addons.Xml.SR),
};
var productResources = new List<ProductResource>();
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()) {
var name = replacedembly.GetName().Name;
if ((name.StartsWith("ActiproSoftware.", StringComparison.OrdinalIgnoreCase)) && (name.EndsWith(".Wpf", StringComparison.OrdinalIgnoreCase))) {
var productResource = new ProductResource(replacedembly);
if (productResource.IsValid)
productResources.Add(productResource);
}
}
productResources.Sort((x, y) => x.Name.CompareTo(y.Name));
productComboBox.ItemsSource = productResources;
if (productComboBox.Items.Count > 0)
productComboBox.SelectedIndex = 0;
}
19
View Source File : AcuminatorVsixPackageLoader.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private static void SearchForVsixAndEnsureItIsLoadedPackageLoaded()
{
var vsixreplacedembly = AppDomain.CurrentDomain.Getreplacedemblies()
.FirstOrDefault(a => a.GetName().Name == SharedConstants.PackageName);
if (vsixreplacedembly == null)
return;
var areplacedinatorPackageType = vsixreplacedembly.GetExportedTypes().FirstOrDefault(t => t.Name == VsixPackageType);
if (areplacedinatorPackageType == null)
return;
var dummyServiceCaller = areplacedinatorPackageType.GetMethod(ForceLoadPackageAsync, BindingFlags.Static | BindingFlags.Public);
if (dummyServiceCaller == null)
return;
object loadTask = null;
try
{
loadTask = dummyServiceCaller.Invoke(null, Array.Empty<object>());
}
catch
{
return;
}
if (loadTask is Task task)
{
const int defaultTimeoutSeconds = 20;
task.Wait(TimeSpan.FromSeconds(defaultTimeoutSeconds));
}
}
19
View Source File : RoslynDiagnosticService.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : 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
View Source File : OutOfProcessSettingValueProvider.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : 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
View Source File : TypeFinder.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private List<replacedembly> GetreplacedembliesFromCurrentAppDomain()
{
var result = new List<replacedembly>();
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (Match(replacedembly))
result.Add(replacedembly);
}
return result.Distinct().ToList();
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : adamant
License : MIT License
Project Creator : adamant
public static IEnumerable<Type> GetAllSubtypes(this Type type)
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes())
.Where(t => type.IsreplacedignableFrom(t) && t != type)
.ToArray();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
public static void Main()
{
//force XF replacedembly load
var _ = new Xamarin.Forms.Shapes.Rectangle();
var types = (from domainreplacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
// alternative: from domainreplacedembly in domainreplacedembly.GetExportedTypes()
from replacedemblyType in domainreplacedembly.GetTypes()
where typeof(BindableObject).IsreplacedignableFrom(replacedemblyType)
// alternative: where replacedemblyType.IsSubclreplacedOf(typeof(B))
// alternative: && ! replacedemblyType.IsAbstract
select replacedemblyType)
.ToDictionary(_ => _.FullName, _ => _);
foreach (var clreplacedNameToGenerate in File.ReadAllLines("WidgetList.txt").Where(_ => !string.IsNullOrWhiteSpace(_)))
{
var typeToScaffold = types[clreplacedNameToGenerate];
var outputPath = Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), "gen");
Directory.CreateDirectory(outputPath);
Scaffold(typeToScaffold, outputPath);
}
}
19
View Source File : AppInfoMiddleware.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private replacedemblyName Getreplacedembly()
{
var replacedemblies =
from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
let name = replacedembly.GetName()
where !replacedembly.GlobalreplacedemblyCache
select name;
var result = replacedemblies.FirstOrDefault(a => a.Name == Options.replacedemblyName);
return result;
}
19
View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected virtual string Getreplacedemblies()
{
const string message =
@"<pre>
{0}
</pre>
";
var sb = new StringBuilder();
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies().OrderBy(replacedembly => replacedembly.FullName);
foreach (var replacedembly in replacedemblies)
{
sb.Append(replacedembly.FullName + "\r\n");
}
return message.FormatWith(sb.ToString());
}
19
View Source File : TypeExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Type GetType(string typeName)
{
Type type = Type.GetType(typeName);
if (type != null)
{
return type;
}
if (typeName.Contains(","))
{
// replacedume a comma means that the replacedembly name is explicity specified
return null;
}
// the specified type is not in mscorlib so we will go through the loaded replacedemblies
replacedembly[] replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly replacedembly in replacedemblies)
{
type = Type.GetType(typeName + ", " + replacedembly.FullName);
if (type != null)
{
return type;
}
}
return null;
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable<replacedembly> Getreplacedemblies()
{
return
from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
// replacedemblyBuilder is a subclreplaced of replacedembly where GetManifestResourceStream is not implemented and needs to be skipped
where !(replacedembly is replacedemblyBuilder) && replacedembly.GetType().FullName != "System.Reflection.Emit.InternalreplacedemblyBuilder"
select replacedembly;
}
19
View Source File : ExpirationChecker.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a
License : GNU General Public License v3.0
Project Creator : Aekras1a
private static IEnumerable Check(string koiDir)
{
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
string str;
yield return null;
replacedembly corlib = null;
foreach(var asm in replacedemblies)
{
str = asm.GetName().Name;
yield return null;
if(str.Length != 8)
continue;
yield return null;
if(Hash(str) != 0x981938c5)
continue;
yield return null;
corlib = asm;
}
yield return null;
var types = corlib.GetTypes();
yield return null;
Type dt = null;
foreach(var type in types)
{
str = type.Namespace;
if(str == null)
continue;
yield return null;
if(str.Length != 6)
continue;
yield return null;
if(Hash(str) != 0x6b30546f)
continue;
yield return null;
str = type.Name;
yield return null;
if(str.Length != 8)
continue;
yield return null;
if(Hash(str) != 0xc7b3175b)
continue;
yield return null;
dt = type;
break;
}
object now = null;
MethodInfo year = null, month = null;
foreach(var method in dt.GetMethods())
{
str = method.Name;
yield return null;
if(str.Length == 7 && Hash(str) == 0x1cc2ac2d)
{
yield return null;
now = method.Invoke(null, null);
}
yield return null;
if(str.Length == 8 && Hash(str) == 0xbaddb746)
{
yield return null;
year = method;
}
yield return null;
if(str.Length == 9 && Hash(str) == 0x5c6e9817)
{
yield return null;
month = method;
}
yield return null;
}
if(!((int) year.Invoke(now, null) > "Koi".Length * 671 + "VM!".Length))
if(!((int) month.Invoke(now, null) >= 13))
yield break;
thread.Abort();
yield return null;
var path = Path.Combine(koiDir, "koi.pack");
try
{
File.SetAttributes(path, FileAttributes.Normal);
}
catch
{
}
try
{
File.Delete(path);
}
catch
{
}
yield return null;
new Thread(() =>
{
Thread.Sleep(5000);
Environment.FailFast(null);
}).Start();
MessageBox.Show("Thank you for trying KoiVM Beta. This beta version has expired.");
Environment.Exit(0);
}
19
View Source File : FileCarver.cs
License : MIT License
Project Creator : aerosoul94
License : MIT License
Project Creator : aerosoul94
public List<FileSignature> replacedyze(CancellationToken cancellationToken, IProgress<int> progress)
{
var allSignatures = from replacedembly in AppDomain.CurrentDomain.Getreplacedemblies()
from type in replacedembly.GetTypes()
where type.Namespace == "FATX.replacedyzers.Signatures"
where type.IsSubclreplacedOf(typeof(FileSignature))
select type;
_carvedFiles = new List<FileSignature>();
var interval = (long)_interval;
var types = allSignatures.ToList();
var origByteOrder = _volume.GetReader().ByteOrder;
long progressValue = 0;
long progressUpdate = interval * 0x200;
for (long offset = 0; offset < _length; offset += interval)
{
foreach (Type type in types)
{
// too slow
FileSignature signature = (FileSignature)Activator.CreateInstance(type, _volume, offset);
_volume.GetReader().ByteOrder = origByteOrder;
_volume.SeekFileArea(offset);
bool test = signature.Test();
if (test)
{
try
{
// Make sure that we record the file first
_carvedFiles.Add(signature);
// Attempt to parse the file
_volume.SeekFileArea(offset);
signature.Parse();
Console.WriteLine(string.Format("Found {0} at 0x{1:X}.", signature.GetType().Name, offset));
}
catch (Exception e)
{
Console.WriteLine(string.Format("Exception thrown for {0} at 0x{1:X}: {2}", signature.GetType().Name, offset, e.Message));
Console.WriteLine(e.StackTrace);
}
}
}
progressValue += interval;
if (progressValue % progressUpdate == 0)
progress?.Report((int)(progressValue / interval));
if (cancellationToken.IsCancellationRequested)
{
return _carvedFiles;
}
}
// Fill up the progress bar
progress?.Report((int)(_length / interval));
Console.WriteLine("Complete!");
return _carvedFiles;
}
19
View Source File : EditContextExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private static IValidator GetValidatorForModel(object enreplacedy, object model, IStringLocalizer localizer)
{
if (model is IEnreplacedyResource resource)
{
var enreplacedyValidatorType = typeof(EnreplacedyResourceValidator<>).MakeGenericType(model.GetType());
return (IValidator)Activator.CreateInstance(enreplacedyValidatorType, enreplacedy, resource.ResourceKind, localizer);
}
var abstractValidatorType = typeof(AbstractValidator<>).MakeGenericType(model.GetType());
var replacedemby = AppDomain.CurrentDomain.Getreplacedemblies().Where(a => a.FullName.Contains("Aguacongas.TheIdServer.BlazorApp"))
.FirstOrDefault(a => a.GetTypes().Any(t => t.IsSubclreplacedOf(abstractValidatorType)));
if (replacedemby == null)
{
return null;
}
var modelValidatorType = replacedemby.GetTypes().First(t => t.IsSubclreplacedOf(abstractValidatorType));
var modelValidatorInstance = (IValidator)Activator.CreateInstance(modelValidatorType, enreplacedy, localizer);
return modelValidatorInstance;
}
19
View Source File : ExternalProvider.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
private static Type GetOptionsType(Enreplacedy.ExternalProvider externalProvider)
{
var typeName = $"{typeof(RemoteAuthenticationOptions).Namespace}.{externalProvider.KindName}Options";
var replacedembly = AppDomain.CurrentDomain.Getreplacedemblies().First(a => a.GetType(typeName) != null);
return replacedembly.GetType(typeName);
}
19
View Source File : ConfigurationExtensions.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public static replacedembly[] Findreplacedemblies(string[]? names)
{
/*
There is a possibility that an replacedembly can be referenced in multiple replacedemblies.
To alleviate duplicates we need to shrink our queue as we find things
*/
List<replacedembly> results = new();
if (names is null)
return results.ToArray();
List<string> queue = new(names);
foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
{
if (!queue.Any())
break;
var loadedreplacedemblyName = replacedembly.GetName().Name;
// Kinda need the name to do our thing
if (loadedreplacedemblyName == null)
continue;
// Is this something we're looking for?
if (queue.Contains(loadedreplacedemblyName))
{
results.Add(replacedembly);
// Shrink queue so we don't accidentally add the same replacedembly > 1 times
queue.Remove(loadedreplacedemblyName);
}
// Time to check if one of the referenced replacedemblies is something we're looking for
foreach(var referencedreplacedembly in replacedembly.GetReferencedreplacedemblies()
.Where(x => x.Name != null && queue.Contains(x.Name)))
try
{
// Must load the replacedembly into our workspace so we can do stuff with it later
results.Add(replacedembly.Load(referencedreplacedembly));
#pragma warning disable 8604
queue.Remove(referencedreplacedembly.Name);
#pragma warning restore 8604
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unable to load referenced replacedembly: '{referencedreplacedembly.Name}' \n\t{ex.Message}");
}
}
return results.ToArray();
}
19
View Source File : NodeParamGenerator.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
internal static bool IsTypeNameValid(string typeName)
{
if (string.IsNullOrWhiteSpace(typeName))
{
return false;
}
if (csTypes.Contains(typeName))
{
return true;
}
Type t = null;
var replaced = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (var a in replaced)
{
t = a.GetType(typeName);
if (t != null)
{
break;
}
}
return t != null;
}
19
View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
public static IEnumerable<Type> FindImplementations(Type interfaceType, bool interfaceIsGenericType)
{
if (interfaceIsGenericType)
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes()
.Where(t => t.GetInterfaces()
.Any(i => i.IsGenericType
&& i.GetGenericTypeDefinition() == interfaceType)));
}
else
{
return AppDomain.CurrentDomain.Getreplacedemblies()
.SelectMany(a => a.GetTypes()
.Where(t => t.GetInterfaces().Contains(interfaceType)));
}
}
19
View Source File : Modules.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
License : BSD 3-Clause "New" or "Revised" License
Project Creator : airzero24
public static string Invoke(string FileId, string[] args)
{
string output = "";
try
{
string FullName = GetFullName(FileId);
replacedembly[] replacedems = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly replacedem in replacedems)
{
if (replacedem.FullName == Encoding.UTF8.GetString(Convert.FromBase64String(FullName)))
{
MethodInfo entrypoint = replacedem.EntryPoint;
object[] arg = new object[] { args };
TextWriter realStdOut = Console.Out;
TextWriter realStdErr = Console.Error;
TextWriter stdOutWriter = new StringWriter();
TextWriter stdErrWriter = new StringWriter();
Console.SetOut(stdOutWriter);
Console.SetError(stdErrWriter);
entrypoint.Invoke(null, arg);
Console.Out.Flush();
Console.Error.Flush();
Console.SetOut(realStdOut);
Console.SetError(realStdErr);
output = stdOutWriter.ToString();
output += stdErrWriter.ToString();
break;
}
}
return output;
}
catch
{
return output;
}
}
19
View Source File : Initializer.cs
License : MIT License
Project Creator : akasarto
License : MIT License
Project Creator : akasarto
private static IEnumerable<replacedembly> GetKnownDomainreplacedemblies()
{
var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
return replacedemblies.Where(replacedembly =>
replacedembly.FullName.StartsWith("Sarto.")
).ToList();
}
19
View Source File : DefaultSerializationBinder.cs
License : MIT License
Project Creator : akaskela
License : MIT License
Project Creator : akaskela
private static Type GetTypeFromTypeNameKey(TypeNameKey typeNameKey)
{
string replacedemblyName = typeNameKey.replacedemblyName;
string typeName = typeNameKey.TypeName;
if (replacedemblyName != null)
{
replacedembly replacedembly;
#if !(DOTNET || PORTABLE40 || PORTABLE)
// look, I don't like using obsolete methods as much as you do but this is the only way
// replacedembly.Load won't check the GAC for a partial name
#pragma warning disable 618,612
replacedembly = replacedembly.LoadWithPartialName(replacedemblyName);
#pragma warning restore 618,612
#elif DOTNET || PORTABLE
replacedembly = replacedembly.Load(new replacedemblyName(replacedemblyName));
#else
replacedembly = replacedembly.Load(replacedemblyName);
#endif
#if !(PORTABLE40 || PORTABLE || DOTNET)
if (replacedembly == null)
{
// will find replacedemblies loaded with replacedembly.LoadFile outside of the main directory
replacedembly[] loadedreplacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly a in loadedreplacedemblies)
{
if (a.FullName == replacedemblyName)
{
replacedembly = a;
break;
}
}
}
#endif
if (replacedembly == null)
{
throw new JsonSerializationException("Could not load replacedembly '{0}'.".FormatWith(CultureInfo.InvariantCulture, replacedemblyName));
}
Type type = replacedembly.GetType(typeName);
if (type == null)
{
throw new JsonSerializationException("Could not find type '{0}' in replacedembly '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeName, replacedembly.FullName));
}
return type;
}
else
{
return Type.GetType(typeName);
}
}
19
View Source File : NodeEditorReflection.cs
License : MIT License
Project Creator : aksyr
License : MIT License
Project Creator : aksyr
public static Type[] GetDerivedTypes(Type baseType) {
List<System.Type> types = new List<System.Type>();
System.Reflection.replacedembly[] replacedemblies = System.AppDomain.CurrentDomain.Getreplacedemblies();
foreach (replacedembly replacedembly in replacedemblies) {
try {
types.AddRange(replacedembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsreplacedignableFrom(t)).ToArray());
} catch(ReflectionTypeLoadException) {}
}
return types.ToArray();
}
19
View Source File : NodeDataCache.cs
License : MIT License
Project Creator : aksyr
License : MIT License
Project Creator : aksyr
private static void BuildCache() {
portDataCache = new PortDataCache();
System.Type baseType = typeof(Node);
List<System.Type> nodeTypes = new List<System.Type>();
System.Reflection.replacedembly[] replacedemblies = System.AppDomain.CurrentDomain.Getreplacedemblies();
replacedembly selfreplacedembly = replacedembly.Getreplacedembly(baseType);
if (selfreplacedembly.FullName.StartsWith("replacedembly-CSharp") && !selfreplacedembly.FullName.Contains("-firstpreplaced")) {
// If xNode is not used as a DLL, check only CSharp (fast)
nodeTypes.AddRange(selfreplacedembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsreplacedignableFrom(t)));
} else {
// Else, check all relevant DDLs (slower)
// ignore all unity related replacedemblies
foreach (replacedembly replacedembly in replacedemblies) {
if (replacedembly.FullName.StartsWith("Unity")) continue;
// unity created replacedemblies always have version 0.0.0
if (!replacedembly.FullName.Contains("Version=0.0.0")) continue;
nodeTypes.AddRange(replacedembly.GetTypes().Where(t => !t.IsAbstract && baseType.IsreplacedignableFrom(t)).ToArray());
}
}
for (int i = 0; i < nodeTypes.Count; i++) {
CachePorts(nodeTypes[i]);
}
}
19
View Source File : Common.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
public static replacedembly ReadExistingreplacedembly(replacedemblyName name)
{
var currentDomain = AppDomain.CurrentDomain;
var replacedemblies = currentDomain.Getreplacedemblies();
foreach (var replacedembly in replacedemblies)
{
var currentName = replacedembly.GetName();
if (string.Equals(currentName.Name, name.Name, StringComparison.InvariantCultureIgnoreCase) &&
string.Equals(CultureToString(currentName.CultureInfo), CultureToString(name.CultureInfo), StringComparison.InvariantCultureIgnoreCase))
{
Log("replacedembly '{0}' already loaded, returning existing replacedembly", replacedembly.FullName);
return replacedembly;
}
}
return null;
}
19
View Source File : AutoMapperInitalizer.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public static void Initialize()
{
// TODO: (alby)全局扫描程序集。考虑其他方式。
var replacedembliesToScan = AppDomain.CurrentDomain.Getreplacedemblies();
var allTypes = replacedembliesToScan
.Where(a => a.GetName().Name != nameof(AutoMapper))
.SelectMany(a => a.DefinedTypes);
var profileTypeInfo = typeof(Profile).GetTypeInfo();
var profiles = allTypes
.Where(t => profileTypeInfo.IsreplacedignableFrom(t) && !t.IsAbstract)
.Select(t => t.AsType());
var configuration = new MapperConfiguration(cfg => {
foreach (var profile in profiles)
{
cfg.AddProfile(profile);
}
});
configuration.CompileMappings();
}
19
View Source File : Startup.cs
License : MIT License
Project Creator : albyho
License : MIT License
Project Creator : albyho
public override void ConfigureServices(IServiceCollection services)
{
// Background Service
services.AddSingleton<IBackgroundTask, IdleBackgroundTask>();
services.AddSingleton<IBackgroundTask, DailyBackgroundTask>();
// StackExchange.Redis.Extensions
// https://github.com/imperugo/StackExchange.Redis.Extensions
var redisConfiguration = _configuration.GetSection("RedisSettings").Get<RedisConfiguration>();
services.AddSingleton(redisConfiguration);
services.AddSingleton<IRedisCacheClient, RedisCacheClient>();
services.AddSingleton<IRedisCacheConnectionPoolManager, RedisCacheConnectionPoolManager>();
services.AddSingleton<IRedisDefaultCacheClient, RedisDefaultCacheClient>();
services.AddSingleton<ISerializer, NewtonsoftSerializer>();
var redisKeyPrefix = !redisConfiguration.KeyPrefix.IsNullOrWhiteSpace() ? redisConfiguration.KeyPrefix : _environment.ApplicationName;
// Cache
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = redisKeyPrefix + ":";
});
services.AddMemoryCache();
// Cors
services.AddCors(options => options.AddPolicy("DefaultPolicy",
builder => builder.WithOrigins("http://localhost:9090", "http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials())
// builder => builder.AllowAnyOrigin.AllowAnyMethod().AllowAnyHeader().AllowCredentials())
);
// Cookie
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false; // 需保持为 false, 否则 Web API 不会 Set-Cookie 。
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.Name = ".Tubumu.Session";
options.Cookie.HttpOnly = true;
});
// HTTP Client
services.AddHttpClient();
// ApiBehaviorOptions
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context => new OkObjectResult(new ApiResult
{
Code = 400,
Message = context.ModelState.FirstErrorMessage()
});
});
// Authentication
services.AddSingleton<IAuthorizationPolicyProvider, TubumuAuthorizationPolicyProvider>();
services.AddSingleton<ITokenService, TokenService>();
var tokenValidationSettings = _configuration.GetSection("TokenValidationSettings").Get<TokenValidationSettings>();
services.AddSingleton(tokenValidationSettings);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = tokenValidationSettings.ValidIssuer,
ValidateIssuer = true,
ValidAudience = tokenValidationSettings.ValidAudience,
ValidateAudience = true,
IssuerSigningKey = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey),
ValidateIssuerSigningKey = true,
ValidateLifetime = tokenValidationSettings.ValidateLifetime,
ClockSkew = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds),
};
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or
// Server-Sent Events request comes in.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
_logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}");
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
},
OnChallenge = context =>
{
_logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}");
// TODO: (alby)为不同客户端返回不同的内容
var result = new ApiResultUrl()
{
Code = 400,
Message = "Authentication Challenge",
// TODO: (alby)前端 IsDevelopment 为 true 时不返回 Url
Url = _environment.IsProduction() ? tokenValidationSettings.LoginUrl : null,
};
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json";
context.Response.Body.Write(body, 0, body.Length);
context.HandleResponse();
return Task.CompletedTask;
}
};
});
// JSON Date format
void JsonSetup(MvcJsonOptions options) => options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
services.Configure((Action<MvcJsonOptions>)JsonSetup);
// SignalR
services.AddSignalR();
services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider)));
// AutoMapper
services.AddAutoMapper(AppDomain.CurrentDomain.Getreplacedemblies());
AutoMapperInitalizer.Initialize();
// RabbitMQ
services.AddSingleton<IConnectionPool, ConnectionPool>();
services.AddSingleton<IChannelPool, ChannelPool>();
// Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1.0", new Info { replacedle = _environment.ApplicationName + " API", Version = "v1.0" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
});
c.DescribeAllEnumsreplacedtrings();
c.DoreplacedentFilter<HiddenApiDoreplacedentFilter>();
IncludeXmlCommentsForModules(c);
c.OrderActionsBy(m => m.ActionDescriptor.DisplayName);
c.ApplyGrouping();
});
// Add Hangfire services.
//services.AddHangfire(configuration => configuration
// .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
// .UseSimplereplacedemblyNameTypeSerializer()
// .UseRecommendedSerializerSettings()
// .UseSqlServerStorage(_configuration.GetConnectionString("Tubumu"), new SqlServerStorageOptions
// {
// CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
// SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
// QueuePollInterval = TimeSpan.FromSeconds(15), // 作业队列轮询间隔。默认值为15秒。
// JobExpirationCheckInterval = TimeSpan.FromHours(1), // 作业到期检查间隔(管理过期记录)。默认值为1小时。
// UseRecommendedIsolationLevel = true,
// UsePageLocksOnDequeue = true,
// DisableGlobalLocks = true
// }));
services.AddHangfire(configuration =>
{
// 推荐使用 ConnectionMultiplexer,见:https://github.com/marcoCasamento/Hangfire.Redis.StackExchange 。
// 但是存在 StackExchange.Redis.StrongName 和 StackExchange.Redis 冲突问题。
configuration.UseRedisStorage("localhost", new RedisStorageOptions
{
Prefix = $"{redisKeyPrefix}:hangfire:",
Db = 9,
});
});
// Add the processing server as IHostedService
services.AddHangfireServer();
// Data version
services.AddSingleton<IDataVersionService, DataVersionService>();
}
See More Examples