using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Hosting;
using System.Web.Http;
using Newtonsoft.Json;
using ChartService.Models;
namespace ChartService.Controllers
{
public class ChartController : ApiController
{
public HttpResponseMessage Post([FromBody] IEnumerable<ChartModel> payload)
{
String imageFile = GenerateChartImage(payload);
MemoryStream imageStream = ReadChartImage(imageFile);
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(imageStream.ToArray());
result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
return result;
}
private string GenerateChartImage(IEnumerable<ChartModel> payload)
{
Guid chartID = Guid.NewGuid();
string templatePath = @"C:\Temp\Chart\donut_template.html";
string htmlPath = String.Format(@"C:\Temp\Chart\{0}.html", chartID);
string pngPath = String.Format(@"C:\Temp\Chart\{0}.png", chartID);
// Read HTML Template File
string html = File.ReadAllText(templatePath);
// Create copy with Payload
html = html.Replace("$$$PAYLOADINJECTION$$$", JsonConvert.SerializeObject(payload));
File.WriteAllText(htmlPath, html);
// Start PhantomJS as Hidden Process in Background
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = Path.Combine(@"C:\Temp\Chart\", "phantomjs.exe");
startInfo.WorkingDirectory = @"C:\Temp\Chart\";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "render.js \"" + htmlPath + "\" \"" + pngPath + "\"";
try
{
using (Process phantomJsProc = Process.Start(startInfo))
{
phantomJsProc.WaitForExit();
return pngPath;
}
}
catch (Exception)
{
throw;
}
finally
{
// At the end, don't forget to delete temp. generated files
File.Delete(htmlPath);
}
}
private static MemoryStream ReadChartImage(string imageFile)
{
FileStream fileStream = new FileStream(imageFile, FileMode.Open);
Image image = Image.FromStream(fileStream);
MemoryStream memoryStream = new MemoryStream();
image.Save(memoryStream, ImageFormat.Png);
// Dispose objects and delete the temp. generated files
image.Dispose();
fileStream.Close();
File.Delete(imageFile);
return memoryStream;
}
}
}