Exemple #1
0
        /// <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);
        }
Exemple #2
0
        public static Byte[] DownloadExcel(System.Web.HttpContextBase httpContext, ReportExecutionBE reportexecution)
        {
            var rs     = ReportWebServiceInstance(httpContext);
            var rsExec = new ReportExecutionService();

            rsExec.Timeout     = System.Threading.Timeout.Infinite;
            rsExec.Credentials = rs.Credentials;
            byte[] result  = null;
            string format  = "EXCEL";
            string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
            string extension;
            string encoding;
            string mimeType;

            ReportExecution.Warning[] warnings = null;
            string[] streamIDs = null;

            ExecutionInfo execInfo = new ExecutionInfo();

            //var output = new HttpResponseMessage();
            try
            {
                ReportExecution.ExecutionInfo         ei         = rsExec.LoadReport(reportexecution.ReportPath, null);
                List <ReportExecution.ParameterValue> parameters = new List <ReportExecution.ParameterValue>();

                for (int i = 0; i < reportexecution.Parameters.Count; ++i)
                {
                    for (int j = 0; j < reportexecution.Parameters[i].Value.Length; ++j)
                    {
                        ReportExecution.ParameterValue item = new ReportExecution.ParameterValue();
                        item.Name  = reportexecution.Parameters[i].Name;
                        item.Label = reportexecution.Parameters[i].Label;
                        item.Value = reportexecution.Parameters[i].Value[j];
                        parameters.Add(item);
                    }
                }
                ReportExecution.ParameterValue[] parametersExec = parameters.ToArray();
                rsExec.SetExecutionParameters(parametersExec, "en-us");
                result = rsExec.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);

                execInfo = rsExec.GetExecutionInfo();
            }
            catch (SoapException ex)
            {
                //output = new HttpResponseMessage(HttpStatusCode.BadRequest);
                LoggingHelper.LogException("Unable to generate the excel file.", ex);
            }
            //return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", reportexecution.ReportName + "-" + execInfo.ExecutionDateTime + ".xlsx");
            return(result);
        }
        public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
        {
            //initialize report execution service
            string RSExecURL = @"http://" + Server + "/ReportServer/ReportExecution2005.asmx";
            ReportExecutionService RSExec2005 = new ReportExecutionService();

            RSExec2005.Credentials = System.Net.CredentialCache.DefaultCredentials;
            RSExec2005.Url         = RSExecURL;

            //prepare variables
            byte[]    Results  = null;
            Warning[] warnings = null;
            string    encoding;
            string    mimetype;

            string[] streamids = null;
            string   extension;

            try
            {
                ExecutionInfo Info = new ExecutionInfo();
                Info = RSExec2005.LoadReport(SelectedReport, null);


                if (DtParameters != null)
                {
                    if (DtParameters.Rows.Count > 0)
                    {
                        List <Tuple <string, string> > lstParameters = new List <Tuple <string, string> >();
                        foreach (DataRow row in DtParameters.Rows)
                        {
                            if (row["ParameterValue"] != null)
                            {
                                if (!string.IsNullOrEmpty(row["ParameterValue"].ToString()))
                                {
                                    //the parameter value has to be a variable
                                    string pName = row["ParameterName"].ToString();

                                    Variables varPValue = null;
                                    variableDispenser.LockOneForRead(row["ParameterValue"].ToString(), ref varPValue);
                                    string pValue = varPValue[0].Value.ToString();

                                    lstParameters.Add(Tuple.Create(pName, pValue));
                                }
                            }
                        }

                        ParameterValue[] Parameters;
                        if (lstParameters.Count > 0)
                        {
                            Parameters = new ParameterValue[lstParameters.Count];

                            for (int i = 0; i < lstParameters.Count; i++)
                            {
                                Parameters[i]       = new ParameterValue();
                                Parameters[i].Name  = lstParameters[i].Item1;
                                Parameters[i].Value = lstParameters[i].Item2;
                            }

                            RSExec2005.SetExecutionParameters(Parameters, "en-us");
                        }
                    }
                }

                //output format and name
                Variables varFileFormat = null;
                variableDispenser.LockOneForRead(FileFormat, ref varFileFormat);

                Variables varFileName = null;
                variableDispenser.LockOneForRead(FileName, ref varFileName);

                Results = RSExec2005.Render(varFileFormat[0].Value.ToString(), null, out extension, out mimetype, out encoding, out warnings, out streamids);
                Info    = RSExec2005.GetExecutionInfo();

                FileStream FS = File.Create(varFileName[0].Value.ToString(), Results.Length);
                FS.Write(Results, 0, Results.Length);
                FS.Close();

                return(DTSExecResult.Success);
            }
            catch (Exception ex)
            {
                componentEvents.FireError(0, "Reporting Service Task", "Task Error: " + ex.ToString(), "", -1);
                return(DTSExecResult.Failure);
            }
        }
