public void OnFinishedShouldPassDetailsAboutError()
        {
            // Arrange
            var result = default(FinishedEventArgs?);
            var code   = _fixture.Create <int>();
            var doc    = new Mock <ISettings>().Object;

            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, runtimeIdentifier: null)
            {
                FinishedAction = eventArgs =>
                {
                    result = eventArgs;
                },
            };

            var sut = new PdfProcessor(configuration, _module.Object)
            {
                ProcessingDocument = doc,
            };

            // Act
            sut.OnFinished(new IntPtr(1), code);

            // Assert
            using (new AssertionScope())
            {
                result !.Document.Should().Be(doc);
                result !.Success.Should().Be(code == 1);
            }
        }
        public void OnProgressChangedShouldPassDetailsAboutError()
        {
            // Arrange
            var progressDescription = _fixture.Create <string>();

            _module.Setup(m => m.GetProgressDescription(It.IsAny <IntPtr>()))
            .Returns(progressDescription);

            var result = default(ProgressChangedEventArgs?);
            var doc    = new Mock <ISettings>().Object;

            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, runtimeIdentifier: null)
            {
                ProgressChangedAction = eventArgs =>
                {
                    result = eventArgs;
                },
            };

            var sut = new PdfProcessor(configuration, _module.Object)
            {
                ProcessingDocument = doc,
            };

            // Act
            sut.OnProgressChanged(new IntPtr(1));

            // Assert
            using (new AssertionScope())
            {
                result !.Document.Should().Be(doc);
                result !.Description.Should().Be(progressDescription);
            }
        }
        public void RegisterEventsShouldRegisterProgressChangedCallbackWhenSpecified()
        {
            // Arrange
            _module.Setup(m => m.SetProgressChangedCallback(It.IsAny <IntPtr>(), It.IsAny <VoidCallback>()));

            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, runtimeIdentifier: null)
            {
                ProgressChangedAction = _ => { },
            };

            var sut = new PdfProcessor(configuration, _module.Object);

            // Act
            sut.RegisterEvents(new IntPtr(12));

            // Assert
            using (new AssertionScope())
            {
                _module.Verify(
                    m =>
                    m.SetProgressChangedCallback(
                        It.IsAny <IntPtr>(),
                        It.IsAny <VoidCallback>()),
                    Times.Once);
            }
        }
        public void OnWarningShouldPassDetailsAboutError()
        {
            // Arrange
            var result       = default(WarningEventArgs?);
            var errorMessage = _fixture.Create <string>();
            var doc          = new Mock <ISettings>().Object;

            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, runtimeIdentifier: null)
            {
                WarningAction = eventArgs =>
                {
                    result = eventArgs;
                },
            };

            var sut = new PdfProcessor(configuration, _module.Object)
            {
                ProcessingDocument = doc,
            };

            // Act
            sut.OnWarning(new IntPtr(1), errorMessage);

            // Assert
            using (new AssertionScope())
            {
                result !.Document.Should().Be(doc);
                result !.Message.Should().Be(errorMessage);
            }
        }
Ejemplo n.º 5
0
        private Container ConfigureIoC(IAppBuilder app, HttpConfiguration httpConfiguration)
        {
            var container = new Container();

            app.Use(async(_, next) =>
            {
                using (AsyncScopedLifestyle.BeginScope(container))
                {
#pragma warning disable CC0031 // Check for null before calling a delegate
#pragma warning disable MA0004 // Use .ConfigureAwait(false)
                    await next();
#pragma warning restore MA0004 // Use .ConfigureAwait(false)
#pragma warning restore CC0031 // Check for null before calling a delegate
                }
            });

            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
            container.RegisterSingleton <IHtmlGenerator, SmallHtmlGenerator>();
            container.RegisterSingleton <IHtmlToPdfDocumentGenerator, HtmlToPdfDocumentGenerator>();
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);
            container.RegisterInstance(configuration);
            container.RegisterSingleton <IWkHtmlToXEngine, WkHtmlToXEngine>();
            container.RegisterSingleton <IPdfConverter, PdfConverter>();
            container.RegisterInitializer <IWkHtmlToXEngine>(e => e.Initialize());
            container.RegisterWebApiControllers(httpConfiguration);

            httpConfiguration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
            return(container);
        }
