passing parameter to report viewer - asp.net

I want to pass a parameter to my report view. I have a drop down list with values from database and a button for displaying the report after selecting an item from the drop down list.
here is the code I wrote for adding the parameter
protected void Button1_Click(object sender, EventArgs e)
{
RenderReport();
}
protected void RenderReport()
{
try
{
ServerReport serverReport = ReportViewer1.ServerReport;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
try
{
serverReport.ReportServerUrl = new Uri("http://hedinaily-pc/Reports_HEDI");
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";
ReportParameter employe = new ReportParameter();
employe.Name = "Employe";
employe.Values.Add(DropDownList1.SelectedValue);
ReportViewer1.ServerReport.SetParameters( new ReportParameter[] { employe });
ReportViewer1.Visible = true;
}
catch (Exception ex)
{
Logger.Error(ex.Message, "");
}
}
Here is the data set of my report
When I check my log file I find this error :
The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
Can anyone tell me where doe's this error come from. I spent hours searching on google I found this LINK but I couldn't resolve it.

Try it like this...
ReportViewer1.ServerReport.ReportPath = "FooReport.rdlc";
ReportParameter[] reportParameter = new ReportParameter[2];
reportParameter[0] = new ReportParameter("fooFromDate", dateFrom.ToShortDateString());
reportParameter[1] = new ReportParameter("fooDateTo", dateTo.ToShortDateString());
ReportViewer1.ServerReport.SetParameters(reportParameter);
ReportViewer1.ServerReport.Refresh();
Also .Refresh() method must be called so that...report is displayed..

You can test with this code
ReportParameter[] yourParams = new ReportParameter[1];
yourParams [0] = new ReportParameter("Employe", DropDownList1.SelectedValue);//Adjust value
this.ReportViewer1.ServerReport.SetParameters(yourParams );

One way of doing the same is by using the Report Parameters dialog box to define parameters for a report that is processed in local mode. You can define parameters to support conditional formatting or to use in expressions or code. You cannot use the Report Parameters dialog box to map report parameters to query parameters or use them in data source filters.
So you can pass the parameters to the SP as we can do it in normal operation, by usign sqlParameters. Then execute the SP bind it to report viewer datasource.

For the "The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version." error try:
serverReport.ReportPath = "/Diagrammes/PresenceTotale";
instead of:
serverReport.ReportPath = "~/Diagrammes/PresenceTotale.rdlc";

Related

Importing a asp.net webPart in WebForm website from .Webpart file programmatically (Not a sharePoint Project)

We have created several user Controls (Ascx) that we render to a webpart zone. Similarly, we have a control containing WebPartManager which is implemented in all the .aspx pages.
I am working on a feature where it is required to Import generated .webpart file on any page using a file upload control.
I am Using devExpress fileUpload control and upon FileUploadComplete Event executing the below-mentioned code.
The code Runs without any error but also doesn't display any web-part in the specified zone. Which is the problem.
protected void WebPartUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
{
string ErrorMessge = string.Empty;
if (e.UploadedFile.IsValid)
{
var xmlReader = XmlReader.Create(e.UploadedFile.FileContent);
xmlReader.Read();
System.Web.UI.WebControls.WebParts.WebPart webPart = wpManager.ImportWebPart(xmlReader, out ErrorMessge);
wpManager.AddWebPart(webPart, wpManager.Zones["Zone5"], 1);
}
}
I might be missing some fundamental code. If anybody knows the answer kindly help. Thanks .
I finally figured out the issue. Just in case if someone in future come across a similar problem, this will help.
So, The problem here is the Devexpress File-Upload control is an ajax control, making partial postback thus not updating the CatalogZone of the page which is out of its scope.
The way to deal with it is :
Create a new .WebPart file and clone the content of the uploaded file.
Re-direct to the same page which fires Page_Load event
Execute the above code in the page_Load Event in order to import.
Below is the code to explain just that :
WebPartUploadControl_FileUploadComplete
protected void WebPartUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
{
String WebPartFilePath = Server.MapPath("DirectoryWhereYouWantTosaveCloneFile");
String WebPartFileName = "NameOfYourCloneFile.WebPart";
string FileContent = string.Empty;
Creating Directory to store data of uploaded file(.webPart).
Session["ImportWebPartFilePath"] = $"{WebPartFilePath}/{WebPartFileName}";
if (!Directory.Exists(WebPartFilePath))
{
Directory.CreateDirectory(WebPartFilePath);
}
Reading Uploaded file Data
using (StreamReader sr = new StreamReader(e.UploadedFile.FileContent))
{
FileContent = sr.ReadToEnd();
}
//Copying File Data to the newly Created file
if (!File.Exists(Session["ImportWebPartFilePath"].ToString()))
{
File.AppendAllText(WebPartFilePath + "/" + WebPartFileName, FileContent);
}
e.CallbackData = "Page Settings Imported Successfully.";
// Response.Redirect(Request.RawUrl) does not work in while ajax callback in
devexpress
// Creating a callback to current page to trigger Page_Load event.
DevExpress.Web.ASPxWebControl.RedirectOnCallback(this.Request.Path);
}
Page_Load
if (Session["ImportWebPartFilePath"] != null)
{
//Import Webpart Settings
ImportWebPartsToCurrentPage(Session["ImportWebPartFilePath"].ToString());
File.Delete(Session["ImportWebPartFilePath"].ToString());
Session["ImportWebPartFilePath"] = null;
}
ImportWebPartsToCurrentPage
private void ImportWebPartsToCurrentPage(String FilePath)
{
string ErrorMessge = string.Empty;
//Extracting All WebParts in the file
XDocument WebPartXml = XDocument.Load(FilePath);
//Spliting the each webpart.
var WebPartDescriptions = WebPartXml.Root.Elements();
try
{
foreach (var WebPartDescription in WebPartDescriptions)
{
var xmlReader = XmlReader.Create(new StringReader(WebPartDescription.ToString()));
xmlReader.Read();
// Adding Webpart to page Catalog.
System.Web.UI.WebControls.WebParts.WebPart webPart = wpManager.ImportWebPart(xmlReader, out ErrorMessge);
//Adding webpart to the page.
if (!wpManager.WebParts.Contains(webPart))
{
wpManager.AddWebPart(webPart, wpManager.Zones["ZoneName"], 0);
}
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}

Save and New Button will not clear fields

I have 3 custom visual force pages. a view which views the record, edit which edits and a new that makes a new record. Edit and New have a save and new button. When I click save and new I need a redirect, a new record to be made, and few of the fields to be cleared however all the previous data is being transferred over on the redirect.
My apex code..
public PageReference saveAndNew() {
try {
// Save the current sObject
sController.save();
Schema.DescribeSObjectResult describeResult = sController.getRecord().getSObjectType().getDescribe();
// Create PageReference for creating a new sObject and add any inbound query string parameters.
PageReference pr = new PageReference('/' + describeResult.getKeyPrefix() + '/e?' + queryString);
// Don't redirect with the viewstate of the current record.
pr.setRedirect(true);
eventPackageRevenueBreakdown = new eventPackageRevenueBreakdown__c();
eventPackageRevenueBreakdown.Name = null;
eventpackageRevenueBreakdown.AdminIsIncludedInInclusivePrice__c = false;
return pr;
} catch(Exception e) {
// Don't redirect if something goes wrong. May be a validation or trigger issue on save.
ApexPages.addMessages(e);
return null;
}
}
I suggest you check Using the transient Keyword. Mark data, which you don't want to be transferred, as transient.

how to link to ssrs report from asp.net webpage

I'm having trouble linking to an ssrs report from my asp.net webpage.
the direct link is
server/Reports/Pages/Report.aspx?ItemPath=%2fRig+Dashboard%2fRig+Status+Report
I also need to pass in two parameters which is FileTypeID and Date
Please help...
ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://server/Reports"); // Report Server URL
ReportViewer1.ServerReport.ReportPath = "/Rig Dashboard/Rig Status Report"; // Report Name
ReportViewer1.ShowParameterPrompts = false;
ReportViewer1.ShowPrintButton = true;
ReportViewer1.ServerReport.Refresh();
The attempt to connect to the report server failed. Check your connection information and that the report server is a compatible version.
The request failed with HTTP status 404: Not Found.
Your doing it wrong. You are trying to call the 'landing page' : /Reports NOT THE SERVICE: /ReportServer. Yuriy gave you a good place to get started. I can give you an example of how I do it in some local code I use in WPF calling a Windows Form(blech!):
private void ResetReportViewer(ProcessingMode mode)
{
this.reportViewer.Clear();
this.reportViewer.LocalReport.DataSources.Clear();
this.reportViewer.ProcessingMode = mode;
}
private void ReportViewerRemote_Load(object sender, EventArgs e)
{
ResetReportViewer(ProcessingMode.Remote);
reportViewer.ServerReport.ReportServerUrl = new Uri(#"http://server/ReportServer");
reportViewer.ServerReport.ReportPath = "/Folder/ReportName";
reportViewer.RefreshReport();
}
private void ReportViewerRemoteWithCred_Load(object sender, EventArgs e)
{
ResetReportViewer(ProcessingMode.Remote);
reportViewer.ServerReport.ReportServerUrl = new Uri(#"http://server/ReportServer");
reportViewer.ServerReport.ReportPath = "/Folder/ReportName";
DataSourceCredentials dsCrendtials = new DataSourceCredentials();
dsCrendtials.Name = "DataSource1";
dsCrendtials.UserId = "DedicatedUser";
dsCrendtials.Password = "P#ssword(jk)";
reportViewer.ServerReport.SetDataSourceCredentials(new DataSourceCredentials[] { dsCrendtials });
reportViewer.RefreshReport();
}

Accessing SSRS server report from local application

I have deployed my SSRS reports in the server. Is it possible for me to access that report from my local web application. I have given the server's credentials in the web.config. But still its not displaying the report and it shows some error like Cannot create a connection to data source 'DataSource1'. (rsErrorOpeningConnection).
When I hosted the same application in the server it is working absolutely fine.
Can anyone tell me why am not able to access the reports from my local system?
This is not my code, but ideally is all you have to do. I remember using it successfully in one of previous projects some time back
private void ShowReport()
{
try
{
string urlReportServer = "http://sqlDBServer//Reportserver";
rptViewer.ProcessingMode = ProcessingMode.Remote; // ProcessingMode will be Either Remote or Local
rptViewer.ServerReport.ReportServerUrl = new Uri(urlReportServer); //Set the ReportServer Url
rptViewer.ServerReport.ReportPath = "/ReportName"; //Passing the Report Path
//Creating an ArrayList for combine the Parameters which will be passed into SSRS Report
ArrayList reportParam = new ArrayList();
reportParam = ReportDefaultPatam();
ReportParameter[] param = new ReportParameter[reportParam.Count];
for (int k = 0; k < reportParam.Count; k++)
{
param[k] = (ReportParameter)reportParam[k];
}
// pass crendentitilas
//rptViewer.ServerReport.ReportServerCredentials =
// new ReportServerCredentials("uName", "PassWORD", "doMain");
//pass parmeters to report
rptViewer.ServerReport.SetParameters(param); //Set Report Parameters
rptViewer.ServerReport.Refresh();
}
catch (Exception ex)
{
throw ex;
}
}
Ref: http://www.codeproject.com/Articles/675762/Call-SSRS-Reports-by-using-Csharp

Problem with Object Data Source in ASP.NET (GetData method)

I want to create a report viewer in ASP.NET that presents to the users their data.
the data for all the users is located in the same table.
for now I created DBDataSet and in the TableAdapter there is this method
GetData(#idNumber, #userNumber)
in code behind of the screen that I want to show the report viewer I wrote:
FlightsDBDataSetTableAdapters.ReservationsTableAdapter ReservationsTableAdapter;
ReservationsTableAdapter = new FlightsDBDataSetTableAdapters.ReservationsTableAdapter();
FlightsDBDataSet.ReservationsDataTable newReservationTable;
newReservationTable = ReservationsTableAdapter.GetData(userId, userName);
ObjectDataSource1.SelectParameters.Add("userName", userName);
ObjectDataSource1.SelectParameters.Add("idNumber", userId);
when I run this I get the next error
An error has occurred during report processing. ObjectDataSource
'ObjectDataSource1' could not find a non-generic method
'GetData(idNumber, userName)' that has parameters: userName, idNumber.
SO, my question is where do I need to write the method GetData and how can I generate the report with the right data.
thanks a lot.
Try this out.
1.Create a method which will return db null if parameter is not passed in the stored procedure
public static object GetDataValue(object o)
{
if (o == null || String.Empty.Equals(o))
return DBNull.Value;
else
return o;
}
2.Create a method which will called the stored procedure and fill the dataset.
public DataSet GetspTest(string userName, string userId) {
try
{
DataSet oDS = new DataSet();
SqlParameter[] oParam = new SqlParameter[2];
oParam[0] = new SqlParameter("#userName", GetDataValue(userName));
oParam[1] = new SqlParameter("#idNumber", GetDataValue(userId));
oDS = SqlHelper.ExecuteDataset(DataConnectionString, CommandType.StoredProcedure, "spTest", oParam);
return oDS;
}
catch (Exception e)
{
ErrorMessage = e.Message;
return null;
}
}
Now you add the dataset let us say 'DataSet1.xsd'
Drag and Drop the TableAdapter and it will ask you the following details
3.1 Connection String (Either Select the existing connection string or create new connection string)
3.2 Choose Command Type (Now select the existing stored Procedure, specify the stored procedure with you have create earlier to display details in the report
3.3 Choose Methods to Generate (check both Fill a Datatable and Return a datatable
3.4 Click on Next and Submit ( Now your dataset is really to use in the report)
Create a report and use this DataSet1 as datasource.

Resources