I have been working on SQL Server Reporting Services 2008, and i am connecting to report server from asp.net using below code:
ReportExecutionService rs = new ReportExecutionService();
System.Net.CredentialCache.DefaultNetworkCredentials.Domain = ConfigurationManager.AppSettings["Domain"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.UserName = ConfigurationManager.AppSettings["UserName"].ToString();
System.Net.CredentialCache.DefaultNetworkCredentials.Password = ConfigurationManager.AppSettings["Password"].ToString();
rs.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
// Render arguments
byte[] result = null;
string reportpath = reportPath;
string format = "PDF";
string historyID = null;
string devInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
string encoding;
string mimeType;
string extension;
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = new ParameterValue();
parameters[0].Name = reportParameterBidName.Trim();
parameters[0].Value = reportParameterBidValue.Trim();
Warning[] warnings = null;
string[] streamIDs = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
rs.ExecutionHeaderValue = execHeader;
execInfo = rs.LoadReport(reportpath, historyID);
rs.SetExecutionParameters(parameters, "en-us");
String SessionId = rs.ExecutionHeaderValue.ExecutionID;
try
{
result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
return result;
}
catch (SoapException e)
{
return null;
}
Now it works well with my local server, when i upload it to final server it does not work and throws unable to connect error. If i use VPN and use same credentials then too it is working.
Please advise on this.
Related
My ASP.NET Core MVC project has several reports. To render the reports as PDF, I'm using AspNetCore.Reporting library.
This library works fine for a single report but due to some cache issues it throws an exception while generating another report. The solution I found on the internet was to run report generation as a new process but I don't know how to implement that.
I found the suggestion to use Tmds.ExecFunction to run report generation as a seperate process. But I dont know how to pass parameters to the function.
Here is my code:
string ReportName = "invoiceDine";
DataTable dt = new DataTable();
dt = GetInvoiceItems(invoiceFromDb.Id);
Dictionary<string, string> param = new Dictionary<string, string>();
param.Add("bParam", $"{invoiceFromDb.Id}");
param.Add("gParam", $"{salesOrderFromDb.Guests}");
param.Add("tParam", $"{invoiceFromDb.Table.Table}");
param.Add("dParam", $"{invoiceFromDb.Time}");
param.Add("totalP", $"{invoiceFromDb.SubTotal}");
param.Add("t1", $"{tax1}");
param.Add("t2", $"{tax2}");
param.Add("tA1", $"{tax1Amount}");
param.Add("tA2", $"{tax2Amount}");
param.Add("AT1", $"{totalAmountWithTax1}");
param.Add("AT2", $"{totalAmountWithTax2}");
param.Add("terminalParam", $"{terminalFromDb.Name}");
param.Add("addressParam", $"{t.Address}");
param.Add("serviceParam", "Service Charges of applicable on table of " + $"{personForServiceCharges}" + " & Above");
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
return File(result,"application/Pdf");
This is my version of the function:
``` public byte[] GenerateReport(string ReportName, Dictionary<string,string> Parameters,string DataSetName,DataTable DataSource )
{
string guID = Guid.NewGuid().ToString().Replace("-", "");
string fileDirPath = Assembly.GetExecutingAssembly().Location.Replace("POS_Website.dll", string.Empty);
string ReportfullPath = Path.Join(fileDirPath, "\\Reports");
string JsonfullPath = Path.Join(fileDirPath,"\\JsonFiles");
string rdlcFilePath = string.Format("{0}\\{1}.rdlc", ReportfullPath, ReportName);
string generatedFilePath = string.Format("{0}\\{1}.pdf", JsonfullPath, guID);
string jsonDataFilePath = string.Format("{0}\\{1}.json", JsonfullPath, guID);
File.WriteAllText(jsonDataFilePath, JsonConvert.SerializeObject(DataSource));
FunctionExecutor.Run((string[] args) =>
{
// 0 : Data file path - jsonDataFilePath
// 1 : Filename - generatedFilePath
// 2 : RDLCPath - rdlcFilePath
ReportResult result;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
LocalReport report = new LocalReport(args[2]);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(File.ReadAllText(args[0]));
report.AddDataSource(args[3], dt);
result = report.Execute(RenderType.Pdf, 1,Parameters);
using (var fs = new FileStream(args[1], FileMode.Create, FileAccess.Write))
{
fs.Write(result.MainStream);
}
}, new string[] {jsonDataFilePath, generatedFilePath, rdlcFilePath, DataSetName });
var memory = new MemoryStream();
using (var stream = new FileStream(Path.Combine("", generatedFilePath), FileMode.Open))
{
stream.CopyTo(memory);
}
File.Delete(generatedFilePath);
File.Delete(jsonDataFilePath);
memory.Position = 0;
return memory.ToArray();
}
But it throws exception "Field marshaling is not supported by ExecFunction" on line:
var result = reportService.GenerateReport(ReportName, param, "dsInvoiceDine", dt);
No Need to run report generation as a seperate process. Just Dont Pass extension as 1
in:
var result = localReport.Execute(RenderType.Pdf, 1, param);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);
In MVC I could generate .xsl or .pdf file with no issues with File(), but with the web Api nothing is happening when the action is fired! This is what I have tried so far.
I have tried a couple of solutions in here including this one Web API and report viewer
but nothing has worked for me.
public HttpResponseMessage Export(ExportVolunteerSearchFilter searchModel)
{
if (searchModel.Equals(null))
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
var volunteers = _volunteersService.ExportAllVolunteersData(searchModel);
ReportViewer ReportViewer1 = new ReportViewer();
ReportViewer1.SizeToReportContent = true;
ReportViewer1.LocalReport.ReportPath =
System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc");
ReportViewer1.LocalReport.EnableExternalImages = true;
ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource _rsource = new ReportDataSource("DataSet1", volunteers);
ReportViewer1.LocalReport.DataSources.Add(_rsource);
ReportViewer1.LocalReport.Refresh();
Warning[] warnings;
string[] streamIds;
string mimeType = string.Empty;
string encoding = string.Empty;
string extension = string.Empty;
string fileName = "reportVolunteer";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath("~/Reports/VolunteersReport.rdlc"), FileMode.Open);
response.Content = new StreamContent(stream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = fileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xls");
return response;
}
I have done it as:-
response.Content = new PushStreamContent(
async (outstream) =>
{
await getDataMethod(outstream)
},
new MediaTypeHeadrerValue(mediaType:"application/xls"));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = $"test.xls"
};
return response;
final String SOAP_ACTION = "http://tempuri.org/get_data2";
final String OPERATION_NAME = "get_data2";
final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";
final String SOAP_ADDRESS = "****";
final String req_no, req_date, bolnumber, container_no, current_loc, truck_no;
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
try
{
httpTransport.call(SOAP_ACTION, envelope);
SoapObject resultsString = (SoapObject)envelope.getResponse();
Log.d("-----------------------", resultsString.getProperty("emp_name").toString());
tv.setText(resultsString.getPropertyCount());
}
catch (Exception exception)
{
exception.printStackTrace();
tv.setText(exception.toString());
}
I've been trying to convert a SSRS Report to PDF and save to my local drive using the Reporting Web Services. Though I'm able to generate the corresponding pdf file but the contents of the file are missing. I've checked that the report I'm trying to convert is not an empty one. Only the header section is present there within the generated pdf files. Below is the code I'm using:
protected void GeneratePDFFromReport(object sender, EventArgs e)
{
RS2005.ReportingService2005 rs;
RE2005.ReportExecutionService rsExec;
// Create a new proxy to the web service
rs = new RS2005.ReportingService2005();
rsExec = new RE2005.ReportExecutionService();
// Authenticate to the Web service using Windows credentials
rs.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
rsExec.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
//rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "http://servername/reportserver/reportservice2005.asmx";
rsExec.Url = "http://servername/reportserver/reportexecution2005.asmx";
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] results;
string encoding = String.Empty;
string mimeType = "application/pdf";
string extension = String.Empty;
RE2005.Warning[] warnings = null;
string[] streamIDs = null;
// Path of the Report - XLS, PDF etc.
string fileName = #"C:\Report\MemberReport.pdf";
// Name of the report - Please note this is not the RDL file.
string _reportName = #"/ReportFolder/ReportName";
string _historyID = null;
bool _forRendering = false;
RS2005.ParameterValue[] _values = null;
RS2005.DataSourceCredentials[] _credentials = null;
RS2005.ReportParameter[] _parameters = null;
try
{
_parameters = rs.GetReportParameters(_reportName, _historyID, _forRendering, _values, _credentials);
RE2005.ExecutionInfo ei = rsExec.LoadReport(_reportName, historyID);
results = rsExec.Render(format, deviceInfo,
out extension, out encoding,
out mimeType, out warnings, out streamIDs);
try
{
FileStream stream = File.Create(fileName, results.Length);
stream.Write(results, 0, results.Length);
stream.Close();
}
catch { }
results = null;
}
catch (Exception ex)
{
throw ex;
}
}
Any help would highly be appreciated. Thanks.
Assuming that SSRS is working OK using browser, please modify your posted code as shown below:
1) Device info string, please set it as follows:
string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; //Initial value was null
2) Create Header instance before using web call LoadReport:
ExecutionHeader execHeader = new ExecutionHeader();
RE2005.ExecutionHeaderValue = execHeader;
This is an interesting problem, and I will do my best to explain. If you have any questions, please ask.
I have written a WCF service that is suppose to communicate with a JAVA client. This service was created via contract first from a WSDL. Now, according to the WCF test client everything works, even testing on a PHP client works as well. But when it comes to the Java client, the request messages and subsequent response messages fail to return: I get a null object SOAP fault. Here is were I think the problem lies:
According to the XSD and WSDL, I have a DateTime value that I am suppose to take in. This dateTime value from the client is of form: 2012-01-01T12:00:00.00Z. Unfortunately, this input is not valid with the built in .NET datetime. So, to get around this, I changed my code to take in a string datatype, convert that string to a Datetime to send it to the database, get a response from the database in that dateTime and convert it back to a string for the response to return a value that is like the one that was inputted.
I built a logger to check to see if the messages were being sent to and from my wcf service. From that, I have identified that messages from the client were not being received. My only guess is that it is because of the datetime issue.
Is there a way to take in a dateTime datatype in the format: 2012-01-01T12:00:00.000Z? If i can, then that will mean that the request will match my datatype and maybe it will work.
Here is some code:
public partial class findSeatsRequest
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="departAirport")]
public string DepartAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=1, Name="arriveAirport")]
public string ArriveAirport;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=2, Name="earliestDepartTime")]
public string EarliestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=3, Name="latestDepartTime")]
public string LatestDepartTime;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=4, Name="minimumSeatsAvailable")]
public int MinimumSeatsAvailable;
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineMessage", Order=5, Name="maximumFlightsToReturn")]
public int MaximumFlightsToReturn;
public findSeatsRequest()
{
}
public findSeatsRequest(string departAirport, string arriveAirport, string earliestDepartTime, string latestDepartTime, int minimumSeatsAvailable, int maximumFlightsToReturn)
{
this.DepartAirport = departAirport;
this.ArriveAirport = arriveAirport;
this.EarliestDepartTime = earliestDepartTime;
this.LatestDepartTime = latestDepartTime;
this.MinimumSeatsAvailable = minimumSeatsAvailable;
this.MaximumFlightsToReturn = maximumFlightsToReturn;
}
}
public partial class findSeatsResponse
{
[MessageBodyMemberAttribute(Namespace="http://soa.cs.uwf.edu/airlineData", Order=0, Name="flight")]
[XmlElementAttribute("flight")]
public System.Collections.Generic.List<flightType> Flight;
public findSeatsResponse()
{
}
public findSeatsResponse(System.Collections.Generic.List<flightType> flight)
{
this.Flight = flight;
}
}
public virtual findSeatsResponse findSeats(findSeatsRequest request)
{
string departAirport = request.DepartAirport;
string arriveAirport = request.ArriveAirport;
string earliestDepartTime = request.EarliestDepartTime;
string latestDepartTime = request.LatestDepartTime;
int minimumSeatsAvailable = request.MinimumSeatsAvailable;
int maximumFlightsToReturn = request.MaximumFlightsToReturn;
SqlCommand cmd = null;
DataSet ds = new DataSet();
List<flightType> flight = new List<flightType>();
EventLogger log = new EventLogger();
findSeatsRequest inValue = new findSeatsRequest();
inValue.DepartAirport = departAirport;
inValue.ArriveAirport = arriveAirport;
inValue.EarliestDepartTime = earliestDepartTime;
inValue.LatestDepartTime = latestDepartTime;
inValue.MinimumSeatsAvailable = minimumSeatsAvailable;
inValue.MaximumFlightsToReturn = maximumFlightsToReturn;
string latestT = inValue.LatestDepartTime.Replace("T", " ");
string latestZ = latestT.Replace("Z", "");
DateTime _latestDepartTime = DateTime.ParseExact(latestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
string earliestT = inValue.EarliestDepartTime.Replace("T", " ");
string earliestZ = earliestT.Replace("Z", "");
DateTime _earliestDepartTime = DateTime.ParseExact(earliestZ, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
log.WriteToDataBase(DateTime.Now, "FindSeats", 1, "This is the request: " + inValue);
//Check Maximum Flights
if (inValue.MaximumFlightsToReturn > 100 | inValue.MaximumFlightsToReturn < 0)
{
throw new FaultException(
"You cannot select more than 100 flights to return, or the maximum flights to return is negative.",
new FaultCode("OutOfRange"));
}
// Check Minimum Seats Available.
if (inValue.MinimumSeatsAvailable < 0)
{
throw new FaultException(
"You minimum seats available cannot be negative.",
new FaultCode("OutOfRange"));
}
// Check for valid Departure Airport
if (departAirport != null && departAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT DepartAirport FROM Flight WHERE DepartAirport='" + departAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader depAirport;
depAirport = cmd.ExecuteReader();
if (depAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
// Check for valid Arrival Airport
if (arriveAirport != null && arriveAirport != "ANY")
{
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
string check = "SELECT ArriveAirport FROM Flight WHERE ArriveAirport='" + arriveAirport + "'";
cmd = new SqlCommand(check, conn);
cmd.CommandText = check;
SqlDataReader arrAirport;
arrAirport = cmd.ExecuteReader();
if (arrAirport.HasRows == false)
{
throw new FaultException(
"Invalid Airport code used.",
new FaultCode("Invalid Text Entry"));
}
}
finally
{
if (cmd != null)
cmd.Dispose();
}
}
try
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
cmd = new SqlCommand("usp_NewFindSeats", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#DepartureAirport", inValue.DepartAirport));
cmd.Parameters.Add(new SqlParameter("#ArrivalAirport", inValue.ArriveAirport));
cmd.Parameters.Add(new SqlParameter("#EarliestDepTime", _earliestDepartTime));
cmd.Parameters.Add(new SqlParameter("#LatestDepTime", _latestDepartTime));
cmd.Parameters.Add(new SqlParameter("#minSeatsAvailable", inValue.MinimumSeatsAvailable));
cmd.Parameters.Add(new SqlParameter("#maxFlightsRequested", inValue.MaximumFlightsToReturn));
using (SqlDataReader sqlReader = cmd.ExecuteReader())
{
while (sqlReader.Read())
{
flightType Flight = new flightType();
Flight.FlightId = sqlReader.GetString(0);
Flight.DepartAirport = sqlReader.GetString(1);
Flight.ArriveAirport = sqlReader.GetString(2);
Flight.DepartTime = sqlReader.GetDateTime(3).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.ArriveTime = sqlReader.GetDateTime(4).ToString("yyyy-MM-ddTHH:mm:ss.fffZ");
Flight.FlightSeatsAvailable = sqlReader.GetInt32(5);
Flight.FlightSeatPriceUSD = sqlReader.GetDouble(6);
flight.Add(Flight);
}
}
For this particular problem, the issue wasn't anything I thought it was in the beginning. Firstly, had to use WrapperNames in my C# code's request operations and the names I used were incorrect.
Secondly, I needed to specify SOAP Body encoding which I had to do within my Interface layer.
[XmlSerializerFormatAttribute(SupportFaults=true, Style=OperationFormatStyle.Document ,Use=OperationFormatUse.Literal)]