public void Deletes_File_On_Dispose() { string tempFile = Path.GetTempFileName(); Assert.IsTrue(File.Exists(tempFile), "Temp file not created."); using (var ts = new TempFileStream(tempFile)) { } Assert.IsTrue(!File.Exists(tempFile), "Temp file not deleted."); }
/// <summary> /// Validate the ticket and optionally add schema info (defaults and PVSI) /// </summary> /// <param name="addSchemaInfo">True adds default elements, default attributes and schema info to the ticket. False leaves this alone. Default is true.</param> /// <param name="workAroundMSBug">True works around an issue in the .NET framework that causes validation to work improperly on schema types that inherit /// from an abstract base class if the document is created via node authoring code instead of by Parse or Load methods. Default is true.</param> /// <returns></returns> public bool Validate(bool addSchemaInfo = true, bool workAroundMSBug = true) { //todo: this method should probably return ResultOf. ResultOf needs to be taken from connent and move to common to accomplish this properly. messages.Clear(); ticket.Document.Validate(SchemaSet.Instance.Schemas, (o, e) => messages.Add(new ValidationMessage(o, e.Severity, e.Message)), addSchemaInfo); if (workAroundMSBug) { using (var tempFileSream = new TempFileStream()) { messages.Clear(); ticket.Document.Save(tempFileSream); tempFileSream.Seek(0, SeekOrigin.Begin); var newDocument = XDocument.Load(tempFileSream); newDocument.Validate(SchemaSet.Instance.Schemas, (o, e) => messages.Add(new ValidationMessage(o, e.Severity, e.Message)), false); } } IsValid = messages.Where(m => m.ValidationMessageType == ValidationMessageType.Error).Count() == 0; Messages = new ReadOnlyCollection <ValidationMessage>(messages); HasValidatedAtLeastOnce = true; return(IsValid.Value); }
public FileStream CreateTempFile(string name) { var dir = Path.Combine(GetTempDir(), Guid.NewGuid().ToString("N")); var path = Path.Combine(dir, name); Directory.CreateDirectory(dir); var stream = new TempFileStream(path); stream.Disposing += () => { try { File.Delete(path); Directory.Delete(dir); } catch { } }; return(stream); }
/// <exception cref="IOException"></exception> /// <exception cref="ClrStrongNameMissingException"></exception> internal override void SignAssembly(StrongNameKeys keys, Stream inputStream, Stream outputStream) { Debug.Assert(inputStream is TempFileStream); TempFileStream tempStream = (TempFileStream)inputStream; string assemblyFilePath = tempStream.Path; tempStream.DisposeUnderlyingStream(); if (keys.KeyContainer != null) { Sign(assemblyFilePath, keys.KeyContainer); } else { Sign(assemblyFilePath, keys.KeyPair); } using (FileStream fileToSign = new FileStream(assemblyFilePath, FileMode.Open)) { fileToSign.CopyTo(outputStream); } }
public TempFileCache(StorageEnvironmentOptions options) { _options = options; string path = _options.TempPath.FullPath; if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } foreach (string file in Directory.GetDirectories(path, "lucene-*" + StorageEnvironmentOptions.DirectoryStorageEnvironmentOptions.TempFileExtension)) { var info = new FileInfo(file); if (info.Length > MaxFileSizeToKeepInBytes || _files.Count >= MaxFilesToKeepInCache) { File.Delete(file); } else { TempFileStream fileStream; try { var stream = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose); fileStream = new TempFileStream(stream); fileStream.ResetLength(); } catch (IOException) { // if can't open, just ignore it. continue; } _files.Enqueue(fileStream); } } LowMemoryNotification.Instance.RegisterLowMemoryHandler(this); }
public static Stream DecodeSin(Stream stream, long totalSize) { var rewindable = new RewindableStream(stream); rewindable.StartRecording(); var reader = new BinaryReader(rewindable); var version = reader.ReadByte(); switch (version) { case 1: case 2: throw new Exception($"SIN version 1 and 2 not supported."); case 3: rewindable.Rewind(true); var tempStream = TempFileStream.Create(); SinParserV3.CopyTo(reader, tempStream); return(tempStream); } rewindable.Rewind(true); return(DecodeTarSin(rewindable, totalSize)); }
public ZipEntryViewModel(ZipFileInfo parent, ZipArchiveEntry e) { this.parent = parent; totalSize = e.Size; Name = e.Key; getStream = new Lazy <Stream>(delegate { var transferList = parent.GetTransferList(); using (var srcStream = e.OpenEntryStream()) { if (Name.EndsWith(".new.dat")) { return(new BlockImgStream(srcStream, transferList)); } if (Name.EndsWith(".new.dat.br")) { return(new BlockImgStream( new BrotliStream(srcStream, CompressionMode.Decompress), transferList)); } return(TempFileStream.CreateFrom(srcStream, done => FileInfoBase.ReportProgress(done, totalSize))); } }); }
public void Read(Stream str) { this.Entries.Clear(); BigEndianBinaryReader bigEndianBinaryReader = new BigEndianBinaryReader(str); this.header.MagicNumber = bigEndianBinaryReader.ReadUInt32(); this.header.VersionNumber = bigEndianBinaryReader.ReadUInt32(); this.header.CompressionMethod = bigEndianBinaryReader.ReadUInt32(); this.header.TotalTOCSize = bigEndianBinaryReader.ReadUInt32(); this.header.TOCEntrySize = bigEndianBinaryReader.ReadUInt32(); this.header.numFiles = bigEndianBinaryReader.ReadUInt32(); this.header.blockSize = bigEndianBinaryReader.ReadUInt32(); this.header.archiveFlags = bigEndianBinaryReader.ReadUInt32(); var tocStream = str; BigEndianBinaryReader bigEndianBinaryReaderTOC = bigEndianBinaryReader; if (this.header.archiveFlags == 4) { var decStream = new TempFileStream(); using (var outputStream = new MemoryStream()) { RijndaelEncryptor.DecryptPSARC(str, outputStream, this.header.TotalTOCSize); int bytesRead; byte[] buffer = new byte[30000]; int decMax = (int)this.header.TotalTOCSize - 32; int decSize = 0; outputStream.Seek(0, SeekOrigin.Begin); while ((bytesRead = outputStream.Read(buffer, 0, buffer.Length)) > 0) { decSize += bytesRead; if (decSize > decMax) bytesRead = decMax - (decSize - bytesRead); decStream.Write(buffer, 0, bytesRead); } } decStream.Seek(0, SeekOrigin.Begin); str.Seek(this.header.TotalTOCSize, SeekOrigin.Begin); tocStream = decStream; bigEndianBinaryReaderTOC = new BigEndianBinaryReader(tocStream); } if (this.header.MagicNumber == 1347633490) { if (this.header.CompressionMethod == 2053925218) { byte b = 1; uint num = 256; do { num *= 256; b += 1; } while (num < this.header.blockSize); int num2 = 0; while (num2 < this.header.numFiles) { this.Entries.Add(new Entry { id = num2, MD5 = bigEndianBinaryReaderTOC.ReadBytes(16), zIndex = bigEndianBinaryReaderTOC.ReadUInt32(), Length = bigEndianBinaryReaderTOC.ReadUInt40(), Offset = bigEndianBinaryReaderTOC.ReadUInt40() }); num2++; } long decMax = (this.header.archiveFlags == 4) ? 32 : 0; uint num3 = (this.header.TotalTOCSize - (uint)(tocStream.Position + decMax)) / (uint)b; uint[] array = new uint[num3]; num2 = 0; while (num2 < num3) { switch (b) { case 2: array[num2] = (uint)bigEndianBinaryReaderTOC.ReadUInt16(); break; case 3: array[num2] = bigEndianBinaryReaderTOC.ReadUInt24(); break; case 4: array[num2] = bigEndianBinaryReaderTOC.ReadUInt32(); break; } num2++; } this.inflateEntries(bigEndianBinaryReader, array.ToArray<uint>(), this.header.blockSize); this.ReadNames(); } } //str.Flush(); }
public void Read(Stream str) { this.Entries.Clear(); BigEndianBinaryReader bigEndianBinaryReader = new BigEndianBinaryReader(str); this.header.MagicNumber = bigEndianBinaryReader.ReadUInt32(); this.header.VersionNumber = bigEndianBinaryReader.ReadUInt32(); this.header.CompressionMethod = bigEndianBinaryReader.ReadUInt32(); this.header.TotalTOCSize = bigEndianBinaryReader.ReadUInt32(); this.header.TOCEntrySize = bigEndianBinaryReader.ReadUInt32(); this.header.numFiles = bigEndianBinaryReader.ReadUInt32(); this.header.blockSize = bigEndianBinaryReader.ReadUInt32(); this.header.archiveFlags = bigEndianBinaryReader.ReadUInt32(); var tocStream = str; BigEndianBinaryReader bigEndianBinaryReaderTOC = bigEndianBinaryReader; if (this.header.archiveFlags == 4) { var decStream = new TempFileStream(); using (var outputStream = new MemoryStream()) { RijndaelEncryptor.DecryptPSARC(str, outputStream, this.header.TotalTOCSize); int bytesRead; byte[] buffer = new byte[30000]; int decMax = (int)this.header.TotalTOCSize - 32; int decSize = 0; outputStream.Seek(0, SeekOrigin.Begin); while ((bytesRead = outputStream.Read(buffer, 0, buffer.Length)) > 0) { decSize += bytesRead; if (decSize > decMax) { bytesRead = decMax - (decSize - bytesRead); } decStream.Write(buffer, 0, bytesRead); } } decStream.Seek(0, SeekOrigin.Begin); str.Seek(this.header.TotalTOCSize, SeekOrigin.Begin); tocStream = decStream; bigEndianBinaryReaderTOC = new BigEndianBinaryReader(tocStream); } if (this.header.MagicNumber == 1347633490) { if (this.header.CompressionMethod == 2053925218) { byte b = 1; uint num = 256; do { num *= 256; b += 1; }while (num < this.header.blockSize); int num2 = 0; while (num2 < this.header.numFiles) { this.Entries.Add(new Entry { id = num2, MD5 = bigEndianBinaryReaderTOC.ReadBytes(16), zIndex = bigEndianBinaryReaderTOC.ReadUInt32(), Length = bigEndianBinaryReaderTOC.ReadUInt40(), Offset = bigEndianBinaryReaderTOC.ReadUInt40() }); num2++; } long decMax = (this.header.archiveFlags == 4) ? 32 : 0; uint num3 = (this.header.TotalTOCSize - (uint)(tocStream.Position + decMax)) / (uint)b; uint[] array = new uint[num3]; num2 = 0; while (num2 < num3) { switch (b) { case 2: array[num2] = (uint)bigEndianBinaryReaderTOC.ReadUInt16(); break; case 3: array[num2] = bigEndianBinaryReaderTOC.ReadUInt24(); break; case 4: array[num2] = bigEndianBinaryReaderTOC.ReadUInt32(); break; } num2++; } this.inflateEntries(bigEndianBinaryReader, array.ToArray <uint>(), this.header.blockSize); this.ReadNames(); } } str.Flush(); }
/// <summary> /// Returns the data unmodified. (New <see cref="TempFileStream"/> for semantic equivalence) /// </summary> /// <param name='data'> /// The data to be (de)compressed. /// </param> private static System.IO.Stream NullHandler(System.IO.Stream data) { System.IO.Stream tfs = new TempFileStream(); data.CopyTo(tfs); tfs.Seek(0, System.IO.SeekOrigin.Begin); return tfs; }
/// <summary> /// Returns the data decompressed using Gzip. /// </summary> /// <param name='data'> /// The data to be decompressed. /// </param> private static System.IO.Stream DecompressGz(System.IO.Stream data) { System.IO.Compression.GZipStream gz = new System.IO.Compression.GZipStream(data, System.IO.Compression.CompressionMode.Decompress); TempFileStream tfs = new TempFileStream(); gz.CopyTo(tfs); tfs.Seek(0, System.IO.SeekOrigin.Begin); return tfs; }
private void ReportProblem(MemoryTraceBuilder contextTraceBuilder, Exception exception, string functionName, bool isExceptionReport, bool isExceptionReportTerminating, bool verbose) { using (TempFileStream tempFileStream = TempFileStream.CreateInstance("Traces_", false)) { using (StreamWriter streamWriter = new StreamWriter(tempFileStream)) { bool addHeader = true; if (contextTraceBuilder != null) { lock (this) { contextTraceBuilder.Dump(streamWriter, addHeader, verbose); } addHeader = false; } MemoryTraceBuilder memoryTraceBuilder = ExTraceInternal.GetMemoryTraceBuilder(); if (memoryTraceBuilder != null) { memoryTraceBuilder.Dump(streamWriter, addHeader, verbose); } streamWriter.Flush(); } StringBuilder stringBuilder = new StringBuilder(1024); TroubleshootingContext.DumpExceptionInfo(exception, stringBuilder); if (TroubleshootingContext.IsTestTopology()) { string path = ExWatson.AppName + "_" + DateTime.UtcNow.ToString("yyyyMMdd_hhmmss") + ".trace"; try { File.Copy(tempFileStream.FilePath, Path.Combine(Path.Combine(Environment.GetEnvironmentVariable("SystemDrive"), "\\dumps"), path)); } catch { } } if (exception != TroubleshootingContext.FaultInjectionInvalidOperationException) { if (isExceptionReport) { WatsonExtraFileReportAction watsonExtraFileReportAction = null; try { watsonExtraFileReportAction = new WatsonExtraFileReportAction(tempFileStream.FilePath); ExWatson.RegisterReportAction(watsonExtraFileReportAction, WatsonActionScope.Thread); ExWatson.SendReport(exception, isExceptionReportTerminating ? ReportOptions.ReportTerminateAfterSend : ReportOptions.None, null); goto IL_152; } finally { if (watsonExtraFileReportAction != null) { ExWatson.UnregisterReportAction(watsonExtraFileReportAction, WatsonActionScope.Thread); } } } ExWatson.SendTroubleshootingWatsonReport("15.00.1497.012", this.location, "UnexpectedCondition:" + exception.GetType().Name, exception.StackTrace, functionName, stringBuilder.ToString(), tempFileStream.FilePath); IL_152: File.Delete(tempFileStream.FilePath); } } }
public override SubmissionStatus ServiceSubmit(string jobName, string fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions) { AttachDebugger(); var status = new SubmissionStatus(); status.Result = false; try { string username = GetPropertyResult("username", "", false); string password = GetPropertyResult("password", "", false); string destination = GetPropertyResult("destination", "", false); if (string.IsNullOrWhiteSpace(username)) { throw new Exception("Missing property: username"); } if (string.IsNullOrWhiteSpace(password)) { throw new Exception("Missing property: password"); } if (string.IsNullOrWhiteSpace(destination)) { throw new Exception("Missing property: destination"); } var outputImageType = GetProperty <OutputImageTypeProperty>("outputImageType", false); if (outputImageType == null) { throw new Exception("Missing property: outputImageType"); } DocumentRenderer renderingConverter = GetRenderer(outputImageType); if (renderingConverter != null) { TempFileStream outputStream = null; try { try { string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } catch (Exception) { // Ignore - attempt another temp location (UAC may block UI from accessing Temp folder. } if (outputStream == null) { string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\NewUpdPlugin\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler); outputStream.Seek(0, SeekOrigin.Begin); string jobId; if (SubmitDocumentWithCustomLogic(outputStream, username, password, destination, out jobId)) { status.Result = true; status.Message = "Successfully Submitted"; status.StatusCode = 0; status.LogDetails = "Submitted Document with ID: " + jobId + "\r\n"; } } finally { if (outputStream != null) { outputStream.Dispose(); outputStream = null; } } } } catch (Exception ex) { status.Result = false; status.Message = "An error has occurred."; status.LogDetails = ex.Message; status.NotifyUser = true; status.StatusCode = 12; } return(status); }
public unsafe void WriteMetadata(Stream stream, AudioMetadata metadata, SettingDictionary settings) { using (var tempStream = new TempFileStream()) { OggStream inputOggStream = null; OggStream outputOggStream = null; #if NETSTANDARD2_0 var buffer = ArrayPool <byte> .Shared.Rent(4096); #else Span <byte> buffer = stackalloc byte[4096]; #endif try { using (var sync = new OggSync()) { var headerWritten = false; OggPage page; var pagesWritten = 0u; do { // Read from the buffer into a page while (!sync.PageOut(out page)) { #if NETSTANDARD2_0 var bytesRead = stream.Read(buffer, 0, buffer.Length); #else var bytesRead = stream.Read(buffer); #endif if (bytesRead == 0) { throw new AudioInvalidException("No Ogg stream was found."); } var nativeBuffer = new Span <byte>(sync.Buffer(bytesRead).ToPointer(), bytesRead); #if NETSTANDARD2_0 buffer.AsSpan().Slice(0, bytesRead).CopyTo(nativeBuffer); #else buffer.Slice(0, bytesRead).CopyTo(nativeBuffer); #endif sync.Wrote(bytesRead); } if (inputOggStream == null) { inputOggStream = new OggStream(SafeNativeMethods.OggPageSerialNo(page)); } if (outputOggStream == null) { outputOggStream = new OggStream(inputOggStream.SerialNumber); } // Write new header page(s) using a modified comment packet if (!headerWritten) { inputOggStream.PageIn(page); while (inputOggStream.PacketOut(out var packet)) { switch (packet.PacketNumber) { case 0: outputOggStream.PacketIn(packet); break; // Substitute the new comment packet case 1: using (var adapter = new MetadataToOpusCommentAdapter(metadata)) { adapter.HeaderOut(out var commentPacket); outputOggStream.PacketIn(commentPacket); } headerWritten = true; break; default: throw new AudioInvalidException("Missing header packet."); } } // Flush at the end of each header while (outputOggStream.Flush(out var outPage)) { WritePage(outPage, tempStream); pagesWritten++; } } else { // Copy the existing data pages verbatim, with updated sequence numbers UpdateSequenceNumber(ref page, pagesWritten); WritePage(page, tempStream); pagesWritten++; } } while (!SafeNativeMethods.OggPageEos(page)); // Once the end of the input is reached, overwrite the original file and return stream.Position = 0; stream.SetLength(tempStream.Length); tempStream.Position = 0; tempStream.CopyTo(stream); } } finally { #if NETSTANDARD2_0 ArrayPool <byte> .Shared.Return(buffer); #endif inputOggStream?.Dispose(); outputOggStream?.Dispose(); } } }
public override SubmissionStatus ServiceSubmit(string jobName, string fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions) { AttachDebugger(); var status = new SubmissionStatus(); status.Result = false; try { string account = GetPropertyResult("account", ""); string username = GetPropertyResult("username", ""); string password = GetPropertyResult("password", ""); //string faxHeader = GetPropertyResult("faxHeader", ""); string faxTag = GetPropertyResult("faxTag", ""); string callerId = GetPropertyResult("callerId", ""); string faxNumber = GetPropertyResult("faxNumber", ""); bool? requireEncryption = GetPropertyResult <bool?>("requireEncryption", null); if (String.IsNullOrWhiteSpace(account)) { throw new Exception("Missing property: account"); } if (String.IsNullOrWhiteSpace(username)) { throw new Exception("Missing property: username"); } if (String.IsNullOrWhiteSpace(password)) { throw new Exception("Missing property: password"); } //if (String.IsNullOrWhiteSpace(faxHeader)) //{ // throw new Exception("Missing property: faxHeader"); //} if (String.IsNullOrWhiteSpace(faxNumber)) { throw new Exception("Missing property: faxNumber"); } if (requireEncryption == null) { throw new Exception("Missing property: requireEncryption"); } // Force OuptutImageType values. The user cannot change them for EtherFax. OutputImageTypeProperty outputImageType = new OutputImageTypeProperty("OutputImageType", "Output File Type") { UserGenerated = false, DocxOutputAllowed = false, XpsOutputAllowed = false, PdfOutputAllowed = false, TiffOutputAllowed = true, RenderMode = RenderModes.Raster_1, RenderModesAllowed = new List <RenderModes>() { RenderModes.Raster_1 }, TiffCompression = TiffCompressOption.Ccitt4, TiffCompressionsAllowed = new List <TiffCompressOption>() { TiffCompressOption.Ccitt4 }, RenderPixelFormat = PixelFormats.BlackWhite, RenderPixelFormatsAllowed = new List <PixelFormats>() { PixelFormats.BlackWhite } }; /* * https://tools.ietf.org/html/rfc2306 * * XResolution x Yresolution | ImageWidth * --------------------------------------------|------------------ * 204x98, 204x196, 204x391, 200x100, 200x200 | 1728, 2048, 2432 * 300x300 | 2592, 3072, 3648 * 408x391, 400x400 | 3456, 4096, 4864 * --------------------------------------------|------------------ * * These are the fixed page widths in pixels. The permissible values are dependent upon X and Y resolutions. * */ int faxHorizontalResolution = 204; int faxVerticalResolution = 196; outputImageType.HorizontalDpi = faxHorizontalResolution; outputImageType.VerticalDpi = faxVerticalResolution; int faxPageWidth = 1728; // 8.5" x 11" @ 204 x 196 dpi = 1734px x 2156px @ 99.6% => 1728px x 2148px (Desired fax width of 1728px @ 204 horizontal dpi) PointF pagePixels = pageDimensions[pageIndexStart].GetPixels(faxHorizontalResolution, faxVerticalResolution); float pageScaleRatio = faxPageWidth / pagePixels.X; int faxPageHeight = (int)(pageScaleRatio * pagePixels.Y); outputImageType.ImageDimensions = new System.Drawing.Point(faxPageWidth, faxPageHeight); DocumentRenderer renderingConverter = GetRenderer(outputImageType); if (renderingConverter != null) { // Read the image to memory byte[] fileBytes; TempFileStream outputStream = null; try { try { string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } catch (Exception) { // Ignore - attempt another temp location (UAC may block UI test button from accessing the default Temp folder.) } if (outputStream == null) { string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\EtherFax\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler); outputStream.Seek(0, SeekOrigin.Begin); fileBytes = new byte[outputStream.Length]; outputStream.Read(fileBytes, 0, fileBytes.Length); } finally { if (outputStream != null) { outputStream.Dispose(); outputStream = null; } } var offset = TimeZoneInfo.Local.GetUtcOffset(DateTime.UtcNow); status.Destination = "Fax: " + faxNumber; var client = new SampleEtherFaxApi(account, username, password); FaxStatus faxStatus = client.SendFax(faxNumber, faxTag, callerId, offset, fileBytes, ((pageIndexEnd - pageIndexStart) + 1), requireEncryption.Value); if (faxStatus.FaxResult == FaxResult.InProgress) { status.Result = true; status.Message = "Fax in progress."; status.NextStatusRefresh = DateTime.Now.AddSeconds(30); status.StatusCode = 0; var stateData = new UpdStatusState(); stateData.account = account; stateData.username = username; stateData.password = Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(password), _encryptionEntropy, DataProtectionScope.LocalMachine)); stateData.jobId = faxStatus.JobId; stateData.tagValue = faxTag; stateData.statusRetryCount = 0; status.State = JsonConvert.SerializeObject(stateData); status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n"; status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n"; } else if (faxStatus.FaxResult == FaxResult.Success) { status.Result = true; status.Message = "Your fax was delivered successfully."; status.StatusCode = 100; status.NotifyUser = true; status.LogDetails = "Your fax was delivered successfully!\r\n"; status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n"; status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n"; } else if (faxStatus.FaxResult == FaxResult.Cancelled) { status.Result = false; status.Message = "Your fax was cancelled."; status.StatusCode = 300; status.SeverityLevel = StatusResults.SeverityLevels.Low; status.NotifyUser = true; status.LogDetails = "Fax cancelled: " + faxStatus.ToString().Replace("_", " ") + "\r\n"; status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n"; status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n"; } else // All errors { status.Result = false; status.Message = "Your fax was not delivered. Reason: " + faxStatus.ToString().Replace("_", " "); status.StatusCode = 400 + (int)faxStatus.FaxResult; status.SeverityLevel = StatusResults.SeverityLevels.High; status.NotifyUser = true; status.LogDetails = "Fax failed: " + faxStatus.ToString().Replace("_", " ") + "\r\n"; status.LogDetails += "Submitted Fax with etherFAX ID: " + faxStatus.JobId + "\r\n"; status.LogDetails += "etherFAX Tag: " + faxTag + "\r\n"; } } } catch (WebException httpEx) { string webExDetails = ""; using (var httpResponse = httpEx.Response as HttpWebResponse) { if (httpResponse != null) { HttpStatusCode statusCode = httpResponse.StatusCode; string statusDescription = httpResponse.StatusDescription; string responseHeaders = httpResponse.Headers != null?httpResponse.Headers.ToString() : null; using (Stream stream = httpResponse.GetResponseStream()) { using (var sr = new StreamReader(stream)) { string content = sr.ReadToEnd(); webExDetails = "Status: " + statusCode.ToString() + @"/" + statusDescription + "\r\n\r\n" + "Response: " + content; } } } } status.Result = false; status.Message = "An error has occurred."; status.LogDetails = httpEx.Message + "\r\n\r\n" + webExDetails; status.NotifyUser = true; status.StatusCode = 11; } catch (Exception ex) { status.Result = false; status.Message = "An error has occurred."; status.LogDetails = ex.Message; status.NotifyUser = true; status.StatusCode = 12; } return(status); }
public override SubmissionStatus ServiceSubmit(string jobName, List <KeyValuePair <string, string> > fclInfo, Dictionary <string, string> driverSettings, Logger externalHandler, Stream xpsStream, int pageIndexStart, int pageIndexEnd, List <PageDimensions> pageDimensions) { AttachDebugger(); SubmissionStatus status = new SubmissionStatus(); status.Result = false; try { string recipientEmail = GetPropertyResult("Recipient_EmailAddress", "", false); string recipientName = GetPropertyResult("Recipient_Name", "", false); MailAddress emailRecipient = new MailAddress(recipientEmail, recipientName); status.Destination = emailRecipient.ToString(); using (SmtpClient smtpConn = new SmtpClient()) { using (MailMessage newMessage = new MailMessage()) { smtpConn.Host = GetPropertyResult("SMTP_Server", "", false); smtpConn.EnableSsl = (GetPropertyResult("SMTP_SSL", "", false) == "NO" ? false : true); string username = GetPropertyResult("SMTP_Username", "", false); if (!string.IsNullOrWhiteSpace(username)) { string smtpPassword = GetPropertyResult("SMTP_Password", "", false); smtpConn.Credentials = new System.Net.NetworkCredential(username, smtpPassword); } smtpConn.Port = GetPropertyResult("SMTP_Port", 587, false); string senderAddress = GetPropertyResult("Sender_EmailAddress", "", false); string senderName = GetPropertyResult("Sender_Name", "", false); newMessage.From = new MailAddress(senderAddress, senderName); newMessage.To.Add(emailRecipient); string ccAddress = GetPropertyResult("Recipient_CCEmailAddress", "", false); if (!string.IsNullOrWhiteSpace(ccAddress)) { newMessage.CC.Add(new MailAddress(ccAddress)); } string bccAddress = GetPropertyResult("Recipient_BCCEmailAddress", "", false); if (!string.IsNullOrWhiteSpace(bccAddress)) { newMessage.Bcc.Add(new MailAddress(bccAddress)); } newMessage.Subject = GetPropertyResult("Message_Subject", "", false); newMessage.Body = GetPropertyResult("Message_Body", "", false); string attachmentName = GetPropertyResult("Message_Attachment_Name", "", false); if (string.IsNullOrWhiteSpace(attachmentName)) { attachmentName = "Document"; } var outputImageType = GetProperty <OutputImageTypeProperty>("OutputImageType", false); if (outputImageType != null) { DocumentRenderer renderingConverter = GetRenderer(outputImageType); if (renderingConverter != null) { TempFileStream outputStream = null; try { try { string tempFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Temp\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } catch (Exception) { //Ignore - attempt another temp location (UAC may block UI from accessing Temp folder. } if (outputStream == null) { string tempFolder = Path.Combine(Path.GetTempPath(), @"FS_UPD_v4\Email_SMTP\"); Directory.CreateDirectory(tempFolder); outputStream = new TempFileStream(tempFolder); } renderingConverter.RenderXpsToOutput(xpsStream, outputStream, pageIndexStart, pageIndexEnd, externalHandler); outputStream.Seek(0, SeekOrigin.Begin); attachmentName += renderingConverter.FileExtension; Attachment mailAttachment = new Attachment(outputStream, attachmentName); newMessage.Attachments.Add(mailAttachment); smtpConn.Send(newMessage); } finally { if (outputStream != null) { outputStream.Dispose(); outputStream = null; } } } } } } status.Result = true; status.Message = "Successfully sent the email to " + emailRecipient.ToString(); status.StatusCode = 0; } catch (Exception ex) { externalHandler.LogMessage("SMTP Email Error: " + ex.ToString()); status.Message = "Email Error: " + ex.Message.ToString(); status.LogDetails = "Email Error: " + ex.ToString(); status.SeverityLevel = StatusResults.SeverityLevels.High; status.StatusCode = 1; status.IsUserCorrectable = false; status.NotifyUser = true; } externalHandler.LogMessage("SMTP Email Result: " + status.Result.ToString()); return(status); }