0

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
}
}

1 Answer 1

0

I have just create DB for this case.

First, you need create a table that mapping with SalesOrderDetail class

CREATE TABLE [dbo].[SalesOrderDetail](
    [Sr] [int] PRIMARY KEY NOT NULL,
    [OrderTrackNumber] [nvarchar](50) NULL,
    [Quantity] [int] NULL,
    [ProductName] [nvarchar](50) NULL,
    [SpecialOffer] [nvarchar](50) NULL,
    [UnitPrice] [decimal](18, 0) NULL,
    [UnitPriceDiscount] [decimal](18, 0) NULL,
)

Second, you create a ADO.NET Entity Data Model. And add code to save data from file to Database. Change code in Load Data method

private List<SalesOrderDetail> LoadData()
        {
            // Initialization.
            List<SalesOrderDetail> lst = new List<SalesOrderDetail>();
            CustomerEntities ctx = new CustomerEntities();
            //lst = ctx.SalesOrderDetails.ToList();
            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.
                    SalesOrderDetail infoObj = new SalesOrderDetail();
                    string[] info = line.Split(',');

                    // Setting.
                    infoObj.Sr = Convert.ToInt32(info[0].ToString());
                    infoObj.OrderTrackNumber = info[1].ToString();
                    infoObj.Quantity = Convert.ToInt32(info[2].ToString());
                    infoObj.ProductName = info[3].ToString();
                    infoObj.SpecialOffer = info[4].ToString();
                    infoObj.UnitPrice = Convert.ToDecimal(info[5].ToString());
                    infoObj.UnitPriceDiscount = Convert.ToDecimal(info[6].ToString());

                    // Adding.
                    lst.Add(infoObj);
                    ctx.SalesOrderDetails.Add(infoObj);

                }

                ctx.SaveChanges();

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

After first running, data from text file inserted to DB, you comment out code to get data from file and insert line of code lst = ctx.SalesOrderDetails.ToList(); to read from DB.

private List<SalesOrderDetail> LoadData()
        {
            // Initialization.
            List<SalesOrderDetail> lst = new List<SalesOrderDetail>();
            CustomerEntities ctx = new CustomerEntities();
            lst = ctx.SalesOrderDetails.ToList();
            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.
                //    SalesOrderDetail infoObj = new SalesOrderDetail();
                //    string[] info = line.Split(',');

                //    // Setting.
                //    infoObj.Sr = Convert.ToInt32(info[0].ToString());
                //    infoObj.OrderTrackNumber = info[1].ToString();
                //    infoObj.Quantity = Convert.ToInt32(info[2].ToString());
                //    infoObj.ProductName = info[3].ToString();
                //    infoObj.SpecialOffer = info[4].ToString();
                //    infoObj.UnitPrice = Convert.ToDecimal(info[5].ToString());
                //    infoObj.UnitPriceDiscount = Convert.ToDecimal(info[6].ToString());

                //    // Adding.
                //    lst.Add(infoObj);
                //    ctx.SalesOrderDetails.Add(infoObj);

                //}

                //ctx.SaveChanges();

                // Closing.
                //sr.Dispose();
                //sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

You can download source code at https://github.com/viethien/MVC5GoogleGraph

Sign up to request clarification or add additional context in comments.

6 Comments

So I'm alittle confused with the txt file. Is it there for data purposes or is it used to take data from the database?
I used that text file to insert into DB for testing, you can add more data to database
Okay, cool! So if I had data in my db already, there would be no need for it? So my LoadData() method would look like the second part with the commented out code you posted.
only need call lst = ctx.SalesOrderDetails.ToList(); and comment out code for reading file
It did'nt seem to work. I used break points and it seem var graphData has datacount 0 but I definitely have data in the db
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.