Exemple #4
0
        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);
        }
Exemple #5
0
        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);
            }
        }
        public RSExecutionInfo GetExecutionInfo()
        {
            ExecutionInfo outval = rs.GetExecutionInfo();

            return((RSExecutionInfo)Converter.Convert(outval));
        }
Exemple #7
0
        /// <summary>
        /// Generate TUI Reports
        /// </summary>
        /// <param name="serialNumber">Serial Number</param>
        /// <param name="flightName">flightName</param>
        /// <param name="period">Period</param>
        /// <returns>Task result </returns>
        private Task GenerateTuiReport(string serialNumber, string flightName, string period)
        {
            var pdfDirectory    = this._configuration["SSRSInfo:PDFDirectory"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:PDFDirectory\"]");
            var reportServerUrl = this._configuration["SSRSInfo:ServerUrl"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:ServerUrl\"]");
            var userSsrs        = this._configuration["SSRSInfo:SSRSUser"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:SSRSUser\"]");
            var pwdSsrs         = this._configuration["SSRSInfo:SSRSPwd"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:SSRSPwd\"]");
            var domainSsrs      = this._configuration["SSRSInfo:SSRSDomain"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:SSRSDomain\"]");
            var reportPath      = this._configuration["SSRSInfo:ReportPath"] ?? throw new ArgumentNullException($"_configuration[\"SSRSInfo:ReportPath\"]");

            using (var rs = new ReportExecutionService())
            {
                try
                {
                    rs.Timeout     = Timeout.Infinite;
                    rs.Credentials = new NetworkCredential(userSsrs, pwdSsrs, domainSsrs);
                    rs.Url         = $"{reportServerUrl}/ReportExecution2005.asmx";

                    ParameterValue[] parameters = new ParameterValue[3];
                    parameters[0] = new ParameterValue
                    {
                        Name  = "SerialNumber",
                        Value = serialNumber
                    };
                    parameters[1] = new ParameterValue
                    {
                        Name  = "FlightName",
                        Value = flightName
                    };
                    parameters[2] = new ParameterValue
                    {
                        Name  = "Period",
                        Value = period
                    };

                    rs.LoadReport(reportPath, null);
                    rs.SetExecutionParameters(parameters, CultureInfo.CurrentCulture.ToString());

                    string devInfo = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
                    var    result  = rs.Render("pdf", devInfo, Extension: out _, MimeType: out _, Encoding: out _, Warnings: out _, StreamIds: out _);

                    rs.GetExecutionInfo();

                    File.WriteAllBytes(
                        $"{pdfDirectory}\\{serialNumber}_{period}_{DateTime.Now.ToString("ddMMyyyyHHmmss", CultureInfo.InvariantCulture)}.pdf",
                        result);
                    this._logger?.LogDebug(
                        $"GenerateTUIReport {Thread.CurrentThread.ManagedThreadId} :  GeneratedPdf {serialNumber}_{period}");

                    rs.Dispose();
                }
                catch (SoapException se)
                {
                    this._logger?.LogError(se, "ReportExecutionTask se: ");
                    this._logger?.LogError(se, "SerialNumber is: " + serialNumber);
                }
                catch (WebException we)
                {
                    Debug.WriteLine(we);
                    this._logger?.LogError(we, "ReportExecutionTask we: ");
                    throw;
                }
                catch (UnauthorizedAccessException e)
                {
                    this._logger?.LogError(e, "ReportExecutionTask e : ");
                    throw;
                }
            }

            return(Task.FromResult(0));
        }
        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);
        }