How to pass query string parameter to ssrs reports from report viewer control - asp.net

In my 2012 asp.net web form application, one of the aspx pages that contains asp.net report viewer control is coded
in its Page_Load event handler as below to call remote ssrs (SQL Server 2012) reports using property ReportPath.
I have 2 questions:
Question 1: If I want to pass one more query string via property ReportPath, for example deviceId=1234, how can I do so?
protected void Page_Load(object sender, EventArgs e)
{
....
ReportViewer1.ServerReport.ReportPath = _myReportPart; // I want to pass more query string here like deviceId=1234. How can I do so?
ReportViewer1.ServerReport.ReportServerUrl = new Uri(myReportServerUrl);
}
}
Question 2: on remote ssrs rdl reports, how can reports consume/extract that extra query string?
Thank you.

For adding parameters to the report in asp.net you can do the following
ReportParameter rpt7 = new ReportParameter(**PARAMETER NAME**, **VALUE**);
this.ReportViewer1.ServerReport.SetParameters(new ReportParameter[] { rpt7 });
From the above example you could replace the value with Request.QueryString["deviceId"].ToString() to pass the query strings value as the parameter.
See the following for more details
http://social.msdn.microsoft.com/Forums/en/sqlreportingservices/thread/72fdf94f-2b5d-4fc3-82c4-7db887033507
As for the report excepting the extra parameter you would have to modify the report in Visual studio to except the new parameter. This can be done under the Report Data window's parameters section.

Related

Devexpress XAF (Blazor) Popup window to edit property

I have an XAF application. Most of my Business Objects are based on a baseclass "MyBaseClass" which contains Createdby, ModifiedBy, ... Comments. The Comments field is AllowEdit=false. I only want users to be able to modify the comment thru an action which would allow them to create an entry to which I would prepend their UserName and timestamp.
I don't know how to pop up a window to edit a property (string) within the current object and view.
There are plenty of examples of how to CreateListView but in this case what I wish to edit in the popup is not a separate BO but just a string. Maybe that is my problem(???)
I have the Action Controller and I am not sure how to create the DetailView when I get into the _Execute()
In Winforms XAF I add an action in a view controller.
In the action's execute event I call something like
private void actOpenDetailView_Execute(object sender, SimpleActionExecuteEventArgs e)
{
var application = Controller.Application
var viewId = application.FindDetailViewId(typeof(MyBusinessObject));
application.CreateObjectSpace(typeof(MyBusinessObject));
var detailView = application.CreateDetailView(newObjectSpace, jh, true);
e.ShowViewParameters.CreatedView = detailView;
e.ShowViewParameters.TargetWindow = TargetWindow.NewWindow;
}
I haven't tried that in Blazor.

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 pass data from Silverlight OOB application to asp.net website?

I created silver-light 4.0 application in that user can enter their username and password.
After submit this secret data(username, password ) from SL application,
it submitted to website with query string..
I want to pass as below URL string
for ex: -
http://testsite.com/mypage.aspx?<encrypted string>
I want to pass username and password in encrypted format from SL to Aspx page..
How I pass those information from SL application to asp.net website..
So you could just use the WebClient class and GET the page.
(I'm assuming your doing asp.net WebForms NOT MVC)
Your asp.net page should be a blank page, in your code behind you read your query string and do what you need with it, depending on success or failure you write the appropriate response with Response.Write();.
In your silverlight code, you will just need to request for your page, and you can then read the response from your asp.net page.
Asp.net:
var encyString = Request.QueryString["str"];
//some logic
Response.Write("Success");
Silverlight:
WebClient client = new WebClient();
client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(
client_DownloadStringCompleted);
In Button1_Click, I call DownloadStringAsync, passing the complete URL that includes the number specified by the user.
private void Button1_Click(object sender, RoutedEventArgs e)
{
string encryptedString = "example";
client.DownloadStringAsync
(new Uri("http://testsite.com/mypage.aspx?"+encryptedString));
}
In the DownloadStringCompleted event-handler, I check that the Error property of the event args is null, and either output the response or the error message to the text block.
void client_DownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
resultBlock.Text = "Using WebClient: "+ e.Result;
//will be Response.Write();
else
resultBlock.Text = e.Error.Message;
}
Above code was plagiarized from this blog.
Remember, a sniffer can read your request. You may want to use SSL if you need better security. Possibly a more secure way to send this data would be to POST it to your asp.net page.
This article describes how to POST from silverlight to a page.
HTH
What I understood from the question is that you are authenticating user twice – First in SL app and then in ASP.Net app. Instead can you just authenticate user in SL and pass the result (True/False or token may be) to ASP.Net app? This is the safe way I feel.
You can use like HtmlPage.Window.Eval("window.location.href='"+ YOURURL +"'");

Maintaining GridView current page index after navigating away from Gridview page

