Crystal Report in VS2008 doesn't display data on web - asp.net

I have a problem with my crystal reports in Visual Studio 2008, and after searching and searching I got nothing.
My file CrystalReportxxx.rpt has an xsd file as dataschema. A datatable is created and it's passed to report as datasource. To fill the datatable, my application connects to Oracle database.
For showing rows or data with CrystalReportViewer, the report needs credentials like logid and password of database. However, if I export this report to a PDF file, then no credentials are needed and PDF file shows all rows.
This is my code:
Dim dt As DataTable
FunctionsOP.CreaDataTable("pkg_list.sp_list", True, ospEntry,
dt)
Dim oRpt As New Reportes.CrystalReportxxx
oRpt.SetDatabaseLogon("userxxx", "passwordxxx")
oRpt.SetDataSource(dt)
CrystalReportViewer1.EnableDatabaseLogonPrompt = False
CrystalReportViewer1.ReportSource = oRpt
CrystalReportViewer1.DataBind()
CrystalReportViewer1.Dispose()
I suppose that when setting:
oRpt.SetDatabaseLogon("userxxx", "passwordxxx")
and report shows no data, is because credentials are wrong.
My question is: How to bypass this credential input?
Is it mandatory to input userid, password, etc for using a xsd file in my Crystal
Report?
What is strange to me is that when I export that report to PDF, there is no
problem. Data is shown OK and no credential is needed:
Dim exportOpts As ExportOptions = oRpt.ExportOptions
oRpt.ExportOptions.ExportFormatType =
ExportFormatType.PortableDocFormat
oRpt.ExportOptions.ExportDestinationType =
ExportDestinationType.DiskFile
oRpt.ExportOptions.DestinationOptions = New
DiskFileDestinationOptions
CType(oRpt.ExportOptions.DestinationOptions,
DiskFileDestinationOptions).DiskFileName = Server.MapPath("../Temp/" +
PDFName)
oRpt.Export()
oRpt.Close()
oRpt.Dispose()
I also tried this code:
Dim dt1 As New DataTable : Dim dt2 As New DataTable
Dim oRpt As New Reportes.CR_IndicadorA11
Dim ParRep As ReportClass = oRpt
SetConnectionsReports(ParRep)
FunctionsOP.CreaDataTable("pkg_Listar_Tipos.sp_indicador_a11_sum", True, Nothing, dt1)
FunctionsOP.CreaDataTable("pkg_Listar_Tipos.sp_indicador_a11_det", True, Nothing, dt2)
oRpt.SetDataSource(dt1)
oRpt.OpenSubreport("CR_sub_indicadorA11_det.rpt").SetDataSource(dt2)
CrystalReportViewer1.Visible = True
CrystalReportViewer1.EnableDatabaseLogonPrompt = False
CrystalReportViewer1.ReportSource = oRpt
CrystalReportViewer1.DataBind()
CrystalReportViewer1.Dispose()
Public Sub SetConnectionsReports(ByRef Rpt As ReportClass)
Dim server, base, user, pass As String
server = "SRVBDDESA2.DOMINTERN0XXX.LOCAL" ' also with IP number is the same
base = "DESAOPINT"
user = "ORGPOL"
pass = "desarrollo"
For Each connection As IConnectionInfo In Rpt.DataSourceConnections
connection.SetConnection(server, base, user, pass)
Next
End Sub

Related

Open XML SDK Open and Save not working

I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)

Export Crystal Report to PDF in a Loop only works with first

i'm trying to generate a report and export it to pdf in a loop, the report will receive a new parameter in each loop and prompt the client to download a PDF, in other words, the client may need to download 2 or 3 (or more) PDFs at the same time, the problem is that the prompt to accept the download only appears for the first pdf, dont know why. I can export to disk (server side) without any problems.
Code:
Sub PrintReport(ByVal Cod As Integer)
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.SQL
ConnInfo.ServerName = ConfigurationManager.AppSettings("SQLSERVERNAME")
ConnInfo.DatabaseName = ConfigurationManager.AppSettings("SQLDBNAME")
ConnInfo.UserID = ConfigurationManager.AppSettings("SQLSERVERUSER")
ConnInfo.Password = ConfigurationManager.AppSettings("SQLSERVERPASSWORD")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CrystalReportSource1.ReportDocument.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CrystalReportSource1.ReportDocument.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
Dim pField As ParameterField = CrystalReportSource1.ReportDocument.ParameterFields(0)
Dim val1 As ParameterDiscreteValue = New ParameterDiscreteValue
val1.Value = Cod
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
Dim PDFName As String = "PDF Nº " & Cod
CrystalReportSource1.ReportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, True, PDFName)
End Sub
EDIT:
Tried to zip the reports with DotNetZip but i get an broken zip.
Can you tell me whats wrong? (Solved: code bellow is corrected now)
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/zip"
Response.AppendHeader("content-disposition", "attachment; filename=AllPDFs.zip")
Using zipFile As New ZipFile()
For i = 0 To Cod.Length - 1
If Cod(i) > 0 Then
val1.Value = Cod(i)
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
val2.Value = Cod(i)
pField2.CurrentValues.Clear()
pField2.CurrentValues.Add(val2)
Dim PDFNameAs String = "PDF Nº " & Cod(i) & ".pdf"
Dim s As New System.IO.MemoryStream
s =CrystalReportSource1.ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat)
zipFile.AddEntry(PDFName, s)
End If
Next
zipFile.Save(Response.OutputStream)
End Using
Response.Clear()
Probably the response ends after the first one, therefore there's no response to write to for the 2nd and 3rd attempts.
Instead, you can have the client download the reports via AJAX Request (move your report generation into an .ashx generic handler), or have the user click the button 3 times to initiate new requests.
Or zip the PDF's up until a single file and allow the client to download that.

