private void AssertTestCertFile(CertificateStore store, string fileName) { FileInfo f = new FileInfo(fileName); if (f.Exists) { Console.WriteLine(f.FullName); } if (!File.Exists(fileName)) { using (Stream stream = GetType().Assembly.GetManifestResourceStream("Library.Nunit.US.res." + fileName) ) { using (Stream certFile = File.OpenWrite(fileName)) { Streams.CopyStream(stream, certFile); certFile.Close(); } stream.Close(); } Certificate cert = Certificate.CreateFromPfxFile(fileName, "changeit", true); Certificate found = store.FindCertificateByKeyIdentifier(cert.GetKeyIdentifier()); if (found == null) { store.AddCertificate(cert); } } }
/** * We need to make sure that the url that we are trying to treat as a file * lies below the document root of the http server so that people can't grab * random files off your computer while this is running. */ public void ProcessRequest(AdkHttpRequestContext context) { try { FileInfo filename = new FileInfo(fVirtualDirectoryServer.MapPath(context.Request.Url)); if (!filename.FullName.StartsWith(fVirtualDirectoryServer.PhysicalPath)) { context.Response.Status = AdkHttpStatusCode.ClientError_403_Forbidden; } else { if (!filename.Exists) { if (filename.Extension == "") { context.Response.Status = AdkHttpStatusCode.Redirection_302_Found; string newUrl = context.Request.Url.AbsolutePath + "/"; context.Response.Headers["Location"] = newUrl; context.Response.AdditionalInfo = "<a href=\"" + newUrl + "\">" + newUrl + "</a>"; return; } else { throw new FileNotFoundException("File Not Found", filename.FullName); } } string aFileTime = filename.LastWriteTimeUtc.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT"; string aDateTime = context.Request.Headers["If-Modified-Since"]; if (aDateTime != null && aFileTime == aDateTime) { context.Response.Status = AdkHttpStatusCode.Redirection_304_Not_Modified; } else { context.Response.ContentType = GetContentType(filename); context.Response.Headers["Last-Modified"] = aFileTime; // Open the file using ( FileStream fs = new FileStream(filename.FullName, FileMode.Open, FileAccess.Read) ) { Streams.CopyStream(fs, context.Response.GetResponseStream(), 4096); fs.Close(); } } } } catch (FileNotFoundException) { context.Response.Status = AdkHttpStatusCode.ClientError_404_Not_Found; } }
/// <summary> /// Creates a new instance of MessageStreamImpl, based upon the underlying stream /// </summary> /// <param name="message"></param> public MessageStreamImpl(Stream message) { if (message.CanSeek) { fMessageStream = message; } else { fMessageStream = new MemoryStream(); Streams.CopyStream(message, fMessageStream); message.Close(); } }
public void SaveSheet(Package package, Sheet sheet) { var uri = new Uri($"/{sheet.Id}.json", UriKind.Relative); package.DeletePart(uri); var sheetPart = package.CreatePart(uri, "", CompressionOption.Normal); using var stringStream = Streams.GenerateStreamFromString(JsonConvert.SerializeObject(sheet, Formatting.Indented)); using Stream dest = sheetPart.GetStream(); Streams.CopyStream(stringStream, dest); }
/// <summary> /// Copies the message to the stream /// </summary> /// <param name="stream"></param> public void CopyTo(Stream stream) { SeekBeginning(); Streams.CopyStream(fMessageStream, stream); }
/// <summary> /// Copies the response buffer to the outgoing socket using an efficient asynchronous pattern. /// </summary> /// <param name="socket">The socket to write the result to</param> /// <param name="request">The source request</param> /// <param name="finishHandler">The delegate to call when the asynchronous operation is complete</param> /// <param name="asyncState">The state that should be returned to the async delegate</param> internal void AsyncFinishRequest(AdkSocketConnection socket, AdkHttpRequest request, bool keepAlive) { string statusDescription = ParseDescription(fStatus); if (this.Status != AdkHttpStatusCode.Success_200_OK) { this.Clear(); if (ShouldReturnBody(this.Status)) { this.Write("<html><head><title>"); this.Write(statusDescription); this.Write("</title></head><body><h1>HTTP "); this.Write(((int)fStatus).ToString()); this.Write(" "); this.Write(statusDescription); this.Write("</h1><br>"); this.Write(this.AdditionalInfo); this.Write("</body></html>"); } } // Flush our underlying stream. We are done writing to the response and we need the correct length this.Flush(); Stream outputStream = socket.GetOutputDataStream(); StreamWriter aWriter = new StreamWriter(outputStream); { aWriter.Write(request.Protocol); aWriter.Write(" "); aWriter.Write((int)fStatus); aWriter.Write(" "); aWriter.Write(statusDescription); aWriter.Write("\r\n"); aWriter.Write("Content-Length: " + fResponseStream.Length.ToString() + "\r\n"); if (keepAlive) { aWriter.Write("Connection: Keep-Alive\r\n"); } else { aWriter.Write("Connection: Close\r\n"); } foreach (string aKey in fHeaders.Keys) { aWriter.WriteLine("{0}: {1}", aKey, fHeaders[aKey]); } aWriter.Write(string.Empty + "\r\n"); aWriter.Flush(); GC.SuppressFinalize(aWriter); } if (socket.Connected && fResponseStream.Length > 0) { fWriter.Flush(); GC.SuppressFinalize(fWriter); fResponseStream.Seek(0, SeekOrigin.Begin); Streams.CopyStream(fResponseStream, outputStream, 4096); } }
public IActionResult Save(string file, string activeSheetId) { if (!System.IO.File.Exists(file)) { return(BadRequest()); } using (var p = Package.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.Read)) { var docUri = new Uri("/Document.json", UriKind.Relative); var documentpart = p.GetPart(docUri); Document document; using (var stream = documentpart.GetStream(FileMode.Open)) { var reader = new StreamReader(stream); document = JsonConvert.DeserializeObject <Document>(reader.ReadToEnd()); } document.Date = DateTime.Now; var cachedSheets = cache.GetSheets(); foreach (var cachedSheet in cachedSheets) { var sheet = cachedSheet; if (document.Sheets.ContainsKey(cachedSheet.Id)) { if (sheet.Deleted) { document.Sheets.Remove(sheet.Id); documentService.RemoveSheet(p, sheet.Id); continue; } sheet = documentService.LoadSheet(p, cachedSheet.Id); } document.Sheets[sheet.Id] = sheet.Name; if (sheet.Id == activeSheetId) { document.ActiveSheetId = activeSheetId; } foreach (var cahcedRow in cachedSheet.Rows.ToList()) { if (sheet.Rows.ContainsKey(cahcedRow.Key)) { var row = sheet.Rows[cahcedRow.Key]; foreach (var cachedCell in cahcedRow.Value.Cells.ToList()) { row.Cells[cachedCell.Key] = cachedCell.Value; } } else { sheet.Rows[cahcedRow.Key] = cahcedRow.Value; } } documentService.SaveSheet(p, sheet); } p.DeletePart(docUri); var docPart = p.CreatePart(docUri, "", CompressionOption.Normal); using var stringStream = Streams.GenerateStreamFromString(JsonConvert.SerializeObject(document, Formatting.Indented)); using var dest = docPart.GetStream(); Streams.CopyStream(stringStream, dest); } return(Ok()); }
/// <summary> Write a SifDataObject to the stream</summary> public override void Write(SifDataObject data) { // Check to see if the data object is null or if the // deferResponses() property has been set if (data == null || fDeferResponses) { return; } // Check to see if a SIF_Error has already been written if (fError != null) { throw new AdkException ("A SIF_Error has already been written to the stream", fZone); } // If the autoFilter property has been set, determine if this object meets the // conditions of the filter if (fFilter != null) { if (!fFilter.Evaluate(data)) { // TODO: Perhaps this feature should log any objects not written to the output // stream if extended logging is enabled return; } } try { if (fCurrentOutputStream == null || fZone.Properties.OneObjectPerResponse) { NewPacket(); } using (MemoryStream buffer = new MemoryStream()) { // Write to memory stream first so we can determine if the resulting // message will fit in the current packet WriteObject(data, buffer, fRenderAsVersion, fQueryRestrictions); if ((buffer.Length + fCurSize) > fMaxSize) { // If the current packet size is equal to the envelope size (e.g. no objects // have been written), we have exceeded the size of the buffer and need to abort if (buffer.Length == fEnvSize) { String errorMessage = "Publisher result data in packet " + fCurPacket + " too large (" + buffer.Length + " [Data] + " + fEnvSize + " [Sif Envelope] > " + fMaxSize + ")"; if (fZone.Properties.OneObjectPerResponse) { errorMessage += " [1 Object per Response Packet]"; } throw new AdkException(errorMessage, fZone); } else { // Create new packet for this object NewPacket(); } } if ((Adk.Debug & AdkDebugFlags.Message_Content) != 0) { buffer.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(buffer, SifIOFormatter.ENCODING); string message = reader.ReadToEnd(); fZone.Log.Debug ("Writing object to SIF_Response packet #" + fCurPacket + ":\r\n" + message); } buffer.Seek(0, SeekOrigin.Begin); Streams.CopyStream(buffer, fCurrentOutputStream); fCurSize += buffer.Length; buffer.Close(); } } catch (Exception ioe) { throw new AdkException ( "Failed to write Publisher result data (packet " + fCurPacket + ") to " + fFile.FullName + ": " + ioe, fZone); } }
public static int Convert(string inputFile, string outFile) { if (!File.Exists(inputFile)) { Console.Out.WriteLine($"File {inputFile} does not exist"); return(-1); } if (File.Exists(outFile)) { Console.Out.WriteLine($"File {outFile} already exist"); return(-1); } Console.Out.WriteLine($"Processing file {inputFile}..."); using (var zip = Package.Open(outFile, FileMode.CreateNew)) { var document = new Document { Date = DateTime.Now, IsArchived = false, Sheets = new Dictionary <string, string>() }; using (var stream = File.Open(inputFile, FileMode.Open, FileAccess.Read)) { using (var reader = ExcelReaderFactory.CreateReader(stream)) { var result = reader.AsDataSet(new ExcelDataSetConfiguration() { UseColumnDataType = true, ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration { UseHeaderRow = false, FilterRow = (rowReader) => rowReader.ResultsCount > 0, FilterColumn = (rowReader, columnIndex) => columnIndex < 3 } }); foreach (DataTable table in result.Tables) { if (table.Rows.Count == 0) { Console.Out.WriteLine($"Skipping empty sheet {table.TableName}"); continue; } Console.Out.WriteLine($"Processing sheet {table.TableName}"); var sheet = new Sheet { Id = Guid.NewGuid().ToString("D"), Name = table.TableName, Columns = new List <Column> { new Column { Name = "A" }, new Column { Name = "B" }, new Column { Name = "C" } } }; document.Sheets.Add(sheet.Id, sheet.Name); var i = 0; foreach (DataRow r in table.Rows) { var row = new Row { Cells = new Dictionary <string, string>() }; var y = 0; foreach (var o in r.ItemArray.Take(3)) { row.Cells.Add(y.ToString(), o.ToString()); y++; } sheet.Rows.Add(i.ToString(), row); i++; } var sheetUri = PackUriHelper.CreatePartUri(new Uri(".\\" + Path.GetFileName(sheet.Id + ".json"), UriKind.Relative)); if (zip.PartExists(sheetUri)) { zip.DeletePart(sheetUri); } var sheetPart = zip.CreatePart(sheetUri, "", CompressionOption.Normal); using (var stringStream = Streams.GenerateStreamFromString(JsonConvert.SerializeObject(sheet, Formatting.Indented))) { using (Stream dest = sheetPart.GetStream()) { Streams.CopyStream(stringStream, dest); } } } } } var uri = PackUriHelper.CreatePartUri(new Uri(".\\" + Path.GetFileName("Document.json"), UriKind.Relative)); if (zip.PartExists(uri)) { zip.DeletePart(uri); } var docPart = zip.CreatePart(uri, "", CompressionOption.Normal); using (var stringStream = Streams.GenerateStreamFromString(JsonConvert.SerializeObject(document, Formatting.Indented))) { using (Stream dest = docPart.GetStream()) { Streams.CopyStream(stringStream, dest); } } } return(0); }