Example #1
0
        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);
        }
        private void test_1()
        {
            NetworkCredential clientCredentials = new NetworkCredential("Chathuranga", "blahhhhh", "Chathu-Nable");


            ReportingService2010SoapClient client = new ReportingService2010SoapClient();

            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            client.ClientCredentials.Windows.ClientCredential          = clientCredentials;



            client.Open();
            TrustedUserHeader t = new TrustedUserHeader();



            CatalogItem[] items;
            // I need to list of children of a specified folder.
            ServerInfoHeader oServerInfoHeader = client.ListChildren(t, "/", true, out items);

            foreach (var item in items)
            {
                // I can access any properties of item
                Console.WriteLine(item.ID);
            }

            Console.ReadLine();
        }
Example #3
0
 private ServerReport(ServerReport parentReport, ExecutionInfo executionInfo)
     : this(parentReport)
 {
     m_reportPath           = executionInfo.ReportPath;
     m_executionID          = executionInfo.ExecutionID;
     m_executionInfo        = executionInfo;
     m_trustedUserHeader    = parentReport.TrustedUserHeaderValue;
     base.DrillthroughDepth = parentReport.DrillthroughDepth + 1;
 }
        public ReportOutput Execute()
        {
            ExecutionInfo         executionInfo;
            List <ParameterValue> parameterValues   = new List <ParameterValue>();
            TrustedUserHeader     trustedUserHeader = null;
            ServerInfoHeader      serverInfoHeader;
            ExecutionHeader       executionHeader;

            byte[] result;
            string extension;
            string mimeType;
            string encoding;

            Warning[] warnings = { };
            string[]  streamIds;

            // Build client
            _client = new ReportExecutionServiceSoapClient(new BasicHttpBinding(), new EndpointAddress(this.ReportServerUrl));

            // Set credentials
            _client.ClientCredentials.Windows.ClientCredential          = this.Credential;
            _client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;

            // Load the report
            executionHeader = _client.LoadReport(trustedUserHeader, this.Report, this.HistoryId, out serverInfoHeader, out executionInfo);

            // Map the parameters
            foreach (KeyValuePair <string, string> parameter in this.Parameters)
            {
                parameterValues.Add(new ParameterValue()
                {
                    Name  = parameter.Key,
                    Value = parameter.Value
                });
            }

            // Set the execution parameters
            if (parameterValues.Count > 0)
            {
                serverInfoHeader = _client.SetExecutionParameters(executionHeader, trustedUserHeader, parameterValues.ToArray(), null, out executionInfo);
            }

            // Render the report
            serverInfoHeader = _client.Render(executionHeader, trustedUserHeader, this.Format, this.DeviceInfo, out result, out extension, out mimeType, out encoding, out warnings, out streamIds);

            // Build output object
            return(new ReportOutput()
            {
                ExecutionInfo = executionInfo,
                Result = result,
                Extension = extension,
                MimeType = mimeType,
                Encoding = encoding,
                Warnings = warnings,
                StreamIds = streamIds
            });
        }
Example #5
0
 public SoapReportExecutionService(System.Security.Principal.WindowsIdentity impersonationUser, Uri reportServerUrl, IReportServerCredentials reportServerCredentials, TrustedUserHeader trustedUserHeader, IEnumerable <string> headers, IEnumerable <Cookie> cookies, int timeout)
 {
     m_impersonationUser       = impersonationUser;
     m_reportServerUrl         = reportServerUrl;
     m_reportServerCredentials = reportServerCredentials;
     m_trustedUserHeader       = trustedUserHeader;
     m_headers = headers;
     m_cookies = cookies;
     m_timeout = timeout;
 }
        public void Upload(string targetServerUri, string artifactsFolderPath)
        {
            bool isHttpsEndpoint = new Uri(targetServerUri).Scheme == Uri.UriSchemeHttps;
            ReportingService2010SoapClient reportingServicesClient = CreateClientProxy(targetServerUri, isHttpsEndpoint);

            var userHeader = new TrustedUserHeader();

            UploadReportDataSources(reportingServicesClient, userHeader, artifactsFolderPath);
            UploadSharedDataSets(reportingServicesClient, userHeader, artifactsFolderPath);
            UploadReports(reportingServicesClient, userHeader, artifactsFolderPath);
        }
