diff --git a/How to/Redis Cache/Controllers/PdfViewerController.cs b/How to/Redis Cache/Controllers/PdfViewerController.cs new file mode 100644 index 0000000..f7aa2d3 --- /dev/null +++ b/How to/Redis Cache/Controllers/PdfViewerController.cs @@ -0,0 +1,342 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Caching.Distributed; +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Configuration; +using Newtonsoft.Json; +using PDFViewerWebService; +using Syncfusion.EJ2.PdfViewer; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace RedisCache.Controllers +{ + [Route("[controller]")] + [ApiController] + public class PdfViewerController : ControllerBase + { + //Initialize the cache object   + private readonly IHostingEnvironment _hostingEnvironment; + public IMemoryCache _cache; + private IDistributedCache _dCache; + private IConfiguration _configuration; + private int _slidingTime = 0; + string path; + public PdfViewerController(IMemoryCache memoryCache, IHostingEnvironment hostingEnvironment, IDistributedCache cache, IConfiguration configuration) + { + _cache = memoryCache; + _dCache = cache; + _hostingEnvironment = hostingEnvironment; + _configuration = configuration; + path = _configuration["DOCUMENT_PATH"]; + //check the document path environment variable value and assign default data folder + //if it is null. + path = string.IsNullOrEmpty(path) ? Path.Combine(_hostingEnvironment.ContentRootPath, "Data") : Path.Combine(_hostingEnvironment.ContentRootPath, path); + } + + [HttpPost("Load")] + [Route("[controller]/Load")] +        //Post action for Loading the PDF documents   +        public IActionResult Load([FromBody] Dictionary jsonObject) + { + Console.WriteLine("Load called"); + //Initialize the PDF viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + MemoryStream stream = new MemoryStream(); + object jsonResult = new object(); + if (jsonObject != null && jsonObject.ContainsKey("document")) + { + if (bool.Parse(jsonObject["isFileName"])) + { + string documentPath = GetDocumentPath(jsonObject["document"]); + if (!string.IsNullOrEmpty(documentPath)) + { + byte[] bytes = System.IO.File.ReadAllBytes(documentPath); + stream = new MemoryStream(bytes); + } + else + { + string fileName = jsonObject["document"].Split(new string[] { "://" }, StringSplitOptions.None)[0]; + + if (fileName == "http" || fileName == "https") + { + WebClient WebClient = new WebClient(); + byte[] pdfDoc = WebClient.DownloadData(jsonObject["document"]); + stream = new MemoryStream(pdfDoc); + } + + else + { + return this.Content(jsonObject["document"] + " is not found"); + } + } + } + else + { + byte[] bytes = Convert.FromBase64String(jsonObject["document"]); + stream = new MemoryStream(bytes); + } + } + jsonResult = pdfviewer.Load(stream, jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + + [AcceptVerbs("Post")] + [HttpPost("Bookmarks")] + [Route("[controller]/Bookmarks")] +        //Post action for processing the bookmarks from the PDF documents +        public IActionResult Bookmarks([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + var jsonResult = pdfviewer.GetBookmarks(jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + + [AcceptVerbs("Post")] + [HttpPost("RenderPdfPages")] + [Route("[controller]/RenderPdfPages")] +        //Post action for processing the PDF documents  +        public IActionResult RenderPdfPages([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + object jsonResult = pdfviewer.GetPage(jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + + [AcceptVerbs("Post")] + [HttpPost("RenderPdfTexts")] + [Route("[controller]/RenderPdfTexts")] +        //Post action for processing the PDF texts  +        public IActionResult RenderPdfTexts([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + object jsonResult = pdfviewer.GetDocumentText(jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + + [AcceptVerbs("Post")] + [HttpPost("RenderThumbnailImages")] + [Route("[controller]/RenderThumbnailImages")] +        //Post action for rendering the ThumbnailImages +        public IActionResult RenderThumbnailImages([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + object result = pdfviewer.GetThumbnailImages(jsonObject); + return Content(JsonConvert.SerializeObject(result)); + } + [AcceptVerbs("Post")] + [HttpPost("RenderAnnotationComments")] + [Route("[controller]/RenderAnnotationComments")] +        //Post action for rendering the annotations +        public IActionResult RenderAnnotationComments([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + object jsonResult = pdfviewer.GetAnnotationComments(jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + [AcceptVerbs("Post")] + [HttpPost("ExportAnnotations")] + [Route("[controller]/ExportAnnotations")] +        //Post action to export annotations +        public IActionResult ExportAnnotations([FromBody] Dictionary jsonObject) + { + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + string jsonResult = pdfviewer.ExportAnnotation(jsonObject); + return Content(jsonResult); + } + [AcceptVerbs("Post")] + [HttpPost("ImportAnnotations")] + [Route("[controller]/ImportAnnotations")] +        //Post action to import annotations +        public IActionResult ImportAnnotations([FromBody] Dictionary jsonObject) + { + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + string jsonResult = string.Empty; + object JsonResult; + if (jsonObject != null && jsonObject.ContainsKey("fileName")) + { + string documentPath = GetDocumentPath(jsonObject["fileName"]); + if (!string.IsNullOrEmpty(documentPath)) + { + jsonResult = System.IO.File.ReadAllText(documentPath); + } + else + { + return this.Content(jsonObject["document"] + " is not found"); + } + } + else + { + string extension = Path.GetExtension(jsonObject["importedData"]); + if (extension != ".xfdf") + { + JsonResult = pdfviewer.ImportAnnotation(jsonObject); + return Content(JsonConvert.SerializeObject(JsonResult)); + } + else + { + string documentPath = GetDocumentPath(jsonObject["importedData"]); + if (!string.IsNullOrEmpty(documentPath)) + { + byte[] bytes = System.IO.File.ReadAllBytes(documentPath); + jsonObject["importedData"] = Convert.ToBase64String(bytes); + JsonResult = pdfviewer.ImportAnnotation(jsonObject); + return Content(JsonConvert.SerializeObject(JsonResult)); + } + else + { + return this.Content(jsonObject["document"] + " is not found"); + } + } + } + return Content(jsonResult); + } + + [AcceptVerbs("Post")] + [HttpPost("ExportFormFields")] + [Route("[controller]/ExportFormFields")] + public IActionResult ExportFormFields([FromBody] Dictionary jsonObject) + + { + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + string jsonResult = pdfviewer.ExportFormFields(jsonObject); + return Content(jsonResult); + } + + [AcceptVerbs("Post")] + [HttpPost("ImportFormFields")] + [Route("[controller]/ImportFormFields")] + public IActionResult ImportFormFields([FromBody] Dictionary jsonObject) + { + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + jsonObject["data"] = GetDocumentPath(jsonObject["data"]); + object jsonResult = pdfviewer.ImportFormFields(jsonObject); + return Content(JsonConvert.SerializeObject(jsonResult)); + } + + [AcceptVerbs("Post")] + [HttpPost("Unload")] + [Route("[controller]/Unload")] +        //Post action for unloading and disposing the PDF document resources  +        public IActionResult Unload([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + pdfviewer.ClearCache(jsonObject); + return this.Content("Document cache is cleared"); + } + + + [HttpPost("Download")] + [Route("[controller]/Download")] +        //Post action for downloading the PDF documents +        public IActionResult Download([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + string documentBase = pdfviewer.GetDocumentAsBase64(jsonObject); + return Content(documentBase); + } + + [HttpPost("PrintImages")] + [Route("[controller]/PrintImages")] +        //Post action for printing the PDF documents +        public IActionResult PrintImages([FromBody] Dictionary jsonObject) + { + //Initialize the PDF Viewer object with memory cache object + PdfRenderer pdfviewer = new PdfRenderer(_cache); + if (Startup.isRedisCacheEnable) + pdfviewer = new PdfRenderer(_cache, _dCache, _slidingTime); + else + pdfviewer = new PdfRenderer(_cache, _slidingTime); + object pageImage = pdfviewer.GetPrintImage(jsonObject); + return Content(JsonConvert.SerializeObject(pageImage)); + } + + //Gets the path of the PDF document + private string GetDocumentPath(string document) + { + string documentPath = string.Empty; + if (!System.IO.File.Exists(document)) + { + var path = _hostingEnvironment.ContentRootPath; + if (System.IO.File.Exists(path + "/Data/" + document)) + documentPath = path + "/Data/" + document; + } + else + { + documentPath = document; + } + Console.WriteLine(documentPath); + return documentPath; + } + // GET api/values + [HttpGet] + public IEnumerable Get() + { + return new string[] { "value1", "value2" }; + } + + // GET api/values/5 + [HttpGet("{id}")] + public string Get(int id) + { + return "value"; + } + } +} \ No newline at end of file diff --git a/How to/Redis Cache/Data/PDF_Succinctly.pdf b/How to/Redis Cache/Data/PDF_Succinctly.pdf new file mode 100644 index 0000000..19b4956 Binary files /dev/null and b/How to/Redis Cache/Data/PDF_Succinctly.pdf differ diff --git a/How to/Redis Cache/Program.cs b/How to/Redis Cache/Program.cs new file mode 100644 index 0000000..141c1a6 --- /dev/null +++ b/How to/Redis Cache/Program.cs @@ -0,0 +1,27 @@ +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using PDFViewerWebService; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace PdfViewerWebService +{ + public class Program + { + public static void Main(string[] args) + { + CreateHostBuilder(args).Build().Run(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => + Host.CreateDefaultBuilder(args) + .ConfigureWebHostDefaults(webBuilder => + { + webBuilder.UseStartup(); + }); + } +} diff --git a/How to/Redis Cache/Properties/launchSettings.json b/How to/Redis Cache/Properties/launchSettings.json new file mode 100644 index 0000000..7093788 --- /dev/null +++ b/How to/Redis Cache/Properties/launchSettings.json @@ -0,0 +1,28 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:32141", + "sslPort": 44347 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "pdfviewer", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "PdfViewerWebService_3._0": { + "commandName": "Project", + "launchBrowser": true, + "applicationUrl": "https://localhost:5001;http://localhost:5000", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/How to/Redis Cache/RedisCache.csproj b/How to/Redis Cache/RedisCache.csproj new file mode 100644 index 0000000..60ec23e --- /dev/null +++ b/How to/Redis Cache/RedisCache.csproj @@ -0,0 +1,16 @@ + + + + net6.0 + PdfViewerWebService + PdfViewerWebService + + + + + + + + + + diff --git a/How to/Redis Cache/RedisCache.sln b/How to/Redis Cache/RedisCache.sln new file mode 100644 index 0000000..2af9003 --- /dev/null +++ b/How to/Redis Cache/RedisCache.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.6.33723.286 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RedisCache", "RedisCache.csproj", "{24556E54-B878-4609-B138-0BB171B1022C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {24556E54-B878-4609-B138-0BB171B1022C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {24556E54-B878-4609-B138-0BB171B1022C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {24556E54-B878-4609-B138-0BB171B1022C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {24556E54-B878-4609-B138-0BB171B1022C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {9EC7B3D9-9729-4948-AE50-B0F0898C992F} + EndGlobalSection +EndGlobal diff --git a/How to/Redis Cache/Startup.cs b/How to/Redis Cache/Startup.cs new file mode 100644 index 0000000..dbb77fa --- /dev/null +++ b/How to/Redis Cache/Startup.cs @@ -0,0 +1,90 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.HttpsPolicy; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.ResponseCompression; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Newtonsoft.Json.Serialization; + +namespace PDFViewerWebService +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + internal static bool isRedisCacheEnable = false; + readonly string MyAllowSpecificOrigins = "MyPolicy"; + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddControllers(); + services.AddMemoryCache(); + services.AddMvc(); + string redisCacheConnectionString = Configuration["REDIS_CACHE_CONNECTION_STRING"]; + if (redisCacheConnectionString != null && redisCacheConnectionString != string.Empty) + { + + services.AddDistributedRedisCache(options => + { + options.Configuration = redisCacheConnectionString; + }); + isRedisCacheEnable = true; + } + services.AddControllers().AddNewtonsoftJson(options => + { + // Use the default property (Pascal) casing + options.SerializerSettings.ContractResolver = new DefaultContractResolver(); + }); + services.AddCors(options => + { + options.AddPolicy(MyAllowSpecificOrigins, + builder => + { + builder.AllowAnyOrigin() + .AllowAnyMethod() + .AllowAnyHeader(); + }); + }); + services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); + services.Configure(options => options.Level = System.IO.Compression.CompressionLevel.Optimal); + services.AddResponseCompression(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IWebHostEnvironment env) + { + //Register Syncfusion license + string licenseKey = string.Empty; + Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense(licenseKey); + + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + } + else + { + app.UseHsts(); + } + app.UseHttpsRedirection(); + app.UseRouting(); + app.UseAuthorization(); + app.UseCors(MyAllowSpecificOrigins); + app.UseResponseCompression(); + app.UseEndpoints(endpoints => + { + endpoints.MapControllers().RequireCors("MyPolicy"); + }); + } + } +} \ No newline at end of file diff --git a/How to/Redis Cache/appsettings.Development.json b/How to/Redis Cache/appsettings.Development.json new file mode 100644 index 0000000..a2880cb --- /dev/null +++ b/How to/Redis Cache/appsettings.Development.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Debug", + "System": "Information", + "Microsoft": "Information" + } + } +} diff --git a/How to/Redis Cache/appsettings.json b/How to/Redis Cache/appsettings.json new file mode 100644 index 0000000..81ff877 --- /dev/null +++ b/How to/Redis Cache/appsettings.json @@ -0,0 +1,10 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft": "Warning", + "Microsoft.Hosting.Lifetime": "Information" + } + }, + "AllowedHosts": "*" +} diff --git a/How to/Redis Cache/wwwroot/favicon.ico b/How to/Redis Cache/wwwroot/favicon.ico new file mode 100644 index 0000000..a3a7999 Binary files /dev/null and b/How to/Redis Cache/wwwroot/favicon.ico differ