how to export a local report to a pdf and excel file? - asp.net

I have two web pages, page1.aspx and page2.aspx. In page1, there is a button; in page2, there is a local report (rdlc). When I click the button, it will bring up page2, and exporting the report to a pdf and excel file. If the report is Crystal Report, in the page_load of page2, I can call the function ExportToDisk(ExportFormatType, FileName) to export the report to pdf/excel. But now I am using local report (rdlc), I wonder how do I export it to a pdf/excel.

http://weblogs.asp.net/rajbk/archive/2006/03/02/How-to-render-client-report-definition-files-_28002E00_rdlc_2900_-directly-to-the-Response-stream-without-preview.aspx
/// <summary>
/// References:
/// </summary>
private void RenderReport() {
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Report.rdlc");
//A method that returns a collection for our report
//Note: A report can have multiple data sources
List<Employee> employeeCollection = GetData();
//Give the collection a name (EmployeeCollection) so that we can reference it in our report designer
ReportDataSource reportDataSource = new ReportDataSource("EmployeeCollection", employeeCollection);
localReport.DataSources.Add(reportDataSource);
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
//http://msdn2.microsoft.com/en-us/library/ms155397.aspx
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render the report
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Clear the response stream and write the bytes to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=foo." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}

Related

asp.net C# webform show report without reportviewer

currently i want to generate the report without showing in reportviewer. I search for the solution online but i only can find the MVC approach. I cant convert it to normal webform behavior.
public ActionResult Report(string id)
{
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
return View("Index");
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
return File(renderedBytes, mimeType);
}
enter code here
Here is the sample of code that can allow user to generate the report in different format such as PDF, excel, image. ( http://www.dotnetawesome.com/2013/09/microsoft-report-in-mvc-4.html ).
Anyone can help or provide me a website which have a simple tutorial of that by using the SQL select statement instead of LINQ ?
As far as returning the report from a WebForms page, what you have above is actually pretty close. You want to return the renderedBytes array through the Response object of your current Page context like:
protected void ReportPrint_Click(object sender, EventArgs e)
{
string id = "PDF"; // get this from another control on your page
LocalReport lr = new LocalReport();
string path = Path.Combine(Server.MapPath("~/Report"), "ReportStateArea.rdlc");
if (System.IO.File.Exists(path))
{
lr.ReportPath = path;
}
else
{
// handle error condition
}
List<StateArea> cm = new List<StateArea>();
using (PopulationEntities dc = new PopulationEntities())
{
cm = dc.StateAreas.ToList();
}
ReportDataSource rd = new ReportDataSource("MyDataset", cm);
lr.DataSources.Add(rd);
string reportType = id;
string mimeType;
string encoding;
string fileNameExtension;
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>" + id + "</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>1in</MarginLeft>" +
" <MarginRight>1in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = lr.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
Response.Clear(); // we're going to override the default page response
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=report." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
This will replace the normal page response with your report content.
As far as SQL vs Linq, the DataSource object that ReportViewer uses is the old-style System.Data.DataTable so just look for information on populating a DataTable from SQL.

Asp.Net not only create a text file on client but also delete it

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?)

rdlc Report works in local but not on server

I have a report with some datasets, working perfectly in local, but on the server i get the error :
One or more parameters required to run the report have not been specified.
I don't have any parameters on this report, so i don't understand this error... I have this code in controller :
public ActionResult RunReport(int PremiseId)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath("~/Views/Report/PremisePricing.rdlc");
Premise premise = _db.GetPremise(PremiseId);
ICollection<PremisePricing> premisePricings;
if (premise.PremiseMeters.Count() > 0)
{
premisePricings = premiseMeterPricingToPremisePricing(_db.FindAllPremiseMeteredPricing(premise).ToList());
}
else
{
premisePricings = _db.FindAllPremisePricing(PremiseId).ToList();
}
// Add your data source
List<ReportDataSource> listDS = new List<ReportDataSource>();
ICollection<Premise> premises = new List<Premise>();
premises.Add(premise);
ReportDataSource premiseDS = new ReportDataSource("Premise", premises);
listDS.Add(premiseDS);
ReportDataSource premisePricingDS = new ReportDataSource("PremisePricing", premisePricings);
listDS.Add(premisePricingDS);
ICollection<CompanyProvider> companyProviders = new List<CompanyProvider>();
CompanyProvider companyProvider = _db.GetCompanyProvider();
companyProviders.Add(companyProvider);
ReportDataSource companyProviderDS = new ReportDataSource("CompPro", companyProviders);
listDS.Add(companyProviderDS);
ICollection<CompanyProviderContactManager> companyProviderContactManager = new List<CompanyProviderContactManager>();
if (companyProvider.CompanyProviderContactManager != null)
{
companyProviderContactManager.Add(companyProvider.CompanyProviderContactManager);
}
ReportDataSource companyProviderContactManagerDS = new ReportDataSource("CompProContactManager", companyProviderContactManager);
listDS.Add(companyProviderContactManagerDS);
ICollection<Customer> customer = new List<Customer>();
if (_db.GetPremiseProviderByPremiseId(PremiseId) != null)
{
Customer cust = _db.GetPremiseProviderByPremiseId(PremiseId).Customer;
customer.Add(cust);
}
ReportDataSource customerDS = new ReportDataSource("Customer", customer);
listDS.Add(customerDS);
RenderReport(localReport, listDS, companyProvider.logo);
return View();
}
private void RenderReport(LocalReport localReport, List<ReportDataSource> listDS, byte[] logo)
{
foreach (ReportDataSource ds in listDS)
{
localReport.DataSources.Add(ds);
}
HttpContextBase imageDirectoryPath = HttpContext;
string reportType = "PDF";
string mimeType;
string encoding;
string fileNameExtension;
//The DeviceInfo settings should be changed based on the reportType
string deviceInfo =
"<DeviceInfo>" +
" <OutputFormat>PDF</OutputFormat>" +
" <PageWidth>8.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
//Render
renderedBytes = localReport.Render(
reportType,
deviceInfo,
out mimeType,
out encoding,
out fileNameExtension,
out streams,
out warnings);
//Write to the outputstream
//Set content-disposition to "attachment" so that user is prompted to take an action
//on the file (open or save)
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "attachment; filename=Pricing." + fileNameExtension);
Response.BinaryWrite(renderedBytes);
Response.End();
}
Any suggestion?