Example #7
0
        public CatalogItem[] ListReportCollection(string itemPath, bool recursive)
        {
            CatalogItem[] reportCollection = { };

            try
            {
                ReportingService2010SoapClient client = new ReportingService2010SoapClient();

                //NT LAN Manager (NTLM) is a suite of Microsoft security protocols that provides authentication, integrity, and confidentiality to users.[1][2][3] NTLM is the successor to the authentication protocol in Microsoft LAN Manager (LANMAN),
                client.ClientCredentials.Windows.AllowNtlm        = true;
                client.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;

                //
                // Summary:
                //     The server process can impersonate the client's security context on its local
                //     system. The server cannot impersonate the client on remote systems.
                //  Impersonation = 3,

                //       Finally figure it out.
                //       My Reporting Services were configured to a local account while my Application Pool for IIS was configured to ApplicationPoolIdentity.
                //      I changed my Application Pool to LocalSystem and it fixed it. Hopefully this information will be useful to others as I wasted several hours figuring this out.

                client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

                CatalogItem aCatalogItem = new CatalogItem();


                // aCatalogItem.TypeName

                // Summary:
                //     The server process can impersonate the client's security context on remote
                //     systems.
                // client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;

                client.Open();
                TrustedUserHeader t = new TrustedUserHeader();

                try
                {
                    // I need to list of children of a specified folder.
                    client.ListChildren(t, itemPath, recursive, out reportCollection); // see http://msdn.microsoft.com/en-us/library/reportservice2010.reportingservice2010.listchildren.aspx
                }
                catch (SoapException ex)
                {
                    // _logger.Error("ReportServerManagementService--" + ex);
                }
            }
            catch (SoapException ex)
            {
                // _logger.Error("ReportServerManagementService--" + ex);
            }

            return(reportCollection);
        }
        public void Upload(string targetServerUri, string artifactsFolderPath)
        {
            bool isHttpsEndpoint = new Uri(targetServerUri).Scheme == Uri.UriSchemeHttps;
            ReportingService2010SoapClient reportingServicesClient = CreateClientProxy(targetServerUri, isHttpsEndpoint);

            var userHeader = new TrustedUserHeader();

            UploadReportDataSources(reportingServicesClient, userHeader, artifactsFolderPath);
            UploadSharedDataSets(reportingServicesClient, userHeader, artifactsFolderPath);
            UploadReports(reportingServicesClient, userHeader, artifactsFolderPath);
        }
 private void UploadReportDataSources(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, string artifactsFolderPath)
 {
     foreach (var dataSourceDefinitionFile in Directory.GetFiles(artifactsFolderPath, String.Format("*{0}", DataSourceFileExtension)))
     {
         string itemName = Path.GetFileNameWithoutExtension(dataSourceDefinitionFile);
         CatalogItem dataSetItem = null;
         DataSourceDefinition definition = DataSourceDefinitionParser.Parse(File.OpenRead(dataSourceDefinitionFile));
         Console.WriteLine("Uploaded report data source '{0}'", itemName);
         reportingServicesClient.CreateDataSource(userHeader, itemName, "/", true, definition, null, out dataSetItem);
     }
 }
        private SSRSServiceHandler()
        {
            NetworkCredential clientCredentials = new NetworkCredential("Test", "123", "Chathu-Nable");


            serviceClient = new ReportingService2010SoapClient();
            serviceClient.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            serviceClient.ClientCredentials.Windows.ClientCredential          = clientCredentials;
            serviceClient.Open();

            userHeader = new TrustedUserHeader();
        }
 private void UploadSharedDataSets(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, string artifactsFolderPath)
 {
     foreach (var dataSetDefinitionFile in Directory.GetFiles(artifactsFolderPath, String.Format("*{0}", DataSetFileExtension)))
     {
         string itemName = Path.GetFileNameWithoutExtension(dataSetDefinitionFile);
         byte[] itemDefinition = File.ReadAllBytes(dataSetDefinitionFile);
         CatalogItem dataSetItem = null;
         Warning[] warnings = null;
         Console.WriteLine("Uploaded shared data set '{0}'", itemName);
         reportingServicesClient.CreateCatalogItem(userHeader, "DataSet", itemName, "/", true, itemDefinition, null, out dataSetItem, out warnings);
     }
 }
 private void DownloadSharedDataSets(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, CatalogItem[] items)
 {
     foreach (var dataSetDefinition in items.Where(item => item.TypeName == "DataSet"))
     {
         byte[] itemDefinition = null;
         string outputFilePath = Path.Combine(outputFolderPath, dataSetDefinition.Name + DataSetFileExtension);
         reportingServicesClient.GetItemDefinition(userHeader, dataSetDefinition.Path, out itemDefinition);
         string reportContents = new StreamReader(new MemoryStream(itemDefinition)).ReadToEnd();
         Console.WriteLine("Downloaded shared data set '{0}' into file '{1}'", dataSetDefinition.Name, outputFilePath);
         File.WriteAllText(outputFilePath, reportContents);
     }
 }
        /// <summary>
        /// Returns a list with all reports
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <CatalogItem[]> GetItems(string path)
        {
            TrustedUserHeader header = new TrustedUserHeader();

            return(await System.Threading.Tasks.Task.Factory.FromAsync <CatalogItem[]>(
                       _service.BeginListChildren(header, path, true, null, null),
                       (ar) =>
            {
                CatalogItem[] items = null;
                _service.EndListChildren(ar, out items);
                return items;
            }));
        }
        /// <summary>
        /// Returns the content of specified file
        /// </summary>
        /// <param name="itemPath"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <byte[]> GetResourceContents(string itemPath)
        {
            TrustedUserHeader header = new TrustedUserHeader();

            return(await System.Threading.Tasks.Task.Factory.FromAsync <byte[]>(
                       _service.BeginGetItemDefinition(header, itemPath, null, null),
                       (ar) =>
            {
                byte[] data;
                _service.EndGetItemDefinition(ar, out data);
                return data;
            }));
        }
        public void Download(string targetServerUri, string artifactsFolderPath)
        {
            bool isHttpsEndpoint = new Uri(targetServerUri).Scheme == Uri.UriSchemeHttps;
            outputFolderPath = artifactsFolderPath;
            ReportingService2010SoapClient reportingServicesClient = CreateClientProxy(targetServerUri, isHttpsEndpoint);

            var userHeader = new TrustedUserHeader();
            CatalogItem[] items = null;
            reportingServicesClient.ListChildren(userHeader, "/", true, out items);
            DownloadReportDataSources(reportingServicesClient, userHeader, items);
            DownloadSharedDataSets(reportingServicesClient, userHeader, items);
            DownloadReports(reportingServicesClient, userHeader, items);
        }
