ASP.net - An error has occurred when trying to initialize jsreport



  • Hello!

    I'm running a local server using IIS and Visual Studio 2017. The install versions of JSreport are as follows:

    <package id="jsreport.Binary" version="1.9.2" targetFramework="net462" />
    <package id="jsreport.Client" version="2.0.2" targetFramework="net462" />
    <package id="jsreport.Local" version="1.1.1" targetFramework="net462" />
    <package id="jsreport.Shared" version="1.0.1" targetFramework="net462" />
    <package id="jsreport.Types" version="1.8.5" targetFramework="net462" />

    Visual studio is running as administrator, and every folder in the project has "Full Control" permissions for iusr, iis_iusrs, my own login, etc.

    Interestingly enough, I'm using source control - a coworker has this running on their local machine with no issues. I've even come to copy the entire project file over my own, packages and all, and still no luck. My guess at this point is that there's something environment related going on, although I can't quite figure out what.

    In C#, the particular block of code that's failing is:

           string file_name = ReportName + System.DateTime.Now.Ticks.ToString() + ".pdf";
            var rs = JSReport.Service;
            var report = rs.RenderByNameAsync(ReportName, reportData).Result;
    

    The line of code that's throwing the error is actually the last, where it tries to retrieve the result. (var report = rs.RenderByNameAsync(ReportName, reportData).Result;)

    This is a stack trace of the error I'm receiving:

    Error rendering report: Error: An error occurred while trying to execute the command: at onCriticalError ([eval]:36106:25) at [eval]:36061:13 at tryCatcher ([eval]:9718:23) at Promise._settlePromiseFromHandler ([eval]:38241:31) at Promise._settlePromise ([eval]:38298:18) at Promise._settlePromise0 ([eval]:38343:10) at Promise._settlePromises ([eval]:38418:18) at Async._drainQueue ([eval]:4650:16) at Async._drainQueues ([eval]:4660:10) at Immediate.Async.drainQueues [as _onImmediate] ([eval]:4534:14) at processImmediate [as _immediateCallback] (timers.js:396:17) {"originalError":{}}(Original) Error: An error occurred while trying to start daemonized process: An error has occurred when trying to initialize jsreport.. at null.<anonymous> ([eval]:37276:13) at listener ([eval]:13761:10) at EventEmitter.emit ([eval]:13849:22) at onData ([eval]:85833:8) at Lazy.<anonymous> ([eval]:52268:13) at Lazy.<anonymous> ([eval]:52250:19) at emitTwo (events.js:87:13) at Lazy.emit (events.js:172:7) at Lazy.<anonymous> ([eval]:52251:22) at emitOne (events.js:77:13) at Lazy.emit (events.js:169:7) at yieldTo ([eval]:52358:18) at Function.<anonymous> ([eval]:52396:27) at Lazy.<anonymous> ([eval]:52364:21) at emitOne (events.js:77:13) at Lazy.emit (events.js:169:7) at Socket.<anonymous> ([eval]:52227:22) at emitNone (events.js:67:13) at Socket.emit (events.js:166:7) at emitReadable (_stream_readable.js:419:10) at emitReadable (_stream_readable.js:413:7) at readableAddChunk (_stream_readable.js:164:13) {}

    Does anyone have any ideas as to what exactly is going on here?

    Thanks!



  • Lets the first check if jsreport itself works...

    Please find on that server jsreport.exe in the temp folder. For me it is:
    c:\Users\janbl\AppData\Local\Temp\jsreport\dotnet\binary-default-1.9.2.0\

    Then open command line in that folder and type

    jsreport start --httpPort=5488
    

    Then open browser on localhost:5488, create a template and try to render it. Does it work?



  • Thanks for the response! We've installed jsreport using nuget packages - in the project, there only seems to be .dlls, no executable files.



  • The executable is extracted from the dll manifest during the first RenderByNameAsync call into the temp folder.
    Please try to search for jsreport.exe.. It must be there based on the error message you posted.



  • Strange, then - I'm doing a search for jsreport.exe, and finding nothing. I've tried running the search while the program hits those lines as well, and it returns nothing.



  • Hm, I cannot think about situation when you would see such error clearly produced by the jsreport.exe and not seeing it.

    You should see structure like this.

    0_1519826172304_upload-6c7d2d6b-ca9e-4b06-8462-bebf96696c79



  • Hm, yeah, I've done a search on the entire C:\ drive for jsreport.exe, with no results. This is after a clean and build as well, and running the code (with the same error.)



  • Could you please print somewhere this path? It should be found there.

    Console.WriteLine(Path.Combine(Path.GetTempPath(), "jsreport"));
    

    In case you don't use something like .Configure(cfg => cfg.TempDirectory = "something").



  • Sorry about disappearing for a few days!

    The path is C:\Windows\Temp. It requires admin access, which explains why it might not have appeared on searches. I ran jsreport.exe, and it works properly!



  • Ok, thanks. The things to try...

    Try to run this command

    echo hello > test.html
    jsreport.exe render --keepAlive --template.engine=handlebars --template.recipe=phantom-pdf --template.content=test.html --out=out.pdf
    

    Does this work?

    Perhaps changing the tempDirectory out from the Windows could help. This can be done in c# using:

    var rs = new LocalReporting()
    .Configure((cfg) => {                  
                        cfg.TempDirectory = Path.Combine(Directory.GetCurrentDirectory(), "jsreport", "temp");
                        return cfg;
                    })...
    


  • Here's the config for JSreport's we're using:

            JSReport.Service= new LocalReporting()
                .KillRunningJsReportProcesses()
                .UseBinary(JsReportBinary.GetBinary())
                .RunInDirectory(Path.Combine(Directory.GetCurrentDirectory(), "jsreport", "temp"))
                .Configure(cfg => cfg.AllowLocalFilesAccess().FileSystemStore().BaseUrlAsWorkingDirectory())
                .AsUtility()
                .Create();
    

    I tried changing the directory to what you posted. The application did not launch. It threw an error, telling me that access was denied to the path c:\windows\system32\inetsrv\jsreport\temp. Which makes sense, because there is no jsreport exe in there.

    I tried to then run it in the directory directly (.RunInDirectory(@"C:\Windows\Temp\jsreport"), and it threw a different error, pertaining to how it was unable to find the template. That also makes sense, because we've been running and keeping our jsreport files in the bin.



  • Thank you for more info. I spent now half day trying to figure out why the error message your provided doesn't include the actual error why the init failed.
    I found out that we swallow the inner error in one place. I was able to fix that and rebuilt jsreport.exe.

    Now I would like to ask you to test it if you find time. It would be great. To run it...

    Open c:\Windows\Temp\jsreport\dotnet\binary-default-1.9.2.0\. There you should see jsreport.exe.
    Download this exe and copy it there instead.
    Run you original again and paste it here. We should see more info.



  • Thank you so much! I really appreciate the work you're putting in for this.

    I placed it where you've directed, clean and rebuilt my project (even blew out the bin folder), and this is the error (still):

    Error: An error occurred while trying to execute the command: at onCriticalError ([eval]:36106:25) at [eval]:36061:13 at tryCatcher ([eval]:9718:23) at Promise._settlePromiseFromHandler ([eval]:38241:31) at Promise._settlePromise ([eval]:38298:18) at Promise._settlePromise0 ([eval]:38343:10) at Promise._settlePromises ([eval]:38418:18) at Async._drainQueue ([eval]:4650:16) at Async._drainQueues ([eval]:4660:10) at Immediate.Async.drainQueues [as _onImmediate] ([eval]:4534:14) at processImmediate [as _immediateCallback] (timers.js:396:17) {"originalError":{}}(Original) Error: An error occurred while trying to start daemonized process: An error has occurred when trying to initialize jsreport.. at null.<anonymous> ([eval]:37276:13) at listener ([eval]:13761:10) at EventEmitter.emit ([eval]:13849:22) at onData ([eval]:85833:8) at Lazy.<anonymous> ([eval]:52268:13) at Lazy.<anonymous> ([eval]:52250:19) at emitTwo (events.js:87:13) at Lazy.emit (events.js:172:7) at Lazy.<anonymous> ([eval]:52251:22) at emitOne (events.js:77:13) at Lazy.emit (events.js:169:7) at yieldTo ([eval]:52358:18) at Function.<anonymous> ([eval]:52396:27) at Lazy.<anonymous> ([eval]:52364:21) at emitOne (events.js:77:13) at Lazy.emit (events.js:169:7) at Socket.<anonymous> ([eval]:52227:22) at emitNone (events.js:67:13) at Socket.emit (events.js:166:7) at emitReadable (_stream_readable.js:419:10) at emitReadable (_stream_readable.js:413:7) at readableAddChunk (_stream_readable.js:164:13) {}



  • Could you please reach me on skype or gitter "pofider" ? It would get faster if we solve this realtime.
    Also would you be able to prepare a minimal project in which it fails for you? Just empty web app or something like that.



  • Certainly! Allow me a few moments to prepare the project, and I will contact you shortly. Thank you!



  • SOLVED/SOLUTION: As it turns out, my license key was improperly applied. I have it applied through my environment variable and it is currently working. Big thanks to Jan, who worked with me for hours on this!



  • Hi i'm facing the same issue. However earlier the same piece of code was working like a charm, below are the details.

    <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    </PropertyGroup>

    <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <LangVersion>7.2</LangVersion>
    </PropertyGroup>

    <ItemGroup>
    <PackageReference Include="jsreport.Binary" Version="1.10.0" />
    <PackageReference Include="jsreport.Client" Version="2.0.2" />
    <PackageReference Include="jsreport.Local" Version="1.1.2" />
    </ItemGroup>

    Code Snippet. The same i downloaded from your github repo.
    https://github.com/jsreport/jsreport-dotnet-example-consoleapp

    Running above app gives me an error.

    Also i have created a Web API project there also same error persist. Code snippet is below.

    Start Up file:

    public void ConfigureServices(IServiceCollection services)
    {
    services.AddNodeServices();
    services.AddSingleton<IConfiguration>(_config);
    services.AddMvcCore(opt =>
    {
    opt.OutputFormatters.RemoveType<TextOutputFormatter>();
    opt.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
    })
    .AddJsonFormatters() // Adding Json Formatters in Pipeline
    .AddDataAnnotations() // Always keep it in config for Model Validation
    .AddJsonOptions(opts =>
    {
    opts.SerializerSettings.ContractResolver = new DefaultContractResolver();
    opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    opts.SerializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
    opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    })
    .AddMvcOptions(opts =>
    {
    opts.RespectBrowserAcceptHeader = true;
    opts.ReturnHttpNotAcceptable = true;
    });
    }

    method to generate HTML TO PDF

    public static async Task<byte[]> Generate_PDFReport(string template, string headerTemplte, string footerTemplte, string content, string helper)
    {
    try
    {
    var runExePath = Path.Combine(Directory.GetCurrentDirectory(), "jsreport", "temp");
    var rs = new LocalReporting()
    .RunInDirectory(runExePath)
    .KillRunningJsReportProcesses()
    .Configure(cfg => cfg.AllowLocalFilesAccess().FileSystemStore().BaseUrlAsWorkingDirectory())
    .UseBinary(JsReportBinary.GetBinary()).AsWebServer().Create();

                await rs.StartAsync();
    
                var report = await rs.RenderAsync(new RenderRequest()
                {
                    Template = new Template()
                    {
                        Recipe = Recipe.PhantomPdf,
                        Engine = Engine.Handlebars,
                        Content = template,
                        Helpers = helper,
                        //XlsxTemplate = new XlsxTemplate {
                        //    Content = "",
                        //    Shortid = ""
                        //},
                        Phantom = new Phantom
                        {
                            Header = headerTemplte,
                            Footer = footerTemplte,
                            Orientation = PhantomOrientation.Portrait,
                            Format = PhantomFormat.A4,
                            BlockJavaScript = true,
                            Margin = MarginNew
                        }
                    },
                    Data = content
                });
                using (var ms = new MemoryStream())
                {
                    report.Content.CopyTo(ms);
                    byte[] byteContent = ms.ToArray();
    
                    await rs.KillAsync();
                    return byteContent;
                }
            }
            catch (Exception ex){ throw; }
        }
    

    EXceptions:-

    Win32Exception: Access is denied
    System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
    System.Diagnostics.Process.Start()
    jsreport.Local.Internal.BinaryProcess+<InnerExecute>d__18.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
    jsreport.Local.Internal.BinaryProcess+<ExecuteExe>d__17.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    jsreport.Local.Internal.LocalWebServerReportingService+<StartAsync>d__32.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Net_Core_Poc.PDFGenerator_jsReport+<Generate_PDFReport>d__1.MoveNext() in PDFGenerator_jsReport.cs

    •       catch (Exception ex){ throw; }
      

    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Net_Core_Poc_API.Controllers.PDFController+<Get_jsReportPDF>d__9.MoveNext() in PDFController.cs

    •       var bytesContent = await PDFGenerator_jsReport.Generate_PDFReport(htmlContent, "<div style='text-align:left'></div>", "<div style='text-align:center'>{#pageNum}</div>", jsonData, helper);
      

    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__12.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__10.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
    Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeInnerFilterAsync>d__14.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

    Show raw exception details

    System.ComponentModel.Win32Exception (0x80004005): Access is denied
    at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo)
    at System.Diagnostics.Process.Start()
    at jsreport.Local.Internal.BinaryProcess.<InnerExecute>d__18.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at jsreport.Local.Internal.BinaryProcess.<ExecuteExe>d__17.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
    at jsreport.Local.Internal.LocalWebServerReportingService.<StartAsync>d__32.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at Net_Core_Poc.PDFGenerator_jsReport.<Generate_PDFReport>d__1.MoveNext() in G:\RND\RnD_Solutions\Net_Core_Poc\PDFGenerator_jsReport.cs:line 68 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
    at Net_Core_Poc_API.Controllers.PDFController.<Get_jsReportPDF>d__9.MoveNext() in G:\RND\RnD_Solutions\Net_Core_Poc_API\Controllers\PDFController.cs:line 923
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__10.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeInnerFilterAsync>d__14.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeFilterPipelineAsync>d__17.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.<InvokeAsync>d__15.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
    --- End of stack trace from previous location where exception was thrown ---
    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()



  • I'm far less qualified than Jan to comment, but I'll give a few thoughts! If you error message is "Access is denied", then I would first try running the project as administrator. If that doesn't work, go to every place that jsreports will be accessing (temp folder, folder where you store templates, etc) and make sure the security allows access. If you're using IIS, then you'll have to grant full control to "IUSR" and "IIS_IUSRS"



  • Hi great help incredible. But things went the other way around.
    I can run the project irrespective of modes(admin/standard user), now i'm getting an error from the antivirus(Avast Free Ware) that i have installed on my workstation. But however if i unchecked the Checkbox to (Scan programs when executing, it's an option in the Avast antivirus dashbord) the code works like a charm.

    What I don't understand is that is it good practice to disable "Scan programs when executing," option in the antivirus. Coz when i disable the option, i can run the poc effortlessly. Vice versa is leading to a malware Detect error, avast antivirus recognizing .jsReport.exe as some maleware and removing it after clicking yes to remove.

    Also now im getting a popup saying its been submitted to Avast Lab, and soon will be hearing about it.



  • When i'm adding the jsReport.exe as a trusted file the code works great, seems like some issue on jsReport.exe thing.


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.