//broken - this should get something instead of scenarios[] cuz scenarios test rawTests public SuiteResult Test(Assemblies assemblies, Scenario[] scenarios, IResultsWriter resultsWriter) { var scenarioResults = new List<ScenarioResult>(scenarios.Length); Array.ForEach(scenarios, scenario => scenarioResults.Add(scenario.Test(null, resultsWriter))); return new SuiteResult(suiteName, scenarioResults); }
public Session( ProjectConfiguration configuration, Assemblies assemblies, TestReaders testReaders, IResultsWriter resultsWriter) { this.configuration = configuration; this.assemblies = assemblies; this.testReaders = testReaders; this.resultsWriter = resultsWriter; testRunner = new TestRunner(assemblies); }
private static int EntryPoint(string args) { if (m_initialized) { return(0); } m_initialized = true; Logging.Write(true)("Process (" + Process.GetCurrentProcess().ProcessName + ") [" + Process.GetCurrentProcess().Id + "] Found"); Logging.LogAllExceptions(); //Get All Signatures Signatures.LoadSignatures(); //Initialize Hooking System DetoursMgr.Initialize(); //Initialize Loading Assemblies Assemblies.Initialize(); return(0); }
/// <summary> /// Executes the task. /// </summary> /// <returns></returns> public override bool Execute() { ResolvedAssemblies = Assemblies?.Select(i => ResolveIdentity(i)).Where(i => i != null).ToArray(); return(true); }
public void ManagedLink() { var cache_path = Path.Combine(ArchDirectory, "linked-assemblies.txt"); foreach (var a in Assemblies) { a.CopyToDirectory(LinkDirectory, false, check_case: true); } // Check if we can use a previous link result. if (!Driver.Force) { var input = new List <string> (); var output = new List <string> (); var cached_output = new List <string> (); if (File.Exists(cache_path)) { cached_output.AddRange(File.ReadAllLines(cache_path)); var cached_loaded = new HashSet <string> (); // Only add the previously linked assemblies (and their satellites) as the input/output assemblies. // Do not add assemblies which the linker process removed. foreach (var a in Assemblies) { if (!cached_output.Contains(a.FullPath)) { continue; } cached_loaded.Add(a.FullPath); input.Add(a.FullPath); output.Add(Path.Combine(PreBuildDirectory, a.FileName)); if (File.Exists(a.FullPath + ".mdb")) { // Debug files can change without the assemblies themselves changing // This should also invalidate the cached linker results, since the non-linked mdbs can't be copied. input.Add(a.FullPath + ".mdb"); output.Add(Path.Combine(PreBuildDirectory, a.FileName) + ".mdb"); } if (a.Satellites != null) { foreach (var s in a.Satellites) { input.Add(s); output.Add(Path.Combine(PreBuildDirectory, Path.GetFileName(Path.GetDirectoryName(s)), Path.GetFileName(s))); // No need to copy satellite mdb files, satellites are resource-only assemblies. } } } // The linker might have added assemblies that weren't specified/reachable // from the command line arguments (such as I18N assemblies). Those are not // in the Assemblies list at this point (since we haven't run the linker yet) // so make sure we take those into account as well. var not_loaded = cached_output.Except(cached_loaded); foreach (var path in not_loaded) { input.Add(path); output.Add(Path.Combine(PreBuildDirectory, Path.GetFileName(path))); } // Include mtouch here too? // input.Add (Path.Combine (MTouch.MonoTouchDirectory, "usr", "bin", "mtouch")); if (Application.IsUptodate(input, output)) { cached_link = true; for (int i = Assemblies.Count - 1; i >= 0; i--) { var a = Assemblies [i]; if (!cached_output.Contains(a.FullPath)) { Assemblies.RemoveAt(i); continue; } // Load the cached assembly a.LoadAssembly(Path.Combine(PreBuildDirectory, a.FileName)); Driver.Log(3, "Target '{0}' is up-to-date.", a.FullPath); } foreach (var path in not_loaded) { var a = new Assembly(this, path); a.LoadAssembly(Path.Combine(PreBuildDirectory, a.FileName)); Assemblies.Add(a); } Driver.Watch("Cached assemblies reloaded", 1); Driver.Log("Cached assemblies reloaded."); return; } } } // Load the assemblies into memory. foreach (var a in Assemblies) { a.LoadAssembly(a.FullPath); } var assemblies = new List <string> (); foreach (var a in Assemblies) { assemblies.Add(a.FullPath); } var linked_assemblies = new List <string> (assemblies); LinkAssemblies(App.RootAssembly, ref linked_assemblies, PreBuildDirectory, out LinkContext); // Remove assemblies that were linked away var removed = new HashSet <string> (assemblies); removed.ExceptWith(linked_assemblies); foreach (var assembly in removed) { for (int i = Assemblies.Count - 1; i >= 0; i--) { var ad = Assemblies [i]; if (assembly != ad.FullPath) { continue; } Assemblies.RemoveAt(i); } } // anything added by the linker will have it's original path var added = new HashSet <string> (); foreach (var assembly in linked_assemblies) { added.Add(Path.GetFileName(assembly)); } var original = new HashSet <string> (); foreach (var assembly in assemblies) { original.Add(Path.GetFileName(assembly)); } added.ExceptWith(original); foreach (var assembly in added) { // the linker already copied the assemblies (linked or not) into the output directory // and we must NOT overwrite the linker work with an original (unlinked) assembly string path = Path.Combine(PreBuildDirectory, assembly); var ad = ManifestResolver.Load(path); var a = new Assembly(this, ad); a.CopyToDirectory(PreBuildDirectory); Assemblies.Add(a); } assemblies = linked_assemblies; // Make the assemblies point to the right path. foreach (var a in Assemblies) { a.FullPath = Path.Combine(PreBuildDirectory, a.FileName); // The linker can copy files (and not update timestamps), and then we run into this sequence: // * We run the linker, nothing changes, so the linker copies // all files to the PreBuild directory, with timestamps intact. // * This means that for instance SDK assemblies will have the original // timestamp from their installed location, and the exe will have the // timestamp of when it was built. // * mtouch is executed again for some reason, and none of the input assemblies changed. // We'll still re-execute the linker, because at least one of the input assemblies // (the .exe) has a newer timestamp than some of the assemblies in the PreBuild directory. // So here we manually touch all the assemblies we have, to make sure their timestamps // change (this is us saying 'we know these files are up-to-date at this point in time'). Driver.Touch(a.GetRelatedFiles()); } File.WriteAllText(cache_path, string.Join("\n", linked_assemblies)); }
public string[] GetAssemblies() { return(Assemblies.IsNullOrEmpty() && !string.IsNullOrWhiteSpace(AssemblyPath) ? new[] { AssemblyPath } : Assemblies); }
internal void RemoveDuplicates() { Assemblies = Assemblies.Distinct().ToList(); Types = Types.Distinct().ToList(); }
private static bool Contains(string @namespace) { return(Assemblies.ContainsKey(@namespace) && Contexts.ContainsKey(@namespace)); }
public override SQLScriptList ToSqlDiff(List <ISchemaBase> schemas) { var isAzure10 = this.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServerAzure10; var listDiff = new SQLScriptList(); listDiff.Add(new SQLScript(String.Format(@"/* Open DBDiff {0} http://opendbiff.codeplex.com/ Script created by {1}\{2} on {3} at {4}. Created on: {5} Source: {6} on {7} Destination: {8} on {9} */ ", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(), Environment.UserDomainName, Environment.UserName, DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString(), Environment.MachineName, SourceInfo != null ? SourceInfo.Database : "Uknown", SourceInfo != null ? SourceInfo.Server : "Uknown", Info != null ? Info.Database : "Uknown", Info != null ? Info.Server : "Uknown", 0), 0, Enums.ScripActionType.None)); if (!isAzure10) { listDiff.Add("USE [" + Name + "]\r\nGO\r\n\r\n", 0, Enums.ScripActionType.UseDatabase); listDiff.AddRange(Assemblies.ToSqlDiff(schemas)); listDiff.AddRange(UserTypes.ToSqlDiff(schemas)); } listDiff.AddRange(TablesTypes.ToSqlDiff(schemas)); listDiff.AddRange(Tables.ToSqlDiff(schemas)); listDiff.AddRange(Rules.ToSqlDiff(schemas)); listDiff.AddRange(Schemas.ToSqlDiff(schemas)); listDiff.AddRange(XmlSchemas.ToSqlDiff(schemas)); listDiff.AddRange(Procedures.ToSqlDiff(schemas)); if (!isAzure10) { listDiff.AddRange(CLRProcedures.ToSqlDiff(schemas)); listDiff.AddRange(CLRFunctions.ToSqlDiff(schemas)); listDiff.AddRange(FileGroups.ToSqlDiff(schemas)); } listDiff.AddRange(DDLTriggers.ToSqlDiff(schemas)); listDiff.AddRange(Synonyms.ToSqlDiff(schemas)); listDiff.AddRange(Views.ToSqlDiff(schemas)); listDiff.AddRange(Users.ToSqlDiff(schemas)); listDiff.AddRange(Functions.ToSqlDiff(schemas)); listDiff.AddRange(Roles.ToSqlDiff(schemas)); listDiff.AddRange(PartitionFunctions.ToSqlDiff(schemas)); listDiff.AddRange(PartitionSchemes.ToSqlDiff(schemas)); if (!isAzure10) { listDiff.AddRange(FullText.ToSqlDiff(schemas)); } return(listDiff); }
public Scenario(string name, Assemblies assemblies) { this.name = name; this.assemblies = assemblies; }
public TestRunner(Assemblies assemblies) { this.assemblies = assemblies; }
private static string Decompile(Assemblies.AssemblyDefinition asm, IEnumerable<TypeDefinition> types) { DecompilerSettings settings = new DecompilerSettings(); settings.FullyQualifyAmbiguousTypeNames = false; var ctx = new DecompilerContext(asm.MainModule) { Settings = settings }; var decompiler = new AstBuilder(ctx); foreach (var t in types) { decompiler.AddType(t); } new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit); var output = new StringWriter(); decompiler.GenerateCode(new PlainTextOutput(output)); return output.ToString().Trim(); }
private static void RunTest(string testCase, Assemblies.AssemblyDefinition asm, IEnumerable<TypeDefinition> types, IEnumerable<IGrouping<string,string>> matchingCode) { if (testCase == "Generics") testCase.GetHashCode(); string decompiledText = Decompile(asm, types); IEnumerable<string> matchingFiles = matchingCode.FirstOrDefault(kv => string.Equals(kv.Key, testCase, StringComparison.OrdinalIgnoreCase)); if (matchingFiles == null || matchingFiles.Count()==0) throw new FileNotFoundException("No source code found for " + testCase + "."); if (matchingFiles.Count() != 1) throw new AmbiguousMatchException("More than one source code file found for " + testCase + "."); string originalCode = matchingFiles.Single(); string noComments = CodeSampleFileParser.ConcatLines( from line in SplitLines(originalCode) where !CodeSampleFileParser.IsIgnorableLine(line) select line); CodeAssert.AreEqual(noComments, decompiledText); }
public SessionProvider(Assemblies assemblies) { this.assemblies = assemblies; }
public Assembly?Resolve(AssemblyLoadContext context, AssemblyName name) => Assemblies.FirstOrDefault(a => a.Assembly.FullName == name.FullName)?.Assembly;
private static async Task <App> BuildAppAsync( CancellationTokenSource cancellationTokenSource, Action <LoggerConfiguration> loggerConfigurationAction, string[] args) { ImmutableArray <Assembly> scanAssemblies = Assemblies.FilteredAssemblies(); string basePathFromArg = args.ParseParameter(ConfigurationConstants.ApplicationBasePath); string contentBasePathFromArg = args.ParseParameter(ConfigurationConstants.ContentBasePath); bool IsRunningAsService() { bool hasRunAsServiceArgument = args.Any(arg => arg.Equals(ApplicationConstants.RunAsService, StringComparison.OrdinalIgnoreCase)); if (hasRunAsServiceArgument) { return(true); } FileInfo processFileInfo; using (Process currentProcess = Process.GetCurrentProcess()) { processFileInfo = new FileInfo(currentProcess.MainModule.FileName); } if (processFileInfo.Name.Equals("Milou.Deployer.Web.WindowsService.exe", StringComparison.OrdinalIgnoreCase)) { return(true); } return(false); } string currentDomainBaseDirectory = AppDomain.CurrentDomain.BaseDirectory; if (IsRunningAsService()) { Console.WriteLine($"Switching current directory from {Directory.GetCurrentDirectory()} to {currentDomainBaseDirectory}"); Directory.SetCurrentDirectory(currentDomainBaseDirectory); } string basePath = basePathFromArg ?? currentDomainBaseDirectory; string contentBasePath = contentBasePathFromArg ?? Directory.GetCurrentDirectory(); ILogger startupLogger = SerilogApiInitialization.InitializeStartupLogging(file => GetBaseDirectoryFile(basePath, file)); startupLogger.Information("Using application root directory {Directory}", basePath); MultiSourceKeyValueConfiguration configuration = ConfigurationInitialization.InitializeConfiguration(args, file => GetBaseDirectoryFile(basePath, file), startupLogger, scanAssemblies, contentBasePath); string tempDirectory = configuration[ApplicationConstants.ApplicationTempDirectory]; if (!string.IsNullOrWhiteSpace(tempDirectory)) { if (tempDirectory.TryEnsureDirectoryExists(out DirectoryInfo tempDirectoryInfo)) { Environment.SetEnvironmentVariable(TempConstants.Tmp, tempDirectoryInfo.FullName); Environment.SetEnvironmentVariable(TempConstants.Temp, tempDirectoryInfo.FullName); startupLogger.Debug("Using specified temp directory {TempDirectory} {AppName}", tempDirectory, ApplicationConstants.ApplicationName); } else { startupLogger.Warning("Could not use specified temp directory {TempDirectory}, {AppName}", tempDirectory, ApplicationConstants.ApplicationName); } } var loggingLevelSwitch = new LoggingLevelSwitch(LogEventLevel.Debug); ILogger appLogger = SerilogApiInitialization.InitializeAppLogging(configuration, startupLogger, loggerConfigurationAction, loggingLevelSwitch); if (args.Length > 0) { appLogger.Debug("Application started with command line args, {Args}, {AppName}", args, ApplicationConstants.ApplicationName); } else if (appLogger.IsEnabled(LogEventLevel.Verbose)) { appLogger.Verbose("Application started with no command line args, {AppName}", ApplicationConstants.ApplicationName); } IReadOnlyList <IModule> modules = GetConfigurationModules(configuration, cancellationTokenSource, appLogger, scanAssemblies); Type[] excludedModuleTypes = { typeof(AppServiceModule) }; var environmentConfiguration = new EnvironmentConfiguration { ApplicationBasePath = basePath, ContentBasePath = contentBasePath }; var singletons = new object[] { loggingLevelSwitch, environmentConfiguration }; Scope rootScope = Bootstrapper.Start(configuration, modules, appLogger, scanAssemblies, excludedModuleTypes, singletons); DeploymentTargetIds deploymentTargetIds = await GetDeploymentWorkerIdsAsync(rootScope.Deepest().Lifetime, appLogger, cancellationTokenSource.Token); ILifetimeScope webHostScope = rootScope.Deepest().Lifetime.BeginLifetimeScope(builder => { builder.RegisterInstance(deploymentTargetIds).AsSelf().SingleInstance(); builder.RegisterType <Startup>().AsSelf(); }); var webHostScopeWrapper = new Scope(Scope.WebHostScope, webHostScope); rootScope.Deepest().SubScope = webHostScopeWrapper; EnvironmentConfigurator.ConfigureEnvironment(rootScope.Deepest().Lifetime); IWebHostBuilder webHostBuilder = CustomWebHostBuilder.GetWebHostBuilder(configuration, rootScope, webHostScopeWrapper, appLogger, rootScope.Top()); var app = new App(webHostBuilder, cancellationTokenSource, appLogger, configuration) { AppRootScope = rootScope.SubScope }; return(app); }
public RealTestFactory(Assemblies assemblies, UserCache userCache) { this.assemblies = assemblies; this.userCache = userCache; }
// Get an assembly by its image name public Assembly GetAssembly(string name) => Assemblies.FirstOrDefault(a => a.ShortName == name);
public RealTest CreateRealTest(Assemblies assemblies, UserCache cache) { RealTestFactory testFactory = new RealTestFactory(assemblies, cache); return testFactory.CreateRealTestFrom(this); }
private async Task RunItemAsync(SchedulerDataProvider schedDP, SchedulerItemData item) { long logId = DateTime.UtcNow.Ticks; SchedulerLog.SetCurrent(logId, 0, item.Name); item.IsRunning = true; item.RunTime = new TimeSpan(); item.Last = DateTime.UtcNow; try { await schedDP.UpdateItemAsync(item); } catch (Exception exc) { Logging.AddErrorLog("Updating scheduler item {0} failed.", item.Name, exc); } StringBuilder errors = new StringBuilder(); DateTime? nextRun = null;// called event handlers can return a next run time try { item.Errors = null; DateTime now = DateTime.UtcNow; { string m = $"Scheduler event - running scheduler item '{item.Name}'."; Logging.AddLog(m); errors.AppendLine(m); } Type tp = null; try { Assembly asm = Assemblies.Load(item.Event.ImplementingAssembly); tp = asm.GetType(item.Event.ImplementingType); } catch (Exception exc) { throw new InternalError("Scheduler item '{0}' could not be loaded (Type={1}, Assembly={2}) - {3}", item.Name, item.Event.ImplementingType, item.Event.ImplementingAssembly, ErrorHandling.FormatExceptionMessage(exc)); } if (item.SiteSpecific) { DataProviderGetRecords <SiteDefinition> info = await SiteDefinition.GetSitesAsync(0, 0, null, null); foreach (SiteDefinition site in info.Data) { IScheduling schedEvt = null; try { schedEvt = (IScheduling)Activator.CreateInstance(tp); } catch (Exception exc) { string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddLog(m); errors.AppendLine(m); } if (schedEvt != null) { YetaWFManager.MakeThreadInstance(site, null, true);// set up a manager for the site SchedulerLog.LimitTo(YetaWFManager.Manager); SchedulerLog.SetCurrent(logId, site.Identity, item.Name); SchedulerItemBase itemBase = new SchedulerItemBase { Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = true }; try { await schedEvt.RunItemAsync(itemBase); } catch (Exception exc) { string m = $"An error occurred in scheduler item '{site.Identity}: {item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddLog(m); errors.AppendLine(m); } foreach (var s in itemBase.Log) { string m = $"{site.Identity}: {s}"; Logging.AddLog(m); errors.AppendLine(m); } if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun)) { nextRun = itemBase.NextRun; } YetaWFManager.RemoveThreadInstance(); YetaWFManager.MakeThreadInstance(null, null, true);// restore scheduler's manager SchedulerLog.LimitTo(YetaWFManager.Manager); SchedulerLog.SetCurrent(); } } } else { IScheduling schedEvt = null; try { schedEvt = (IScheduling)Activator.CreateInstance(tp); } catch (Exception exc) { string m = $"Scheduler item '{item.Name}' could not be instantiated (Type={item.Event.ImplementingType}, Assembly={item.Event.ImplementingAssembly}) - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddLog(m); errors.AppendLine(m); } if (schedEvt != null) { SchedulerItemBase itemBase = new SchedulerItemBase { Name = item.Name, Description = item.Description, EventName = item.Event.Name, Enabled = true, Frequency = item.Frequency, Startup = item.Startup, SiteSpecific = false }; try { await schedEvt.RunItemAsync(itemBase); } catch (Exception exc) { string m = $"An error occurred in scheduler item '{item.Name}' - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddLog(m); errors.AppendLine(m); } foreach (var s in itemBase.Log) { Logging.AddLog(s); errors.AppendLine(s); } if (itemBase.NextRun != null && (nextRun == null || (DateTime)itemBase.NextRun < nextRun)) { nextRun = itemBase.NextRun; } } } TimeSpan diff = DateTime.UtcNow - now; item.RunTime = diff; { string m = $"Elapsed time for scheduler item '{item.Name}' was {diff} (hh:mm:ss.ms)."; Logging.AddLog(m); errors.AppendLine(m); } } catch (Exception exc) { string m = $"Scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddErrorLog(m); errors.AppendLine(m); } if (item.RunOnce) { item.Enabled = false; } item.IsRunning = false; item.SetNextRuntime(); if (nextRun != null) { Logging.AddLog($"Next run at {nextRun} (UTC)"); item.Next = nextRun; item.Enabled = true; } item.Errors = errors.ToString(); try { await schedDP.UpdateItemAsync(item); } catch (Exception exc) { string m = $"Updating scheduler item {item.Name} failed - {ErrorHandling.FormatExceptionMessage(exc)}"; Logging.AddErrorLog(m); errors.AppendLine(m); } SchedulerLog.SetCurrent(); }
public Assemblies(Assemblies other) { appDomain = other.appDomain; assemblies = new List<Types>(other.assemblies); }
public AssemblyTypeResolver(IEnumerable <Assembly> assemblies) { Assemblies.AddRange(assemblies); }
public ApplicationUnderTest(ApplicationDomain appDomain) { assemblies = new Assemblies(appDomain); namespaces = new Namespaces(); AddNamespace(GetType().Namespace); }
public void AddAssembly(AssemblyFile assembly) { Assemblies?.Add(assembly); }
public ApplicationUnderTest(ApplicationUnderTest other) { assemblies = new Assemblies(other.assemblies); namespaces = new Namespaces(other.namespaces); }
public GrpcProxyerOptions AddAssembly(params Assembly[] assemblies) { Assemblies.AddRange(assemblies); return(this); }
public AssemblyTypes(Assemblies assemblies) { Assemblies = assemblies; }
public void Compile() { // Compile the managed assemblies into object files or shared libraries if (App.IsDeviceBuild) { foreach (var a in Assemblies) { a.CreateCompilationTasks(compile_tasks, BuildDirectory, Abis); } } // The static registrar. List <string> registration_methods = null; if (App.Registrar == RegistrarMode.Static) { var registrar_m = Path.Combine(ArchDirectory, "registrar.m"); var registrar_h = Path.Combine(ArchDirectory, "registrar.h"); if (!Application.IsUptodate(Assemblies.Select(v => v.FullPath), new string[] { registrar_m, registrar_h })) { StaticRegistrar.Generate(Assemblies.Select((a) => a.AssemblyDefinition), registrar_h, registrar_m); registration_methods = new List <string> (); registration_methods.Add("xamarin_create_classes"); Driver.Watch("Registrar", 1); } else { Driver.Log(3, "Target '{0}' is up-to-date.", registrar_m); } RegistrarTask.Create(compile_tasks, Abis, this, registrar_m); } if (App.Registrar == RegistrarMode.Dynamic && App.IsSimulatorBuild && App.LinkMode == LinkMode.None) { if (registration_methods == null) { registration_methods = new List <string> (); } string method; string library; switch (App.Platform) { case ApplePlatform.iOS: method = "xamarin_create_classes_Xamarin_iOS"; library = "Xamarin.iOS.registrar.a"; break; case ApplePlatform.WatchOS: method = "xamarin_create_classes_Xamarin_WatchOS"; library = "Xamarin.WatchOS.registrar.a"; break; case ApplePlatform.TVOS: method = "xamarin_create_classes_Xamarin_TVOS"; library = "Xamarin.TVOS.registrar.a"; break; default: throw ErrorHelper.CreateError(71, "Unknown platform: {0}. This usually indicates a bug in Xamarin.iOS; please file a bug report at http://bugzilla.xamarin.com with a test case.", App.Platform); } registration_methods.Add(method); link_with.Add(Path.Combine(Driver.GetProductSdkDirectory(App), "usr", "lib", library)); } // The main method. foreach (var abi in Abis) { MainTask.Create(compile_tasks, this, abi, Assemblies, App.AssemblyName, registration_methods); } // Start compiling. compile_tasks.ExecuteInParallel(); if (App.FastDev) { foreach (var a in Assemblies) { if (a.Dylibs == null) { continue; } foreach (var dylib in a.Dylibs) { LinkWith(dylib); } } } Driver.Watch("Compile", 1); }
public IEnumerable <Type> GetImplementations() { return(Assemblies.SelectMany(SelectTypes)); }
public Winforms() { if (PlatformHelper.IsRunningOnMono()) { throw new NotSupportedException("Building events for Winforms on Mac is not implemented."); } else { // BackgroundWorker // EventLog // FileSystemWatcher // PerformanceCounter // Process // SerialPort Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.dll"); // DataSet Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Data.dll"); // DirectoryEntry // DirectorySearcher Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.DirectoryServices.dll"); // PrintDocument Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Drawing.dll"); // MessageQueue Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Messaging.dll"); // BindingNavigator // ToolStripButton // ToolStripLabel // ToolStripButton // ToolStripButton // ToolStripButton // ToolStripSeparator // ToolStripTextBox // ToolStripSeparator // ToolStripButton // ToolStripButton // ToolStripSeparator // BindingSource // Button // CheckBox // CheckedListBox // ColorDialog // ComboBox // ContextMenuStrip // DataGridView // DateTimePicker // DomainUpDown // ErrorProvider // WebBrowser // VScrollBar // TreeView // ToolStripContainer // TrackBar // ToolStrip // SplitContainer // TabControl // TabPage // TableLayoutPanel // TextBox // TabPage // StatusStrip // Splitter // RichTextBox // RadioButton // PropertyGrid // ProgressBar // PrintPreviewControl // PictureBox // Panel // NumericUpDown // MonthCalendar // MaskedTextBox // ListView // ListBox // LinkLabel // Label // HScrollBar // GroupBox // FlowLayoutPanel // MenuStrip // FolderBrowserDialog // FontDialog // HelpProvider // ImageList // NotifyIcon // OpenFileDialog // PageSetupDialog // PrintDialog // PrintPreviewDialog // SaveFileDialog // Timer // ToolTip Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Windows.Forms.dll"); // Chart Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.Windows.Forms.DataVisualization.dll"); // ServiceController Assemblies.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1\System.ServiceProcess.dll"); CecilSearchDirectories.Add(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.1"); } }
// Extracts library project contents under e.g. obj/Debug/[__library_projects__/*.jar | res/*/*] // Extracts library project contents under e.g. obj/Debug/[lp/*.jar | res/*/*] void Extract( DirectoryAssemblyResolver res, IDictionary <string, ITaskItem> jars, ICollection <ITaskItem> resolvedResourceDirectories, ICollection <ITaskItem> resolvedAssetDirectories, ICollection <ITaskItem> resolvedEnvironments) { // lets "upgrade" the old directory. string oldPath = Path.GetFullPath(Path.Combine(OutputImportDirectory, "..", "__library_projects__")); if (!OutputImportDirectory.Contains("__library_projects__") && Directory.Exists(oldPath)) { MonoAndroidHelper.SetDirectoryWriteable(Path.Combine(oldPath, "..")); Directory.Delete(oldPath, recursive: true); } var outdir = Path.GetFullPath(OutputImportDirectory); Directory.CreateDirectory(outdir); foreach (var assembly in Assemblies) { res.Load(assembly.ItemSpec); } // FIXME: reorder references by import priority (not sure how to do that yet) foreach (var assemblyPath in Assemblies .Select(a => a.ItemSpec) .Distinct()) { var fileName = Path.GetFileName(assemblyPath); if (MonoAndroidHelper.IsFrameworkAssembly(fileName) && !MonoAndroidHelper.FrameworkEmbeddedJarLookupTargets.Contains(fileName) && !MonoAndroidHelper.FrameworkEmbeddedNativeLibraryAssemblies.Contains(fileName)) { Log.LogDebugMessage($"Skipping framework assembly '{fileName}'."); continue; } if (DesignTimeBuild && !File.Exists(assemblyPath)) { Log.LogDebugMessage($"Skipping non-existent dependency '{assemblyPath}' during a design-time build."); continue; } if (assembliestoSkipExtraction.Contains(assemblyPath)) { Log.LogDebugMessage("Skipping resource extraction for '{0}' .", assemblyPath); continue; } string assemblyFileName = Path.GetFileNameWithoutExtension(assemblyPath); string assemblyIdentName = assemblyFileName; if (UseShortFileNames) { assemblyIdentName = assemblyMap.GetLibraryImportDirectoryNameForAssembly(assemblyFileName); } string outDirForDll = Path.Combine(OutputImportDirectory, assemblyIdentName); string importsDir = Path.Combine(outDirForDll, ImportsDirectory); string nativeimportsDir = Path.Combine(outDirForDll, NativeImportsDirectory); string resDir = Path.Combine(importsDir, "res"); string assetsDir = Path.Combine(importsDir, "assets"); // Skip already-extracted resources. bool updated = false; string assemblyHash = MonoAndroidHelper.HashFile(assemblyPath); string stamp = Path.Combine(outdir, assemblyIdentName + ".stamp"); string stampHash = File.Exists(stamp) ? File.ReadAllText(stamp) : null; if (assemblyHash == stampHash) { Log.LogDebugMessage("Skipped resource lookup for {0}: extracted files are up to date", assemblyPath); if (Directory.Exists(importsDir)) { foreach (var file in Directory.EnumerateFiles(importsDir, "*.jar", SearchOption.AllDirectories)) { AddJar(jars, Path.GetFullPath(file)); } } if (Directory.Exists(resDir)) { var taskItem = new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> { { OriginalFile, assemblyPath }, }); if (assembliesToSkipCaseFixup.Contains(assemblyPath)) { taskItem.SetMetadata(AndroidSkipResourceProcessing, "True"); } resolvedResourceDirectories.Add(taskItem); } if (Directory.Exists(assetsDir)) { resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> { { OriginalFile, assemblyPath } })); } foreach (var env in Directory.EnumerateFiles(outDirForDll, "__AndroidEnvironment__*", SearchOption.TopDirectoryOnly)) { resolvedEnvironments.Add(new TaskItem(env, new Dictionary <string, string> { { OriginalFile, assemblyPath } })); } continue; } Log.LogDebugMessage($"Refreshing {assemblyFileName}.dll"); var assembly = res.GetAssembly(assemblyPath); foreach (var mod in assembly.Modules) { // android environment files foreach (var envtxt in mod.Resources .Where(r => r.Name.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase)) .Where(r => r is EmbeddedResource) .Cast <EmbeddedResource> ()) { var outFile = Path.Combine(outDirForDll, envtxt.Name); using (var stream = envtxt.GetResourceStream()) { updated |= MonoAndroidHelper.CopyIfStreamChanged(stream, outFile); } resolvedEnvironments.Add(new TaskItem(Path.GetFullPath(outFile), new Dictionary <string, string> { { OriginalFile, assemblyPath } })); } // embedded jars (EmbeddedJar, EmbeddedReferenceJar) var resjars = mod.Resources .Where(r => r.Name.EndsWith(".jar", StringComparison.InvariantCultureIgnoreCase)) .Select(r => (EmbeddedResource)r); foreach (var resjar in resjars) { using (var stream = resjar.GetResourceStream()) { AddJar(jars, importsDir, resjar.Name, assemblyPath); updated |= MonoAndroidHelper.CopyIfStreamChanged(stream, Path.Combine(importsDir, resjar.Name)); } } var libzip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidNativeLibraries__.zip") as EmbeddedResource; if (libzip != null) { List <string> files = new List <string> (); using (var stream = libzip.GetResourceStream()) using (var zip = Xamarin.Tools.Zip.ZipArchive.Open(stream)) { try { updated |= Files.ExtractAll(zip, nativeimportsDir, modifyCallback: (entryFullName) => { files.Add(Path.GetFullPath(Path.Combine(nativeimportsDir, entryFullName))); return(entryFullName .Replace("native_library_imports\\", "") .Replace("native_library_imports/", "")); }, deleteCallback: (fileToDelete) => { return(!files.Contains(fileToDelete)); }); } catch (PathTooLongException ex) { Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}"); return; } catch (NotSupportedException ex) { Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}"); return; } } } // embedded AndroidResourceLibrary archive var reszip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidLibraryProjects__.zip") as EmbeddedResource; if (reszip != null) { // temporarily extracted directory will look like: // __library_projects__/[dllname]/[library_project_imports | jlibs]/bin using (var stream = reszip.GetResourceStream()) using (var zip = Xamarin.Tools.Zip.ZipArchive.Open(stream)) { try { updated |= Files.ExtractAll(zip, importsDir, modifyCallback: (entryFullName) => { var path = entryFullName .Replace("library_project_imports\\", "") .Replace("library_project_imports/", ""); if (path.EndsWith(".jar", StringComparison.OrdinalIgnoreCase)) { AddJar(jars, importsDir, path, assemblyPath); } return(path); }, deleteCallback: (fileToDelete) => { return(!jars.ContainsKey(fileToDelete)); }); } catch (PathTooLongException ex) { Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}"); return; } catch (NotSupportedException ex) { Log.LogCodedError("XA4303", $"Error extracting resources from \"{assemblyPath}\": {ex}"); return; } } // We used to *copy* the resources to overwrite other resources, // which resulted in missing resource issue. // Here we replaced copy with use of '-S' option and made it to work. if (Directory.Exists(resDir)) { var taskItem = new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> { { OriginalFile, assemblyPath } }); if (assembliesToSkipCaseFixup.Contains(assemblyPath)) { taskItem.SetMetadata(AndroidSkipResourceProcessing, "True"); } resolvedResourceDirectories.Add(taskItem); } if (Directory.Exists(assetsDir)) { resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> { { OriginalFile, assemblyPath } })); } } } if (Directory.Exists(importsDir)) { // Delete unknown files in the top directory of importsDir foreach (var file in Directory.EnumerateFiles(importsDir, "*")) { var fullPath = Path.GetFullPath(file); if (file.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase) && !resolvedEnvironments.Any(x => x.ItemSpec == fullPath)) { Log.LogDebugMessage($"Deleting unknown AndroidEnvironment file: {Path.GetFileName (file)}"); File.Delete(fullPath); updated = true; } else if (file.EndsWith(".jar", StringComparison.OrdinalIgnoreCase) && !jars.ContainsKey(fullPath)) { Log.LogDebugMessage($"Deleting unknown jar: {Path.GetFileName (file)}"); File.Delete(fullPath); updated = true; } } if (assemblyHash != stampHash) { Log.LogDebugMessage($"Saving hash to {stamp}, changes: {updated}"); //NOTE: if the hash is different we always want to write the file, but preserve the timestamp if no changes WriteAllText(stamp, assemblyHash, preserveTimestamp: !updated); } } } foreach (var aarFile in AarLibraries ?? new ITaskItem[0]) { if (!File.Exists(aarFile.ItemSpec)) { continue; } string aarIdentityName = Path.GetFileNameWithoutExtension(aarFile.ItemSpec); if (UseShortFileNames) { aarIdentityName = assemblyMap.GetLibraryImportDirectoryNameForAssembly(aarIdentityName); } string outDirForDll = Path.Combine(OutputImportDirectory, aarIdentityName); string importsDir = Path.Combine(outDirForDll, ImportsDirectory); string resDir = Path.Combine(importsDir, "res"); string assetsDir = Path.Combine(importsDir, "assets"); bool updated = false; string aarHash = MonoAndroidHelper.HashFile(aarFile.ItemSpec); string stamp = Path.Combine(outdir, aarIdentityName + ".stamp"); string stampHash = File.Exists(stamp) ? File.ReadAllText(stamp) : null; var aarFullPath = Path.GetFullPath(aarFile.ItemSpec); if (aarHash == stampHash) { Log.LogDebugMessage("Skipped {0}: extracted files are up to date", aarFile.ItemSpec); if (Directory.Exists(importsDir)) { foreach (var file in Directory.EnumerateFiles(importsDir, "*.jar", SearchOption.AllDirectories)) { AddJar(jars, Path.GetFullPath(file)); } } if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> { { OriginalFile, Path.GetFullPath(aarFile.ItemSpec) }, { AndroidSkipResourceProcessing, "True" }, })); } if (Directory.Exists(assetsDir)) { resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> { { OriginalFile, aarFullPath }, })); } continue; } Log.LogDebugMessage($"Refreshing {aarFile.ItemSpec}"); // temporarily extracted directory will look like: // _lp_/[aarFile] using (var zip = MonoAndroidHelper.ReadZipFile(aarFile.ItemSpec)) { try { updated |= Files.ExtractAll(zip, importsDir, modifyCallback: (entryFullName) => { var entryFileName = Path.GetFileName(entryFullName); var entryPath = Path.GetDirectoryName(entryFullName); if (entryFileName.StartsWith("internal_impl", StringComparison.InvariantCulture)) { var hash = Files.HashString(entryFileName); var jar = Path.Combine(entryPath, $"internal_impl-{hash}.jar"); AddJar(jars, importsDir, jar, aarFullPath); return(jar); } if (entryFullName.EndsWith(".jar", StringComparison.OrdinalIgnoreCase)) { AddJar(jars, importsDir, entryFullName, aarFullPath); } return(entryFullName); }, deleteCallback: (fileToDelete) => { return(!jars.ContainsKey(fileToDelete)); }); if (Directory.Exists(importsDir) && aarHash != stampHash) { Log.LogDebugMessage($"Saving hash to {stamp}, changes: {updated}"); //NOTE: if the hash is different we always want to write the file, but preserve the timestamp if no changes WriteAllText(stamp, aarHash, preserveTimestamp: !updated); } } catch (PathTooLongException ex) { Log.LogErrorFromException(new PathTooLongException($"Error extracting resources from \"{aarFile.ItemSpec}\"", ex)); } } if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(new TaskItem(Path.GetFullPath(resDir), new Dictionary <string, string> { { OriginalFile, aarFullPath }, { AndroidSkipResourceProcessing, "True" }, })); } if (Directory.Exists(assetsDir)) { resolvedAssetDirectories.Add(new TaskItem(Path.GetFullPath(assetsDir), new Dictionary <string, string> { { OriginalFile, aarFullPath }, })); } } }
/// <summary> /// Initializes a new instance of <see cref="YamlLocalizationSourceBase{T}"/> /// </summary> /// <param name="filename">The filename of the json file the contains the localization.</param> public YamlLocalizationSourceBase(string filename) { this.localizations = YamlConvert.DeserializeObject <T>(Assemblies.GetManifestResource(filename).TryEncode()); }
public override bool Execute() { RemotingUtility.CleanUpRegisteredChannels(); XElement assembliesElement = null; var environment = String.Format("{0}-bit .NET {1}", IntPtr.Size * 8, Environment.Version); if (NeedsXml) { assembliesElement = new XElement("assemblies"); } string originalWorkingFolder = Directory.GetCurrentDirectory(); using (AssemblyHelper.SubscribeResolve()) { Log.LogMessage(MessageImportance.High, "xUnit.net MSBuild runner ({0})", environment); var testAssemblyPaths = Assemblies.Select(assembly => { string assemblyFileName = assembly.GetMetadata("FullPath"); string configFileName = assembly.GetMetadata("ConfigFile"); if (configFileName != null && configFileName.Length == 0) { configFileName = null; } return(Tuple.Create(assemblyFileName, configFileName)); }).ToList(); if (WorkingFolder != null) { Directory.SetCurrentDirectory(WorkingFolder); } if (ParallelizeAssemblies) { var tasks = testAssemblyPaths.Select(path => Task.Run(() => ExecuteAssembly(path.Item1, path.Item2))); var results = Task.WhenAll(tasks).GetAwaiter().GetResult(); foreach (var assemblyElement in results.Where(result => result != null)) { assembliesElement.Add(assemblyElement); } } else { foreach (var path in testAssemblyPaths) { var assemblyElement = ExecuteAssembly(path.Item1, path.Item2); if (assemblyElement != null) { assembliesElement.Add(assemblyElement); } } } if (completionMessages.Count > 0) { Log.LogMessage(MessageImportance.High, "=== TEST EXECUTION SUMMARY ==="); int longestAssemblyName = completionMessages.Keys.Max(key => key.Length); int longestTotal = completionMessages.Values.Max(summary => summary.Total.ToString().Length); int longestFailed = completionMessages.Values.Max(summary => summary.Failed.ToString().Length); int longestSkipped = completionMessages.Values.Max(summary => summary.Skipped.ToString().Length); int longestTime = completionMessages.Values.Max(summary => summary.Time.ToString("0.000s").Length); foreach (var message in completionMessages.OrderBy(m => m.Key)) { Log.LogMessage(MessageImportance.High, " {0} Total: {1}, Failed: {2}, Skipped: {3}, Time: {4}", message.Key.PadRight(longestAssemblyName), message.Value.Total.ToString().PadLeft(longestTotal), message.Value.Failed.ToString().PadLeft(longestFailed), message.Value.Skipped.ToString().PadLeft(longestSkipped), message.Value.Time.ToString("0.000s").PadLeft(longestTime)); } } } Directory.SetCurrentDirectory(WorkingFolder ?? originalWorkingFolder); if (NeedsXml) { if (Xml != null) { assembliesElement.Save(Xml.GetMetadata("FullPath")); } if (XmlV1 != null) { Transform("xUnit1.xslt", assembliesElement, XmlV1); } if (Html != null) { Transform("HTML.xslt", assembliesElement, Html); } } return(ExitCode == 0); }
private bool Equals(Architecture other) { return(Assemblies.Equals(other.Assemblies) && Namespaces.Equals(other.Namespaces) && Types.Equals(other.Types)); }
private void OnExecuteAssemblyRemoveAll() { RemoveAssemblies(Assemblies.ToArray()); }
public PoetryConfigurator AddAssembly(Assembly assembly) { Assemblies.Add(new AssemblyWrapper(assembly)); return(this); }
public IList <Assembly> GetAssemblies() { return(Assemblies.ToList()); }
// Create type model public TypeModel(Il2CppInspector package) { Package = package; TypesByDefinitionIndex = new TypeInfo[package.TypeDefinitions.Length]; TypesByReferenceIndex = new TypeInfo[package.TypeReferences.Count]; GenericParameterTypes = new TypeInfo[package.GenericParameters.Length]; MethodsByDefinitionIndex = new MethodBase[package.Methods.Length]; MethodInvokers = new MethodInvoker[package.MethodInvokePointers.Length]; // Recursively create hierarchy of assemblies and types from TypeDefs // No code that executes here can access any type through a TypeRef (ie. via TypesByReferenceIndex) for (var image = 0; image < package.Images.Length; image++) { Assemblies.Add(new Assembly(this, image)); } // Create and reference types from TypeRefs // Note that you can't resolve any TypeRefs until all the TypeDefs have been processed for (int typeRefIndex = 0; typeRefIndex < package.TypeReferences.Count; typeRefIndex++) { if (TypesByReferenceIndex[typeRefIndex] != null) { /* type already generated - probably by forward reference through GetTypeFromVirtualAddress */ continue; } var typeRef = Package.TypeReferences[typeRefIndex]; var referencedType = resolveTypeReference(typeRef); TypesByReferenceIndex[typeRefIndex] = referencedType; } // Create types and methods from MethodSpec (which incorporates TypeSpec in IL2CPP) foreach (var spec in Package.MethodSpecs) { var methodDefinition = MethodsByDefinitionIndex[spec.methodDefinitionIndex]; var declaringType = methodDefinition.DeclaringType; // Concrete instance of a generic class // If the class index is not specified, we will later create a generic method in a non-generic class if (spec.classIndexIndex != -1) { var genericInstance = Package.GenericInstances[spec.classIndexIndex]; var genericArguments = ResolveGenericArguments(genericInstance); declaringType = declaringType.MakeGenericType(genericArguments); } MethodBase method; if (methodDefinition is ConstructorInfo) { method = declaringType.GetConstructorByDefinition((ConstructorInfo)methodDefinition); } else { method = declaringType.GetMethodByDefinition((MethodInfo)methodDefinition); } if (spec.methodIndexIndex != -1) { var genericInstance = Package.GenericInstances[spec.methodIndexIndex]; var genericArguments = ResolveGenericArguments(genericInstance); method = method.MakeGenericMethod(genericArguments); } method.VirtualAddress = Package.GetGenericMethodPointer(spec); GenericMethods[spec] = method; } // Generate a list of all namespaces used Namespaces = Assemblies.SelectMany(x => x.DefinedTypes).GroupBy(t => t.Namespace).Select(n => n.Key).Distinct().ToList(); // Find all custom attribute generators (populate AttributesByIndices) (use ToList() to force evaluation) var allAssemblyAttributes = Assemblies.Select(a => a.CustomAttributes).ToList(); var allTypeAttributes = TypesByDefinitionIndex.Select(t => t.CustomAttributes).ToList(); var allEventAttributes = TypesByDefinitionIndex.SelectMany(t => t.DeclaredEvents).Select(e => e.CustomAttributes).ToList(); var allFieldAttributes = TypesByDefinitionIndex.SelectMany(t => t.DeclaredFields).Select(f => f.CustomAttributes).ToList(); var allPropertyAttributes = TypesByDefinitionIndex.SelectMany(t => t.DeclaredProperties).Select(p => p.CustomAttributes).ToList(); var allMethodAttributes = MethodsByDefinitionIndex.Select(m => m.CustomAttributes).ToList(); var allParameterAttributes = MethodsByDefinitionIndex.SelectMany(m => m.DeclaredParameters).Select(p => p.CustomAttributes).ToList(); // Create method invokers (one per signature, in invoker index order) foreach (var method in MethodsByDefinitionIndex) { var index = package.GetInvokerIndex(method.DeclaringType.Assembly.ModuleDefinition, method.Definition); if (index != -1) { if (MethodInvokers[index] == null) { MethodInvokers[index] = new MethodInvoker(method, index); } method.Invoker = MethodInvokers[index]; } } // TODO: Some invokers are not initialized or missing, need to find out why // Create method invokers sourced from generic method invoker indices foreach (var spec in GenericMethods.Keys) { if (package.GenericMethodInvokerIndices.TryGetValue(spec, out var index)) { if (MethodInvokers[index] == null) { MethodInvokers[index] = new MethodInvoker(GenericMethods[spec], index); } GenericMethods[spec].Invoker = MethodInvokers[index]; } } }
public ByConventionConfiguration AddFromAssemblyOfThis <T>() { Assemblies.Add(typeof(T).Assembly); return(this); }
/// <summary> /// Load assembly from disk /// </summary> /// <param name="location">assembly location</param> /// <param name="loadsymbols">load pdb symbols</param> /// <returns></returns> public override AssemblyDefinition LoadAssembly(string location, bool loadsymbols) { // Stay in sync with Cecil Studio browser, don't load anything but reuse previously loaded assembly return(Assemblies.Cast <AssemblyDefinition>().FirstOrDefault(adef => adef.MainModule.Image.FileName.Equals(location, StringComparison.OrdinalIgnoreCase))); }
// Extracts library project contents under e.g. obj/Debug/[__library_projects__/*.jar | res/*/*] // Extracts library project contents under e.g. obj/Debug/[lp/*.jar | res/*/*] void Extract( DirectoryAssemblyResolver res, ICollection <string> jars, ICollection <string> resolvedResourceDirectories, ICollection <string> resolvedAssetDirectories, ICollection <string> resolvedEnvironments) { // lets "upgrade" the old directory. string oldPath = Path.GetFullPath(Path.Combine(OutputImportDirectory, "..", "__library_projects__")); if (!OutputImportDirectory.Contains("__library_projects__") && Directory.Exists(oldPath)) { MonoAndroidHelper.SetDirectoryWriteable(Path.Combine(oldPath, "..")); Directory.Delete(oldPath, recursive: true); } var outdir = new DirectoryInfo(OutputImportDirectory); if (!outdir.Exists) { outdir.Create(); } foreach (var assembly in Assemblies) { res.Load(assembly.ItemSpec); } // FIXME: reorder references by import priority (not sure how to do that yet) foreach (var assemblyPath in Assemblies .Select(a => GetTargetAssembly(a)) .Where(a => a != null) .Distinct()) { string assemblyIdentName = Path.GetFileNameWithoutExtension(assemblyPath); if (UseShortFileNames) { assemblyIdentName = assemblyMap.GetLibraryImportDirectoryNameForAssembly(assemblyIdentName); } string outDirForDll = Path.Combine(OutputImportDirectory, assemblyIdentName); string importsDir = Path.Combine(outDirForDll, ImportsDirectory); #if SEPARATE_CRUNCH // FIXME: review these binResDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. //string binResDir = Path.Combine (importsDir, "bin", "res"); //string binAssemblyDir = Path.Combine (importsDir, "bin", "assets"); #endif string resDir = Path.Combine(importsDir, "res"); string assemblyDir = Path.Combine(importsDir, "assets"); // Skip already-extracted resources. var stamp = new FileInfo(Path.Combine(outdir.FullName, assemblyIdentName + ".stamp")); if (stamp.Exists && stamp.LastWriteTimeUtc > new FileInfo(assemblyPath).LastWriteTimeUtc) { Log.LogDebugMessage("Skipped resource lookup for {0}: extracted files are up to date", assemblyPath); #if SEPARATE_CRUNCH // FIXME: review these binResDir/binAssemblyDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. if (Directory.Exists(binResDir)) { resolvedResourceDirectories.Add(binResDir); } if (Directory.Exists(binAssemblyDir)) { resolvedAssetDirectories.Add(binAssemblyDir); } #endif if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(resDir); } if (Directory.Exists(assemblyDir)) { resolvedAssetDirectories.Add(assemblyDir); } foreach (var env in Directory.EnumerateFiles(outDirForDll, "__AndroidEnvironment__*", SearchOption.TopDirectoryOnly)) { resolvedEnvironments.Add(env); } continue; } Log.LogDebugMessage("Refreshing {0}", assemblyPath); Directory.CreateDirectory(importsDir); var assembly = res.GetAssembly(assemblyPath); var assemblyLastWrite = new FileInfo(assemblyPath).LastWriteTimeUtc; bool updated = false; foreach (var mod in assembly.Modules) { // android environment files foreach (var envtxt in mod.Resources .Where(r => r.Name.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase)) .Where(r => r is EmbeddedResource) .Cast <EmbeddedResource> ()) { if (!Directory.Exists(outDirForDll)) { Directory.CreateDirectory(outDirForDll); } var finfo = new FileInfo(Path.Combine(outDirForDll, envtxt.Name)); if (!finfo.Exists || finfo.LastWriteTimeUtc > assemblyLastWrite) { using (var fs = finfo.Create()) { var data = envtxt.GetResourceData(); fs.Write(data, 0, data.Length); } updated = true; } resolvedEnvironments.Add(finfo.FullName); } // embedded jars (EmbeddedJar, EmbeddedReferenceJar) var resjars = mod.Resources .Where(r => r.Name.EndsWith(".jar", StringComparison.InvariantCultureIgnoreCase)) .Select(r => (EmbeddedResource)r); foreach (var resjar in resjars) { var outjarFile = Path.Combine(importsDir, resjar.Name); var fi = new FileInfo(outjarFile); if (!fi.Exists || fi.LastWriteTimeUtc > assemblyLastWrite) { var data = resjar.GetResourceData(); using (var outfs = File.Create(outjarFile)) outfs.Write(data, 0, data.Length); updated = true; } jars.Add(outjarFile); } // embedded AndroidResourceLibrary archive var reszip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidLibraryProjects__.zip") as EmbeddedResource; if (reszip != null) { if (!Directory.Exists(outDirForDll)) { Directory.CreateDirectory(outDirForDll); } var finfo = new FileInfo(Path.Combine(outDirForDll, reszip.Name)); using (var fs = finfo.Create()) { var data = reszip.GetResourceData(); fs.Write(data, 0, data.Length); } // temporarily extracted directory will look like: // __library_projects__/[dllname]/[library_project_imports | jlibs]/bin using (var zip = MonoAndroidHelper.ReadZipFile(finfo.FullName)) { try { updated |= Files.ExtractAll(zip, importsDir, modifyCallback: (entryFullName) => { return(entryFullName .Replace("library_project_imports\\", "") .Replace("library_project_imports/", "")); }, deleteCallback: (fileToDelete) => { return(!jars.Contains(fileToDelete)); }, forceUpdate: false); } catch (PathTooLongException ex) { Log.LogErrorFromException(new PathTooLongException($"Error extracting resources from \"{assemblyPath}\"", ex)); } } // We used to *copy* the resources to overwrite other resources, // which resulted in missing resource issue. // Here we replaced copy with use of '-S' option and made it to work. #if SEPARATE_CRUNCH // FIXME: review these binResDir/binAssemblyDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. if (Directory.Exists(binResDir)) { resolvedResourceDirectories.Add(binResDir); } if (Directory.Exists(binAssemblyDir)) { resolvedAssetDirectories.Add(binAssemblyDir); } #endif if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(resDir); } if (Directory.Exists(assemblyDir)) { resolvedAssetDirectories.Add(assemblyDir); } finfo.Delete(); } } if (Directory.Exists(importsDir) && (updated || !stamp.Exists)) { Log.LogDebugMessage("Touch {0}", stamp.FullName); stamp.Create().Close(); } } foreach (var f in outdir.GetFiles("*.jar", SearchOption.AllDirectories) .Select(fi => fi.FullName)) { if (jars.Contains(f)) { continue; } jars.Add(f); } }
// Extracts library project contents under e.g. obj/Debug/[__library_projects__/*.jar | res/*/*] void Extract( DirectoryAssemblyResolver res, ICollection <string> jars, ICollection <string> resolvedResourceDirectories, ICollection <string> resolvedAssetDirectories, ICollection <string> resolvedEnvironments) { var outdir = new DirectoryInfo(OutputImportDirectory); if (!outdir.Exists) { outdir.Create(); } foreach (var assembly in Assemblies) { res.Load(assembly.ItemSpec); } // FIXME: reorder references by import priority (not sure how to do that yet) foreach (var assemblyPath in Assemblies .Select(a => GetTargetAssembly(a)) .Where(a => a != null) .Distinct()) { foreach (var imp in new string [] { imports_dir, "library_project_imports" }.Distinct()) { string assemblyIdentName = Path.GetFileNameWithoutExtension(assemblyPath); if (UseShortFileNames) { assemblyIdentName = Xamarin.Android.Tasks.MonoAndroidHelper.GetLibraryImportDirectoryNameForAssembly(assemblyIdentName); } string outDirForDll = Path.Combine(OutputImportDirectory, assemblyIdentName); string importsDir = Path.Combine(outDirForDll, imp); #if SEPARATE_CRUNCH // FIXME: review these binResDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. //string binResDir = Path.Combine (importsDir, "bin", "res"); //string binAssemblyDir = Path.Combine (importsDir, "bin", "assets"); #endif string resDir = Path.Combine(importsDir, "res"); string assemblyDir = Path.Combine(importsDir, "assets"); // Skip already-extracted resources. var stamp = new FileInfo(Path.Combine(outdir.FullName, assemblyIdentName + ".stamp")); if (stamp.Exists && stamp.LastWriteTime > new FileInfo(assemblyPath).LastWriteTime) { Log.LogDebugMessage("Skipped resource lookup for {0}: extracted files are up to date", assemblyPath); #if SEPARATE_CRUNCH // FIXME: review these binResDir/binAssemblyDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. if (Directory.Exists(binResDir)) { resolvedResourceDirectories.Add(binResDir); } if (Directory.Exists(binAssemblyDir)) { resolvedAssetDirectories.Add(binAssemblyDir); } #endif if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(resDir); } if (Directory.Exists(assemblyDir)) { resolvedAssetDirectories.Add(assemblyDir); } continue; } if (Directory.Exists(outDirForDll)) { Directory.Delete(outDirForDll, true); } Directory.CreateDirectory(importsDir); var assembly = res.GetAssembly(assemblyPath); foreach (var mod in assembly.Modules) { // android environment files foreach (var envtxt in mod.Resources .Where(r => r.Name.StartsWith("__AndroidEnvironment__", StringComparison.OrdinalIgnoreCase)) .Where(r => r is EmbeddedResource) .Cast <EmbeddedResource> ()) { if (!Directory.Exists(outDirForDll)) { Directory.CreateDirectory(outDirForDll); } var finfo = new FileInfo(Path.Combine(outDirForDll, envtxt.Name)); using (var fs = finfo.Create()) { var data = envtxt.GetResourceData(); fs.Write(data, 0, data.Length); } resolvedEnvironments.Add(finfo.FullName); } // embedded jars (EmbeddedJar, EmbeddedReferenceJar) var resjars = mod.Resources .Where(r => r.Name.EndsWith(".jar", StringComparison.InvariantCultureIgnoreCase)) .Select(r => (EmbeddedResource)r); foreach (var resjar in resjars) { var data = resjar.GetResourceData(); using (var outfs = File.Create(Path.Combine(importsDir, resjar.Name))) outfs.Write(data, 0, data.Length); } // embedded AndroidResourceLibrary archive var reszip = mod.Resources.FirstOrDefault(r => r.Name == "__AndroidLibraryProjects__.zip") as EmbeddedResource; if (reszip != null) { if (!Directory.Exists(outDirForDll)) { Directory.CreateDirectory(outDirForDll); } var finfo = new FileInfo(Path.Combine(outDirForDll, reszip.Name)); using (var fs = finfo.Create()) { var data = reszip.GetResourceData(); fs.Write(data, 0, data.Length); } // temporarily extracted directory will look like: // __library_projects__/[dllname]/[library_project_imports | jlibs]/bin using (var zip = MonoAndroidHelper.ReadZipFile(finfo.FullName)) Files.ExtractAll(zip, outDirForDll); // We used to *copy* the resources to overwrite other resources, // which resulted in missing resource issue. // Here we replaced copy with use of '-S' option and made it to work. #if SEPARATE_CRUNCH // FIXME: review these binResDir/binAssemblyDir thing and enable this. Eclipse does this. // Enabling these blindly causes build failure on ActionBarSherlock. if (Directory.Exists(binResDir)) { resolvedResourceDirectories.Add(binResDir); } if (Directory.Exists(binAssemblyDir)) { resolvedAssetDirectories.Add(binAssemblyDir); } #endif if (Directory.Exists(resDir)) { resolvedResourceDirectories.Add(resDir); } if (Directory.Exists(assemblyDir)) { resolvedAssetDirectories.Add(assemblyDir); } finfo.Delete(); } } stamp.Create().Close(); } } foreach (var f in outdir.GetFiles("*.jar") .Select(fi => fi.FullName)) { jars.Add(f); } }
protected override Assembly Load(AssemblyName args) { if (Assemblies.ContainsKey(args.Name)) { return(Assemblies[args.Name]); } var separatorIndex = args.Name.IndexOf(",", StringComparison.Ordinal); var assemblyName = separatorIndex > 0 ? args.Name.Substring(0, separatorIndex) : args.Name; var assembly = TryLoadExistingAssemblyName(args.FullName); if (assembly != null) { Assemblies[args.Name] = assembly; return(assembly); } var version = args.Version; if (version != null) { // var assemblyByVersion = TryLoadByVersion(AllReferencePaths, assemblyName, version.Major + "." + version.Minor + "." + version.Build + "." + version.Revision); // if (assemblyByVersion != null) // { // Assemblies[args.Name] = assemblyByVersion; // return assemblyByVersion; // } var assemblyByVersion = TryLoadByVersion(AllReferencePaths, assemblyName, version.Major + "." + version.Minor + "." + version.Build + "."); if (assemblyByVersion != null) { Assemblies[args.Name] = assemblyByVersion; return(assemblyByVersion); } assemblyByVersion = TryLoadByVersion(AllReferencePaths, assemblyName, version.Major + "." + version.Minor + "."); if (assemblyByVersion != null) { Assemblies[args.Name] = assemblyByVersion; return(assemblyByVersion); } assemblyByVersion = TryLoadByVersion(AllReferencePaths, assemblyName, version.Major + "."); if (assemblyByVersion != null) { Assemblies[args.Name] = assemblyByVersion; return(assemblyByVersion); } } assembly = TryLoadByAssemblyName(args.FullName); if (assembly != null) { Assemblies[args.Name] = assembly; return(assembly); } assembly = TryLoadByName(AllReferencePaths, assemblyName); if (assembly != null) { Assemblies[args.Name] = assembly; return(assembly); } Assemblies[args.Name] = TryLoadByAssemblyName(assemblyName); return(Assemblies[args.Name]); }