Example #16
0
 public async Task TestAsync()
 {
     try
     {
         var trustedUserHeader = new TrustedUserHeader();
         var reportPath        = "replace with path to report in SSRS";
         var report            = await _reportClient.LoadReportAsync(trustedUserHeader, reportPath, null);
     }
     catch (Exception ex)
     {
         Console.WriteLine($"An excpetion occurred: {ex.Message}");
         throw;
     }
 }
        public void Download(string targetServerUri, string artifactsFolderPath)
        {
            bool isHttpsEndpoint = new Uri(targetServerUri).Scheme == Uri.UriSchemeHttps;

            outputFolderPath = artifactsFolderPath;
            ReportingService2010SoapClient reportingServicesClient = CreateClientProxy(targetServerUri, isHttpsEndpoint);

            var userHeader = new TrustedUserHeader();

            CatalogItem[] items = null;
            reportingServicesClient.ListChildren(userHeader, "/", true, out items);
            DownloadReportDataSources(reportingServicesClient, userHeader, items);
            DownloadSharedDataSets(reportingServicesClient, userHeader, items);
            DownloadReports(reportingServicesClient, userHeader, items);
        }
Example #18
0
        public IEnumerable <object> GetReports()
        {
            NetworkCredential clientCredentials = new NetworkCredential("nrodas", "P@ssw0rd", "CLIN");

            ReportingServices.ReportingService2010SoapClient client = new ReportingServices.ReportingService2010SoapClient();
            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            client.ClientCredentials.Windows.ClientCredential          = clientCredentials;
            client.Open();
            TrustedUserHeader t = new TrustedUserHeader();

            CatalogItem[] items;
            // I need to list of children of a specified folder.
            ServerInfoHeader oServerInfoHeader = client.ListChildren(t, "/", true, out items);

            return(items);
        }
        /// <summary>
        /// Download the specified report file
        /// </summary>
        /// <param name="itemPath"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <System.Xml.XmlDocument> GetReportDefinition(string itemPath)
        {
            TrustedUserHeader header = new TrustedUserHeader();

            return(await System.Threading.Tasks.Task.Factory.FromAsync <System.Xml.XmlDocument>(
                       _service.BeginGetItemDefinition(header, itemPath, null, null),
                       (ar) =>
            {
                byte[] data;
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                ServerInfoHeader result = _service.EndGetItemDefinition(ar, out data);
                MemoryStream stream = new MemoryStream(data);

                doc.Load(stream);
                return doc;
            }));
        }
        /// <summary>
        /// Upload the specified data content to a remote report (parent/name).
        /// </summary>
        /// <param name="dataType">Must be "Report" to upload a report content</param>
        /// <param name="sourceFile"></param>
        /// <param name="parent"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task CreateCatalogItem(string dataType, FileInfo sourceFile, DirectoryInfo relativeTo, string remoteParent, byte[] data)
        {
            TrustedUserHeader header = new TrustedUserHeader();
            Property          prop1  = new Property()
            {
                Name = "MimeType", Value = MimeTypes.MimeTypeMap.GetMimeType(sourceFile.Extension)
            };
            string filenameWithoutExtension = sourceFile.Name.Substring(0, Convert.ToInt32(sourceFile.Name.Length - sourceFile.Extension.Length));

            string parent = await this.CreateSubFolders(sourceFile.FullName, relativeTo.FullName, remoteParent);

            await System.Threading.Tasks.Task.Factory.FromAsync(
                _service.BeginCreateCatalogItem(header, dataType, filenameWithoutExtension, parent, true, data, String.IsNullOrEmpty(prop1.Value) ? null : new Property[] { prop1 }, null, null)
                ,
                (ar) =>
            {
                CatalogItem catalogItem;
                Warning[] warning;
                _service.EndCreateCatalogItem(ar, out catalogItem, out warning);
                return(data);
            });
        }
        /// <summary>
        /// Creates all subfolders to store the filename in a parent folder, relative to a base folder.
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="relativeToFolder"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <string> CreateSubFolders(string filename, string relativeToFolder, string parent)
        {
            TrustedUserHeader header = new TrustedUserHeader();

            string[] folders         = Data.Report.GetRelativePathSplitted(filename, relativeToFolder, true);
            string   parentCompleted = parent;

            foreach (string folder in folders)
            {
                await System.Threading.Tasks.Task.Factory.FromAsync(
                    _service.BeginCreateFolder(header, folder, parentCompleted, null, null, null)
                    ,
                    (ar) =>
                {
                    try
                    {
                        CatalogItem catalogItem;
                        _service.EndCreateFolder(ar, out catalogItem);
                    }
                    catch (System.ServiceModel.FaultException ex)
                    {
                        if (ex.Message.Contains("Microsoft.ReportingServices.Diagnostics.Utilities.ItemAlreadyExistsException"))
                        {
                            // Bypass if the folder already exits
                        }
                        else
                        {
                            throw;
                        }
                    }
                });

                parentCompleted += "/" + folder;
            }

            return(parentCompleted);
        }
        private void grantPriviledges_1()
        {
            NetworkCredential clientCredentials = new NetworkCredential("Test", "123", "Chathu-Nable");


            ReportingService2010SoapClient client = new ReportingService2010SoapClient();

            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            client.ClientCredentials.Windows.ClientCredential          = clientCredentials;



            client.Open();
            TrustedUserHeader t = new TrustedUserHeader();



            Policy[] MyPolicyArr = new Policy[2];


            Role[] MyRoles = new Role[3];

            Role browser = new Role();

            browser.Name = "Browser";

            Role myReports = new Role();

            myReports.Name = "My Reports";

            Role publisher = new Role();

            publisher.Name = "Publisher";

            Role contentManager = new Role()
            {
                Name = "Content Manager"
            };

            MyRoles[0] = publisher;
            MyRoles[1] = browser;
            MyRoles[2] = contentManager;


            MyPolicyArr[0] = new Policy()
            {
                GroupUserName = @"Chathu-Nable\Test", Roles = MyRoles
            };
            MyPolicyArr[1] = new Policy()
            {
                GroupUserName = @"Chathu-Nable\Test2", Roles = MyRoles
            };


            client.SetPolicies(t, "/New Folder", MyPolicyArr);

            //rs.SetPolicies("/SecurityTestFolder", MyPolicyArr);



            MessageBox.Show("blahhhh");
        }
