/// <summary> /// Gets a resource, using a Uniform Resource Identifier (or Locator). /// </summary> /// <param name="Uri">URI</param> /// <param name="TimeoutMs">Timeout, in milliseconds. (Default=60000)</param> /// <param name="Headers">Optional headers. Interpreted in accordance with the corresponding URI scheme.</param> /// <exception cref="InvalidOperationException">No <see cref="HttpxProxy"/> set in the HTTPX <see cref="Types"/> module parameter.</exception> /// <exception cref="ArgumentException">If the <paramref name="Uri"/> parameter is invalid.</exception> /// <exception cref="ArgumentException">If the object response be decoded.</exception> /// <exception cref="ConflictException">If an approved presence subscription with the remote entity does not exist.</exception> /// <exception cref="ServiceUnavailableException">If the remote entity is not online.</exception> /// <exception cref="TimeoutException">If the request times out.</exception> /// <exception cref="OutOfMemoryException">If resource too large to decode.</exception> /// <exception cref="IOException">If unable to read from temporary file.</exception> /// <returns>Decoded object.</returns> public async Task <object> GetAsync(Uri Uri, int TimeoutMs, params KeyValuePair <string, string>[] Headers) { KeyValuePair <string, TemporaryFile> Rec = await this.GetTempFileAsync(Uri, TimeoutMs, Headers); string ContentType = Rec.Key; TemporaryFile File = Rec.Value; try { if (File is null) { return(null); } File.Position = 0; if (File.Length > int.MaxValue) { throw new OutOfMemoryException("Resource too large."); } int Len = (int)File.Length; byte[] Bin = new byte[Len]; if (await File.ReadAsync(Bin, 0, Len) != Len) { throw new IOException("Unable to read from file."); } return(InternetContent.Decode(ContentType, Bin, Uri)); } finally { File?.Dispose(); } }
/// <summary> /// Downloads a <see cref="DownloadRetrievalMethod"/> to a temporary file. /// </summary> /// <param name="retrievalMethod">The file to download.</param> /// <param name="tag">The <see cref="ITask.Tag"/> to set for the download process.</param> /// <returns>The downloaded temporary file.</returns> /// <exception cref="OperationCanceledException">A download was canceled from another thread.</exception> /// <exception cref="WebException">A file could not be downloaded from the internet.</exception> /// <exception cref="IOException">A downloaded file could not be written to the disk or.</exception> /// <exception cref="UnauthorizedAccessException">Write access to <see cref="IImplementationStore"/> is not permitted.</exception> protected virtual TemporaryFile Download(DownloadRetrievalMethod retrievalMethod, object?tag = null) { #region Sanity checks if (retrievalMethod == null) { throw new ArgumentNullException(nameof(retrievalMethod)); } #endregion retrievalMethod.Validate(); var tempFile = new TemporaryFile("0install-fetcher"); try { Handler.RunTask(new DownloadFile(retrievalMethod.Href, tempFile, retrievalMethod.DownloadSize) { Tag = tag }); return(tempFile); } #region Error handling catch { tempFile.Dispose(); throw; } #endregion }
public ReadStreamResult Read() { if (!_stream.CanRead) { return(new ReadStreamResult()); } TemporaryFile file = new TemporaryFile(); try { _stream.Position = 0; using (var fs = File.OpenWrite(file.FileName)) { _stream.CopyTo(fs); } } catch { file.Dispose(); throw; } return(new ReadStreamResult { TemporaryFile = file }); }
public void Clear() { if (tmpFile != null) { tmpFile.Dispose(); tmpFile = null; } }
public void ExtensionIsInLowerCase(string extension, string expectedExtension) { TemporaryFile file = new TemporaryFile(extension); string fileExtension = Path.GetExtension(file.FileName).Substring(1); file.Dispose(); Assert.AreEqual(expectedExtension, fileExtension); }
public void ExtensionContainingDotIsHandled(string extension, string expectedExtension) { TemporaryFile file = new TemporaryFile(extension); string fileExtension = Path.GetExtension(file.FileName).Substring(1); file.Dispose(); Assert.AreEqual(expectedExtension, fileExtension); }
public void NotAllowedExtensionGeneratesDefaultExtension(string extension) { TemporaryFile file = new TemporaryFile(extension); string fileExtension = Path.GetExtension(file.FileName).Substring(1); file.Dispose(); Assert.AreEqual(TemporaryFile.DefaultExtension, fileExtension); }
public void FileNameAlwaysHasExtension(string extension) { TemporaryFile file = new TemporaryFile(extension); string fileExtension = Path.GetExtension(file.FileName).Substring(1); file.Dispose(); Assert.IsTrue(string.IsNullOrWhiteSpace(fileExtension) == false); Assert.IsTrue(fileExtension.Length > 1); }
public void Test_Dispose() { // Arrange. var temp = new TemporaryFile().Touch(); // Act. temp.Dispose(); temp.File.Refresh(); // Assert. Assert.False(temp.File.Exists); }
public void Test_Dispose() { // Arrange. var temp = new TemporaryFile().Touch(); // Act. temp.Dispose(); temp.File.Refresh(); // Assert. Assert.False(temp.File.Exists); }
public void DisposeUpdatesTheDisposedField() { TemporaryFile file = new TemporaryFile(); bool disposedBefore = file._disposed; file.Dispose(); bool disposedAfter = file._disposed; Assert.IsFalse(disposedBefore); Assert.IsTrue(disposedAfter); }
public void DisposeDeletesTheFile() { TemporaryFile file = new TemporaryFile(); bool existsBeforeDispose = File.Exists(file.FileName); file.Dispose(); bool existsAfterDispose = File.Exists(file.FileName); Assert.IsTrue(existsBeforeDispose); Assert.IsFalse(existsAfterDispose); }
public void CreatesEmptyFile() { TemporaryFile file = new TemporaryFile(); FileInfo fi = new FileInfo(file.FileName); bool exists = fi.Exists; long length = fi.Length; file.Dispose(); Assert.IsTrue(exists); Assert.AreEqual(0, length); }
private bool DoCompress(FileInfo file, bool lossless) { bool isCompressed = false; using (MagickImage image = new MagickImage(file)) { if (image.GetAttribute("png:acTL") != null) { return(false); } StartCompression(image, lossless); Collection <TemporaryFile> tempFiles = new Collection <TemporaryFile>(); try { TemporaryFile bestFile = null; foreach (int quality in GetQualityList()) { TemporaryFile tempFile = new TemporaryFile(); tempFiles.Add(tempFile); image.Quality = quality; image.Write(tempFile); if (bestFile == null || bestFile.Length > tempFile.Length) { bestFile = tempFile; } } if (bestFile.Length < file.Length) { isCompressed = true; bestFile.CopyTo(file); file.Refresh(); } } finally { foreach (TemporaryFile tempFile in tempFiles) { tempFile.Dispose(); } } } return(isCompressed); }
public LoggedFile LogFile(string sourceFilePath, string fileName = null) { if (string.IsNullOrWhiteSpace(fileName)) { fileName = Path.GetFileName(sourceFilePath); } fileName = NormalizeFileName(fileName); FileInfo fi = new FileInfo(sourceFilePath); if (!fi.Exists) { _logger.Error(new LogFileException(sourceFilePath, new FileNotFoundException(null, sourceFilePath))); return(null); } if (fi.Length > Constants.MaximumAllowedFileSizeInBytes) { _logger.Error(new FileSizeTooLargeException(fi.Length, Constants.MaximumAllowedFileSizeInBytes)); return(null); } TemporaryFile temporaryFile = null; try { temporaryFile = new TemporaryFile(); File.Delete(temporaryFile.FileName); File.Copy(sourceFilePath, temporaryFile.FileName, true); long length = temporaryFile.GetSize(); LoggedFile loggedFile = new LoggedFile(fileName, temporaryFile.FileName, length); _temporaryFiles.Add(temporaryFile); _loggedFiles.Add(loggedFile); return(loggedFile); } catch (Exception ex) { if (temporaryFile != null) { temporaryFile.Dispose(); } _logger.Error(new LogFileException(sourceFilePath, ex)); return(null); } }
private bool DoLosslessCompress(FileInfo file) { bool isCompressed = false; using (MagickImage image = new MagickImage(file)) { ImageOptimizerHelper.CheckFormat(image, MagickFormat.Png); image.Strip(); image.Settings.SetDefine(MagickFormat.Png, "exclude-chunks", "all"); image.Settings.SetDefine(MagickFormat.Png, "include-chunks", "tRNS,gAMA"); CheckTransparency(image); Collection <TemporaryFile> tempFiles = new Collection <TemporaryFile>(); try { TemporaryFile bestFile = null; foreach (int quality in GetQualityList()) { TemporaryFile tempFile = new TemporaryFile(); tempFiles.Add(tempFile); image.Quality = quality; image.Write(tempFile); if (bestFile == null || bestFile.Length > tempFile.Length) { bestFile = tempFile; } } if (bestFile.Length < file.Length) { isCompressed = true; bestFile.CopyTo(file); file.Refresh(); } } finally { foreach (TemporaryFile tempFile in tempFiles) { tempFile.Dispose(); } } } return(isCompressed); }
private void StatisticsGeneratorForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } else { if (_scriptFile != null) { _scriptFile.Dispose(); _scriptFile = null; } } }
public TemporaryFile DownloadFile(IItem item) { var temp = new TemporaryFile(); try { _bridge.Unwrap <Item>(item).DownloadFile(temp); return(temp); } catch (Exception) { Trace.WriteLine(String.Format("Something went wrong downloading \"{0}\" in changeset {1}", item.ServerItem, item.ChangesetId)); temp.Dispose(); throw; } }
/// <inheritdoc cref="IDeltaUpdate.ApplyDeltaFile"/> public async Task <bool> ApplyDeltaFile( TemporaryFolder tempFolder, string originalFileLocation, string newFileLocation, string deltaFileName, Stream deltaFileStream, Action <double>?progress = null) { if (OSHelper.ActiveOS != OSPlatform.Windows) { _logger.Error("We aren't on Windows so can't apply MSDiff update"); return(false); } if (string.IsNullOrWhiteSpace(deltaFileName)) { _logger.Error("Wasn't given a file location for the delta file"); return(false); } //Put the delta file onto disk using var tmpDeltaFile = tempFolder.CreateTemporaryFile(deltaFileName); var tmpFileStream = tmpDeltaFile.GetStream(); await deltaFileStream.CopyToAsync(tmpFileStream); tmpFileStream.Dispose(); deltaFileStream.Dispose(); //If baseFile + outputLocation are the same, copy it to a tmp file //and then give it that (deleting it after) TemporaryFile?tmpBaseFile = null; if (originalFileLocation == newFileLocation) { tmpBaseFile = tempFolder.CreateTemporaryFile(); File.Copy(originalFileLocation, tmpBaseFile.Location); originalFileLocation = tmpBaseFile.Location; } //Make the updated file! File.Create(newFileLocation).Dispose(); var wasApplySuccessful = ApplyDelta(ApplyFlags.None, originalFileLocation, tmpDeltaFile.Location, newFileLocation); tmpBaseFile?.Dispose(); return(wasApplySuccessful); }
public TemporaryFile FindBestFileQuality(IMagickImage <QuantumType> image, out int bestQuality) { bestQuality = 0; CheckTransparency(image); TemporaryFile bestFile = null; foreach (var quality in GetQualityList()) { TemporaryFile tempFile = null; try { tempFile = new TemporaryFile(); image.Quality = quality; image.Write(tempFile); if (bestFile == null || bestFile.Length > tempFile.Length) { if (bestFile != null) { bestFile.Dispose(); } bestFile = tempFile; bestQuality = quality; tempFile = null; } } finally { if (tempFile != null) { tempFile.Dispose(); } } } return(bestFile); }
public LoggedFile LogAsFile(byte[] contents, string fileName = null) { if (contents == null || !contents.Any()) { return(null); } fileName = NormalizeFileName(fileName); long fileSize = contents.Length; if (fileSize > Constants.MaximumAllowedFileSizeInBytes) { _logger.Error(new FileSizeTooLargeException(fileSize, Constants.MaximumAllowedFileSizeInBytes)); return(null); } TemporaryFile temporaryFile = null; try { temporaryFile = new TemporaryFile(); File.WriteAllBytes(temporaryFile.FileName, contents); LoggedFile loggedFile = new LoggedFile(fileName, temporaryFile.FileName, fileSize); _temporaryFiles.Add(temporaryFile); _loggedFiles.Add(loggedFile); return(loggedFile); } catch (Exception ex) { if (temporaryFile != null) { temporaryFile.Dispose(); } _logger.Error(new LogByteArrayAsFileException(contents, ex)); return(null); } }
public void Dispose() { Thread.Sleep(10); var outPath = OutputFile.Path; var inPath = InputFile.Path; OutputFile.Dispose(); InputFile.Dispose(); if (File.Exists(outPath)) { throw new IncorrectOperationException(); } if (File.Exists(inPath)) { throw new IncorrectOperationException(); } }
private bool DoCompress(FileInfo file, bool lossless) { bool isCompressed = false; using (var image = new MagickImage(file)) { if (image.GetAttribute("png:acTL") != null) { return(false); } StartCompression(image, lossless); TemporaryFile bestFile = null; try { var pngHelper = new PngHelper(this); bestFile = pngHelper.FindBestFileQuality(image, out _); if (bestFile != null && bestFile.Length < file.Length) { isCompressed = true; bestFile.CopyTo(file); file.Refresh(); } } finally { if (bestFile != null) { bestFile.Dispose(); } } } return(isCompressed); }
private async Task <TemporaryFile> ReadResponseAsync(HttpResponse response) { TemporaryFile responseBodyFile = null; try { responseBodyFile = new TemporaryFile(); response.Body.Seek(0, SeekOrigin.Begin); using (var fs = File.OpenWrite(responseBodyFile.FileName)) { await response.Body.CopyToAsync(fs); } } catch (Exception ex) { StringBuilder sb = new StringBuilder(); sb.AppendLine("KissLogMiddleware.ReadResponseAsync error"); sb.AppendLine(ex.ToString()); KissLog.Internal.InternalHelpers.Log(sb.ToString(), LogLevel.Error); if (responseBodyFile != null) { responseBodyFile.Dispose(); } responseBodyFile = null; } finally { response.Body.Seek(0, SeekOrigin.Begin); } return(responseBodyFile); }
/// <summary> /// Gets a (possibly big) resource, using a Uniform Resource Identifier (or Locator). /// </summary> /// <param name="Uri">URI</param> /// <param name="TimeoutMs">Timeout, in milliseconds. (Default=60000)</param> /// <param name="Headers">Optional headers. Interpreted in accordance with the corresponding URI scheme.</param> /// <returns>Content-Type, together with a Temporary file, if resource has been downloaded, or null if resource is data-less.</returns> public async Task <KeyValuePair <string, TemporaryFile> > GetTempFileAsync(Uri Uri, int TimeoutMs, params KeyValuePair <string, string>[] Headers) { using (HttpClient HttpClient = new HttpClient() { Timeout = TimeSpan.FromMilliseconds(10000) }) { using (HttpRequestMessage Request = new HttpRequestMessage() { RequestUri = Uri, Method = HttpMethod.Get }) { this.PrepareHeaders(Request, Headers); HttpResponseMessage Response = await HttpClient.SendAsync(Request); Response.EnsureSuccessStatusCode(); string ContentType = Response.Content.Headers.ContentType.ToString(); TemporaryFile File = new TemporaryFile(); try { await Response.Content.CopyToAsync(File); } catch (Exception ex) { File.Dispose(); File = null; ExceptionDispatchInfo.Capture(ex).Throw(); } return(new KeyValuePair <string, TemporaryFile>(ContentType, File)); } } }
public void EmailWebServiceWithAttachment(string To, string From, string Subject, string Body, byte[] Attachment, string AttachmentName) { SmtpClient smtpclient = new SmtpClient { Host = smtpServer }; MailMessage message = GetMailMessage(To, From, Subject, Body); TemporaryFile tempFile = new TemporaryFile("", AttachmentName); FileStream objfilestream = new FileStream(tempFile.FilePath, FileMode.Create, FileAccess.ReadWrite); using (BinaryWriter writer = new BinaryWriter(objfilestream)) { writer.Write(Attachment); } Attachment a = new Attachment(tempFile.FilePath); message.Attachments.Add(a); smtpclient.Send(message); a.Dispose(); tempFile.Dispose(); smtpclient.Dispose(); }
/// <summary> /// Downloads a <see cref="DownloadRetrievalMethod"/> to a temporary file. /// </summary> /// <param name="retrievalMethod">The file to download.</param> /// <param name="tag">The <see cref="ITask.Tag"/> to set for the download process.</param> /// <returns>The downloaded temporary file.</returns> /// <exception cref="OperationCanceledException">A download was canceled from another thread.</exception> /// <exception cref="WebException">A file could not be downloaded from the internet.</exception> /// <exception cref="IOException">A downloaded file could not be written to the disk or.</exception> /// <exception cref="UnauthorizedAccessException">Write access to <see cref="IStore"/> is not permitted.</exception> protected virtual TemporaryFile Download([NotNull] DownloadRetrievalMethod retrievalMethod, [CanBeNull] object tag = null) { #region Sanity checks if (retrievalMethod == null) throw new ArgumentNullException("retrievalMethod"); #endregion var tempFile = new TemporaryFile("0install-fetcher"); try { Handler.RunTask(new DownloadFile(retrievalMethod.Href, tempFile, retrievalMethod.DownloadSize) {Tag = tag}); return tempFile; } #region Error handling catch { tempFile.Dispose(); throw; } #endregion }
public async Task Invoke(HttpContext context) { Logger logger = Logger.Factory.Get() as Logger; if (logger == null) { return; } logger.DataContainer.AddProperty(InternalHelpers.IsCreatedByHttpRequest, true); WebRequestProperties properties = WebRequestPropertiesFactory.Create(context.Request); Exception ex = null; Stream originalBodyStream = context.Response.Body; TemporaryFile responseBodyFile = null; long contentLength = 0; try { using (var responseStream = new MemoryStream()) { context.Response.Body = responseStream; await _next(context); responseBodyFile = new TemporaryFile(); await ReadResponse(context.Response, responseBodyFile.FileName); contentLength = responseStream.Length; if (CanWriteToResponseBody(context.Response)) { await responseStream.CopyToAsync(originalBodyStream); } } } catch (Exception e) { ex = e; throw; } finally { context.Response.Body = originalBodyStream; properties.EndDateTime = DateTime.UtcNow; HttpStatusCode statusCode = (HttpStatusCode)context.Response.StatusCode; if (ex != null) { statusCode = HttpStatusCode.InternalServerError; logger.Log(LogLevel.Error, ex); } if (logger.DataContainer.ExplicitHttpStatusCode.HasValue) { statusCode = logger.DataContainer.ExplicitHttpStatusCode.Value; } ResponseProperties response = ResponsePropertiesFactory.Create(context.Response); response.HttpStatusCode = statusCode; response.ContentLength = contentLength; properties.Response = response; if (responseBodyFile != null && InternalHelpers.PreFilterShouldLogResponseBody(logger, responseBodyFile, response)) { string responseFileName = InternalHelpers.ResponseFileName(response.Headers); logger.LogFile(responseBodyFile.FileName, responseFileName); } logger.DataContainer.WebRequestProperties = properties; responseBodyFile?.Dispose(); IEnumerable <ILogger> loggers = Logger.Factory.GetAll(); Logger.NotifyListeners(loggers.ToArray()); } }
public void Dispose() { packageV1.Dispose(); packageV2.Dispose(); }
public void EmailWebServiceWithAttachment(string To, string From, string Subject, string Body, byte[] Attachment, string AttachmentName) { SmtpClient smtpclient = new SmtpClient { Host = smtpServer }; MailMessage message = GetMailMessage(To, From, Subject, Body); TemporaryFile tempFile = new TemporaryFile("", AttachmentName); FileStream objfilestream = new FileStream(tempFile.FilePath, FileMode.Create, FileAccess.ReadWrite); using (BinaryWriter writer = new BinaryWriter(objfilestream)) { writer.Write(Attachment); } Attachment a = new Attachment(tempFile.FilePath); message.Attachments.Add(a); smtpclient.Send(message); a.Dispose(); tempFile.Dispose(); smtpclient.Dispose(); }
public override void Dispose() { base.Dispose(); _tempFile.Dispose(); }
public void TearDown() { _integrationManager.Dispose(); _appListFile.Dispose(); }
public void Dispose() { nupkgFile.Dispose(); tarFile.Dispose(); }
public void Dispose_FileCaught_ExpectedException() { var temporaryFile = new TemporaryFile(); using (new FileStream(temporaryFile.FileName, FileMode.Open)) { temporaryFile.Dispose(); } }
public void FileName_AfterDispose_GenerateObjectDisposedException() { var temporaryFile = new TemporaryFile(); Assert.That(temporaryFile.FileName, Is.Not.Null); temporaryFile.Dispose(); string fileName = temporaryFile.FileName; Assert.Fail("expected exception ObjectDisposedException"); }