internal static WebFile UploadFile(HttpPostedFileBase file, UploadResults uploadResults, ApplicationDbContext db, HttpContextBase context, Settings settings) { string tempfile = GetTempFileName(file.FileName, settings); file.SaveAs(tempfile); return(UploadFileCore(tempfile, file.FileName, uploadResults, db, context)); }
internal static WebFile UploadFile(byte[] bytes, string fileName, UploadResults uploadResults, ApplicationDbContext db, HttpContextBase context, Settings settings) { string tempfile = GetTempFileName(fileName, settings); System.IO.File.WriteAllBytes(tempfile, bytes); return(UploadFileCore(tempfile, fileName, uploadResults, db, context)); }
private WebFile UploadImage(HttpPostedFileBase file, UploadResults uploadResults) { var webfile = UploadFile(file, uploadResults, db, HttpContext, Settings); if (uploadResults.status == UploadResults.OK) { webfile.PreviewLocation = "/" + CreateThumbnail(Server.MapPath(webfile.Location)).ToAppPath(HttpContext); } return(webfile); }
public UploadResults UploadFile() { try { //try upload return(UploadResults.Succeeded()); } catch (Exception ex) { return(UploadResults.Failed(ex)); } }
public async Task <UploadResults> Upload(IEnumerable <MatchInfo> incoming) { IEnumerable <MatchInfo> toUpload = incoming .Where(b => b.IsSelected); UploadResults newResults = await UploadNewBooks(toUpload); UploadResults fileResults = await UploadNewFiles(toUpload); return(new UploadResults { Uploaded = newResults.Uploaded + fileResults.Uploaded, Errors = newResults.Errors + fileResults.Errors }); }
public async Task <bool> UpdateSummary(UploadResult summary) { var update = await UploadResults.SingleOrDefaultAsync(t => t.UploadResultId == summary.UploadResultId); if (update == null) { return(false); } update.Status = summary.Status; update.ReadingsFailed = summary.ReadingsFailed; update.ReadingsStored = summary.ReadingsStored; return(await SaveChangesAsync() == 1); }
async Task DoUpload() { _messageListener.Write("Upload: starting"); this.IsBusy = true; var uploader = new Uploader(this.SelectedFullDataSourceInfo.GetFullDataSource(), _simpleDataSource, _exceptionHandler); uploader.DateAddedText = DateAddedText; UploadResults results = await uploader.Upload(this.BookFileList); this.IsBusy = false; _messageListener.Write("Upload: uploaded {0} books ({1} errors)", results.Uploaded, results.Errors); }
private WebFile UploadDocument(HttpPostedFileBase file, UploadResults uploadResults) { WebFile webfile = UploadFile(file, uploadResults, db, HttpContext, Settings); string docFile = Server.MapPath(webfile.Location); string pdfFile = Path.ChangeExtension(docFile, ".pdf"); bool createPdf = !docFile.Equals(pdfFile, StringComparison.InvariantCultureIgnoreCase); if (createPdf && uploadResults.status == UploadResults.OK && Settings.CreatePDFVersionsOfDocuments) { DocumentHelper.CreatePDF(Settings.ConvertPdfExe, docFile, pdfFile, true); } if (System.IO.File.Exists(pdfFile)) { webfile.PreviewLocation = "/" + CreatePdfThumbnail(pdfFile).ToAppPath(HttpContext); } return(webfile); }
public async void SelectUploadImages() { var dlg = new OpenFileDialog { DefaultExt = ".jpg", InitialDirectory = AppDomain.CurrentDomain.BaseDirectory, Filter = "Images (.jpg)|*.jpg", Multiselect = true }; var result = dlg.ShowDialog(); if (result != true) { return; } foreach (var group in dlg.SafeFileNames.Where(s => s.EndsWith("pl.jpg"))) { var uploadInfo = new UploadInfo(@group.Substring(0, @group.Length - 6)); UploadResults.Add(uploadInfo); uploadInfo.UploadList = new List <UploadImage>(); foreach (var image in dlg.FileNames.Where(s => s.IndexOf(uploadInfo.Id, StringComparison.OrdinalIgnoreCase) >= 0)) { var uploadImage = new UploadImage { Name = Path.GetFileName(image), Path = image, Data = File.ReadAllBytes(image) }; if (image.EndsWith("pl.jpg")) { uploadInfo.UploadList.Insert(0, uploadImage); } else { uploadInfo.UploadList.Add(uploadImage); } } } }
private UploadResults ParseResponse(string xml) { UploadResults results = new UploadResults(); using (XmlReader reader = XmlReader.Create(new StringReader(xml))) { string lastNodeName = ""; reader.ReadToFollowing("links"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { lastNodeName = reader.Name; } if (reader.NodeType == XmlNodeType.Text) { switch (lastNodeName) { case "original": results.original = reader.Value; break; case "imgur_page": results.imgur_page = reader.Value; continue; case "delete_page": results.delete_page = reader.Value; continue; default: break; } lastNodeName = ""; } } return(results); } }
private static WebFile UploadFileCore(string filePath, string fileName, UploadResults uploadResults, ApplicationDbContext db, HttpContextBase context) { WebFile webfile = db.WebFiles.Create(); if (System.IO.File.Exists(filePath)) { string FileUrl = FileStorage.Save(new FileInfo(filePath), context); webfile.Location = FileUrl; webfile.Name = Path.GetFileNameWithoutExtension(fileName); webfile.Size = (new FileInfo(filePath)).Length; uploadResults.status = UploadResults.OK; } else { uploadResults.status = UploadResults.Failed; uploadResults.message = "The file could not be saved."; } return(webfile); }
public void RemoveAll() { UploadResults.Clear(); }
public void RemoveItem() { UploadResults.RemoveRange(SelectedUploadInfos); }
public async void Upload() { if (!UploadResults.Any()) { return; } IsUploadFinished = false; Message = ""; Blogger.StartPosting(); UploadInfo.RemoveSignature(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\west.txt"); UploadInfo.RemoveSignature(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\west_pornbb.txt"); var rnd = new Random(); foreach (var uploadInfo in UploadResults) { var megaLinks = MEGA.GetEnabled ? await MEGA.GetLinks(uploadInfo.Id) : Enumerable.Empty <string>(); var rapidgatorLinks = Rapidgator.GetEnabled ? await Rapidgator.GetLinks(uploadInfo.Id) : Enumerable.Empty <string>(); if (MEGA.GetEnabled && !megaLinks.Any()) { uploadInfo.Id += "\n(No MEGA links!)"; continue; } if (Rapidgator.GetEnabled && !rapidgatorLinks.Any()) { uploadInfo.Id += "\n(No Rapidgator links!)"; continue; } if (MEGA.GetEnabled && Rapidgator.GetEnabled && megaLinks.Count() != rapidgatorLinks.Count()) { uploadInfo.Id += "\n(Missing some Mega/Rapidgator links!)"; continue; } // TODO: refactor var zippyshareLinks = Enumerable.Empty <string>(); var linkSuccess = true; foreach (var fileHost in FileHosts) { if (!fileHost.Enabled) { continue; } var links = await fileHost.GetLinks(uploadInfo.Id); if (!links.Any()) { uploadInfo.Id += $"\n(No {fileHost.Name} links!)"; linkSuccess = false; break; } if (MEGA.GetEnabled && megaLinks.Count() != links.Count) { uploadInfo.Id += $"\n(Missing some Mega/{fileHost.Name} links!)"; linkSuccess = false; break; } zippyshareLinks = links; } if (!linkSuccess) { continue; } var uploadTasks = new List <Task <List <string> > >(); if (ImgChili.LoggedIn && ImgChili.Enabled) { uploadTasks.Add(ImgChili.Upload(uploadInfo.UploadList)); } if (ImgRock.LoggedIn && ImgRock.Enabled) { uploadTasks.Add(ImgRock.Upload(uploadInfo.UploadList)); } if (PixSense.LoggedIn && PixSense.Enabled) { uploadTasks.Add(PixSense.Upload(uploadInfo.UploadList)); } var taskCount = uploadTasks.Count; var uploadCount = 0; while (uploadTasks.Count > 0) { try { var finishedTask = await Task.WhenAny(uploadTasks); uploadTasks.Remove(finishedTask); var links = await Task.Run(() => finishedTask); if (links == null) { continue; } if (links[0].Contains("imgchili")) { uploadInfo.WebLinks1 = links[0].Trim(); uploadInfo.ForumLinks1 = ToLowerForumCode(links[1].Trim()); uploadCount++; } else if (links[0].Contains("imgrock")) { uploadInfo.WebLinks2 = links[0].Trim(); uploadInfo.ForumLinks2 = links[1].Trim(); uploadCount++; } else if (links[0].Contains("pixsense") || links[0].Contains("iceimg") || links[0].Contains("imgvip")) { uploadInfo.WebLinks3 = links[0].Trim(); uploadInfo.ForumLinks3 = links[1].Trim(); uploadCount++; } } catch (Exception ex) { if (ex.Message.Contains(ImgChili.Name)) { uploadInfo.WarningBrush1 = Brushes.Red; } else if (ex.Message.Contains(ImgRock.Name)) { uploadInfo.WarningBrush2 = Brushes.Red; } else if (ex.Message.Contains(PixSense.Name)) { uploadInfo.WarningBrush3 = Brushes.Red; } uploadInfo.IdColor = Colors.Red; Message = ex.InnerException.Message; } } try { if (Rapidgator.GetEnabled) { await uploadInfo.WriteOutput(string.Join("\\n", megaLinks), string.Join("\\n", rapidgatorLinks)); } else if (Zippyshare.Enabled) { await uploadInfo.WriteOutput(string.Join("\\n", megaLinks), string.Join("\\n", zippyshareLinks)); } else { await uploadInfo.WriteOutput(string.Join("\\n", megaLinks), string.Join("\\n", rapidgatorLinks)); } } catch (Exception ex) { Logger.Error(string.Format("Failed to write output: {0}", uploadInfo.Id), ex); if (ex.InnerException != null) { Logger.Error(string.Format("Failed to write output (InnerException): {0}", uploadInfo.Id), ex.InnerException); } } // Delete or Move images if (uploadCount == taskCount) { foreach (var image in uploadInfo.UploadList) { try { File.Delete(image.Path); } catch (Exception ex) { Logger.Error(string.Format("Failed to delete images: {0}", uploadInfo.Id), ex); } } } else { foreach (var image in uploadInfo.UploadList) { try { var dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Handled"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } File.Move(image.Path, Path.Combine(dir, Path.GetFileName(image.Path))); } catch (Exception ex) { Logger.ErrorException(string.Format("Failed to move images: {0}", uploadInfo.Id), ex); } } } // Move files foreach (var path in UploadInfo.UploadPaths) { if (!Directory.Exists(path)) { continue; } var files = Directory.GetFiles(path, string.Format("{0}*.part*.rar", uploadInfo.Id), SearchOption.TopDirectoryOnly); foreach (var file in files) { var fileInfo = new FileInfo(file); var donePath = Path.Combine(fileInfo.DirectoryName, "Done"); if (!Directory.Exists(donePath)) { Directory.CreateDirectory(donePath); } try { File.Move(file, Path.Combine(donePath, fileInfo.Name)); } catch (IOException) { break; } } if (files.Any()) { break; } } SpinWait.SpinUntil(() => false, rnd.Next(600, 1200)); } UploadInfo.WriteSignature(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\west.txt"); UploadInfo.WriteSignature(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + @"\west_pornbb.txt"); IsUploadFinished = true; Message = "Upload done"; }
private static void GenerateFiles(ParsedEvtcLog log, OperationController operation, string[] uploadStrings, FileInfo fInfo) { operation.UpdateProgressWithCancellationCheck("Creating File(s)"); DirectoryInfo saveDirectory = GetSaveDirectory(fInfo); string result = log.FightData.Success ? "kill" : "fail"; string encounterLengthTerm = Properties.Settings.Default.AddDuration ? "_" + (log.FightData.FightDuration / 1000).ToString() + "s" : ""; string PoVClassTerm = Properties.Settings.Default.AddPoVProf ? "_" + log.LogData.PoV.Spec.ToString().ToLower() : ""; string fName = fInfo.Name.Split('.')[0]; fName = $"{fName}{PoVClassTerm}_{log.FightData.Logic.Extension}{encounterLengthTerm}_{result}"; var uploadResults = new UploadResults(uploadStrings[0], uploadStrings[1]); if (Properties.Settings.Default.SaveOutHTML) { operation.UpdateProgressWithCancellationCheck("Creating HTML"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.html" ); operation.GeneratedFiles.Add(outputFile); operation.OpenableFiles.Add(outputFile); operation.OutLocation = saveDirectory.FullName; using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) using (var sw = new StreamWriter(fs)) { var builder = new HTMLBuilder(log, new HTMLSettings( Properties.Settings.Default.LightTheme, Properties.Settings.Default.HtmlExternalScripts, Properties.Settings.Default.HtmlExternalScriptsPath, Properties.Settings.Default.HtmlExternalScriptsCdn, Properties.Settings.Default.HtmlCompressJson ), htmlAssets, ParserVersion, uploadResults); builder.CreateHTML(sw, saveDirectory.FullName); } operation.UpdateProgressWithCancellationCheck("HTML created"); } if (Properties.Settings.Default.SaveOutCSV) { operation.UpdateProgressWithCancellationCheck("Creating CSV"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.csv" ); operation.GeneratedFiles.Add(outputFile); operation.OpenableFiles.Add(outputFile); operation.OutLocation = saveDirectory.FullName; using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1252))) { var builder = new CSVBuilder(log, new CSVSettings(","), ParserVersion, uploadResults); builder.CreateCSV(sw); } operation.UpdateProgressWithCancellationCheck("CSV created"); } if (Properties.Settings.Default.SaveOutJSON || Properties.Settings.Default.SaveOutXML) { var builder = new RawFormatBuilder(log, new RawFormatSettings(Properties.Settings.Default.RawTimelineArrays), ParserVersion, uploadResults); if (Properties.Settings.Default.SaveOutJSON) { operation.UpdateProgressWithCancellationCheck("Creating JSON"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.json" ); operation.OutLocation = saveDirectory.FullName; Stream str; if (Properties.Settings.Default.CompressRaw) { str = new MemoryStream(); } else { str = new FileStream(outputFile, FileMode.Create, FileAccess.Write); } using (var sw = new StreamWriter(str, NoBOMEncodingUTF8)) { builder.CreateJSON(sw, Properties.Settings.Default.IndentJSON); } if (str is MemoryStream msr) { CompressFile(outputFile, msr, operation); operation.UpdateProgressWithCancellationCheck("JSON compressed"); } else { operation.GeneratedFiles.Add(outputFile); } operation.UpdateProgressWithCancellationCheck("JSON created"); } if (Properties.Settings.Default.SaveOutXML) { operation.UpdateProgressWithCancellationCheck("Creating XML"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.xml" ); operation.OutLocation = saveDirectory.FullName; Stream str; if (Properties.Settings.Default.CompressRaw) { str = new MemoryStream(); } else { str = new FileStream(outputFile, FileMode.Create, FileAccess.Write); } using (var sw = new StreamWriter(str, NoBOMEncodingUTF8)) { builder.CreateXML(sw, Properties.Settings.Default.IndentXML); } if (str is MemoryStream msr) { CompressFile(outputFile, msr, operation); operation.UpdateProgressWithCancellationCheck("XML compressed"); } else { operation.GeneratedFiles.Add(outputFile); } operation.UpdateProgressWithCancellationCheck("XML created"); } } operation.UpdateProgressWithCancellationCheck($"Completed parsing for {result}ed {log.FightData.Logic.Extension}"); }
public UploadResults PostImage(Image image, ImageFormat format) { MemoryStream imageDataStream = new MemoryStream(); image.Save(imageDataStream, format); // get the raw bytes byte[] imageDataBytes; imageDataBytes = imageDataStream.ToArray(); // construct the post string string base64img = System.Convert.ToBase64String(imageDataBytes); StringBuilder sb = new StringBuilder(); for (int i = 0; i < base64img.Length; i += MAX_URI_LENGTH) { sb.Append(Uri.EscapeDataString(base64img.Substring(i, Math.Min(MAX_URI_LENGTH, base64img.Length - i)))); } string uploadRequestString = "image=" + sb.ToString() + "&key=" + apiKey; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(POST_URL); webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ServicePoint.Expect100Continue = false; Stream reqStream = webRequest.GetRequestStream(); byte[] reqBuffer = Encoding.UTF8.GetBytes(uploadRequestString); // send the bytes in chunks so we can check the progress int overflow = reqBuffer.Length % UPDATE_CHUNKS; ProgressData progress = new ProgressData(); progress.max_value = reqBuffer.Length; progress.value = 0; int size = UPDATE_CHUNKS; for (int i = 0; i < reqBuffer.Length; i += UPDATE_CHUNKS) { if (i + UPDATE_CHUNKS > reqBuffer.Length - 1) { size = overflow; } reqStream.Write(reqBuffer, i, size); // update the progress progress.value = i + size; if (_uploadprogressUpdateProperty != null) { _uploadprogressUpdateProperty(progress); } } reqStream.Close(); WebResponse response = webRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader responseReader = new StreamReader(responseStream); string responseString = responseReader.ReadToEnd(); UploadResults results = ParseResponse(responseString); if (_uploadCompleteProperty != null) { _uploadCompleteProperty(results); } return(results); }
private static void GenerateFiles(ParsedEvtcLog log, OperationController operation, string[] uploadStrings, FileInfo fInfo) { operation.UpdateProgressWithCancellationCheck("Creating File(s)"); DirectoryInfo saveDirectory = GetSaveDirectory(fInfo); string result = log.FightData.Success ? "kill" : "fail"; string encounterLengthTerm = Properties.Settings.Default.AddDuration ? "_" + (log.FightData.FightDuration / 1000).ToString() + "s" : ""; string PoVClassTerm = Properties.Settings.Default.AddPoVProf ? "_" + log.LogData.PoV.Spec.ToString().ToLower() : ""; string fName = fInfo.Name.Split('.')[0]; fName = $"{fName}{PoVClassTerm}_{log.FightData.Logic.Extension}{encounterLengthTerm}_{result}"; // parallel stuff if (Properties.Settings.Default.MultiThreaded && HasFormat()) { IReadOnlyList <PhaseData> phases = log.FightData.GetPhases(log); operation.UpdateProgressWithCancellationCheck("Multi threading"); var friendliesAndTargets = new List <AbstractSingleActor>(log.Friendlies); friendliesAndTargets.AddRange(log.FightData.Logic.Targets); var friendliesAndTargetsAndMobs = new List <AbstractSingleActor>(log.FightData.Logic.TrashMobs); friendliesAndTargetsAndMobs.AddRange(friendliesAndTargets); foreach (AbstractSingleActor actor in friendliesAndTargetsAndMobs) { // that part can't be // due to buff extensions actor.GetTrackedBuffs(log); actor.GetMinions(log); } Parallel.ForEach(friendliesAndTargets, actor => actor.GetStatus(log)); /*if (log.CombatData.HasMovementData) * { * // init all positions * Parallel.ForEach(friendliesAndTargetsAndMobs, actor => actor.GetCombatReplayPolledPositions(log)); * }*/ Parallel.ForEach(friendliesAndTargetsAndMobs, actor => actor.GetBuffGraphs(log)); Parallel.ForEach(friendliesAndTargets, actor => { foreach (PhaseData phase in phases) { actor.GetBuffDistribution(log, phase.Start, phase.End); } }); Parallel.ForEach(friendliesAndTargets, actor => { foreach (PhaseData phase in phases) { actor.GetBuffPresence(log, phase.Start, phase.End); } }); // //Parallel.ForEach(log.PlayerList, player => player.GetDamageModifierStats(log, null)); Parallel.ForEach(log.Friendlies, actor => { foreach (PhaseData phase in phases) { actor.GetBuffs(BuffEnum.Self, log, phase.Start, phase.End); } }); Parallel.ForEach(log.PlayerList, actor => { foreach (PhaseData phase in phases) { actor.GetBuffs(BuffEnum.Group, log, phase.Start, phase.End); } }); Parallel.ForEach(log.PlayerList, actor => { foreach (PhaseData phase in phases) { actor.GetBuffs(BuffEnum.OffGroup, log, phase.Start, phase.End); } }); Parallel.ForEach(log.PlayerList, actor => { foreach (PhaseData phase in phases) { actor.GetBuffs(BuffEnum.Squad, log, phase.Start, phase.End); } }); Parallel.ForEach(log.FightData.Logic.Targets, actor => { foreach (PhaseData phase in phases) { actor.GetBuffs(BuffEnum.Self, log, phase.Start, phase.End); } }); } var uploadResults = new UploadResults(uploadStrings[0], uploadStrings[1]); if (Properties.Settings.Default.SaveOutHTML) { operation.UpdateProgressWithCancellationCheck("Creating HTML"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.html" ); operation.GeneratedFiles.Add(outputFile); operation.OpenableFiles.Add(outputFile); operation.OutLocation = saveDirectory.FullName; using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) using (var sw = new StreamWriter(fs)) { var builder = new HTMLBuilder(log, new HTMLSettings( Properties.Settings.Default.LightTheme, Properties.Settings.Default.HtmlExternalScripts, Properties.Settings.Default.HtmlExternalScriptsPath, Properties.Settings.Default.HtmlExternalScriptsCdn, Properties.Settings.Default.HtmlCompressJson ), htmlAssets, ParserVersion, uploadResults); builder.CreateHTML(sw, saveDirectory.FullName); } operation.UpdateProgressWithCancellationCheck("HTML created"); } if (Properties.Settings.Default.SaveOutCSV) { operation.UpdateProgressWithCancellationCheck("Creating CSV"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.csv" ); operation.GeneratedFiles.Add(outputFile); operation.OpenableFiles.Add(outputFile); operation.OutLocation = saveDirectory.FullName; using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write)) using (var sw = new StreamWriter(fs, Encoding.GetEncoding(1252))) { var builder = new CSVBuilder(log, new CSVSettings(","), ParserVersion, uploadResults); builder.CreateCSV(sw); } operation.UpdateProgressWithCancellationCheck("CSV created"); } if (Properties.Settings.Default.SaveOutJSON || Properties.Settings.Default.SaveOutXML) { var builder = new RawFormatBuilder(log, new RawFormatSettings(Properties.Settings.Default.RawTimelineArrays), ParserVersion, uploadResults); if (Properties.Settings.Default.SaveOutJSON) { operation.UpdateProgressWithCancellationCheck("Creating JSON"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.json" ); operation.OutLocation = saveDirectory.FullName; Stream str; if (Properties.Settings.Default.CompressRaw) { str = new MemoryStream(); } else { str = new FileStream(outputFile, FileMode.Create, FileAccess.Write); } using (var sw = new StreamWriter(str, NoBOMEncodingUTF8)) { builder.CreateJSON(sw, Properties.Settings.Default.IndentJSON); } if (str is MemoryStream msr) { CompressFile(outputFile, msr, operation); operation.UpdateProgressWithCancellationCheck("JSON compressed"); } else { operation.GeneratedFiles.Add(outputFile); } operation.UpdateProgressWithCancellationCheck("JSON created"); } if (Properties.Settings.Default.SaveOutXML) { operation.UpdateProgressWithCancellationCheck("Creating XML"); string outputFile = Path.Combine( saveDirectory.FullName, $"{fName}.xml" ); operation.OutLocation = saveDirectory.FullName; Stream str; if (Properties.Settings.Default.CompressRaw) { str = new MemoryStream(); } else { str = new FileStream(outputFile, FileMode.Create, FileAccess.Write); } using (var sw = new StreamWriter(str, NoBOMEncodingUTF8)) { builder.CreateXML(sw, Properties.Settings.Default.IndentXML); } if (str is MemoryStream msr) { CompressFile(outputFile, msr, operation); operation.UpdateProgressWithCancellationCheck("XML compressed"); } else { operation.GeneratedFiles.Add(outputFile); } operation.UpdateProgressWithCancellationCheck("XML created"); } } operation.UpdateProgressWithCancellationCheck($"Completed parsing for {result}ed {log.FightData.Logic.Extension}"); }
private UploadResults ParseResponse(string xml) { UploadResults results = new UploadResults(); using (XmlReader reader = XmlReader.Create(new StringReader(xml))) { string lastNodeName = ""; reader.ReadToFollowing("links"); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { lastNodeName = reader.Name; } if (reader.NodeType == XmlNodeType.Text) { switch (lastNodeName) { case "original": results.original = reader.Value; break; case "imgur_page": results.imgur_page = reader.Value; continue; case "delete_page": results.delete_page = reader.Value; continue; default: break; } lastNodeName = ""; } } return results; } }
private WebFile UploadVideoOrAudio(HttpPostedFileBase file, UploadResults uploadResults) { //TODO: Handle video conversion to MP4 and thumbnailing return(UploadFile(file, uploadResults, db, HttpContext, Settings)); }
public async Task <ActionResult> SendToAPIAsync() { var db = new CustomerDB(); ViewBag.SuccessUpload = TempData["SuccessUpload"]; string serverFileName = TempData["ServerFileName"].ToString(); string fileName = TempData["FileName"].ToString(); string filePath = Server.MapPath(Url.Content("~/CSVFiles/" + serverFileName)); var records = System.IO.File.ReadAllLines(filePath); var h = new HttpHandler(); var hashs = new List <string>(); UploadResults model = new UploadResults { RecordsCount = 0, FaildCount = 0, FileName = fileName, SuccessCount = 0 }; #region SendData foreach (var item in records) { if (!string.IsNullOrEmpty(item)) { model.RecordsCount++; //for inCorrect Data Format var detail = new Details(); try { var dt = item.Split(','); detail = new Details { customer = dt[0].Trim(), value = int.Parse(dt[1].Trim()), file = fileName, action = "order created", property = "Mohammad" }; } catch { continue; } //Send Data var responce = await h.SendDetailsToAPIAsync(detail); if (responce.hash.Length > 50) { responce.hash = "NOT Valid Hash"; responce.added = false; } db.CustomersInfoes.Add(new CustomersInfo { customer = detail.customer, value = detail.value, file = detail.file, added = responce.added, errors = string.Join(",", responce.errors.ToArray()), action = detail.action, hash = responce.hash, property = detail.property }); db.SaveChanges(); hashs.Add(responce.hash); } } #endregion SendData hashs = db.CustomersInfoes.Select(o => o.hash).ToList(); //check Customer Data foreach (var hash in hashs) { CustomersInfo responce; try { responce = await h.CheckCustommerAsync(hash); } catch (Exception e) { try { var notfounItem = db.CustomersInfoes.FirstOrDefault(o => o.hash == hash); notfounItem.errors = "Hash not found"; notfounItem.added = false; db.SaveChanges(); } catch { continue; } model.FaildCount++; continue; } model.SuccessCount++; } return(View(model)); }
public async Task <ActionResult> Create([Bind(Include = AllowedFields)] WebFile webFile, bool redir = false) { UploadResults results = new UploadResults { message = "No file upload received.", status = UploadResults.Failed }; try { var uploadRoles = Settings.RolesWithUploadPermission.Split(','); if (Roles.UserInAnyRole(User, RoleManager, uploadRoles)) { if (Request.Files.Count > 0) { string defaultRoleSetting = Settings.DefaultUploadPermissions; string[] defaultRoles; if (!string.IsNullOrEmpty(defaultRoleSetting)) { defaultRoles = defaultRoleSetting.Split(','); } else { defaultRoles = new string[] { RoleManager.FindByName(Roles.Users)?.Id }; } int fileCount = Request.Files.Count; for (int i = 0; i < fileCount; i++) { HttpPostedFileBase uploadedFile = Request.Files[i]; if (uploadedFile != null && uploadedFile.ContentLength > 0) { WebFile file = null; ModelState["Name"]?.Errors?.Clear(); if (ImageHelper.IsImageFile(uploadedFile)) { file = UploadImage(uploadedFile, results); } else if ((VideoHelper.IsVideoFile(uploadedFile) || VideoHelper.IsAudioFile(uploadedFile))) { file = UploadVideoOrAudio(uploadedFile, results); } else if (DocumentHelper.IsDocumentFile(uploadedFile)) { file = UploadDocument(uploadedFile, results); } else if (IsAllowedFileType(uploadedFile)) { file = UploadFile(uploadedFile, results, db, HttpContext, Settings); } else { results.status = UploadResults.Failed; results.message = "The file format was not recognized or is not an allowed file type."; } if (file != null) { if (webFile != null) { file.Update(webFile, UserTimeZoneOffset); webFile = null; } Permission.Apply(db, User, RoleManager, file, defaultRoles); //default permissions db.WebFiles.Add(file); await db.SaveChangesAsync(); results.files.Add(file); } } } if (results.status != UploadResults.Failed) { results.status = UploadResults.OK; results.message = null; //"File uploaded successfully."; } foreach (var wf in results.files) { if (!string.IsNullOrEmpty(webFile?.Name)) { wf.Name = webFile.Name; } else { wf.Name = wf.GetFileName(); } } if (fileCount > 1) { SetSuccessMessage("{0} files uploaded successfully", fileCount); } else if (results.files.Count > 0) { SetSuccessMessage("{0} uploaded successfully", results.files.First().Name); } } else { results.status = UploadResults.Failed; results.message = ErrorsFromModelState(ModelState) ?? results.message; } } else { throw new Exception("Permission denied"); } } catch (Exception ex) { results.status = UploadResults.Failed; results.message = ex.Message; } if (redir) { if (results.status == UploadResults.Failed) { SetFailureMessage(results.message); return(View(webFile)); } else { SetSuccessMessage(webFile.Name + " uploaded successfully!"); return(RedirectToAction("Index")); } } return(Auto(results, "Created")); }