Create A Simple đŸ“ˆChart By Date For The Latest C# Corner Article Count

Introduction

In this post, we will create a simple Line Chart in Blazor using Chart JS. We will show the latest C# Corner article count by date in this chart. For creating a chart in Blazor, we will use a third-party library, BlazorComponents, created by Muqeet Khan. You can get the source code of this library from this Link.

About Chart JS
 
Chart.js is a JavaScript library that allows you to draw different types of charts by using the HTML5 canvas element. Since it uses canvas, you must include a polyfill to support older browsers. You can get more details on Chart JS from this URL.
 
About Blazor Framework
 
Blazor is (still an experimental) .NET web framework from Microsoft using C#/Razor and HTML that runs in the browser with Web Assembly. Blazor provides all the benefits of a client-side web UI framework using .NET on the client and optionally on the server.

I have already written many articles on Blazor for you good people on C# Corner. If you are new to it, please refer to the below articles to get started with Blazor.

Create a Blazor project in Visual Studio 2017

We can create a new Blazor project using Visual Studio 2017 (I am using the free community edition). Currently, there are three types of templates available for Blazor. We can choose Blazor (ASP.NET Core hosted) template.

Please make sure you are using Blazor version 0.7.0 or higher. Chart Component does not support previous versions of Blazor.
 
Create a Simple đŸ“ˆChart for Date wise C# Corner Latest Articles Count
 
Our solution will be ready shortly. Please note that there are three projects created in our solution - “Client”, “Server”, and “Shared”.
 
Create a Simple đŸ“ˆChart for Date wise C# Corner Latest Articles Count 
 
By default, Blazor creates many files in these three projects. We can remove all the unwanted files like “Counter.cshtml”, “FetchData.cshtml”, “SurveyPrompt.cshtml” from the Client project, “SampleDataController.cs” file from the Server project, and remove “WeatherForecast.cs” file from the Shared project.

We need to install the BlazorComponents library in Client Project for creating the chart. Currently the NuGet package has some issues. So, I am adding the entire BlazorComponentproject to our Blazor solution.

We can add the BlazorComponent project reference to Client project.

Create a Simple đŸ“ˆChart for Date wise C# Corner Latest Articles Count 

We must create a “Models” folder in Shared project and add “Feed” and ”DateWiseCount” classes to this folder. I am creating a single file “Classes.cs” and adding these two classes.

Classes.cs
  1. namespace BlazorLineChart.Shared.Models  
  2. {  
  3.     public class Feed  
  4.     {  
  5.         public string PubDate { getset; }  
  6.     }  
  7.   
  8.     public class DateWiseCount  
  9.     {  
  10.         public string PubDate { getset; }  
  11.         public double Count { getset; }  
  12.     }  
  13. }  

These two classes are used for getting C# Corner's latest article count by date and passing it to our Razor view file. We will discuss more about these details later in this post.

We can create a “CsharpConerRssController” API controller in Server project. We will write the logic for the latest article count in this controller class.
 
CsharpConerRssController.cs
  1. using BlazorLineChart.Shared.Models;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Globalization;  
  6. using System.Linq;  
  7. using System.Xml.Linq;  
  8.   
  9. namespace BlazorLineChart.Server.Controllers  
  10. {  
  11.     [Route("api/[controller]")]  
  12.     public class CsharpConerRssController : Controller  
  13.     {  
  14.         readonly CultureInfo culture = new CultureInfo("en-US");  
  15.   
  16.         [HttpGet]  
  17.         public List<DateWiseCount> GetLatestArticls()  
  18.         {  
  19.   
  20.             try  
  21.             {  
  22.                 XDocument doc = XDocument.Load("https://www.c-sharpcorner.com/rss/latestarticles.aspx");  
  23.                 var feeds = from item in doc.Root.Descendants().First(i => i.Name.LocalName == "channel").Elements().Where(i => i.Name.LocalName == "item")  
  24.                             select new Feed  
  25.                             {  
  26.                                 PubDate = Convert.ToDateTime(item.Elements().First(i => i.Name.LocalName == "pubDate").Value, culture).ToString("dd-MMM-yy")  
  27.                             };  
  28.   
  29.                 var feedGroups =  
  30.                 from p in feeds  
  31.                 orderby p.PubDate descending  
  32.                 group p by p.PubDate into g  
  33.                 select new { PubDate = g.Key, Count = g.Count() };  
  34.   
  35.                 List<DateWiseCount> dateWiseCounts = new List<DateWiseCount>();  
  36.                 foreach (var feed in feedGroups)  
  37.                 {  
  38.   
  39.                     dateWiseCounts.Add(new DateWiseCount { PubDate = feed.PubDate, Count = feed.Count });  
  40.                 }  
  41.                 return dateWiseCounts;  
  42.   
  43.             }  
  44.             catch (Exception)  
  45.             {  
  46.                 return null;  
  47.             }  
  48.         }  
  49.     }  
  50. }  

We are getting the data from C# Corner RSS feeds. Please note, C# Corner RSS feed returns a list of the 100 latest articles only.

Then we used a LINQ query to create a list and I stored it in a variable. After getting the data, we will return this list from API controller.

We can add a “LatestArticles.cshtml” Razor view file in Client project inside the Pages folder and add the below code to this view.

