Target Object Tag with PDF stream in HTML page - asp.net

I am using crystal reports in a .NET 2.0 asp.net website to create a PDF from the report. I then want to stream the report to the browser, which I already know how to do. What I don't know how to do is target the object tag the will hold the PDF. Does someone know how to do this within HTML with javascript or any other way?
Thanks in advance for any help that can be given.

I wanted to come back and answer this after finding out what I had to do. I had to create a separate aspx page and called it PDFView.aspx. I then added the code to the PageLoad event:
if (!IsPostBack)
{
ReportDocument rpt;
rpt = (ReportDocument)Session["CrystalReport"];
System.IO.Stream myStream;
CrystalDecisions.Shared.ExportOptions myExportOptions;
myExportOptions = myReport.ExportOptions;
myExportOptions.ExportFormatType = CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
myExportOptions.FormatOptions = new CrystalDecisions.Shared.PdfRtfWordFormatOptions();
CrystalDecisions.Shared.ExportRequestContext myExportRequestContext = new CrystalDecisions.Shared.ExportRequestContext();
myExportRequestContext.ExportInfo = myExportOptions;
//SetReportParameter("pPrinterFriendly", true, (ReportClass)myReport);
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ClearHeaders();
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
myStream = myReport.FormatEngine.ExportToStream(myExportRequestContext);
Byte[] myBuffer = new Byte[myStream.Length];
myStream.Read(myBuffer, 0, (int)myStream.Length);
System.Web.HttpContext.Current.Response.BinaryWrite(myBuffer);
System.Web.HttpContext.Current.Response.Flush();
}
I created the report object setting all parameters and datasource in the calling aspx page and the wrote the report to a session variable for retrieval when the PDFView.aspx page is loaded. I then used the code above to retrieve, execute and stream the report as a binary stream "the binary PDF" to the browsers response stream.
The PDFView.aspx page is referenced in the calling page with an object tag like this:
<object id="pdfObj" type="application/pdf" style="width:60%;height:95%;position:relative;top:2%;left:0%;right:10%;bottom:10%;margin:0px;padding:0px;border:0px;" data="PDFView.aspx"></object>

Related

Creating Reports in ASP.Net with Entity Framework

