public static void CreateISOMedia( string ISOPath, string UUPPath, string Edition, string LanguageCode, bool IntegrateUpdates, Common.CompressionType CompressionType, ProgressCallback progressCallback = null) { progressCallback?.Invoke(Common.ProcessPhase.ReadingMetadata, true, 0, "Enumerating files"); var temp = Path.GetTempFileName(); File.Delete(temp); Directory.CreateDirectory(temp); string WinREWIMFilePath = Path.Combine(temp, "Winre.wim"); string MediaRootPath = Path.Combine(temp, "MediaRoot"); string InstallWIMFilePath = CompressionType == Common.CompressionType.LZMS ? Path.Combine(MediaRootPath, "sources", "install.esd") : Path.Combine(MediaRootPath, "sources", "install.wim"); // // Build installer // bool result = SetupMediaCreator.CreateSetupMedia(UUPPath, LanguageCode, MediaRootPath, WinREWIMFilePath, CompressionType, progressCallback); if (!result) { goto error; } // // Build Install.WIM/ESD // result = BaseEditionBuilder.CreateBaseEdition(UUPPath, LanguageCode, Edition, WinREWIMFilePath, InstallWIMFilePath, CompressionType, progressCallback); if (!result) { goto error; } // // Build ISO // result = UUPMediaCreator.CreateISO(MediaRootPath, ISOPath, progressCallback); if (!result) { goto error; } progressCallback?.Invoke(Common.ProcessPhase.Done, true, 0, ""); goto exit; error: progressCallback?.Invoke(Common.ProcessPhase.Error, true, 0, ""); exit: return; }
public bool CaptureImage(string wimFile, string imageName, string imageDescription, string InputDirectory, CompressionType compressionType = CompressionType.LZX, AddFlags addFlags = AddFlags.DEFAULT, ProgressCallback progressCallback = null) { string title = $"Creating {wimFile.Split('\\').Last()}"; try { CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.SCAN_BEGIN: { ProgressInfo_Scan m = (ProgressInfo_Scan)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.SCAN_END: { ProgressInfo_Scan m = (ProgressInfo_Scan)info; progressCallback?.Invoke($"Scanning files ({m.NumBytesScanned} bytes scanned, Current directory: {m.CurPath})", 0, true); } break; case ProgressMsg.WRITE_METADATA_BEGIN: break; case ProgressMsg.WRITE_STREAMS: { ProgressInfo_WriteStreams m = (ProgressInfo_WriteStreams)info; progressCallback?.Invoke(title, (int)Math.Round((double)m.CompletedBytes / m.TotalBytes * 100), false); } break; case ProgressMsg.WRITE_METADATA_END: break; } return(CallbackStatus.CONTINUE); } using (Wim wim = Wim.CreateNewWim((ManagedWimLib.CompressionType)compressionType)) { wim.RegisterCallback(ProgressCallback); wim.AddImage(InputDirectory, imageName, null, (ManagedWimLib.AddFlags)addFlags); if (!string.IsNullOrEmpty(imageDescription)) { wim.SetImageDescription(1, imageDescription); } wim.Write(wimFile, Wim.AllImages, WriteFlags.DEFAULT, Wim.DefaultThreads); } } catch { return(false); } return(true); }
private static bool CreateSetupMediaRoot( string BaseESD, string OutputPath, ProgressCallback ProgressCallback = null ) { bool result = true; // // Verify that the folder exists, if it doesn't, simply create it // if (!Directory.Exists(OutputPath)) { Directory.CreateDirectory(OutputPath); } void callback(string Operation, int ProgressPercentage, bool IsIndeterminate) { ProgressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, IsIndeterminate, ProgressPercentage, Operation); } // // Apply the first index of the base ESD containing the setup files we need // result = imagingInterface.ApplyImage( BaseESD, 1, OutputPath, progressCallback: callback, PreserveACL: false); if (!result) { ProgressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, true, 0, "An error occured while applying the image for the setup files."); goto exit; } // // The setup files from the first index are missing a single component (wtf?) so extract it from index 3 and place it in sources // Note: the file in question isn't in a wim that needs to be referenced, so we don't need to mention reference images. // ProgressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, true, 0, "Extracting XML Lite"); result = imagingInterface.ExtractFileFromImage(BaseESD, 3, Path.Combine("Windows", "System32", "xmllite.dll"), Path.Combine(OutputPath, "sources", "xmllite.dll")); if (!result) { ProgressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, true, 0, "An error occured while extracting XML Lite."); goto exit; } exit: return(result); }
public static byte[] ReadBlock(this Stream source, int count, ProgressCallback callback, object userItem = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var buf = new byte[count]; var pos = 0; while (pos < count) { var size = source.Read(buf, pos, Math.Min(count - pos, blockSize)); if (size != count) { Array.Resize(ref buf, size); return(buf); } pos += size; if (callback != null) { var e = new ProgressEventArgs(userItem, pos, size, count, true); callback.Invoke(source, e); if (e.Break) { break; } } } return(buf); }
private static void PrintOrgs(WriteTo write, ProgressCallback progress = null) { using (var db = new TransportContext()) { var p = 0; var max = db.Areas.Count(); // для каждой зоны записываем свой блок в файл foreach (var area in db.Areas.Include(a => a.Buildings .Select(b => b.OrgFils .Select(of => of.Org) .Select(o => o.OrgRubs)))) { const int lineLenght = 60; PrintLine('*', lineLenght, write); var buildingsCount = area.Buildings.Count; var orgFilsCount = area.Buildings.SelectMany(b => b.OrgFils).Count(); write($"{area.AreaId}. {area.Name} " + Environment.NewLine + $"Зданий: {buildingsCount} Жителей: {area.People} Организаций: {orgFilsCount}" + Environment.NewLine); PrintLine('-', lineLenght, write); var n = 1; foreach (var orgFil in area.Buildings.SelectMany(b => b.OrgFils)) { write($"{n++}. {orgFil.Org.Name}" + Environment.NewLine); } write(Environment.NewLine); progress?.Invoke(++p, max); } write(Environment.NewLine); } }
internal static (bool Succeeded, string BaseESD) LocateFilesForSetupMediaCreation( string UUPPath, string LanguageCode, ProgressCallback?progressCallback = null) { progressCallback?.Invoke(Common.ProcessPhase.ReadingMetadata, true, 0, "Looking up Composition Database in order to find a Base ESD image appropriate for building windows setup files."); if (Planning.NET.FileLocator.GetCompDBsFromUUPFiles(UUPPath) is HashSet <CompDBXmlClass.CompDB> compDBs) { HashSet <CompDBXmlClass.CompDB> filteredCompDBs = compDBs.GetEditionCompDBsForLanguage(LanguageCode); if (filteredCompDBs.Count > 0) { foreach (var currentCompDB in filteredCompDBs) { foreach (CompDBXmlClass.Package feature in currentCompDB.Features.Feature[0].Packages.Package) { CompDBXmlClass.Package pkg = currentCompDB.Packages.Package.First(x => x.ID == feature.ID); string file = pkg.GetCommonlyUsedIncorrectFileName(); if (feature.PackageType == "MetadataESD") { if (!File.Exists(Path.Combine(UUPPath, file))) { file = pkg.Payload.PayloadItem.Path; if (!File.Exists(Path.Combine(UUPPath, file))) { break; } } return(true, Path.Combine(UUPPath, file)); } } } } progressCallback?.Invoke(Common.ProcessPhase.Error, true, 0, "While looking up the Composition Database, we couldn't find an edition composition for the specified language. This error is fatal."); return(false, null); } else { progressCallback?.Invoke(Common.ProcessPhase.Error, true, 0, "We couldn't find the Composition Database. Please make sure you have downloaded the <aggregatedmetadata> cabinet file, or the <CompDB> cabinet files (if the build is lower than RS3 RTM). This error is fatal."); return(false, null); } }
private static bool RunDismComponentRemovalOperation( string OSPath, ProgressCallback progressCallback = null ) { string parentDirectory = PathUtils.GetParentExecutableDirectory(); string toolpath = Path.Combine(parentDirectory, "UUPMediaConverterDismBroker", "UUPMediaConverterDismBroker.exe"); if (!File.Exists(toolpath)) { parentDirectory = PathUtils.GetExecutableDirectory(); toolpath = Path.Combine(parentDirectory, "UUPMediaConverterDismBroker", "UUPMediaConverterDismBroker.exe"); } if (!File.Exists(toolpath)) { parentDirectory = PathUtils.GetExecutableDirectory(); toolpath = Path.Combine(parentDirectory, "UUPMediaConverterDismBroker.exe"); } Process proc = new Process(); proc.StartInfo = new ProcessStartInfo("cmd.exe", $"/c \"\"{toolpath}\" /PECompUninst \"{OSPath}\"\""); proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.CreateNoWindow = true; proc.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { if (e.Data != null && e.Data.Contains(",")) { var percent = int.Parse(e.Data.Split(',')[0]); progressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, false, percent, e.Data.Split(',')[1]); } }; proc.Start(); proc.BeginOutputReadLine(); proc.WaitForExit(); if (proc.ExitCode != 0) { progressCallback?.Invoke(Common.ProcessPhase.CreatingWindowsInstaller, true, 0, "An error occured while running the external tool for component cleanup. Error code: " + proc.ExitCode); } return(proc.ExitCode == 0); }
public static long CopyBlocksTo(this Stream source, Stream target, long length = -1, ProgressCallback callback = null, object userItem = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (target == null) { throw new ArgumentNullException(nameof(target)); } long written = 0; if (length <= 0) { if (source.CanSeek) { length = source.Length - source.Position; } } if (length <= 0) { length = long.MaxValue; } var buffer = new byte[blockSize]; while (written < length) { var block = (int)Math.Min(buffer.Length, length - written); if (block == 0) { break; } var read = source.Read(buffer, 0, block); if (read <= 0) { break; } target.Write(buffer, 0, read); written += read; if (callback != null) { var e = new ProgressEventArgs(userItem, written, read, length, true); callback.Invoke(source, e); if (e.Break) { break; } } } return(written); }
/*public void ExpandFiles(string OutputPath, ProgressCallback progressCallback) * { * int buffersize = 0x20000; * * int fileCount = Files.Count(); * * int fileCounter = 0; * foreach (var file in Files) * { * int progressOffset = (int)Math.Round((double)fileCounter / fileCount * 100); * int progressScale = (int)Math.Round((double)1 / fileCount * 100); * * var filedirectoryonly = file.Contains("\\") ? string.Join("\\", file.Split('\\').Reverse().Skip(1).Reverse()) : ""; * var targetDirectory = Path.Combine(OutputPath, filedirectoryonly); * var targetFile = Path.Combine(OutputPath, file); * if (!Directory.Exists(targetDirectory)) * Directory.CreateDirectory(targetDirectory); * * using (var inStream = OpenFile(file)) * using (var outStream = File.Create(targetFile)) * { * byte[] buffer = new byte[buffersize]; * for (int i = 0; i < inStream.Length; i += buffersize) * { * int read = inStream.Read(buffer, 0, buffersize); * outStream.Write(buffer, 0, read); * progressCallback.Invoke(progressOffset + (int)Math.Round((double)i / inStream.Length * progressScale), file); * } * } * fileCounter++; * } * }*/ public static void ExpandFiles(string CabinetPath, string OutputPath, ProgressCallback progressCallback) { CabInfo info = new CabInfo(CabinetPath); info.Unpack(OutputPath, (a, b) => { progressCallback.Invoke((int)Math.Round((double)b.CurrentArchiveBytesProcessed / b.CurrentArchiveTotalBytes * 100), b.CurrentFileName); }); }
//Кодує файли, перед викликом не забути присвоїти потрібний IV public void WriteEncrypt(long streamOffset, Stream inputStream, AesCryptoServiceProvider AES, out byte[] Hash, ProgressCallback Progress) { lock (_WriteLock) { if (streamOffset > _stream.Length) { throw new Exception(""); } if (AES.Padding == PaddingMode.None) { _Length = streamOffset + inputStream.Length - inputStream.Position; //Якщо файл кодується з доповненням, то тут може бути менше значення чим потрібно. } else { _Length = streamOffset + (long)Crypto.GetMod16((UInt64)(inputStream.Length - inputStream.Position)); } byte[] buffer = new byte[1048576]; CryptoStream cs = new CryptoStream(_stream, AES.CreateEncryptor(), CryptoStreamMode.Write); MD5 md5 = MD5.Create(); long position = streamOffset; while (inputStream.Position < inputStream.Length) { int count = inputStream.Read(buffer, 0, buffer.Length); lock (_ReadWriteLock) { _stream.Position = position; cs.Write(buffer, 0, count); position = _stream.Position; } if (inputStream.Position < inputStream.Length) { md5.TransformBlock(buffer, 0, count, buffer, 0); } else { md5.TransformFinalBlock(buffer, 0, count); } Progress?.Invoke(inputStream.Position / (double)inputStream.Length * 100.0); } lock (_ReadWriteLock) { _stream.Position = position; cs.FlushFinalBlock(); } Hash = md5.Hash; } }
private static string ConvertCABToESD(string cabFilePath, ProgressCallback progressCallback, int progressoffset, int progressscale) { string esdFilePath = Path.ChangeExtension(cabFilePath, "esd"); if (File.Exists(esdFilePath)) { return(esdFilePath); } progressCallback?.Invoke(Common.ProcessPhase.PreparingFiles, false, progressoffset, "Unpacking..."); var tmp = Path.GetTempFileName(); File.Delete(tmp); string tempExtractionPath = Path.Combine(tmp, "Package"); int progressScaleHalf = progressscale / 2; void ProgressCallback(int percent, string file) { progressCallback?.Invoke(Common.ProcessPhase.PreparingFiles, false, progressoffset + (int)Math.Round((double)percent / 100 * progressScaleHalf), "Unpacking " + file + "..."); }; CabinetHandler.ExpandFiles(cabFilePath, tempExtractionPath, ProgressCallback); void callback(string Operation, int ProgressPercentage, bool IsIndeterminate) { progressCallback?.Invoke(Common.ProcessPhase.PreparingFiles, IsIndeterminate, progressoffset + progressScaleHalf + (int)Math.Round((double)ProgressPercentage / 100 * progressScaleHalf), Operation); }; bool result = imagingInterface.CaptureImage(esdFilePath, "Metadata ESD", null, null, tempExtractionPath, compressionType: WimCompressionType.None, PreserveACL: false, progressCallback: callback); Directory.Delete(tmp, true); if (!result) { return(null); } return(esdFilePath); }
private void ThProgressMonitor() { while (_runThMain) { if (_progressCallback != null && _maxProgress > 0) { _progressCallback.Invoke(_currentProgress / _maxProgress); } progressManualResetEvent.WaitOne(PROGRESS_UPDATE_INTERVAL); } }
private void ReadFileStruct(ProgressCallback Progress) { List <DirElement> dirs = new List <DirElement>(); //Потім зробити приватним List <Element> elements = new List <Element>(); dirs.Add(this); _headersFileStream.Position = 0; byte[] buf = new byte[1048576]; double percent = 0; //Читаємо список файлів з диску в пам’ять MemoryStream headers = new MemoryStream(); while (_headersFileStream.Position < _headersFileStream.Length) { int count = _headersFileStream.Read(buf, 0, buf.Length); headers.Write(buf, 0, count); Progress?.Invoke(_headersFileStream.Position / (double)_headersFileStream.Length * 100.0, "Read file list"); } //headers.Position = 1; ReadVersion(headers); //Читаємо список файлів з пам’яті int lastProgress = 0; while (headers.Position < headers.Length) { Element element = GetNextElementFromStream(headers); if (element != null) { AddElement(dirs, elements, element); } percent = headers.Position / (double)headers.Length * 100.0; if ((Progress != null) && (lastProgress != (int)percent)) { Progress(percent, "Parse elements"); lastProgress = (int)percent; } } dataFileStream.FreeSpaceAnalyse(); headers.Dispose(); FillParents(dirs, elements); elements.Clear(); elements = null; dirs.Clear(); dirs = null; }
public static DirectorySize GetDirectorySize(DirectoryInfo directoryInfo, bool ignoreUnauthorizedAccessAndIOExceptions, ProgressCallback progressCallback = null) { if (!directoryInfo.Exists) { throw new DirectoryNotFoundException("The directory does not exist."); } var directorySize = new DirectorySize(); foreach (var fileSystemInfo in directoryInfo.GetFileSystemInfos()) { if ((fileSystemInfo.Attributes & FileAttributes.ReparsePoint) != 0) { continue; } try { switch (fileSystemInfo) { case DirectoryInfo subDirectoryInfo: directorySize += GetDirectorySize(subDirectoryInfo, ignoreUnauthorizedAccessAndIOExceptions); directorySize.FolderCount++; break; case FileInfo fileInfo: directorySize.Size += GetFileSize(fileInfo); directorySize.FileCount++; break; } } catch (FileNotFoundException) { // ignored } catch (Exception e) when(e is UnauthorizedAccessException || e is IOException) { directorySize.Inaccessible++; if (!ignoreUnauthorizedAccessAndIOExceptions) { throw; } } finally { progressCallback?.Invoke(fileSystemInfo.FullName, directorySize); } } return(directorySize); }
public static void SetTargetEdition(string ospath, string edition, ProgressCallback progressCallback) { int counter = 0; // // Initialize DISM log // tryagain: string tempLog = Path.GetTempFileName(); DismApi.Initialize(DismLogLevel.LogErrorsWarningsInfo, tempLog); DismSession session = DismApi.OpenOfflineSession(ospath); try { void callback3(DismProgress progress) { progressCallback?.Invoke(false, (int)Math.Round((double)progress.Current / progress.Total * 100), "Setting edition " + edition); } DismApi.SetEdition(session, edition, callback3); } catch (Exception ex) { Console.WriteLine("Failed attempt #" + counter); Console.WriteLine(ex.ToString()); // // Clean DISM // DismApi.CloseSession(session); try { DismApi.Shutdown(); } catch { } if (counter < 3) { counter++; goto tryagain; } } // // Clean DISM // try { DismApi.CloseSession(session); } catch { } DismApi.Shutdown(); }
/// <summary> /// Async version of ExtractToDirectory with progress reporting. /// </summary> public static async Task ExtractToDirectoryAsync( string file, string path, ProgressCallback progressCallback = null, bool deleteAfter = false ) { if (path.IsNullOrEmpty()) { path = Path.GetDirectoryName(file); } using (FileStream stream = File.OpenRead(file)) { using (ZipArchive zipFile = new ZipArchive(stream, ZipArchiveMode.Read)) { int count = 0; int total = zipFile.Entries.Count; foreach (ZipArchiveEntry entry in zipFile.Entries) { await Task.Run(() => { string destination = Path.GetFullPath(Path.Combine(path, entry.FullName)); if (Path.GetFileName(destination).IsEmpty()) { if (!Directory.Exists(destination)) { Directory.CreateDirectory(destination); } } else { string directory = Path.GetDirectoryName(destination); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } entry.ExtractToFile(destination, true); } }); count += 1; progressCallback?.Invoke(count, total); } } } if (deleteAfter) { File.Delete(file); } }
/// <summary> /// Append to Dest Feature Class. Auto map same field name. /// </summary> /// <param name="ftCursorSrc"></param> /// <param name="fclassDest"></param> public int Append(IFeatureCursor ftCursorSrc, IFeatureClass fclassDest, int totalSrcRecord) { // Make key Upper MakeAllDictConvertFieldValueKeyUpper(); IFeature ftSrc = null; IFeature ftDest = null; SkipFields.Add(fclassDest.OIDFieldName.ToUpper()); SkipFields.Add(fclassDest.ShapeFieldName.ToUpper()); int count = 0; int total = totalSrcRecord; int percent = 0; int updateInterval = PercentCallbackInterval; int nextUpdatePercent = updateInterval; try { // Loop Src Record while ((ftSrc = ftCursorSrc.NextFeature()) != null) { ftDest = fclassDest.CreateFeature(); // Graphic CopyShapeFieldValue(ftSrc, ftDest); // Attribute CopyFieldsValue(ftSrc, ftDest); // Save ftDest.Store(); count++; percent = CalPercent(count, total); if (percent >= nextUpdatePercent) { ProgressCallback?.Invoke(percent); nextUpdatePercent += updateInterval; } } } finally { ComReleaser.ReleaseCOMObject(ftCursorSrc); ftCursorSrc = null; } return(count); }
public static void UninstallPEComponents(string ospath, ProgressCallback progressCallback) { // // Initialize DISM log // string tempLog = Path.GetTempFileName(); DismApi.Initialize(DismLogLevel.LogErrorsWarningsInfo, tempLog); var session = DismApi.OpenOfflineSession(ospath); var packages = DismApi.GetPackages(session); List <DismPackage> componentsToRemove = new List <DismPackage>(); // // Queue components we don't need according to our hardcoded list for removal // foreach (var package in packages) { if (componentsNotInWinPE.Any(x => package.PackageName.StartsWith(x, StringComparison.InvariantCultureIgnoreCase))) { componentsToRemove.Add(package); } } // // Remove components // foreach (var pkg in componentsToRemove) { try { void callback3(DismProgress progress) { progressCallback?.Invoke(false, (int)Math.Round((double)progress.Current / progress.Total * 100), "Removing " + pkg.PackageName); } DismApi.RemovePackageByName(session, pkg.PackageName, callback3); } catch //(Exception ex) { } } // // Clean DISM // DismApi.CloseSession(session); DismApi.Shutdown(); File.Delete(tempLog); }
public static bool GetTargetedPlan( string UUPPath, string LanguageCode, out List <EditionTarget> EditionTargets, ProgressCallback progressCallback = null) { progressCallback?.Invoke(Common.ProcessPhase.ReadingMetadata, true, 0, "Acquiring Composition Databases"); HashSet <CompDBXmlClass.CompDB> compDBs = FileLocator.GetCompDBsFromUUPFiles(UUPPath); string EditionPack = ""; // // Get base editions that are available with all their files // IEnumerable <CompDBXmlClass.CompDB> filteredCompDBs = compDBs.GetEditionCompDBsForLanguage(LanguageCode).Where(x => { (bool success, HashSet <string> missingfiles) = FileLocator.VerifyFilesAreAvailableForCompDB(x, UUPPath); return(success); }); if (filteredCompDBs.Count() > 0) { foreach (CompDBXmlClass.Package feature in filteredCompDBs.First().Features.Feature[0].Packages.Package) { CompDBXmlClass.Package pkg = filteredCompDBs.First().Packages.Package.First(x => x.ID == feature.ID); string file = pkg.GetCommonlyUsedIncorrectFileName(); // // We know already that all files exist, so it's just a matter of knowing which path format is used // file = !File.Exists(Path.Combine(UUPPath, file)) ? pkg.Payload.PayloadItem.Path : file; if (!file.EndsWith(".esd", StringComparison.InvariantCultureIgnoreCase) || !file.Contains("microsoft-windows-editionspecific", StringComparison.InvariantCultureIgnoreCase) || file.Contains("WOW64", StringComparison.InvariantCultureIgnoreCase) || file.Contains("arm64.arm", StringComparison.InvariantCultureIgnoreCase)) { // We do not care about this file continue; } EditionPack = file; } } return(ConversionPlanBuilder.GetTargetedPlan(UUPPath, compDBs, Path.Combine(UUPPath, EditionPack), LanguageCode, out EditionTargets, (string msg) => progressCallback?.Invoke(Common.ProcessPhase.ReadingMetadata, true, 0, msg))); }
/// <summary> /// Progresses the specified percentage. /// </summary> /// <param name="percentage">The percentage value, from 0.0 to 1.0.</param> /// <param name="step">The step.</param> /// <param name="stepCount">The step count.</param> protected void Progress(double percentage, int?step = null, int?stepCount = null) { if (step.HasValue && stepCount.HasValue) { ProgressCallback?.Invoke(string.Format("{0:0.00}% (Step {1} of {2})", percentage * 100, step, stepCount)); } else if (step.HasValue) { ProgressCallback?.Invoke(string.Format("{0:0.00}% (Step {1})", percentage * 100, step)); } else { ProgressCallback?.Invoke(string.Format("{0:0.00}%", percentage * 100)); } }
public XDB(string FileName, string Password, ProgressCallback Progress = null) { Progress?.Invoke(0, "Creating AES key"); InitKey(Password); _addElementLocker = new Object(); _changeElementsLocker = new Object(); string DataFilename = Path.GetDirectoryName(FileName) + "\\" + Path.GetFileNameWithoutExtension(FileName) + ".Data"; try { bool writeVersion = !File.Exists(FileName); _headersFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); _dataFileStream = new FileStream(DataFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); if (writeVersion) { _headersFileStream.WriteByte(Version); } IsReadOnly = false; } catch { if (_headersFileStream != null) { _headersFileStream.Close(); } _headersFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); _dataFileStream = new FileStream(DataFilename, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite); IsReadOnly = true; } header = new Header(new SafeStreamAccess(_headersFileStream), AES, ElementType.Dir); dataFileStream = new SafeStreamAccess(_dataFileStream); try { ReadFileStruct(Progress); } catch (Exception) { throw new ReadingDataException("Помилка читання даних. Можливо невірний пароль."); } }
protected new void HandleTickDone(object sender, TickDoneEventArgs e) { ProgressCallback?.Invoke(Demo.Id, Parser.ParsingProgess); if (!_isTeamsInitialized) { Application.Current.Dispatcher.Invoke(delegate { if (Demo.Players.Count < 10) InitMatch(); Demo.Rounds.Clear(); CreateNewRound(); // since some demos are already started we can't use the freezetime event if (CurrentRound.Number == 1) IsFreezetime = false; }); } base.HandleTickDone(sender, e); }
public virtual void Update() { var uploadProgress = 0f; if (m_TotalBytesToUpload > 0) { uploadProgress = (float)m_BytesUploaded / m_TotalBytesToUpload; } var downloadProgress = 0f; if (m_TotalBytesToDownload > 0) { downloadProgress = (float)m_BytesDownloaded / m_TotalBytesToDownload; } m_Progress?.Invoke(uploadProgress, downloadProgress); }
public async Task PostBytesWithProgressAsync(byte[] byteContentsArray, ProgressCallback callback) { if ((_requestMessage == null) || (callback == null)) { return; } if (ContentType != ContentTypeEnum.eMultipartFormData) { return; } if ((byteContentsArray == null) || (byteContentsArray.Length == 0)) { return; } _requestMessage.Method = HttpMethod.Post; byte[] writeBuffer = new byte[_chunkBufferSize]; using (Stream inputStream = new MemoryStream(byteContentsArray)) { using (Stream outputStream = new MemoryStream()) { Task <int> readCountTask = null; do { readCountTask = inputStream.ReadAsync(writeBuffer, 0, _chunkBufferSize); await readCountTask; Task writeTask = outputStream.WriteAsync(writeBuffer, 0, _chunkBufferSize); await writeTask; var multiPartContent = new MultipartFormDataContent(); multiPartContent.Add(new ByteArrayContent(writeBuffer), KDefaultContentNameString); _requestMessage.Content = multiPartContent; Task <CMPHttpResponse> responseTask = PerformAsync(); await responseTask; callback.Invoke(responseTask.Result, _chunkBufferSize, byteContentsArray.Length); } while (readCountTask.Result > 0); } } }
public bool ExportImage(string wimFile, int imageIndex, string outputWIMFile, CompressionType compressionType = CompressionType.LZX, ExportFlags exportFlags = ExportFlags.DEFAULT, ProgressCallback progressCallback = null) { string title = $"Exporting {wimFile.Split('\\').Last()} - Index {imageIndex}"; try { CallbackStatus ProgressCallback(ProgressMsg msg, object info, object progctx) { switch (msg) { case ProgressMsg.WRITE_STREAMS: { ProgressInfo_WriteStreams m = (ProgressInfo_WriteStreams)info; progressCallback?.Invoke(title, (int)Math.Round((double)m.CompletedBytes / m.TotalBytes * 100), false); } break; case ProgressMsg.WRITE_METADATA_BEGIN: break; case ProgressMsg.WRITE_METADATA_END: break; } return(CallbackStatus.CONTINUE); } using (Wim srcWim = Wim.OpenWim(wimFile, OpenFlags.DEFAULT)) { string imageName = srcWim.GetImageName(imageIndex); using (Wim destWim = Wim.CreateNewWim((ManagedWimLib.CompressionType)compressionType)) { destWim.RegisterCallback(ProgressCallback); srcWim.ExportImage(imageIndex, destWim, imageName, null, (ManagedWimLib.ExportFlags)exportFlags); destWim.Write(outputWIMFile, Wim.AllImages, WriteFlags.DEFAULT, Wim.DefaultThreads); } } } catch { return(false); } return(true); }
public static byte[] ReadAllBytes(this Stream source, long length = -1, ProgressCallback callback = null, object userItem = null) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if ((length <= 0) && source.CanSeek) { length = source.Length - source.Position; } if (length > 0) { var buffer = new byte[length]; var done = 0; while (done < length) { var read = source.Read(buffer, done, (int)length - done); var e = new ProgressEventArgs(userItem, done, read, length, true); callback?.Invoke(source, e); if ((read == -1) || e.Break) { break; } done += read; } if (done != length) { throw new EndOfStreamException(); } return(buffer); } using (var buffer = new MemoryStream()) { CopyBlocksTo(source, buffer, -1, callback, userItem); return(buffer.ToArray()); } }
public static bool GenerateISOImage(string isopath, string cdroot, string volumelabel, ProgressCallback progressCallback) { var runningDirectory = Process.GetCurrentProcess().MainModule.FileName.Contains("\\") ? string.Join("\\", Process.GetCurrentProcess().MainModule.FileName.Split('\\').Reverse().Skip(1).Reverse()) : ""; string cdimagepath = Path.Combine(runningDirectory, "CDImage", "cdimage.exe"); var setupexe = Path.Combine(cdroot, "setup.exe"); var creationtime = File.GetCreationTimeUtc(setupexe); var timestamp = creationtime.ToString("MM/dd/yyyy,hh:mm:ss"); ProcessStartInfo processStartInfo = new ProcessStartInfo(cdimagepath, $"\"-bootdata:2#p0,e,b{cdroot}\\boot\\etfsboot.com#pEF,e,b{cdroot}\\efi\\Microsoft\\boot\\efisys.bin\" -o -h -m -u2 -udfver102 -t{timestamp} -l{volumelabel} \"{cdroot}\" \"{isopath}\""); processStartInfo.UseShellExecute = false; processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.RedirectStandardError = true; processStartInfo.CreateNoWindow = true; Process process = new Process(); process.StartInfo = processStartInfo; try { process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { if (e.Data != null && e.Data.Contains("%")) { var percent = int.Parse(e.Data.Split(' ').First(x => x.Contains("%")).Replace("%", "")); progressCallback?.Invoke($"Building {isopath}", percent, false); } }; process.Start(); process.BeginErrorReadLine(); process.WaitForExit(); return(process.ExitCode == 0); } catch { return(false); } }
//Розкодувує файли, перед викликом не забути присвоїти потрібний IV //streamOffset - _stream.Position //outputStream - куди зберігати розшифровані дані //dataSize - read count public void ReadDecrypt(long streamOffset, Stream outputStream, long dataSize, AesCryptoServiceProvider AES, ProgressCallback Progress) { byte[] buffer = new byte[1048576]; CryptoStream cs = new CryptoStream(_stream, AES.CreateDecryptor(), CryptoStreamMode.Read); long max = dataSize; long position = streamOffset; while (max > 0) { lock (_ReadWriteLock) { _stream.Position = position; int count = cs.Read(buffer, 0, (int)Math.Min(buffer.Length, max)); outputStream.Write(buffer, 0, count); position = _stream.Position; max -= count; } Progress?.Invoke((dataSize - max) / (double)dataSize * 100.0); } }
public void PutFile(string filename1, byte[] bytes, DateTime lastModified, ProgressCallback progressCallback) { var webDav = GetWebDavClient(); var yaFile = new YandexDiscFile(filename1, Location, webDav); CreateDirectory(Path.GetDirectoryName(yaFile.Location), webDav); using (var stream = new MemoryStream(bytes)) { var props = new PutFileParameters(); props.OperationProgress = args => { progressCallback?.Invoke(args.Progress); }; var response = webDav.PutFile(yaFile.Uri, stream, props); if (!response.IsSuccessful) { throw new ApplicationException($"Unable save file: --> {response.StatusCode} {response.Description}"); } } RetryIfFail(5, () => { var name = XName.Get("x-lastmodified", "DataSync"); var patch = new ProppatchParameters(); patch.PropertiesToSet.Add(name, lastModified.ToString("u")); patch.Namespaces.Add(new NamespaceAttr("u", "DataSync")); var propPatch = webDav.Proppatch(yaFile.Uri, patch); if (!propPatch.IsSuccessful) { throw new ApplicationException($"Unable update file properties: --> {propPatch.StatusCode} {propPatch.Description}"); } return(true); }); }
public byte[] GetFile(string filename1, ProgressCallback progressCallback) { var webDav = GetWebDavClient(); var yaFile = new YandexDiscFile(filename1, Location, webDav); var props = new GetFileParameters(); props.OperationProgress = args => { progressCallback?.Invoke(args.Progress); }; using (var response = webDav.GetFile(yaFile.Uri, false, props)) { if (!response.IsSuccessful) { throw new ApplicationException($"Unable read file: --> {response.StatusCode} {response.Description}"); } var data = new byte[response.Stream.Length]; response.Stream.Read(data, 0, data.Length); return(data); } }
/// <summary> /// Collects statistics on how much space savings minimizing will achieve, and (if outStream /// is not null) writes out the minimized cache file. /// </summary> public void Minimize(Settings settings, ProgressCallback progressCallback, Stream outStream, FileStream outStreamScans = null, FileStream outStreamPeaks = null, FileStream outStreamScores = null) { var writer = outStream == null ? null : new Writer(ChromatogramCache, outStream, outStreamScans, outStreamPeaks, outStreamScores); var statisticsCollector = new MinStatisticsCollector(this); bool readChromatograms = settings.NoiseTimeRange.HasValue || writer != null; var chromGroupHeaderToIndex = ChromGroupHeaderInfos .Select((cghi, index) => new KeyValuePair<ChromGroupHeaderInfo5, int>(cghi, index)) .ToDictionary(kvp => kvp.Key, kvp=>kvp.Value); var chromGroups = new ChromatogramGroupInfo[ChromGroupHeaderInfos.Count]; var transitionGroups = new List<TransitionGroupDocNode>[ChromGroupHeaderInfos.Count]; foreach (var nodePep in Document.Molecules) { foreach (var nodeGroup in nodePep.TransitionGroups) { ChromatogramGroupInfo[] groupInfos; ChromatogramCache.TryLoadChromatogramInfo(nodePep, nodeGroup, _tolerance, out groupInfos); foreach (var chromGroupInfo in groupInfos) { int headerIndex = chromGroupHeaderToIndex[chromGroupInfo.Header]; if (chromGroups[headerIndex] == null) { chromGroups[headerIndex] = chromGroupInfo; transitionGroups[headerIndex] = new List<TransitionGroupDocNode>(); } transitionGroups[headerIndex].Add(nodeGroup); } } } for (int iHeader = 0; iHeader < ChromGroupHeaderInfos.Count; iHeader++) { var chromGroupInfo = chromGroups[iHeader]; IList<TransitionGroupDocNode> transitionGroupDocNodes; if (chromGroupInfo == null) { chromGroupInfo = ChromatogramCache.LoadChromatogramInfo(ChromGroupHeaderInfos[iHeader]); transitionGroupDocNodes = new TransitionGroupDocNode[0]; } else { transitionGroupDocNodes = transitionGroups[iHeader]; } if (readChromatograms) { try { chromGroupInfo.ReadChromatogram(ChromatogramCache); } catch (Exception exception) { Trace.TraceWarning("Unable to read chromatogram {0}", exception); // Not L10N } } MinimizedChromGroup minimizedChromGroup = MinimizeChromGroup(settings, chromGroupInfo, transitionGroupDocNodes); statisticsCollector.ProcessChromGroup(minimizedChromGroup); if (progressCallback != null) { progressCallback.Invoke(statisticsCollector.GetStatistics()); } if (writer != null) { writer.WriteChromGroup(chromGroupInfo, minimizedChromGroup); } // Null out the ChromGroup in our array so it can be garbage collected. chromGroups[iHeader] = null; } if (progressCallback != null) { progressCallback.Invoke(statisticsCollector.GetStatistics()); } if (writer != null) { writer.WriteEndOfFile(); } }