Passing Parameter to SSRSfrom asp.net

I need to pass a parameter to reporting services which is on the reporting services server on my computer from my asp.net. The parameter is SellerID
MyReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote
MyReportViewer.ServerReport.ReportServerUrl = New Uri("http://jean-daniel/ReportServer_SQLEXPRESSADDD")
' Report Server URL
MyReportViewer.ServerReport.ReportPath = "/Report Project2/Auction History"
' Report Name
MyReportViewer.ShowParameterPrompts = False
MyReportViewer.ShowToolBar = False
MyReportViewer.ServerReport.Refresh()
Dim params(0) As ReportParameter
params(0) = New ReportParameter("SellerID", "201", False)
MyReportViewer.ServerReport.SetParameters(params)
MyReportViewer.ServerReport.Refresh()
Any idea on how to do this?
To pass parameters to a report via code you have to do it like this:
C#:
ReportParameter[] params = new ReportParameter[1];
params[0] = new ReportParameter("SellerId", ParameterValue , false);
MyReportViewer.ServerReport.SetParameters(params);
MyReportViewer.ServerReport.Refresh();
VB.NET:
Dim params(0) As ReportParameter
params(0) = New ReportParameter("SellerId", "YourValue", false)
MyReportViewer.ServerReport.SetParameters(params);
MyReportViewer.ServerReport.Refresh();
Here you can find a complete example Generate SQL Server Reporting Services (SSRS) Report as PDF from URL with VB.NET or C#.NET

Crystal reports - logon failed

I see the topic isn't new, but I searched many sites, found many clues, but nothing worked for me:(
I am using Crystal Reports Viewer control in my ASP.NET application. Report is quite simple, there are two parameters which I have to pass. I have two CrystalReportsSource and one CrystalReportsViewer controls on my site. When the page loads I run this snippet:
CrystalReportSource1.ReportDocument.SetParameterValue("name", Session["name"].ToString());
CrystalReportSource1.ReportDocument.SetParameterValue("code", Session["code"].ToString());
CrystalReportViewer1.ReportSource = CrystalReportSource1;
Setting source is needed, because I have two kinds of report and depending on some other session parameter I change which report should I print on screen (and which report source should I bind).
Unfortunately, this code doesn't work for me. CRViewer shows me little prompt/box saying that ~"Logging into database failed" (its only my translation, cause this is in my locale). I have no idea how to make it works. Nor my DB (Access), nor reports need credential to login (other words - I don't have to put them in any place).
Any help would be appreciated.
Since you are dynamically changing the report source, you will need to dynamically specify the logon as well.
It would be easier if your server and database are thesame. I have not tried this myself but you may give it a try.
Private Sub aMethod(ByVal name as String, ByVal sessionName as String)Handles Me.Load
Try
Dim cryRpt As New ReportDocument
Dim crtableLogoninfos As New TableLogOnInfos
Dim crtableLogoninfo As New TableLogOnInfo
Dim crConnectionInfo As New ConnectionInfo
Dim CrTables As Tables
Dim CrTable As Table
Select Case sessionName
Case OneSessionName 'specify a session name here'
Dim rptDoc = OneSessionName
Case AnotherSessionName 'specify other session name here'
Dim rptDoc = AnotherSessionName
End Select
Dim rptDoc = CType(rptDoc, String)
cryRpt.Load(rptDoc)
Select Case sessionName
Case OneSessionName
With crConnectionInfo
.ServerName = "yourServer1Name"
.DatabaseName = "YourDB1Name"
.UserID = "yourUser1Id"
.Password = "yourPassword1"
End With
Case AnotherSessionName
With crConnectionInfo
.ServerName = "yourServer2Name"
.DatabaseName = "YourDB2Name"
.UserID = "yourUser2Id"
.Password = "yourPassword2"
End With
End Select
CrTables = cryRpt.Database.Tables
For Each CrTable In CrTables
crtableLogoninfo = CrTable.LogOnInfo
crtableLogoninfo.ConnectionInfo = crConnectionInfo
CrTable.ApplyLogOnInfo(crtableLogoninfo)
Next
crsAllReports.PrintMode = PaperOrientation.Landscape
crsAllReports.ReportSource = cryRpt
Catch ex As Exception
lblError.Text = "No report"
lblError.Visible = True
End Try
End Sub
Note 'If your server and dbnames are thesame you may, you may not need the second switch statement. Instead just use:
With crConnectionInfo
.ServerName = "yourServerName"
.DatabaseName = "YourDBName"
.UserID = "yourUserId"
.Password = "yourPassword"
End With

