I hwas trying to generate a multi page XPS document from a web application and trying to stream that ona button click.
public class Class1
{
protected void btnGenerateLetter_OnClick(object sender, EventArgs e)
{
try
{
string sid = Request.Form["id"];
byte[] bytes = FlowDocumentToXPS(GenerateLetter(), 640, 800);
Response.Clear();
Response.ContentType = "application/vnd.ms-xpsdocument";
Response.AddHeader("Content-Disposition", "attachment; filename=document.xps");
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.Close();
}
catch (Exception ex)
{
}
}
private FlowDocument GenerateLetter()
{
FlowDocument flowDocument = new FlowDocument();
string Header = "Test Header Message";
string Body = "Content goes here";
string Footer = "Footer Text";
for (int i = 0; i < 3; i++)
{
Paragraph header = new Paragraph();
header.Margin = new System.Windows.Thickness(250, 100, 250, 10);
header.BreakPageBefore = true;
header.Inlines.Add(new Run(Header));
header.Inlines.Add(new LineBreak());
header.Inlines.Add(new LineBreak());
header.Inlines.Add(new LineBreak());
Paragraph body = new Paragraph();
body.Inlines.Add(new Run(Body));
body.Inlines.Add(new LineBreak());
body.Inlines.Add(new LineBreak());
Paragraph footer = new Paragraph();
footer.Inlines.Add(new Run(Footer));
flowDocument.Blocks.Add(header);
flowDocument.Blocks.Add(body);
flowDocument.Blocks.Add(footer);
}
return flowDocument;
}
public static byte[] FlowDocumentToXPS(FlowDocument flowDocument, int width, int height)
{
MemoryStream stream = new MemoryStream();
// create a package
using (Package package = Package.Open(stream, FileMode.CreateNew))
{
// create an empty XPS document
using (XpsDocument xpsDoc = new XpsDocument(package, CompressionOption.NotCompressed))
{
// create a serialization manager
XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false);
// retrieve document paginator
DocumentPaginator paginator = ((IDocumentPaginatorSource)flowDocument).DocumentPaginator;
// set page size
paginator.PageSize = new System.Windows.Size(width, height);
// save as XPS
rsm.SaveAsXaml(paginator);
rsm.Commit();
}
return stream.ToArray();
}
}
}
This wroks fine on the development environment.But getting this error when deployed on a different machine.(IIS6).
Startup URI: C:\Documents and Settings\050583b.syn\Desktop\document.xps
Application Identity:
System.IO.FileFormatException: File contains corrupted data.
at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream)
at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.SeekableLoad(ZipIOBlockManager blockManager)
at MS.Internal.IO.Zip.ZipIOBlockManager.LoadEndOfCentralDirectoryBlock()
at MS.Internal.IO.Zip.ZipArchive..ctor(Stream archiveStream, FileMode mode, FileAccess access, Boolean streaming, Boolean ownStream)
at MS.Internal.IO.Zip.ZipArchive.OpenOnStream(Stream stream, FileMode mode, FileAccess access, Boolean streaming)
at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at System.IO.Packaging.Package.Open(Stream stream)
at MS.Internal.Documents.Application.TransactionalPackage..ctor(Stream original)
at MS.Internal.Documents.Application.PackageController.MS.Internal.Documents.Application.IDocumentController.Open(Document document)
at MS.Internal.Documents.Application.DocumentManager.DispatchOpen(IDocumentController controller, Document document)
at MS.Internal.Documents.Application.DocumentManager.<>c__DisplayClass6.b__5(IDocumentController controller, Document subject)
at MS.Internal.Documents.Application.ChainOfResponsiblity2.Dispatch(Action action, S subject)
at MS.Internal.Documents.Application.DocumentManager.<>c__DisplayClass6.<OrderByLeastDependent>b__4(Document member)
at MS.Internal.Documents.Application.ChainOfDependencies1.OrderByLeastDependent(T member, Action action)
at MS.Internal.Documents.Application.DocumentManager.OrderByLeastDependent(DispatchDelegate action, Document document)
at MS.Internal.Documents.Application.DocumentManager.Open(Document document)
at MS.Internal.AppModel.ApplicationProxyInternal.InitContainer()
at MS.Internal.AppModel.ApplicationProxyInternal.Run(InitData initData)
I guess the problem is the with the bytes not completely getting written into the response.
Try the following and hopefully it should work.
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "application/vnd.ms-xpsdocument";
context.Response.AppendHeader("Content-Disposition", "attachment; filename=document.xps");
context.Response.End();
Related
I am working on ASP.net core Web API in server side and Angular 8 on Client side.
I need to compress a list of files and send to server and decompress in server. I use JSZip in client side to compress and my client side code is:
zipAndAddFileToUploader2(file: File): void {
const fileName = file.name
var url = URL.createObjectURL(file)
let self = this;
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
throw err;
}
var zip = new JSZip();
zip.file(fileName, data);
zip.generateAsync({type:'blob', compression: 'DEFLATE', compressionOptions: { level: 9 }})
.then(function(content) {
var file_object = new File([content], fileName, {type: 'application/zip'});
self.uploader.addToQueue([file_object]);
});
});
}
My Server side is as follows:
static byte[] Decompress(byte[] data)
{
byte[] byteArray = null;
using (var compressedStream = new MemoryStream(data))
using (MemoryStream decompressedFileStream = new MemoryStream(data))
{
using (GZipStream decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress))
{
decompressedFileStream.Position = 0;
decompressionStream.CopyTo(decompressedFileStream);//Exception ****
byteArray = decompressedFileStream.ToArray();
}
}
return byteArray;
}
CopyTo(decompressedFileStream) throws following exception:
Exception : The archive entry was compressed using an unsupported compression method.
Exception details:
at System.IO.Compression.Inflater.Inflate(FlushCode flushCode)
at System.IO.Compression.Inflater.ReadInflateOutput(Byte* bufPtr, Int32 length, FlushCode flushCode, Int32& bytesRead)
at System.IO.Compression.Inflater.ReadOutput(Byte* bufPtr, Int32 length, Int32& bytesRead)
at System.IO.Compression.Inflater.InflateVerified(Byte* bufPtr, Int32 length)
at System.IO.Compression.DeflateStream.CopyToStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.IO.MemoryStream.CopyTo(Stream destination, Int32 bufferSize)
at System.IO.Compression.DeflateStream.CopyToStream.CopyFromSourceToDestination()
at System.IO.Compression.DeflateStream.CopyTo(Stream destination, Int32 bufferSize)
at System.IO.Compression.GZipStream.CopyTo(Stream destination, Int32 bufferSize)
at System.IO.Stream.CopyTo(Stream destination)
at MyApp.MyService.Decompress(Byte[] data) in C:\...\MyService.cs:line 125
at MyApp.MyService.<UpdateMyFile>d__24.MoveNext() in C:\...\MyService.cs:line 137
Any help?
I hope this will be useful to someone.
The problem was in Server side. I changed the code and it is working. Thanks v much all your comments.
static byte[] Decompress(byte[] data)
{
MemoryStream memoryStream = new MemoryStream();
memoryStream.Write(data, 0, data.Length);
ZipArchive archive = new ZipArchive(memoryStream);
ZipArchiveEntry entry = archive.Entries.FirstOrDefault();
if (null == entry)
return null;
var stream1 = entry.Open();
using (var ms = new MemoryStream())
{
stream1.CopyTo(ms);
return ms.ToArray();
}
}
I have a web application developed in ASP.NET. I am using rdlc to do the reporting. Everything seems to work fine on my development machine, but not when I upload the application to the hosting service (GoDaddy.com). The reports show up as preview (ReportViewer Control). But when I click on Print it is not showing the preview.
public void print()
{
try
{
Warning[] warnings;
string[] streamids;
string mimeType;
string encoding;
string extension;
byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create);
fs.Write(bytes, 0, bytes.Length);
fs.Close();
//Open exsisting pdf
Document document = new Document(PageSize.A4);
PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
//Getting a instance of new pdf wrtiter
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
int i = 0;
int p = 0;
int n = reader.NumberOfPages;
Rectangle psize = reader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
//Add Page to new document
while (i < n)
{
document.NewPage();
p++;
i++;
PdfImportedPage page1 = writer.GetImportedPage(reader, i);
cb.AddTemplate(page1, 0, 0);
}
//Attach javascript to the document
PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
writer.AddJavaScript(jAction);
document.Close();
//Attach pdf to the iframe
frmPrint.Attributes["src"] = "Print.pdf";
}
catch (Exception ex)
{
Response.Write("<script>alert('Error Occured')</script>");
}
}
I am using the above code for print..
I create an asp.net 4.0 web application which has a web service for uploading images. I am uploading images by sending the image in form of Base64 string from my mobile app to the web service.
Following is my code:
public string Authenticate(string username, string password, string fileID, string imageData)
{
Dictionary<string, string> responseDictionary = new Dictionary<string, string>();
bool isAuthenticated = true; // Set this value based on the authentication logic
try
{
if (isAuthenticated)
{
UploadImage(imageData);
string result = "success";
var message = "Login successful";
responseDictionary["status"] = result;
responseDictionary["message"] = message;
}
}
catch (Exception ex)
{
responseDictionary["status"] = ex.Message;
responseDictionary["message"] = ex.StackTrace;
}
return new JavaScriptSerializer().Serialize(responseDictionary);
}
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
bitmap.Save(uploadPath, System.Drawing.Imaging.ImageFormat.Jpeg);
bitmap.Dispose();
}
This code was working fine on my local ASP.NET development server and I was able to see the uploaded image in my "uploads" directory. However, after transferring the code to the FTP directory, I am now getting the following error:
A generic error occurred in GDI+
I have checked that the upload directory has proper permission by creating a dummy .aspx page and creating a text file on page_load, and it works fine.
Even after doing google search, I was not able to solve this problem. Can anybody help me fixing this?
Thanks a lot in advance.
Instead of writing directly to files, save your bitmap to a MemoryStream and then save the contents of the stream to disk. This is an old, known issue and, frankly, I don't remember all the details why this is so.
MemoryStream mOutput = new MemoryStream();
bmp.Save( mOutput, ImageFormat.Png );
byte[] array = mOutput.ToArray();
// do whatever you want with the byte[]
In your case it could be either
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
// store the byte[] directly, without converting to Bitmap first
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( imageBytes );
}
or
private void UploadImage(string uploadedImage)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(uploadedImage);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Image.FromStream(ms);
string uploadPath = Server.MapPath("..\\uploads\\") + DateTime.Now.Ticks.ToString() + ".jpeg";
ms.Close();
// convert to image first and store it to disk
using ( MemoryStream mOutput = new MemoryStream() )
{
bitmap.Save( mOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
using ( FileStream fs = File.Create( uploadPath ) )
using ( BinaryWriter bw = new BinaryWriter( fs ) )
bw.Write( mOutput.ToArray() );
}
}
Furthermore I think it's worth pointing out that when MemoryStream is used, stream must always be closed and save method MUST be called before the stream closure
byte[] byteBuffer = Convert.FromBase64String(Base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
Bitmap bmpReturn = (Bitmap)Bitmap.FromStream(memoryStream);
bmpReturn.Save(PicPath, ImageFormat.Jpeg);
memoryStream.Close();
When pressing a button I have to create on client a text file, open it and then delete it.
I can create and open/download it with:
protected void btNotepadPending_Click(object sender, EventArgs e)
{
string sFileName = System.IO.Path.GetRandomFileName();
try
{
String testo = "XXX" + Environment.NewLine;
int iii = 0;
foreach (var item in lUserPending)
testo += ++iii + " - " + item.Item1 + " " + item.Item2;
//Create and populate a memorystream
MemoryStream mstream = GetTextAsStream(testo);
//Convert the memorystream to an array of bytes.
byte[] byteArray = mstream.ToArray();
//Clean up the memory stream
mstream.Flush();
mstream.Close();
// Clear all content output from the buffer stream
Response.Clear();
// Add a HTTP header to the output stream that specifies the default filename
// for the browser's download dialog
Response.AddHeader("Content-Disposition", "attachment; filename=delenda.txt");
// Add a HTTP header to the output stream that contains the
// content length(File Size). This lets the browser know how much data is being transfered
Response.AddHeader("Content-Length", byteArray.Length.ToString());
// Set the HTTP MIME type of the output stream
Response.ContentType = "application/octet-stream";
// Write the data out to the client.
Response.BinaryWrite(byteArray);
Response.Flush();
Response.Close();
}
catch (Exception exc)
{
MessageBox.SendErrorEmail("Exception: " + exc);
}
}
private MemoryStream GetTextAsStream(String text)
{
//Create the return memorystream object
MemoryStream ReturnStream = new MemoryStream();
//Create a streamwriter to write to the memory stream
StreamWriter WriteStream = new StreamWriter(ReturnStream);
//Write the text in the textbox to the Memory Stream.
WriteStream.WriteLine(text);
//Clean up the stream writer
WriteStream.Flush();
WriteStream.Close();
//Return the memory Stream
return ReturnStream;
}
but how to delete it?
I tried to put a delete when exiting on
protected override void OnUnload(EventArgs e)
{
if (IsPostBack)
{
if (File.Exists("delenda.txt"))
File.Delete("delenda.txt");
}
}
but it never stopped here. So how can I now when notepad (or any other associated program is closed?)
I'm new to FTP and asp.net my code works only during local host test however during live test on go-daddy i get error. any help would be great thank you.
I'm currently hosting 2 web site all the pages and code is in AMUS folder
Unable to connect to the remote server
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Net.WebException: Unable to connect to the remote server
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[WebException: Unable to connect to the remote server]
System.Net.FtpWebRequest.GetRequestStream() +839
DBMiddleTier.addImageFTP(FileUpload file) +360
Admin_CrudOperation.imgAddProduct_Click(Object sender, ImageClickEventArgs e) +96
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +115
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +120
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
My code
//method to add image ftp
public string addImageFTP(FileUpload file)
{
string filename = Path.GetFileName(file.FileName);
Bitmap src = Bitmap.FromStream(file.PostedFile.InputStream) as Bitmap;
Bitmap result = new Bitmap(src, 300, 300);
string saveName = savePath + filename;
result.Save(saveName, ImageFormat.Jpeg);
System.Net.FtpWebRequest request = System.Net.WebRequest.Create("ftp://***.***.***.*/AMUS/images/" + filename) as System.Net.FtpWebRequest;
//this example assumes the FTP site uses anoymous login on
//NetWorkCredentials provides credentials for password-based authentication such as digest, basic, NTLM
request.Credentials = new System.Net.NetworkCredential("Username", "Password");
//Copy the contents of the file to the request stream
byte[] fileContents = null;
if (file.HasFile)
{
//fileContents = FileUploadControl.FileBytes;
fileContents = File.ReadAllBytes(saveName);
}
else
{
string res = "you need to provide a file";
return res;
}
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
request.ContentLength = fileContents.Length;
//GetReequestStream: retrieves the stream used to upload data to an FTP server.
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
return "Successful Upload";
}
/// <summary>
/// ftpClient.upload("etc/test.txt", #"C:\Users\metastruct\Desktop\test.txt");
/// </summary>
/// <param name="remoteFile"></param>
/// <param name="localFile"></param>
public void uploadFile(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Establish Return Communication with the FTP Server */
ftpStream = ftpRequest.GetRequestStream();
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
try
{
while (bytesSent != 0)
{
ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
/// <summary>
/// ftp.uploadFolderContents("httpdocs/omid", #"E:\omid");
/// </summary>
/// <param name="remoteFolder"></param>
/// <param name="localFolder"></param>
/// <returns></returns>
public bool uploadFolderContents(string remoteFolder, string localFolder)
{
bool rslt = false;
try
{
string[] files = Directory.GetFiles(localFolder);
string[] dirs = Directory.GetDirectories(localFolder);
foreach (string file in files)
{
uploadFile(remoteFolder + "/" + Path.GetFileName(file), file);
}
foreach (string dir in dirs)
{
createFolder(remoteFolder + "/" + Path.GetFileName(dir));
uploadFolderContents(remoteFolder + "/" + Path.GetFileName(dir), dir);
}
rslt = true;
}
catch (Exception)
{
rslt = false;
}
return rslt;
}
/// <summary>
/// ftpClient.createDirectory("etc/test");
/// </summary>
/// <param name="newDirectory"></param>
public void createFolder(string newDirectory)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + newDirectory);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Resource Cleanup */
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}