//关于 private void biAbout_Click(object sender, EventArgs e) { var assembly = new AssemblyInformation(Assembly.GetEntryAssembly()); FrmAbout frmAbout = new FrmAbout(assembly, "XuWangBin", "http://www.cnblogs.com/huyong/"); frmAbout.ShowDialog(); }
/// <summary> /// Displays the message on the specified output. /// </summary> /// <param name="output">The output to display the message.</param> private static void DisplayHelp(StreamWriter output) { SetLowlightColor(); DisplayTitle(output); DisplayInfo(output); SetHighlightColor(); output.WriteLine("Usage: "); SetImportantColor(); output.Write(AssemblyInformation.Product()); SetLowlightColor(); output.WriteLine(" source stylesheet [options] [param=value...] [xmlns:prefix=uri...]"); output.WriteLine(); SetHighlightColor(); output.WriteLine("Options:"); SetLowlightColor(); DisplayOption(output, "-?", "Show this message"); DisplayOption(output, "-o filename", "Write output to named file"); DisplayOption(output, "-m startMode", "Start the transform in this mode", true); DisplayOption(output, "-xw", "Strip non-significant whitespace from source and stylesheet"); DisplayOption(output, "-xe", "Do not resolve external definitions during parse phase"); DisplayOption(output, "-v", "Validate documents during parse phase"); DisplayOption(output, "-t", "Show load and transformation timings"); DisplayOption(output, "-pi", "Get stylesheet URL from xml-stylesheet PI in source document"); DisplayOption(output, "-u version", "Use a specific version of MSXML: '2.6', '3.0', '4.0'", true); DisplayOption(output, "-", "Dash used as source argument loads XML from stdin"); DisplayOption(output, "-", "Dash used as stylesheet argument loads XSL from stdin"); output.WriteLine(); }
private static (AssemblyInformation assembly, Assembly?msAssembly) CreateManagedAssemblyInformation(MetadataLoadContext context, AssemblyName assemblyName, string baseDirectory, string extension = "dll") { var assemblyPath = FilePathProvider.GetAssemblyPath($"{assemblyName.Name}.{extension}", baseDirectory); Assembly?assembly = null; try { assembly = File.Exists(assemblyPath) ? context.LoadFromAssemblyPath(assemblyPath ?? string.Empty) : context.LoadFromAssemblyName(assemblyName); } catch { // In this case, assembly is not found } var assemblyShortName = assemblyName.Name ?? string.Empty; var assemblyVersion = assemblyName.Version?.ToString() ?? string.Empty; var info = new AssemblyInformation(assemblyShortName, assembly?.GetName().Version?.ToString() ?? assemblyVersion, assemblyPath) { IsLocalAssembly = assemblyPath != null || assembly == null, AssemblyName = assemblyName.FullName, IsResolved = assembly != null }; info.EnhancePropertiesWithFile(); info.EnhanceProperties(assembly?.GetModules().First()); return(info, assembly); }
public void TestInit() { Assembly assembly = Assembly.LoadFrom("TestConsoleApp.exe"); AssemblyBrowser assemblyBrowser = new AssemblyBrowser(); AssemblyInformation = assemblyBrowser.GetAssemblyInformation(assembly); }
/// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app"></param> /// <param name="env"></param> /// <param name="loggerFactory"></param> /// <param name="options"></param> public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, Microsoft.Extensions.Options.IOptions <ViewBookingOptions> options) { Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(Configuration).CreateLogger(); loggerFactory.AddSerilog(); var config = options.Value; try { //to log errors thrown by Startup() and ConfigureServices() if (StartupErrorHandler.WriteExceptionsToResponse(app, _exceptions, loggerFactory)) { return; } ErrorHandlingSetup(app, env); app.UseStaticFiles(); app.UsePathBase(config.ApplicationRoot); app.UseStatusCodePages(); #if DEBUG app.UseCors("Default"); #endif app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Traveller}/{action=Get}/{id?}"); }); //app.UseMvcWithDefaultRoute(); AssemblyInformation.SetMainAssembly(Assembly.GetExecutingAssembly()); } catch (Exception ex) { StartupErrorHandler.WriteExceptionToResponse(app, ex, loggerFactory); } }
internal static void EnhanceProperties(this AssemblyInformation info, AssemblyDefinition?assembly) { if (assembly == null) { return; } try { info.IsILOnly = (assembly.MainModule.Attributes & ModuleAttributes.ILOnly) == ModuleAttributes.ILOnly; if (assembly.MainModule.Architecture == TargetArchitecture.I386 && info.IsILOnly) // This configuration is for any CPU... { info.TargetProcessor = TargetProcessor.AnyCpu; } else { info.TargetProcessor = TargetProcessorProvider[assembly.MainModule.Architecture]; } info.IsDebug = assembly.GetIsDebugFlag(); info.TargetFramework = assembly.GetTargetFramework(); } catch { // We keep information and skip error } }
private void SaveAddinAttribute(Assembly asm, AssemblyInformation asmInfo) { Type addInAttributeType = asm.GetType("Dover.Framework.Attribute.AddInAttribute"); if (addInAttributeType == null) { addInAttributeType = typeof(AddInAttribute); } var types = (from type in asm.GetTypes() where type.IsClass select type); foreach (var type in types) { var attrs = type.GetCustomAttributes(addInAttributeType, true); if (attrs != null && attrs.Length > 0) { var attr = attrs[0]; dynamic addInAttribute = attr; if (!string.IsNullOrEmpty(addInAttribute.i18n)) { asmInfo.Description = i18nService.GetLocalizedString(addInAttribute.i18n, asm); } else { asmInfo.Description = addInAttribute.Description; } asmInfo.Name = addInAttribute.Name; asmInfo.Namespace = addInAttribute.Namespace; break; } } }
internal override bool AutoUpdateEnabled(AssemblyInformation asm) { string autoUpdateFlag = b1DAO.ExecuteSqlForObject <string>( string.Format(this.GetSQL("CheckAutoUpdate.sql"), asm.Code)); return(!string.IsNullOrEmpty(autoUpdateFlag) && autoUpdateFlag == "Y"); }
public IEnumerable <AssemblyLink> GetNativeLinks(AssemblyInformation assembly, string parentName, string baseDirectory) { if (string.IsNullOrEmpty(assembly.FilePath)) { yield break; } var peFile = new PeFile(assembly.FilePath); if (peFile.ImportedFunctions == null) { yield break; } var referencedAssemblies = peFile.ImportedFunctions .Select(x => GetFilePath(x.DLL, baseDirectory)) .Where(x => !string.Equals(x.file, assembly.FilePath, StringComparison.InvariantCultureIgnoreCase)) .Distinct() .Select(x => GetNative(x.file, x.filePath, x.isSystem, baseDirectory)); foreach (var item in referencedAssemblies) { yield return(GetAssemblyLink(item, parentName)); } }
internal override void SaveAssembly(AssemblyInformation asm, byte[] asmBytes) { string installed = (asm.Type == AssemblyType.Core) ? "Y" : "N"; SoapHexBinary shb = new SoapHexBinary(Compression.Compress(asmBytes)); string asmHex = null; if (asmBytes != null) { asmHex = shb.ToString(); } string sql; if (String.IsNullOrEmpty(asm.Code)) { asm.Code = b1DAO.GetNextCode("DOVER_MODULES"); sql = String.Format(this.GetSQL("SaveAssembly.sql"), asm.Code, asm.Code, asm.Name, asm.Description, asm.FileName, asm.Version, asm.MD5, asm.Date.ToString("yyyyMMdd"), asmBytes.Length, asm.TypeCode, installed, asm.Namespace); } else { sql = String.Format(this.GetSQL("UpdateAssembly.sql"), asm.Version, asm.MD5, asm.Date.ToString("yyyyMMdd"), asmBytes.Length, asm.Code, asm.Description, installed); b1DAO.ExecuteStatement(String.Format(this.GetSQL("DeleteAssembly.sql"), asm.Code)); b1DAO.ExecuteStatement(String.Format(this.GetSQL("DeleteDependencies.sql"), asm.Code)); } b1DAO.ExecuteStatement(sql); // Modules binaries if (asmBytes != null) { InsertAsmBin(asm, asmHex); } }
internal override void SaveAssemblyDependency(AssemblyInformation newAsm, AssemblyInformation dependency, byte[] dependencyBytes) { dependency.Code = null; // force insert. SaveAssembly(dependency, dependencyBytes); SaveAssemblyDependency(newAsm, dependency.Code); }
private void UpdateAssembly(AssemblyInformation asmMeta, string fullPath) { try { Logger.Debug(String.Format(Messages.FileUpdating, asmMeta.Name, asmMeta.Version)); string cacheFile = Path.Combine(GetDoverDirectory(), "..", "Cache", asmMeta.MD5); if (!CreateFromCache(asmMeta, cacheFile, fullPath)) { byte[] asmBytes = asmDAO.GetAssembly(asmMeta); if (asmBytes != null) { File.WriteAllBytes(cacheFile, asmBytes); CreateFromCache(asmMeta, cacheFile, fullPath); } else { Logger.Warn(String.Format(Messages.FileMissing, asmMeta.Name, asmMeta.Version)); } } } catch (Exception e) { Logger.Error(String.Format(Messages.FileError, asmMeta.Name, asmMeta.Version), e); } }
private void DisplayAssemblyInfo() { Assembly asmb = Assembly.GetExecutingAssembly(); AssemblyInformation info = new AssemblyInformation(asmb); txtOutput.Text = txtOutput.Text + System.Environment.NewLine + info.ToString(); }
private void EmitAssemblyWrapper(string wrapRoot, FrameworkName targetFramework, string assemblyPath, string projectName = null, bool isSubProcedure = false) { if (string.IsNullOrEmpty(projectName)) { projectName = Path.GetFileNameWithoutExtension(assemblyPath); } var targetProjectJson = Path.Combine(wrapRoot, projectName, Runtime.Project.ProjectFileName); var outputIndentation = string.Empty; if (isSubProcedure) { outputIndentation = " "; } Reports.Information.WriteLine("{0}Wrapping project '{1}' for '{2}'", outputIndentation, projectName, targetFramework); Reports.Information.WriteLine("{0} Source {1}", outputIndentation, assemblyPath.Bold()); Reports.Information.WriteLine("{0} Target {1}", outputIndentation, targetProjectJson.Bold()); // Add 'assembly' and 'pdb' to 'bin' section of the target framework var relativeAssemblyPath = PathUtility.GetRelativePath(targetProjectJson, assemblyPath, PathSeparator); var pdbPath = GetSideBySidePdbPath(assemblyPath); string relativePdbPath = null; if (!string.IsNullOrEmpty(pdbPath)) { relativePdbPath = PathUtility.GetRelativePath(targetProjectJson, pdbPath, PathSeparator); } var projectJson = LoadOrCreateProjectJson(targetProjectJson); AddFrameworkBinPaths(projectJson, targetFramework, relativeAssemblyPath, relativePdbPath); // Wrap dependency assemblies that are in the same dir var assemblyInfo = new AssemblyInformation(assemblyPath, processorArchitecture: null); // Key: dependency assembly file name. Value: original dependency name used by dependee. var dependencyOriginalName = assemblyInfo.GetDependencies() .ToDictionary(x => x + ".dll", x => x, StringComparer.OrdinalIgnoreCase); foreach (var filePath in Directory.EnumerateFiles(Path.GetDirectoryName(assemblyPath))) { var fileName = Path.GetFileName(filePath); if (dependencyOriginalName.ContainsKey(fileName)) { // Project dependency name should be case-sensitive, so here we // correct dependency project name by passing in project name with correct case EmitAssemblyWrapper(wrapRoot, targetFramework, filePath, projectName: dependencyOriginalName[fileName], isSubProcedure: isSubProcedure); AddProjectDependency(projectJson, projectName: dependencyOriginalName[fileName], targetFramework: targetFramework); } } PathUtility.EnsureParentDirectory(targetProjectJson); File.WriteAllText(targetProjectJson, projectJson.ToString()); }
private void UpdateI18NAssembly(AssemblyInformation asm, string appFolder) { List <string> supportedI18N = asmDAO.GetSupportedI18N(asm); foreach (var i18n in supportedI18N) { Directory.CreateDirectory(Path.Combine(appFolder, i18n)); string asmName = asm.Name + ".resources.dll"; try { byte[] asmBytes = asmDAO.GetI18NAssembly(asm, i18n); if (asmBytes != null) { File.WriteAllBytes(Path.Combine(appFolder, i18n, asmName), asmBytes); Logger.Info(String.Format(Messages.FileUpdated, asmName, asm.Version)); } else { Logger.Warn(String.Format(Messages.FileMissing, asmName, asm.Version)); } } catch (Exception e) { Logger.Error(String.Format(Messages.FileError, asmName, asm.Version), e); } } }
private IList <string> WalkAll(string rootPath) { var result = new HashSet <string>(); var stack = new Stack <string>(); stack.Push(rootPath); while (stack.Count > 0) { var path = stack.Pop(); if (!result.Add(Path.GetFileNameWithoutExtension(path))) { continue; } var assemblyInformation = new AssemblyInformation(path, null); foreach (var reference in assemblyInformation.GetDependencies()) { var newPath = Path.Combine(_assemblyFolder, reference + ".dll"); if (!File.Exists(newPath)) { continue; } stack.Push(newPath); } } return(result.ToList()); }
private AssemblyInformation GetNewAsm(string directory, string filename, string name, string type, out byte[] asmBytes) { string path = Path.Combine(directory, filename); List <byte> allBytes = new List <byte>(); byte[] fileByte; AssemblyInformation newAsm = new AssemblyInformation(); newAsm.Name = name; newAsm.FileName = filename; fileByte = File.ReadAllBytes(path); allBytes.AddRange(fileByte); string[] i18nDirectories = Directory.GetDirectories(directory); foreach (string i18nPath in i18nDirectories) { string i18n = Path.GetFileName(i18nPath); string resourceAsm = Path.Combine(directory, i18n, name + ".resources.dll"); if (i18nService.IsValidi18NCode(i18n) && File.Exists(resourceAsm)) { allBytes.AddRange(File.ReadAllBytes(resourceAsm)); } } asmBytes = allBytes.ToArray(); GetAssemblyInfoFromBin(fileByte, newAsm); newAsm.MD5 = MD5Sum(asmBytes); newAsm.Size = asmBytes.Length; newAsm.Date = DateTime.Now; newAsm.Type = type; return(newAsm); }
private void InsertAsmBin(AssemblyInformation asm, string asmHex) { string sql; int maxtext = 256000; int insertedText = 0; string insertSQL = this.GetSQL("InsertAsm.sql"); for (int i = 0; i < asmHex.Length / maxtext; i++) { string code = b1DAO.GetNextCode("DOVER_MODULES_BIN"); sql = String.Format(insertSQL, code, code, asm.Code, asmHex.Substring(i * maxtext, maxtext)); b1DAO.ExecuteStatement(sql); insertedText += maxtext; } if (insertedText < asmHex.Length) { string code = b1DAO.GetNextCode("DOVER_MODULES_BIN"); sql = String.Format(insertSQL, code, code, asm.Code, asmHex.Substring(insertedText)); b1DAO.ExecuteStatement(sql); } }
public static void EnhancePropertiesWithFile(this AssemblyInformation info) { if (info is null) { throw new System.ArgumentNullException(nameof(info)); } if (!info.IsLocalAssembly || !info.IsResolved) { return; } if (info.FilePath is null || !File.Exists(info.FilePath)) { return; } var fileInfo = new FileInfo(info.FilePath); info.CreationDate = fileInfo.CreationTime; var fileVersionInfo = FileVersionInfo.GetVersionInfo(info.FilePath); info.Creator = fileVersionInfo.CompanyName; if (string.IsNullOrEmpty(info.LoadedVersion)) { info.LoadedVersion = fileVersionInfo.ProductVersion; } if (info.IsDebug.HasValue) { info.IsDebug = fileVersionInfo.IsDebug; } }
public void Get_MetaData_Value_By_Key_That_Does_Not_Exist_Throws_KeyException() { var sut = new AssemblyInformation(AssemblyUnderTest.Instance); Action action = () => { var x = sut["abc"]; }; action.Should().Throw <KeyNotFoundException>(); }
private static (AssemblyInformation assembly, AssemblyDefinition?monoAssembly) CreateManagedAssemblyInformation(AssemblyNameReference assemblyName, string?baseDirectory, string extension = "dll") { var assemblyPath = FilePathProvider.GetAssemblyPath($"{assemblyName.Name}.{extension}", baseDirectory); AssemblyDefinition?assembly = null; try { using var resolver = new DefaultAssemblyResolver(); assembly = assemblyPath != null?AssemblyDefinition.ReadAssembly(assemblyPath) : resolver.Resolve(assemblyName); } catch { // do nothing, assembly is not found } var info = new AssemblyInformation(assemblyName.Name, assembly?.Name.Version.ToString() ?? assemblyName.Version.ToString(), assemblyPath) { IsLocalAssembly = assemblyPath != null || assembly == null, AssemblyName = assembly?.FullName ?? assemblyName.FullName, IsResolved = assembly != null, HasEntryPoint = assembly?.EntryPoint != null }; info.EnhancePropertiesWithFile(); info.EnhanceProperties(assembly); return(info, assembly); }
public void Create_AssemblyInformation_For_Entry_Assembly() { // test runner does not have an entry assembly Action action = () => AssemblyInformation.ForEntryAssembly(); action.Should().Throw <ArgumentNullException>(); }
public App() { AssemblyInfo = new AssemblyInformation(); // Configure log4net ConfigureLog4Net(); // Handle unhandled exceptions DispatcherUnhandledException += App_DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // Initialize Collection MangaCacheObjects = new ObservableCollection <MangaCacheObject>(); // Create a File System Watcher for Manga Objects MangaObjectArchiveWatcher = new FileSystemWatcher(CORE.MANGA_ARCHIVE_DIRECTORY, CORE.MANGA_ARCHIVE_FILTER); MangaObjectArchiveWatcher.EnableRaisingEvents = false; // Create a File System Watcher for Manga Chapter Objects ChapterObjectArchiveWatcher = new FileSystemWatcher(CORE.CHAPTER_ARCHIVE_DIRECTORY, CORE.CHAPTER_ARCHIVE_FILTER); ChapterObjectArchiveWatcher.IncludeSubdirectories = true; ChapterObjectArchiveWatcher.EnableRaisingEvents = false; // Load UserConfig LoadUserConfig(); SerializeType = CORE.UserConfiguration.SerializeType; // Initialize the ContentDownloadManager v2 ContentDownloadManager = new ContentDownloadManager(CORE: CORE); Startup += App_Startup; Exit += App_Exit; InitializeComponent(); }
protected internal virtual void InstallAddin(string name) { AssemblyInformation asmInfo = assemblyDAO.GetAssemblyInformation(name, "A"); assemblyManager.UpdateAppDataFolder(asmInfo, AppDomain.CurrentDomain.BaseDirectory); InstallAddin(asmInfo); }
public void IsWinMDFileCLROnlyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleClrOnly.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); }
public void IsWinMDFileRegularNetAssemblyFile() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\Framework\Whidbey\System.dll", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); }
public void IsWinMDFileFileDoesNotExistFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleDoesNotExist.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); }
public void IsWinMDFileEmptyFilePath() { string imageRuntime; bool isManagedWinMD; Assert.False(AssemblyInformation.IsWinMDFile(String.Empty, getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.False(isManagedWinMD); }
public void IsWinMDFileMixedFile() { string imageRuntime; bool isManagedWinMD; Assert.True(AssemblyInformation.IsWinMDFile(@"C:\WinMD\SampleWindowsRuntimeAndCLR.Winmd", getRuntimeVersion, fileExists, out imageRuntime, out isManagedWinMD)); Assert.True(isManagedWinMD); }
public AssemblyMetadata(string path) { using (var import = new AssemblyInformation(path)) { Dependencies = import.Dependencies; FrameworkName = import.FrameworkNameAttribute; ScatterFiles = NativeMethodsShared.IsWindows ? import.Files : null; } }
internal override byte[] GetAssembly(AssemblyInformation asm) { List<String> hexFile = b1DAO.ExecuteSqlForList<String>( String.Format(this.GetSQL("GetAssembly.sql"), asm.Code)); StringBuilder sb = new StringBuilder(); foreach (var hex in hexFile) { sb.Append(hex); } SoapHexBinary shb = SoapHexBinary.Parse(sb.ToString()); return Compression.Uncompress(shb.Value); }
private IEnumerable<string> GetAssemblyDependencies(string assemblyName) { var filepath = ResolveAssemblyFilePath(assemblyName); if (filepath != null && File.Exists(filepath)) { var assemblyInfo = new AssemblyInformation(filepath, processorArchitecture: null); return assemblyInfo.GetDependencies(); } else { return Enumerable.Empty<string>(); } }
internal override int GetDependencyCount(AssemblyInformation dep) { return b1DAO.ExecuteSqlForObject<int>(string.Format(this.GetSQL("GetDependencyCount.sql"), dep.Code)); }
internal override List<AssemblyInformation> GetDependencies(AssemblyInformation asm) { return b1DAO.ExecuteSqlForList<AssemblyInformation>(string.Format(this.GetSQL("GetDependencyInformation.sql"), asm.Code)); }
private AssemblyInformation GetAssemblyInformation(AssemblyName assemblyName) { Assembly asm = AppDomain.CurrentDomain.Load(assemblyName); if (!string.IsNullOrEmpty(asm.Location) && File.Exists(asm.Location) && Path.GetDirectoryName(asm.Location).StartsWith(Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory))) { byte[] depBytes = File.ReadAllBytes(asm.Location); AssemblyInformation dependencyInformation = new AssemblyInformation() { Name = assemblyName.Name, Description = assemblyName.Name, Date = DateTime.Today, Type = AssemblyType.Dependency, FileName = assemblyName.Name + ".dll", MD5 = FileUpdate.MD5Sum(depBytes) }; Assembly depAsm = AppDomain.CurrentDomain.Load(depBytes); SaveVersion(depAsm, dependencyInformation); dependencyInformation.Size = depBytes.Length; return dependencyInformation; } return null; }
private bool GenerateNativeImage(AssemblyInformation assemblyInfo) { var retCrossgen = false; if (assemblyInfo.Closure.Any(a => !a.Generated)) { Console.WriteLine("Skipping {0}. Because one or more dependencies failed to generate", assemblyInfo.Name); return false; } // Add the assembly itself to the closure var closure = assemblyInfo.Closure.Select(d => d.NativeImagePath) .Concat(new[] { assemblyInfo.AssemblyPath }); Console.WriteLine("Generating native images for {0}", assemblyInfo.Name); const string crossgenArgsTemplate = @"/Nologo /in ""{0}"" /out ""{1}"" /MissingDependenciesOK /Trusted_Platform_Assemblies ""{2}"""; // crossgen.exe /in {il-path}.dll /out {native-image-path} /MissingDependenciesOK /Trusted_Platform_Assemblies {closure} string args = null; // Treat mscorlib specially if (assemblyInfo.Name.Equals("mscorlib", StringComparison.OrdinalIgnoreCase)) { args = String.Format(crossgenArgsTemplate, assemblyInfo.AssemblyPath, assemblyInfo.NativeImagePath, assemblyInfo.AssemblyPath); } else { args = String.Format(crossgenArgsTemplate, assemblyInfo.AssemblyPath, assemblyInfo.NativeImagePath, String.Join(";", closure)); } // Make sure the target directory for the native image is there Directory.CreateDirectory(Path.GetDirectoryName(assemblyInfo.NativeImagePath)); retCrossgen = ExecuteCrossgen(_options.CrossgenPath, args, assemblyInfo.Name); if (retCrossgen) { assemblyInfo.Generated = true; } else { return false; } if (_options.Symbols) { Console.WriteLine("Generating native pdb for {0}", assemblyInfo.Name); const string crossgenArgsTemplateCreatePdb = @"/Nologo /CreatePDB ""{0}"" /in ""{1}"" /out ""{2}"" /Trusted_Platform_Assemblies ""{3}"""; // crossgen.exe /CreatePDB {native-pdb-directory} /in {native-image-path}.dll /out {native-pdb-path} /Trusted_Platform_Assemblies {closure} string argsPdb = null; // Treat mscorlib specially if (assemblyInfo.Name.Equals("mscorlib", StringComparison.OrdinalIgnoreCase)) { argsPdb = String.Format(crossgenArgsTemplateCreatePdb, assemblyInfo.NativeImageDirectory, assemblyInfo.NativeImagePath, assemblyInfo.NativePdbPath, assemblyInfo.AssemblyPath); } else { // Note: for CreatePDB need the native image (not the il image) // Add the assembly itself to the closure var closurePdb = assemblyInfo.Closure.Select(d => d.NativeImagePath) .Concat(new[] { assemblyInfo.NativeImagePath }); argsPdb = String.Format(crossgenArgsTemplateCreatePdb, assemblyInfo.NativeImageDirectory, assemblyInfo.NativeImagePath, assemblyInfo.NativePdbPath, String.Join(";", closurePdb)); } retCrossgen = ExecuteCrossgen(_options.CrossgenPath, argsPdb, assemblyInfo.Name); } return retCrossgen; }
private void UpdateFrameworkDBAssembly(ref AssemblyInformation asm) { const string defaultFrameworkDll = "Framework.dll"; if (asm == null) { AssemblyInformation newAsm = GetCurrentAsm(AppDomain.CurrentDomain.BaseDirectory, defaultFrameworkDll, AssemblyType.Core); AssemblyInformation savedAsm = SaveIfNotExistsOrDifferent(null, newAsm, AppDomain.CurrentDomain.BaseDirectory); asm = savedAsm; } else { if (asmDAO.AutoUpdateEnabled(asm)) { asm = UpdateModuleDBAssembly(asm, AssemblyType.Core); } } }
List<AssemblyInformation> ITempAssemblyLoader.GetAssemblyInfoFromBin(byte[] asmBytes, AssemblyInformation asmInfo) { Assembly asm = AppDomain.CurrentDomain.Load(asmBytes); asmInfo.Size = asmBytes.Length; SaveVersion(asm, asmInfo); SaveAddinAttribute(asm, asmInfo); List<AssemblyInformation> i18nDependencies = new List<AssemblyInformation>(); List<AssemblyInformation> dependencies = new List<AssemblyInformation>(); string[] defaultDependenciesNames = {"Castle.Core", "Castle.Facilities.Logging", "Castle.Services.Logging.Log4netIntegration", "Castle.Windsor", "ICSharpCode.SharpZipLib", "log4net", "SAPbouiCOM", "FrameworkInterface", "Interop.SAPbobsCOM"}; HashSet<string> defaultDependenciesNamesSet = new HashSet<string>(defaultDependenciesNames); foreach (var dependency in defaultDependenciesNames) { Assembly dependencyAsm = AppDomain.CurrentDomain.Load(dependency); CheckAssembly(dependencies, dependencyAsm.GetName()); } foreach (var dependency in asm.GetReferencedAssemblies()) { if (!defaultDependenciesNamesSet.Contains(dependency.Name)) CheckAssembly(dependencies, dependency); } string[] i18nDirectories = Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory); foreach (string i18nPath in i18nDirectories) { string i18n = Path.GetFileName(i18nPath); if (i18nService.IsValidi18NCode(i18n)) { CheckI18NAssembly(i18n, asm.GetName(), i18nDependencies); foreach (var dependencyInfo in dependencies) { var dependency = AppDomain.CurrentDomain.Load(dependencyInfo.Name); CheckI18NAssembly(i18n, dependency.GetName(), i18nDependencies); } } } dependencies.AddRange(i18nDependencies); return dependencies; }
internal override void SaveAssemblyDependency(AssemblyInformation newAsm, string dependencyCode) { string newCode = b1DAO.GetNextCode("DOVER_MODULES_DEP"); b1DAO.ExecuteStatement(string.Format(this.GetSQL("InsertDependency.sql"), newCode, newAsm.Code, dependencyCode)); }
private void ConfigureLog(AssemblyInformation addin) { using (var source = Assembly.GetExecutingAssembly().GetManifestResourceStream("Dover.Framework.DoverAddin.config")) { var destination = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "addIn", addin.Namespace, addin.Name, addin.Name + ".config"); if (source != null && !File.Exists(destination)) { var doc = XDocument.Load(source); var query = from c in doc.Elements("configuration").Elements("log4net") .Elements("appender").Elements("file") select c; foreach (var fileTag in query) { fileTag.Attribute("value").Value = addin.Name + ".log"; } doc.Save(destination); } } }
private void ConfigureAddin(AssemblyInformation addin, string baseDirectory) { Logger.Info(String.Format(Messages.ConfiguringAddin, addin)); var setup = new AppDomainSetup(); setup.ApplicationName = "Dover.ConfigureDomain"; setup.ApplicationBase = baseDirectory; AppDomain configureDomain = AppDomain.CreateDomain("ConfigureDomain", null, setup); try { IApplication app = (IApplication)configureDomain.CreateInstanceAndUnwrap("Framework", "Dover.Framework.Application"); SAPServiceFactory.PrepareForInception(configureDomain); IConfigAddin addinConfig = app.Resolve<IConfigAddin>(); addinConfig.ConfigureAddin(addin.Name); } finally { AppDomain.Unload(configureDomain); } }
private void InstallAddin(AssemblyInformation addin, string baseDirectory) { try { Logger.Info(string.Format(Messages.ConfiguringAddin, addin.Name)); ConfigureAddin(addin, baseDirectory); MarkAsInstalled(addin.Code); Logger.Info(string.Format(Messages.ConfiguredAddin, addin.Name)); } catch (Exception e) { MarkAsNotInstalled(addin.Code); throw e; } }
private void LoadAddin(AssemblyInformation addin) { DateTime dueDate; if (licenseManager.AddinIsValid(addin.Code, out dueDate)) { string directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "addIn", addin.Namespace, addin.Name); Directory.CreateDirectory(directory); fileUpdate.UpdateAppDataFolder(addin, directory); if (!IsInstalled(addin.Code)) { InstallAddin(addin, directory); } RegisterAddin(addin); ConfigureLog(addin); } else { Logger.Error(string.Format(Messages.NoLicenseError, addin.Name)); } }
private void RegisterAddin(AssemblyInformation addin) { AddInRunner runner = new AddInRunner(addin, this); var thread = new Thread(new ThreadStart(runner.Run)); thread.SetApartmentState(ApartmentState.STA); i18nService.ConfigureThreadI18n(thread); runner.runnerThread = thread; runner.runningAddins = runningAddIns; runner.runningAddinsHash = runningAddinsHash; thread.Start(); runner.bootEvent.WaitOne(); }
internal override void SaveAssembly(AssemblyInformation asm, byte[] asmBytes) { string installed = (asm.Type ==AssemblyType.Core) ? "Y" : "N"; SoapHexBinary shb = new SoapHexBinary(Compression.Compress(asmBytes)); string asmHex = null; if (asmBytes != null) asmHex = shb.ToString(); string sql; if (String.IsNullOrEmpty(asm.Code)) { asm.Code = b1DAO.GetNextCode("DOVER_MODULES"); sql = String.Format(this.GetSQL("SaveAssembly.sql"), asm.Code, asm.Code, asm.Name, asm.Description, asm.FileName, asm.Version, asm.MD5, asm.Date.ToString("yyyyMMdd"), asmBytes.Length, asm.TypeCode, installed, asm.Namespace); } else { sql = String.Format(this.GetSQL("UpdateAssembly.sql"), asm.Version, asm.MD5, asm.Date.ToString("yyyyMMdd"), asmBytes.Length, asm.Code, asm.Description, installed); b1DAO.ExecuteStatement(String.Format(this.GetSQL("DeleteAssembly.sql"), asm.Code)); b1DAO.ExecuteStatement(String.Format(this.GetSQL("DeleteDependencies.sql"), asm.Code)); } b1DAO.ExecuteStatement(sql); // Modules binaries if (asmBytes != null) InsertAsmBin(asm, asmHex); }
internal override bool AutoUpdateEnabled(AssemblyInformation asm) { string autoUpdateFlag = b1DAO.ExecuteSqlForObject<string>( string.Format(this.GetSQL("CheckAutoUpdate.sql"), asm.Code)); return !string.IsNullOrEmpty(autoUpdateFlag) && autoUpdateFlag == "Y"; }
internal override void SaveAssemblyDependency(AssemblyInformation newAsm, AssemblyInformation dependency, byte[] dependencyBytes) { dependency.Code = null; // force insert. SaveAssembly(dependency, dependencyBytes); SaveAssemblyDependency(newAsm, dependency.Code); }
internal AddInRunner(AssemblyInformation asm, IAddinManager frameworkAddinManager) { this.asm = asm; this.frameworkAddinManager = frameworkAddinManager; }
private void InsertAsmBin(AssemblyInformation asm, string asmHex) { string sql; int maxtext = 256000; int insertedText = 0; string insertSQL = this.GetSQL("InsertAsm.sql"); for (int i = 0; i < asmHex.Length / maxtext; i++) { string code = b1DAO.GetNextCode("DOVER_MODULES_BIN"); sql = String.Format(insertSQL, code, code, asm.Code, asmHex.Substring(i * maxtext, maxtext)); b1DAO.ExecuteStatement(sql); insertedText += maxtext; } if (insertedText < asmHex.Length) { string code = b1DAO.GetNextCode("DOVER_MODULES_BIN"); sql = String.Format(insertSQL, code, code, asm.Code, asmHex.Substring(insertedText)); b1DAO.ExecuteStatement(sql); } }
internal void UpdateAddinDueDate(AssemblyInformation asm) { if (asm.Type == AssemblyType.Core) { licenseDAO.UpdateAddinDueDate(asm.Code, DateTime.MaxValue); } else { DateTime dueDate; if (AddinIsValid(asm.Code, out dueDate)) { licenseDAO.UpdateAddinDueDate(asm.Code, dueDate); } } }
private IEnumerable<string> GetAssemblyDependencies(string assemblyName) { var filepath = ResolveAssemblyFilePath(assemblyName); if (filepath != null && File.Exists(filepath)) { var assemblyInfo = new AssemblyInformation(filepath, processorArchitecture: null); var dependencies = assemblyInfo.GetDependencies(); foreach (var dependency in dependencies) { AddDependencySource(_dependencyAssemblySources, dependency, assemblyName); } return dependencies; } else { return Enumerable.Empty<string>(); } }
private void EmitAssemblyWrapper(string wrapRoot, FrameworkName targetFramework, string assemblyPath, string projectName = null, bool isSubProcedure = false) { if (string.IsNullOrEmpty(projectName)) { projectName = Path.GetFileNameWithoutExtension(assemblyPath); } var targetProjectJson = Path.Combine(wrapRoot, projectName, Runtime.Project.ProjectFileName); var outputIndentation = string.Empty; if (isSubProcedure) { outputIndentation = " "; } Reports.Information.WriteLine("{0}Wrapping project '{1}' for '{2}'", outputIndentation, projectName, targetFramework); Reports.Information.WriteLine("{0} Source {1}", outputIndentation, assemblyPath.Bold()); Reports.Information.WriteLine("{0} Target {1}", outputIndentation, targetProjectJson.Bold()); // Add 'assembly' and 'pdb' to 'bin' section of the target framework var relativeAssemblyPath = PathUtility.GetRelativePath(targetProjectJson, assemblyPath, PathSeparator); var pdbPath = GetSideBySidePdbPath(assemblyPath); string relativePdbPath = null; if (!string.IsNullOrEmpty(pdbPath)) { relativePdbPath = PathUtility.GetRelativePath(targetProjectJson, pdbPath, PathSeparator); } var projectJson = LoadOrCreateProjectJson(targetProjectJson); AddFrameworkBinPaths(projectJson, targetFramework, relativeAssemblyPath, relativePdbPath); // Wrap dependency assemblies that are in the same dir var assemblyInfo = new AssemblyInformation(assemblyPath, processorArchitecture: null); // Key: dependency assembly file name. Value: original dependency name used by dependee. var dependencyOriginalName = assemblyInfo.GetDependencies() .ToDictionary(x => x + ".dll", x => x, StringComparer.OrdinalIgnoreCase); foreach (var filePath in Directory.EnumerateFiles(Path.GetDirectoryName(assemblyPath))) { var fileName = Path.GetFileName(filePath); if (dependencyOriginalName.ContainsKey(fileName)) { // Project dependency name should be case-sensitive, so here we // correct dependency project name by passing in project name with correct case EmitAssemblyWrapper(wrapRoot, targetFramework, filePath, projectName: dependencyOriginalName[fileName], isSubProcedure: isSubProcedure); AddProjectDependency(projectJson, projectName: dependencyOriginalName[fileName], targetFramework: targetFramework); } } PathUtility.EnsureParentDirectory(targetProjectJson); File.WriteAllText(targetProjectJson, projectJson.ToString()); }
private AssemblyInformation UpdateModuleDBAssembly(AssemblyInformation asm, AssemblyType assemblyType) { try { AssemblyInformation newAsm = GetCurrentAsm(AppDomain.CurrentDomain.BaseDirectory, asm.FileName, assemblyType); AssemblyInformation savedAsm = SaveIfNotExistsOrDifferent(asm, newAsm, AppDomain.CurrentDomain.BaseDirectory); Logger.Info(string.Format(Messages.FileUpdated, savedAsm.Name, savedAsm.Version)); return savedAsm; } catch (FileNotFoundException) { // Ignore it, use DB version. Logger.Warn(string.Format(Messages.FileMissing, asm.Name, "?")); return asm; } }
private IList<string> WalkAll(string rootPath) { var result = new HashSet<string>(); var stack = new Stack<string>(); stack.Push(rootPath); while (stack.Count > 0) { var path = stack.Pop(); if (!result.Add(Path.GetFileNameWithoutExtension(path))) { continue; } var assemblyInformation = new AssemblyInformation(path, null); foreach (var reference in assemblyInformation.GetDependencies()) { var newPath = Path.Combine(_assemblyFolder, reference + ".dll"); if (!File.Exists(newPath)) { continue; } stack.Push(newPath); } } return result.ToList(); }
public static string GetUserAgent() { AssemblyInformation inf = new AssemblyInformation(); string osVersion = DeviceInformationHelper.GetFirmwareVersion(); string deviceManufacturer = DeviceInformationHelper.GetDeviceManufacturer(); string deviceModel = DeviceInformationHelper.GetDeviceModel(); string userAgent = "NPOxUG/" + inf.Version.ToString() + " WindowsPhone/" + osVersion + " " + deviceManufacturer + "/" + deviceModel; return userAgent; }
private void Sort(AssemblyInformation node, List<AssemblyInformation> output, HashSet<AssemblyInformation> seen) { if (!seen.Add(node)) { return; } foreach (var dependency in node.GetDependencies()) { AssemblyInformation dependencyInfo; if (_universe.TryGetValue(dependency, out dependencyInfo)) { Sort(dependencyInfo, output, seen); } } if (!output.Contains(node)) { output.Add(node); } }
private void SaveVersion(Assembly asm, AssemblyInformation asmInfo) { var version = asm.GetName().Version; asmInfo.Major = version.Major; asmInfo.Minor = version.Minor; asmInfo.Build = version.Build; asmInfo.Revision = version.Revision; }
private void SaveAddinAttribute(Assembly asm, AssemblyInformation asmInfo) { Type addInAttributeType = asm.GetType("Dover.Framework.Attribute.AddInAttribute"); if (addInAttributeType == null) addInAttributeType = typeof(AddInAttribute); var types = (from type in asm.GetTypes() where type.IsClass select type); foreach (var type in types) { var attrs = type.GetCustomAttributes(addInAttributeType, true); if (attrs != null && attrs.Length > 0) { var attr = attrs[0]; dynamic addInAttribute = attr; if (!string.IsNullOrEmpty(addInAttribute.i18n)) { asmInfo.Description = i18nService.GetLocalizedString(addInAttribute.i18n, asm); } else { asmInfo.Description = addInAttribute.Description; } asmInfo.Name = addInAttribute.Name; asmInfo.Namespace = addInAttribute.Namespace; break; } } }
private AssemblyInformation SaveIfNotExistsOrDifferent(AssemblyInformation existingAsm, AssemblyInformation newAsm, string baseDirectory) { if (existingAsm != null) newAsm.Code = existingAsm.Code; // Prepare for update. if (existingAsm == null || newAsm.CompareTo(existingAsm) == 1 || (newAsm.Version == existingAsm.Version && newAsm.MD5 != existingAsm.MD5)) { byte[] asmBytes = File.ReadAllBytes(Path.Combine(baseDirectory, newAsm.FileName)); asmDAO.SaveAssembly(newAsm, asmBytes); // TODO: remove deleteDependencies from SaveAssembly do some sort of incremental SaveIfNotExists // Updating each assembly deparatly. Right now we just update everything if mainDll differs. foreach (var dependency in newAsm.Dependencies) { string dependencyCode = asmDAO.GetDependencyCode(dependency.MD5); if (string.IsNullOrEmpty(dependencyCode)) { asmBytes = File.ReadAllBytes(Path.Combine(baseDirectory, dependency.FileName)); asmDAO.SaveAssemblyDependency(newAsm, dependency, asmBytes); } else { asmDAO.SaveAssemblyDependency(newAsm, dependencyCode); } } asmDAO.DeleteOrphanDependency(); licenseManager.UpdateAddinDueDate(newAsm); return newAsm; } else { return existingAsm; } }
public static async Task CheckUpdate() { const string storeAppDetailsUri = "http://marketplaceedgeservice.windowsphone.com/v8/catalog/apps/b658425e-ba4c-4478-9af3-791fd0f1abfe?os={0}&cc={1}&lang={2}"; var updatedAvailable = false; try { var osVersion = "8.1"; var lang = CultureInfo.CurrentCulture.Name; var countryCode = lang.Length == 5 ? lang.Substring(3) : "US"; using (var message = new HttpRequestMessage(HttpMethod.Get, new Uri(string.Format(storeAppDetailsUri, osVersion, countryCode, lang)))) { message.Headers.UserAgent.ParseAdd("Windows Mobile 8.1"); using (var client = new HttpClient()) { var response = await client.SendRequestAsync(message); if (response.StatusCode != HttpStatusCode.Ok) return; var stream = await response.Content.ReadAsStringAsync(); XNamespace atom = "http://www.w3.org/2005/Atom"; XNamespace apps = "http://schemas.zune.net/catalog/apps/2008/02"; var doc = XDocument.Parse(stream); if (doc.Document == null) return; var entry = doc.Document.Descendants(atom + "feed") .Descendants(atom + "entry") .FirstOrDefault(); if (entry == null) return; var versionElement = entry.Elements(apps + "version").FirstOrDefault(); if (versionElement == null) return; Version storeVersion; if (Version.TryParse(versionElement.Value, out storeVersion)) { AssemblyInformation assembly = new AssemblyInformation(); var currentVersion = assembly.Version; updatedAvailable = storeVersion > currentVersion; } } } } catch (Exception ex) { // HANDLE ERROR HERE. THERE IS NO POINT IN SHOWING USER A MESSAGE. GOOD PLACE TO SEND SILENT ERROR REPORT OR JUST SWALLOW THE EXCEPTION. Debug.WriteLine(ex); } if (updatedAvailable) { await MessageBox.Show("Update beschikbaar", "Er is een nieuwe update beschikbaar in de Windows Phone Store."); } }