How to pass parameters to SSRS report programmatically

I'm looking for a little help on programmatically passing parameters to a SSRS report via VB.NET and ASP.NET. This seems like it should be a relatively simple thing to do, but I haven't had much luck finding help on this.
Does anyone have any suggestions on where to go to get help with this, or perhaps even some sample code?
Thanks.
You can do the following,: (it works both on local reports as in Full Blown SSRS reports. but in full mode, use the appropriate class, the parameter part remains the same)
LocalReport myReport = new LocalReport();
myReport.ReportPath = Server.MapPath("~/Path/To/Report.rdlc");
ReportParameter myParam = new ReportParameter("ParamName", "ParamValue");
myReport.SetParameters(new ReportParameter[] { myParam });
// more code here to render report
If the Report server is directly accessible, you can pass parameters in the Querystring if you are accessing the repoort with a URL:
http://MyServer/ReportServer/?MyReport&rs:Command=Render&Param1=54321&Param2=product
You can add output formatting by adding the following on the end of the URL:
&rs:Format=Excel
or
&rs:Format=PDF
It's been a while since I did this code, but it may help:
Your web project has to be a Web Site, and not a project of type "ASP.Net Web Application", or you won't be able to add the reference mentioned below.
Right click on the project and add an ASP.Net folder - App_WebReferences. You'll have to specify the server where your SRS is; choose the .asmx.
Once it's added, the folder under that level is called RSService, and under that are 2 things: reportservice.discomap & .wsdl.
In my VB, I do Imports RSService and Imports System.Web.Services.Protocols, then...
Dim MyRS As New ReportingService
The reporting service is on a different server than the webserver the app is on, so I can't do the following: MyRS.Credentials = System.Net.CredentialCache.DefaultCredentials
Instead: MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3),
where the rs1/2/3 are the login to SRS box, password to SRS box, & domain name". (These are encrypted in my web.config.)
Then, a mass-paste:
MyRS.Credentials = New System.Net.NetworkCredential(rs1, rs2, rs3)
Dim ReportByteArray As Byte() = Nothing
Dim ReportPath As String = "/SRSSiteSubFolder/ReportNameWithoutRDLExtension"
Dim ReportFormat As String = "PDF"
Dim HistoryID As String = Nothing
Dim DevInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
'Dim x As ReportParameter - not necessary
Dim ReportParams(0) As ParameterValue
ReportParams(0) = New ParameterValue()
ReportParams(0).Name = "TheParamName"
ReportParams(0).Value = WhateverValue
Dim Credentials As DataSourceCredentials() = Nothing
Dim ShowHideToggle As String = Nothing
Dim Encoding As String
Dim MimeType As String
Dim ReportHistoryParameters As ParameterValue() = Nothing
Dim Warnings As Warning() = Nothing
Dim StreamIDs As String() = Nothing
'Dim sh As New SessionHeader() - not necessary
''MyRS.SessionHeaderValue = sh - not necessary
ReportByteArray = MyRS.Render(ReportPath, ReportFormat, HistoryID, DevInfo, ReportParams, Credentials, _
ShowHideToggle, Encoding, MimeType, ReportHistoryParameters, Warnings, StreamIDs)
'(Yay! That line was giving "HTTP error 401 - Unauthorized", until I set the credentials
' as above, as explained by http://www.odetocode.com/Articles/216.aspx.)
'Write the contents of the report to a PDF file:
Dim fs As FileStream = File.Create(FullReportPath, ReportByteArray.Length)
fs.Write(ReportByteArray, 0, ReportByteArray.Length)
fs.Close()
Call EmailTheReport(FullReportPath)
If IO.File.Exists(FullReportPath) Then
IO.File.Delete(FullReportPath)
End If
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.Reset();
Label1.Visible = false;
ReportViewer1.Visible = true;
DataSet dataSet = new DataSet();
dataSet = new ClassBLL().Load_Report_Detail(TextBox1.Text,
ddlType.SelectedValue, levelcode, fields);
ReportDataSource datasource = new ReportDataSource("DataSet_StoreprocedureName",
dataSet.Tables[0]);
if (dataSet.Tables[0].Rows.Count == 0)
{
ReportViewer1.Visible = false;
}
ReportViewer1.LocalReport.ReportPath = Server.MapPath("") + #"\Report.rdlc";
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);
string fields="name,girish,Z0117";
string[] filedName = fields.Split(',');
ReportParameter[] param = new ReportParameter[2];
//for (int i = 0; i < filedName.Length; i++)
//{
param[0] = new ReportParameter(filedName[0], filedName[0], true);
param[1] = new ReportParameter(filedName[3], filedName[3], true);
// }
ReportViewer1.LocalReport.SetParameters(param);
ReportViewer1.ServerReport.Refresh();

Resources