ngs-doo / TemplaterExamples

Creating reports in .NET and Java
https://templater.info
The Unlicense
48 stars 27 forks source link

CORS #54

Open sergook opened 2 years ago

sergook commented 2 years ago

The TemplateServer doesn't support CORS. I added following lines in Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
             {
                 options.AddDefaultPolicy(
                     policy =>
                     {
                         policy
                         .WithOrigins("http://localhost:3000", "http://localhost:3001")
                         .AllowAnyHeader()
                         .AllowAnyMethod();
                     });
             });
            services.AddMvc(options => options.EnableEndpointRouting = false);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseCors();
            app.UseMvc();
        }

It works well on Windows, but it dosn't works as expected in Docker container. Then I tried to run modified TemplateServer in Docker container with the following Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk AS build

# copy csproj and restore as distinct layers
WORKDIR /source
COPY TemplaterServer.sln .
COPY Advanced/TemplaterServer/*.csproj ./Advanced/TemplaterServer/
RUN dotnet restore

# copy everything else and build app

COPY Advanced/TemplaterServer/. ./Advanced/TemplaterServer/
WORKDIR /source/Advanced/TemplaterServer
#RUN dotnet publish -c release -o /app --no-restore
RUN dotnet publish -c release -o /app

# final stage/image

FROM mcr.microsoft.com/dotnet/aspnet
WORKDIR /app
COPY --from=build /app ./
COPY dotnet-install.sh ./
RUN apt update && apt upgrade
RUN yes | apt install curl
RUN yes | apt install libc6-dev
RUN yes | apt install libgdiplus
RUN ./dotnet-install.sh --architecture x64 --install-dir /usr/share/dotnet/ --runtime aspnetcore --version 3.1.0
ENTRYPOINT ["dotnet", "TemplaterServer.dll"]
docker build --pull -t templateserver .
docker run --rm -it -p 8000:80 templateserver

It runs successfully, but CORS doesn't work. Also there is issues in the interface of the web-page. It doesn't switch between json examples and doesn't process the templates.

What might be the reason of that? Is the way to add CORS support in java version of the TemplateServer?

zapov commented 2 years ago

This examples are meant to show how you can setup Templater via http. Not to be production quality implementations of it.

I think whenever I made something more elaborate, it just confused some people wanting to learn how to use Templater. So its not all that important to me that it has CORS.

zapov commented 2 years ago

As for this web-interface problem... can you be a bit more specific? App actually has two mode of operations, without JS and with JS For me it works both without JS and with JS The only problem I'm aware if you start using it without JS and then switch on JS that it doesn't really work unless you reload it (reloading from initial page is fine)

sergook commented 2 years ago

I build and run docker container with the Dockerfile (from the above message):

PS C:\sergook\TemplaterExamples-master> docker build --pull -t templateserver .
[+] Building 4.3s (23/23) FINISHED
 => [internal] load build definition from Dockerfile                                                                                                                 0.0s 
 => => transferring dockerfile: 916B                                                                                                                                 0.0s 
 => [internal] load .dockerignore                                                                                                                                    0.0s 
 => => transferring context: 2B                                                                                                                                      0.0s 
 => [internal] load metadata for mcr.microsoft.com/dotnet/aspnet:latest                                                                                              0.4s 
 => [internal] load metadata for mcr.microsoft.com/dotnet/sdk:latest                                                                                                 0.4s 
 => [stage-1 1/9] FROM mcr.microsoft.com/dotnet/aspnet@sha256:55973d59f8ffd46af48ee247c847ec97ab04ae12d09f178720d615a62faa363c                                       0.0s 
 => [build 1/8] FROM mcr.microsoft.com/dotnet/sdk@sha256:2d4a7a352d5a9b9acd3b4bacb1d621a2eeeaf7ea8ea54a081736604d683f359a                                            0.0s 
 => [internal] load build context                                                                                                                                    0.1s 
 => => transferring context: 785.28kB                                                                                                                                0.1s 
 => CACHED [build 3/8] COPY TemplaterServer.sln .                                                                                                                    0.0s 
 => CACHED [build 4/8] COPY Advanced/TemplaterServer/*.csproj ./Advanced/TemplaterServer/                                                                            0.0s 
 => CACHED [build 5/8] RUN dotnet restore                                                                                                                            0.0s 
 => [build 6/8] COPY Advanced/TemplaterServer/. ./Advanced/TemplaterServer/                                                                                          0.2s 
 => [build 7/8] WORKDIR /source/Advanced/TemplaterServer                                                                                                             0.0s 
 => [build 8/8] RUN dotnet publish -c release -o /app                                                                                                                3.0s 
 => CACHED [stage-1 2/9] WORKDIR /app                                                                                                                                0.0s 
 => CACHED [stage-1 3/9] COPY --from=build /app ./                                                                                                                   0.0s 
 => CACHED [stage-1 4/9] COPY dotnet-install.sh ./                                                                                                                   0.0s 
 => CACHED [stage-1 5/9] RUN apt update && apt upgrade                                                                                                               0.0s 
 => CACHED [stage-1 6/9] RUN yes | apt install curl                                                                                                                  0.0s 
 => CACHED [stage-1 7/9] RUN yes | apt install libc6-dev                                                                                                             0.0s 
 => CACHED [stage-1 8/9] RUN yes | apt install libgdiplus                                                                                                            0.0s 
 => CACHED [stage-1 9/9] RUN ./dotnet-install.sh --architecture x64 --install-dir /usr/share/dotnet/ --runtime aspnetcore --version 3.1.0                            0.0s 
 => exporting to image                                                                                                                                               0.0s 
 => => exporting layers                                                                                                                                              0.0s 
 => => writing image sha256:d6cc0816bb45bdbb0e8192f6feaca33d87eb7ab5a893dccb475b656bed0fc5c5                                                                         0.0s 
 => => naming to docker.io/library/templateserver                                                                                                                    0.0s 

Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
PS C:\sergook\TemplaterExamples-master> docker run --rm -it -p 8000:80 templateserver
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.ArgumentException: Unable to find LibreOffice on the system. Please explicitly specify it via: -libreoffice=C:/Program Files (x86)/LibreOffice 6.4/program/soffice.exe
   at TemplaterServer.src.LibreOffice..ctor(String[] args) in /source/Advanced/TemplaterServer/src/LibreOffice.cs:line 51
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
   at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
   at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
   at TemplaterServer.SharedResource..ctor(String[] args) in /source/Advanced/TemplaterServer/src/SharedResource.cs:line 43
warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
      Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[58]
      Creating key {78f8b5c8-aa5d-4ca9-bbef-8c94c3591c7b} with creation date 2022-08-03 12:32:40Z, activation date 2022-08-03 12:32:40Z, and expiration date 2022-11-01 12:32:40Z.
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {78f8b5c8-aa5d-4ca9-bbef-8c94c3591c7b} may be persisted to storage in unencrypted form.
info: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[39]
      Writing data to file '/root/.aspnet/DataProtection-Keys/key-78f8b5c8-aa5d-4ca9-bbef-8c94c3591c7b.xml'.
Hosting environment: Production
Content root path: /app
Now listening on: http://[::]:80
Application started. Press Ctrl+C to shut down.

When I open the page http://localhost:8000/ the server generates following log:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:8000/
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "Get", controller = "Templater"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Get(System.String) 
on controller TemplaterServer.TemplaterController (TemplaterServer).
info: Microsoft.AspNetCore.Mvc.Infrastructure.FileContentResultExecutor[2]
      Executing Microsoft.AspNetCore.Mvc.FileContentResult, sending file with download name '' ...
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action TemplaterServer.TemplaterController.Get (TemplaterServer) in 77.3893ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 142.1982ms 200 text/html; charset=UTF-8
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:8000/favicon.ico
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "Get", controller = "Templater"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Get(System.String) 
on controller TemplaterServer.TemplaterController (TemplaterServer).
info: Microsoft.AspNetCore.Mvc.Infrastructure.FileContentResultExecutor[2]
      Executing Microsoft.AspNetCore.Mvc.FileContentResult, sending file with download name '' ...
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action TemplaterServer.TemplaterController.Get (TemplaterServer) in 1.5104ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 2.938ms 200 text/html; charset=UTF-8

When I try to switch from the first template (BeerList.docx) to the second (Benchmark.xlsx) by pushing the second button in the Templates list, the server generates following log:

info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
      Request starting HTTP/1.1 GET http://localhost:8000/examples/benchmark.xlsx.json
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[3]
      Route matched with {action = "Examples", controller = "Templater"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult Examples(System.String) on controller TemplaterServer.TemplaterController (TemplaterServer).
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
      Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker[2]
      Executed action TemplaterServer.TemplaterController.Examples (TemplaterServer) in 4.8131ms
info: Microsoft.AspNetCore.Hosting.Diagnostics[2]
      Request finished in 9.1483ms 404

and the text in the text field "Put your JSON here" remains the same from the first template (BeerList):

{
  "user": {
    "name": "Bob Barley",
    "age": "42"
  },
  "beers": [
    {
      "name": "Rare Bourbon County Brand Stout",
      "brewery": "Goose Island Beer Co.",
      "type": "Stout",
. . . 

The only change on the page is new text on two green buttons "Create... Benchmark.xlsx"/ "Download Benchmark.xlsx". So, only the first template works as expected - generate the final document in docx and pdf. Other templates return just initial template document when press "Create... Benchmark.xlsx" and "Download Benchmark.xlsx" As I understand the JSON of the first template always used to create all other documents.

zapov commented 2 years ago

When I try this without Docker it works as expected for me. Does it work as expected for you when you do

dotnet run TemplaterServer.csproj

I can look into your Docker problem, but this is not really related to Templater or this example as it works without Docker just fine