protected void Button1_Click(object sender, EventArgs e) { ReportExecutionService reportExecutionService = new ReportExecutionService(); // Web Service proxy reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107"); string reportPath = "/ReconCurrent/ReconInvest"; string format = "PDF"; // Render arguments byte[] result = null; string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ParameterValue[] parameters = new ParameterValue[4]; parameters[0] = new ParameterValue(); parameters[0].Name = "StartDate"; parameters[1] = new ParameterValue(); parameters[1].Name = "EndDate"; parameters[2] = new ParameterValue(); parameters[2].Name = "IsinCode"; parameters[3] = new ParameterValue(); parameters[3].Name = "AccountNumber"; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); reportExecutionService.ExecutionHeaderValue = execHeader; execInfo = reportExecutionService.LoadReport(reportPath, historyID); String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID; parameters[0].Value = DatePickerBegin.SelectedDate.ToShortDateString(); parameters[1].Value = DatePickerEnd.SelectedDate.ToShortDateString(); parameters[3].Value = ddlAccount.SelectedValue.ToString(); parameters[2].Value = ddlInstrument.SelectedValue.ToString(); reportExecutionService.SetExecutionParameters(parameters, "nl-nl"); result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); //Response.Flush(); //Response.Close(); }
public async Task <byte[]> RenderReport(string report, ParameterValue[] parameters, string exportFormat = "PDF") { var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; binding.MaxReceivedMessageSize = 100485760; var rsExec = new ReportExecutionServiceSoapClient(binding, new EndpointAddress(url)); var clientCredentials = new NetworkCredential(userName, password); rsExec.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials; TrustedUserHeader trustedUserHeader = new TrustedUserHeader(); LoadReportResponse taskLoadReport = null; string historyID = null; taskLoadReport = await rsExec.LoadReportAsync(trustedUserHeader, report, historyID); ExecutionHeader executionHeader = new ExecutionHeader { ExecutionID = taskLoadReport.executionInfo.ExecutionID }; await rsExec.SetExecutionParametersAsync(executionHeader, trustedUserHeader, parameters, null); const string deviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"; RenderResponse response = await rsExec.RenderAsync(new RenderRequest(executionHeader, trustedUserHeader, exportFormat ?? "PDF", deviceInfo)); return(response.Result); }
/// <summary /> public void BeforeSendReply(ref Message reply, object correlationState) { if (reply == null) { return; } var ctx = (WcfExecutionContext)correlationState; /* * Always append the ExecutionHeader to the response. */ ExecutionHeader content = new ExecutionHeader(); content.ExecutionId = ctx.ExecutionId; content.MomentStart = ctx.MomentStart; content.MomentEnd = DateTime.UtcNow; WcfExecutionHeader header = new WcfExecutionHeader(); header.Content = content; reply.Headers.Add(header); }
/// <summary> /// Gerar arquivo binário conforme formato e caminho do relatório especificado e seus parâmetros /// </summary> /// <param name="formato"></param> /// <param name="caminho"></param> /// <param name="parametros"></param> /// <returns></returns> public byte[] RelatorioBinarioRS(string formato, string caminho, List <ParametroRelatorio> parametros) { var rs = new ReportExecutionService { Credentials = CredentialCache.DefaultNetworkCredentials, Url = GerenciadorConfiguracao.ServidorDeRelatorio }; string PastaDoRelatorio = GerenciadorConfiguracao.PastaDoRelatorio; byte[] result = null; string reportPath = PastaDoRelatorio + caminho; string format = formato; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var executionParams = new List <ParameterValue>(); foreach (var parametro in parametros) { executionParams.Add(new ParameterValue { Name = parametro.IdParametro, Value = parametro.Valor != null ? parametro.Valor.ToString() : null }); } string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; var execInfo = new ExecutionInfo(); var execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(executionParams.ToArray(), "pt-BR"); 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 ex) { throw new Exception($"Não foi possível gerar o relatório erro do servidor : {ex.RecuperarMsgExcecaoAninhada()}"); } return(result); }
public SSRSReportGenerator(IReportingConfiguration reportingConfiguration, IFileWriter fileWriter) { this.trusteduserHeader = new RE2005.TrustedUserHeader(); this.execHeader = new ExecutionHeader(); this.serviceInfo = new RE2005.ServerInfoHeader(); this.execInfo = new ExecutionInfo(); this.fileWriter = fileWriter; this.reportService2010Reference = new EndpointAddress(reportingConfiguration.ReportService2010Reference); this.reportExecution2005Reference = new EndpointAddress(reportingConfiguration.ReportExecution2005Reference); }
public void SetUp() { Mocks = new MockRepository(MockBehavior.Strict); ClientFactory = Mocks.Create <IReportingServicesClientFactory>(); ExecutionClient = Mocks.Create <IReportExecutionSoapClient>(); Storage = Mocks.Create <IBlobStorage>(); Context = Mocks.Create <ConsumeContext <ExecuteReportRequest> >(); Consumer = new ExecuteReportConsumer(ClientFactory.Object, Storage.Object); ExecutionHeader = new ExecutionHeader(); }
public void ProcessRequest(HttpContext context) { ReportExecutionService rs = new ReportExecutionService(); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); string historyId = null, encoding = ""; string reportPath = "/wismusta/DistrictAuditionStatistics"; //string extension = "PDF"; //string mimeType = "pdf"; string extension = ""; string mimeType = ""; string devInfo = "False"; Warning[] warning = null; string[] streamId = null; byte[] result = null; rs.Url = "http://sunflower.arvixe.com/ReportServer_SQL_Service/ReportExecution2005.asmx?wsdl"; //add credentials rs.Credentials = new NetworkCredential("wismusta_reportservr", "33wi8mu8ta44", "sunflower.arvixe.com"); //add parameters ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = "auditionOrgId"; parameters[0].Value = "1036"; rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyId); rs.SetExecutionParameters(parameters, "en-us"); result = rs.Render("PDF", devInfo, out extension, out mimeType, out encoding, out warning, out streamId); HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.AppendHeader("content-length", result.Length.ToString()); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.BinaryWrite(result); HttpContext.Current.Response.End(); HttpContext.Current.Response.Flush(); //HttpContext.Current.Response.ClearContent(); //HttpContext.Current.Response.AddHeader("Pragma", "public"); //HttpContext.Current.Response.AddHeader("Content-Description", "File Transfer"); //HttpContext.Current.Response.AddHeader("X-Download-Options", "noopen"); //HttpContext.Current.Response.AddHeader("X-Content-Type-Options", "nosniff"); //HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary"); //HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=Student_History_Rpt.pdf"); //HttpContext.Current.Response.AppendHeader("content-length", result.Length.ToString()); //HttpContext.Current.Response.ContentType("application/excel"); //HttpContext.Current.Response.BinaryWrite(result); //HttpContext.Current.Response.End(); //HttpContext.Current.Response.Flush(); }
public static bool ReportExists(string reportPath, string ssrsUrl) { var rs = new ReportExecutionService(); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; rs.Url = ssrsUrl; byte[] result = null; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; string format = "XML"; ParameterValue[] parameters = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; try { execInfo = rs.LoadReport(reportPath, historyID); } catch (SoapException e) { if (e.Detail.OuterXml.Contains("rsItemNotFound")) { Console.WriteLine("Report: {0} not found", reportPath); } else { Console.WriteLine(e.Detail.OuterXml); } return(false); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } return(true); }
/// <summary> /// Executes report and returns file /// </summary> /// <param name="path">Path to report</param> /// <param name="format">Format</param> /// <param name="parameters">List of parameters</param> /// <returns>Array of bytes</returns> public byte[] ExportReport(string path, string format, List <SsrsParameter> parameters) { string reportPath = path; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>Full</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.Warning[] warnings = null; string[] streamIDs = null; ReportExecutionService res = new ReportExecutionService(); res.Url = ConfigurationManager.AppSettings["ReportingServiceExecutionUrl"]; res.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["ReportingServiceLogin"], ConfigurationManager.AppSettings["ReportingServicePassword"], ConfigurationManager.AppSettings["ReportingServiceDomain"]); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); res.ExecutionHeaderValue = execHeader; execInfo = res.LoadReport(reportPath, historyID); if (parameters.Count > 0) { ParameterValue[] plist = new ParameterValue[parameters.Count]; for (var i = 0; i < parameters.Count; i++) { plist[i] = new ParameterValue { Name = parameters[i].Name, Value = parameters[i].Value }; i++; } res.SetExecutionParameters(plist, "en-us"); } return(res.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs)); }
protected void Page_Load(object sender, EventArgs e) { ReportExecutionService rs = new ReportExecutionService(); //set parameters and report settings string reportPath = "/StudentHistory"; rs.Url = "http://sunflower.arvixe.com/ReportServer_SQL_Service/ReportExecution2005.asmx?wsdl"; DataSourceCredentials credentials = new DataSourceCredentials(); credentials.DataSourceName = "sunflower.arvixe.com"; credentials.UserName = "******"; credentials.Password = "******"; rs.SetExecutionCredentials(new DataSourceCredentials[] { credentials }); ExecutionInfo info = new ExecutionInfo(); ExecutionHeader header = new ExecutionHeader(); string historyId = "", extension = "", mimeType = "", encoding = "", devInfo = "False"; string[] streamId; Warning[] warning; byte[] result; ParameterValue param = new ParameterValue(); param.Name = "@auditionOrgId"; param.Value = "1036"; rs.ExecutionHeaderValue = header; info = rs.LoadReport(reportPath, historyId); rs.SetExecutionParameters(new ParameterValue[] { param }, "en-us"); result = rs.Render("PDF", devInfo, out extension, out mimeType, out encoding, out warning, out streamId); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); Response.Flush(); }
public byte[] GetReportFromRS(ReportCallContext reportContext, out string mimeType, out string extension) { reportContext.ReportName = "/eSoda/" + reportContext.ReportName; ReportExecutionService ws = new ReportingServices.ReportExecutionService(); Warning[] warnings; string[] sids; string encoding; ws.Credentials = System.Net.CredentialCache.DefaultCredentials; ws.Timeout = 1000 * 600; //parameters[0] = new ParameterValue(); //parameters[0].Name = "params"; //parameters[0].Value = reportContext.ReportParameters.ToString(SaveOptions.DisableFormatting); ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); ws.ExecutionHeaderValue = execHeader; byte[] reportContent = null; try { execInfo = ws.LoadReport(reportContext.ReportName, null); ws.SetExecutionParameters(reportContext.Parameters, "pl-PL"); string sessionID = ws.ExecutionHeaderValue.ExecutionID; reportContent = ws.Render(reportContext.ReportFormat, null, out extension, out mimeType, out encoding, out warnings, out sids); } catch (Exception ex) { mimeType = null; extension = null; System.Diagnostics.Trace.WriteLine(ex.Message); throw; } return(reportContent); }
protected void Button1_Click(object sender, EventArgs e) { ReportExecutionService reportExecutionService = new ReportExecutionService(); // Web Service proxy reportExecutionService.Credentials = new NetworkCredential("reportservice", "Asdfghjkl?", "kswh107"); string reportPath = "/ReconCurrent/ReconCurrent"; string format = "PDF"; // Render arguments byte[] result = null; string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); reportExecutionService.ExecutionHeaderValue = execHeader; execInfo = reportExecutionService.LoadReport(reportPath, historyID); String SessionId = reportExecutionService.ExecutionHeaderValue.ExecutionID; result = reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.ClearContent(); Response.AppendHeader("content-length", result.Length.ToString()); Response.ContentType = "application/pdf"; Response.BinaryWrite(result); Response.End(); //Response.Flush(); //Response.Close(); }
public FileContentResult Index() { Dictionary <string, string> reportParameters = new Dictionary <string, string>(); Request.QueryString.AllKeys.Where(x => !x.Equals("ReportName")).ForEach(x => reportParameters.Add(x, Request.QueryString[x])); byte[] byteResult = new byte[0]; string extension, mimeType, encoding; Warning[] warnings = new Warning[0]; string[] streamIds = new string[0]; ServerInfoHeader serverInfoHeader; ExecutionInfo2 execInfo = new ExecutionInfo2(); ReportExecutionServiceSoapClient rsServiceClient = new ReportExecutionServiceSoapClient(); rsServiceClient.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; ExecutionHeader execHeader = rsServiceClient.LoadReport2(null, "/Axis.ReportDB/" + Request.QueryString["ReportName"], null, out serverInfoHeader, out execInfo); rsServiceClient.SetExecutionParameters2(execHeader, null, reportParameters.Select(x => new ParameterValue { Name = x.Key, Value = x.Value }).ToArray(), "en-us", out execInfo); string sessionId = execInfo.ExecutionID; try { serverInfoHeader = rsServiceClient.Render2(execHeader, null, "PDF", @"<DeviceInfo><Toolbar>True</Toolbar></DeviceInfo>", PageCountMode.Actual, out byteResult, out extension, out mimeType, out encoding, out warnings, out streamIds); } catch (Exception) { throw; } return(new FileContentResult(byteResult, "application/pdf")); }
static void Main(string[] args) { var rs = new ReportExecutionService(); //rs.Url = "http://air:80/SunOpps_ReportServer_Inst4/ReportExecution2005.asmx"; //rs.Url = "http://ore-sql-report.cloudapp.net:801/ReportServer/ReportExecution2005.asmx"; rs.Url = "http://ore-report-test.cloudapp.net:801/ReportServer/ReportExecution2005.asmx"; bool useDefaultCredentials = false; if (!useDefaultCredentials) { string sDomain = "ore-sql-report"; string sUserName = "******"; string sPassword = "******"; rs.Credentials = new NetworkCredential(sUserName, sPassword, sDomain); } else { rs.Credentials = System.Net.CredentialCache.DefaultCredentials; } const string sFormat = "PDF"; string sExtension; string sEncoding; string sMimeType; Warning[] oWarnings; string[] sStreamIDs; ExecutionHeader oExecutionHeader = new ExecutionHeader(); //int proposalID = 171871; //int proposalID = 171873; //int proposalID = 186277; int proposalID = 159796; //string sReportPath = "/SolarAgreements"; //string sReportPath = "/SunOpps/Prod/"; //string sReportPath = "/SunOpps/SE-Default-Dev"; //string sReportPath = "/SunOpps/SE-Default/OneRoofEnergyProposals"; string sReportPath = "/SunOpps/SE-Default/SolarAgreements"; string sReportFilename = "PPA"; ParameterValue[] oParameters = new ParameterValue[1]; oParameters[0] = new ParameterValue { Name = "ProposalID", Value = proposalID.ToString(CultureInfo.InvariantCulture) }; rs.ExecutionHeaderValue = oExecutionHeader; byte[] result = null; try { rs.LoadReport(string.Format("{0}/{1}", sReportPath, sReportFilename), null); rs.SetExecutionParameters(oParameters, "en-us"); result = rs.Render(sFormat, null, out sExtension, out sMimeType, out sEncoding, out oWarnings, out sStreamIDs); } catch (Exception e) { Console.WriteLine(e.Message); } if (result != null) { string currentDirectory = System.Reflection.Assembly.GetExecutingAssembly().Location; if (currentDirectory.IndexOf("bin") != -1) { currentDirectory = currentDirectory.Substring(0, currentDirectory.LastIndexOf("bin", currentDirectory.Length - 1)); } string outputFileName = Path.Combine(currentDirectory, string.Format("{0}_{1}.{2}", sReportFilename, proposalID, sFormat.ToLower())); if (File.Exists(outputFileName)) { File.Delete(outputFileName); } File.WriteAllBytes(outputFileName, result); } }
public void ProcessRequest(HttpContext context) { byte[] result; string encoding; string mimeType; string extension; string[] streamIDs = null; Warning[] warnings = null; var uId = 0; if (context.Request.QueryString["uId"] != null) { uId = int.Parse(context.Request.QueryString["uId"]); } var rs = new ReportExecutionService { Url = ConfigurationManager.AppSettings["URI_report_srv"], Credentials = CredentialCache.DefaultCredentials }; var parameters = new ParameterValue[1]; if (uId != 0) { parameters[0] = new ParameterValue { Name = "КодСотрудника", Value = uId.ToString() }; } try { var devInfo = string.Format( @"<DeviceInfo><DpiX>300</DpiX><DpiY>300</DpiY><ColorDepth>32</ColorDepth><OutputFormat>PDF</OutputFormat><StreamRoot>" + Config.styles + "</StreamRoot></DeviceInfo>"); var execInfo = new ExecutionInfo(); var execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport("/INVENTORY/карточка", null); rs.SetExecutionParameters(parameters, "en-us"); try { result = rs.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); } catch (Exception ex) { Logger.WriteEx(ex); throw ex; } context.Response.Clear(); context.Response.Buffer = true; context.Response.AddHeader("Content-Disposition", "inline; filename=Report_" + uId + ".pdf"); context.Response.ContentType = "application/octet-stream"; context.Response.BinaryWrite(result); context.Response.Flush(); } catch (Exception e) { context.Response.Write(e.Message); } }
/// <summary> /// This first version of RenderReport is strictly for legacy support of NIFTransferShipment. NIFTransferShipment should be re-worked to use the rendorReport /// version that accepts an array of ParameterValues. /// </summary> /// <param name="reportPath"></param> /// <param name="identifier"></param> /// <returns></returns> public byte[][] renderReport(string reportPath, ParameterValue[] reportParameters) { // Private variables for rendering string historyID = null; ExecutionHeader execHeader = new ExecutionHeader(); try { rs.Timeout = 300000; rs.ExecutionHeaderValue = execHeader; ExecutionInfo execInfo = new ExecutionInfo(); execInfo = rs.LoadReport(reportPath, historyID); if (reportParameters != null) { rs.SetExecutionParameters(reportParameters, "en-us"); } Byte[][] pages = new Byte[0][]; string format = "IMAGE"; int numberOfPages = 1; byte[] currentPageStream = new byte[1] { 0x00 }; // this single byte will prime the while loop string extension = null; string encoding = null; string mimeType = null; string[] streamIDs = null; Warning[] warnings = null; while (currentPageStream.Length > 0) { string deviceInfo = String.Format(@"<DeviceInfo><OutputFormat>EMF</OutputFormat><PrintDpiX>96</PrintDpiX><PrintDpiY>96</PrintDpiY><StartPage>{0}</StartPage></DeviceInfo>", numberOfPages); //Execute the report and get page count. currentPageStream = rs.Render( format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); if (currentPageStream.Length == 0 && numberOfPages == 1) { break; // nothing rendered } if (currentPageStream.Length > 0) { Array.Resize(ref pages, pages.Length + 1); pages[pages.Length - 1] = currentPageStream; numberOfPages++; } } m_numberOfPages = numberOfPages - 1; return pages; } catch (SoapException ex) { eventLog.WriteEntry(ex.Detail.InnerXml, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Detail.InnerXml); } catch (Exception ex) { eventLog.WriteEntry(ex.Message, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Message); } finally { } return null; }
public async Task <byte[]> RenderReport(string reportPath, IDictionary <string, string> parameters, ExportFormat exportFormat, string fileName) { byte[] fileContent = null; try { //My binding setup, since ASP.NET Core apps don't use a web.config file var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm; binding.MaxReceivedMessageSize = 10485760; //I wanted a 10MB size limit on response to allow for larger PDFs string _reportingServicesUrl = _config["WCFExternalServices:ReportingService:EndpointAddress"]; //Create the execution service SOAP Client var rsExec = new ReportExecutionServiceSoapClient(binding, new EndpointAddress(_reportingServicesUrl)); //Setup access credentials. I use windows credentials, yours may differ var clientCredentials = new NetworkCredential(); //rsExec.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials; //This handles the problem of "Missing session identifier" rsExec.Endpoint.EndpointBehaviors.Add(new ReportingServicesEndpointBehavior()); string historyID = null; TrustedUserHeader trustedUserHeader = new TrustedUserHeader(); ExecutionHeader execHeader = new ExecutionHeader(); trustedUserHeader.UserName = clientCredentials.UserName; //Load the report var taskLoadReport = await rsExec.LoadReportAsync(trustedUserHeader, reportPath, historyID); // Fixed the exception of "session identifier is missing". execHeader.ExecutionID = taskLoadReport.executionInfo.ExecutionID; // //Set the parameteres asked for by the report // string lang = ""; if (fileName == "LoanStatement" || fileName == "Payment_order" || fileName == "CreditLineStatement") { if (Convert.ToInt32(parameters["lang_id"]) == 1) { lang = "hy-am"; } else { lang = "en-us"; } } else { lang = "en-us"; } ParameterValue[] reportParameters = null; if (parameters != null && parameters.Count > 0) { reportParameters = taskLoadReport.executionInfo.Parameters.Where(x => parameters.ContainsKey(x.Name)).Select(x => new ParameterValue() { Name = x.Name, Value = parameters[x.Name] != null ? parameters[x.Name].ToString() : null }).ToArray(); } await rsExec.SetExecutionParametersAsync(execHeader, trustedUserHeader, reportParameters, lang); //run the report string format = GetExportFormatString(exportFormat); // run the report const string deviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var response = await rsExec.RenderAsync(new RenderRequest(execHeader, trustedUserHeader, format, deviceInfo)); //spit out the result return(response.Result); } catch (Exception ex) { // System.Web.HttpContext.Current.Response.BufferOutput = true; // System.Web.HttpContext.Current.Response.TrySkipIisCustomErrors = true; // System.Web.HttpContext.Current.Response.StatusCode = 422; // System.Web.HttpContext.Current.Response.StatusDescription = Utils.ConvertAnsiToUnicode(ex.Message); throw ex; } return(fileContent); }
protected override void Execute(CodeActivityContext executionContext) { var tracingService = executionContext.GetExtension <ITracingService>(); var context = executionContext.GetExtension <IWorkflowContext>(); var serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>(); var service = serviceFactory.CreateOrganizationService(context.UserId); try { Guid RecordId = context.PrimaryEntityId; string _rpName = RptName.Get <string>(executionContext); string _appNum = AppNum.Get <string>(executionContext); byte[] result = null; ReportExecutionService rs = new ReportExecutionService(); rs.Credentials = new NetworkCredential("<Username>", "<Password>", "<Domain>"); rs.Url = "<Org_URL>/ReportExecution2005.asmx"; tracingService.Trace(context.OrganizationName); string reportPath = "/" + context.OrganizationName + "_MSCRM/" + _rpName; string format = "PDF"; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; ParameterValue[] parameters = new ParameterValue[1]; parameters[0] = new ParameterValue(); parameters[0].Name = "id"; parameters[0].Value = RecordId.ToString(); tracingService.Trace("Id passed: " + RecordId.ToString()); 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; result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); Response.Rootobject response = this.GetStamp(Convert.ToBase64String(result), Convert.ToInt32(result.Length.ToString()), _appNum, "<Token>", "<BlockChain_URL>"); string StamppedFile = response.UploadZipHash; //Create email activity Entity attachment = new Entity("activitymimeattachment"); attachment["objectid"] = Email.Get <EntityReference>(executionContext); attachment["objecttypecode"] = "email"; attachment["filename"] = "الشهادة.pdf"; attachment["subject"] = "لمن يهمه الأمر"; attachment["body"] = System.Convert.ToBase64String(response.StampContent); try { service.Create(attachment); } catch (Exception ex) { throw new Exception(string.Format("Error creating attachment - {0}", ex.Message)); } try { service.Execute(new SendEmailRequest() { EmailId = Email.Get <EntityReference>(executionContext).Id, IssueSend = true, TrackingToken = string.Empty }); } catch (Exception ex) { throw new Exception(string.Format("Error sending email - {0}", ex.Message)); } } catch (Exception err) { throw new Exception("Exception" + err); } }
public string RunReport(string path, string reportCode, Dictionary <string, string> dicParams) { var format = ""; var result = ""; try { DataSourceCredentials[] credentials = null; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; string historyID = null; byte[] reportResult = null; var devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var rs = new ReportExecutionServiceSoapClient(GetDefaultBinding(), new EndpointAddress(@"http://localhost:8282/ReportServer/ReportExecution2005.asmx")); rs.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation; rs.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials; rs.ClientCredentials.UserName.UserName = "******"; rs.ClientCredentials.UserName.Password = "******"; // Render arguments var execInfo = new ExecutionInfo(); var execHeader = new ExecutionHeader(); var trustedHeader = new TrustedUserHeader(); var serverInfo = new ServerInfoHeader(); var path2 = "/" + path + "/" + reportCode; rs.LoadReport(trustedHeader, path2, historyID, out serverInfo, out execInfo); // Genera los parametros apartir de un diccionario var parameters = new ParameterValue[dicParams.Count]; var index = 0; foreach (var param in dicParams) { var paramValue = new ParameterValue { Name = param.Key, Value = param.Value }; parameters[index] = paramValue; index++; } execHeader.ExecutionID = execInfo.ExecutionID; rs.SetExecutionParameters(execHeader, trustedHeader, parameters, "en-us", out execInfo); //Invocacion del reporte format = "PDF"; rs.Render(execHeader, trustedHeader, format, devInfo, out reportResult, out extension, out mimeType, out encoding, out warnings, out streamIDs); result = Convert.ToBase64String(reportResult); } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// Renders content via SOAP /// </summary> /// <returns></returns> private byte[] GetContent(out string mimeType) { //ReportingService2005 rs; ReportExecutionService rsExec; byte[] content; //In argements string deviceInfo; ReportExecution20051.ParameterValue[] parameterValues; //ReportExecutionService2005.ReportParameter[] _parameters = null; //string _report = null; string _historyID = null; //bool _forRendering = false; //ReportExecutionService2005.ParameterValue[] _values = null; //ReportExecutionService2005.DataSourceCredentials[] _credentials = null; //Out arguments string encoding; //1. Get input arguments // Set html device information deviceInfo = ""; //Get report parameters parameterValues = this.ReportParameters; //2. Get reporting web service //rs = Util.GetReportingService(this.SessionID); rsExec = Util.GetReportExecutionService(this.SessionID); //3. Call render web service //content = rsExec.RenderStream(this.Settings.ReportFolder + this.ReportPath, this.Format,this.StreamID, null, deviceInfo, parameterValues, out encoding, out mimeType); // Get if any parameters needed. //_parameters = rs.GetReportParameters(this.Settings.ReportFolder + this.ReportPath, _historyID, _forRendering, _values, _credentials); // Load the selected report. ExecutionHeader EH = new ExecutionHeader(); EH.ExecutionID = this.SessionID; rsExec.ExecutionHeaderValue = EH; // rsExec.LoadReport(this.Settings.ReportFolder + this.ReportPath, _historyID); // Prepare report parameter. // Set the parameters for the report needed. //ReportExecutionService2005.ParameterValue[] parameters = // new ReportExecutionService2005.ParameterValue[1]; //rsExec.SetExecutionParameters(this.ReportParameters, "en-us"); //content = rsExec.Render(this.Format, deviceInfo, out extension, out mimeType, out encoding, out warnings, out streamIDs); content = rsExec.RenderStream(this.Format, this.StreamID, deviceInfo, out encoding, out mimeType); // Create a file stream and write the report to it //using (FileStream stream = File.OpenWrite("c:\\BinStream")) //{ // stream.Write(content, 0, content.Length); // stream.Close(); //} //4. Session Validation if (this.Settings.SessionValidation) { if (rsExec.ExecutionHeaderValue.ExecutionID != this.SessionID) { throw new ApplicationException("Session timeout"); } } return(content); }
public object ReporteFormatoEtiquetasOrdenRecepcion(int ordenRecepcionID, Sam3_Usuario usuario) { try { #region parametros byte[] reporte; string historyID = null; string deviceInfo = null; string extension; string encoding; string mimeType; Warning[] warnings; string[] streamIDs = null; string format = "PDF"; string rutaReporte = "/Reportes/Formato de Etiquetas"; NetworkCredential credenciales = new NetworkCredential(usuarioReportes, passReportes); #endregion ReportExecutionServiceSoapClient cliente = new ReportExecutionServiceSoapClient(); cliente.ClientCredentials.Windows.ClientCredential = credenciales; cliente.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation; cliente.ClientCredentials.UserName.UserName = usuarioReportes; cliente.ClientCredentials.UserName.Password = passReportes; ParameterValue[] parametros = new ParameterValue[1]; parametros[0] = new ParameterValue(); parametros[0].Name = "OrdenRecepcionID"; parametros[0].Value = ordenRecepcionID.ToString(); ExecutionInfo infoEjecucion = new ExecutionInfo(); TrustedUserHeader encabezadoSeguro = null; ExecutionHeader encabezadoDeEjecucion = new ExecutionHeader(); ServerInfoHeader encavezadoDeServidor = new ServerInfoHeader(); encabezadoDeEjecucion = cliente.LoadReport(encabezadoSeguro, rutaReporte, historyID, out encavezadoDeServidor, out infoEjecucion); cliente.SetExecutionParameters(encabezadoDeEjecucion, encabezadoSeguro, parametros, "en-US", out infoEjecucion); cliente.Render(encabezadoDeEjecucion, encabezadoSeguro, format, deviceInfo, out reporte, out extension, out mimeType, out encoding, out warnings, out streamIDs); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); Stream iStream = new MemoryStream(reporte); response.Content = new StreamContent(iStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = "EtiquetasMaterial_" + ordenRecepcionID.ToString() + ".pdf"; return(response); } catch (Exception ex) { //-----------------Agregar mensaje al Log ----------------------------------------------- LoggerBd.Instance.EscribirLog(ex); //-----------------Agregar mensaje al Log ----------------------------------------------- TransactionalInformation result = new TransactionalInformation(); result.ReturnMessage.Add("Error al cargar el reporte"); result.ReturnCode = 500; result.ReturnStatus = false; result.IsAuthenicated = true; return(result); } }
private static SoapResponse ToFault(SoapVersion version, ExecutionHeader execution, ActorException exception) { #region Validations if (execution == null) { throw new ArgumentNullException(nameof(execution)); } if (exception == null) { throw new ArgumentNullException(nameof(exception)); } #endregion /* * */ XNamespace fwkNs = "https://github.com/filipetoscano/Zinc"; XNamespace soapNs; if (version == SoapVersion.Soap11) { soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; } else { soapNs = "http://www.w3.org/2003/05/soap-envelope"; } XDocument responseDoc = new XDocument(); var envelope = new XElement(soapNs + "Envelope"); envelope.Add(new XAttribute(XNamespace.Xmlns + "soap", soapNs.NamespaceName)); var header = new XElement(soapNs + "Header"); var body = new XElement(soapNs + "Body"); var fault = new XElement(soapNs + "Fault"); body.Add(fault); envelope.Add(header, body); responseDoc.Add(envelope); /* * Header */ execution.MomentEnd = DateTime.UtcNow; XmlSerializer serHeader = new XmlSerializer(typeof(ExecutionHeader)); header.Add(serHeader.SerializeAsXElement(execution)); /* * Fault */ if (version == SoapVersion.Soap11) { // TODO: recurse through exception stack XElement x = new XElement(fwkNs + "ActorFault", new XElement(fwkNs + "Actor", new XText(exception.Actor)), new XElement(fwkNs + "Code", new XText(exception.Code.ToString(CultureInfo.InvariantCulture))), new XElement(fwkNs + "Message", new XText(exception.Description)), new XElement(fwkNs + "ExceptionType", new XText(exception.GetType().FullName)) ); if (exception.StackTrace != null) { x.Add(new XElement(fwkNs + "StackTrace", new XText(exception.StackTrace))); } fault.Add( new XElement("faultcode", new XText(exception.Actor.EndsWith("Client", StringComparison.Ordinal) == true ? "soap:Client" : "soap:Server")), new XElement("faultstring", new XText(exception.Description)), new XElement("detail", x) ); } else { // TODO: implemented throw new NotImplementedException(); } /* * */ SoapResponse response = new SoapResponse(); response.Version = version; response.IsFault = true; response.Message = responseDoc.ToString(SaveOptions.DisableFormatting); return(response); }
public byte[] RenderReport(string url, string reportPath, ReportParameter[] parameters, string formatType, bool humanReadablePdf, IDTSComponentEvents componentEvents) { bool refire = false; byte[] retVal; componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Create the instance of the WS - " + string.Format("{0}ReportExecution2005.asmx", (url.Substring(url.Length - 1, 1) == "/") ? url : url + "/"), string.Empty, 0, ref refire); using (var rs = new ReportExecutionService { Credentials = CredentialCache.DefaultCredentials, Url = string.Format("{0}ReportExecution2005.asmx", (url.Substring(url.Length - 1, 1) == "/") ? url : url + "/") }) { const string historyID = null; string encoding; string mimeType; string extension; Warning[] warnings; string[] streamIDs; var execHeader = new ExecutionHeader(); componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Load the report from " + reportPath, string.Empty, 0, ref refire); var execInfo = rs.LoadReport(reportPath, historyID); componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Set parameters", string.Empty, 0, ref refire); rs.SetExecutionParameters(parameters.Select(p => new ParameterValue { Label = p.Name, Name = p.Name, Value = p.Value }).ToArray(), "en-EN"); rs.ExecutionHeaderValue = execHeader; rs.ExecutionHeaderValue.ExecutionID = execInfo.ExecutionID; componentEvents.FireInformation(0, "SSISReportGeneratorTask", "Render the report", string.Empty, 0, ref refire); retVal = rs.Render(formatType, (humanReadablePdf) ? DeviceSettings : null, out extension, out encoding, out mimeType, out warnings, out streamIDs); } return(retVal); }
public static bool RenderReport(string reportPath, string ssrsUrl) { var rs = new ReportExecutionService(); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; rs.Url = ssrsUrl; byte[] result = null; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; string format = "XML"; ParameterValue[] parameters = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; try { execInfo = rs.LoadReport(reportPath, historyID); } catch (SoapException e) { if (e.Detail.OuterXml.Contains("rsItemNotFound")) { Console.WriteLine("Report: {0} not found", reportPath); } else { Console.WriteLine(e.Detail.OuterXml); } return(false); } catch (Exception e) { Console.WriteLine(e.Message); return(false); } //check if this report requires parms if (execInfo.ParametersRequired) { //if it does, then iterate parms and create set of input parms with appropriate values parameters = new ParameterValue[execInfo.Parameters.Length]; for (int i = 0; i < execInfo.Parameters.Length; i++) { if (execInfo.Parameters[i].PromptUser) { parameters[i] = new ParameterValue(); parameters[i].Name = execInfo.Parameters[i].Name; if (execInfo.Parameters[i].ValidValues != null && execInfo.Parameters[i].ValidValues.Length > 0) { for (int x = 0; x < execInfo.Parameters[i].ValidValues.Length; x++) { //problem setting parm value to null from valid values //iterate till we get a non-null value if (!string.IsNullOrEmpty(execInfo.Parameters[i].ValidValues[x].Value)) { parameters[i].Value = execInfo.Parameters[i].ValidValues[x].Value; } } Console.WriteLine("Setting {0} to {1}", parameters[i].Name, parameters[i].Value); } else { switch (execInfo.Parameters[i].Type) { case ParameterTypeEnum.DateTime: parameters[i].Value = DateTime.Now.ToLongDateString(); break; case ParameterTypeEnum.Boolean: parameters[i].Value = "true"; break; case ParameterTypeEnum.Float: parameters[i].Value = "1000.00"; break; case ParameterTypeEnum.Integer: parameters[i].Value = "10"; break; case ParameterTypeEnum.String: parameters[i].Value = "AAA"; break; default: break; } } Console.WriteLine("---- Parameter: {0}, Value: {1}", parameters[i].Name, parameters[i].Value.ToString()); } } } else { parameters = new ParameterValue[0]; } rs.SetExecutionParameters(parameters, "en-us"); String SessionId = rs.ExecutionHeaderValue.ExecutionID; try { rs.Timeout = 300000; result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime); } catch (SoapException e) { Console.WriteLine(e.Detail.OuterXml); return(false); } return(true); }
public void ProcessRequest(HttpContext context) { #region Validations if (context == null) { throw new ArgumentNullException("context"); } #endregion /* * */ ExecutionHeader execution = new ExecutionHeader(); execution.ExecutionId = Guid.NewGuid(); execution.MomentStart = DateTime.UtcNow; /* * */ SoapRequest request = null; if (context.Request.Headers["SOAPAction"] != null) { request = new SoapRequest(); request.Version = SoapVersion.Soap11; request.SoapAction = context.Request.Headers["SOAPAction"]; request.SoapAction = request.SoapAction.Substring(1, request.SoapAction.Length - 2); } else { var values = context.Request.ContentType .Split(';') .Select(s => { var p = s.Split(new char[] { '=' }, 2); if (p.Length == 1) { return new { Key = "content-type", Value = p[0] } } ; else { return new { Key = p[0], Value = p[1] } }; }).ToList(); var contentType = values.FirstOrDefault(x => x.Key == "content-type"); var action = values.FirstOrDefault(x => x.Key == "action"); if (contentType?.Value == "application/soap+xml" && action != null) { request = new SoapRequest(); request.Version = SoapVersion.Soap12; request.SoapAction = action.Value.Substring(1, action.Value.Length - 2); } } if (request == null) { ActorException error = new WebException(ER.Soap_RequestNotSoap); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } /* * Derive the rule being invoked, based on the URL of the request. */ if (request.SoapAction.StartsWith(WebServicesConfiguration.Current.Namespace) == false) { ActorException error = new WebException(ER.Soap_ActionUnsupported, request.SoapAction, WebServicesConfiguration.Current.Namespace); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } string ruleName = request.SoapAction.Substring(WebServicesConfiguration.Current.Namespace.Length).Replace("/", "."); /* * */ using (var sr = new StreamReader(HttpContext.Current.Request.InputStream)) { sr.BaseStream.Seek(0, SeekOrigin.Begin); request.Message = sr.ReadToEnd(); } /* * Service NS - derived from the name of the rule :) */ string[] parts = ruleName.Split('.'); string serviceNs = string.Join("/", parts.Take(parts.Length - 2)) + "/"; /* * */ RuleRunner rr = new RuleRunner(); IRule rule = rr.Get(ruleName); if (rule == null) { ActorException error = new WebException(ER.Soap_ActionUnknown, request.SoapAction); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } /* * */ XNamespace soapNs; if (request.Version == SoapVersion.Soap11) { soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; } else { soapNs = "http://www.w3.org/2003/05/soap-envelope"; } XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable()); manager.AddNamespace("soap", soapNs.NamespaceName); /* * */ XDocument requestDoc; try { using (StringReader sr = new StringReader(request.Message)) { requestDoc = XDocument.Load(sr); } } catch (XmlException ex) { ActorException error = new WebException(ER.Soap_RequestNotXml, ex); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } XElement element = requestDoc.XPathSelectElement(" /soap:Envelope/soap:Body/*[ 1 ] ", manager); if (element == null) { ActorException error = new WebException(ER.Soap_BodyNotFound); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } /* * */ object oreq; XmlSerializer der = XmlSerializerFor(rule.RequestType, serviceNs); try { oreq = der.Deserialize(element.CreateReader()); } catch (InvalidOperationException ex) { ActorException error = new WebException(ER.Soap_RequestInvalid, ex, rule.Name, rule.RequestType.FullName); var fault = ToFault(request.Version, execution, error); ResponseEmit(context, fault); return; } /* * */ SoapResponse response; try { object oresp; oresp = rr.Run(rule, oreq); response = ToResponse(request.Version, execution, oresp, serviceNs); } catch (ActorException ex) { response = ToFault(request.Version, execution, ex); } catch (Exception ex) { ActorException aex = new WebException(ER.Soap_UnhandledException, ex); response = ToFault(request.Version, execution, aex); } /* * */ ResponseEmit(context, response); return; }
protected static string GetReport(string reportpath, string format, List <RC_ParamReports> Param, string NameFile) { ReportExecutionService re2005 = new ReportExecutionService(); re2005.Credentials = CredentialCache.DefaultCredentials; // Render arguments byte[] result = null; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; // Prepare report parameter ReportExecution2005.ParameterValue[] parameters = new ReportExecution2005.ParameterValue[Param.Count]; for (int i = 0; i < Param.Count; i++) { parameters[i] = new ReportExecution2005.ParameterValue(); parameters[i].Name = Param[i].Name; parameters[i].Value = GetParamValue(Param[i].Type, Param[i].ValueFix, Param[i].ValueExpression, Param[i].Format); Console.WriteLine("Param[i].Name = {0}; Param[i].ValueExpression = {1}; Param[i].ValueCatalog = {2}; Param[i].ValueFix = {3}", Param[i].Name, Param[i].ValueExpression, Param[i].ValueCatalog, Param[i].ValueFix); Console.WriteLine("parameters[i].Name = {0}; parameters[i].Value = {1}", parameters[i].Name, parameters[i].Value); } //Блок херни ReportExecution2005.DataSourceCredentials[] credentials = null; string showHideToggle = null; string encoding; string mimeType; string extension = ""; ReportExecution2005.Warning[] warnings = null; ReportExecution2005.ParameterValue[] reportHistoryParameters = null; string[] streamIDs = null; // ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); try {// re2005.ExecutionHeaderValue = execHeader; execInfo = re2005.LoadReport(reportpath, historyID); re2005.SetExecutionParameters(parameters, "ru-RU"); String SessionId = re2005.ExecutionHeaderValue.ExecutionID; ///Console.WriteLine("SessionID: {0}", re2005.ExecutionHeaderValue.ExecutionID); result = re2005.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); ///Console.WriteLine("format = {0}; devInfo = {1}; extension = {2}; encoding = {3}; mimeType = {4}; warnings = {5}; streamIDs = {6}", format, devInfo, extension, encoding, mimeType, warnings, streamIDs); } catch (SoapException e) { Console.WriteLine(e.Detail.OuterXml); } catch (Exception e) { Console.WriteLine(e.Message); } ///finally { Console.WriteLine(e.Message); } // Write the contents of the report to an MHTML file. try { using (FileStream stream = System.IO.File.Create(NameFile, result.Length)) { ///Console.WriteLine("File created."); stream.Write(result, 0, result.Length); Console.WriteLine("Result written to the file {0}.", NameFile); // stream.Close(); } } catch (Exception e) { Console.WriteLine("ОШИБКА " + e.Message); } return(NameFile); }
private byte[] GetRsReport_New(MD_ReportItem _reportItem, string Format) { byte[] results; ReportExecutionService rs = new ReportExecutionService(); rs.Credentials = new System.Net.NetworkCredential(RsConfig.Name, RsConfig.Pass); rs.Url = RsConfig.RsURL; // Render arguments byte[] result = null; string reportPath = "/海关总署缉私局/" + _reportItem.ReportName.ReportName; string historyID = null; string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; // Prepare report parameter. ReportService2008.ParameterValue[] param = new ReportService2008.ParameterValue[3]; param[0] = new ReportService2008.ParameterValue(); param[0].Name = "Report_Parameter_Year"; param[0].Value = _reportItem.StartDate.Year.ToString(); param[1] = new ReportService2008.ParameterValue(); param[1].Name = "Report_Parameter_month"; param[1].Value = _reportItem.StartDate.Month.ToString("D2"); param[2] = new ReportService2008.ParameterValue(); param[2].Name = "Report_Parameter_Dw"; param[2].Value = _reportItem.ReportDWID; ReportService2008.DataSourceCredentials[] credentials = null; string showHideToggle = null; string encoding; string mimeType; string extension; ReportService2008.Warning[] warnings = null; ReportService2008.ParameterValue[] reportHistoryParameters = null; string[] streamIDs = null; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); rs.SetExecutionParameters(param, "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(); //Console.WriteLine("Execution date and time: {0}", execInfo.ExecutionDateTime); } catch (SoapException e) { OralceLogWriter.WriteSystemLog(e.Detail.OuterXml, "ERROR"); } return(result); }
/// <summary> /// This first version of RenderReport is strictly for legacy support of NIFTransferShipment. NIFTransferShipment should be re-worked to use the rendorReport /// version that accepts an array of ParameterValues. /// </summary> /// <param name="reportPath"></param> /// <param name="identifier"></param> /// <returns></returns> public byte[][] renderReport(string reportPath, ParameterValue[] reportParameters) { // Private variables for rendering string historyID = null; ExecutionHeader execHeader = new ExecutionHeader(); try { rs.Timeout = 300000; rs.ExecutionHeaderValue = execHeader; ExecutionInfo execInfo = new ExecutionInfo(); execInfo = rs.LoadReport(reportPath, historyID); if (reportParameters != null) { rs.SetExecutionParameters(reportParameters, "en-us"); } Byte[][] pages = new Byte[0][]; string format = "IMAGE"; int numberOfPages = 1; byte[] currentPageStream = new byte[1] { 0x00 }; // this single byte will prime the while loop string extension = null; string encoding = null; string mimeType = null; string[] streamIDs = null; Warning[] warnings = null; while (currentPageStream.Length > 0) { string deviceInfo = String.Format(@"<DeviceInfo><OutputFormat>EMF</OutputFormat><PrintDpiX>96</PrintDpiX><PrintDpiY>96</PrintDpiY><StartPage>{0}</StartPage></DeviceInfo>", numberOfPages); //Execute the report and get page count. currentPageStream = rs.Render( format, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); if (currentPageStream.Length == 0 && numberOfPages == 1) { break; // nothing rendered } if (currentPageStream.Length > 0) { Array.Resize(ref pages, pages.Length + 1); pages[pages.Length - 1] = currentPageStream; numberOfPages++; } } m_numberOfPages = numberOfPages - 1; return(pages); } catch (SoapException ex) { eventLog.WriteEntry(ex.Detail.InnerXml, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Detail.InnerXml); } catch (Exception ex) { eventLog.WriteEntry(ex.Message, EventLogEntryType.Information, 7001); Console.WriteLine(ex.Message); } finally { } return(null); }
/// <summary> /// Runs reports in SSRS and creates them in a specific folder /// </summary> /// <param name="reportPath">File system location to create the report</param> /// <param name="fileName">The name of the file to create</param> /// <param name="exportFormat">Format of file to export</param> /// <param name="hospitalListName">The parameter to use for the hospital name</param> private static void CreateFiles(string reportPath, string fileName, string exportFormat, string hospitalListName) { //var csvMappingFile = ConfigurationManager.AppSettings["ReportExtractorOutputFormat"]; DataTable hospitalMapping = GetDataTableFromCsvFile(ConfigurationManager.AppSettings["ReportExtractorOutputFormat"]); DataTable excludedHospitals = GetDataTableFromCsvFile(ConfigurationManager.AppSettings["excludedHospitals"]); var excludedHospitalsList = excludedHospitals.AsEnumerable().Select(row => row.Field <string>("sourceID")).ToArray(); var rs = new ReportExecutionService { Credentials = new NetworkCredential( ConfigurationManager.AppSettings["NetworkCredentialUsername"].ToString( CultureInfo.InvariantCulture), ConfigurationManager.AppSettings["NetworkCredentialPassword"].ToString( CultureInfo.InvariantCulture)), Url = Properties.Settings.Default.ServiceURL }; rs.Timeout = Int32.Parse(ConfigurationManager.AppSettings["ReportTimeoutInMillis"]); //Render arguments const string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"; var execHeader = new ExecutionHeader(); rs.ExecutionHeaderValue = execHeader; var execInfo = rs.LoadReport(reportPath, null); // Run the report extractor for every valid hospital foreach ( ValidValue sourceId in execInfo.Parameters.Where(i => i.Name == hospitalListName).Select(i => i.ValidValues).First() .Where(i => !excludedHospitalsList.Contains(i.Value))) { Log.Info(String.Format("Starting report execution process: {0}-{1}-{2}", reportPath, sourceId.Value, rs.ExecutionHeaderValue.ExecutionID)); //Prepare report parameter. var parameters = new ParameterValue[1]; parameters[0] = new ParameterValue { Name = hospitalListName, Value = sourceId.Value }; rs.SetExecutionParameters(parameters, "en-us"); string encoding; string mimeType; string extension; Warning[] warnings = null; string[] streamIDs = null; var result = rs.Render(exportFormat, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); // Write the contents of the report to an Excel file. Log.Info(String.Format("Starting create file process: {0}-{1}-{2}-{3}", reportPath, sourceId.Value, rs.ExecutionHeaderValue.ExecutionID, fileName)); var id = sourceId; var sourceCode = (from hospital in hospitalMapping.AsEnumerable() where hospital.Field <string>("SourceID") == id.Value select hospital.Field <string>("SourceCode")).First(); var id1 = sourceId; var hospitalSystem = (hospitalMapping.AsEnumerable() .Where(hospital => hospital.Field <string>("SourceID") == id1.Value) .Select(hospital => hospital.Field <string>("hospitalSystem"))).First(); string[] fromArray = execInfo.Parameters.Where(i => i.Name.ToLower() == "from").Select(i => i.DefaultValues).First(); string from = fromArray[0]; DateTime fromTime = Convert.ToDateTime(from); string[] toArray = execInfo.Parameters.Where(i => i.Name.ToLower() == "to").Select(i => i.DefaultValues).First(); string to = toArray[0]; DateTime toTime = Convert.ToDateTime(to); try { var stream = File.Create(String.Format(fileName, hospitalSystem, sourceId.Value + " " + sourceCode, fromTime.ToString("yy-MM"), toTime.ToString("yy-MM"), DateTime.Now.ToString("yyyy-MM-dd"), sourceId.Value, sourceCode), result.Length); stream.Write(result, 0, result.Length); stream.Close(); } catch (DirectoryNotFoundException ex) { } } }
private static SoapResponse ToResponse(SoapVersion version, ExecutionHeader execution, object response, string serviceNs) { /* * */ XNamespace soapNs; if (version == SoapVersion.Soap11) { soapNs = "http://schemas.xmlsoap.org/soap/envelope/"; } else { soapNs = "http://www.w3.org/2003/05/soap-envelope"; } /* * */ XDocument responseDoc = new XDocument(); var envelope = new XElement(soapNs + "Envelope"); envelope.Add(new XAttribute(XNamespace.Xmlns + "soap", soapNs.NamespaceName)); var header = new XElement(soapNs + "Header"); var body = new XElement(soapNs + "Body"); envelope.Add(header, body); responseDoc.Add(envelope); /* * */ execution.MomentEnd = DateTime.UtcNow; XmlSerializer serHeader = new XmlSerializer(typeof(ExecutionHeader)); header.Add(serHeader.SerializeAsXElement(execution)); /* * */ Type t = response.GetType(); XmlSerializer serBody = XmlSerializerFor(t, serviceNs); body.Add(serBody.SerializeAsXElement(response)); /* * */ SoapResponse resp = new SoapResponse(); resp.Version = version; resp.IsFault = false; resp.Message = responseDoc.ToString(SaveOptions.DisableFormatting); return(resp); }
public ActionResult GenerateReport(ITABUWiseReportModel objITABUWiseModel) { // ITABUWiseReportModel objITABUWise = new ITABUWiseReportModel(); try { #region Declarations string encoding; string mimeType; string extension; string fileNamePath1 = ""; string historyID = null; Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.Warning[] warnings = null; string[] streamIDs = null; string reportPath = ""; string reportName = "ITABusinessVerticalWise"; string strGetCurrentDate = DateTime.Now.ToString("MMMM") + " " + DateTime.Now.ToString("dd") + " " + DateTime.Now.Year.ToString(); string strPath = ConfigurationManager.AppSettings["ReportsPath"].ToString() + strGetCurrentDate; byte[] result = null; string format = "EXCEL"; ExecutionInfo execInfo = new ExecutionInfo(); ExecutionHeader execHeader = new ExecutionHeader(); ReportExecutionService rs = new ReportExecutionService(); #endregion if (!Directory.Exists(strPath)) { //Create Reports Folder with Current Date Directory.CreateDirectory(strPath); } //strPath = string.Format("{0}\\{1}_{2}", strPath, objITABUWiseModel.YearId, objITABUWiseModel.Quarter); rs.Credentials = System.Net.CredentialCache.DefaultCredentials; rs.Url = ConfigurationManager.AppSettings["ReportExecutionService2012"].ToString(); reportPath = "/TrainingModuleReports/" + reportName; RMS.Common.Master objMaster = new Common.Master(); System.Data.DataTable dt = objMaster.FillDropDownList("105"); rs.ExecutionHeaderValue = execHeader; execInfo = rs.LoadReport(reportPath, historyID); ParameterValue[] parametersBusinessverticals = null; foreach (DataRow dr in dt.Rows) { fileNamePath1 = strPath + "\\" + reportName + "_" + Convert.ToString(dr["MasterName"]).Trim() + ".xlsx"; if (!System.IO.File.Exists(fileNamePath1)) { parametersBusinessverticals = new ParameterValue[3]; parametersBusinessverticals[0] = new ParameterValue(); parametersBusinessverticals[0].Name = "StartYear"; parametersBusinessverticals[0].Value = objITABUWiseModel.YearId; parametersBusinessverticals[1] = new ParameterValue(); parametersBusinessverticals[1].Name = "Quarter"; parametersBusinessverticals[1].Value = objITABUWiseModel.Quarter; parametersBusinessverticals[2] = new ParameterValue(); parametersBusinessverticals[2].Name = "BusinessVertical"; parametersBusinessverticals[2].Value = Convert.ToString(dr["MasterId"]); rs.SetExecutionParameters(parametersBusinessverticals, "en-us"); rs.Timeout = 3600000; //60 mins result = rs.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs); execInfo = rs.GetExecutionInfo(); using (FileStream stream = System.IO.File.Create(fileNamePath1, result.Length)) { stream.Write(result, 0, result.Length); stream.Close(); } } } objITABUWiseModel.Message = string.Format("Reports Generated Sucessfully at Location {0}", strPath); return(View(objITABUWiseModel)); } catch (Exception ex) { throw new RaveHRException(ex.Message, ex, Sources.BusinessLayer, "ReportController", "GenerateReport", EventIDConstants.TRAINING_PRESENTATION_LAYER); } }