Ejemplo n.º 6
0
        private static async Task Main()
        {
            var htmlToPdfGenerator = new HtmlToPdfDocumentGenerator(new SmallHtmlGenerator());
            var configuration      = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);

            using (var engine = new WkHtmlToXEngine(configuration))
            {
                engine.Initialize();
                var doc = htmlToPdfGenerator.Generate();

                if (!Directory.Exists("files"))
                {
                    Directory.CreateDirectory("files");
                }

                var converter = new PdfConverter(engine);
#pragma warning disable SEC0112 // Path Tampering Unvalidated File Path
#pragma warning disable SCS0018 // Potential Path Traversal vulnerability was found where '{0}' in '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'.
#pragma warning disable CC0022  // Should dispose object
                using var stream = new FileStream(
                          Path.Combine("Files", $"{DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture)}.pdf"),
                          FileMode.Create);
#pragma warning restore CC0022  // Should dispose object
#pragma warning restore SCS0018 // Potential Path Traversal vulnerability was found where '{0}' in '{1}' may be tainted by user-controlled data from '{2}' in method '{3}'.
#pragma warning restore SEC0112 // Path Tampering Unvalidated File Path
                var converted = await converter.ConvertAsync(doc, _ => stream, CancellationToken.None).ConfigureAwait(false);

                Console.WriteLine(converted);
            }

            Console.ReadKey();
        }
Ejemplo n.º 7
0
        public EngineTest()
        {
            _configuration            = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);
            _libraryLoaderMock        = new Mock <ILibraryLoader>();
            _libraryLoaderFactoryMock = new Mock <ILibraryLoaderFactory>();
            _libraryLoaderFactoryMock
            .Setup(l => l.Create(It.IsAny <WkHtmlToXConfiguration>()))
            .Returns(_libraryLoaderMock.Object);

            _pdfModuleMock    = new Mock <IWkHtmlToPdfModule>();
            _pdfProcessorMock = new Mock <IPdfProcessor>();
            _pdfProcessorMock.SetupGet(p => p.WkHtmlToPdfModule)
            .Returns(_pdfModuleMock.Object);

            _imageModuleMock    = new Mock <IWkHtmlToImageModule>();
            _imageProcessorMock = new Mock <IImageProcessor>();
            _imageProcessorMock.SetupGet(p => p.WkHtmlToImageModule)
            .Returns(_imageModuleMock.Object);

            _sut = new WkHtmlToXEngine(
                _configuration,
                _libraryLoaderFactoryMock.Object,
                _pdfProcessorMock.Object,
                _imageProcessorMock.Object);
        }
Ejemplo n.º 8
0
        public ILibraryLoader Create(
            WkHtmlToXConfiguration wkHtmlToXConfiguration)
        {
            switch (wkHtmlToXConfiguration.PlatformId)
            {
            case (int)PlatformID.MacOSX:
                return(new LibraryLoaderOsx());

            case (int)PlatformID.Unix:
            // Legacy mono value. See https://www.mono-project.com/docs/faq/technical/
            case 128:
                if (!wkHtmlToXConfiguration.RuntimeIdentifier.HasValue)
                {
                    throw new InvalidLinuxRuntimeIdentifierException();
                }

                return(new LibraryLoaderLinux(wkHtmlToXConfiguration.RuntimeIdentifier.Value));

            case (int)PlatformID.Win32NT:
            case (int)PlatformID.Win32S:
            case (int)PlatformID.Win32Windows:
            case (int)PlatformID.WinCE:
            case (int)PlatformID.Xbox:
                return(new LibraryLoaderWindows());

            default:
                throw new InvalidPlatformIdentifierException();
            }
        }
Ejemplo n.º 9
0
        public static void Initialize()
        {
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);

            Engine?.Dispose();
            Engine = new WkHtmlToXEngine(configuration);
            Engine.Initialize();
        }
