Environment Configuration – Aspose.SVG for .NET

The setting of environment configuration is used for various purposes. For example, when you develop an application, you will definitely demand some configuration that can range from runtime service or handle any web requests from the application to injecting custom themes.

In this guide, you will learn how to create various configurations and adapt them to the different environments where the application runs. This can be a custom theme, a runtime service or a web request network service.

The Aspose.Svg.Services namespace contains a set of interfaces for separated services implementations. This article considers different types of environment configuration services such as User Agent Service, Runtime Service, and Network Service. Aspose.SVG for .NET provides the Configuration class that can be used to set the environment where the application is running.

You can download the complete examples and data files from GitHub. You find out about downloading from GitHub and running examples from the How to Run the Examples section.

User Agent Service

The User Agent Service allows you to specify a custom user stylesheet, a primary character set for the document, language and fonts settings. You can select your custom style information for a particular document and provide as little or as many environment configuration changes as needed.

The IUserAgentService interface describes a user agent environment.

Consider an example that illustrates UserStyleSheet, CharSet and FontsSettings properties applying:

 1using System.IO;
 2using Aspose.Svg;
 3using Aspose.Svg.Services;
 4using Aspose.Svg.Converters;
 5using Aspose.Svg.Saving;
 6...
 7
 8   // Prepare SVG code and save it to a file
 9   var code = "<svg xmlns=\"https://www.w3.org/2000/svg\">\r\n" +
10              "    <circle cx=\"40\" cy=\"80\" r=\"30\" />\r\n" +
11              "    <text x=\"80\" y=\"100\">Aspose.SVG</text>\r\n" +
12              "</svg>\r\n";
13
14   File.WriteAllText(Path.Combine(OutputDir, "user-agent.svg"), code);
15
16   // Create an instance of Configuration
17   using (var configuration = new Configuration())
18   {
19       // Get the IUserAgentService
20       var userAgentService = configuration.GetService<IUserAgentService>();
21
22       // Set a custom style parameters for the "circle" and "text" elements
23       userAgentService.UserStyleSheet = "circle { fill:silver; }\r\n" +
24                                         "text { fill:DarkCyan; font-size:3em; }\r\n";
25
26       // Set ISO-8859-1 encoding to parse a document
27       userAgentService.CharSet = "ISO-8859-1";
28
29       // Set a custom font folder path
30       userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir + "fonts"));
31
32       // Initialize an SVG document with specified configuration
33       using (var document = new SVGDocument(Path.Combine(OutputDir, "user-agent.svg"), configuration))
34       {
35           // Convert SVG to PDF
36           Converter.ConvertSVG(document, new PdfSaveOptions(), Path.Combine(OutputDir, "user-agent.pdf"));
37       }
38   }

The figure illustrates the result of User Agent Service applying (b) to the source “user-agent.svg” file (a).

Text “Rendering of “user-agent.svg” and “user-agent.pdf” files”

Runtime Service

When planning to run your application, you might require a runtime service configuration. This service gives you control over the lifetime of the internal processes. For instance, using IRuntimeService you can specify timeouts for JavaScripts. It is important to have such a timeout in case if a script contains an endless loop. The next code snippet demonstrates how to use timeouts.

 1using System.IO;
 2using Aspose.Svg;
 3using Aspose.Svg.Services;
 4using Aspose.Svg.Converters;
 5using Aspose.Svg.Saving;
 6...
 7
 8    // Prepare SVG code and save it to a file
 9    var code = "<svg xmlns=\"https://www.w3.org/2000/svg\">\r\n" +
10               "    <script> while(true) {} </script>\r\n" +
11               "    <circle cx=\"40\" cy=\"80\" r=\"30\" />\r\n" +
12               "</svg>\r\n";
13
14    File.WriteAllText(Path.Combine(OutputDir, "runtime.svg"), code);
15
16    // Create an instance of Configuration
17    using (var configuration = new Configuration())
18    {
19        // Limit JS execution time to 5 seconds
20        var runtimeService = configuration.GetService<IRuntimeService>();
21        runtimeService.JavaScriptTimeout = TimeSpan.FromSeconds(5);
22
23        // Initialize an SVG document with specified configuration
24        using (var document = new SVGDocument(Path.Combine(OutputDir, "runtime.svg"), configuration))
25        {
26            // Convert SVG to PNG
27            Converter.ConvertSVG(document, new ImageSaveOptions(), Path.Combine(OutputDir, "runtime.png"));
28        }
29    }