Example #23
0
        // https://docs.microsoft.com/en-us/dotnet/api/reportexecution2005.reportexecutionservice.render?view=sqlserver-2016
        // https://docs.microsoft.com/en-us/sql/reporting-services/customize-rendering-extension-parameters-in-rsreportserver-config?view=sql-server-ver15
        // https://medium.com/@yates.programmer/generating-an-ssrs-report-using-wcf-from-net-core-application-730e22886da3
        public async Task <byte[]> Render(string reportPath, string reportType = "PDF", string deviceInfo = null)
        {
            if (string.IsNullOrEmpty(reportPath))
            {
                throw new Exception("Missing required reportPath parameter");
            }

            reportType = reportType.ToUpper().Trim();
            switch (reportType)
            {
            case "PDF":
            case "EXCEL":
            case "WORD":
            case "XML":
            case "CSV":
            case "IMAGE":
            case "HTML4.0":
            case "MHTML":
                break;

            default:
                throw new Exception("Invalid reportType: " + reportType);
            }

            TrustedUserHeader  trustedHeader = new TrustedUserHeader();
            LoadReportResponse loadReponse   = await LoadReport(RSExecutionClient, trustedHeader, reportPath);

            if (ReportParameters.Count > 0)
            {
                await RSExecutionClient.SetExecutionParametersAsync(
                    loadReponse.ExecutionHeader,
                    trustedHeader,
                    ReportParameters.ToArray(),
                    "en-US"
                    );
            }

            var            renderRequest = new RenderRequest(loadReponse.ExecutionHeader, trustedHeader, reportType, deviceInfo);
            RenderResponse response      = await RSExecutionClient.RenderAsync(renderRequest);

            if (response.Warnings != null)
            {
                foreach (ReportExecution.Warning warning in response.Warnings)
                {
                    Warnings.Add(
                        new KeyValuePair <string, string>(
                            warning.Code,
                            String.Format(
                                "Severity: {0} Object: {1} Message: {2}",
                                warning.Severity,
                                warning.ObjectName,
                                warning.Message
                                )
                            )
                        );
                }
            }

            Extension = response.Extension;
            MimeType  = response.MimeType;
            Encoding  = response.Encoding;
            StreamIds = response.StreamIds;

            return(response.Result);
        }