force chrome to open downloaded pdf in a viewer

I have written the code for downloading a pdf file over http request.
public void downloadDocument(HttpServletRequest request,
HttpServletResponse response, #PathVariable("id") String docId)
throws Exception {
HttpSession session = request.getSession(true);
int accountId = (Integer) session.getAttribute("ownerAccountId");
Map<String, String> docMap = DbInteractor.getUploadedDocsByDocId(
Integer.valueOf(docId), accountId);
String docName = docMap.get("name");
String typeName = docMap.get("type");
String[] fileName = docName.split("\\.(?=[^\\.]+$)");
typeName= typeName.replace(" ", "");
if (typeName.equals("CCD/CCR")) {
typeName = "CCDorCCR";
}
String filename = typeName + docId + "." + fileName[1];
System.out.println(filename);
FileInputStream fileInputStream = new FileInputStream(
Constants.DOCUMENTS_PATH + filename);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-disposition", "attachment; filename="
+ docName);
OutputStream os = response.getOutputStream();
IOUtils.copy(fileInputStream, os);
os.flush();
os.close();
}
But the file is getting automatically downloaded in chrome .Is there any way to force chrome to open this document in a viewer(or to ask for an open with dialog in chrome)
You are forcing the browser to download by sending "Content-Disposition: attachment".

Reportviewer print button in Google Chrome

for what I've read, reportviewer print button doesn't work in Google Chrome and Firefox because it's made with an ActiveX control which only works in IE. So I was trying to make an asp.net button outside the report and print the report programatically, but it's being a pain and I was wondering if there is a simpler workaround to get the report to print in Google Chrome.
Edit/Update: I've found this reportviewer print button which is supposed to work for Firefox and Google Chrome, it seems to be working for Firefox but it prints me a blank page in Google Chrome. http://cafalse.blogspot.com/2011/04/reportviewer-print-button-for-firefox.html
If you don't mind adding your own button somewhere on the page. This only works if your way of generating the report looks similar to mine. Basically I take the Report, render it into bytes and send those bytes as a Response in pdf format. This will open up the file as PDF which most browser such as Chrome support. This requires the user to take the extra step and click print.
ServerReport sr = new ServerReport();
ReportViewer.ProcessingMode = ProcessingMode.Remote;
sr = ReportViewer.ServerReport;
sr.ReportServerUrl = new Uri("http://****/****");
sr.ReportPath = "/Report";
ReportParameter paramDateFrom = new ReportParameter();
ReportParameter paramDateTo = new ReportParameter();
ReportParameter paramState = new ReportParameter();
ReportParameter paramCounty = new ReportParameter();
string dateFrom = TB_Date_From.Text;
string dateTo = TB_Date_To.Text;
string state = DDL_State.SelectedValue;
string county = DDL_County.SelectedValue;
paramDateFrom.Name = "DateFrom";
paramDateFrom.Values.Add((dateFrom != "" ? dateFrom : null));
paramDateTo.Name = "DateTo";
paramDateTo.Values.Add((dateTo != "" ? dateTo : null));
paramState.Name = "State";
paramState.Values.Add((state != "" ? Common_Functions.resolveStateID(state) : null));
paramCounty.Name = "County";
paramCounty.Values.Add((county != "" ? Common_Functions.resolveCountyID(county) : null));
ReportViewer.ServerReport.SetParameters(new ReportParameter[] { paramDateFrom, paramDateTo, paramState, paramCounty });
// DUMP PDF TO BROWSER
Warning[] warnings;
string[] streamids;
string mimeType, encoding, extension;
byte[] bytes = ReportViewer.ServerReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);
Response.Buffer = true;
Response.Clear();
Response.ContentType = mimeType;
Response.AddHeader("content-disposition", "inline; filename=myfile." + extension);
Response.BinaryWrite(bytes);
string pdfPath = Server.MapPath("~") + "pdf." + extension;
FileStream pdfFile = new FileStream(pdfPath, FileMode.Create);
pdfFile.Write(bytes, 0, bytes.Length);
pdfFile.Close();
Response.Flush();
Response.End();

Resources