The JavaScriptTimeout property sets TimeSpan, which limits JavaScript execution time. If the script is executed longer than provided TimeSpan, it will be cancelled. The default value is 1 minute.

Network Service

Modern network environments generate a significant amount of security events and log data via network routers and switches, servers, anti-malware systems, and so on.

Aspose.SVG for .Net offers the INetworkService that is envisioned as a solution to help manage and analyze all this information. Service allows you to control all incoming/outcoming traffic and implement your custom message handlers. It can be used for different purposes, such as creating a custom caching mechanism, tracing/logging request messages, etc.

Create a Custom Message Handler

Aspose.SVG for .NET offers functionality for custom message handlers creating. Let’s develop a simple custom handler that logs information about unreachable resources. Take the following steps:

  1. Use the necessary Namespace, which is the Aspose.Svg.Net. This Namespace is presented by classes and interfaces, which are responsible for helping easy network processing.
  2. To create a custom message handler, you need to define your own class that will be derived from the MessageHandler class. We construct a LogMessageHandler class.
  3. Override the Invoke() method of the MessageHandler class to implement the custom message handler behaviour.

The following example demonstrates how to create LogMessageHandler to log information about unreachable resources.

 1using Aspose.Svg.Net;
 2using System.Collections.Generic;
 3using System.Net;
 4...
 5
 6    // Define LogMessageHandler that is derived from the MessageHandler class
 7    public class LogMessageHandler : MessageHandler
 8    {
 9        private List<string> errors = new List<string>();
10
11        public List<string> ErrorMessages
12        {
13            get { return errors; }
14        }
15
16        // Override the Invoke() method
17        public override void Invoke(INetworkOperationContext context)
18        {
19            // Check whether response is OK
20            if (context.Response.StatusCode != HttpStatusCode.OK)
21            {
22                // Set error information
23                errors.Add(string.Format("File '{0}' Not Found", context.Request.RequestUri));
24            }
25
26            // Invoke the next message handler in the chain
27            Next(context);
28        }
29    }

For more information about custom message handlers creation, please see the chapter Message Handlers.

Use LogMessageHandler for logging information about unreachable resources

The following example demonstrates how to use the LogMessageHandler class for logging information about unreachable resources.

 1using System.IO;
 2using Aspose.Svg;
 3using Aspose.Svg.Services;
 4using Aspose.Svg.Converters;
 5using Aspose.Svg.Saving;
 6using Aspose.Svg.Net;
 7...
 8
 9    // Prepare SVG code and save it to a file
10    var code = "<svg xmlns=\"https://www.w3.org/2000/svg\">\r\n" +
11               "    <image href=\"https://docs.aspose.com/svg/images/drawing/park.jpg\" width=\"640px\" height=\"480px\" />\r\n" +
12               "    <image href=\"https://docs.aspose.com/svg/net/missing1.svg\" width=\"400px\" height=\"300px\" />\r\n" +
13               "    <image href=\"https://docs.aspose.com/svg/net/missing2.svg\" width=\"400px\" height=\"300px\" />\r\n" +
14               "</svg>\r\n";
15
16    File.WriteAllText(Path.Combine(OutputDir, "network.svg"), code);
17
18    // Create an instance of the Configuration class
19    using (var configuration = new Configuration())
20    {
21        // Add LogMessageHandler to the chain of existing message handlers for logging errors
22        var networkService = configuration.GetService<INetworkService>();
23        
24        var logHandler = new LogMessageHandler();
25        networkService.MessageHandlers.Add(logHandler);
26
27        // Initialize an SVG document with specified configuration
28        using (var document = new SVGDocument(Path.Combine(OutputDir, "network.svg"),  configuration))
29        {
30            // Convert SVG to PNG
31            Converter.ConvertSVG(document, new ImageSaveOptions(), Path.Combine(OutputDir, "network.png"));
32
33            // Print the List of ErrorMessages
34            foreach (string errorMessage in logHandler.ErrorMessages)
35            {
36                Console.WriteLine(errorMessage);
37            }
38        }
39    }

After the example run:

File 'https://docs.aspose.com/svg/net/missing1.svg' Not Found
File 'https://docs.aspose.com/svg/net/missing2.svg' Not Found

You can download the complete examples and data files from GitHub. About downloading from GitHub and running examples, you find out from the How to Run the Examples section.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.