Local Report. GetTotalPages() always return 0 - winforms

I have problem with Microsoft.Reporting.WinForms.LocalReport. Method GetTotalPages() always returns zero even after rendering and saving file. Report generated and saved correctly. Help, please.
foreach (DataSet.PersonsRow person in dataSet.Persons.Rows)
{
DataSet.PersonsDataTable persons = new DataSet.PersonsDataTable();
persons.ImportRow(person); ReportViewer rv = new ReportViewer();
string mimeType, encoding, fnameExtension;
string[] streamids; Warning[] warnings;
rv.ProcessingMode = ProcessingMode.Local;
rv.LocalReport.ReportPath = "ReportTemplates\\report.rdlc";
rv.LocalReport.SetParameters(new ReportParameter("Parameter", Settings.Parameter.ToString()));
rv.LocalReport.DataSources.Add(new ReportDataSource(dataSet.persons.TableName, (DataTable)persons));
rv.LocalReport.DataSources.Add(new ReportDataSource(dataSet.Profile.TableName, (DataTable)dataSet.Profile));
rv.LocalReport.DataSources.Add(new ReportDataSource(dataSet.Places.TableName, dataSet.Equipment.Where(tc => tc.PersonID == person.PersonID)));
byte[] bytes = rv.LocalReport.Render(OutputTypeStr, "<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>", out mimeType, out encoding, out fnameExtension, out streamids, out warnings);
int pagesCount = rv.LocalReport.GetTotalPages(); // pagesCount equal zero
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
fs.Write(bytes, 0, bytes.Length);
fs.Close();
pagesCount = rv.LocalReport.GetTotalPages(); // pagesCount also equal zero
}
}

I'd like point out that you are not using:
Microsoft.Reporting.WinForms.LocalReport.GetTotalPages();
but
Microsoft.Reporting.WinForms.ReportViewer.LocalReport.GetTotalPages();
Why do you create LocalReport lr if don't use it?
Hope this helps.

Related

With HelixToolkit.SharpDX.Wpf how do I set the DiffuseMap on a PhongMaterial from an ImageSource?