Ejemplo n.º 10
0
        public ImageProcessorTest()
        {
            _fixture = new Fixture();
            _module  = new Mock <IWkHtmlToImageModule>();
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);

            _sut = new ImageProcessor(configuration, _module.Object);
        }
Ejemplo n.º 11
0
        private void InitializeContainer()
        {
            _container.RegisterSingleton <IHtmlGenerator, SmallHtmlGenerator>();
            _container.RegisterSingleton <IHtmlToPdfDocumentGenerator, HtmlToPdfDocumentGenerator>();
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);

            _container.RegisterInstance(configuration);
            _container.RegisterSingleton <IWkHtmlToXEngine, WkHtmlToXEngine>();
            _container.RegisterSingleton <IPdfConverter, PdfConverter>();
            _container.RegisterInitializer <IWkHtmlToXEngine>(e => e.Initialize());
        }
Ejemplo n.º 12
0
        public void GetModuleShouldThrowWhenLinuxPlatformIdAndNotKnownRuntimeIdentifierPassed()
        {
            // Arrange
            var wkHtmlToXConfiguration = new WkHtmlToXConfiguration((int)PlatformID.Unix, null);

            // ReSharper disable once AssignmentIsFullyDiscarded
#pragma warning disable IDISP004 // Don't ignore created IDisposable.
            Action action = () => _ = _sut.Create(wkHtmlToXConfiguration);
#pragma warning restore IDISP004 // Don't ignore created IDisposable.

            // Act & Assert
            action.Should().Throw <InvalidLinuxRuntimeIdentifierException>();
        }
Ejemplo n.º 13
0
        public void CreateShouldReturnCorrectLoaderAndRuntimeIdentifierPassed(
            int platformId,
            WkHtmlToXRuntimeIdentifier?runtimeIdentifier,
            Type type)
        {
            // Arrange
            var wkHtmlToXConfiguration = new WkHtmlToXConfiguration(platformId, runtimeIdentifier);

            // Act
            using var result = _sut.Create(wkHtmlToXConfiguration);

            // Assert
            result.Should().BeOfType(type);
        }
Ejemplo n.º 14
0
        public void ShouldThrowExceptionWhenNullPassedInModuleConstructor()
        {
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);

#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.

            // ReSharper disable once AssignmentIsFullyDiscarded
#pragma warning disable MA0003   // Name parameter
#pragma warning disable IDISP004 // Don't ignore created IDisposable.
            Action action = () => _ = new ImageProcessor(configuration, null);
#pragma warning restore IDISP004 // Don't ignore created IDisposable.
#pragma warning restore MA0003   // Name parameter
#pragma warning restore CS8625   // Cannot convert null literal to non-nullable reference type.

            // Act & Assert
            action.Should().Throw <ArgumentNullException>();
        }
Ejemplo n.º 15
0
        public static void Register(HttpConfiguration config)
        {
            if (config is null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            // Web API configuration and services
#pragma warning disable CA2000   // Dispose objects before losing scope
#pragma warning disable IDISP001 // Dispose created.
            var container = new Container();
#pragma warning restore IDISP001 // Dispose created.
#pragma warning restore CA2000   // Dispose objects before losing scope
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            // Register your types, for instance using the scoped lifestyle:
            container.RegisterSingleton <IHtmlGenerator, SmallHtmlGenerator>();
            container.RegisterSingleton <IHtmlToPdfDocumentGenerator, HtmlToPdfDocumentGenerator>();
            var configuration = new WkHtmlToXConfiguration((int)Environment.OSVersion.Platform, null);
            container.RegisterInstance(configuration);
            container.RegisterSingleton <IWkHtmlToXEngine, WkHtmlToXEngine>();
            container.RegisterSingleton <IPdfConverter, PdfConverter>();
            container.RegisterInitializer <IWkHtmlToXEngine>(e => e.Initialize());

            // This is an extension method from the integration package.
            container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

            container.Verify();

            GlobalConfiguration.Configuration.DependencyResolver =
                new SimpleInjectorWebApiDependencyResolver(container);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });
        }