We are looking to add Microsoft Reports - SSRS to one of our internal websites.
The database has all the reporting features installed.
The website is using Entity Framework 4 for all data.
I have been able to create a report using the old fashioned way of creating a DataSet (*.XSD) and this works well.
My question though, is it possible to utilise the existing Entity Framework in the site for the data required by the reports? Rather than having to re-invent the wheel and make a whole DataSet, along with relationships etc..
It's a website and not application, so this (http://weblogs.asp.net/rajbk/archive/2010/05/09/creating-an-asp-net-report-using-visual-studio-2010-part-1.aspx) doesn't seem to apply; I don't see the DataSource (in part 2 of the tutorial)
Update
As a side-note, we would like to steer clear of expensive third-party controls etc.
Also, another way to look at the issue might be to generate the *.XSD from the entity framework entity model; is this possible? It's not ideal though would get us up and running..
Below is a quick sample of how i set the report datasource in one of my .NET winForms applications.
public void getMyReportData()
{
using (myEntityDataModel v = new myEntityDataModel())
{
var reportQuery = (from r in v.myTable
select new
{
l.ID,
l.LeaveApplicationDate,
l.EmployeeNumber,
l.EmployeeName,
l.StartDate,
l.EndDate,
l.Supervisor,
l.Department,
l.Col1,
l.Col2,
.......,
.......,
l.Address
}).ToList();
reportViewer1.LocalReport.DataSources.Clear();
ReportDataSource datasource = new ReportDataSource("nameOfReportDataset", reportQuery);
reportViewer1.LocalReport.DataSources.Add(datasource);
Stream rpt = loadEmbededReportDefinition("Report1.rdlc");
reportViewer1.LocalReport.LoadReportDefinition(rpt);
reportViewer1.RefreshReport();
//Another way of setting the reportViewer report source
string exeFolder = Path.GetDirectoryName(Application.ExecutablePath);
string reportPath = Path.Combine(exeFolder, #"rdlcReports\Report1.rdlc");
reportViewer1.LocalReport.ReportPath = reportPath;
reportParameter p = new ReportParameter("DeptID", deptID.ToString());
reportViewer1.LocalReport.SetParameters(new[] { p });
}
}
public static Stream loadEmbededReportDefinition(string reportName)
{
Assembly _assembly = Assembly.GetExecutingAssembly();
Stream _reportStream = _assembly.GetManifestResourceStream("ProjectNamespace.rdlcReportsFolder." + reportName);
return _reportStream;
}
My approach has always been to use RDLC files with object data sources and run them in 'local' mode. These data sources are ... my entities! This way, I'm using all of the same business logic, string formatting, culture awareness, etc. that I use for my web apps. There are a some quirks, but I've been able to live with them:
RDLC files don't like to live in web projects. We create a separate dummy winform project and add the RDLC files there.
I don't show reports in a viewer. I let the user download a PDF, Word, or Excel file and choose to save or open in the native viewer. This saves a bunch of headaches, but can put some folks off, depending on requirements. For mobile devices, it's pretty nice.
Since you are not using SSRS, you don't get the nice subscription feature. You are going to build that, if required. In many ways, though, I prefer this.
However, the benefits are really nice:
I'm using all of the same business logic goodness that I've already written for my views.
I have a custom ReportActionResult and DownloadReport controller method that allows me to essentially run any report via a single URL. This can be VERY handy. It sure makes a custom subscription component easier.
Report development seems to go pretty quick, now that I only need to adjust entity partial classes to tweak a little something here or there. Also - If I need to shape the data just a bit differently, I have LINQ.
We too use SSRS as "local" reports. We create Views in SQL server, then create that Object in our application along with the other EF Domain Models, and query that object using our DbContext. We use an ASPX page and use the code behind (Page_Load) to get the data passed to the report.
Here is an example of how we query it in the Page_Load Event:
var person = MyDbContext
.Query<ReportModel>()
.Where(x => x.PersonId == personId)
.Where(x => x.Year == year)
.Select(x =>
{
PersonId = x.PersonId,
Year = x.Year,
Name = x.Name
});
var datasource = new ReportDataSource("DataSet1", person.ToList());
if (!Page.IsPostBack)
{
myReport.Visible = true;
myReport.ProcessingMode = ProcessingMode.Local;
myReport.LocalReport.ReportPath = #"Areas\Person\Reports\PersonReport.rdlc";
}
myReport.LocalReport.DataSources.Clear();
myReport.LocalReport.DataSources.Add(datasource);
myReport.LocalReport.Refresh();
The trick is to create a report (.rdlc) with a blank data source connection string, a blank query block and a blank DataSetInfo (I had to modify the xml manually). They must exist in file and be blank as follows:
SomeReport.rdlc (viewing as xml)
...
<DataSources>
<DataSource Name="conx">
<ConnectionProperties>
<DataProvider />
<ConnectString />
</ConnectionProperties>
<rd:DataSourceID>19f59849-cdff-4f18-8611-3c2d78c44269</rd:DataSourceID>
</DataSource>
</DataSources>
...
<Query>
<DataSourceName>conx</DataSourceName>
<CommandText />
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>
</Query>
<rd:DataSetInfo>
<rd:DataSetName>SomeDataSetName</rd:DataSetName>
</rd:DataSetInfo>
now in a page event, I use a SelectedIndexChanged on a DropDownList, bind the report datasource as follows:
protected void theDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
if (theDropDownList.SelectedIndex == 0)
return;
var ds = DataTranslator.GetRosterReport(Int64.Parse(theDropDownList.SelectedValue));
_rvReport.LocalReport.ReportPath = "SomePathToThe\\Report.rdlc";
_rvReport.LocalReport.DataSources.Add(new ReportDataSource("SomeDataSetName", ds));
_rvReport.Visible = true;
_rvReport.LocalReport.Refresh();
}
You can use a WCF-Service as Datasource and so re-use your application data and logic for your report. This requires a SQL-server standard edition at least i believe. So no can do with the free SQL-express edition.
You can use LINQ with RDLC Report which is quite easy to use
LinqNewDataContext db = new LinqNewDataContext();
var query = from c in db.tbl_Temperatures
where c.Device_Id == "Tlog1"
select c;
var datasource = new ReportDataSource("DataSet1", query.ToList());
ReportViewer1.Visible = true;
ReportViewer1.ProcessingMode = ProcessingMode.Local;
ReportViewer1.LocalReport.ReportPath = #"Report6.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
ReportViewer1.LocalReport.Refresh();

How to access the properties and parts of an SSRS report at runtime

