Passing parameter ot RDL report for ASP.NET - asp.net

I am trying to call rdl reports remotely in ASP.NET, And i was successful calling report without parameter. But when i pass parameter, reporting i not populating and not giving error. It display noting in report. find my code below. and please do suggest me on the same.
MyReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;
MyReportViewer.ServerReport.ReportServerUrl = new Uri(#"http://gblon9sqm10 /ReportServer_DB10");
MyReportViewer.ServerReport.ReportPath = "/Reports/Report1";
MyReportViewer.ShowParameterPrompts = false;
MyReportViewer.ShowPrintButton = true;
ReportParameter[] rptParameters = new ReportParameter[1];
rptParameters[0] = new ReportParameter();
rptParameters[0].Name = "exposureType";
rptParameters[0].Values.Add("Impressions");
MyReportViewer.ServerReport.SetParameters(rptParameters);
MyReportViewer.ServerReport.Refresh();

It's been a while since I set this up but I remember having to make sure that you didn't setup the report again on postback. This is my code in page_load:
if (!Page.IsPostBack)
{
rptViewer.ServerReport.ReportServerUrl = Settings.ReportServerUrl;
if (rptViewer.ServerReport.ReportServerCredentials == null)
rptViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials();
List<ReportParameter> parameters = new List<ReportParameter>();
parameters.Add(new ReportParameter("TitleLabel", "Title string here"));
//More parameters added here...
rptViewer.ServerReport.SetParameters(parameters);
}

I was facing the same problem with same code and configuration as you have mentioned.
I tried bit extra work and get the rid of problem.
I have created a new report with single parameter "Name" and pass value to this parameter from code-behind as ReportParameter. At the report configuration side set the type of parameter text and allow to blank values. Note here i didn't touch any other settings of parameter means kept it as comes by default.
This works for me and then i started adding more parameters and it works perfectly fine.
There is no any browser constraint.
Try as said above and still you face issue then reply me i will put a sample code.
Hope it will help you.

Related

Binding database data to a dropdownlist

I have been trying for a long time to fix the bugs I'm encountering with my dropdownlists in my project. I'm getting data this with at the moment and it's working fine:
using (InfoEntities ie = new InfoEntities())
{
var sqlddl = (from query in ie.Table_Customers
from q in ie.Accounting_PriceType
where query.TypeID == 1 && q.ID == 1
orderby query.Customers
select query).Distinct().ToList();
DropDownListCust.DataTextField = "Customers";
DropDownListCust.DataValueField = "ID";
DropDownListCust.DataSource = sqlddl;
DropDownListCust.DataBind();
}
Now when the user saves the data and opens the website again I need the saved value that was chosen on the dropdownlist earlier retreived. This also works fine but the problem is I'm getting duplicates. Anyways I'm doing it like this and I'm pretty sure I'm doing it wrong:
On the page load i load my dropdownlist to get all the items plus the following to get the saved value:
DropDownListCust.SelectedItem.Text = sql.Customers;
This makes my DDL very buggy, some items dissapear and also sometimes dupicated values. Can anyone please help? I'm using LINQ but I can use some other methods as long as it's fixed.
Cheers
I solved my problem like this:
DropDownList1.ClearSelection();
DropDownList1.Items.FindByText(sql.Customer).Selected = true;

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

Passing parameter using ReportViewer

I used to work with winForm. Now I need to make a report using Web.
I Need to know how to pass parameters using WebForms. I have something but don't know how to pass it to the other page as parameter to the reportviewer
ReportParameter[] param = new ReportParameter[2];
param[0] = new ReportParameter("usr",Drop_Responsaveis.SelectedValue.ToString());
param[1] = new ReportParameter("clube", Drop_Clientes.SelectedValue.ToString());
Is this right ? Create the parameters at one page and pass it to another page that contains the reportviewer ?
You can use Querystring or Session to pass value to the next page. e.g. page2.aspx?clube=1234&user=John
Then you can retrieve the values from the querystring and pass to the report viewer
param[0] = new ReportParameter("usr", Request.QueryString["user"]);
param[1] = new ReportParameter("clube", Request.QueryString["clube"]);

ASP.NET EnqityDataSource WhereParameters, creates new property

I am trying to populate GridView, using EntityDataSource(code behind), I need to able to sort GridView. However when I sort i get error:
A property with name 'aspnet_Users.UserId1' does not exist in metadata for entity type
So I beleive it is because I generate where parameter in code behind:
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Full code is :
ActiveEnqDataSource.ConnectionString = db.Connection.ConnectionString;
ActiveEnqDataSource.DefaultContainerName = "Entities";
ActiveEnqDataSource.EntitySetName = "Enquiries";
ActiveEnqDataSource.Include = "UserCars.CarModel.CarMake, Category, aspnet_Users";
ActiveEnqDataSource.EnableUpdate = true;
ActiveEnqDataSource.EnableInsert = true;
ActiveEnqDataSource.EnableDelete = true;
ActiveEnqDataSource.AutoGenerateWhereClause = true;
ActiveEnqDataSource.WhereParameters.Add(new SessionParameter("aspnet_Users.UserId", TypeCode.Object, "UserName"));
Any suggestions? Thank you very much! The gridview itself renders perfectly, only thing I cannot sort it, any "whereParameters" I add, Add 1 to the property e.g UserId1,EnquiryStatus1, ProdauctName1. etc...
I got a similar error because I was adding the where clause each time the page was posted back. Dropping my code that generated the where clause inside an IsPostback statement fixed the problem:
if (!IsPostBack) {
// code to add where parameters
}
I got the same error when I used markup to define a Where parameter AND then I added the same parameter in code. Somewhere along the line, the 1 at the end of the parameter name was added.

Is asp.net caching my sql results?

I have the following method in an App_Code/Globals.cs file:
public static XmlDataSource getXmlSourceFromOrgid(int orgid)
{
XmlDataSource xds = new XmlDataSource();
var ctx = new SensusDataContext();
SqlConnection c = new SqlConnection(ctx.Connection.ConnectionString);
c.Open();
SqlCommand cmd = new SqlCommand(String.Format("select orgid, tekst, dbo.GetOrgTreeXML({0}) as Subtree from tblOrg where OrgID = {0}", orgid), c);
var rdr = cmd.ExecuteReader();
rdr.Read();
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<node orgid=\"{0}\" tekst=\"{1}\">",rdr.GetInt32(0),rdr.GetString(1));
sb.Append(rdr.GetString(2));
sb.Append("</node>");
xds.Data = sb.ToString();
xds.ID = "treedata";
rdr.Close();
c.Close();
return xds;
}
This gives me an XML-structure to use with the asp.net treeview control (I also use the CssFriendly extender to get nicer code)
My problem is that if I logon on my pc with a code that gives me access on a lower level in the tree hierarchy (it's an orgianization hierarchy), it somehow "remembers" what level i logon at. So when my coworker tests from her computer with another code, giving access to another place in the tree, she get's the same tree as me.
(The tree is supposed to show your own level and down.)
I have added a html-comment to show what orgid it passes to the function, and the orgid passed is correct. So either the treeview caches something serverside, or the sqlquery caches it's result somehow...
Any ideas?
Sql function:
ALTER function [dbo].[GetOrgTreeXML](#orgid int)
returns XML
begin RETURN
(select org.orgid as '#orgid',
org.tekst as '#tekst',
[dbo].GetOrgTreeXML(org.orgid)
from tblOrg org
where (#orgid is null and Eier is null) or Eier=#orgid
for XML PATH('NODE'), TYPE)
end
Extra code as requested:
int orgid = int.Parse(Session["org"].ToString());
string orgname = context.Orgs.Where(q => q.OrgID == orgid).First().Tekst;
debuglit.Text = String.Format("<!-- Id: {0} \n name: {1} -->", orgid, orgname);
var orgxml = Globals.getXmlSourceFromOrgid(orgid);
tvNavtree.DataSource = orgxml;
tvNavtree.DataBind();
Where "debuglit" is a asp:Literal in the aspx file.
EDIT:
I have narrowed it down. All functions returns correct values. It just doesn't bind to it. I suspect the CssFriendly adapter to have something to do with it.
I disabled the CssFriendly adapter and the problem persists...
Stepping through it in debug it's correct all the way, with the stepper standing on "tvNavtree.DataBind();" I can hover the pointer over the tvNavtree.Datasource and see that it actually has the correct data. So something must be faulting in the binding process...
I would normally suspect the issue is with orgid that is getting passed in to your method, but you say that you have checked to make sure the right code is being passed. Just to confirm, show us the code that assigns the value to that.
Additionally, there are a few problems with your code, SQL injection risk being one of them. orgid is an int, offering some protection, but if at some point orgid is changed to require characters by your organization, a developer may just change the data type to string, suddenly opening up the app to SQL injection. You should remove the String.Fotmat, and use a parameterized query instead.
I found the problem. The XmlDataSource component has a cache function, which by default is enabled. When I disabled this, everything works nicely.

Resources