当前位置:网站首页>Bootstrapblazor + FreeSQL actual combat chart usage (2)
Bootstrapblazor + FreeSQL actual combat chart usage (2)
2022-06-27 00:58:00 【Station master No】
Next chapter BootstrapBlazor actual combat Chart The chart uses (1)
13. Add prerequisite Libraries
Use nuget.org Conduct BootstrapBlazor Component installation , FreeSql library ,Newtonsoft.Json
dotnet add b06chart package Densen.FreeSql.Extensions.BootstrapBlazordotnet add b06chart package FreeSql.Provider.Sqlitedotnet add b06chart package Newtonsoft.Json
14. Data services
add to FreeSql Service to Program.cs To stay builder.Services.AddBootstrapBlazor(); Before joining
builder.Services.AddFreeSql(option =>{ //demo The demonstration is Sqlite drive ,FreeSql Support multiple databases ,MySql/SqlServer/PostgreSQL/Oracle/Sqlite/Firebird/ Reach a dream / Supernatural power / Renmin Jincang / Hangao / Huawei GaussDB/MsAccess option.UseConnectionString(FreeSql.DataType.Sqlite, "Data Source=test.db;") // It can also be written to the configuration file #if DEBUG // development environment : Automatically synchronize entities .UseAutoSyncStructure(true) .UseNoneCommandParameter(true) // debugging sql Statement output .UseMonitorCommand(cmd => System.Console.WriteLine(cmd.CommandText))#endif ;});
15. Add entity class Model/OrdersEntry.cs
using BootstrapBlazor.Components;using FreeSql.DataAnnotations;using Newtonsoft.Json;using System.ComponentModel;using System.Linq;namespace Blazor100.Data;public partial class Orders{ /// <summary> /// Serial number /// </summary> [AutoGenerateColumn(Editable = false, DefaultSort = true, DefaultSortOrder = SortOrder.Desc, Order = 1)] [JsonProperty, Column(IsIdentity = true)] [DisplayName(" Serial number ")] public int OrderID { get; set; } /// <summary> /// Document date /// </summary> [AutoGenerateColumn(FormatString = "yyyy-MM-dd", ComponentType = typeof(DatePickerBody))] [JsonProperty] [DisplayName(" date ")] public DateTime OrderDate { get; set; } /// <summary> /// Total amount /// </summary> [AutoGenerateColumn(FormatString = "N2", Align = Alignment.Right)] [JsonProperty, Column(DbType = "decimal(19,4)")] [DisplayName(" total ")] public decimal SubTotal { get; set; } [AutoGenerateColumn(Ignore = true)] [Navigate(nameof(OrderID))] public virtual List<OrderDetails>? OrderDetailss { get; set; } }}/// <summary>/// Order details /// </summary>public partial class OrderDetails{ [JsonProperty, Column(IsIdentity = true)] public int ID { get; set; } [JsonProperty] public int OrderID { get; set; } [JsonProperty, Column(StringLength = -1)] [DisplayName(" bar code ")] public string? BarCode { get; set; } [AutoGenerateColumn(FormatString = "N0", Align = Alignment.Center)] [JsonProperty, Column(DbType = "numeric(18,3)")] [DisplayName(" Number ")] public decimal Quantity { get; set; } [AutoGenerateColumn(Ignore = true)] [Navigate(nameof(OrderID))] public virtual Orders Orders { get; set; }}
16. Add a namespace reference Shared/_Imports.razor
@using Blazor100.Data
17. add to NavLink To Shared/NavMenu.razor
<div class="nav-item px-3"> <NavLink class="nav-link" href="DayReport"> Monthly report </NavLink> </div> <div class="nav-item px-3"> <NavLink class="nav-link" href="TopSales"> Ranking List </NavLink> </div> <div class="nav-item px-3"> <NavLink class="nav-link" href="YearsCharts"> The annual report </NavLink> </div>
18. Components Chart encapsulation , Add files Components/ChartsBase.razor
@namespace [email protected] (!IsHideSelectores){ <span> @Year year </span> <span> @Month month </span> <span> total : @(Total.ToString("N2")) @TotalString2 @TotalString3 </span>}<div class="text-center mt-2 chart"> @if (!IsHideSelectores && UseDateTimeRangeValue) { <DateTimeRange @bind-Value="@DateTimeRangeValue1" OnConfirm="OnConfirm" OnClearValue="OnClear" /> } <div class="btn-group"> @if (!IsHideSelectores) { for (int i = DateTime.Now.Year - 7; i <= DateTime.Now.Year; i++) { var year = i; <Button Color="Color.Primary" IsOutline="@(Year!=year)" Text="@year.ToString()" OnClick="(()=>SetYear(year))" /> } } <Button Color="Color.Primary" IsOutline="true" OnClick="SwitchChart"><i class="fa @(IsLineChart?"fa-bar-chart":"fa-line-chart")"></i><span> Switch </span></Button> <Button Color="Color.Primary" IsOutline="true" OnClick="SwitchStacked"><i class="fa @(IsStacked?"fa-toggle-on":"fa-toggle-off")"></i><span>@(IsStacked? " Merge " : " Do not merge ")</span></Button> <Button Color="Color.Primary" IsOutline="true" OnClick="e=>ReloadChart(true)"><i class="fa fa-refresh"></i><span> Refresh </span></Button> </div></div>@if (!IsHideSelectores && IsShowMonthSelector){ <div class="text-center mt-2 chart"> <div class="btn-group"> @{ for (int i = 1; i <= 12; i++) { var month = i; <Button Color="Color.Primary" IsOutline="@(Month!=month)" Text="@month.ToString()" OnClick="(()=>SetMonth(month))" /> } } <Button Color="Color.Primary" IsOutline="true" OnClick="PreMonth"><i class="fa fa-calendar-minus-o"></i><span> Last month, </span></Button> <Button Color="Color.Primary" IsOutline="true" OnClick="NextMonth"><i class="fa fa-calendar-plus-o"></i><span> Next month </span></Button> <Button Color="Color.Primary" IsOutline="true" OnClick="SetNow"><i class="fa fa-calendar-check-o"></i><span> This month, </span></Button> </div> </div>}<div style="width: calc(80%);display: block;margin: 0 auto;"> @if (Show) { if (!IsLineChart) { <Chart ChartType="ChartType.Bar" OnInitAsync="OnInit" @ref="BarChart" Width="" /> } else { <Chart OnInitAsync="OnInit" @ref="LineChart" /> } }</div>
Add post code Components/ChartsBase.razor.cs
using BootstrapBlazor.Components;using Microsoft.AspNetCore.Components;using System.Diagnostics.CodeAnalysis;namespace b06chart{ public partial class ChartsBase { private Chart? LineChart { get; set; } private Chart? BarChart { get; set; } /// <summary> /// Set the current year /// </summary> [Parameter] public int Year { get; set; } = DateTime.Now.Year; /// <summary> /// Set the current month /// </summary> [Parameter] public int Month { get; set; } = DateTime.Now.Month; /// <summary> /// Set chart title /// </summary> [Parameter] public string TitleCharts { get; set; } = " A daily report "; /// <summary> /// Set up X Axis text /// </summary> [Parameter] public string XAxesText { get; set; } = " Days "; /// <summary> /// Set up Y Axis text /// </summary> [Parameter] public string YAxesText { get; set; } = " The number "; /// <summary> /// Chart type : yes =LineChart, no =BarChart /// </summary> [Parameter] public bool IsLineChart { get; set; } /// <summary> /// Use default data /// </summary> [Parameter] public bool IsDemo { get; set; } /// <summary> /// Show month selector /// </summary> [Parameter] public bool IsShowMonthSelector { get; set; } = true; [Parameter] public EventCallback<ChartDataSource> OnInitCallback { get; set; } [Parameter] public EventCallback<ChartDataSource> The data generated Callback { get; set; } [Parameter] public decimal Total { get; set; } [Parameter] public string? TotalString2 { get; set; } [Parameter] public string? TotalString3 { get; set; } /// <summary> /// Hide selector /// </summary> [Parameter] public bool IsHideSelectores { get; set; } /// <summary> /// Use / Initialization date select control date /// </summary> [Parameter] public bool UseDateTimeRangeValue { get; set; } /// <summary> /// Whether to merge Bar Show Default false /// </summary> public bool IsStacked { get; set; } /// <summary> /// Strong brush display control ,Hack once /// </summary> private bool Show { get; set; } = true; public int LastCount { get; set; } public bool FirstLoad { get; set; } = true; public bool ForceRefresh { get; set; } private string? ClickItemID { get; set; } private IEnumerable<string> Colors { get; set; } = new List<string>() { "Blue", "Green", "Red", "Orange", "Yellow", "Tomato", "Pink", "Violet" }; #region Date selection control private DateTimeRangeValue DateTimeRangeValue1 { get; set; } = new DateTimeRangeValue(); DateTime Start date = DateTime.Today.FirstDay(); DateTime End date = DateTime.Today.LastDay(); private Task OnConfirm(DateTimeRangeValue value) { Start date = value.Start.FirstSecond(); End date = value.End.Year == 1 ? value.Start.LastSecond() : value.End.LastSecond(); Chart? chart = IsLineChart ? LineChart : BarChart; chart?.Update(ChartAction.Update); //StateHasChanged(); return Task.CompletedTask; } private Task OnClear(DateTimeRangeValue value) { Start date = DateTime.Today.FirstDay(); End date = DateTime.Today.LastDay(); Chart? chart = IsLineChart ? LineChart : BarChart; chart?.Update(ChartAction.Update); //StateHasChanged(); return Task.CompletedTask; } /// <summary> /// Set date select control date /// </summary> /// <param name="_ Start date "></param> /// <param name="_ End date "></param> /// <returns></returns> protected Task SetDates(DateTime _ Start date , DateTime _ End date ) { Start date = _ Start date ; End date = _ End date ; DateTimeRangeValue1.Start = Start date ; DateTimeRangeValue1.End = End date ; return Task.CompletedTask; } #endregion protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (UseDateTimeRangeValue && firstRender) { DateTimeRangeValue1.Start = Start date ; DateTimeRangeValue1.End = End date ; } } private Task OnAfterInit() { System.Console.WriteLine("Bar Initialization done "); return Task.CompletedTask; } /// <summary> /// initialization ChartDataSource /// </summary> /// <returns></returns> protected Task<ChartDataSource> OnInit() { var ds = new ChartDataSource(); if (!OnInitCallback.HasDelegate) { ds.Options.Title = TitleCharts; ds.Options.X.Title = XAxesText; ds.Options.X.Stacked = IsStacked; ds.Options.Y.Title = YAxesText; ds.Options.Y.Stacked = IsStacked; } else { OnInitCallback.InvokeAsync(ds); } // Set custom colors ds.Options.Colors = new Dictionary<string, string>() { { "blue:", "rgb(54, 162, 235)" }, { "green:", "rgb(75, 192, 192)" }, { "red:", "rgb(255, 99, 132)" }, { "orange:", "rgb(255, 159, 64)" }, { "yellow:", "rgb(255, 205, 86)" }, { "tomato:", "rgb(255, 99, 71)" }, { "pink:", "rgb(255, 192, 203)" }, { "violet:", "rgb(238, 130, 238)" }, }; if (! The data generated Callback.HasDelegate) The data generated (ds); else The data generated Callback.InvokeAsync(ds); if (ds.Labels ==null || ds.Labels!.Count() == 0) { LastCount = 0; Show = false; return Task.FromResult(ds); } Show = true; ForceRefresh = LastCount == 0 || LastCount < ds.Labels!.Count(); LastCount = ds.Labels!.Count(); if (!FirstLoad && ForceRefresh) { ReloadChart(); ForceRefresh = false; } FirstLoad = false; return Task.FromResult(ds); } /// <summary> /// The data generated , add to Labels and ChartDataset /// </summary> /// <param name="ds"></param> protected virtual void The data generated (ChartDataSource ds) { } private Task SetYear(int year) { Chart? chart = IsLineChart ? LineChart : BarChart; Year = year; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task SetMonth(int month) { Chart? chart = IsLineChart ? LineChart : BarChart; Month = month; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task PreMonth() { Chart? chart = IsLineChart ? LineChart : BarChart; Year = Month - 1 >= 1 ? Year : Year - 1; Month = Month - 1 >= 1 ? Month - 1 : 12; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task NextMonth() { Chart? chart = IsLineChart ? LineChart : BarChart; Year = Month + 1 <= 12 ? Year : Year + 1; Month = Month + 1 <= 12 ? Month + 1 : 1; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task SetNow() { Chart? chart = IsLineChart ? LineChart : BarChart; Year = DateTime.Now.Year; Month = DateTime.Now.Month; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task RandomData() { Chart? chart = IsLineChart ? LineChart : BarChart; chart?.Update(ChartAction.Update); return Task.CompletedTask; } private Task SwitchChart() { IsLineChart = !IsLineChart; return Task.CompletedTask; } /// <summary> /// Toggle merge display /// </summary> private void SwitchStacked() { IsStacked = !IsStacked; ReloadChart(); } /// <summary> /// Strong brush control , Reinitialize the control appearance /// </summary> private async void ReloadChart(bool reloadData=false) { Chart? chart = IsLineChart ? LineChart : BarChart; if (reloadData) chart?.Update(ChartAction.Update); Show = false; await InvokeAsync(StateHasChanged); await Task.Delay(1); Show = true; await InvokeAsync(StateHasChanged); } } public static class DateTimeExtensions { public static DateTime FirstDay(this DateTime obj) => new DateTime(obj.Year, obj.Month, 1, 0, 0, 0); public static DateTime LastDay(this DateTime obj) => obj.FirstDay().AddMonths(1).AddDays(-1).LastSecond(); public static DateTime FirstSecond(this DateTime obj) => new DateTime(obj.Year, obj.Month, obj.Day, 0, 0, 0); public static DateTime LastSecond(this DateTime obj) => new DateTime(obj.Year, obj.Month, obj.Day, 23, 59, 59); }}
19. Add daily report page `Pages/DayReport.razor'
@page "/DayReport"@namespace b06chart<Tab> <TabItem Text=" A daily report "> <ChartsBase @ref="charts" TitleCharts=" A daily report " The data generated Callback="@((ds)=> The data generated (ds))" Total="@Total" TotalString2="@TotalString2" /> </TabItem> <TabItem Text=" data "> <Table TItem="Orders" IsPagination="true" IsStriped="true" IsBordered="true" AutoGenerateColumns="true" ShowSearch="true" ShowToolbar="true" ShowExtendButtons="true" DoubleClickToEdit=true ShowColumnList=true ShowCardView=true> </Table> </TabItem></Tab>
Add post code Pages/DayReport.razor.cs
using Blazor100.Data;using BootstrapBlazor.Components;using Microsoft.AspNetCore.Components;using System.Diagnostics.CodeAnalysis;namespace b06chart{ public partial class DayReport { [Inject] [NotNull] IFreeSql? fsql { get; set; } [Inject] ToastService? toastService { get; set; } List<Orders> orders { get; set; } = new List<Orders>(); ChartsBase? charts; decimal Total { get; set; } string? TotalString2 { get; set; } private Task The data generated (ChartDataSource ds) { var orders = fsql.Select<Orders>() .Where(a => a.OrderDate.Month == charts!. Month && a.OrderDate.Year == charts.Year) .GroupBy(a => new { a.OrderDate.Day }) .ToList(a => new { cou1 = a.Count(), OrderDate = a.Key.Day, Total = a.Sum(a.Value.SubTotal) }); orders = orders.OrderBy(a => a.OrderDate).ToList(); ds.Labels = orders.Select(a => a.OrderDate.ToString()); ds.Data.Add(new ChartDataset() { Label = $" Number of documents ", Data = orders.Select(a => a.cou1).Cast<object>() }); ds.Data.Add(new ChartDataset() { Label = $" amount of money ", Data = orders.Select(a => a.Total).Cast<object>() }); Total = orders.Select(a => a.Total).Sum(); return Task.CompletedTask; } protected override void OnAfterRender(bool firstRender) { if (firstRender) { Orders.DemoDatas(fsql!); } } }}
20. Add annual report page `Pages/YearsCharts.razor'
@page "/YearsCharts"@namespace b06chart<ChartsBase @ref="charts" TitleCharts=" Annual report " XAxesText=" month " IsShowMonthSelector="false" The data generated Callback="@((ds)=> The data generated (ds))" Total="@Total" />
Add post code Pages/YearsCharts.razor.cs
using Blazor100.Data;using BootstrapBlazor.Components;using Microsoft.AspNetCore.Components;using System.Diagnostics.CodeAnalysis;namespace b06chart{ public partial class YearsCharts { [Inject] [NotNull] IFreeSql? fsql { get; set; } [Inject] ToastService? toastService { get; set; } List<Orders> orders { get; set; } = new List<Orders>(); ChartsBase? charts; decimal Total { get; set; } string? TotalString2 { get; set; } private Task The data generated (ChartDataSource ds) { var orders = fsql.Select<Orders>() .Where(a => a.OrderDate.Year == charts!.Year) .GroupBy(a => new { a.OrderDate.Month }) .ToList(a => new { cou1 = a.Count(), OrderDate = a.Key.Month, Total = a.Sum(a.Value.SubTotal) }); orders = orders.OrderBy(a => a.OrderDate).ToList(); ds.Labels = orders.Select(a => a.OrderDate.ToString()); ds.Data.Add(new ChartDataset() { Label = $" Number of documents ", Data = orders.Select(a => a.cou1).Cast<object>() }); ds.Data.Add(new ChartDataset() { Label = $" amount of money ", Data = orders.Select(a => a.Total).Cast<object>() }); Total = orders.Select(a => a.Total).Sum(); return Task.CompletedTask; } protected override void OnAfterRender(bool firstRender) { if (firstRender) { Orders.DemoDatas(fsql!); } } }}
21. Add leaderboard page Pages/OrdersTopSalesCharts.razor
@page "/TopSales"@namespace b06chart<Tab> <TabItem Text=" Sales leaderboards "> <ChartsBase @ref="charts" TitleCharts=" Sales leaderboards " The data generated Callback="@((ds)=> The data generated (ds))" Total="@Total" /> </TabItem> <TabItem Text=" data "> <Table TItem="OrderDetails" IsPagination="true" IsStriped="true" IsBordered="true" AutoGenerateColumns="true" ShowSearch="true" ShowToolbar="true" ShowExtendButtons="true" DoubleClickToEdit=true ShowColumnList=true ShowCardView=true> </Table> </TabItem></Tab>
Add post code Pages/OrdersTopSalesCharts.razor.cs
using Blazor100.Data;using BootstrapBlazor.Components;using Microsoft.AspNetCore.Components;namespace b06chart{ public partial class OrdersTopSalesCharts { [Inject] IFreeSql? fsql { get; set; } [Inject] ToastService? toastService { get; set; } List<OrderDetails> orders { get; set; } = new List<OrderDetails>(); ChartsBase? charts; decimal Total { get; set; } private Task The data generated (ChartDataSource ds) { var Start date = (new DateTime(charts!.Year, charts.Month, 1)).FirstDay(); var End date = Start date .LastDay(); orders = fsql!.Select<OrderDetails>() .Where( a => a.Orders.OrderDate.Between( Start date , End date )) .GroupBy(a => a.BarCode ) .OrderByDescending(a => a.Sum(a.Value.Quantity)) .ToList(a => new OrderDetails { BarCode = a.Key, Quantity = a.Sum(a.Value.Quantity) } ); ds.Labels = orders.Select(a => $"{a.BarCode}"); ds.Data.Add(new ChartDataset() { Label = $" Sales volume ", Data = orders.Select(a => a.Quantity).Cast<object>() }); Total = orders.Sum(a => a.Quantity); return Task.CompletedTask; } protected override void OnAfterRender(bool firstRender) { if (firstRender) { Orders.DemoDatas(fsql!); } } }}
22. The packaging code comes from my actual project , There is still much room for optimization in the logic part , There are still a few bug Didn't clean up . I hope you have a better plan , Make more corrections in the comment area , I will study with an open mind , Common progress .
Project source code
[Github] https://github.com/densen2014/Blazor100
[Gitee] https://gitee.com/densen2014/Blazor100
Creative Commons license agreement
This work adopts Creative Commons signature - Noncommercial use - Share in the same way 4.0 International licensing agreement Licensing . Welcome to reprint 、 Use 、 Re release , But be sure to keep the signature of the article AlexChow( Include links : https://github.com/densen2014 ), Not for commercial purposes , Based on this revised work must be released with the same license . If you have any questions , Please contact me .
AlexChow
Today's headline | Blog Garden | You know | Gitee | GitHub
边栏推荐
- 解决unable to create a folder to save the sketch: mkdir sketch
- com.fasterxml.jackson.databind.exc.MismatchedInputException: Expected array or string. at [Source:x
- Solve the problem that only one line of text is displayed or not displayed in u8glib
- Law of Large Numbers
- Moher College -x-forwarded-for injection vulnerability practice
- Lambda expression
- 2022年地理信息系统与遥感专业就业前景与升学高校排名选择
- 如何把老式键盘转换成USB键盘并且自己编程?
- 如何写好测试用例以及go单元测试工具testify简单介绍
- memcached基础1
猜你喜欢
One click acceleration of Sony camera SD card file copy operation, file operation batch processing tutorial
Network in network (dolls)
如何把老式键盘转换成USB键盘并且自己编程?
网络中的网络(套娃)
Custom jsp[if, foreach, data, select] tag
自定义MVC(导成jar包)+与三层架构的区别+反射+面试题
Concepts de base de données Oracle
Unable to create a folder to save the sketch: MKDIR sketch
buuctf-pwn write-ups (6)
LeetCode 142. Circular linked list II
随机推荐
Is it safe to open a securities account online? Is it reliable to speculate in stocks by mobile phone
Live review | Ziya &ccf TF: Discussion on software supply chain risk management technology under cloud native scenario
Sword finger offer 10- ii Frog jumping on steps
JS library for number formatting
数据库面试题+sql语句解析
3線spi屏幕驅動方式
Using physical information neural network to solve hydrodynamics equations
30《MySQL 教程》MySQL 存储引擎概述
memcached基础5
Law of Large Numbers
滑环安装有哪些技巧和方法
如何把老式键盘转换成USB键盘并且自己编程?
这3个并发编程的核心,竟然还有人不知道?
Play OLED, u8g2 animation, increasing numbers, random triangles, etc
简单快速的数网络(网络中的网络套娃)
C#程序结构预览最基础入门
Oracle database basics concepts
自定义JSP[if,foreach,数据,select]标签
matlab数据类型 —— 字符型
Generate flow chart with code, and how to use markdown