private void OnCheckerResourceCheckComplete(int removedCount, int updateCount, long updateTotalLength, long updateTotalZipLength) { m_VersionListProcessor.VersionListUpdateSuccess -= OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.VersionListUpdateFailure -= OnVersionListProcessorUpdateFailure; m_VersionListProcessor.Shutdown(); m_VersionListProcessor = null; m_UpdateVersionListCallbacks = null; m_ResourceChecker.ResourceNeedUpdate -= OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete -= OnCheckerResourceCheckComplete; m_ResourceChecker.Shutdown(); m_ResourceChecker = null; m_ResourceUpdater.CheckResourceComplete(removedCount > 0); if (updateCount <= 0) { m_ResourceUpdater.ResourceUpdateStart -= OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged -= OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess -= OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure -= OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdaterResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; m_UpdateFileCache = null; if (m_DecompressCache != null) { m_DecompressCache.Dispose(); m_DecompressCache = null; } } m_CheckResourcesCompleteCallback(updateCount > 0, removedCount, updateCount, updateTotalLength, updateTotalZipLength); m_CheckResourcesCompleteCallback = null; }
protected override void OnClick() { try { if (MessageBox.Show("Are you sure you want to update the RAVE AddIn resources?", "Update Resources", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { Cursor.Current = Cursors.WaitCursor; ResourceUpdater rru = new ResourceUpdater(Properties.Resources.ResourcesURL, Properties.Resources.BusinessLogicXMLFolder, Properties.Resources.AppDataSymbologyFolder); string appDataResources = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Properties.Resources.AppDataFolder); ResourceUpdater.UpdateResults results = rru.Update(appDataResources); Cursor.Current = Cursors.Default; MessageBox.Show(string.Format("The RAVE resources were updated successfully.\n{0} resource files were updated.", results.TotalDownloads), "Resources Updated", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { Cursor.Current = Cursors.Default; ErrorHandling.frmException.HandleException(ex, "Error Showing RAVE About Form", string.Empty); } ArcMap.Application.CurrentTool = null; }
/// <summary> /// 初始化资源管理器的新实例。 /// </summary> public ResourceManager() { m_AssetInfos = new Dictionary <string, AssetInfo>(); m_AssetDependencyInfos = new Dictionary <string, AssetDependencyInfo>(); m_ResourceInfos = new Dictionary <ResourceName, ResourceInfo>(); m_ResourceGroups = new Dictionary <string, ResourceGroup>(); m_ReadWriteResourceInfos = new SortedDictionary <ResourceName, ReadWriteResourceInfo>(new ResourceNameComparer()); m_ResourceIniter = null; m_VersionListProcessor = null; m_ResourceChecker = null; m_ResourceUpdater = null; m_ResourceLoader = new ResourceLoader(this); m_ResourceHelper = null; m_ReadOnlyPath = null; m_ReadWritePath = null; m_ResourceMode = ResourceMode.Unspecified; m_RefuseSetCurrentVariant = false; m_CurrentVariant = null; m_UpdatePrefixUri = null; m_ApplicableGameVersion = null; m_InternalResourceVersion = 0; m_DecryptResourceCallback = null; m_ResourceInitCompleteEventHandler = null; m_VersionListUpdateSuccessEventHandler = null; m_VersionListUpdateFailureEventHandler = null; m_ResourceCheckCompleteEventHandler = null; m_ResourceUpdateStartEventHandler = null; m_ResourceUpdateChangedEventHandler = null; m_ResourceUpdateSuccessEventHandler = null; m_ResourceUpdateFailureEventHandler = null; m_ResourceUpdateAllCompleteEventHandler = null; }
/// <summary> /// 初始化资源管理器的新实例。 /// </summary> public ResourceManager() { m_AssetInfos = null; m_ResourceInfos = null; m_ReadWriteResourceInfos = new SortedDictionary <ResourceName, ReadWriteResourceInfo>(new ResourceNameComparer()); m_CachedBytesForEncryptedString = new byte[byte.MaxValue]; m_ResourceIniter = null; m_VersionListProcessor = null; m_ResourceChecker = null; m_ResourceUpdater = null; m_ResourceLoader = new ResourceLoader(this); m_ResourceHelper = null; m_ReadOnlyPath = null; m_ReadWritePath = null; m_ResourceMode = ResourceMode.Unspecified; m_RefuseSetCurrentVariant = false; m_CurrentVariant = null; m_UpdatePrefixUri = null; m_ApplicableGameVersion = null; m_InternalResourceVersion = 0; m_UpdateFileCache = null; m_DecompressCache = null; m_DecryptResourceCallback = null; m_InitResourcesCompleteCallback = null; m_UpdateVersionListCallbacks = null; m_CheckResourcesCompleteCallback = null; m_UpdateResourcesCompleteCallback = null; m_ResourceUpdateStartEventHandler = null; m_ResourceUpdateChangedEventHandler = null; m_ResourceUpdateSuccessEventHandler = null; m_ResourceUpdateFailureEventHandler = null; }
internal override void Shutdown() { if (m_ResourceIniter != null) { m_ResourceIniter.Shutdown(); m_ResourceIniter = null; } m_VersionListProcessor.VersionListUpdateSuccess -= OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.Shutdown(); m_VersionListProcessor = null; m_ResourceChecker.ResourceNeedUpdate -= OnCheckerResourceNeedUpdate; m_resourceChecker.Shutdown(); m_ResourceChecker = null; m_ResourceUpdater.ResourceUpdateStart -= OnUpdateResourceUpdateStart; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdateResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; m_ResourceLoader.Shutdown(); m_ResourceLoader = null; m_AssetInfos.Clear(); m_AssetDependencyInfos.Clear(); m_ResourceInfos.Clear(); m_ReadWriteResourceInfos.Clear(); }
public void SetResourceMode(ResourceMode mode) { if (m_ResourceMode == m_ResourceMode.Unspecified) { m_ResourceMode = m_ResourceMode; if (m_ResourceMode == ResourceMode.Package) { m_ResourceIniter = new ResourceIniter(this); m_ResourceIniter.ResourceInitComplete += OnInitResourceInitComplete; } else if (m_ResourceMode == ResourceMode.Updatable) { m_VersionListProcessor = new VersionListProcessor(this); m_VersionListProcessor.VersionListUpdateSuccess += OnVersionListProcessorUpdateSuccess; m_ResourceChecker = new ResourceChecker(this); m_ResourceChecker.ResourceNeedUpdate += OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete += OnCheckResourceCheckComplete; m_ResourceUpdater = new ResourceUpdater(this); m_ResourceUpdater.ResourceUpdateStart += OnUpdateResourceUpdateStart; m_ResourceUpdater.ResourceUpdateSuccess += OnUpdateResourceUpdateSuccess; } } }
private void OnCheckerResourceCheckComplete(int removedCount, int updateCount, int updateTotalLength, int updateTotalZipLength) { m_VersionListProcessor.VersionListUpdateSuccess -= OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.VersionListUpdateFailure -= OnVersionListProcessorUpdateFailure; m_VersionListProcessor.Shutdown(); m_VersionListProcessor = null; m_ResourceChecker.ResourceNeedUpdate -= OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete -= OnCheckerResourceCheckComplete; m_ResourceChecker.Shutdown(); m_ResourceChecker = null; m_ResourceUpdater.CheckResourceComplete(removedCount > 0); if (updateCount <= 0) { m_ResourceUpdater.ResourceUpdateStart -= OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged -= OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess -= OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure -= OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdaterResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; } if (m_ResourceCheckCompleteEventHandler != null) { m_ResourceCheckCompleteEventHandler(this, new ResourceCheckCompleteEventArgs(removedCount, updateCount, updateTotalLength, updateTotalZipLength)); } }
/// <summary> /// Create a ComHost with an embedded CLSIDMap file to map CLSIDs to .NET Classes. /// </summary> /// <param name="comHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="comHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="clsidmapFilePath">The path to the *.clsidmap file.</param> public static void Create( string comHostSourceFilePath, string comHostDestinationFilePath, string clsidmapFilePath) { var destinationDirectory = new FileInfo(comHostDestinationFilePath).Directory.FullName; if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Copy apphost to destination path so it inherits the same attributes/permissions. File.Copy(comHostSourceFilePath, comHostDestinationFilePath, overwrite: true); if (!ResourceUpdater.IsSupportedOS()) { throw new ComHostCustomizationUnsupportedOSException(); } string clsidMap = File.ReadAllText(clsidmapFilePath); byte[] clsidMapBytes = Encoding.UTF8.GetBytes(clsidMap); using (ResourceUpdater updater = new ResourceUpdater(comHostDestinationFilePath)) { updater.AddResource(clsidMapBytes, (IntPtr)ClsidmapResourceType, (IntPtr)ClsidmapResourceId); updater.Update(); } }
public static void Main(string[] args) { try { if (args.Length != 3) { Console.Error.WriteLine("Wrong parameter count specified!"); Console.Error.WriteLine("Usage: ResourcePatcher.exe <APPHOST.exe> <ASSEMBLY.dll> <IS_WINEXE: 0 or 1>"); return; } var fnTarget = args[0]; var fnOrig = args[1]; var winExeBit = args[2]; if (!File.Exists(fnTarget) || !PEUtils.IsPEImage(fnTarget)) { Console.Error.WriteLine("Non-existant or invalid PE target file specified!"); return; } if (!File.Exists(fnOrig) || !PEUtils.IsPEImage(fnOrig)) { Console.Error.WriteLine("Non-existant or invalid PE source file specified!"); return; } if (winExeBit.Trim() == "1") { Console.Write("Setting Windows GUI bit... "); try { PEUtils.SetWindowsGraphicalUserInterfaceBit(fnTarget); Console.WriteLine("Done!"); } catch (AppHostNotCUIException) { Console.Write("Already has bit set!"); } } else { Console.WriteLine("Skipped setting WinExe bit..."); } Console.Write("Writing resources... "); using (var ru = new ResourceUpdater(fnTarget)) { ru.AddResourcesFromPEImage(fnOrig); ru.Update(); } Console.WriteLine("Done!"); } catch (Exception ex) { Console.WriteLine("Unhandles exception: " + ex.Message); Environment.Exit(1); } }
/// <summary> /// Create an AppHost with embedded configuration of app binary location /// </summary> /// <param name="appHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="appHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="appBinaryFilePath">Full path to app binary or relative path to the result apphost file</param> /// <param name="windowsGraphicalUserInterface">Specify whether to set the subsystem to GUI. Only valid for PE apphosts.</param> /// <param name="assemblyToCopyResorcesFrom">Path to the intermediate assembly, used for copying resources to PE apphosts.</param> public static void CreateAppHost( string appHostSourceFilePath, string appHostDestinationFilePath, string appBinaryFilePath, bool windowsGraphicalUserInterface = false, string assemblyToCopyResorcesFrom = null) { var bytesToWrite = Encoding.UTF8.GetBytes(appBinaryFilePath); if (bytesToWrite.Length > 1024) { throw new AppNameTooLongException(appBinaryFilePath); } CopyAppHost(appHostSourceFilePath, appHostDestinationFilePath); // Re-write the destination apphost with the proper contents. bool appHostIsPEImage = false; using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostDestinationFilePath)) { using (MemoryMappedViewAccessor accessor = memoryMappedFile.CreateViewAccessor()) { BinaryUtils.SearchAndReplace(accessor, AppBinaryPathPlaceholderSearchValue, bytesToWrite); appHostIsPEImage = BinaryUtils.IsPEImage(accessor); if (windowsGraphicalUserInterface) { if (!appHostIsPEImage) { throw new AppHostNotPEFileException(); } BinaryUtils.SetWindowsGraphicalUserInterfaceBit(accessor); } } } if (assemblyToCopyResorcesFrom != null && appHostIsPEImage) { if (ResourceUpdater.IsSupportedOS()) { // Copy resources from managed dll to the apphost new ResourceUpdater(appHostDestinationFilePath) .AddResourcesFromPEImage(assemblyToCopyResorcesFrom) .Update(); } else { throw new AppHostCustomizationUnsupportedOSException(); } } // Memory-mapped write does not updating last write time File.SetLastWriteTimeUtc(appHostDestinationFilePath, DateTime.UtcNow); }
/// <summary> /// Create a ComHost with an embedded CLSIDMap file to map CLSIDs to .NET Classes. /// </summary> /// <param name="comHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="comHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="clsidmapFilePath">The path to the *.clsidmap file.</param> /// <param name="typeLibraries">Resource ids for tlbs and paths to the tlb files to be embedded.</param> public static void Create( string comHostSourceFilePath, string comHostDestinationFilePath, string clsidmapFilePath, IReadOnlyDictionary <int, string> typeLibraries = null) { var destinationDirectory = new FileInfo(comHostDestinationFilePath).Directory.FullName; if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } // Copy apphost to destination path so it inherits the same attributes/permissions. File.Copy(comHostSourceFilePath, comHostDestinationFilePath, overwrite: true); if (!ResourceUpdater.IsSupportedOS()) { throw new ComHostCustomizationUnsupportedOSException(); } string clsidMap = File.ReadAllText(clsidmapFilePath); byte[] clsidMapBytes = Encoding.UTF8.GetBytes(clsidMap); using (ResourceUpdater updater = new ResourceUpdater(comHostDestinationFilePath)) { updater.AddResource(clsidMapBytes, (IntPtr)ClsidmapResourceType, (IntPtr)ClsidmapResourceId); if (typeLibraries is not null) { foreach (var typeLibrary in typeLibraries) { if (!ResourceUpdater.IsIntResource((IntPtr)typeLibrary.Key)) { throw new InvalidTypeLibraryIdException(typeLibrary.Value, typeLibrary.Key); } try { byte[] tlbFileBytes = File.ReadAllBytes(typeLibrary.Value); updater.AddResource(tlbFileBytes, "typelib", (IntPtr)typeLibrary.Key); } catch (FileNotFoundException ex) { throw new TypeLibraryDoesNotExistException(typeLibrary.Value, ex); } catch (HResultException hr) when(hr.Win32HResult == E_INVALIDARG) { throw new InvalidTypeLibraryException(typeLibrary.Value, hr); } } } updater.Update(); } }
private void OnUpdaterResourceUpdateAllComplete() { m_ResourceUpdater.ResourceUpdateStart -= OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged -= OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess -= OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure -= OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdaterResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; m_ResourceUpdateAllCompleteEventHandler?.Invoke(this, new ResourceUpdateAllCompleteEventArgs()); }
public override async Task <bool> Process(Resource resource) { // write the RPF if (!Directory.Exists("cache/http-files/")) { Directory.CreateDirectory("cache/http-files"); } var rpfName = GetRpfNameFor(resource); try { // create new RPF var rpf = new Formats.RPFFile(); // add required files var requiredFiles = GetRequiredFilesFor(resource); requiredFiles.Where(a => File.Exists(Path.Combine(resource.Path, a))).ToList().ForEach(a => rpf.AddFile(a, File.ReadAllBytes(Path.Combine(resource.Path, a)))); // add external files resource.ExternalFiles.ToList().ForEach(a => rpf.AddFile(a.Key, File.ReadAllBytes(a.Value.FullName))); // and write the RPF rpf.Write(rpfName); // set the hash of the client package for clients to fetch var hash = Utils.GetFileSHA1String(rpfName); resource.ClientPackageHash = hash; // synchronize the files with a download server if (resource.DownloadConfiguration != null && !string.IsNullOrWhiteSpace(resource.DownloadConfiguration.UploadURL)) { var updater = new ResourceUpdater(resource, resource.DownloadConfiguration); resource.IsSynchronizing = true; await updater.SyncResource(); resource.IsSynchronizing = false; } return(true); } catch (Exception e) { this.Log().Error(() => "Error updating client cache file: " + e.Message, e); } return(false); }
static void Main(string[] args) { //string path = Assembly.GetExecutingAssembly().FullName; //string path = @"D:\_clickonce\binaries\Launcher.modified.exe"; string path = @"C:\Users\nikolam\source\repos\PEResources\Launcher\bin\Debug\Launcher.exe"; // first, try to write it ResourceUpdater updater = new ResourceUpdater(); updater.AddStringResource(NativeMethods.CUSTOM_RESOURCE_TYPE, NativeMethods.BINARYTOLAUNCH_STRING, "1235.dll"); updater.UpdateResources(path); // now try to read it //string a = ResourceReader.GetBinaryToLaunch(path); }
public BuildResults Build(string filename, string outputPath) { string launcherFilename = Path.GetFileName(LauncherPath); _results = new BuildResults(); try { if (filename == null) { _results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Error, "GenerateLauncher.InvalidInput")); return(_results); } if (String.IsNullOrEmpty(outputPath)) { _results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Error, "GenerateLauncher.NoOutputPath")); return(_results); } // Copy setup.bin to the output directory string strOutputExe = System.IO.Path.Combine(outputPath, launcherFilename); if (!CopyLauncherToOutputDirectory(strOutputExe)) { // Appropriate messages should have been stuffed into the results already return(_results); } var resourceUpdater = new ResourceUpdater(); resourceUpdater.AddStringResource(LAUNCHER_RESOURCE_TABLE, LAUNCHER_RESOURCENAME, filename); if (!resourceUpdater.UpdateResources(strOutputExe, _results)) { return(_results); } _results.SetKeyFile(launcherFilename); _results.BuildSucceeded(); } catch (Exception ex) { _results.AddMessage(BuildMessage.CreateMessage(BuildMessageSeverity.Error, "GenerateLauncher.General", ex.Message)); } return(_results); }
private void OnUpdaterResourceUpdateAllComplete() { m_ResourceUpdater.ResourceUpdateStart -= OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged -= OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess -= OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure -= OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdaterResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; m_UpdateFileCache = null; if (m_DecompressCache != null) { m_DecompressCache.Dispose(); m_DecompressCache = null; } m_UpdateResourcesCompleteCallback(); m_UpdateResourcesCompleteCallback = null; }
public void CreateApphostShellShim(FilePath entryPoint, FilePath shimPath) { string appHostSourcePath; if (OperatingSystem.IsWindows()) { appHostSourcePath = Path.Combine(_appHostSourceDirectory, ApphostNameWithoutExtension + ".exe"); } else { appHostSourcePath = Path.Combine(_appHostSourceDirectory, ApphostNameWithoutExtension); } var appHostDestinationFilePath = Path.GetFullPath(shimPath.Value); string entryPointFullPath = Path.GetFullPath(entryPoint.Value); var appBinaryFilePath = Path.GetRelativePath(Path.GetDirectoryName(appHostDestinationFilePath), entryPointFullPath); if (ResourceUpdater.IsSupportedOS()) { var windowsGraphicalUserInterfaceBit = PEUtils.GetWindowsGraphicalUserInterfaceBit(entryPointFullPath); HostWriter.CreateAppHost(appHostSourceFilePath: appHostSourcePath, appHostDestinationFilePath: appHostDestinationFilePath, appBinaryFilePath: appBinaryFilePath, windowsGraphicalUserInterface: (windowsGraphicalUserInterfaceBit == WindowsGUISubsystem), assemblyToCopyResorcesFrom: entryPointFullPath); } else { // by passing null to assemblyToCopyResorcesFrom, it will skip copying resources, // which is only supported on Windows HostWriter.CreateAppHost(appHostSourceFilePath: appHostSourcePath, appHostDestinationFilePath: appHostDestinationFilePath, appBinaryFilePath: appBinaryFilePath, windowsGraphicalUserInterface: false, assemblyToCopyResorcesFrom: null, enableMacOSCodeSign: OperatingSystem.IsMacOS()); } _filePermissionSetter.SetUserExecutionPermission(appHostDestinationFilePath); }
public void UpdateWorkResourceMetadata() { var ru = new ResourceUpdater(pwaUri) { // TODO: get firewall opened to Hyper-V server client. //OrgConnStr = "Data Source=db-dev.cts.wa.gov;Initial Catalog=Organization;Integrated Security=True", //OrgNavConnStr = "Data Source=db-dev.cts.wa.gov;Initial Catalog=OrganizationNavigator;Integrated Security=True" OrgConnStr = "Data Source=ctsl7f303059.dis.wa.lcl;Initial Catalog=Organization;Integrated Security=True", OrgNavConnStr = "Data Source=ctsl7f303059.dis.wa.lcl;Initial Catalog=OrganizationNavigator;Integrated Security=True" }; l.WriteEntry("instantiated ResourceUpdater."); try { ru.UpdateWorkResources(); l.WriteEntry("ResourceUpdater.UpdateWorkResources succeeded!"); } catch (Exception xcp) { l.WriteEntry("ResourceUpdater.UpdateWorkResources failed! " + xcp.InnerException.GetType().ToString() + ":" + xcp.Message); } }
/// <summary> /// 设置资源模式。 /// </summary> /// <param name="resourceMode">资源模式。</param> public void SetResourceMode(ResourceMode resourceMode) { if (resourceMode == ResourceMode.Unspecified) { throw new AshException("Resource mode is invalid."); } if (m_ResourceMode == ResourceMode.Unspecified) { m_ResourceMode = resourceMode; if (m_ResourceMode == ResourceMode.Package) { m_ResourceIniter = new ResourceIniter(this); m_ResourceIniter.ResourceInitComplete += OnIniterResourceInitComplete; } else if (m_ResourceMode == ResourceMode.Updatable) { m_VersionListProcessor = new VersionListProcessor(this); m_VersionListProcessor.VersionListUpdateSuccess += OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.VersionListUpdateFailure += OnVersionListProcessorUpdateFailure; m_ResourceChecker = new ResourceChecker(this); m_ResourceChecker.ResourceNeedUpdate += OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete += OnCheckerResourceCheckComplete; m_ResourceUpdater = new ResourceUpdater(this); m_ResourceUpdater.ResourceUpdateStart += OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged += OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess += OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure += OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete += OnUpdaterResourceUpdateAllComplete; } } else if (m_ResourceMode != resourceMode) { throw new AshException("You can not change resource mode at this time."); } }
private void OnCheckerResourceCheckComplete(int removedCount, int updateCount) { m_VersionListProcessor.VersionListUpdateSuccess -= OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.Shutdown(); m_VersionListProcessor = null; m_ResourceChecker.ResourceNeedComplete -= OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete -= OnCheckerResourceCheckComplete; m_ResourceChecker.Shutdown(); m_ResourceChecker = null; m_ResourceUpdater.CheckResourceComplete(removedCount > 0); if (updateCount < 0) { m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdateResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; } m_ResourceCheckCompleteEventHandler(this, new ResourceCheckCompleteEventArgs(removedCount, updateCount)); }
public void ResourceUpdaterTest() { var r = new ResourceDictionary(); var mergedDictionaries = r.MergedDictionaries; var reader = new CacheableResourceReader <Theme>(); var updater = new ResourceUpdater <Theme>(reader, mergedDictionaries); Assert.AreEqual(0, mergedDictionaries.Count); // General to General (update, merge) updater.Update(_generalTheme, _generalTheme); Assert.AreEqual(1, mergedDictionaries.Count); // General to Solarized (update, merge, remove) updater.Update(_generalTheme, _solarizedTheme); Assert.AreEqual(1, mergedDictionaries.Count); Assert.AreEqual("Solarized theme", mergedDictionaries[0]["ThemeName"] as string); // Solarized to General2 (update, merge, remove) updater.Update(_solarizedTheme, _general2Theme); Assert.AreEqual(1, mergedDictionaries.Count); Assert.AreEqual("General2 theme", mergedDictionaries[0]["ThemeName"] as string); }
public override async Task<bool> Process(Resource resource) { // write the RPF if (!Directory.Exists("cache/http-files/")) { Directory.CreateDirectory("cache/http-files"); } var rpfName = GetRpfNameFor(resource); try { // create new RPF var rpf = new Formats.RPFFile(); // add required files var requiredFiles = GetRequiredFilesFor(resource); requiredFiles.Where(a => File.Exists(Path.Combine(resource.Path, a))).ToList().ForEach(a => rpf.AddFile(a, File.ReadAllBytes(Path.Combine(resource.Path, a)))); // add external files resource.ExternalFiles.ToList().ForEach(a => rpf.AddFile(a.Key, File.ReadAllBytes(a.Value.FullName))); // and write the RPF rpf.Write(rpfName); // set the hash of the client package for clients to fetch var hash = Utils.GetFileSHA1String(rpfName); resource.ClientPackageHash = hash; // synchronize the files with a download server if (resource.DownloadConfiguration != null && !string.IsNullOrWhiteSpace(resource.DownloadConfiguration.UploadURL)) { var updater = new ResourceUpdater(resource, resource.DownloadConfiguration); resource.IsSynchronizing = true; await updater.SyncResource(); resource.IsSynchronizing = false; } return true; } catch (Exception e) { this.Log().Error(() => "Error updating client cache file: " + e.Message, e); } return false; }
/// <summary> /// 关闭并清理资源管理器。 /// </summary> internal override void Shutdown() { if (m_ResourceIniter != null) { m_ResourceIniter.Shutdown(); m_ResourceIniter = null; } if (m_VersionListProcessor != null) { m_VersionListProcessor.VersionListUpdateSuccess -= OnVersionListProcessorUpdateSuccess; m_VersionListProcessor.VersionListUpdateFailure -= OnVersionListProcessorUpdateFailure; m_VersionListProcessor.Shutdown(); m_VersionListProcessor = null; } if (m_ResourceChecker != null) { m_ResourceChecker.ResourceNeedUpdate -= OnCheckerResourceNeedUpdate; m_ResourceChecker.ResourceCheckComplete -= OnCheckerResourceCheckComplete; m_ResourceChecker.Shutdown(); m_ResourceChecker = null; } if (m_ResourceUpdater != null) { m_ResourceUpdater.ResourceUpdateStart -= OnUpdaterResourceUpdateStart; m_ResourceUpdater.ResourceUpdateChanged -= OnUpdaterResourceUpdateChanged; m_ResourceUpdater.ResourceUpdateSuccess -= OnUpdaterResourceUpdateSuccess; m_ResourceUpdater.ResourceUpdateFailure -= OnUpdaterResourceUpdateFailure; m_ResourceUpdater.ResourceUpdateAllComplete -= OnUpdaterResourceUpdateAllComplete; m_ResourceUpdater.Shutdown(); m_ResourceUpdater = null; m_UpdateFileCache = null; if (m_DecompressCache != null) { m_DecompressCache.Dispose(); m_DecompressCache = null; } } if (m_ResourceLoader != null) { m_ResourceLoader.Shutdown(); m_ResourceLoader = null; } if (m_AssetInfos != null) { m_AssetInfos.Clear(); m_AssetInfos = null; } if (m_ResourceInfos != null) { m_ResourceInfos.Clear(); m_ResourceInfos = null; } m_ReadWriteResourceInfos.Clear(); }
/// <summary> /// Create an AppHost with embedded configuration of app binary location /// </summary> /// <param name="appHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="appHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="appBinaryFilePath">Full path to app binary or relative path to the result apphost file</param> /// <param name="windowsGraphicalUserInterface">Specify whether to set the subsystem to GUI. Only valid for PE apphosts.</param> /// <param name="assemblyToCopyResorcesFrom">Path to the intermediate assembly, used for copying resources to PE apphosts.</param> public static void CreateAppHost( string appHostSourceFilePath, string appHostDestinationFilePath, string appBinaryFilePath, bool windowsGraphicalUserInterface = false, string assemblyToCopyResorcesFrom = null) { var bytesToWrite = Encoding.UTF8.GetBytes(appBinaryFilePath); if (bytesToWrite.Length > 1024) { throw new AppNameTooLongException(appBinaryFilePath); } bool appHostIsPEImage = false; void RewriteAppHost(MemoryMappedViewAccessor accessor) { // Re-write the destination apphost with the proper contents. BinaryUtils.SearchAndReplace(accessor, AppBinaryPathPlaceholderSearchValue, bytesToWrite); appHostIsPEImage = PEUtils.IsPEImage(accessor); if (windowsGraphicalUserInterface) { if (!appHostIsPEImage) { throw new AppHostNotPEFileException(); } PEUtils.SetWindowsGraphicalUserInterfaceBit(accessor); } } void UpdateResources() { if (assemblyToCopyResorcesFrom != null && appHostIsPEImage) { if (ResourceUpdater.IsSupportedOS()) { // Copy resources from managed dll to the apphost new ResourceUpdater(appHostDestinationFilePath) .AddResourcesFromPEImage(assemblyToCopyResorcesFrom) .Update(); } else { throw new AppHostCustomizationUnsupportedOSException(); } } } try { RetryUtil.RetryOnIOError(() => { FileStream appHostSourceStream = null; MemoryMappedFile memoryMappedFile = null; MemoryMappedViewAccessor memoryMappedViewAccessor = null; try { // Open the source host file. appHostSourceStream = new FileStream(appHostSourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read); memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostSourceStream, null, 0, MemoryMappedFileAccess.Read, HandleInheritability.None, true); memoryMappedViewAccessor = memoryMappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.CopyOnWrite); // Get the size of the source app host to ensure that we don't write extra data to the destination. // On Windows, the size of the view accessor is rounded up to the next page boundary. long sourceAppHostLength = appHostSourceStream.Length; // Transform the host file in-memory. RewriteAppHost(memoryMappedViewAccessor); // Save the transformed host. using (FileStream fileStream = new FileStream(appHostDestinationFilePath, FileMode.Create)) { BinaryUtils.WriteToStream(memoryMappedViewAccessor, fileStream, sourceAppHostLength); // Remove the signature from MachO hosts. if (!appHostIsPEImage) { MachOUtils.RemoveSignature(fileStream); } } } finally { memoryMappedViewAccessor?.Dispose(); memoryMappedFile?.Dispose(); appHostSourceStream?.Dispose(); } }); RetryUtil.RetryOnWin32Error(UpdateResources); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var filePermissionOctal = Convert.ToInt32("755", 8); // -rwxr-xr-x const int EINTR = 4; int chmodReturnCode = 0; do { chmodReturnCode = chmod(appHostDestinationFilePath, filePermissionOctal); }while (chmodReturnCode == -1 && Marshal.GetLastWin32Error() == EINTR); if (chmodReturnCode == -1) { throw new Win32Exception(Marshal.GetLastWin32Error(), $"Could not set file permission {filePermissionOctal} for {appHostDestinationFilePath}."); } } } catch (Exception ex) { // Delete the destination file so we don't leave an unmodified apphost try { File.Delete(appHostDestinationFilePath); } catch (Exception failedToDeleteEx) { throw new AggregateException(ex, failedToDeleteEx); } throw; } }
/// <summary> /// Create an AppHost with embedded configuration of app binary location /// </summary> /// <param name="appHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="appHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="appBinaryFilePath">Full path to app binary or relative path to the result apphost file</param> /// <param name="windowsGraphicalUserInterface">Specify whether to set the subsystem to GUI. Only valid for PE apphosts.</param> /// <param name="assemblyToCopyResorcesFrom">Path to the intermediate assembly, used for copying resources to PE apphosts.</param> public static void CreateAppHost( string appHostSourceFilePath, string appHostDestinationFilePath, string appBinaryFilePath, bool windowsGraphicalUserInterface = false, string assemblyToCopyResorcesFrom = null) { var bytesToWrite = Encoding.UTF8.GetBytes(appBinaryFilePath); if (bytesToWrite.Length > 1024) { throw new AppNameTooLongException(appBinaryFilePath); } BinaryUtils.CopyFile(appHostSourceFilePath, appHostDestinationFilePath); bool appHostIsPEImage = false; void RewriteAppHost() { // Re-write the destination apphost with the proper contents. using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostDestinationFilePath)) { using (MemoryMappedViewAccessor accessor = memoryMappedFile.CreateViewAccessor()) { BinaryUtils.SearchAndReplace(accessor, AppBinaryPathPlaceholderSearchValue, bytesToWrite); appHostIsPEImage = BinaryUtils.IsPEImage(accessor); if (windowsGraphicalUserInterface) { if (!appHostIsPEImage) { throw new AppHostNotPEFileException(); } BinaryUtils.SetWindowsGraphicalUserInterfaceBit(accessor); } } } } void UpdateResources() { if (assemblyToCopyResorcesFrom != null && appHostIsPEImage) { if (ResourceUpdater.IsSupportedOS()) { // Copy resources from managed dll to the apphost new ResourceUpdater(appHostDestinationFilePath) .AddResourcesFromPEImage(assemblyToCopyResorcesFrom) .Update(); } else { throw new AppHostCustomizationUnsupportedOSException(); } } } void RemoveSignatureIfMachO() { MachOUtils.RemoveSignature(appHostDestinationFilePath); } void SetLastWriteTime() { // Memory-mapped write does not updating last write time File.SetLastWriteTimeUtc(appHostDestinationFilePath, DateTime.UtcNow); } try { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var filePermissionOctal = Convert.ToInt32("755", 8); // -rwxr-xr-x const int EINTR = 4; int chmodReturnCode = 0; do { chmodReturnCode = chmod(appHostDestinationFilePath, filePermissionOctal); }while (chmodReturnCode == -1 && Marshal.GetLastWin32Error() == EINTR); if (chmodReturnCode == -1) { throw new Win32Exception(Marshal.GetLastWin32Error(), $"Could not set file permission {filePermissionOctal} for {appHostDestinationFilePath}."); } } RetryUtil.RetryOnIOError(RewriteAppHost); RetryUtil.RetryOnWin32Error(UpdateResources); RetryUtil.RetryOnIOError(RemoveSignatureIfMachO); RetryUtil.RetryOnIOError(SetLastWriteTime); } catch (Exception ex) { // Delete the destination file so we don't leave an unmodified apphost try { File.Delete(appHostDestinationFilePath); } catch (Exception failedToDeleteEx) { throw new AggregateException(ex, failedToDeleteEx); } throw; } }
/// <summary> /// Create an AppHost with embedded configuration of app binary location /// </summary> /// <param name="appHostSourceFilePath">The path of Apphost template, which has the place holder</param> /// <param name="appHostDestinationFilePath">The destination path for desired location to place, including the file name</param> /// <param name="appBinaryFilePath">Full path to app binary or relative path to the result apphost file</param> /// <param name="windowsGraphicalUserInterface">Specify whether to set the subsystem to GUI. Only valid for PE apphosts.</param> /// <param name="assemblyToCopyResorcesFrom">Path to the intermediate assembly, used for copying resources to PE apphosts.</param> public static void CreateAppHost( string appHostSourceFilePath, string appHostDestinationFilePath, string appBinaryFilePath, bool windowsGraphicalUserInterface = false, string assemblyToCopyResorcesFrom = null) { var bytesToWrite = Encoding.UTF8.GetBytes(appBinaryFilePath); if (bytesToWrite.Length > 1024) { throw new AppNameTooLongException(appBinaryFilePath); } BinaryUtils.CopyFile(appHostSourceFilePath, appHostDestinationFilePath); bool appHostIsPEImage = false; void RewriteAppHost() { // Re-write the destination apphost with the proper contents. using (var memoryMappedFile = MemoryMappedFile.CreateFromFile(appHostDestinationFilePath)) { using (MemoryMappedViewAccessor accessor = memoryMappedFile.CreateViewAccessor()) { BinaryUtils.SearchAndReplace(accessor, AppBinaryPathPlaceholderSearchValue, bytesToWrite); appHostIsPEImage = BinaryUtils.IsPEImage(accessor); if (windowsGraphicalUserInterface) { if (!appHostIsPEImage) { throw new AppHostNotPEFileException(); } BinaryUtils.SetWindowsGraphicalUserInterfaceBit(accessor); } } } } void UpdateResources() { if (assemblyToCopyResorcesFrom != null && appHostIsPEImage) { if (ResourceUpdater.IsSupportedOS()) { // Copy resources from managed dll to the apphost new ResourceUpdater(appHostDestinationFilePath) .AddResourcesFromPEImage(assemblyToCopyResorcesFrom) .Update(); } else { throw new AppHostCustomizationUnsupportedOSException(); } } } try { RetryUtil.RetryOnIOError(RewriteAppHost); RetryUtil.RetryOnWin32Error(UpdateResources); // Memory-mapped write does not updating last write time RetryUtil.RetryOnIOError(() => File.SetLastWriteTimeUtc(appHostDestinationFilePath, DateTime.UtcNow)); } catch (Exception ex) { // Delete the destination file so we don't leave an unmodified apphost try { File.Delete(appHostDestinationFilePath); } catch (Exception failedToDeleteEx) { throw new AggregateException(ex, failedToDeleteEx); } throw; } }