How to pass parameters to SSRS report programmatically - asp.net

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();

Related

Downloading html as string

I am trying to download a webpage as string. Can someone please explain why the following code doesn't work?
Dim URL As String = "http://stackoverflow.com/"
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
When I run it it never goes inside the loop.
Give this a shot...
Dim URL As String = "http://stackoverflow.com/"
Dim html As String = New WebClient().DownloadString(URL)
Better Solution (Releases resources that the network stack is using. Also ensure's (hope) the CLR cleans these up when needed.)
Using client As New WebClient()
html = client.DownloadString(URL)
End Using

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.

Server Transfer with Session

I have a site contains login page and Default this is part of my code when trying to server transfer from login to Default
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim wrapper As New Simple3Des(MyKey)
Dim userNamePlan As String = UserNameTextBox.Text
Dim PasswordPlan As String = PassWorldTextBox.Text
Dim user As String = wrapper.EncryptData(userNamePlan)
Dim pass As String = wrapper.EncryptData(PasswordPlan)
Session("un") = user.ToString
Session("pw") = PassWorldTextBox.Text
Server.Transfer("Default.aspx")
...
if I change Session("un") = user.ToString to UserNameTextBox.text it will transfer, if not, fail. And no Error Messages. Don't know why
I hope user is already string..Then you can write..
System.Web.HttpContext.Current.Session(“un”)=user;

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

Resources