Example #24
0
        private async Task <LoadReportResponse> LoadReport(ReportExecutionServiceSoapClient rs, TrustedUserHeader trustedHeader, string reportPath)
        {
            // Get the report and set the execution header.
            // Failure to set the execution header will result in this error: "The session identifier is missing. A session identifier is required for this operation."
            // See https://social.msdn.microsoft.com/Forums/sqlserver/en-US/17199edb-5c63-4815-8f86-917f09809504/executionheadervalue-missing-from-reportexecutionservicesoapclient
            LoadReportResponse loadResponse = await rs.LoadReportAsync(trustedHeader, reportPath, HistoryId);

            return(loadResponse);
        }
Example #25
0
        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);
        }
 private void UploadReports(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, string artifactsFolderPath)
 {
     foreach (var reportDefinitionFile in Directory.GetFiles(artifactsFolderPath, String.Format("*{0}", ReportFileExtension)))
     {
         string      itemName       = Path.GetFileNameWithoutExtension(reportDefinitionFile);
         byte[]      itemDefinition = File.ReadAllBytes(reportDefinitionFile);
         CatalogItem dataSetItem    = null;
         Warning[]   warnings       = null;
         Console.WriteLine("Uploaded report '{0}'", itemName);
         reportingServicesClient.CreateCatalogItem(userHeader, "Report", itemName, "/", true, itemDefinition, null, out dataSetItem, out warnings);
     }
 }
 private void UploadReportDataSources(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, string artifactsFolderPath)
 {
     foreach (var dataSourceDefinitionFile in Directory.GetFiles(artifactsFolderPath, String.Format("*{0}", DataSourceFileExtension)))
     {
         string               itemName    = Path.GetFileNameWithoutExtension(dataSourceDefinitionFile);
         CatalogItem          dataSetItem = null;
         DataSourceDefinition definition  = DataSourceDefinitionParser.Parse(File.OpenRead(dataSourceDefinitionFile));
         Console.WriteLine("Uploaded report data source '{0}'", itemName);
         reportingServicesClient.CreateDataSource(userHeader, itemName, "/", true, definition, null, out dataSetItem);
     }
 }
