public static void DeleteFileAndRelated(string dbFileName, DeleteType deleteType) { dbFileName = StringHelper.TrimToEmpty(dbFileName); if (dbFileName.Length > 0) { var fileName = Path.Combine(RootPath, ToPath(dbFileName)); if (deleteType == DeleteType.TryDeleteOrMark) { var folder = Path.GetDirectoryName(fileName); TemporaryFileHelper.TryDeleteMarkedFiles(folder); } TemporaryFileHelper.Delete(fileName, deleteType); string sourcePath = Path.GetDirectoryName(fileName); string sourceBase = Path.GetFileNameWithoutExtension(fileName); foreach (var f in Directory.GetFiles(sourcePath, sourceBase + "_t*.jpg")) { TemporaryFileHelper.Delete(f, deleteType); } TemporaryFileHelper.Delete(fileName + ".meta", deleteType); } }
public static string FormatDbFileName(string format, object identity, string extension) { long l; object groupKey; string s; if (identity == null) { groupKey = "_"; } else if (identity is Guid) { s = ((Guid)identity).ToString("N"); identity = s; groupKey = s.Substring(0, 2); } else { s = identity.ToString(); if (long.TryParse(s, out l)) { groupKey = l / 1000; } else if (s.Length == 0) { groupKey = "_"; } else { groupKey = s.SafeSubstring(0, 2); } } return(String.Format(format, identity, groupKey, TemporaryFileHelper.RandomFileCode(), DateTime.Now) + extension); }
internal static string CreateDatabaseFilesForScript(string script, string hash) { var cachedPath = Path.Combine(DbSettings.Current.RootPath, "cache_" + hash + ".mdf"); Tuple <byte[], byte[]> data; lock (fileCacheLock) { if (!fileCache.TryGetValue(cachedPath, out data)) { data = null; } } Func <string> writeDb = delegate() { var rnd = TemporaryFileHelper.RandomFileCode(); var instancePath = Path.Combine(DbSettings.Current.RootPath, "test_" + rnd + ".mdf"); WriteDb(instancePath, data.Item1, data.Item2); return(instancePath); }; if (data != null) { return(writeDb()); } if (!File.Exists(cachedPath)) { try { CreateDb("cache_" + hash, cachedPath, script); } finally { DetachDb("cache_" + hash); } } else { DetachDb("cache_" + hash); } if (!File.Exists(cachedPath)) { throw new InvalidOperationException("Test için cache veritabanı oluşturulamadı!"); } data = new Tuple <byte[], byte[]>( File.ReadAllBytes(cachedPath), File.ReadAllBytes(Path.ChangeExtension(cachedPath, ".ldf"))); lock (fileCacheLock) fileCache[cachedPath] = data; return(writeDb()); }
public static string FormatFilename(FormatFilenameOptions options) { object groupKey; string s; object identity = options.EntityId; if (identity == null) { groupKey = "_"; } else if (identity is Guid g) { s = g.ToString("N"); identity = s; groupKey = s.Substring(0, 2); } else { s = identity.ToString(); if (long.TryParse(s, out long l)) { groupKey = l / 1000; } else if (s.Length == 0) { groupKey = "_"; } else { groupKey = s.SafeSubstring(0, 2); } } var formatted = string.Format(options.Format, identity, groupKey, TemporaryFileHelper.RandomFileCode(), DateTime.Now, Path.GetFileNameWithoutExtension(options.OriginalName)) + Path.GetExtension(options.OriginalName); if (options.PostFormat != null) { formatted = options.PostFormat(formatted); } return(formatted); }
public virtual void SetFileMetadata(string path, IDictionary <string, string> metadata, bool overwriteAll) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException(nameof(path)); } if (metadata == null) { throw new ArgumentNullException(nameof(metadata)); } if (IsInternalFile(path)) { throw new ArgumentOutOfRangeException(nameof(path)); } var filePath = FilePath(path); var metaFile = filePath + ".meta"; if (overwriteAll && metadata.Count == 0) { if (File.Exists(metaFile)) { TemporaryFileHelper.TryDeleteOrMark(metaFile); } } else if (metadata.Count == 0) { return; } if (!overwriteAll && File.Exists(metaFile)) { var existing = GetFileMetadata(path); foreach (var x in metadata) { existing[x.Key] = x.Value; } metadata = existing; } File.WriteAllText(metaFile, JSON.StringifyIndented(metadata)); }
public string WriteResources() { IDeclarationTarget idt = null; if (this.IsPartial) { return(null); } for (idt = this; idt != null && (!(idt is INameSpaceDeclaration)); idt = idt.ParentTarget) { ; } if ((idt == null) || (!(idt is INameSpaceDeclaration))) { throw new InvalidOperationException("Object in an invalid state."); } INameSpaceDeclaration insd = (INameSpaceDeclaration)idt; TemporaryFile tf; if (this == this.Project.Resources) { tf = TemporaryFileHelper.GetTemporaryDirectory("", true).Files.GetTemporaryFile(string.Format("Resources.resources", insd.FullName, this.Name)); } else { tf = TemporaryFileHelper.GetTemporaryDirectory("", true).Files.GetTemporaryFile(string.Format("{0}.{1}.resources", insd.FullName, this.Name)); } tf.OpenStream(FileMode.Create); ResourceWriter rw = new ResourceWriter(tf.FileStream); foreach (IDeclarationResourcesStringTableEntry idrste in this.StringTable.Values) { rw.AddResource(idrste.Name, idrste.Value); } rw.Close(); tf.CloseStream(); return(tf.FileName); }
public static void RemoveTestFiles() { HashSet <string> files = new HashSet <string>(StringComparer.OrdinalIgnoreCase); using (var connection = SqlConnections.New(DbSettings.Current.ServerConnectionString, DbSettings.Current.Provider)) using (var reader = SqlHelper.ExecuteReader(connection, "SELECT physical_name FROM sys.master_files")) { while (reader.Read()) { if (!reader.IsDBNull(0)) { files.Add(Path.GetFileName(reader.GetString(0))); } } } foreach (var file in Directory.GetFiles(DbSettings.Current.RootPath, "test*.*")) { if (!files.Contains(Path.GetFileName(file))) { TemporaryFileHelper.TryDelete(file); } } }
public static string CreateDatabaseFilesForScript(string script) { var hash = GetHash(script); var cachedPath = Path.Combine(DbSettings.Current.RootPath, "cache_" + hash + ".mdf"); if (!File.Exists(cachedPath)) { try { CreateDb("cache_" + hash, cachedPath, script); } finally { DetachDb("cache_" + hash); } } else { DetachDb("cache_" + hash); } if (!File.Exists(cachedPath)) { throw new InvalidOperationException("Test için cache veritabanı oluşturulamadı!"); } var rnd = TemporaryFileHelper.RandomFileCode(); var instancePath = Path.Combine(DbSettings.Current.RootPath, "test_" + rnd + ".mdf"); CopyDb(cachedPath, instancePath); return(instancePath); }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/App_Data/Reporting/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("Can't find wkhtmltopdf.exe which is required for PDF generation.\n" + "Please download a stable version from http://wkhtmltopdf.org/downloads.html\n and place it under directory '{0}'.", Path.GetDirectoryName(exePath))); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); args.Add(!SmartShrinking ? "--disable-smart-shrinking" : "--enable-smart-shrinking"); if (!string.IsNullOrEmpty(PageSize)) { args.Add("--page-size"); args.Add(PageSize); } if (!string.IsNullOrEmpty(PageWidth)) { args.Add("--page-width"); args.Add(PageWidth); } if (!string.IsNullOrEmpty(PageHeight)) { args.Add("--page-height"); args.Add(PageHeight); } if (MarginLeft != null) { args.Add("--margin-left"); args.Add(MarginLeft); } if (MarginTop != null) { args.Add("--margin-top"); args.Add(MarginTop); } if (MarginRight != null) { args.Add("--margin-right"); args.Add(MarginRight); } if (MarginBottom != null) { args.Add("--margin-bottom"); args.Add(MarginBottom); } if (Dpi != null) { args.Add("--dpi"); args.Add(Dpi.Value.ToString(CultureInfo.InvariantCulture)); } if (Zoom != null) { args.Add("--zoom"); args.Add(Zoom); } if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } if (PrintBackground) { args.Add("--background"); } else { args.Add("--no-background"); } if (FooterHtmlUrl != null) { args.Add("--footer-html"); args.Add(FooterHtmlUrl); } if (Landscape) { args.Add("--orientation"); args.Add("Landscape"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } foreach (var replace in FooterHeaderReplace) { args.Add("--replace"); args.Add(replace.Key); args.Add(replace.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } foreach (var arg in CustomArgs) { args.Add(arg); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("An error occured while starting PDF generator!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 seconds { throw new InvalidOperationException("Timeout while PDF generation!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF generator returned error code {0}!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("Can't find generatored PDF file!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Generated PDF file is empty!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }
public static string FormatDbFileName(string format, Int64 identity, string extension) { return(String.Format(format, identity, identity / 1000, TemporaryFileHelper.RandomFileCode()) + extension); }
private bool ProcessImageStream(Stream fileContent, string extension) { Image image = null; var imageChecker = new ImageChecker(); CheckResult = imageChecker.CheckStream(fileContent, true, out image); try { FileSize = imageChecker.DataSize; ImageWidth = imageChecker.Width; ImageHeight = imageChecker.Height; if (CheckResult != ImageCheckResult.JPEGImage && CheckResult != ImageCheckResult.GIFImage && CheckResult != ImageCheckResult.PNGImage) { ErrorMessage = imageChecker.FormatErrorMessage(CheckResult); return(false); } else { IsImage = true; extension = (CheckResult == ImageCheckResult.PNGImage ? ".png" : (CheckResult == ImageCheckResult.GIFImage ? ".gif" : ".jpg")); var temporaryPath = UploadHelper.TemporaryPath; Directory.CreateDirectory(temporaryPath); TemporaryFileHelper.PurgeDirectoryDefault(temporaryPath); string baseFileName = System.IO.Path.Combine(temporaryPath, Guid.NewGuid().ToString("N")); FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) fileContent.CopyTo(fs); if (ThumbWidth > 0 || ThumbHeight > 0) { using (System.Drawing.Image thumbImage = ThumbnailGenerator.Generate(image, ThumbWidth, ThumbHeight, ThumbScaleMode, ThumbBackColor)) { ThumbFile = baseFileName + "_t.jpg"; if (ThumbQuality != 0) { var p = new System.Drawing.Imaging.EncoderParameters(1); p.Param[0] = new EncoderParameter(Encoder.Quality, ThumbQuality); ImageCodecInfo jpegCodec = null; ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) { if (codecs[i].MimeType == "image/jpeg") { jpegCodec = codecs[i]; } } thumbImage.Save(ThumbFile, jpegCodec, p); } else { thumbImage.Save(ThumbFile, System.Drawing.Imaging.ImageFormat.Jpeg); } ThumbHeight = thumbImage.Width; ThumbWidth = thumbImage.Height; } } return(true); } } finally { if (image != null) { image.Dispose(); image = null; } } }
public bool ProcessStream(Stream fileContent, string extension) { extension = extension.TrimToEmpty().ToLowerInvariant(); if (IsDangerousExtension(extension)) { ErrorMessage = "Unsupported file extension!"; return(false); } CheckResult = ImageCheckResult.InvalidImage; ErrorMessage = null; ImageWidth = 0; ImageHeight = 0; IsImage = false; var success = false; var temporaryPath = UploadHelper.TemporaryPath; Directory.CreateDirectory(temporaryPath); TemporaryFileHelper.PurgeDirectoryDefault(temporaryPath); string baseFileName = System.IO.Path.Combine(temporaryPath, Guid.NewGuid().ToString("N")); try { try { if (IsImageExtension(extension)) { IsImage = true; success = true; FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) { fileContent.CopyTo(fs); FileSize = fs.Length; } success = ProcessImageStream(fileContent, extension); } else { FilePath = baseFileName + extension; fileContent.Seek(0, SeekOrigin.Begin); using (FileStream fs = new FileStream(FilePath, FileMode.Create)) { fileContent.CopyTo(fs); FileSize = fs.Length; } success = true; } } catch (Exception ex) { ErrorMessage = ex.Message; success = false; return(success); } } finally { if (!success) { if (!ThumbFile.IsNullOrEmpty()) { TemporaryFileHelper.TryDelete(ThumbFile); } if (!FilePath.IsNullOrEmpty()) { TemporaryFileHelper.TryDelete(FilePath); } } fileContent.Dispose(); } return(success); }
public void CheckUploadedImageAndCreateThumbs(ref string temporaryFile, params ImageCheckResult[] supportedFormats) { if (supportedFormats == null || supportedFormats.Length == 0) { supportedFormats = new ImageCheckResult[] { ImageCheckResult.JPEGImage, ImageCheckResult.GIFImage, ImageCheckResult.PNGImage } } ; UploadHelper.CheckFileNameSecurity(temporaryFile); var checker = new ImageChecker(); checker.MinWidth = this.MinWidth; checker.MaxWidth = this.MaxWidth; checker.MinHeight = this.MinHeight; checker.MaxHeight = this.MaxHeight; checker.MaxDataSize = this.MaxBytes; Image image = null; try { var temporaryPath = Path.Combine(UploadHelper.TemporaryPath, temporaryFile); using (var fs = new FileStream(temporaryPath, FileMode.Open)) { if (this.MinBytes != 0 && fs.Length < this.MinBytes) { throw new ValidationError(String.Format("Yükleyeceğiniz dosya en az {0} boyutunda olmalı!", UploadHelper.FileSizeDisplay(this.MinBytes))); } if (this.MaxBytes != 0 && fs.Length > this.MaxBytes) { throw new ValidationError(String.Format("Yükleyeceğiniz dosya en çok {0} boyutunda olabilir!", UploadHelper.FileSizeDisplay(this.MaxBytes))); } ImageCheckResult result; if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf") { result = ImageCheckResult.FlashMovie; // validate swf file somehow! } else { result = checker.CheckStream(fs, true, out image); } if (result > ImageCheckResult.FlashMovie || Array.IndexOf(supportedFormats, result) < 0) { string error = checker.FormatErrorMessage(result); throw new ValidationError(error); } if (result != ImageCheckResult.FlashMovie) { string basePath = UploadHelper.TemporaryPath; string baseFile = Path.GetFileNameWithoutExtension(temporaryFile); TemporaryFileHelper.PurgeDirectoryDefault(basePath); if ((this.ScaleWidth > 0 || this.ScaleHeight > 0) && ((this.ScaleWidth > 0 && (this.ScaleSmaller || checker.Width > this.ScaleWidth)) || (this.ScaleHeight > 0 && (this.ScaleSmaller || checker.Height > this.ScaleHeight)))) { using (Image scaledImage = ThumbnailGenerator.Generate( image, this.ScaleWidth, this.ScaleHeight, this.ScaleMode, Color.Empty)) { temporaryFile = baseFile + ".jpg"; fs.Close(); scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg); } } var thumbSizes = this.ThumbSizes.TrimToNull(); if (thumbSizes != null) { foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' })) { var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' }); int w, h; if (dims.Length != 2 || !Int32.TryParse(dims[0], out w) || !Int32.TryParse(dims[1], out h) || w < 0 || h < 0 || (w == 0 && h == 0)) { throw new ArgumentOutOfRangeException("thumbSizes"); } using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, this.ThumbMode, Color.Empty)) { string thumbFile = Path.Combine(basePath, baseFile + "t_" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg"); if (this.ThumbQuality != 0) { var p = new System.Drawing.Imaging.EncoderParameters(1); p.Param[0] = new EncoderParameter(Encoder.Quality, 80L); ImageCodecInfo jpegCodec = null; ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); // Find the correct image codec for (int i = 0; i < codecs.Length; i++) { if (codecs[i].MimeType == "image/jpeg") { jpegCodec = codecs[i]; } } thumbImage.Save(thumbFile, jpegCodec, p); } else { thumbImage.Save(thumbFile, System.Drawing.Imaging.ImageFormat.Jpeg); } } } } } } } finally { if (image != null) { image.Dispose(); } } } }
public override void PurgeTemporaryFiles() { TemporaryFileHelper.PurgeDirectoryDefault(RootPath); }
public static void WriteProject(IIntermediateProject project, IIntermediateCodeTranslator translator, string temporaryDirectory, out TemporaryDirectory td, out TempFileCollection tfc, out List <string> files, out Stack <IIntermediateProject> partialCompletions, out Dictionary <IIntermediateModule, List <string> > moduleFiles, bool keepTempFiles, bool allowPartials, string extension = ".cs", bool purgeTempDir = false, string tabString = " ") { td = TemporaryFileHelper.GetNonStandardTempDirectory(temporaryDirectory, project.Name, keepTempFiles); if (purgeTempDir) { try { Directory.Delete(td.Path, true); } catch (IOException) { } Directory.CreateDirectory(td.Path); } tfc = new TempFileCollection(td.Path, td.Keep); files = new List <string>(); partialCompletions = new Stack <IIntermediateProject>(); moduleFiles = new Dictionary <IIntermediateModule, List <string> >(); bool attributesOverride = !allowPartials; if (!attributesOverride) { foreach (IIntermediateModule iim in project.Modules.Values) { moduleFiles.Add(iim, new List <string>()); foreach (IDeclaredType idt in iim.DeclaredTypes) { string currentFile = string.Empty; IDeclaredType target = (idt is ISegmentableDeclaredType) ? ((ISegmentableDeclaredType)idt).GetRootDeclaration() : idt; currentFile = WriteFile(project, translator, td, tfc, partialCompletions, target, extension, tabString); if (currentFile != null) { files.Add(currentFile); moduleFiles[iim].Add(currentFile); } //Don't forget to include the partials... if (target is ISegmentableDeclaredType) { foreach (IDeclaredType partial in ((ISegmentableDeclaredType)idt).Partials) { currentFile = WriteFile(project, translator, td, tfc, partialCompletions, partial, extension, tabString); if (currentFile != null) { files.Add(currentFile); moduleFiles[iim].Add(currentFile); } } } } } } if (project.Attributes.Count > 0 || attributesOverride) { if (attributesOverride) { moduleFiles.Add(project.RootModule, new List <string>()); } string attrFile = null; /* * * Only add it if there are no types in the * root declaration of the project. * */ var p = project; if (!p.IsRoot) { p = p.GetRootDeclaration(); } if (!partialCompletions.Contains(project)) { attrFile = WriteAttributeFile(project, translator, td, tfc, partialCompletions, extension, tabString); if (attrFile != null) { moduleFiles[project.RootModule].Add(attrFile); } } } }
public static void DeleteDb(string path) { TemporaryFileHelper.TryDelete(path); TemporaryFileHelper.TryDelete(Path.ChangeExtension(path, ".ldf")); }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/Reports/Utility/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("PDF üretimi için gereken wkhtmltopdf.exe dosyası '{0}' konumunda bulunamadı'", exePath)); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("PDF üretim programı başlatılırken hata oluştu!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 sn de üretmeli { throw new InvalidOperationException("PDF üretilirken zaman aşımı oluştu!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF üretim programı {0} hata kodu döndürdü!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("PDF üretimi sonrasında geçici dosya bulunamadı!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Üretilen PDF dosyası boş!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }
public List <ExternalType> List() { var files = Directory.GetFiles(Path.Combine(projectDir, @"Modules"), "*.ts", SearchOption.AllDirectories) .Concat(Directory.GetFiles(Path.Combine(projectDir, @"Imports"), "*.ts", SearchOption.AllDirectories)) .Concat(Directory.GetFiles(Path.Combine(projectDir, @"typings"), "*.ts", SearchOption.AllDirectories)) .Where(x => !x.EndsWith(".d.ts", StringComparison.OrdinalIgnoreCase) || x.Contains("Serenity", StringComparison.Ordinal)).OrderBy(x => x); var tsServices = GetEmbeddedScript("Serenity.CodeGenerator.Resource.typescriptServices.js"); var codeGeneration = GetEmbeddedScript("Serenity.CodeGenerator.Resource.Serenity.CodeGeneration.js"); StringBuilder sb = new StringBuilder(); sb.AppendLine("var fs = require('fs');"); sb.AppendLine(tsServices); sb.AppendLine(codeGeneration); foreach (var file in files) { sb.AppendLine("Serenity.CodeGeneration.addSourceFile(" + file.Replace('\\', '/').ToJson() + ", " + File.ReadAllText(file).ToJson() + ");"); } sb.AppendLine("var types = JSON.stringify(Serenity.CodeGeneration.parseTypes());"); sb.AppendLine("fs.writeFileSync('./typeList.json', types);"); var cacheDir = Path.Combine(Path.GetTempPath(), ".tstypecache"); var md5 = MD5.Create(); var hash = BitConverter.ToString(md5.ComputeHash(Encoding.Unicode.GetBytes(sb.ToString()))); var cacheFile = Path.Combine(cacheDir, hash + ".json"); if (File.Exists(cacheFile)) { try { return(JSON.Parse <List <ExternalType> >(File.ReadAllText(cacheFile))); } catch { } } Action <string> writeCache = (json) => { try { Directory.CreateDirectory(cacheDir); TemporaryFileHelper.PurgeDirectory(cacheDir, TimeSpan.Zero, 99, null); File.WriteAllText(cacheFile, json); } catch { } }; var tempDirectory = Path.ChangeExtension(Path.GetTempFileName(), null) + "__"; Directory.CreateDirectory(tempDirectory); try { File.WriteAllText(Path.Combine(tempDirectory, "index.js"), sb.ToString()); var process = Process.Start(new ProcessStartInfo() { FileName = "node", Arguments = "index.js", WorkingDirectory = tempDirectory, CreateNoWindow = true }); process.WaitForExit(60000); var json = File.ReadAllText(Path.Combine(tempDirectory, "typeList.json")); writeCache(json); return(JSON.Parse <List <ExternalType> >(json)); } finally { Directory.Delete(tempDirectory, true); } }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/Reports/Utility/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("Can't find wkhtmltopdf.exe which is required for PDF generation at location: '{0}'!", exePath)); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("An error occured while starting PDF generator!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 seconds { throw new InvalidOperationException("Timeout while PDF generation!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF generator returned error code {0}!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("Can't find generatored PDF file!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Generated PDF file is empty!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }
public static void CheckUploadedImageAndCreateThumbs(ImageUploadEditorAttribute attr, ref string temporaryFile) { ImageCheckResult[] supportedFormats = null; if (!attr.AllowNonImage) { supportedFormats = new ImageCheckResult[] { ImageCheckResult.JPEGImage, ImageCheckResult.GIFImage, ImageCheckResult.PNGImage } } ; UploadHelper.CheckFileNameSecurity(temporaryFile); var checker = new ImageChecker(); checker.MinWidth = attr.MinWidth; checker.MaxWidth = attr.MaxWidth; checker.MinHeight = attr.MinHeight; checker.MaxHeight = attr.MaxHeight; checker.MaxDataSize = attr.MaxSize; Image image = null; try { var temporaryPath = UploadHelper.DbFilePath(temporaryFile); using (var fs = new FileStream(temporaryPath, FileMode.Open)) { if (attr.MinSize != 0 && fs.Length < attr.MinSize) { throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooSmall, UploadHelper.FileSizeDisplay(attr.MinSize))); } if (attr.MaxSize != 0 && fs.Length > attr.MaxSize) { throw new ValidationError(String.Format(Texts.Controls.ImageUpload.UploadFileTooBig, UploadHelper.FileSizeDisplay(attr.MaxSize))); } ImageCheckResult result; if (Path.GetExtension(temporaryFile).ToLowerInvariant() == ".swf") { result = ImageCheckResult.FlashMovie; // validate swf file somehow! } else { result = checker.CheckStream(fs, true, out image); } if (result == ImageCheckResult.InvalidImage && attr.AllowNonImage) { return; } if (result > ImageCheckResult.UnsupportedFormat || (supportedFormats != null && Array.IndexOf(supportedFormats, result) < 0)) { string error = checker.FormatErrorMessage(result); throw new ValidationError(error); } if (result >= ImageCheckResult.FlashMovie) { return; } string basePath = UploadHelper.TemporaryPath; string baseFile = Path.GetFileNameWithoutExtension(Path.GetFileName(temporaryPath)); TemporaryFileHelper.PurgeDirectoryDefault(basePath); if ((attr.ScaleWidth > 0 || attr.ScaleHeight > 0) && ((attr.ScaleWidth > 0 && (attr.ScaleSmaller || checker.Width > attr.ScaleWidth)) || (attr.ScaleHeight > 0 && (attr.ScaleSmaller || checker.Height > attr.ScaleHeight)))) { using (Image scaledImage = ThumbnailGenerator.Generate( image, attr.ScaleWidth, attr.ScaleHeight, attr.ScaleMode, Color.Empty)) { temporaryFile = baseFile + ".jpg"; fs.Close(); scaledImage.Save(Path.Combine(basePath, temporaryFile), System.Drawing.Imaging.ImageFormat.Jpeg); temporaryFile = "temporary/" + temporaryFile; } } var thumbSizes = attr.ThumbSizes.TrimToNull(); if (thumbSizes == null) { return; } foreach (var sizeStr in thumbSizes.Replace(";", ",").Split(new char[] { ',' })) { var dims = sizeStr.ToLowerInvariant().Split(new char[] { 'x' }); int w, h; if (dims.Length != 2 || !Int32.TryParse(dims[0], out w) || !Int32.TryParse(dims[1], out h) || w < 0 || h < 0 || (w == 0 && h == 0)) { throw new ArgumentOutOfRangeException("thumbSizes"); } using (Image thumbImage = ThumbnailGenerator.Generate(image, w, h, attr.ThumbMode, Color.Empty)) { string thumbFile = Path.Combine(basePath, baseFile + "_t" + w.ToInvariant() + "x" + h.ToInvariant() + ".jpg"); thumbImage.Save(thumbFile); } } } } finally { if (image != null) { image.Dispose(); } } } }
private void TranslateSource(out TemporaryDirectory td, out TempFileCollection tfc, out List <string> files, out Stack <IIntermediateProject> partialCompletions, out Dictionary <IIntermediateModule, List <string> > moduleFiles) { ProjectTranslator.WriteProject(this.Project, this.Translator, Path.Combine(TemporaryFileHelper.GetTemporaryPath(), "Oilexer"), out td, out tfc, out files, out partialCompletions, out moduleFiles, options.KeepTempFiles, this.translator.Options.AllowPartials); }