I have a GridView on ASP.NET web form which I have bound to a data source and set it to have 10 records per page.
I also have a hyper link column on the GridView, such that a user can navigate to another page (details page) from the list. On the details page, they have "Back" button to return to the GridView page
Edit
Just to clarify the query
I am looking for sample code snippet on the Server Side on how to specify the page index to set the GridView after data binding. The idea is to ensure the user navigates to the same page index they were on.
The three basic options at your disposal: query string, session, cookie. They each have their drawbacks and pluses:
Using the query string will require you to format all links leading to the page with the gridview to have the proper information in the query string (which could end up being more than just a page number).
Using a session would work if you're sure that each browser instance will want to go to the same gridview, otherwise you'll have to tag your session variable with some id key that is uniquely identifiable to each gridview page in question. This could result in the session management of a lot of variables that may be completely undesirable as most of them will have to expire by timeout only.
Using a cookie would require something similar where cookie data is stored in a key/data matrix (optimized hash table might work for this). It would not be recommended to have a separate cookie name for each gridview page you're tracking, but rather have a cookie with a common name that holds the data for all gridview pages being tracked and inside that have the key/value structure.
Edit: A small code snippet on setting the page index.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
try
{
if(HttpContext.Current.Request["myGVPageId"] != null])
{
myGridview.PageIndex = Convert.ToInt32(HttpContext.Current.Request["myGVPageId"]);
}
}
catch(Exception ex)
{
// log it
}
}
}
I'm more of a fan of the Session approach, personally. Simply save your page index as a session variable, and, if this Session variable isn't null on page load, use it to fire your "OnPageIndexChanging" method, like so:
Set your current page number whenever the page number changes:
protected void GridViewIndexChanging(object sender, GridViewPageEventArgs e)
{
myGridView.PageIndex = e.NewPageIndex;
Session["pageNumber"] = e.NewPageIndex;
//whatever your page index changing does...
}
Then, on Page_Load do something like:
if (!IsPostBack)
{
if (Session["pageNumber"] != null)
{
GridViewIndexChanged(myGridView, new GridViewPageEventArgs((int)Session["pageNumber"]));
}
}
you can ues the Page Index Change Event of Gridview and Find out the Current Page Index for e:g
yourGridId.PageIndex=e.NewPageIndex;
ViewState["GridPageIndex"]=e.NewPageIndex;
on PageLoad Get the Viewstate Value
string pIndex=string.Empty;
pIndex=Convert.toInt32(ViewState["GridPageIndex"]);
if(!string.Empty(pIndex))
{
yourGridId.PageIndex =pIndex;
}
you must use query string and is recommended, otherwise you can use session object but don't use that for this as you may have grid view opening in different pages so use query string .
gridView1.CurrentPageIndex = (Request["pageNo"] != null) ? Request["pageNo"] as int : 0;
gridView1.DataSource = myDataSet;
gridView1.DataBind();
you can update your link on GridView_DataBound event

Changing Databases in Crystal Reports for .NET

I have a problem which is perfectly described here (http://www.bokebb.com/dev/english/1972/posts/197270504.shtml):
Scenario:
Windows smart client app and the CrystalReportViewer for windows.
Using ServerFileReports to access reports through a centralized and disconnected folder location.
When accessing a report which was designed against DB_DEV and attempting to change its LogonInformation through the CrystalReportViewer to point against DB_UAT, it never seems to actually use the changed information.
It always goes against the DB_DEV info.
Any idea how to change the Database connection and logon information for a ServerFileReport ????
Heres code:
FROM A PRESENTER:
// event that fires when the views run report button is pressed
private void RunReport(object sender, EventArgs e)
{
this.view.LoadReport(Report, ConnectionInfo);
}
protected override object Report
{
get
{
ServerFileReport report = new ServerFileReport();
report.ObjectType = EnumServerFileType.REPORT;
report.ReportPath = #"\Report2.rpt";
report.WebServiceUrl = "http://localhost/CrystalReportsWebServices2005/ServerFileReportService.asmx";
return report;
}
}
private ConnectionInfo ConnectionInfo
{
get
{
ConnectionInfo info = new ConnectionInfo();
info.ServerName = servername;
info.DatabaseName = databasename;
info.UserID = userid;
info.Password = password;
return info;
}
}
ON THE VIEW WITH THE CRYSTAL REPORT VIEWER:
public void LoadReport(object report, ConnectionInfo connectionInfo)
{
viewer.ReportSource = report;
SetDBLogon(connectionInfo);
}
private void SetDBLogon(ConnectionInfo connectionInfo)
{
foreach (TableLogOnInfo logOnInfo in viewer.LogOnInfo)
{
logOnInfo.ConnectionInfo = connectionInfo;
}
}
Does anyone know how to solve the problem?
I know this isn't the programatic answer you're looking for, but:
One thing that helps with this sort of thing is not creating your reports connected to the database directly, but first you create a "Data Dictionary" for Crystal Reports (this is done in the Report Designer). Then you link all of your reports to this dictionary which maps the fields to the proper databases.
Done this way, you only have one place to change the database schema/connection info for all reports.
Also, in your report designer set the report to not cache the results (sorry I don't remember the exact option). Reports can either have their initial results included or not.
Don't you have to browse all the "databaseTable" objects of the report to redirect the corresponding connections? You'll find here my VB version of the 'database switch' problem ...
In your CrystalReportViewer object you should set
AutoDataBind="true"

Resources