Example #28
0
        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);
            }
        }
Example #29
0
        private CatalogItem[] GetAllCatalogSSRS()
        {
            TrustedUserHeader Myheader = new TrustedUserHeader();
            CatalogItem[] catalogItems = null;
            clientSoap.ListChildren(Myheader, "/", true, out catalogItems);

            return catalogItems;
        }
Example #30
0
        public CatalogItem[] GetCatalogItems(String itemPath)
        {
            TrustedUserHeader Myheader = new TrustedUserHeader();
            CatalogItem[] catalogItems = null;

            try
            {
                clientSoap.ListChildren(Myheader, itemPath, true, out catalogItems);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
            
            
            return catalogItems;
        }    
 private void DownloadReports(ReportingService2010SoapClient reportingServicesClient, TrustedUserHeader userHeader, CatalogItem[] items)
 {
     foreach (var reportDefinition in items.Where(item => item.TypeName == "Report"))
     {
         byte[] itemDefinition = null;
         reportingServicesClient.GetItemDefinition(userHeader, reportDefinition.Path, out itemDefinition);
         string reportContents = new StreamReader(new MemoryStream(itemDefinition)).ReadToEnd();
         string outputFilePath = Path.Combine(outputFolderPath, reportDefinition.Name + ReportFileExtension);
         Console.WriteLine("Downloaded report '{0}' into file '{1}'", reportDefinition.Name, outputFilePath);
         File.WriteAllText(outputFilePath, reportContents);
     }
 }
Example #32
0
        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);
        }
        private void grantPriviledges_2()
        {
            NetworkCredential clientCredentials = new NetworkCredential("Test", "123", "Chathu-Nable");


            ReportingService2010SoapClient client = new ReportingService2010SoapClient();

            client.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
            client.ClientCredentials.Windows.ClientCredential          = clientCredentials;



            client.Open();
            TrustedUserHeader t = new TrustedUserHeader();


            Policy [] arrPolicies       = null;
            bool      doesInheritParent = false;

            client.GetPolicies(t, "/New Folder", out arrPolicies, out doesInheritParent);


            List <Policy> listPolicies = new List <Policy>();

            if (arrPolicies != null)
            {
                listPolicies = arrPolicies.ToList();
            }


            listPolicies.Add(
                new Policy()
            {
                Roles = new[] { new Role()
                                {
                                    Name = "Browser"
                                }, new Role()
                                {
                                    Name = "Content Manager"
                                } }, GroupUserName = "******"
            }
                );


            client.SetPolicies(t, "/New Folder", listPolicies.ToArray());



            /*
             *
             * Policy[] MyPolicyArr = new Policy[2];
             *
             *
             * Role[] MyRoles = new Role[3];
             *
             * Role browser = new Role();
             * browser.Name = "Browser";
             *
             * Role myReports = new Role();
             * myReports.Name = "My Reports";
             *
             * Role publisher = new Role();
             * publisher.Name = "Publisher";
             *
             * Role contentManager = new Role() { Name = "Content Manager" };
             *
             * MyRoles[0] = publisher;
             * MyRoles[1] = browser;
             * MyRoles[2] = contentManager;
             *
             *
             * MyPolicyArr[0] = new Policy() { GroupUserName = @"Chathu-Nable\Test", Roles = MyRoles };
             * MyPolicyArr[1] = new Policy() { GroupUserName = @"Chathu-Nable\Test2", Roles = MyRoles };
             *
             *
             * client.SetPolicies(t, "/New Folder", MyPolicyArr);
             *
             * //rs.SetPolicies("/SecurityTestFolder", MyPolicyArr);
             *
             */


            //MessageBox.Show(policies.Length + "") ;
        }