Script task failed to generate files - ssis

I have used script task in ssis package to generate loads of excel files automatically every month.
Untill now script task worked fine but this month failed and when I did debug error showing at below
results = re.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
How can I fix this?
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
#region VSTA generated code
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
public void Main()
{
// TODO: Add your code here
string ssrsReport;
string destination;
string monthName;
string yyyy;
string currentReportName;
string currentReportShortName;
string password;
string filetype;
string version;
yyyy = (string)Dts.Variables["varYear"].Value;
monthName = (string)Dts.Variables["varMonthName"].Value;
filetype = (string)Dts.Variables["varFileType"].Value;
version = (string)Dts.Variables["varVersion"].Value;
// The SQL Task already ensures that these following five values are not null:
currentReportShortName = (string)Dts.Variables["varRSParameter"].Value;
currentReportName = (string)Dts.Variables["varRSReportName"].Value;
password = (string)Dts.Variables["varRSPassword"].Value;
destination = (string)Dts.Variables["varDestinationPath"].Value + "\\" + "Data - " + currentReportName + " " + monthName + " - " + yyyy + "." + filetype;
ssrsReport = (string)Dts.Variables["varSSRSReport"].Value;
try
{
CreateFolder((string)Dts.Variables["varDestinationPath"].Value);
RenderReport(destination, ssrsReport, currentReportShortName, password, filetype, version);
Dts.TaskResult = (int)ScriptResults.Success;
}
catch
{
Dts.TaskResult = (int)ScriptResults.Failure;
throw;
}
}
private void RenderReport(string destinationFile, string ssrsReport, string agent, string password, string filetype, string version)
{
string historyID = null;
string deviceInfo = null;
string format = null;
if (filetype == "xls")
{
format = "Excel"; //Can be XML, NULL, CSV, IMAGE, PDF, HTML4.0, HTML3.2, MHTML, EXCEL, and HTMLOWC
}
else if (filetype == "pdf")
{
format = "PDF";
}
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecutionService.Warning[] warnings = null;
string[] streamIDs = null;
ReportExecutionService.ReportExecutionService re = new ReportExecutionService.ReportExecutionService();
re.Credentials = System.Net.CredentialCache.DefaultCredentials;
re.Timeout = 600000;
try
{
ReportExecutionService.ExecutionInfo ei = re.LoadReport(ssrsReport, historyID);
// If we need to generate a parametised report then do that here:
// check if multiple agent parameters are being passed for this report
ReportExecutionService.ParameterValue[] rptParameters = new ReportExecutionService.ParameterValue[4];
rptParameters[0] = new ReportExecutionService.ParameterValue();
rptParameters[0].Name = "DataName";
rptParameters[0].Value = agent;
rptParameters[1] = new ReportExecutionService.ParameterValue();
rptParameters[1].Name = "Year";
rptParameters[1].Value = (string)Dts.Variables["varYear"].Value;
rptParameters[2] = new ReportExecutionService.ParameterValue();
rptParameters[2].Name = "Month";
rptParameters[2].Value = (string)Dts.Variables["varMonth"].Value;
rptParameters[3] = new ReportExecutionService.ParameterValue();
rptParameters[3].Name = "version";
rptParameters[3].Value = (string)Dts.Variables["varVersion"].Value;
re.SetExecutionParameters(rptParameters, "en-GB");
results = re.Render(format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
FileStream stream = File.Create(destinationFile, results.Length);
stream.Write(results, 0, results.Length);
stream.Close();
if (password != "NONE" && password.Length > 0)
{
PasswordProtectExcel(destinationFile, password);
}
}
catch (Exception e)
{
throw new Exception("Error caught within RenderReport method: ", e);
}
}
private void CreateFolder(string path)
{
try
{
bool exists = Directory.Exists((string)Dts.Variables["varDestinationPath"].Value);
if (!exists)
System.IO.Directory.CreateDirectory((string)Dts.Variables["varDestinationPath"].Value);
}
catch (Exception e)
{
throw new Exception("Error caught within CreateFolder method: ", e);
}
}
// Code adapted from http://www.sqlservercentral.com/articles/Integration+Services+(SSIS)/71222/
private void PasswordProtectExcel(string excelSourceFile, string password)
{
Microsoft.Office.Interop.Excel.Application excelApp = null;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
try
{
//open the Excel application
excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelWorkbook = excelApp.Workbooks.Open(excelSourceFile, 0, false, Type.Missing, Type.Missing, Type.Missing, true,
Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", false, false,
0, false, false, false);
//Save the file with the "excelSourceFile" name
excelApp.DisplayAlerts = false;
excelWorkbook.SaveAs(excelSourceFile, Type.Missing, password, //password is used in the SaveAs function
Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, true, Type.Missing,
Type.Missing, Type.Missing);
}
catch (Exception e)
{
throw new Exception("Error caught within PasswordProtectExcel method: ", e);
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
//Close the workbook
excelWorkbook.Close(true, excelSourceFile, false);
Marshal.FinalReleaseComObject(excelWorkbook);
excelWorkbook = null;
//Quit the application
excelApp.Quit();
Marshal.FinalReleaseComObject(excelApp);
excelApp = null;
}
}
}
}

