Angular SPA cannot open remote SSRS report - asp.net

thanks to all for your time and efforts trying to help me solve this.
Now lets get to it... I have an AngularJS SPA. I would like to provide links on my view page, that when clicked, open a new tab and launch pre-existing SSRS reports in PDF format. Technically what I am trying to do: Render an SSRS report in my Repository, pass that through my WEB API then on to my SPA for display in a new tab.
One important note before I go any further: This setup, method, approach works flawlessly on my local machine within Visual Studio. It's when I move my SPA to a remote Web server (the same server that hosts SSRS) that I have a problem.
My Landscape:
Local Development Machine (Windows 7 Pro, VS2015 Pro)
Server1 (Win Server 2012R2): Hosts IIS (8), SPA, SQL (2014) and SSRS
Server2 (Win Server 2012R2). Hosts SSRS (SQL 2012) source of data (happens to be SSAS cubes, but I don't think that matters).
On My Local Development Machine:
As stated above the solution works fine through Visual Studio. The only part of the solution on my local machine is the SPA. The SSRS and SQL portion are located remotely. I can launch my SPA, click on a link and new tab opens containing the PDF report. I can also make a call directly to the web API and display a PDF report (http://localhost:3040/api/dataservice/ProductivityReportH/)
Problem 1
Browsing to the deployed version of my SPA on Server1, the application displays fine. But, if I click on a report hyperlink I get a the following message:
Do you want to open or save ProductivityReportH/ (3.28KB) from Server1?
No matter what I click (Open, Save, Cancel) nothing happens.
If I try and launch the report directly through the API, I get the same message. There are no errors displayed in the console window. I could find no errors in the Server1 log files.
On Server1: I can display the report via the SSRS report viewer.
Problem 1A
Using a browser on Server1, I can display the application just fine. But, if I click on a report hyperlink I get the same message as Problem 1. If I try to launch the report directly through the web API (http://Server1/projecttracker/api/dataservice/ProductivityReportH/)
on Server1, I get the same message.
Any ideas would be greatly appreciated
My SPA Setup:
View Page:
<div class="view indent">
<div class="container">
<h2>Productivity Reports Method 1</h2>
<a ng-href='#here' ng-click="hproductivityreport()">Launch</a><br>
</div>
My Controller:
(function () {
var ProjectsController = function ($scope, $window) {
$scope.hproductivityreport = function () {
$window.open('api/dataservice/ProductivityReportH/', '_blank');
};
}
ProjectsController.$inject = ['$scope', '$window'];
angular.module('ReportTracker').controller('ProjectsController', ProjectsController)
}());
The WEB API:
using ProjectTracker.Repository;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
namespace ProjectTracker.Model
{
[Authorize]
public class DataServiceController : ApiController
{
IProjectTracker _ProjectTrackerRepository;
public DataServiceController()
: this(null)
{
}
public DataServiceController(IProjectTracker Repo)
{
_ProjectTrackerRepository = Repo ?? new ProjectTrackerRepository ();
}
[HttpGet]
public HttpResponseMessage ProductivityReportH()
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
byte[] bytes = _ProjectTrackerRepository.RenderProductivityReport("Hibble, Norman");
Stream stream = new MemoryStream(bytes);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
}
}
The Respository:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
namespace ProjectTracker.Repository
{
public class ProjectTrackerRepository : RepositoryBase<ProjectTrackerContext>, IProjectTracker
{
ProjectTrackerContext _Context;
public ProjectTrackerRepository()
{
_Context = new ProjectTrackerContext();
}
public Byte[] RenderProductivityReport(string _sManager)
{
Server1.ReportExecutionService rs = new Server1.ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://Server1/reportserver/ReportExecution2005.asmx";
// Render arguments
byte[] result = null;
string reportPath = "/Staff Client Services/StaffProductivity";
string format = "PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
//Create the list of parameters that will be passed to the report
List<Server1.ParameterValue> lstParameterValues = new List<Server1.ParameterValue>();
Server1.ParameterValue aParameter = new Server1.ParameterValue();
aParameter.Name = "SupervisorSupervisorName";
aParameter.Value = "[Supervisor].[Supervisor Name].&[" + _sManager + "]";
lstParameterValues.Add(aParameter);
Server1.ParameterValue bParameter = new Server1.ParameterValue();
bParameter.Name = "PayPeriodPayPeriodYear";
bParameter.Value = "[Pay Period].[Pay Period Year].&[2015]";
lstParameterValues.Add(bParameter);
int index = 0;
Server1.ParameterValue[] parameterValues = new Server1.ParameterValue[lstParameterValues.Count];
foreach (Server1.ParameterValue parameterValue in lstParameterValues)
{
parameterValues[index] = parameterValue;
index++;
}
string encoding;
string mimeType;
string extension;
Server1.Warning[] warnings = null;
string[] streamIDs = null;
Server1.ExecutionInfo execInfo = new Server1.ExecutionInfo();
Server1.ExecutionHeader execHeader = new Server1.ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportPath, historyID);
rs.SetExecutionParameters(parameterValues, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
execInfo = rs.GetExecutionInfo();
}
catch (Exception e)
{
Exception Errr = e.InnerException;
}
return result;
}
}
}

Finally! For those that are interested...
Found this from nearly two years ago.
AppPool Permission Issue with Accessing Report Server
In particular the comment below:
Almost the same situation here except IIS and Report Server running on Windows Server 2008 R2. I used to have the asp.net application running with it's own application pool and everything worked. When I changed the application to the DefaultAppPool (due to a different problem), I got the permissions problem. I changed the Identity of the DefaultAppPool from ApplicationPoolIdentity to LocalSystem (in IIS, Advanced Settings) and it worked again.
Changed web server default app pool to LocalSystem and wha-la, I am rendering PDF reports from an SSAS cube through my AngularJS SPA.

Related

Zebra Print issue using asp.net with c#

I am using the PrintDocument for printing directly to the network printer using asp.net with and C#. The application hosted in IIS with Windows authentication. I am not getting the error and also the PrintStatus is Printing. But we can not see the printed document in the printer and also there is no errors in the printer.
System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument();
printdoc.DefaultPageSettings.PaperSize = new PaperSize("Custom", 4, 3);
printdoc.OriginAtMargins = true;
// Set the printer name
PrinterSettings printer = new PrinterSettings();
printer.PrinterName = SqlDatabaseUtility.GetZebraPrinterName();
string fullName = CheckPrinterConfiguration(printer.PrinterName);
if (!String.IsNullOrEmpty(fullName))
{
printdoc.PrinterSettings.PrinterName = fullName;
// Handle printing
if (printdoc.PrinterSettings.IsValid)
{
printdoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printdoc_PrintPage);
printdoc.PrinterSettings.Copies = 2;
printdoc.Print();
}
}
Just a theory, but the PrintDocument class is a descendant of Component and so implements IDisposable.
In the same way that you don't leave SqlConnection instances undisposed, you should call Dispose() on your printdoc instance so that any unmanaged resources held by the PrintDocument instance - such as a handle to the printer device, perhaps - get released.
Put a using clause around your printing block as below. It might help with your problem, but even if it does not it is proper practice.
using (System.Drawing.Printing.PrintDocument printdoc = new System.Drawing.Printing.PrintDocument())
{
...
}
The next line of enquiry would be to follow up on the "user permissions" suggestion in the comment. Assuming that your code works if you run it in a test console application, a quick test for this would be to change the user account of your web app's Application Pool to be your own account. If your web app starts printing, then you know that permissions are the problem.

User impersonation between asp.net and ssrs

I have a web application that has application pool configured using domain account. In SSRS, domain account is given the browser access to the folder and SSRS report is configured with proper credentials.
My question is if SSRS report is launched from the web application, will SSRS report be opened under domain account or my account. Currently, it is giving error message as \ doesn't have sufficient permissions to access the report location.
You just need to set a fixed user in the web config along with the SSRS address. This way you set a default for the site to use instead of depending on the user running the site:
Example from a WPF app but very similar to ASP.NET in code behind.
<Button x:Name="btnGetViewerRemoteData" Content="Remote" Click="ReportViewerRemote_Load"/>
Reference name of element in code behind, ensure you import Namespace for 'Microsoft.Reporting.WinForms' (or ASP.NET equivalent).
private void ResetReportViewer(ProcessingMode mode)
{
this.reportViewer.Clear();
this.reportViewer.LocalReport.DataSources.Clear();
this.reportViewer.ProcessingMode = mode;
}
private ICredentials giveuser(string aUser, string aPassword, string aDomain)
{
return new NetworkCredential(aUser, aPassword, aDomain);
}
private void ReportViewerRemoteWithCred_Load(object sender, EventArgs e)
{
ResetReportViewer(ProcessingMode.Remote);
var user = giveuser("User", "Password", "Domain");
reportViewer.ServerReport.ReportServerCredentials.ImpersonationUser = (System.Security.Principal.WindowsIdentity)user;
;
reportViewer.ServerReport.ReportServerUrl = new Uri(#"http:// (server)/ReportServer");
reportViewer.ServerReport.ReportPath = "/Test/ComboTest";
DataSourceCredentials dsCrendtials = new DataSourceCredentials();
dsCrendtials.Name = "DataSource1";
dsCrendtials.UserId = "User";
dsCrendtials.Password = "Password";
reportViewer.ServerReport.SetDataSourceCredentials(new DataSourceCredentials[] { dsCrendtials });
reportViewer.RefreshReport();
}
I hard coded my example but you can have the server, user and password be in a config file. Although security of password may be a concern so depending on your organization so it may be preferable to hard code it or mask it first.

need to automate the RDLC reporting through SSIS script task?

Currently I'm calling RDLC report in asp.net application, where .rdlc is calling and we passing a data source and report in generated as PDF, the entire process initiate on a BUTTON click and report is generate.
Now this process need to automate and report should generate on Monday morning.
There is some suggestion come out that we can use SSIS Script Task and we can call external DLL and can call .rdlc file too to generate the report and then we can schedule SSIS package?
I never having experience on SSIS side, need your suggestion and how to do that, if there is possibilities? Thank You!
Use SSRS to schedule the report to run. No need for ASP.net or SSIS, SSRS has scheduling built in.
You can use SSRS subscription to send the report. If you really want the SSIS to send the report. you can do the following.
Create the report in SSRS
Deploy the report into report server
Create the SSIS package
Drag your Script task into the package.
You could use the following code snippet to send SSRS report using SSIS.
You should create some of the SSIS variables to store the report and render information.
RenderExtension ==> pdf
RenderFileName ==> Name of the file you want write
RenderFormat ==> PDF
RenderOutputPath==> Location to write the file
SSRSConnection ==>
http://localhost/ReportServer/reportexecution2005.asmx [Location of
your report services]
SSRSFolderName ==> Folder name of the report you deployed
SSRSReportName ==> Name of the report
In the following snippet.
public void Main()
{
var rExtension = Dts.Variables["RenderExtension"].Value.ToString();
var rFileName = Dts.Variables["RenderFileName"].Value.ToString();
var rFormat = Dts.Variables["RenderFormat"].Value.ToString();
var rOutputPath = Dts.Variables["RenderOutputPath"].Value.ToString();
var ssrsConnection = Dts.Variables["SSRSConnection"].Value.ToString();
var ssrsFolderName = Dts.Variables["SSRSFolderName"].Value.ToString();
var ssrsReportName = Dts.Variables["SSRSReportName"].Value.ToString();
ReportExecutionService rs=new ReportExecutionService();
Byte[] results;
string encoding = string.Empty;
string mimetype = string.Empty;
string extension = string.Empty;
Warning[] warnings = null;
string[] streamId = null;
string deviceInfo = null;
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = ssrsConnection;
try
{
var reportpath = string.Format("/{0}/{1}", ssrsFolderName, ssrsReportName);
rs.LoadReport(reportpath, null);
//Adding Parameters
//Commenting the following line Till we test the functionality
ParameterValue[] paramValues = new ParameterValue[4];
ParameterValue paramValue = new ParameterValue();
paramValue.Name = "ReportParamName";
paramValue.Value = "X,Y,Z";
paramValues[0] = paramValue;
rs.SetExecutionParameters(paramValues, "en-US");
results = rs.Render(rFormat, deviceInfo, out extension, out mimetype, out encoding, out warnings, out streamId);
var filewithdatetime = string.Format("{0}_{1}",rFileName,DateTime.Now.ToString("yyyy_MM_dd_hhmmss"));
string path = string.Format(#"{0}\{1}.{2}", rOutputPath, filewithdatetime, rExtension);
MessageBox.Show(path);
using (FileStream stream = File.OpenWrite(path))
{
stream.Write(results, 0, results.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
Dts.TaskResult = (int)ScriptResults.Success;
}

Problem with posting to web services within asp.net

I have a web service sitting on a dev machine written in python. I am trying to access said webservice using asp.net via the server side. the webservice has been tested and works in every other instance. but when I hit it via asp.net using a post method asp.net doesn't seem to be sending the post values to the webservice at all, everything else is sent fine. If I run the exact same code in a console application everything works 100%.
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Text;
class WebService {
static public String GetContent(String user_id, String content_id) {
Uri address = new Uri("http://url.to.api/");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
String response_text = String.Empty;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = new NetworkCredential("username", "password");
string data = string.Format("userid={0}&contentid={1}", user_id, content_id);
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
request.ContentLength = byteData.Length;
using (Stream postStream = request.GetRequestStream()) {
postStream.Write(byteData, 0, byteData.Length);
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
StreamReader reader = new StreamReader(response.GetResponseStream());
response_text = reader.ReadToEnd();
}
return response_text;
}
}
updated * with the class more or less thats being used. "url, user/pass".
Also we have checked the information going back and fourth and the webservice never sees the post data... this code as is ran on both a console app and in a asp.net project both hit the webservice, both get a response. the console gets a response with valid information showing that its working, the asp.net project runs and receives and error stating that userid isn't being passed. We have dozens of other sites hitting this webservice with no issues, except non are written in asp.net.
Use a proxy such as Fiddler to view the HTTP transaction between your app and the web service. That should give you a better idea of which end the error is on, and its nature.
You may consider running this against a test "Hello World" service just to test communcations.
Also, post your real code. Change the uri if you want, but what you've quoted above won't compile. The problem may be outside of this snippet.
update
How long is it taking for you to receive a reply? Timeout? Running out of connections?

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