private static Assembly?LoadFromResolveHandler(object?sender, ResolveEventArgs args) { Assembly?requestingAssembly = args.RequestingAssembly; if (requestingAssembly == null) { return(null); } // Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that // is the case. if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly)) { return(null); } // Get the path where requesting assembly lives and check if it is in the list // of assemblies for which LoadFrom was invoked. string requestorPath = Path.GetFullPath(requestingAssembly.Location); if (string.IsNullOrEmpty(requestorPath)) { return(null); } lock (s_loadFromAssemblyList) { // If the requestor assembly was not loaded using LoadFrom, exit. if (!s_loadFromAssemblyList.Contains(requestorPath)) { return(null); } } // Requestor assembly was loaded using loadFrom, so look for its dependencies // in the same folder as it. // Form the name of the assembly using the path of the assembly that requested its load. AssemblyName requestedAssemblyName = new AssemblyName(args.Name !); string requestedAssemblyPath = Path.Combine(Path.GetDirectoryName(requestorPath) !, requestedAssemblyName.Name + ".dll"); try { // Load the dependency via LoadFrom so that it goes through the same path of being in the LoadFrom list. return(Assembly.LoadFrom(requestedAssemblyPath)); } catch (FileNotFoundException) { // Catch FileNotFoundException when attempting to resolve assemblies via this handler to account for missing assemblies. return(null); } }
private Assembly?ResolveSatelliteAssembly(AssemblyName assemblyName) { // Called by native runtime when CultureName is not empty Debug.Assert(assemblyName.CultureName?.Length > 0); const string SatelliteSuffix = ".resources"; if (assemblyName.Name == null || !assemblyName.Name.EndsWith(SatelliteSuffix, StringComparison.Ordinal)) { return(null); } string parentAssemblyName = assemblyName.Name.Substring(0, assemblyName.Name.Length - SatelliteSuffix.Length); Assembly parentAssembly = LoadFromAssemblyName(new AssemblyName(parentAssemblyName)); AssemblyLoadContext parentALC = GetLoadContext(parentAssembly) !; string?parentDirectory = Path.GetDirectoryName(parentAssembly.Location); if (parentDirectory == null) { return(null); } string assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName !, $"{assemblyName.Name}.dll"); bool exists = Internal.IO.File.InternalExists(assemblyPath); if (!exists && Path.IsCaseSensitive) { #if CORECLR if (AssemblyLoadContext.IsTracingEnabled()) { AssemblyLoadContext.TraceSatelliteSubdirectoryPathProbed(assemblyPath, HResults.COR_E_FILENOTFOUND); } #endif // CORECLR assemblyPath = Path.Combine(parentDirectory, assemblyName.CultureName !.ToLowerInvariant(), $"{assemblyName.Name}.dll"); exists = Internal.IO.File.InternalExists(assemblyPath); } Assembly?asm = exists ? parentALC.LoadFromAssemblyPath(assemblyPath) : null; #if CORECLR if (AssemblyLoadContext.IsTracingEnabled()) { AssemblyLoadContext.TraceSatelliteSubdirectoryPathProbed(assemblyPath, exists ? HResults.S_OK : HResults.COR_E_FILENOTFOUND); } #endif // CORECLR return(asm); }
public static Type?CompileCommand(string code) { Match m = _cbRegex.Match(code); if (!m.Success) { return(null); } code = $@" [ModuleLifespan(ModuleLifespan.Transient)] public sealed class DynamicCommands : TheGodfatherModule {{ {m.Groups["code"]} }}"; string type = $"DynamicCommands{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}"; Type? moduleType = null; IEnumerable <PortableExecutableReference> refs = AppDomain.CurrentDomain.GetAssemblies() .Where(xa => !xa.IsDynamic && !string.IsNullOrWhiteSpace(xa.Location)) .Select(x => MetadataReference.CreateFromFile(x.Location)); SyntaxTree ast = SyntaxFactory.ParseSyntaxTree(code, new CSharpParseOptions() .WithKind(SourceCodeKind.Script) .WithLanguageVersion(LanguageVersion.Latest)); var opts = new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, scriptClassName: type, usings: _usings, optimizationLevel: OptimizationLevel.Release, allowUnsafe: true, platform: Platform.AnyCpu ); var compilation = CSharpCompilation.CreateScriptCompilation(type, ast, refs, opts, returnType: typeof(object)); Assembly?assembly = null; using (var ms = new MemoryStream()) { compilation.Emit(ms); ms.Position = 0; assembly = Assembly.Load(ms.ToArray()); } Type?outerType = assembly.ExportedTypes.FirstOrDefault(x => x.Name == type); moduleType = outerType?.GetNestedTypes().FirstOrDefault(x => x.BaseType == typeof(TheGodfatherModule)); return(moduleType); }
internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, Assembly?callingAssembly, AssemblyLoadContext?assemblyLoadContext, IEnumerable <CustomAttributeBuilder>?assemblyAttributes) { ArgumentNullException.ThrowIfNull(name); if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); } if (callingAssembly == null) { // Called either from interop or async delegate invocation. Rejecting because we don't // know how to set the correct context of the new dynamic assembly. throw new InvalidOperationException(); } if (assemblyLoadContext == null) { assemblyLoadContext = AssemblyLoadContext.GetLoadContext(callingAssembly); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); RuntimeAssembly?retAssembly = null; CreateDynamicAssembly(ObjectHandleOnStack.Create(ref name), (int)access, ObjectHandleOnStack.Create(ref assemblyLoadContext), ObjectHandleOnStack.Create(ref retAssembly)); _internalAssembly = retAssembly !; _access = access; // Make sure that ManifestModule is properly initialized // We need to do this before setting any CustomAttribute // Note that this ModuleBuilder cannot be used for RefEmit yet // because it hasn't been initialized. // However, it can be used to set the custom attribute on the Assembly _manifestModuleBuilder = new ModuleBuilder(this, (RuntimeModule)InternalAssembly.ManifestModule); if (assemblyAttributes != null) { foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes) { SetCustomAttribute(assemblyAttribute); } } }
public static XmlSerializer[] FromMappings(XmlMapping[]?mappings, Type?type) { if (mappings == null || mappings.Length == 0) { return(Array.Empty <XmlSerializer>()); } bool anySoapMapping = false; foreach (var mapping in mappings) { if (mapping.IsSoap) { anySoapMapping = true; } } if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return(serializers); } XmlSerializerImplementation?contract = null; Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); TempAssembly?tempAssembly = null; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { AssemblyName name = type !.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } if (XmlMapping.IsShallow(mappings)) { return(Array.Empty <XmlSerializer>()); } else { if (type == null) { tempAssembly = new TempAssembly(mappings, new Type?[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key !] !;
internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, ref StackCrawlMark stackMark, IEnumerable <CustomAttributeBuilder>?unsafeAssemblyAttributes) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access)); } // Clone the name in case the caller modifies it underneath us. name = (AssemblyName)name.Clone(); // Scan the assembly level attributes for any attributes which modify how we create the // assembly. Currently, we look for any attribute which modifies the security transparency // of the assembly. List <CustomAttributeBuilder>?assemblyAttributes = null; if (unsafeAssemblyAttributes != null) { // Create a copy to ensure that it cannot be modified from another thread // as it is used further below. assemblyAttributes = new List <CustomAttributeBuilder>(unsafeAssemblyAttributes); } Assembly?retAssembly = null; CreateDynamicAssembly(ObjectHandleOnStack.Create(ref name), new StackCrawlMarkHandle(ref stackMark), (int)access, ObjectHandleOnStack.Create(ref retAssembly)); _internalAssemblyBuilder = (InternalAssemblyBuilder)retAssembly !; _assemblyData = new AssemblyBuilderData(_internalAssemblyBuilder, access); // Make sure that ManifestModule is properly initialized // We need to do this before setting any CustomAttribute InitManifestModule(); if (assemblyAttributes != null) { foreach (CustomAttributeBuilder assemblyAttribute in assemblyAttributes) { SetCustomAttribute(assemblyAttribute); } } }
public IResourceProvider Build() { if (_Name == null) { throw new BuilderMissingPropertyException("Name"); } if (_Assembly == null) { _Assembly = System.Reflection.Assembly.GetCallingAssembly(); } return(new ResourceDataProvider(_Assembly, _Name)); }
public EmitResult Compile(GameRelease release, CancellationToken cancel, out Assembly?assembly) { var emit = Compile(release, assemblyName: AssemblyName, code: Code, cancel, out var stream); if (emit.Success) { assembly = Assembly.Load(stream.ToArray()); } else { assembly = null; } return(emit); }
public void Init() { MainGraphics !.OriginalSize = new SKSize(55, 72); //change to what the original size is. _thisAssembly = Assembly.GetAssembly(this.GetType()); GetImages(); _pDrewPaint = MainGraphics.GetStandardDrewPaint(); _selectPaint = BaseDeckGraphicsCP.GetStandardSelectPaint(); _redPaint = MiscHelpers.GetSolidPaint(SKColors.Red); _limePaint = MiscHelpers.GetSolidPaint(SKColors.Lime); _textBorder = MiscHelpers.GetStrokePaint(SKColors.Black, 2); _chocolatePaint = MiscHelpers.GetSolidPaint(SKColors.Chocolate); _backPaint = MiscHelpers.GetSolidPaint(SKColors.Aqua); _blackPaint = MiscHelpers.GetSolidPaint(SKColors.Black); }
public AssemblyInfo(Assembly?assembly = default) { var usedAssembly = assembly ?? Assembly.GetEntryAssembly() ?? throw new InvalidOperationException("failed to initialize a valid assembly"); _lazyTitle = usedAssembly.GetAttributeResultLazy <AssemblyTitleAttribute>(a => a.Title); _lazyDescription = usedAssembly.GetAttributeResultLazy <AssemblyDescriptionAttribute>(a => a.Description); _lazyProduct = usedAssembly.GetAttributeResultLazy <AssemblyProductAttribute>(a => a.Product); _lazyVersion = usedAssembly.GetAttributeResultLazy <AssemblyVersionAttribute>(a => a.Version); _lazyFileVersion = usedAssembly.GetAttributeResultLazy <AssemblyFileVersionAttribute>(a => a.Version); _lazyCompany = usedAssembly.GetAttributeResultLazy <AssemblyCompanyAttribute>(a => a.Company); _lazyCopyright = usedAssembly.GetAttributeResultLazy <AssemblyCopyrightAttribute>(a => a.Copyright); _lazyTrademark = usedAssembly.GetAttributeResultLazy <AssemblyTrademarkAttribute>(a => a.Trademark); _lazyInformationalVersion = usedAssembly.GetAttributeResultLazy <AssemblyInformationalVersionAttribute>(a => a.InformationalVersion); }
public static CompiledCode Compile(CSharpCompilation compilation) { using (var stream = new MemoryStream()) { var result = compilation.Emit(stream); Assembly?assembly = null; if (result.Success) { assembly = Assembly.Load(stream.ToArray()); } return(new CompiledCode(result, assembly)); } }
private Assembly?ResolveUsingEvent(AssemblyName assemblyName) { string?simpleName = assemblyName.Name; // Invoke the Resolving event callbacks if wired up Assembly?assembly = GetFirstResolvedAssemblyFromResolvingEvent(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName); } return(assembly); }
public IHandler Build(IHandler parent) { if (_Root == null) { throw new BuilderMissingPropertyException("Root"); } if (_Assembly == null) { _Assembly = System.Reflection.Assembly.GetCallingAssembly(); } return(Concerns.Chain(parent, _Concerns, (p) => new EmbeddedResourcesProvider(p, _Assembly, _Root))); }
/// <summary> /// Checks if all Cef and CefSharp dependencies were found relative to the Executing Assembly. /// Shortcut method that calls <see cref="CheckDependencies(bool, bool, string, string, string, string, string)"/>, throws an Exception if not files are missing. /// </summary> /// <param name="locale">The locale, if empty then en-US will be used.</param> /// <param name="localesDirPath">The path to the locales directory, if empty locales\ will be used.</param> /// <param name="resourcesDirPath">The path to the resources directory, if empty the Executing Assembly path is used.</param> /// <param name="packLoadingDisabled">Is loading of pack files disabled?</param> /// <param name="browserSubProcessPath">The path to a separate executable that will be launched for sub-processes.</param> /// <exception cref="Exception">Throw when not all dependencies are present</exception> public static void AssertAllDependenciesPresent(string locale = null, string localesDirPath = null, string resourcesDirPath = null, bool packLoadingDisabled = false, string browserSubProcessPath = "CefSharp.BrowserSubProcess.exe") { string?nativeLibPath; string?managedLibPath = Path.GetDirectoryName(typeof(DependencyChecker).Assembly.Location); Uri pathUri; if (Uri.TryCreate(browserSubProcessPath, UriKind.Absolute, out pathUri) && pathUri.IsAbsoluteUri) { nativeLibPath = Path.GetDirectoryName(browserSubProcessPath); } else { Assembly?executingAssembly = Assembly.GetExecutingAssembly(); nativeLibPath = Path.GetDirectoryName(executingAssembly.Location); } if (string.IsNullOrEmpty(locale)) { locale = "en-US"; } if (string.IsNullOrEmpty(localesDirPath)) { localesDirPath = Path.Combine(nativeLibPath !, "locales"); } if (string.IsNullOrEmpty(resourcesDirPath)) { resourcesDirPath = nativeLibPath !; } List <string>?missingDependencies = CheckDependencies(true, packLoadingDisabled, managedLibPath !, nativeLibPath !, resourcesDirPath, browserSubProcessPath, Path.Combine(localesDirPath, locale + ".pak")); if (missingDependencies.Count > 0) { var builder = new StringBuilder(); builder.AppendLine("Unable to locate required Cef/CefSharp dependencies:"); foreach (var missingDependency in missingDependencies) { builder.AppendLine("Missing:" + missingDependency); } builder.AppendLine("Executing Assembly Path:" + nativeLibPath); throw new Exception(builder.ToString()); } }
private static DateTime GetProgramDate() { Assembly?current = Assembly.GetAssembly(typeof(ProgramState)); if (current != null) { var attribute = current.GetCustomAttribute <AssemblyBuildDateAttribute>(); if (attribute != null) { return(attribute.BuildDate.Date); } } return(new DateTime()); }
/// <summary>The factory is looked up via "prefixTree" in <paramref name="args"/>, expecting "geohash" or "quad".</summary> /// <remarks> /// The factory is looked up via "prefixTree" in <paramref name="args"/>, expecting "geohash" or "quad". /// If its neither of these, then "geohash" is chosen for a geo context, otherwise "quad" is chosen. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="args"/> or <paramref name="ctx"/> is <c>null</c>.</exception> public static SpatialPrefixTree MakeSPT(IDictionary <string, string> args, Assembly?assembly, SpatialContext ctx) { // LUCENENET specific - added guard clauses if (args is null) { throw new ArgumentNullException(nameof(args)); } if (assembly is null) { assembly = typeof(SpatialPrefixTreeFactory).Assembly; } if (ctx is null) { throw new ArgumentNullException(nameof(ctx)); } SpatialPrefixTreeFactory?instance; if (!args.TryGetValue(PREFIX_TREE, out string?cname)) { cname = ctx.IsGeo ? "geohash" : "quad"; } if ("geohash".Equals(cname, StringComparison.OrdinalIgnoreCase)) { instance = new GeohashPrefixTreeFactory(); } else if ("quad".Equals(cname, StringComparison.OrdinalIgnoreCase)) { instance = new QuadPrefixTreeFactory(); } else { try { Type?c = assembly.GetType(cname) ?? Type.GetType(cname); if (c is null) { throw RuntimeException.Create($"{cname} not found in {assembly.GetName().FullName} or by using Type.GetType(string).");// LUCENENET specific - .NET doesn't throw when the type is not found. } instance = (SpatialPrefixTreeFactory)Activator.CreateInstance(c) !; } catch (Exception e) when(e.IsException()) { throw RuntimeException.Create(e); } } instance.Init(args, ctx); return(instance.NewSPT()); }
private static bool TryPopulateFSharpValueCaches(Type possibleFSharpAsyncGenericType) { var assembly = possibleFSharpAsyncGenericType.Assembly; var fsharpOptionType = assembly.GetType("Microsoft.FSharp.Core.FSharpOption`1"); var fsharpAsyncType = assembly.GetType("Microsoft.FSharp.Control.FSharpAsync"); if (fsharpOptionType == null || fsharpAsyncType == null) { return(false); } // Get a reference to FSharpOption<TaskCreationOptions>.None var fsharpOptionOfTaskCreationOptionsType = fsharpOptionType .MakeGenericType(typeof(TaskCreationOptions)); _fsharpOptionOfTaskCreationOptionsNoneProperty = fsharpOptionOfTaskCreationOptionsType .GetTypeInfo() .GetRuntimeProperty("None"); // Get a reference to FSharpOption<CancellationToken>.None var fsharpOptionOfCancellationTokenType = fsharpOptionType .MakeGenericType(typeof(CancellationToken)); _fsharpOptionOfCancellationTokenNoneProperty = fsharpOptionOfCancellationTokenType .GetTypeInfo() .GetRuntimeProperty("None"); // Get a reference to FSharpAsync.StartAsTask<> var fsharpAsyncMethods = fsharpAsyncType .GetRuntimeMethods() .Where(m => m.Name.Equals("StartAsTask", StringComparison.Ordinal)); foreach (var candidateMethodInfo in fsharpAsyncMethods) { var parameters = candidateMethodInfo.GetParameters(); if (parameters.Length == 3 && TypesHaveSameIdentity(parameters[0].ParameterType, possibleFSharpAsyncGenericType) && parameters[1].ParameterType == fsharpOptionOfTaskCreationOptionsType && parameters[2].ParameterType == fsharpOptionOfCancellationTokenType) { // This really does look like the correct method (and hence assembly). _fsharpAsyncStartAsTaskGenericMethod = candidateMethodInfo; _fsharpCoreAssembly = assembly; break; } } return(_fsharpCoreAssembly != null); }
internal TempAssembly(XmlMapping[] xmlMappings, Type?[] types, string?defaultNamespace, string?location) { bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) { xmlMappings[i].CheckShallow(); if (xmlMappings[i].IsSoap) { containsSoapMapping = true; } } // We will make best effort to use RefEmit for assembly generation bool fallbackToCSharpAssemblyGeneration = false; if (!containsSoapMapping && !TempAssembly.UseLegacySerializerGeneration) { try { _assembly = GenerateRefEmitAssembly(xmlMappings, types, defaultNamespace); } // Only catch and handle known failures with RefEmit catch (CodeGeneratorConversionException) { fallbackToCSharpAssemblyGeneration = true; } // Add other known exceptions here... // } else { fallbackToCSharpAssemblyGeneration = true; } if (fallbackToCSharpAssemblyGeneration) { throw new PlatformNotSupportedException(SR.CompilingScriptsNotSupported); } #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe if (_assembly == null) { throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "Failed to generate XmlSerializer assembly, but did not throw")); } #endif InitAssemblyMethods(xmlMappings); }
public void AddAssemblyPairs(Assembly?apiAssembly, Assembly?domainAssembly) { if (apiAssembly == null) { throw new ArgumentNullException(nameof(apiAssembly)); } if (domainAssembly == null) { throw new ArgumentNullException(nameof(domainAssembly)); } this.AssemblyPairs ??= new List <AssemblyPairOptions>(); this.AssemblyPairs.Add(new AssemblyPairOptions(apiAssembly, domainAssembly)); }
public ResourceManager(Type resourceSource) { ArgumentNullException.ThrowIfNull(resourceSource); if (resourceSource is not RuntimeType) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } _locationInfo = resourceSource; MainAssembly = _locationInfo.Assembly; BaseNameField = resourceSource.Name; CommonAssemblyInit(); }
public ResourceManager(string baseName, Assembly assembly) { ArgumentNullException.ThrowIfNull(baseName); ArgumentNullException.ThrowIfNull(assembly); if (assembly is not RuntimeAssembly) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } MainAssembly = assembly; BaseNameField = baseName; CommonAssemblyInit(); }
public void Init() { _thisA = Assembly.GetAssembly(GetType()); MainGraphics !.OriginalSize = new SKSize(80, 100); //change to what the original size is. _pDrewPaint = MainGraphics.GetStandardDrewPaint(); _selectPaint = BaseDeckGraphicsCP.GetStandardSelectPaint(); _whiteBorder = MiscHelpers.GetStrokePaint(SKColors.White, 1); _steelBluePaint = MiscHelpers.GetSolidPaint(SKColors.SteelBlue); _whitePaint = MiscHelpers.GetSolidPaint(SKColors.White); _bluePaint = MiscHelpers.GetSolidPaint(SKColors.Blue); _darkOrangePaint = MiscHelpers.GetSolidPaint(SKColors.DarkOrange); _blackBorder = MiscHelpers.GetStrokePaint(SKColors.Black, 1); _purplePaint = MiscHelpers.GetSolidPaint(SKColors.Purple); _greenPaint = MiscHelpers.GetSolidPaint(SKColors.Green); //no option to show you can select unknown cards. }
private static void ConfigureDefaults(SQLiteConfigurationOptions options) { Environment.SpecialFolder specialFolder = Environment.SpecialFolder.ApplicationData; string appDataPath = Environment.GetFolderPath(specialFolder); Assembly?entryAssembly = Assembly.GetEntryAssembly(); string? name = entryAssembly?.GetName().Name ?? Process.GetCurrentProcess().ProcessName; string appPath = Path.Combine(appDataPath, name); Directory.CreateDirectory(appPath); options.DataSource = Path.Combine(appPath, "settings.db"); }
/// <summary> /// Creates an instance of the specified <see cref="DbContext" /> type using the standard design-time /// mechanisms. When available, this will use any <see cref="IDesignTimeDbContextFactory{TContext}" /> /// implementations or the application's service provider. /// </summary> /// <param name="contextType"> The <see cref="DbContext" /> type to instantiate. </param> /// <param name="startupAssembly"> The application's startup assembly. </param> /// <param name="reportHandler"> The design-time report handler. </param> /// <param name="args"> Arguments passed to the application. </param> /// <returns> The newly created object. </returns> public static DbContext CreateInstance( Type contextType, Assembly?startupAssembly, IOperationReportHandler?reportHandler, string[]?args) { Check.NotNull(contextType, nameof(contextType)); return(new DbContextOperations( new OperationReporter(reportHandler), contextType.Assembly, startupAssembly ?? contextType.Assembly, args: args ?? Array.Empty <string>()) .CreateContext(contextType.FullName !)); }
private static void PrintVersion(Assembly?assembly = null) { assembly ??= typeof(Program).Assembly; var attribute = assembly.GetCustomAttribute <AssemblyInformationalVersionAttribute>(); Console.WriteLine($"{nameof(ApiDump)} version {{0}}", attribute?.InformationalVersion ?? assembly.GetName().Version !.ToString(3)); var copyright = assembly.GetCustomAttribute <AssemblyCopyrightAttribute>(); if (copyright is not null) { Console.WriteLine(copyright.Copyright.Replace("\u00A9", "(C)")); } }
public GeneratedSerializerWrapper( IGeneratedSerializer <T>?innerSerializer, Assembly?generatedAssembly, Func <string?> generatedCSharp, byte[]?generatedAssemblyBytes) { this.lazyCSharp = new Lazy <string?>(generatedCSharp); this.Assembly = generatedAssembly; this.AssemblyBytes = generatedAssemblyBytes; this.innerSerializer = innerSerializer ?? throw new ArgumentNullException(nameof(innerSerializer)); var tableAttribute = typeof(T).GetCustomAttribute <Attributes.FlatBufferTableAttribute>(); this.fileIdentifier = tableAttribute?.FileIdentifier; }
public static string GetResourceText(string name) { Assembly?assembly = typeof(Rixian.Extensions.AspNetCore.Generators.Sources).GetTypeInfo().Assembly; using Stream? resource = assembly.GetManifestResourceStream(name); if (resource != null) { using StreamReader sr = new StreamReader(resource); return(sr.ReadToEnd()); } else { return(string.Empty); } }
private static bool TryLoadAssemblyIfItReferencesFakeItEasy(string file, [NotNullWhen(true)] out Assembly?assembly) { assembly = null; try { assembly = Assembly.LoadFrom(file); } catch (Exception ex) { WarnFailedToLoadAssembly(file, ex); return(false); } return(assembly.ReferencesFakeItEasy()); }
public void OnGet() { WebRootPath = currentEnvironment.WebRootPath; ApplicationName = currentEnvironment.ApplicationName; Assembly?entryAssembly = Assembly.GetEntryAssembly(); EntryAssemblyName = entryAssembly == null ? "Unknown" : (entryAssembly.FullName == null ? "Unknown (no full name)" : entryAssembly.FullName.ToString()); AssemblyFileVersionAttribute?fileVersionAttribute = entryAssembly?.GetCustomAttribute <AssemblyFileVersionAttribute>(); EntryAssemblyVersion = fileVersionAttribute == null ? "Unknown" : fileVersionAttribute.Version; EnvironmentName = currentEnvironment.EnvironmentName; var assemblies = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.FullName == null ? a.GetName().ToString() : a.FullName).OrderBy(a => a); MemCheckAssemblies = assemblies.Where(assemblyName => assemblyName.StartsWith("MemCheck")); }
private static ObjectHandle?CreateInstanceInternal(string assemblyString, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder?binder, object?[]?args, CultureInfo?culture, object?[]?activationAttributes, ref StackCrawlMark stackMark) { Type? type = null; Assembly?assembly = null; if (assemblyString == null) { assembly = Assembly.GetExecutingAssembly(ref stackMark); } else { RuntimeAssembly?assemblyFromResolveEvent; AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, out assemblyFromResolveEvent); if (assemblyFromResolveEvent != null) { // Assembly was resolved via AssemblyResolve event assembly = assemblyFromResolveEvent; } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) { // WinRT type - we have to use Type.GetType type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase); } else { // Classic managed type assembly = RuntimeAssembly.InternalLoadAssemblyName( assemblyName, ref stackMark); } } if (type == null) { type = assembly !.GetType(typeName, throwOnError: true, ignoreCase); } object?o = CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); return(o != null ? new ObjectHandle(o) : null); }