Related

SSRS Report Execution Service: export to xlsx without error

Hello thanks for looking.
I have some .net code that uses the SSRS Report Execution Service to download a report for the user as an xlsx file.
It works & everything in the report is present & accounted for.
One annoying thing though. When opened in Excel 365 it gives a popup saying:
We found a problem with some content in "theReport.xlsx" Do you want us to try to recover as much as we can? If you trust the source of this workbook click yes
When I click yes then it indicates that the workbook was repaired and the report looks normal.
It does not give any indication what it repaired in the log file, just that it was repaired.
Please take a look at my code. Perhaps there is something small I can change to get rid of the error when the Excel sheet is opened.
private void DownloadQuoteExport()
{
string reportName = "reportName";
string fileName = "filename";
//create web services instance
ReportExecutionService rs = getService();
//render report 1st parameter
ParameterValue param1 = new ParameterValue();
param1.Name = "QuoteID";
param1.Value = quoteId.ToString();
try
{
executeReport(reportName, new ParameterValue[] { param1 }, "EXCELOPENXML", fileName, rs);
}
catch (Exception ex)
{
Response.Write(ex.Message + "<br>" + ex.StackTrace.ToString());
}
}
private void executeReport(String reportName, ParameterValue[] rptParams, String rptFormat, string strRptFileName, ReportExecutionService service)
{
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
string historyID = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
service.ExecutionHeaderValue = execHeader;
execInfo = service.LoadReport(reportName, historyID);
service.SetExecutionParameters(rptParams, "en-us");
String SessionId = service.ExecutionHeaderValue.ExecutionID;
byte[] result = service.Render(rptFormat, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Response.ClearContent();
if (rptFormat == "EXCELOPENXML")
{
Response.AppendHeader("content-disposition", "attachment; filename=" + strRptFileName + ".xlsx");
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Response.BinaryWrite(result);
Response.Flush();
}
This is finally what worked.
private void executeReport(String reportName, ParameterValue[] rptParams, String rptFormat, string strRptFileName, ReportExecutionService service)
{
string encoding;
string mimeType;
string extension;
Warning[] warnings = null;
string[] streamIDs = null;
string historyID = null;
ExecutionInfo execInfo = new ExecutionInfo();
ExecutionHeader execHeader = new ExecutionHeader();
service.ExecutionHeaderValue = execHeader;
execInfo = service.LoadReport(reportName, historyID);
service.SetExecutionParameters(rptParams, "en-us");
String SessionId = service.ExecutionHeaderValue.ExecutionID;
byte[] result = service.Render(rptFormat, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
Response.ClearContent();
Response.Clear();
if (rptFormat == "EXCELOPENXML")
{
Response.AppendHeader("content-disposition", "attachment; filename=" + strRptFileName + ".xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
Response.BinaryWrite(result);
Response.Flush();
Response.SuppressContent = true;
try
{
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (ThreadAbortException ex)
{
//ignore
}
}

CREATE statement fails in ASP.NET MVC

My create statement could not work suddenly and it goes straight to an error message (Account cannot be created). I am not sure where I went wrong as I did not make any modification to it at all. In total, I have encountered this problem THRICE and my only solution is to make a new project for it to work again with the same exact codes. Any suggestions to ensure no such thing happen again in the future? Thank you in advance! Here are my codes in the controller:
[HttpPost]
public IActionResult CreateUser(Users usr)
{
if (!ModelState.IsValid)
{
ViewData["Message"] = "Invalid Input";
ViewData["MsgType"] = "warning";
return View("CreateUser");
}
else
{
string insert = #"INSERT INTO WBUsers(UserId, UserPw,FullName, Email, UserRole, Dob, ContactNo, usr.Billing_Address)
VALUES('{0}', HASHBYTES('SHA1', '{1}'), '{2}', '{3}', '{4}', '{5}', {6}, '{7}')";
if (DBUtl.ExecSQL(insert, usr.UserId, usr.UserPw, usr.FullName, usr.Email, usr.UserRole, usr.Dob, usr.ContactNo, usr.Billing_Address) == 1)
{
string template = #"Hi {0},<br/><br/>
Welcome to WorldBay!
Your userid is <b>{1}</b> and password is <b>{2}</b>. Please change your password upon login.
<br/><br/>Adminstrator";
string title = "Account Sign Up";
string message = String.Format(template, usr.FullName, usr.UserId, usr.UserPw);
string result = "";
bool outcome = false;
outcome = EmailUtl.SendEmail(usr.Email, title, message, out result);
if (outcome)
{
ViewData["Message"] = "Account has been created";
ViewData["MsgType"] = "success";
}
else
{
ViewData["Message"] = result;
ViewData["MsgType"] = "warning";
}
}
else
{
ViewData["Message"] = "Account cannot be created";
ViewData["MsgType"] = "danger";
}
return View("CreateUser");
}
}
DBUtil code consists of:
public static int ExecSQL(string sql, params object[] list)
{
List<String> escParams = new List<String>();
foreach (object o in list)
{
if (o == null)
escParams.Add("");
else
escParams.Add(EscQuote(o.ToString()));
}
DB_SQL = String.Format(sql, escParams.ToArray());
int rowsAffected = 0;
using (SqlConnection dbConn = new SqlConnection(DB_CONNECTION))
using (SqlCommand dbCmd = dbConn.CreateCommand())
{
try
{
dbConn.Open();
dbCmd.CommandText = DB_SQL;
rowsAffected = dbCmd.ExecuteNonQuery();
}
catch (System.Exception ex)
{
DB_Message = ex.Message;
rowsAffected = -1;
}
}
return rowsAffected;
}

Common class for HttpWebRequests - WP8

For making the http calls I use the functions
private void DoneClicked(object sender, RoutedEventArgs e)
{
string emailText = emailTBox.Text;
string oldPass = oldPasswordPBox.Password;
string newPass = newPasswordPBox.Password;
if (emailText == "" || oldPass == "" || newPass == "")
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Some field is empty";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
var data = new { user = new { email = emailText, old_password = oldPass, new_password = newPass } };
jsonStringChild = JsonConvert.SerializeObject(data, Formatting.Indented);
Debug.WriteLine(jsonStringChild);
string uri = CycleManager.HTTP_URI + "change-password";
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = CycleManager.HTTP_PUT;
request.ContentType = "application/json";
request.Accept = "application/json";
bool IsNetWork = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
if (!IsNetWork)
{
PassDiaTB1.Text = "Oops..";
PassDiaTB2.Text = "Check your internet connectivity";
PassiveDialogs.Visibility = System.Windows.Visibility.Visible;
}
else
{
request.BeginGetRequestStream(new AsyncCallback(PostCallBack), request);
}
}
}
void PostCallBack(IAsyncResult result)
{
// End the stream request operation
HttpWebRequest request = result.AsyncState as HttpWebRequest;
Stream postStream = request.EndGetRequestStream(result);
byte[] byteArray = Encoding.UTF8.GetBytes(jsonStringChild);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
request.BeginGetResponse(new AsyncCallback(GetResponseStreamCallBack), request);
}
void GetResponseStreamCallBack(IAsyncResult callBackResult)
{
try
{
HttpWebRequest request = callBackResult.AsyncState as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callBackResult);
statusCode = (int)response.StatusCode;
if (statusCode == 200)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
Dictionary<string, string> token = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
string email = token["email"];
string auth_token = token["auth_token"];
CycleManager cycMan = CycleManager.Instance;
cycMan.AuthToken = auth_token;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
catch (WebException e)
{
if (e.Response != null)
{
HttpWebResponse aResp = e.Response as HttpWebResponse;
if (aResp != null)
{
statusCode = (int)aResp.StatusCode;
}
if (statusCode == 401)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
if (statusCode == 500)
{
string result = "";
using (StreamReader httpWebStreamReader = new StreamReader(aResp.GetResponseStream()))
{
result = httpWebStreamReader.ReadToEnd();
}
string json = result;
var definition = new { message = "" };
var parsedStrings = JsonConvert.DeserializeAnonymousType(json, definition);
message = parsedStrings.message;
Dispatcher.BeginInvoke(ShowPassiveDialog);
}
}
}
}
The same three calls are made in several pages, changing the parameters and methods. I am trying to create a common class which can be called to make http calls. But these functions have differnt return types and I'm not able generalize all this??
Any help would be appreciated.
May this will guide you. I create a wrapper class for such kind of work, its help me a lot and reduce lots of code and effort.
public class CommanHttpRequest
{
private string ACCEPT="application/json";
private string ContentType ="application/json";
private string POST_METHOD="POST";
private string GET_METHOD="GET";
public string IsException { get; set; }
public HttpWebRequest GetHttpRequest(string url,string header1, string header2)
{
HttpWebRequest getRequest = HttpWebRequest.CreateHttp(url);
getRequest.Accept =this.ACCEPT;
getRequest.ContentType = this.ACCEPT;
getRequest.Headers["Header1"] = header1;
getRequest.Headers["Header2"] = header2;
getRequest.Method = this.POST_METHOD;
return getRequest ;
}
public void GetRequestResponse(Action<your type> callback, IAsyncResult asyncResult, string envelop)
{
try
{
UTF8Encoding encoding = new UTF8Encoding();
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
Stream body = request.EndGetRequestStream(asyncResult);
//write body if any
byte[] formBytes = encoding.GetBytes(envelop);
body.Write(formBytes, 0, formBytes.Length);
body.Close();
request.BeginGetResponse(result =>
{
try
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result);
using (Stream data = response.GetResponseStream())
{
using (var reader = new StreamReader(data))
{
string jsonString = reader.ReadToEnd();
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonString));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(your type));
var parseddata = dataContractJsonSerializer.ReadObject(memoryStream) as your type;
callback(parseddata );
}
}
}
catch (WebException ex)
{
IsException = ex.Message;
//I asume your type =List<abc>();
callback(new List<abc>());
}
}, request);
}
catch (Exception ex)
{
IsException = ex.Message;
callback(new List<abc>());
}
}
}
public class abc
{
public void TestRequest()
{
string url="some url";
CommanHttpRequest requestObj = new CommanHttpRequest();
HttpWebRequest testRequest = _requestObj.GetHttpRequest(url, password, email);
//if there some body in request
string envelope = "{\"requestType\":" + requestType + "}";
testRequest .BeginGetRequestStream(result =>
{
requestObj.GetRequestResponse(resultData =>
{
ProcessServiceResponse(resultData);
}, result, envelope);
}, testRequest );
}
public void ProcessServiceResponse(List<abc> abcdata)
{
//abcdata is your data
}
}