LatestArticles.cshtml
  1. @page "/latestarticles"  
  2. @using BlazorComponents.Shared  
  3. @using BlazorLineChart.Shared.Models  
  4. @using BlazorComponents.ChartJS  
  5. @addTagHelper *,BlazorComponents  
  6.   
  7. @inject HttpClient Http  
  8.   
  9. <div class="container">  
  10.   
  11.     <h4>Date wise Latest C# Corner Articles Count Chart using Blazor</h4>  
  12.     <p>(It lists latest 100 articles only)</p>  
  13.     @if (pageLoading)  
  14.     {  
  15.         <p><em>Loading...</em></p>  
  16.     }  
  17.     else  
  18.     {  
  19.         <ChartJsLineChart ref="lineChartJs" Chart="@blazorLineChartJS" Width="600" Height="300" />  
  20.     }  
  21.   
  22. </div>  
  23.   
  24. @functions {  
  25.   
  26. public ChartJSLineChart blazorLineChartJS { getset; } = new ChartJSLineChart();  
  27. ChartJsLineChart lineChartJs;  
  28.   
  29. bool pageLoading;  
  30.   
  31. protected override async Task OnInitAsync()  
  32. {  
  33.     pageLoading = true;  
  34.     List<string> pubDates = new List<string>();  
  35.     List<double> counts = new List<double>();  
  36.     List<DateWiseCount> dateWiseCounts = new List<DateWiseCount>();  
  37.   
  38.     dateWiseCounts = await Http.GetJsonAsync<List<DateWiseCount>>("/api/CsharpConerRSS");  
  39.   
  40.   
  41.     foreach (var data in dateWiseCounts)  
  42.     {  
  43.         pubDates.Add(data.PubDate);  
  44.         counts.Add(data.Count);  
  45.     }  
  46.   
  47.     blazorLineChartJS = new ChartJSLineChart()  
  48.     {  
  49.         ChartType = "line",  
  50.         CanvasId = "LineChart",  
  51.         Options = new ChartJsOptions()  
  52.         {  
  53.             Text = "Date wise Latest Articles",  
  54.             Display = true,  
  55.             Responsive = false  
  56.         },  
  57.         Data = new ChartJsLineData()  
  58.         {  
  59.             Labels = pubDates,  
  60.             Datasets = new List<ChartJsLineDataset>()  
  61. {  
  62. new ChartJsLineDataset()  
  63. {  
  64. BackgroundColor = new List<string>(){"#ff6384" },  
  65. BorderColor = "#ff6384",  
  66. Label = "# of Articles on the Day",  
  67. Data = counts,  
  68. Fill = false,  
  69. BorderWidth = 2,  
  70. PointRadius = 3,  
  71. PointBorderWidth=1  
  72. }  
  73. }  
  74.         }  
  75.     };  
  76.     pageLoading = false;  
  77. }  
  78.   
  79. }  

We can slightly modify the “NavMenu.cshtml” file with the below code. We have added the navigation to the latest articles Razor view.

NavMenu.cshtml
  1. <div class="top-row pl-4 navbar navbar-dark">  
  2.     <a class="navbar-brand" href="">Simple Chart in Blazor</a>  
  3.     <button class="navbar-toggler" onclick=@ToggleNavMenu>  
  4.         <span class="navbar-toggler-icon"></span>  
  5.     </button>  
  6. </div>  
  7.   
  8. <div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>  
  9.     <ul class="nav flex-column">  
  10.         <li class="nav-item px-3">  
  11.             <NavLink class="nav-link" href="" Match=NavLinkMatch.All>  
  12.                 <span class="oi oi-home" aria-hidden="true"></span> Home  
  13.             </NavLink>  
  14.         </li>  
  15.         <li class="nav-item px-3">  
  16.             <NavLink class="nav-link" href="latestarticles">  
  17.                 <span class="oi oi-list-rich" aria-hidden="true"></span> Latest Articles Chart  
  18.             </NavLink>  
  19.         </li>  
  20.     </ul>  
  21. </div>  
  22.   
  23. @functions {  
  24.     bool collapseNavMenu = true;  
  25.   
  26.     void ToggleNavMenu()  
  27.     {  
  28.         collapseNavMenu = !collapseNavMenu;  
  29.     }  
  30. }  

Very importantly, we must include the reference for Chart.js inside the index.html file inside the wwwroot folder.

Index.html
  1. <!DOCTYPE html>    
  2. <html>    
  3. <head>    
  4.     <meta charset="utf-8" />    
  5.     <meta name="viewport" content="width=device-width">    
  6.     <title>Simple Chart in Blazor</title>    
  7.     <base href="/" />    
  8.     <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" />    
  9.     <link href="css/site.css" rel="stylesheet" />    
  10. </head>    
  11. <body>    
  12.     <app>Loading...</app>    
  13.     <script src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>    
  14.     <script src="//cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>    
  15.     <script src="_framework/blazor.webassembly.js"></script>    
  16. </body>    
  17. </html>     

Well, we have completed the coding part. We can check the chart functionality now.

Create a Simple đŸ“ˆChart for Date wise C# Corner Latest Articles Count 

We can click the “Latest Articles Chart” link and open the chart page.

Create a Simple đŸ“ˆChart for Date wise C# Corner Latest Articles Count 

Deployed on Azure

I have deployed this Blazor application on Azure. If you want to check the simple line chart, please run this Live App.
 
Conclusion
 
In this post, we have created a sample chart using Chart JS. We have taken the latest article details from C# Corner RSS feeds and using LINQ query we have taken the article count by date and showed the data in the chart. For chart creation we have used a third-party library, BlazorComponents. The source code of this library is available in GitHub.
 
We will see more exciting charts using Chart JS with Blazor project in upcoming posts.


Similar Articles