Ejemplo n.º 1
0
        private async Task <int?> GetOngoingRequestCountAsync([NotNull] Channel channel,
                                                              [NotNull] string serviceName)
        {
            try
            {
                _logger.LogDebug("Getting load report from {serviceName} at {channel}...",
                                 serviceName, channel);

                var loadRequest = new LoadReportRequest
                {
                    ServiceName = serviceName
                };

                LoadReportingGrpc.LoadReportingGrpcClient loadClient =
                    new LoadReportingGrpc.LoadReportingGrpcClient(channel);

                LoadReportResponse loadReportResponse =
                    await loadClient.ReportLoadAsync(loadRequest);

                return(loadReportResponse.ServerStats.CurrentRequests);
            }
            catch (Exception e)
            {
                _logger.LogDebug(e, "Error getting load report from {serviceName}: {errorMessage}",
                                 serviceName, e.Message);
                return(null);
            }
        }
Ejemplo n.º 2
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);
        }
Ejemplo n.º 3
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);
        }
        private async Task <bool> TryAddLoadReport(
            [NotNull] ServiceLocation serviceLocation,
            TimeSpan workerResponseTimeout,
            [NotNull] ConcurrentBag <QualifiedService> loadReportsByService)
        {
            Channel channel = GetChannel(serviceLocation);

            try
            {
                // Check for health first, it might be that the process is running but we have not
                // started it.
                if (!await IsHealthy(serviceLocation, channel, workerResponseTimeout))
                {
                    return(false);
                }

                LoadReportResponse loadReportResponse =
                    await GetLoadReport(serviceLocation, channel, workerResponseTimeout);

                ProcessUtils.EnsureThreadIdInName();

                if (loadReportResponse.ServerStats.RequestCapacity == 0)
                {
                    _logger.LogDebug(
                        "Service location {serviceLocation} reports 0 capacity. It is ignored.",
                        serviceLocation);

                    return(false);
                }

                var qualifiedLocation =
                    new QualifiedService(serviceLocation, loadReportResponse.ServerStats)
                {
                    KnownLoadRate = loadReportResponse.KnownLoadRate
                };

                loadReportsByService.Add(qualifiedLocation);

                return(true);
            }
            catch (TimeoutException)
            {
                _logger.LogDebug(
                    "Service location {serviceLocation} took longer than {timeout}s. It is ignored.",
                    serviceLocation, workerResponseTimeout.TotalSeconds);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e,
                                   "Error checking service health / load report for {serviceLocation}",
                                   serviceLocation);

                _lastException = e;
            }

            return(false);
        }
        public override Task <LoadReportResponse> ReportLoad(LoadReportRequest request,
                                                             ServerCallContext context)
        {
            var result      = new LoadReportResponse();
            var serverStats = new ServerStats();

            result.ServerStats = serverStats;

            try
            {
                if (!_loadByService.TryGetValue(request.ServiceName, out IServiceLoad currentLoad))
                {
                    // Unknown service;
                    return(Task.FromException <LoadReportResponse>(
                               new RpcException(new Status(StatusCode.OutOfRange,
                                                           $"Service name {request.ServiceName} not found."))));
                }

                if (currentLoad == null)
                {
                    // Unknown load or unknown service;
                    return(Task.FromException <LoadReportResponse>(
                               new RpcException(new Status(StatusCode.OutOfRange,
                                                           $"Service {request.ServiceName} has no load."))));
                }

                result.TimestampTicks = currentLoad.ReportStart.Ticks;
                result.KnownLoadRate  = currentLoad.KnownLoadRate;

                serverStats.RequestCapacity   = currentLoad.ProcessCapacity;
                serverStats.CurrentRequests   = currentLoad.CurrentProcessCount;
                serverStats.ServerUtilization = currentLoad.ServerUtilization;

                currentLoad.Reset();
            }
            catch (Exception e)
            {
                var rpcException = new RpcException(
                    new Status(StatusCode.Internal, e.ToString()), e.Message);

                return(Task.FromException <LoadReportResponse>(rpcException));
            }

            return(Task.FromResult(result));
        }
        private static async Task <LoadReportResponse> GetLoadReport(
            [NotNull] ServiceLocation serviceLocation,
            Channel channel,
            TimeSpan timeout)
        {
            var loadRequest = new LoadReportRequest
            {
                Scope       = serviceLocation.Scope,
                ServiceName = serviceLocation.ServiceName
            };

            LoadReportingGrpc.LoadReportingGrpcClient loadClient =
                new LoadReportingGrpc.LoadReportingGrpcClient(channel);

            LoadReportResponse loadReportResponse = await TaskUtils.TimeoutAfter(
                GetLoadReport(loadClient, loadRequest), timeout);

            return(loadReportResponse);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// step 1
        /// </summary>
        protected void LoadReport(ReportRequest request, ref ReportExecuteResult result)
        {
            if (string.IsNullOrEmpty(request.Path))
            {
                throw new ReportException("Please set ReportPath to execute.");
            }
            try
            {
                if (!string.IsNullOrEmpty(request.SessionId))
                {
                    try
                    {
                        if (request.Reset)
                        {
                            var r = ReportClient.ResetExecutionAsync(new ResetExecutionRequest()).GetAwaiter().GetResult();
                            result.SessionId = r.executionInfo.ExecutionID;
                        }
                        ReportClient.ExecutionHeader.ExecutionID = request.SessionId;
                        var rr = ReportClient.GetExecutionInfoAsync(new GetExecutionInfoRequest()).GetAwaiter().GetResult();
                    }
                    catch { request.SessionId = null; }
                }
                if (string.IsNullOrEmpty(request.SessionId))
                {
                    LoadReportRequest  request0 = new LoadReportRequest(request.Path, null);
                    LoadReportResponse response = ReportClient.LoadReportAsync(request0).GetAwaiter().GetResult();

                    try
                    {
                        var match = VersionRegex.Match(response.ServerInfoHeader.ReportServerVersion);
                        if (match.Success)
                        {
                            Versions.TryAdd(this.ReportSettings.ReportServer, Version.Parse(match.Result("$1")));
                        }
                    }
                    catch { }


                    result.ParametersRequired = response.executionInfo.ParametersRequired;
                    var dict = new Dictionary <string, string>(response.executionInfo.Parameters.Length);
                    if (response.executionInfo.Parameters.Length > 0)
                    {
                        foreach (var p in response.executionInfo.Parameters)
                        {
                            if (p.DefaultValues != null && p.DefaultValues.Length > 0)
                            {
                                dict[p.Name] = p.DefaultValues.SingleOrDefault();
                            }
                            if (request.Parameters.ContainsKey(p.Name))
                            {
                                dict[p.Name] = request.Parameters[p.Name];
                            }
                        }
                    }
                    request.Parameters = dict;
                    result.SessionId   = request.SessionId = response.executionInfo.ExecutionID;
                    //ReportClient.ToggleItemAsync()
                    SetParameters(request, result);
                }
            }
            catch (Exception ex)
            {
                throw new ReportException("LoadReport error: " + ex.Message, ex);
            }
        }