passing values to url using http get

i need to pass 2 string json parameters to a url and i need to get the json response. how can i pass parameters in get method. Here is my code
public void get()
{
HttpConnection con = null;
String url = "my url";
try
{
URLEncodedPostData data = new URLEncodedPostData("UTF-8", false);
data.append("method", "session.getToken");
data.append("phonenumber:=", "1212345687");
data.append("PIN:=", "1234");
url = url + data.toString();
con = (HttpConnection)Connector.open(url);
con.setRequestMethod(HttpConnection.GET);
res = con.getResponseMessage();
res1 = Integer.toString(con.getResponseCode());
screen.add(new RichTextField("Reponce Message: "+res));
screen.add(new RichTextField("Reponce Code: "+res1));
}
catch(Exception ex)
{
screen.add(new RichTextField(""+ex));
}
}
Depending on your server-side language, you can pass the json parameters by adding parameter as a string e.g
For passing parameters to a PHP server-side
String url = "http://www.test.com/test.php?";
url += "method=" + session.getToken;
url += "&phonenumber:=1212345687";
url += "&PIN:=1234";
For your response.. try this
public void get()
{
HttpConnection connection = null;
String results;
byte responseData[] = null;
try {
connection = (HttpConnection) new
ConnectionFactory().getConnection(URL).getConnection();
int len = (int) connection.getLength();
responseData = new byte[len];
DataInputStream dis;
dis = new DataInputStream(connection.openInputStream());
dis.readFully(responseData);
results = new String(responseData);
screen.add(new RichTextField("Reponce Message: "+results));
} catch (Exception e) {
// TODO Handle exception
screen.add(new RichTextField(""+e));
}
}

