I am trying to use google charts api to present data from my database. I am using the following tutorial: https://www.c-sharpcorner.com/article/asp-net-mvc5-google-charts-api-integration/
I've noticed in the controller, that they load data in using a txt file.string srcFilePath = "Content/files/SalesOrderDetail.txt"; Would there be a way to load the data in using entity framework and how would I do it?
I am new to mvc and using an api so I'm very unsure on how to achieve this.
I used database first for my project.
Controller:
using HolidayTracker.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
namespace Graphs.Controllers
{
public class MetricsController : Controller
{
#region Index method
/// <summary>
/// GET: Home/Index method.
/// </summary>
/// <returns>Returns - index view page</returns>
public ActionResult Index()
{
// Info.
return this.View();
}
#endregion
#region Get data method.
/// <summary>
/// GET: /Home/GetData
/// </summary>
/// <returns>Return data</returns>
public ActionResult GetData()
{
// Initialization.
JsonResult result = new JsonResult();
try
{
// Loading.
List<Employee> data = this.LoadData();
// Setting.
var graphData = data.GroupBy(p => new
{
p.FullName,
p.HoursTaken,
p.SickLeaveTaken
})
.Select(g => new
{
g.Key.FullName,
g.Key.HoursTaken,
g.Key.SickLeaveTaken
}).OrderByDescending(q => q.FullName).ToList();
// Top 10
graphData = graphData.Take(10).Select(p => p).ToList();
// Loading drop down lists.
result = this.Json(graphData, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
// Info
Console.Write(ex);
}
// Return info.
return result;
}
#endregion
#region Helpers
#region Load Data
/// <summary>
/// Load data method.
/// </summary>
/// <returns>Returns - Data</returns>
private List<Employee> LoadData()
{
// Initialization.
List<Employee> lst = new List<Employee>();
try
{
// Initialization.
string line = string.Empty;
string srcFilePath = "Content/files/SalesOrderDetail.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// Read file.
while ((line = sr.ReadLine()) != null)
{
// Initialization.
Employee infoObj = new Employee();
string[] info = line.Split(',');
// Setting.
infoObj.FullName = info[3].ToString();
infoObj.HoursTaken = Convert.ToDecimal(info[0].ToString());
infoObj.SickLeaveTaken = Convert.ToDecimal(info[0].ToString());
// Adding.
lst.Add(infoObj);
}
// Closing.
sr.Dispose();
sr.Close();
}
catch (Exception ex)
{
// info.
Console.Write(ex);
}
// info.
return lst;
}
#endregion
#endregion
}
}