static void Main(string[] args) { var orign = args[0]; var diff = args[1]; var target = args[2]; var decoder = new VcdiffDecoder(File.OpenRead(orign), File.OpenRead(diff), File.OpenWrite(target)); decoder.Decode(); }
void CreatewyUpdateFromPatch() { // generate files from patches if (Directory.Exists(Path.Combine(OutputDirectory, "patches"))) { // set the base directory to the home of the client file ProgramDirectory = Path.GetDirectoryName(OldSelfLoc); TempDirectory = OutputDirectory; // patch the file (assume only one - wyUpdate.exe) if (UpdtDetails.UpdateFiles[0].DeltaPatchRelativePath != null) { string tempFilename = Path.Combine(TempDirectory, UpdtDetails.UpdateFiles[0].RelativePath); // create the directory to store the patched file if (!Directory.Exists(Path.GetDirectoryName(tempFilename))) { Directory.CreateDirectory(Path.GetDirectoryName(tempFilename)); } try { using (FileStream original = File.Open(OldSelfLoc, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (FileStream patch = File.Open(Path.Combine(TempDirectory, UpdtDetails.UpdateFiles[0].DeltaPatchRelativePath), FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream target = File.Open(tempFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { VcdiffDecoder.Decode(original, patch, target, UpdtDetails.UpdateFiles[0].NewFileAdler32); } } catch (Exception ex) { throw new PatchApplicationException("Patch failed to apply to this file: " + FixUpdateDetailsPaths(UpdtDetails.UpdateFiles[0].RelativePath) + "\r\n\r\nBecause that file failed to patch, and there's no \"catch-all\" update to download, the update failed to apply. The failure to patch usually happens because the file was modified from the original version. Reinstall the original version of this app.\r\n\r\n\r\nInternal error: " + ex.Message); } // the 'last write time' of the patch file is really the 'lwt' of the dest. file File.SetLastWriteTime(tempFilename, File.GetLastWriteTime(Path.Combine(TempDirectory, UpdtDetails.UpdateFiles[0].DeltaPatchRelativePath))); } try { // remove the patches directory (frees up a bit of space) Directory.Delete(Path.Combine(TempDirectory, "patches"), true); } catch { } } }
static async Task Main(string[] args) { AblyRealtime ably = new AblyRealtime("HG2KVw.AjZP_A:W7VXUG9yw1-Cza6u"); IRealtimeChannel channel = ably.Channels.Get("[?delta=vcdiff]delta-sample-app"); VcdiffDecoder channelDecoder = new VcdiffDecoder(); channel.Subscribe(message => { object data = message.Data; try { if (VcdiffDecoder.IsDelta(data)) { data = channelDecoder.ApplyDelta(data).AsObject(); } else { channelDecoder.SetBase(data); } } catch (Exception e) { /* Delta decoder error */ } /* Process decoded data */ Console.WriteLine(JsonHelper.DeserializeObject <Data>(data as JObject)); }); ably.Connection.On(ConnectionEvent.Connected, change => { Data data = new Data() { foo = "bar", count = 1, status = "active" }; channel.Publish("data", data); data.count++; channel.Publish("data", data); data.status = "inactive"; channel.Publish("data", data); }); await Task.Run(() => { Console.ReadLine(); }); }
private bool DeltaPatch(string original, string patch) { string targetFileName = Path.GetFileName(original); try { using (FileStream originalFile = File.OpenRead(original)) using (FileStream patchFile = File.OpenRead(patch)) using (FileStream targetFile = File.Open(Path.Combine(Path.GetDirectoryName(patch), targetFileName), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { VcdiffDecoder.Decode(originalFile, patchFile, targetFile); } return(true); } catch (Exception) { return(false); } }
private async void downloadClick(object sender, RoutedEventArgs e) { while (Process.GetProcessesByName("BnS-Multi-Tool").Length >= 1) { //Find all instances of BnS-Multi-Tool and close. try { Process[] processes = Process.GetProcessesByName("BnS-Multi-Tool"); foreach (Process proc in processes) { proc.Kill(); } Thread.Sleep(50); } catch (Exception) { } } downloadComplete = new TaskCompletionSource <bool>(); downloadBtn.Visibility = Visibility.Hidden; VersionGrid.Visibility = Visibility.Hidden; ProgressControl.Value = 0; ProgressText.Text = "0%"; downloadingLbl.Content = "Downloading..."; ProgressGrid.Visibility = Visibility.Visible; bool failedToUpdate = false; await Task.Run(async() => { try { WebClient client = new WebClient(); client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DL_PROGRESS_CHANGED); client.DownloadFileCompleted += new AsyncCompletedEventHandler(DL_COMPLETED); client.DownloadFileAsync(new Uri("http://tonic.pw/files/bnsmultitool/BnS-Multi-Tool.exe.dlt"), "BnS-Multi-Tool.exe.dlt"); await downloadComplete.Task; await downloadingLbl.Dispatcher.BeginInvoke(new Action(() => { downloadingLbl.Content = "Patching...."; })); using (FileStream original = File.OpenRead("BnS-Multi-Tool.exe")) using (FileStream patch = File.OpenRead("BnS-Multi-Tool.exe.dlt")) using (FileStream target = File.Open("BnS-Multi-Tool-New.exe", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { VcdiffDecoder.Decode(original, patch, target); } await Task.Delay(1000); //Hash check string localHash = CalculateMD5("BnS-Multi-Tool-New.exe"); await downloadingLbl.Dispatcher.BeginInvoke(new Action(() => { downloadingLbl.Content = "Verifying...."; })); await Task.Delay(1000); if (localHash == onlineJson.HASH) { string jsonString = File.ReadAllText("settings.json"); var SYS = JsonConvert.DeserializeObject <SYSConfig>(jsonString); SYS.VERSION = onlineJson.VERSION; //Append new UPKs to our main list if (onlineJson.MAIN_UPKS.Count() > 0) { List <string> _MAIN_UPKS = SYS.MAIN_UPKS.ToList(); foreach (string UPK in onlineJson.MAIN_UPKS) { if (!SYS.MAIN_UPKS.Contains(UPK)) { _MAIN_UPKS.Add(UPK); } } SYS.MAIN_UPKS = _MAIN_UPKS.ToArray(); } jsonString = JsonConvert.SerializeObject(SYS, Formatting.Indented); File.WriteAllText("settings.json", jsonString); await downloadingLbl.Dispatcher.BeginInvoke(new Action(() => { downloadingLbl.Content = "Launching...."; })); await Task.Delay(500); if (File.Exists("BnS-Multi-Tool.exe.dlt")) { File.Delete("BnS-Multi-Tool.exe.dlt"); } if (File.Exists("BnS-Multi-Tool.exe")) { File.Delete("BnS-Multi-Tool.exe"); } File.Move("BnS-Multi-Tool-New.exe", "BnS-Multi-Tool.exe"); ProcessStartInfo proc = new ProcessStartInfo(); proc.Verb = "runas"; proc.FileName = "BnS-Multi-Tool.exe"; Process.Start(proc); Environment.Exit(0); } else { failedToUpdate = true; } } catch (Exception ex) { MessageBox.Show(ex.Message); failedToUpdate = true; } }); //This is redundant but just in case if (failedToUpdate) { ProgressText.Text = "FAILED"; downloadBtn.Visibility = Visibility.Visible; //VersionGrid.Visibility = Visibility.Visible; //ProgressGrid.Visibility = Visibility.Hidden; ProgressControl.Value = 0; downloadingLbl.Content = "Incorrect Hash"; MessageBox.Show("Are you sure the multi tool is closed and an anti-virus is not blocking the download? You can try again", "Failed to update"); downloadFull.Visibility = Visibility.Visible; downloadBtn.Visibility = Visibility.Hidden; } }
private static void PatchProcessor(XmlNode product, string fullInstallerPath, string licenseChannel, string architecture) { #region XDELTA Patching // List of Patch Nodes for the Product XmlNodeList patchList = null; foreach (XmlNode productChild in product.ChildNodes) { if (productChild.Name == "Patches") { patchList = productChild.ChildNodes; break; } } // Process Patch Nodes if (patchList != null) { foreach (XmlNode patchInstance in patchList) { // Get Patch Attributes (Target File Names) XmlAttributeCollection patchAttributes = patchInstance.Attributes; if (patchAttributes != null) { string retailFileName = patchAttributes["RetailFile"].Value; string volumeFileName = patchAttributes["VolumeFile"].Value; string version = patchAttributes["Version"].Value; string patchDataBase64 = string.Empty; // Skip Patches Based On Version if (!version.Contains(InstallerInformation.SetupVersionFull)) { continue; } // Find Desired PatchData Node for the Source License Channel and Architecture foreach (XmlNode patchDataInstance in patchInstance) { XmlAttributeCollection patchDataAttributes = patchDataInstance.Attributes; if (patchDataAttributes != null && !patchDataAttributes["TargetChannel"].Value.ToUpper().Contains(licenseChannel.ToUpper()) && patchDataAttributes["Architecture"].Value == architecture) { patchDataBase64 = patchDataInstance.InnerText; break; } } string originalFile = string.Empty; string targetFile = string.Empty; if (retailFileName == volumeFileName) { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; targetFile = originalFile + ".new"; } else if (licenseChannel == "Retail") { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; targetFile = fullInstallerPath + Path.DirectorySeparatorChar + volumeFileName; } else if (licenseChannel == "Volume") { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + volumeFileName; targetFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; } // Execute Patcher using (FileStream original = File.OpenRead(originalFile)) { using (Stream patchStream = new MemoryStream(Convert.FromBase64String(patchDataBase64))) { using (FileStream target = File.Open(targetFile, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { VcdiffDecoder.Decode(original, patchStream, target); } } } // Delete Old File CommonUtilities.FileDelete(originalFile); // Rename New File if (targetFile.Contains(".new")) { File.Move(targetFile, targetFile.Replace(".new", "")); } } } } #endregion #region File Replacing // List of File Nodes for the Product XmlNodeList fileList = null; foreach (XmlNode productChild in product.ChildNodes) { if (productChild.Name == "Files") { fileList = productChild.ChildNodes; break; } } // Process Patch Nodes if (fileList != null) { foreach (XmlNode fileInstance in fileList) { // Get File Attributes (Target File Names) XmlAttributeCollection fileAttributes = fileInstance.Attributes; if (fileAttributes != null) { string retailFileName = fileAttributes["RetailFile"].Value; string volumeFileName = fileAttributes["VolumeFile"].Value; string version = fileAttributes["Version"].Value; string fileDataBase64 = string.Empty; // Skip Files Based On Version if (!version.Contains(InstallerInformation.SetupVersionFull)) { continue; } // Find Desired FileData Node for the Source License Channel and Architecture foreach (XmlNode fileDataInstance in fileInstance) { XmlAttributeCollection fileDataAttributes = fileDataInstance.Attributes; if (fileDataAttributes != null && !fileDataAttributes["TargetChannel"].Value.ToUpper().Contains(licenseChannel.ToUpper()) && fileDataAttributes["Architecture"].Value == architecture) { fileDataBase64 = fileDataInstance.InnerText; break; } } string originalFile = string.Empty; string targetFile = string.Empty; if (retailFileName == volumeFileName) { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; targetFile = originalFile; } else if (licenseChannel == "Retail") { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; targetFile = fullInstallerPath + Path.DirectorySeparatorChar + volumeFileName; } else if (licenseChannel == "Volume") { originalFile = fullInstallerPath + Path.DirectorySeparatorChar + volumeFileName; targetFile = fullInstallerPath + Path.DirectorySeparatorChar + retailFileName; } // Delete Old File CommonUtilities.FileDelete(originalFile); // Create New File CommonUtilities.FileCreate(Path.GetFileName(targetFile), Convert.FromBase64String(fileDataBase64), Path.GetDirectoryName(targetFile)); } } } #endregion }
void bw_DoWorkUnzip(object sender, DoWorkEventArgs e) { Exception except = null; string updtDetailsFilename = Path.Combine(TempDirectory, "updtdetails.udt"); try { ExtractUpdateFile(); try { // remove update file (it's no longer needed) File.Delete(Filename); } catch { } // Try to load the update details file if (File.Exists(updtDetailsFilename)) { UpdtDetails = UpdateDetails.Load(updtDetailsFilename); } else { throw new Exception("The update details file \"updtdetails.udt\" is missing."); } if (Directory.Exists(Path.Combine(TempDirectory, "patches"))) { // patch the files foreach (UpdateFile file in UpdtDetails.UpdateFiles) { if (file.DeltaPatchRelativePath != null) { if (IsCancelled()) { break; } string tempFilename = Path.Combine(TempDirectory, file.RelativePath); // create the directory to store the patched file if (!Directory.Exists(Path.GetDirectoryName(tempFilename))) { Directory.CreateDirectory(Path.GetDirectoryName(tempFilename)); } while (true) { try { using (FileStream original = File.Open(FixUpdateDetailsPaths(file.RelativePath), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (FileStream patch = File.Open(Path.Combine(TempDirectory, file.DeltaPatchRelativePath), FileMode.Open, FileAccess.Read, FileShare.Read)) using (FileStream target = File.Open(tempFilename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { VcdiffDecoder.Decode(original, patch, target, file.NewFileAdler32); } } catch (IOException IOEx) { int HResult = Marshal.GetHRForException(IOEx); // if sharing violation if ((HResult & 0xFFFF) == 32) { // notify main window of sharing violation bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.SharingViolation, FixUpdateDetailsPaths(file.RelativePath) }); // sleep for 1 second Thread.Sleep(1000); // stop waiting if cancelled if (IsCancelled()) { break; } // retry file patch continue; } throw new PatchApplicationException("Patch failed to apply to this file: " + FixUpdateDetailsPaths(file.RelativePath) + "\r\n\r\nBecause that file failed to patch, and there's no \"catch-all\" update to download, the update failed to apply. The failure to patch usually happens because the file was modified from the original version. Reinstall the original version of this app.\r\n\r\n\r\nInternal error: " + IOEx.Message); } catch (Exception ex) { throw new PatchApplicationException("Patch failed to apply to this file: " + FixUpdateDetailsPaths(file.RelativePath) + "\r\n\r\nBecause that file failed to patch, and there's no \"catch-all\" update to download, the update failed to apply. The failure to patch usually happens because the file was modified from the original version. Reinstall the original version of this app.\r\n\r\n\r\nInternal error: " + ex.Message); } // the 'last write time' of the patch file is really the 'lwt' of the dest. file File.SetLastWriteTime(tempFilename, File.GetLastWriteTime(Path.Combine(TempDirectory, file.DeltaPatchRelativePath))); break; } } } try { // remove the patches directory (frees up a bit of space) Directory.Delete(Path.Combine(TempDirectory, "patches"), true); } catch { } } } catch (BadPasswordException ex) { except = new BadPasswordException("Could not install the encrypted update because the password did not match."); } catch (Exception ex) { except = ex; } if (IsCancelled() || except != null) { // report cancellation bw.ReportProgress(0, new object[] { -1, -1, "Cancelling update...", ProgressStatus.None, null }); // Delete temporary files if (except != null && except.GetType() != typeof(PatchApplicationException)) { // remove the entire temp directory try { Directory.Delete(OutputDirectory, true); } catch { } } else { //only 'gut' the folder leaving the server file string[] dirs = Directory.GetDirectories(TempDirectory); foreach (string dir in dirs) { // delete everything but the self-update folder (AutoUpdate specific) //Note: this code might be causing the "pyramid of death". TODO: Check. if (Path.GetFileName(dir) == "selfupdate") { continue; } try { Directory.Delete(dir, true); } catch { } } // remove the update details if (File.Exists(updtDetailsFilename)) { File.Delete(updtDetailsFilename); } } bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Failure, except }); } else { bw.ReportProgress(0, new object[] { -1, -1, string.Empty, ProgressStatus.Success, null }); } }