HTTP Get to Report Server 2008 works with DefaultCredentials, fails with some NetworkCredentials

The following WithDefaultCredentials() works but WithCredentialsMe() fails with a http 401 returned ?
The difference is that
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
works OK against the report server 2008 url , but
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
comes back with a HTTP 401.
The console app is being developed by me so, there should not be a difference between DefaultCredentials and NetworkCredential. There is no problem with my Username and password.
Any ideas ?
static void Main(string[] args)
{
WithDefaultCredentials();
WithCredentialsMe();
}
public static void WithDefaultCredentials()
{
try
{
ICredentials credentials = System.Net.CredentialCache.DefaultCredentials;
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_WithDefaultCredentitials.pdf", bytes.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static void WithCredentialsMe()
{
try
{
ICredentials credentials = new NetworkCredential("myUsername", "myPassword", "ourDomain");
string url = "http://myBox/ReportServer_SQLSERVER2008/Pages/ReportViewer.aspx?%2fElfInvoice%2fElfInvoice&rs:Command=Render&InvoiceID=115abba9-61bb-4070-bd28-f572115a2860&rs:format=PDF";
var bytes = GetByteListFromUrl(url, credentials);
File.WriteAllBytes(#"c:\temp\A_Credentials_me_1.pdf", bytes.ToArray());
}
catch( Exception ex )
{
Console.WriteLine( ex.Message);
}
}
public static List<Byte> GetByteListFromUrl(string url, System.Net.ICredentials credentials)
{
List<Byte> lstByte = new List<byte>();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (credentials != null)
{
request.Credentials = credentials;
}
var response = (HttpWebResponse)request.GetResponse();
var stream = response.GetResponseStream();
int totalBytesRead = 0;
int bufferbytesRead = 0;
try
{
byte[] buffer = new byte[1024];
while ((bufferbytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totalBytesRead += bufferbytesRead;
if (bufferbytesRead < buffer.Length)
{
bufferbytesRead = bufferbytesRead - 1 + 1;
}
for (int i = 0; i < bufferbytesRead; i++)
{
var bToAdd = buffer[i];
lstByte.Add(bToAdd);
}
}
}
catch (Exception ex)
{
}
finally{}
//-Return
return lstByte;
}
With the help of http://forums.asp.net/t/1217642.aspx this code got me what I wanted ...
Next step is clean it all up and unit test in dev ...
public static void ReportServerWebService()
{
// wsdl /out:rs.cs /namespace:ReportService2005 http://mybox/ReportServer_SQLSERVER2008/ReportService2005.asmx?wsdl
/// wsdl /out:rsExec.cs /namespace:ReportExecution2005 http://mybox/ReportServer_SQLSERVER2008/ReportExecution2005.asmx?wsdl
ICredentials credentials = new NetworkCredential("myUserName", "myPassword", "hcml");
Guid invoiceID = new Guid("115ABBA9-61BB-4070-BD28-F572115A2860");
var rs = new ReportService2005.ReportingService2005();
var rsExec = new ReportExecution2005.ReportExecutionService();
rs.Credentials = credentials;
rsExec.Credentials = credentials;
string historyID = null;
string deviceInfo = null;
string format = "PDF";
Byte[] bytPDF;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
ReportExecution2005.Warning[] warnings = null;
string[] streamIDs = null;
string _reportName = "/ElfInvoice/ElfInvoice" ;
string _historyID = null;
bool _forRendering = false;
ReportService2005.ParameterValue[] _values = null;
ReportService2005.DataSourceCredentials[] _credentials = null;
ReportService2005.ReportParameter[] _parameters = null;
try
{
// Get if any parameters needed.
_parameters = rs.GetReportParameters( _reportName, _historyID, _forRendering, _values, _credentials);
// Load the selected report.
var ei = rsExec.LoadReport(_reportName, historyID);
// Prepare report parameter.
// Set the parameters for the report needed.
var parameters = new ReportExecution2005.ParameterValue[1];
// // Place to include the parameter.
if (_parameters.Length > 0)
{
parameters[0] = new ReportExecution2005.ParameterValue();
parameters[0].Label = "InvoiceID";
parameters[0].Name = "InvoiceID";
parameters[0].Value = invoiceID.ToString();
}
rsExec.SetExecutionParameters(parameters, "en-us");
bytPDF = rsExec.Render( format , deviceInfo , out extension , out encoding , out mimeType , out warnings , out streamIDs ) ;
try
{
File.WriteAllBytes(#"c:\temp\A_WithMyCredentitials_ReportServerWebService.pdf", bytPDF.ToArray());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}