need to automate the RDLC reporting through SSIS script task? - asp.net

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;
}

Related

Angular SPA cannot open remote SSRS report

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.

scraping html without htmlagilitypack

Due to the limitation of the system, i am not allowed to use htmlagilitypack as i dont have the rights to refer the library. So i can only use native asp.net programming language to parse page.
e.g. i want to scrap this page https://sg.linkedin.com/job/google/jobs/ to get the list of google jobs ( just an example, i am not really planning to get this list but my own company's) , i see they are under how can i extra these jobs description and name.
My current codes are
System.Net.WebClient client = new System.Net.WebClient();
try{
System.IO.Stream myStream = client.OpenRead("https://sg.linkedin.com/job/google/jobs/");
System.IO.StreamReader sr = new System.IO.StreamReader(myStream);
string htmlContent = sr.ReadToEnd();
//do not know how to carry on
}catch(Exception e){
Response.Write(e.Message);
}
how can i carry on?
You can fetch that page and use a regular expression to isolate the useful parts. If you get real lucky, you may have a valid XML file:
var html = new WebClient().DownloadString("https://sg.linkedin.com/job/google/jobs/");
var jobs = new XmlDocument();
jobs.LoadXml(Regex.Replace(Regex.Match(html,
#"<ul class=""jobs"">[\s\S]*?</ul>").Value,
#"itemscope | itemprop="".*?""", "")); // clean invalid attributes
foreach (XmlElement job in jobs.SelectNodes("//li[#class='job']"))
{
Console.WriteLine(job.SelectSingleNode(".//a[#class='company']").InnerText);
Console.WriteLine(job.SelectSingleNode(".//h2/a").InnerText);
Console.WriteLine(job.SelectSingleNode(".//p[#class='abstract']").InnerText);
Console.WriteLine();
}

How to access the properties and parts of an SSRS report at runtime

I'm using the ReportViewer control to display a server report in an ASP.NET page and I'm looking for a way to get the report into an object that I can then read and/or modify.
This kind of thing:
var rw = report.Width;
var t = ((Chart)report.Body.Item[3]).Title;
Is there a way, or am I stuck with parsing the XML file?
ETA:
I'm beginning to think I will need to access the XML file but I can't find out how to download that from the server, modify it (in memory) and then send it to the ReportViewer control.
ETA2:
Here's how to download the report definition (clean up left out for brevity):
// Download the report
var rs = new ReportingService2010();
rs.UseDefaultCredentials = true;
var reportDefinition = rs.GetItemDefinition("/DashboardReports/MyChart");
// Convert to XML
var ms = new MemoryStream(reportDefinition);
var doc = new System.Xml.XmlDocument();
doc.Load(ms);
// To load the stream into the report viewer
stream.Position = 0; // needed because we used the stream above - doc.Load(ms)
this.ReportViewer1.ServerReport.LoadReportDefinition(stream);

How can I import external files into SDL Tridion 2011 using core service?

I want to push PDF, Word and Excel files into SDL Tridion 2011 by using core service.
I tried below code but get this error:
Invalid value for property 'BinaryContent'. Unable to open uploaded file:
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("wsHttp_2011"))
{
ISessionAwareCoreService client = factory.CreateChannel();
ComponentData multimediaComponent = (ComponentData)client.GetDefaultData(
ItemType.Component, "tcm:19-483-2");
multimediaComponent.Title = "MultimediaFile";
multimediaComponent.ComponentType = ComponentType.Multimedia;
multimediaComponent.Schema.IdRef = "tcm:19-2327-8";
using (StreamUploadClient streamClient = new StreamUploadClient())
{
FileStream objfilestream = new FileStream(#"\My Documents\My Poc\images.jpg",
FileMode.Open, FileAccess.Read);
string tempLocation = streamClient.UploadBinaryContent("images.jpg",
objfilestream);
}
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = #"C:\Documents and Settings\My Poc\images.jpg";
binaryContent.Filename = "images.jpg";
binaryContent.MultimediaType = new LinkToMultimediaTypeData()
{
IdRef ="tcm:0-2-65544"
};
multimediaComponent.BinaryContent = binaryContent;
IdentifiableObjectData savedComponent = client.Save(multimediaComponent,
new ReadOptions());
client.CheckIn(savedComponent.Id, null);
Response.Write(savedComponent.Id);
}
Have a read of Ryan's excellent article here http://blog.building-blocks.com/uploading-images-using-the-core-service-in-sdl-tridion-2011
All binary files are handled the same way - so his technique for images will be equally as valid for documents, just make sure you use a Schema with the appropriate mime types.
The process for uploading binaries into Tridion using the Core Service is:
Upload the binary data to the Tridion server using a StreamUploadClient. This returns you the path of the file on the Tridion server.
Create a BinaryContentData that points to the file on the Tridion server (so with the path you got back from step 1)
Create a ComponentData that refers to the the BinaryContentData from step 2
Save the ComponentData
You are setting the local path for your file in step 2.
binaryContent.UploadFromFile = #"C:\Documents and Settings\My Poc\images.jpg";
But Tridion will never be able to find that file there. You instead should set the path that you got back from UploadBinaryContent:
string tempLocation;
using (StreamUploadClient streamClient = new StreamUploadClient())
{
FileStream objfilestream = new FileStream(#"\My Documents\My Poc\images.jpg",
FileMode.Open, FileAccess.Read);
tempLocation = streamClient.UploadBinaryContent("images.jpg", objfilestream);
}
BinaryContentData binaryContent = new BinaryContentData();
binaryContent.UploadFromFile = tempLocation;
Note that the Ryan's original code does exactly that.

Spring MVC 3.0 Jasper-Reports 4 Directing HTML reports in browser

I am working with Spring MVC 3 and JasperReports. I've created some great PDF and Xls reports without a problem. What I would like to do is display the created HTML report on screen for the user as a preview of the report they are getting, wrapped in the website template. Is there a way to do this?
I haven't found any tutorials/articles on this subject, I did find a book on JasperReports 3.5 for Java Developers that kind a addressed this. (I'm a noob on this so bear with me.) My understanding of this is that I have to redirect the input stream to the browser. I figure that there must be an easier way! And a way to strip the HTML report header and footer from it.
Any help would be appreciated!
Instead of using another framework to solve my problem. I solved it like this:
#RequestMapping(value = "/report", method = RequestMethod.POST)
public String htmlReport(#RequestParam(value = "beginDate") Date begin,
#RequestParam(value = "endDate", required = false) Date end,
ModelMap map) {
try {
// Setup my data connection
OracleDataSource ds = new OracleDataSource();
ds.setURL("jdbc:oracle:thin:user/password#10.10.10.10:1521:tst3");
Connection conn = ds.getConnection();
// Get the jasper report object located in package org.dphhs.tarts.reports
// Load it
InputStream reportStream = this.getClass().getResourceAsStream("reports/tartsCostAllocation.jasper");
JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportStream);
// Populate report with data
JasperPrint jasperPrint =
JasperFillManager.fillReport(jasperReport, new HashMap(), conn);
// Create report exporter to be in Html
JRExporter exporter = new JRHtmlExporter();
// Create string buffer to store completed report
StringBuffer sb = new StringBuffer();
// Setup report, no header, no footer, no images for layout
exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, "");
exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, "");
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
// When report is exported send to string buffer
exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sb);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
// Export the report, store to sb
exporter.exportReport();
// Use Jsoup to clean the report table html to output to browser
Whitelist allowedHtml = new Whitelist();
allowedHtml.addTags("table", "tr", "td", "span");
allowedHtml.addTags("table", "style", "cellpadding", "cellspacing", "border", "bgcolor");
allowedHtml.addAttributes("tr", "valign");
allowedHtml.addAttributes("td", "colspan", "style");
allowedHtml.addAttributes("span", "style");
String html = Jsoup.clean(sb.toString(), allowedHtml);
// Add report to map
map.addAttribute("report", html);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "costallocation/report";
}

Resources