I'm using the ReportViewer control to display a server report in an ASP.NET page and I'm looking for a way to get the report into an object that I can then read and/or modify.
This kind of thing:
var rw = report.Width;
var t = ((Chart)report.Body.Item[3]).Title;
Is there a way, or am I stuck with parsing the XML file?
ETA:
I'm beginning to think I will need to access the XML file but I can't find out how to download that from the server, modify it (in memory) and then send it to the ReportViewer control.
ETA2:
Here's how to download the report definition (clean up left out for brevity):
// Download the report
var rs = new ReportingService2010();
rs.UseDefaultCredentials = true;
var reportDefinition = rs.GetItemDefinition("/DashboardReports/MyChart");
// Convert to XML
var ms = new MemoryStream(reportDefinition);
var doc = new System.Xml.XmlDocument();
doc.Load(ms);
// To load the stream into the report viewer
stream.Position = 0; // needed because we used the stream above - doc.Load(ms)
this.ReportViewer1.ServerReport.LoadReportDefinition(stream);

How to read HtmlDocument in ASP.NET?

i have an aspx page,there is textbox to write an url and a button to show some pictures that are in that url.I can load the url's source code to HtmlDocument.but i dont know how to load pictures from that html source code to show that pictures in my page.How can i do that ? Thanks in advance
You need to make the question more clear so that one can give you a specific answer.
HTML is a markup language which means that there are only format tags, there are no pictures embedded in a .html document. There are only links to images that are urls that can be accessed trough some address. In order to get the images you need to get that url.
If your question is how you can get the actual html from a link then refer to the following question. But, since you say that you can get the html, then you need to parse it using Regex or HTML Agility Pack.
Code to get the image:
byte[] imageData = DownloadData(Url); //DownloadData function from here
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);
stream.Close();
for method DownloadData you can use WebClient or WebRequest to get the image in a byte array:
WebRequest req = WebRequest.Create("[URL here]");
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
byte[] b;
using (BinaryReader br = new BinaryReader(stream))
{
b = br.ReadBytes(size);
br.Close();
}
return b;

adding dynamic message at end of flash video

I am working on a Flash training video. I would like at the end of the video for a message to pop up with a dynamic confirmation code. I have the code for the confirmation code, but am having trouble creating something either at the end of the flash video or within the aspx page to trigger this message. Any thoughts or ideas of how to solve this would be greatly appreciated.
Thank You.
Depend on the purpose of the application, you can do either one. One thing to consider is does the user has to go through the flash video to obtain the code. If so, you need to organize the flow of the application in a way that the user can't cheat their way to obtain the code.
The ideal way is to have the flash called aspx page at the end of the movie to obtain the dynamic code. This can be done using URLLoader in ActionScript 3.0 or LoadVars in ActionScript 2.0.
URLLoader example
//this is the data
var data = "This is data";
//url of your aspx code
var request:URLRequest = new URLRequest("http://www.yourdomain.com/GenerateCode.aspx");
request.contentType = "text/xml";
request.data = data;
//use POST method
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
try
{
//execute the request
loader.load(request);
}
catch (error:ArgumentError)
{
trace("There is an ArgumentError.");
}
LoadVars example:
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received response from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "Error!";
}
}
//this is the data
lv_out.data = "This is data";
//begin invoke aspx page
lv_out.sendAndLoad("GenerateCode.aspx", lv_in, "POST");
There another easier way but not the best practice i should say. The easier way would be to direct user to aspx page that generate dynamic code after users finish the flash movie. The negative side is, the page can be accessed although users did not finish the flash movie.

How to pass content of image file from fileupload control to web method via javascript?

I have a problem with using binary content of file. I want to pass web method content of file. I retriev it from fileupload control on my page via javascript function getAsBinary(). But error appears in web method, when I try to create example of class Image.
So, I have the page (.aspx) with fileupload control and scriptmanager. There are three javascript function:
// Get image from fileupload control and pass it in webmethod
function Get_image() {
var file_uploader = document.getElementById(file_uploader_name);
var file_content = file_uploader.files[0].getAsBinary();
imupcon.Get_image(file_content, OnRequestComplete, OnError);
}
// Successful execution
function OnRequestComplete(result) {alert(result);}
//Error execution
function OnError() { alert("Error!");}
And I have web-service with web-method:
[WebMethod]
public string Get_image(string file_content, string file_name)
{
byte[] data = Encoding.Unicode.GetBytes(file_content);
MemoryStream memStream = new MemoryStream();
memStream.Write(data, 0, data.Length);
//Error appears here
System.Drawing.Image image = System.Drawing.Image.FromStream(memStream);
memStream.Close();
return "Hurray!";
}
Does any have idea, what is reason? How I can pass content of file to web method? Thanks.
You don't need Encoding.Unicode.GetBytes if it's as it's already in binary. The data would be in unicode if you called files[0].getAsText("utf-8"). Please note that all of these methods are now obsolete and you should use feature detection and use the standard FileReader API if it is available.

Resources