The DiffuseMap property of a PhongMaterial accepts a Stream.
If I have an ImageSource, how do I convert it to something acceptable to the property? Note that I need to be able to do this fast, in memory.
In the examples in the source code I can only find examples of loading images from file:
var image = LoadFileToMemory(new System.Uri(#"test.png", System.UriKind.RelativeOrAbsolute).ToString());
this.ModelMaterial = new PhongMaterial
{
AmbientColor = Colors.Gray.ToColor4(),
DiffuseColor = Colors.White.ToColor4(),
SpecularColor = Colors.White.ToColor4(),
SpecularShininess = 100f,
DiffuseAlphaMap = image,
DiffuseMap = LoadFileToMemory(new System.Uri(#"TextureCheckerboard2.dds", System.UriKind.RelativeOrAbsolute).ToString()),
NormalMap = LoadFileToMemory(new System.Uri(#"TextureCheckerboard2_dot3.dds", System.UriKind.RelativeOrAbsolute).ToString()),
};
LoadFileToMemory simply takes the bytes from a file and returns it as a MemoryStream.
By ImageSource you mean a BitmapSource or DrawingImage? ImageSource is the abstract base class for both of them.
If you have a BitmapSource you can convert it to a MemoryStream using:
private Stream BitmapSourceToStream(BitmapSource writeBmp)
{
Stream stream = new MemoryStream();
//BitmapEncoder enc = new PngBitmapEncoder();
//BitmapEncoder enc = new JpegBitmapEncoder();
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(writeBmp));
enc.Save(stream);
return stream;
}

SPFiles to .zip

As the title sugests, I have a list of SPFiles (sharepoint attachments) and I need to compress it and push to user download it.
I`ve looked for some examples here and tryed to code something but yet no success.
Here follow my last try until now
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
//string nomeEntrada = item.Substring(item.LastIndexOf("/") + 1);
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
//For testing only, to check if the .zip is beeing correctly generated
using (FileStream file = new FileStream("C:\\teste\\file.zip", FileMode.Create, System.IO.FileAccess.Write))
{
stream.Seek(0, SeekOrigin.Begin);
stream.CopyTo(file);
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/x-zip-compressed";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=anexos.zip");
HttpContext.Current.Response.BinaryWrite(stream.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
HttpContext.Current.Response.End();
}
PS: I do not want to save the file in server directory, that was just a test to check if the file was OK
I created an Application Page and redirected user to it. Since I can control the httpcontext by there, I coded the following and it worked just fine. The page quickly stream the file to client and them close itself. Hope it helps
using (var stream = new MemoryStream())
{
using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, true))
{
foreach (SPFile item in lstFiles)
{
var file = archive.CreateEntry(item.Name);
using (var entryStream = file.Open())
using (var streamWriter = new BinaryWriter(entryStream))
{
byte[] bytes = item.OpenBinary();
streamWriter.Write(bytes, 0, bytes.Length);
}
}
}
stream.Seek(0, SeekOrigin.Begin);
Byte[] byteArray = stream.ToArray();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.CacheControl = "public";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.AddHeader("Expires", "0");
HttpContext.Current.Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
HttpContext.Current.Response.AddHeader("Content-Description", "Report Export");
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=\"Anexos.zip\"");
HttpContext.Current.Response.BinaryWrite(byteArray);
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
}

How can I convert byte[] to BitmapImage?

I have a byte[] that represents the raw data of an image. I would like to convert it to a BitmapImage.
I tried several examples I found but I kept getting the following exception
"No imaging component suitable to complete this operation was found."
I think it is because my byte[] does not actually represent an Image but only the raw bits.
so my question is as mentioned above is how to convert a byte[] of raw bits to a BitmapImage.
The code below does not create a BitmapSource from a raw pixel buffer, as asked in the question.
But in case you want to create a BitmapImage from an encoded frame like a PNG or a JPEG, you would do it like this:
public static BitmapImage LoadFromBytes(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
return image;
}
}
When your byte array contains a bitmap's raw pixel data, you may create a BitmapSource (which is the base class of BitmapImage) by the static method BitmapSource.Create.
However, you need to specify a few parameters of the bitmap. You must know in advance the width and height and also the PixelFormat of the buffer.
byte[] buffer = ...;
var width = 100; // for example
var height = 100; // for example
var dpiX = 96d;
var dpiY = 96d;
var pixelFormat = PixelFormats.Pbgra32; // for example
var stride = (width * pixelFormat.BitsPerPixel + 7) / 8;
var bitmap = BitmapSource.Create(width, height, dpiX, dpiY,
pixelFormat, null, buffer, stride);
I ran across this same error, but it was because my array was not getting filled with the actual data. I had an array of bytes that was equal to the length it was supposed to be, but the values were all still 0 - they had not been written to!
My particular issue - and I suspect for others that arrive at this question, as well - was because of the OracleBlob parameter. I didn't think I needed it, and thought I could just do something like:
DataSet ds = new DataSet();
OracleCommand cmd = new OracleCommand(strQuery, conn);
OracleDataAdapter oraAdpt = new OracleDataAdapter(cmd);
oraAdpt.Fill(ds)
if (ds.Tables[0].Rows.Count > 0)
{
byte[] myArray = (bytes)ds.Tables[0]["MY_BLOB_COLUMN"];
}
How wrong I was! To actually get the real bytes in that blob, I needed to actually read that result into an OracleBlob object. Instead of filling a dataset/datatable, I did this:
OracleBlob oBlob = null;
byte[] myArray = null;
OracleCommand cmd = new OracleCommand(strQuery, conn);
OracleDataReader result = cmd.ExecuteReader();
result.Read();
if (result.HasRows)
{
oBlob = result.GetOracleBlob(0);
myArray = new byte[oBlob.Length];
oBlob.Read(array, 0, Convert.ToInt32(myArray.Length));
oBlob.Erase();
oBlob.Close();
oBlob.Dispose();
}
Then, I could take myArray and do this:
if (myArray != null)
{
if (myArray.Length > 0)
{
MyImage.Source = LoadBitmapFromBytes(myArray);
}
}
And my revised LoadBitmapFromBytes function from the other answer:
public static BitmapImage LoadBitmapFromBytes(byte[] bytes)
{
var image = new BitmapImage();
using (var stream = new MemoryStream(bytes))
{
stream.Seek(0, SeekOrigin.Begin);
image.BeginInit();
image.StreamSource = stream;
image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = null;
image.EndInit();
}
return image;
}
Create a MemoryStream from the raw bytes and pass that into your Bitmap constructor.
Like this:
MemoryStream stream = new MemoryStream(bytes);
Bitmap image = new Bitmap(stream);

Convert HttpPostedFileBase to byte[]

In my MVC application, I am using following code to upload a file.
MODEL
public HttpPostedFileBase File { get; set; }
VIEW
#Html.TextBoxFor(m => m.File, new { type = "file" })
Everything working fine .. But I am trying to convert the result fiel to byte[] .How can i do this
CONTROLLER
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = model.File; //Its not working .How can convert this to byte array
}
}
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.
For efficient purposes you could check whether the stream returned is already a MemoryStream:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
You can read it from the input stream:
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs method. You might find the following blog post useful.
byte[] file = new byte[excelFile.ContentLength];
excelFile.InputStream.Read(file, 0, file.Length);
//Create memory stream object from your bytes
MemoryStream ms = new MemoryStream(file);
// Set WorkbookPart , Sheet
using (var myDoc = DocumentFormat.OpenXml.Packaging.SpreadsheetDocument.Open(ms, true))

How to get Memory Stream/Base64 String from Image.Source?

I have a dynamically created Image control that is populated via a OpenFileDialog like:
OpenFileDialog dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
using (FileStream stream = dialog.File.OpenRead())
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(stream);
myImage.Source = bmp;
}
}
I want to send the image back to the server in a separate function call, as string via a web service.
How do I get a memory stream / base64 string from myImage.Source
Here's an alternative which should work (without BmpBitmapEncoder). It's uses the FileStream stream to create the byte array that is then converted to a Base64 string. This assumes you want to do this within the scope of the current code.
Byte[] bytes = new Byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
return Convert.ToBase64String(bytes);
Make sure you have http://imagetools.codeplex.com/
Then you can do this:
ImageSource myStartImage;
var image = ((WriteableBitmap) myStartImage).ToImage();
var encoder = new PngEncoder( false );
MemoryStream stream = new MemoryStream();
encoder.Encode( image, stream );
var myStartImageByteStream = stream.GetBuffer();
Then for Base64:
string encodedData = Convert.ToBase64String(myStartImageByteStream);

Resources