public void generateName() { using (NameDialog n = new NameDialog()) { n.EntryText = "Battlefield"; n.LabelText = "Enter the stage name. (Use \\n for a line break.)\nType just ] to launch genname.bat/genname.exe instead."; if (n.ShowDialog() == DialogResult.OK) { if (n.EntryText == "]") { generateNameExternal(); } else { if (fontSettings == null) { changeFrontStnameFont(); } if (fontSettings == null) { return; } Bitmap bmp = NameCreator.createImage(fontSettings, n.EntryText); string tempfile = TempFiles.Create(".png"); bmp.Save(tempfile); Replace(frontstname, tempfile); } } } }
public void generateNameExternal() { string exeDir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string tempfile = TempFiles.Create(".png"); ProcessStartInfo start = new ProcessStartInfo() { WorkingDirectory = exeDir, FileName = File.Exists(exeDir + "\\genname.bat") ? "genname.bat" : "genname.exe", Arguments = tempfile }; if (!File.Exists(exeDir + "\\" + start.FileName)) { MessageBox.Show(this, "Could not find genname.bat or genname.exe.\nCreate a program or batch file that takes an output PNG file path as its only argument. It should write to this path before closing."); return; } using (Process p = Process.Start(start)) { p.WaitForExit(); if (!File.Exists(tempfile)) { MessageBox.Show(this, "The program did not write to the temporary file path. Make sure it's using %1 (first argument) as the output filename."); return; } } Replace(frontstname, tempfile); }
public void updateMuMenumain(string msBinPath = null) { if (DialogResult.OK == MessageBox.Show("Overwrite the current mu_menumain?", "Overwrite File", MessageBoxButtons.OKCancel)) { using (ResourceNode mu_menumain = TempFiles.MakeTempNode(mu_menumain_path)) { IconsToMenumain.Copy(sc_selmap, mu_menumain, BestSSS); if (msBinPath != null) { mu_menumain.FindChild("MiscData[7]", false).Replace(msBinPath); } mu_menumain.Export(mu_menumain_path); } byte absent_stage_id = BestSSS[0x1E].Item1; int sss2_count = BestSSS.sss2.Where(b => b != 0x1E).Count() + 1; string warn = sss2_count <= 39 ? "" : "\nWARNING: screen 2 of the SSS " + (AutoSSS == null ? "may have " : "has ") + "more than 39 stages, causing My Music to crash on page 2."; var q = StageIDMap.Stages.Where(s => s.ID == absent_stage_id); string absent = q.Any() ? q.First().Name : "STGCUSTOM" + (absent_stage_id - 0x3f).ToString("X2"); MessageBox.Show("Done. " + (msBinPath != null ? "(Song titles copied too.) " : "") + (AutoSSS == null ? "Without a Custom SSS code, " : "Based on your current SSS code, ") + absent + " will be missing; and Menu will be added to the end of screen 2." + warn); } }
public UpdateDownloaderMaliciousExistingTempFilesTest() { TempFiles.Add("7324c19ad06ea51117d7ffdd01f7d030ac03651f6ea57472de1765b3dfa3a9e0", new MockTempFile { Exists = true, DataStream = new MemoryStream(Encoding.ASCII.GetBytes("NORA??")) }); }
public SSSEditorForm(string gct, string pac) { InitializeComponent(); foreach (Control c in tblColorCodeKeys.Controls) { c.DoubleClick += (o, e) => { tblColorCodeKeys.Visible = false; }; } try { Icon = Icon.ExtractAssociatedIcon(System.Reflection.Assembly.GetCallingAssembly().Location); } catch (Exception e) { Console.WriteLine(e.StackTrace); } tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged; sss = gct != null ? new CustomSSSCodeset(gct) : new CustomSSSCodeset(); if (pac != null) { ReloadIfValidPac(pac); } else { md80 = new BRRESNode(); ReloadData(); } FormClosed += (o, e) => TempFiles.DeleteAll(); }
internal override void DeleteDatabase() { if (!string.IsNullOrWhiteSpace(DBName)) { SqlHelper.Execute("USE master;"); SqlHelper.Execute($"ALTER DATABASE [{DBName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;"); SqlHelper.Execute($"DROP DATABASE [{DBName}]"); DBName = null; } try { foreach (var t in TempFiles.ToList()) { var file = new System.IO.FileInfo(t); if (file.Exists) { file.Delete(); } TempFiles.Remove(t); } //TempFiles.Clear(); } catch (Exception ex) { WriteLine(ex.ToString()); } }
/// <summary> /// Aborts the working thread. /// </summary> /// <remarks>Documented by Dev02, 2008-05-20</remarks> internal static void AbortWorkingThread() { if (WorkingThreadActive) { workerthread.Abort(); } //try to delete the temp directory (try multiple times in case it is still locked) Thread cleanthread = new Thread(delegate() { int tries = 0; while (tries++ < 10) { System.Threading.Thread.Sleep(1000); try { TempFiles.ForEach(f => f.Delete()); break; } catch { } } }); cleanthread.IsBackground = true; cleanthread.Start(); }
/// <summary> /// Gets the card media files. /// </summary> /// <param name="card">The card.</param> /// <param name="mediafield">The mediafield.</param> /// <returns>The found media files.</returns> /// <remarks>Documented by Dev02, 2008-03-30</remarks> private static IList <MediaFieldFile> GetCardMediaFiles(ICard card, List <MediaField> mediafields) { IList <MediaFieldFile> foundfiles = new List <MediaFieldFile>(); foreach (MediaField mediafield in mediafields) { if (mediafield.Type == MediaField.TypeEnum.AudioField) { IList <IMedia> medialist = null; switch (mediafield.Side) { case MediaField.SideEnum.Question: medialist = card.QuestionMedia; break; case MediaField.SideEnum.Answer: medialist = card.AnswerMedia; break; } if (medialist != null) { foreach (IMedia media in medialist) { if (media.MediaType == EMedia.Audio && ((IAudio)media).Example == mediafield.Example) { string sourceFile = GetTempFile(media.Extension); //write to temp file using (Stream mediaStream = media.Stream) { using (Stream output = new FileStream(sourceFile, FileMode.Create)) { byte[] buffer = new byte[32 * 1024]; int read; while ((read = mediaStream.Read(buffer, 0, buffer.Length)) > 0) { output.Write(buffer, 0, read); } } } FileInfo mediafile = new FileInfo(sourceFile); if (mediafile.Exists) { TempFiles.Add(mediafile); foundfiles.Add(new MediaFieldFile(mediafield, mediafile)); } } } } } else if (mediafield.Type == MediaField.TypeEnum.Silence) { foundfiles.Add(new MediaFieldFile(mediafield)); } } return(foundfiles); }
private void lblPMAlt_DragDrop(object sender, DragEventArgs e) { if (e.Effect == DragDropEffects.Copy) { string s = (e.Data.GetData(DataFormats.FileDrop) as string[])[0]; new Task(() => { Bitmap existing = GetTexInfoFor(prevbase).tex0.GetImage(0); Image newBitmap = Bitmap.FromFile(s); Bitmap lowerPortion = new Bitmap(106, 24); using (Graphics g = Graphics.FromImage(lowerPortion)) { int height = (int)(((double)newBitmap.Height / newBitmap.Width) * 106); int offset = (24 - height) / 2; g.DrawImage(newBitmap, 0, offset, 106, height); } Bitmap canvas = new Bitmap(176, 176); using (Graphics g = Graphics.FromImage(canvas)) { g.DrawImage(existing, 0, 0, 176, 176); g.FillRectangle(Brushes.Black, 0, 126, 176, 50); g.DrawImage(lowerPortion, 52, 131, 106, 24); } string temp = TempFiles.Create(".png"); canvas.Save(temp); Replace(prevbase, temp); }).Start(); } }
public string GetTempTmxFile() { string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".tmx"); TempFiles.Add(path); return(path); }
public override string BuildArguments() { string playlistFileName = Path.Combine(Path.GetTempPath(), Path.GetFileName(InputFile) + $"-playlist.txt"); File.WriteAllLines(playlistFileName, ClipFiles.Select(se => $"file '{se.Replace("'", "'\\''")}'")); //concat requires special escaping TempFiles.Add(playlistFileName); return($"-f concat -safe 0 -i \"{playlistFileName}\" -c copy \"{OutputFile}\""); }
public void Run() { try { if (_isSafetyNetRunning != true) //checking if safetynet has already been started { this.StartSafetyNet(); //watch instance numbers _isSafetyNetRunning = true; } if (_isTempCleanerRunning != true) //checking if tempcleaner has been started { TempFiles.StartTempFileWatcher(); //watch temp directory on a diff schedule _isTempCleanerRunning = true; } this._timeline = TimelineBuilder.GetLocalTimeline(); // now watch that file for changes if (timelineWatcher == null) //you can change this to a bool if you want but checks if the object has been created { _log.Trace("Timeline watcher starting and is null..."); timelineWatcher = new FileSystemWatcher(TimelineBuilder.TimelineFilePath().DirectoryName) { Filter = Path.GetFileName(TimelineBuilder.TimelineFilePath().Name) }; _log.Trace($"watching {Path.GetFileName(TimelineBuilder.TimelineFilePath().Name)}"); timelineWatcher.NotifyFilter = NotifyFilters.LastWrite; timelineWatcher.EnableRaisingEvents = true; timelineWatcher.Changed += OnChanged; } _threadJobs = new List <ThreadJob>(); //load into an managing object //which passes the timeline commands to handlers //and creates a thread to execute instructions over that timeline if (this._timeline.Status == Timeline.TimelineStatus.Run) { RunEx(this._timeline); } else { if (MonitorThread != null) { MonitorThread.Abort(); MonitorThread = null; } } } catch (Exception e) { _log.Error($"Orchestrator.Run exception: {e}"); } }
private async Task ProcessBookAsync(Document document, long chatId, BookFormat desiredFormat) { string fileName = document.FileName; Message loadingMessage = await SendLoadingMessageAsync(); using var tempFiles = new TempFiles(); try { Book originalBook = await DownloadOriginalBookAsync(document); tempFiles.Add(originalBook.FilePath); Book convertedBook = await ConvertBookAsync(desiredFormat, originalBook); tempFiles.Add(convertedBook.FilePath); await DeleteLoadingMessageAsync(loadingMessage); if (convertedBook.Equals(originalBook)) { await this.bot.SendTextMessageAsync(chatId, $"Your book *{originalBook.Title}* is already good!", ParseMode.Markdown); } else { await using Stream output = convertedBook.Content(); await this.bot.SendDocumentAsync(chatId, new InputOnlineFile(output, $"{convertedBook.Title}{convertedBook.Format}"), $"Here you go! Your *{convertedBook.Title}* is ready. Enjoy.", ParseMode.Markdown); } } catch (Exception exception) { Log.Error(exception, $"Exception happened when converting {document.FileId}"); await DeleteLoadingMessageAsync(loadingMessage); await this.bot.SendTextMessageAsync(chatId, $"Sorry, something went wrong with *{fileName}*. Try sending the book again.", ParseMode.Markdown); } Task <Message> SendLoadingMessageAsync() { return(this.bot.SendTextMessageAsync(chatId, $"Wait a bit. My dwarfs are working on *{fileName}*", ParseMode.Markdown)); } Task DeleteLoadingMessageAsync(Message message) { return(message != null ? this.bot.DeleteMessageAsync(chatId, message.MessageId) : Task.CompletedTask); } }
public void ResizeAllPrevbases(Size newSize) { if (sc_selmap == null) { return; } var prevbases = from c in sc_selmap.FindChild("MiscData[80]/Textures(NW4R)", false).Children where c is TEX0Node && c.Name.Contains("MenSelmapPrevbase") select(TEX0Node) c; int i = 0; foreach (TEX0Node node in prevbases) { Bitmap origImage = node.GetImage(0); if (origImage.Width <= newSize.Width && origImage.Height <= newSize.Height) { continue; } string file = TempFiles.Create(".png"); if (useTextureConverter) { origImage.Save(file); TextureConverterDialog d = new TextureConverterDialog(); d.ImageSource = file; d.InitialSize = newSize; if (d.ShowDialog(null, node) == DialogResult.OK) { node.IsDirty = true; Console.WriteLine("Resized " + node); i++; } else if (MessageBox.Show(this, "Stop resizing textures here?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { break; } } else { Bitmap b = BitmapUtilities.Resize(origImage, newSize); b.Save(file); node.Replace(file); Console.WriteLine("Resized " + node); i++; } File.Delete(file); } MessageBox.Show("Resized " + i + " images."); UpdateImage(); }
private void ExtractISO(PbpDiscEntry disc, string path, ExtractOptions extractInfo, CancellationToken cancellationToken) { try { disc.ProgressEvent += ProgressEvent; if (!ContinueIfFileExists(extractInfo, path)) { return; } Notify?.Invoke(PopstationEventEnum.Info, $"Writing {path}..."); Notify?.Invoke(PopstationEventEnum.GetIsoSize, disc.IsoSize); Notify?.Invoke(PopstationEventEnum.ExtractStart, disc.Index); var cueFilename = Path.GetFileNameWithoutExtension(path) + ".cue"; var dirPath = Path.GetDirectoryName(path); var cuePath = Path.Combine(dirPath, cueFilename); TempFiles.Add(path); TempFiles.Add(cuePath); using (var isoStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { disc.CopyTo(isoStream, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return; } TempFiles.Remove(path); if (!extractInfo.CreateCuesheet) { return; } var cueFile = TOCtoCUE(disc.TOC, Path.GetFileName(path)); CueFileWriter.Write(cueFile, cuePath); TempFiles.Remove(cuePath); Notify?.Invoke(PopstationEventEnum.ExtractComplete, null); } finally { disc.ProgressEvent -= ProgressEvent; } }
/// <summary> /// Formatiert den Wert der aktuellen Instanz unter Verwendung des angegebenen Formats. /// </summary> /// <returns> /// Der Wert der aktuellen Instanz im angegebenen Format. /// </returns> /// <param name="format">Das zu verwendende Format.– oder – Ein NULL-Verweis (Nothing in Visual Basic), /// wenn das für den Typ der <see cref="T:System.IFormattable"/> -Implementierung definierte Standardformat verwendet werden soll. </param> /// <param name="formatProvider">Der zum Formatieren des Werts zu verwendende Anbieter.– oder – Ein NULL-Verweis (Nothing in Visual Basic), /// wenn die Informationen über numerische Formate dem aktuellen Gebietsschema des Betriebssystems entnommen werden sollen. </param> /// <filterpriority>2</filterpriority> public string ToString(string format, IFormatProvider formatProvider) { var result = string.Empty; result += $"JobName: {JobName} {Environment.NewLine}"; result += $"BaseName: {BaseName} {Environment.NewLine}"; result += $"InputFile: {InputFile} {Environment.NewLine}"; result += $"InputType: {Input} {Environment.NewLine}"; result += $"OutputFile: {OutputFile} {Environment.NewLine}"; result += Environment.NewLine; result += $"AudioStreams: {Environment.NewLine}"; result = AudioStreams.Aggregate(result, (current, item) => current + $"{item} {Environment.NewLine}"); result += Environment.NewLine; result += $"SubtitleStreams: {Environment.NewLine}"; result = SubtitleStreams.Aggregate(result, (current, item) => current + $"{item} {Environment.NewLine}"); result += Environment.NewLine; var list = new List <string>(); foreach (var item in Chapters) { var dt = DateTime.MinValue.Add(item); list.Add(dt.ToString("H:mm:ss.fff")); } result += $"Chapters: {string.Join(",", list.ToArray())} {Environment.NewLine}"; result += $"NextStep: {NextStep} {Environment.NewLine}"; result += $"CompletedStep: {CompletedStep} {Environment.NewLine}"; result += Environment.NewLine; result += $"VideoStream: {Environment.NewLine}"; result += $"{VideoStream} {Environment.NewLine}"; result += Environment.NewLine; result += $"StreamID: {StreamId:0} {Environment.NewLine}"; result += $"TrackID: {TrackId:0} {Environment.NewLine}"; result += $"TempInput: {TempInput} {Environment.NewLine}"; result += $"TempOutput: {TempOutput} {Environment.NewLine}"; result += $"DumpOutput: {DumpOutput} {Environment.NewLine}"; result += $"SelectedDVDChapters:{SelectedDvdChapters} {Environment.NewLine}"; result += $"TempFiles: {string.Join(",", TempFiles.ToArray())} {Environment.NewLine}"; result += $"ReturnValue: {ExitCode:0} {Environment.NewLine}"; return(result); }
public async Task Test() { await UpdateDownloader.DownloadAsync(CancellationToken.None); Assert.Single(Downloads); Assert.Contains(Hash.Parse("ac6cb635c58754672d0e576442db9ecadd8043829916ca85330cf00bd7359df9"), Downloads); Assert.Equal(2, TempFiles.Count); Assert.True(TempFiles.TryGetValue("7324c19ad06ea51117d7ffdd01f7d030ac03651f6ea57472de1765b3dfa3a9e0", out var tempFile)); Assert.Equal("NORA2", Encoding.ASCII.GetString(tempFile.DataStream.ToArray())); Assert.True(TempFiles.TryGetValue("ac6cb635c58754672d0e576442db9ecadd8043829916ca85330cf00bd7359df9", out tempFile)); Assert.Equal("NORA3", Encoding.ASCII.GetString(tempFile.DataStream.ToArray())); }
/// <summary> /// 分块临时文件存储 /// </summary> /// <param name="model"></param> /// <returns></returns> public Result <TempFiles> AddTempFile(TempFiles model) { Result <TempFiles> result = new Result <TempFiles>(); try { dbContext.TempFiles.Add(model); dbContext.SaveChanges(); result.Data = model; result.Flag = EResultFlag.Success; } catch (Exception ex) { result.Data = null; result.Flag = EResultFlag.Failure; result.Exception = new ExceptionEx(ex, "AddTempFile"); } return(result); }
public override IReadOnlyCollection <ConfigurationValidationError> Validate(string?prefix = null) { var errors = new ConfigurationValidationErrorCollection(prefix); errors.AddErrors(base.Validate(prefix)); if (ReverseProxy != null) { errors.AddErrors(ReverseProxy.Validate(nameof(ReverseProxy))); } errors.AddErrors(ExternalUrls.Validate(nameof(ExternalUrls))); errors.AddErrors(DbOptions.Validate(nameof(DbOptions))); errors.AddErrors(MigrationOptions.Validate(nameof(MigrationOptions))); errors.AddErrors(AuthOptions.Validate(nameof(AuthOptions))); errors.AddErrors(SmtpEMailOptions.Validate(nameof(SmtpEMailOptions))); errors.AddErrors(TempFiles.Validate(nameof(TempFiles))); return(errors); }
public void Run() { try { this.StartSafetyNet(); //watch instance numbers TempFiles.StartTempFileWatcher(); //watch temp directory on a diff schedule this._timeline = TimelineBuilder.GetLocalTimeline(); // now watch that file for changes FileSystemWatcher timelineWatcher = new FileSystemWatcher(TimelineBuilder.TimelineFilePath().DirectoryName) { Filter = Path.GetFileName(TimelineBuilder.TimelineFilePath().Name) }; _log.Trace($"watching {timelineWatcher.Path}"); timelineWatcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.CreationTime | NotifyFilters.LastWrite; timelineWatcher.EnableRaisingEvents = true; timelineWatcher.Changed += new FileSystemEventHandler(OnChanged); _threadJobs = new List <ThreadJob>(); //load into an managing object //which passes the timeline commands to handlers //and creates a thread to execute instructions over that timeline if (this._timeline.Status == Timeline.TimelineStatus.Run) { RunEx(this._timeline); } else { if (MonitorThread != null) { MonitorThread.Abort(); MonitorThread = null; } } } catch (Exception e) { _log.Error($"Orchestrator.Run exception: {e}"); } }
public bool AddMenSelmapMark(string path, bool ask) { string tmp = null; if (path.EndsWith(".tex0", StringComparison.InvariantCultureIgnoreCase)) { tmp = TempFiles.Create(".png"); NodeFactory.FromFile(null, path).Export(tmp); } Bitmap bitmap = new Bitmap(tmp ?? path); if (BitmapUtilities.HasSolidCorners(bitmap)) { bitmap = BitmapUtilities.AlphaSwap(bitmap); } string name = Path.GetFileNameWithoutExtension(path); if (ask) { using (var nameDialog = new AskNameDialog(bitmap)) { nameDialog.Text = name; if (nameDialog.ShowDialog() != DialogResult.OK) { return(false); } else { name = nameDialog.NameText; } } } BRRESNode bres = sc_selmap.FindChild("MiscData[80]", false) as BRRESNode; TEX0Node tex0 = bres.CreateResource <TEX0Node>(name); ReplaceSelmapMark(bitmap, tex0, true); return(true); }
internal override void Initialize() { try { #pragma warning disable CS0436 // Type conflicts with imported type //SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory); #pragma warning restore CS0436 // Type conflicts with imported type OnBeforeInitialize(); var od = OriginalSqlDatabase <TDbContext> .GetInstance(() => Version); TempFiles.Add(od.DbFile); TempFiles.Add(od.LogFile); DBName = od.DBName; ConnectionString = (new SqlConnectionStringBuilder() { DataSource = "(localdb)\\MSSQLLocalDB", //sqlCnstr.AttachDBFilename = t; InitialCatalog = od.DBName, IntegratedSecurity = true, ApplicationName = "EntityFramework" }).ToString(); } catch (Exception ex) { WriteLine(ex.ToString()); throw; } }
public ParseDirective_Password_Tests(ITestOutputHelper output) { Ambient.Output = output; _tempFiles = new TempFiles(output.WriteLine); }
/// <summary> /// 分块断点续传,多文件 /// </summary> /// <param name="request"></param> /// <returns></returns> private object UploadFileByChunk(HttpRequestBase request) { //断点续传 string app = Request["app"]; string name = Request["name"]; int fId = Request["fId"].ToInt32Req(); int chunk = Request["chunk"].ToInt32Req(); //当前分块 int chunks = Request["chunks"].ToInt32Req(); //总的分块数量 // 是否上传模型 string bim = request["isbim"]; bool isbim = "true".Equals((string.IsNullOrWhiteSpace(bim) ? "false" : bim).ToLower()); foreach (string file in Request.Files) { if (!string.IsNullOrEmpty(file)) { using (ClientProxyFileServer proxy = new ClientProxyFileServer(ProxyEx(Request))) { //取得文件对比信息 FileGuid fg = proxy.GetFileGuid(fId).Data; HttpPostedFileBase postedFile = Request.Files[file]; //获取客户端上载文件的集合 string fileName = Path.GetFileNameWithoutExtension(name); //获取客户端上传文件的名称 string extensionName = Path.GetExtension(name).ToLower(); //获取客户端上传文件的后缀 string newFileName = name; //获取文件存储目录 var configList = proxy.GetConfig(app); FileConfig config = null; if (isbim) { config = configList.Data.FirstOrDefault(i => i.FileTypeDirectory == "model"); } else { config = configList.Data.FirstOrDefault(i => i.FileTypeExtension.Contains(extensionName) && i.FileTypeDirectory != "model"); } if (config == null) { config = configList.Data.FirstOrDefault(i => i.FileTypeExtension.Contains(".*")); //return (new { flag = false, result = "不允许上传此类型的文件" }); } var pathList = CreatePath(config); string tempPath = pathList[0]; string filePath = pathList[1]; //分块 if (chunks > 1) { newFileName = chunk + "_" + GetRamCode() + "_" + fileName + extensionName; //按文件块重命名块文件 } string chunkPath = tempPath + "\\" + newFileName; //将块文件和临时文件夹路径绑定 postedFile.SaveAs(chunkPath); //保存临时块上载文件内容 //临时块文件入库 FileInfo chunkFile = new FileInfo(chunkPath); TempFiles tf = new TempFiles(); tf.App = app; tf.Chunk = chunk; tf.ChunkName = newFileName; tf.ChunkPath = chunkPath; tf.Chunks = chunks; tf.ChunkSize = (int)chunkFile.Length; tf.FileGuid = Guid.NewGuid().ToString(); tf.FileLastModifiedDate = fg.LastModifiedDate; tf.FileName = name; tf.FileSize = fg.FileSize; tf.UploadTime = DateTime.Now; tf.RequetURL = Request.UrlReferrer.ToString(); tf.IP = request.UserHostAddress; tf.Browser = request.Browser.Browser; //TODO:可以在此处获取每一个块文件的md5在检测是否可以续传时返回少一个块文件的长度,然后对比续传的第一个块的md5来实现去重 tf = proxy.AddTempFile(tf).Data; //最后一个块,执行合并 if (chunks > 1 && chunk + 1 == chunks) { var tempFiles = proxy.GetTempFiles(app, name, fg.LastModifiedDate, fg.FileSize); var fileList = tempFiles.Data.OrderBy(i => i.Chunk); string reName = Guid.NewGuid().ToString() + name; string fullPath = filePath + "\\" + reName; using (FileStream fsw = new FileStream(fullPath, FileMode.Create, FileAccess.Write)) { BinaryWriter bw = new BinaryWriter(fsw); // 遍历文件合并 foreach (var temp in fileList) { //打开一个文件读取流信息,将其写入新文件 bw.Write(System.IO.File.ReadAllBytes(temp.ChunkPath)); System.IO.File.Delete(temp.ChunkPath); //删除临时块文件信息,以避免临时文件越来越大 bw.Flush(); //清理缓冲区 } } //正式文件入库 Files sf = new Files(); sf.App = app; sf.Day = DateTime.Now.ToString("yyyyMMdd").ToInt32Req();; sf.Extension = extensionName; sf.FilePath = fullPath; sf.FileSize = fg.FileSize; sf.FileType = config.FileTypeName; sf.Guid = fg.FId; sf.IsDelete = false; sf.LastModifiedDate = fg.LastModifiedDate; sf.Month = DateTime.Now.ToString("yyyyMM").ToInt32Req();; sf.Name = name; sf.ReName = reName; sf.RequetURL = Request.UrlReferrer.ToString(); sf.UploadTime = DateTime.Now; sf.Year = DateTime.Now.Year; sf.UserDescription = ""; sf.IP = request.UserHostAddress; sf.Browser = request.Browser.Browser; string md5 = GetMD5HashFromFile(fullPath); sf.MD5 = md5; sf.VirtualURL = (filePath.Replace(config.ParentPath, "/").Replace("\\", "/") + "/" + reName); sf = proxy.AddFile(sf).Data; //删除临时块文件信息 proxy.DeleteTempFile(fileList.Select(i => i.Id).ToList()); //删除fileguid对比信息 proxy.DeleteFileGuid(fg); return(new { flag = true, type = "file", file = sf }); } return(new { flag = true, type = "chunk", chunk = tf }); } } } return(new { flag = false, result = "文件上传失败" }); }
/// <summary> /// Generates the audio book. /// </summary> /// <param name="dictionary">The dictionary.</param> /// <param name="audiobook">The target audiobook file.</param> /// <param name="options">The options.</param> /// <param name="worker">The worker.</param> /// <param name="codecs">The codecs.</param> /// <remarks>Documented by Dev02, 2008-03-10</remarks> public static void GenerateAudioBook(IDictionary dictionary, FileInfo audiobook, AudioBookOptions options, Codecs codecs) { if (workerthread != null && workerthread.IsAlive) { AddLog("Error: Another operation is still active."); return; } workerthread = new Thread(delegate() { try { Dictionary <string, Codec> encodeCodecs = codecs.encodeCodecs; Dictionary <string, Codec> decodeCodecs = codecs.decodeCodecs; if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant() && !encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { AddLog(string.Format("Specified extension ({0}) is not available => Check encoder settings", audiobook.Extension.ToLowerInvariant())); return; } List <MediaFieldFile> sourcefiles = new List <MediaFieldFile>(); //source files from dictionary Environment.CurrentDirectory = new FileInfo(dictionary.Connection).Directory.FullName; //fetch source audio files AddLog("Fetching source audio files"); int count = dictionary.Cards.Cards.Count; int index = 0; foreach (ICard card in dictionary.Cards.Cards) { sourcefiles.AddRange(GetCardMediaFiles(card, options.MediaFields)); ReportProgress(index++, count); } //search and generate a new temp folder DirectoryInfo tempfolder; int tempfolderindex = 0; do { tempfolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Settings.Default.TempFolderPath + tempfolderindex.ToString())); tempfolderindex++; } while (tempfolder.Exists); tempfolder.Create(); try { //convert all source files to wave where necessary AddLog("Converting source files"); bool foundfile = false; count = sourcefiles.Count; index = 0; for (int i = 0; i < sourcefiles.Count; i++) { if (sourcefiles[i].ContainsFile && decodeCodecs.ContainsKey(sourcefiles[i].Extension)) { //decode file string filename = sourcefiles[i].file.Name; sourcefiles[i].file = decodeCodecs[sourcefiles[i].Extension].Decode(sourcefiles[i].file, tempfolder, Settings.Default.ShowDecodingWindow, Settings.Default.MimimizeWindows); if (sourcefiles[i].ContainsFile) { foundfile = true; } else { AddLog(string.Format("Decoding ({0}) did not produce a file => Check decoder settings", filename)); } } else if (sourcefiles[i].ContainsFile && sourcefiles[i].Extension == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { foundfile = true; } else if (sourcefiles[i].ContainsFile) { AddLog(string.Format("Extension {0} not supported ({1}) => Check decoder settings", sourcefiles[i].Extension, sourcefiles[i].file.Name)); } ReportProgress(index++, count); } if (!foundfile) { AddLog("No supported audio files found in the selected fields of the learning module"); ReportProgress(0, 0); //disable progress reporting } else { //concatenate all wave files AddLog("Joining audio files"); FileInfo audiobookwave = new FileInfo(Path.Combine(tempfolder.FullName, Resources.AUDIOBOOK_DEFAULTNAME + Resources.AUDIO_WAVE_EXTENSION)); ABWaveCat wavecat = new ABWaveCat(); wavecat.Concatenate(sourcefiles, audiobookwave, options.Stereo); ReportProgress(0, 0); //disable progress reporting bool changeToWaveExtension = true; //fix for [MLA-1272] error message for file path without extension if (audiobook.Extension.ToLowerInvariant() != Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { if (encodeCodecs.ContainsKey(audiobook.Extension.ToLowerInvariant())) { //convert audiobook to specified format AddLog("Converting audiobook"); FileInfo encodedfile = encodeCodecs[audiobook.Extension.ToLowerInvariant()].Encode(audiobookwave, tempfolder, Settings.Default.ShowEncodingWindow, Settings.Default.MimimizeWindows); if (encodedfile != null) { try { if (audiobook.Exists) { audiobook.Delete(); } encodedfile.MoveTo(audiobook.FullName); changeToWaveExtension = false; } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } else { AddLog(string.Format("Encoding ({0}) did not produce a file => Check encoder settings", audiobook.Name)); } } } if (changeToWaveExtension) //change file to wave extension and force wave generation { audiobook = new FileInfo(Path.ChangeExtension(audiobook.FullName, Resources.AUDIO_WAVE_EXTENSION)); } if (audiobook.Extension.ToLowerInvariant() == Resources.AUDIO_WAVE_EXTENSION.ToLowerInvariant()) { try { if (audiobook.Exists) { audiobook.Delete(); } audiobookwave.MoveTo(audiobook.FullName); } catch (Exception e) { AddLog("Could not replace audio file: " + e.Message); return; } } AddLog("Finished: " + audiobook.FullName); } } finally { //try to delete the temp directory (try multiple times in case it is still locked) Thread cleanthread = new Thread(delegate() { int tries = 0; while (tries++ < 10) { System.Threading.Thread.Sleep(1000); try { tempfolder.Delete(true); TempFiles.ForEach(f => f.Delete()); break; } catch { } } }); cleanthread.IsBackground = true; cleanthread.Start(); } } catch (Exception exp) { ReportProgress(0, 0); //disable progressbar if (exp is ThreadAbortException) { AddLog("Operation cancelled"); } else { AddLog("GenerateAudioBook Thread Exception: " + exp.ToString()); } } finally { //fire the working thread finished event in every case OnWorkingThreadFinished(EventArgs.Empty); } }); workerthread.IsBackground = true; workerthread.Start(); return; }
/// <summary> /// Formatiert den Wert der aktuellen Instanz unter Verwendung des angegebenen Formats. /// </summary> /// <returns> /// Der Wert der aktuellen Instanz im angegebenen Format. /// </returns> /// <param name="format">Das zu verwendende Format.– oder – Ein NULL-Verweis (Nothing in Visual Basic), /// wenn das für den Typ der <see cref="T:System.IFormattable"/> -Implementierung definierte Standardformat verwendet werden soll. </param> /// <param name="formatProvider">Der zum Formatieren des Werts zu verwendende Anbieter.– oder – Ein NULL-Verweis (Nothing in Visual Basic), /// wenn die Informationen über numerische Formate dem aktuellen Gebietsschema des Betriebssystems entnommen werden sollen. </param> /// <filterpriority>2</filterpriority> public string ToString(string format, IFormatProvider formatProvider) { string result = string.Empty; result += string.Format(AppSettings.CInfo, "JobName: {0:s} {1:s}", JobName, Environment.NewLine); result += string.Format(AppSettings.CInfo, "BaseName: {0:s} {1:s}", BaseName, Environment.NewLine); result += string.Format(AppSettings.CInfo, "InputFile: {0:s} {1:s}", InputFile, Environment.NewLine); result += string.Format(AppSettings.CInfo, "InputType: {0:s} {1:s}", Input.ToString(), Environment.NewLine); result += string.Format(AppSettings.CInfo, "OutputFile: {0:s} {1:s}", OutputFile, Environment.NewLine); result += Environment.NewLine; result += string.Format(AppSettings.CInfo, "AudioStreams: {0:s}", Environment.NewLine); result = AudioStreams.Aggregate(result, (current, item) => current + string.Format(AppSettings.CInfo, "{0:s} {1:s}", item, Environment.NewLine)); result += Environment.NewLine; result += string.Format(AppSettings.CInfo, "SubtitleStreams: {0:s}", Environment.NewLine); result = SubtitleStreams.Aggregate(result, (current, item) => current + string.Format(AppSettings.CInfo, "{0:s} {1:s}", item, Environment.NewLine)); result += Environment.NewLine; result += string.Format(AppSettings.CInfo, "Chapters: {0:s} {1:s}", string.Join(",", (from item in Chapters let dt = new DateTime() select DateTime.MinValue.Add(item) into dt select dt.ToString("H:mm:ss.fff")).ToArray()), Environment.NewLine); result += string.Format(AppSettings.CInfo, "NextStep: {0:s} {1:s}", NextStep.ToString(), Environment.NewLine); result += string.Format(AppSettings.CInfo, "CompletedStep: {0:s} {1:s}", CompletedStep.ToString(), Environment.NewLine); result += Environment.NewLine; result += string.Format(AppSettings.CInfo, "VideoStream: {0:s}", Environment.NewLine); result += string.Format(AppSettings.CInfo, "{0:s} {1:s}", VideoStream, Environment.NewLine); result += Environment.NewLine; result += string.Format(AppSettings.CInfo, "StreamID: {0:g} {1:s}", StreamId, Environment.NewLine); result += string.Format(AppSettings.CInfo, "TrackID: {0:g} {1:s}", TrackId, Environment.NewLine); result += string.Format(AppSettings.CInfo, "TempInput: {0:s} {1:s}", TempInput, Environment.NewLine); result += string.Format(AppSettings.CInfo, "TempOutput: {0:s} {1:s}", TempOutput, Environment.NewLine); result += string.Format(AppSettings.CInfo, "DumpOutput: {0:s} {1:s}", DumpOutput, Environment.NewLine); result += string.Format(AppSettings.CInfo, "SelectedDVDChapters:{0:s} {1:s}", SelectedDvdChapters, Environment.NewLine); result += string.Format(AppSettings.CInfo, "TempFiles: {0:s} {1:s}", string.Join(",", TempFiles.ToArray()), Environment.NewLine); result += string.Format(AppSettings.CInfo, "ReturnValue: {0:g} {1:s}", ExitCode, Environment.NewLine); return(result); }
public ParseReporter_InputValues_Tests(ITestOutputHelper output) { _output = output; _tempFiles = new TempFiles(_output.AsLogger()); }
public ParseReporter_InputValues_Tests(ITestOutputHelper output) { Ambient.Output = output; _tempFiles = new TempFiles(output.WriteLine); }
public void copyIconsToSelcharacter2() { string fileToSaveTo = null; ResourceNode s2 = null; if (common5 != null) { s2 = common5.FindChild("sc_selcharacter2_en", false); } else if (sc_selmap != null) { if (File.Exists("../../menu2/sc_selcharacter2.pac")) { fileToSaveTo = "../../menu2/sc_selcharacter2.pac"; s2 = TempFiles.MakeTempNode(fileToSaveTo); } else if (File.Exists("../../menu2/sc_selcharacter2_en.pac")) { fileToSaveTo = "../../menu2/sc_selcharacter2_en.pac"; s2 = TempFiles.MakeTempNode(fileToSaveTo); } } if (s2 == null) { return; } ResourceNode md0 = s2.FindChild("MenuRule_en/ModelData[0]", false); MSBinNode md1 = s2.FindChild("MenuRule_en/MiscData[1]", false) as MSBinNode; ResourceNode md80 = sc_selmap.FindChild("MiscData[80]", false); if (md0 == null || md80 == null) { return; } Image[] icons = new Image[41]; Image[] frontstnames = new Image[41]; for (int i = 1; i < 60; i++) { if (i == 32) { i = 50; } int sssPos = StageIDMap.sssPositionForSelcharacter2Icon(i); string nameSelmap = BestSSS[sssPos].Item2.ToString("D2"); icons[sssPos] = ((md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node).GetImage(0)); frontstnames[sssPos] = ((md80.FindChild("Textures(NW4R)/MenSelmapFrontStname." + nameSelmap, false) as TEX0Node).GetImage(0)); } var d = new RandomSelectEditNamesDialog(md1._strings, icons, frontstnames); d.Message = "When finished, press OK to continue."; if (d.ShowDialog() == DialogResult.OK) { for (int i = 0; i < md1._strings.Count; i++) { md1._strings[i] = d[i].ToString(); } } else { return; } using (ProgressWindow w = new ProgressWindow() { CanCancel = false }) { w.Begin(0, 60, 0); for (int i = 1; i < 60; i++) { if (i == 32) { i = 50; } int sssPos = StageIDMap.sssPositionForSelcharacter2Icon(i); string tempFile1 = TempFiles.Create(".tex0"); string tempFile2 = TempFiles.Create(".plt0"); string nameSelcharacter2 = i.ToString("D2"); string nameSelmap = BestSSS[sssPos].Item2.ToString("D2"); TEX0Node iconFrom = md80.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelmap, false) as TEX0Node; TEX0Node iconTo = md0.FindChild("Textures(NW4R)/MenSelmapIcon." + nameSelcharacter2, false) as TEX0Node; var palFrom = md80.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelmap, false); var palTo = md0.FindChild("Palettes(NW4R)/MenSelmapIcon." + nameSelcharacter2, false); if (iconFrom != null && iconTo != null && palFrom != null && palTo != null) { iconFrom.Export(tempFile1); iconTo.Replace(tempFile1); palFrom.Export(tempFile2); palTo.Replace(tempFile2); } TEX0Node prevbase = md80.FindChild("Textures(NW4R)/MenSelmapPrevbase." + nameSelmap, false) as TEX0Node; TEX0Node stageswitch = md0.FindChild("Textures(NW4R)/MenStageSwitch." + nameSelcharacter2, false) as TEX0Node; if (prevbase != null && stageswitch != null) { Bitmap thumbnail = new Bitmap(112, 56); using (Graphics g = Graphics.FromImage(thumbnail)) { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(prevbase.GetImage(0), 0, -28, 112, 112); } stageswitch.Replace(thumbnail); } w.Update(i); } } if (fileToSaveTo != null) { s2.Export(fileToSaveTo); } }
public static void Copy(ResourceNode scSelmap, ResourceNode muMenumain, CustomSSSCodeset sss) { ResourceNode miscData0 = muMenumain.FindChild("Misc Data [0]", false); List <ResourceNode> chrToKeep = miscData0.FindChild("AnmChr(NW4R)", false).Children; Dictionary <string, string> tempFiles = new Dictionary <string, string>(chrToKeep.Count); foreach (ResourceNode n in chrToKeep) { string file = TempFiles.Create(".chr0"); tempFiles.Add(n.Name, file); n.Export(file); } ResourceNode miscData80 = scSelmap.FindChild("Misc Data [80]", false); miscData0.ReplaceRaw(miscData80.WorkingSource.Address, miscData80.WorkingSource.Length); miscData0.SignalPropertyChange(); List <ResourceNode> chrToReplace = miscData0.FindChild("AnmChr(NW4R)", false).Children; foreach (ResourceNode n in chrToReplace) { string file = tempFiles[n.Name]; n.Replace(file); } string xx_png = TempFiles.Create(".png"); ResourceNode xx = miscData0.FindChild("Textures(NW4R)/MenSelmapIcon.XX", false); bool found = false; if (xx != null) { xx.Export(xx_png); found = true; } else { Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BrawlCrate.StageManager.XX.png"); if (stream != null) { Image.FromStream(stream).Save(xx_png); found = true; } } if (found) { foreach (ResourceNode tex in miscData0.FindChild("Textures(NW4R)", false).Children) { byte icon_id; if (tex.Name.StartsWith("MenSelmapIcon.") && byte.TryParse(tex.Name.Substring(14, 2), out icon_id)) { byte stage_id = sss.StageForIcon(icon_id); if (icon_id != 100 && (stage_id == 0x25 || stage_id > 0x33)) { tex.Replace(xx_png); } } } } File.Delete(xx_png); }