C#编写软件发布公告2——服务端

embedded/2024/9/20 7:36:08/ 标签: c#, 数据库, 开发语言

简单说明

框架:.NET 6.0 MVC 数据库:sqlLite3(当然这是为考虑本地数据简单,可以考虑使用大型数据库)

一、界面效果展示

1、启动主页面

2、记录摘要界面

3、对应版本详细

二、实现代码逻辑

1、启动主页面

//关联日志文件写
builder.Logging.AddProvider(new CustomFileLoogerProvider(new CustomFileLoggerConfiguration()
{MinLevel = (LogLevel)Enum.Parse(typeof(LogLevel), builder.Configuration["FileLogPath:MinLogLevel"]),InLogLevel = LogLevel.Information,LogPath = builder.Environment.ContentRootPath + builder.Configuration["FileLogPath:LogPath"]
}));// Add services to the container.
builder.Services.AddControllersWithViews();
//配置DBServer
builder.Services.AddSingleton<IDBServer, DBServer>();

2、数据库相关

2.1 服务接口

  public interface IDBServer{HomeViewData HomeViewData { get; }string RecordViewData { get; }List<RecordData> SNInfoLists { get; }void UpDataHomeViewData();void UpDataHistoricalSummaryViewData(string? sn);void UpData();/// <summary>/// 更新历史版本信息/// </summary>/// <param name="sn">版本号</param>/// <param name="dataTime">发行日期</param>/// <param name="InfoStr">详细信息</param>/// <returns></returns>bool UpDataDetailedInformation(string sn, string dataTime, string InfoStr);}

2.2 服务实现

 public class SqlHelp{private string connectionString = @"Data Source=MyDatabase.db;";private SQLiteConnection connection;public ILogger<DBServer> Logger { get; }public SqlHelp(ILogger<Server.DBServer> logger){connection = new SQLiteConnection(connectionString);Logger = logger;}//仅获取简要信息 包含日期和版本号internal void GetReleaseBriefInfo(ref List<RecordData> list){string sql = "SELECT * FROM ReRecord;";SQLiteCommand command = new SQLiteCommand(sql, connection);connection.Open();SQLiteDataAdapter adaptr = new SQLiteDataAdapter(command);DataTable dt = new DataTable();adaptr.Fill(dt);adaptr.Dispose();command.Dispose();list = new List<RecordData>(dt.Rows.Count);for (int i = 0; i < dt.Rows.Count; i++){list.Add(new RecordData(dt.Rows[i][2].ToString(), dt.Rows[i][1].ToString()));}connection.Close();}//根据sn查找完整信息internal void GetReleaseInfo(string sn, ref List<RecordDataInfo> list){string sql = "SELECT * FROM ReRecordDescribe where Sn=@sn;";SQLiteCommand command = new SQLiteCommand(sql, connection);//SQLiteParameter[] para = new SQLiteParameter[]//{//    new SQLiteParameter("@sn",sn)//};SQLiteParameter snPara = new SQLiteParameter("@sn", sn);command.Parameters.Add(snPara);connection.Open();SQLiteDataAdapter adaptr = new SQLiteDataAdapter(command);DataTable dt = new DataTable();adaptr.Fill(dt);adaptr.Dispose();command.Dispose();list = new List<RecordDataInfo>(dt.Rows.Count);for (int i = 0; i < dt.Rows.Count; i++){list.Add(new RecordDataInfo(Convert.ToInt32(dt.Rows[i][2].ToString()), dt.Rows[i][3].ToString()));}connection.Close();}private bool FindSNInfo(string sn, string dateInfo){string sql = "SELECT * FROM ReRecord where DateInfo=@DateInfo and Sn=@sn;";SQLiteCommand command = new SQLiteCommand(sql, connection);SQLiteParameter[] para = new SQLiteParameter[]{new SQLiteParameter("@sn",sn),new SQLiteParameter("@DateInfo",dateInfo)};command.Parameters.AddRange(para);connection.Open();try{SQLiteDataAdapter adaptr = new SQLiteDataAdapter(command);DataTable dt = new DataTable();adaptr.Fill(dt);adaptr.Dispose();command.Dispose();connection.Close();if (dt.Rows.Count == 0)//没有进行增加{return false;}return true;}catch (Exception ex){throw ex;}finally{connection.Close();command.Dispose();}}private void AddSnInfo(string sn, string dateInfo){string sql = "INSERT INTO ReRecord(DateInfo,Sn) VALUES(@DateInfo,@sn);";SQLiteCommand command = new SQLiteCommand(sql, connection);SQLiteParameter[] para = new SQLiteParameter[]{new SQLiteParameter("@sn",sn),new SQLiteParameter("@DateInfo",dateInfo)};command.Parameters.AddRange(para);connection.Open();try{int a = command.ExecuteNonQuery();}catch (Exception ex){throw ex;}connection.Close();}private void DelOrgDescribeInfo(string sn){string sql = "DELETE FROM ReRecordDescribe WHERE Sn=@sn;";SQLiteCommand command = new SQLiteCommand(sql, connection);SQLiteParameter snPara = new SQLiteParameter("@sn", sn);command.Parameters.Add(snPara);connection.Open();try{int a = command.ExecuteNonQuery();}catch (Exception ex){throw ex;}connection.Close();}private bool AddDescribeInfo(string sn, List<RecordDataInfo> list){string sql = "INSERT INTO ReRecordDescribe(Sn,Num,Describe) VALUES(@sn,@Num,@Describe);";connection.Open();SQLiteTransaction tx = connection.BeginTransaction();SQLiteCommand command = new SQLiteCommand(sql, connection);command.Transaction = tx;try{for (int i = 0; i < list.Count; i++){SQLiteParameter[] para = new SQLiteParameter[]{new SQLiteParameter("@sn",sn),new SQLiteParameter("@Num",list[i].Num),new SQLiteParameter("@Describe",list[i].Describe)};command.Parameters.AddRange(para);int a = command.ExecuteNonQuery();}tx.Commit();command.Dispose();}catch (Exception ex){Logger.LogWarning("AddDescribeInfo:" + ex.Message);tx.Rollback();}connection.Close();return true;}//根据sn查找完整信息internal void UpdateInfo(string sn, string dateInfo, List<RecordDataInfo> list){if (!FindSNInfo(sn, dateInfo)){AddSnInfo(sn, dateInfo);}DelOrgDescribeInfo(sn);AddDescribeInfo(sn, list);}}

3、日志文件写实现

3.1 ILogger实现

public class CustomFileLogger : ILogger
{private readonly string _name;private readonly CustomFileLoggerConfiguration _config;private LogLevel _logLevel;public CustomFileLogger(string name, CustomFileLoggerConfiguration config){_name = name;_config = config;if (config != null){if (!Directory.Exists(config.LogPath)){Directory.CreateDirectory(config.LogPath);}}}public IDisposable BeginScope<TState>(TState state){return null;}public bool IsEnabled(LogLevel logLevel){return logLevel == _config.InLogLevel;}public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter){if (!IsEnabled(logLevel)){return;}_logLevel = logLevel;FileLog($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:fff")} - {logLevel.ToString()} - {_name} - {formatter(state, exception)} \n");}private  void FileLog(string strLog){string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "_" + _logLevel.ToString() + ".txt";string filePath = _config.LogPath + "\\" + fileName;File.AppendAllText(filePath, strLog);//  File.AppendAllTextAsync(filePath, strLog);}
}

3.2 ILoggerProvider实现

 public class CustomFileLoogerProvider:ILoggerProvider{private readonly CustomFileLoggerConfiguration _config;public CustomFileLoogerProvider(CustomFileLoggerConfiguration config){_config = config;}public ILogger CreateLogger(string categoryName){return new CustomFileLogger(categoryName,_config);}public void Dispose(){}}

4、业务调用

 public class HomeController : Controller{private readonly ILogger<HomeController> _logger;private readonly IDBServer dBServer;public HomeController(ILogger<HomeController> logger, IDBServer dBServer){_logger = logger;this.dBServer = dBServer;}public IActionResult Index(){dBServer.UpDataHomeViewData();return View("Index", dBServer.HomeViewData);}public IActionResult HistoricalSummary(string? SN){dBServer.UpDataHistoricalSummaryViewData(SN);return View("HistoricalSummary", dBServer.HomeViewData);}public IActionResult RecordInfo(){dBServer.UpData();this.ViewData["info"] = DateTime.Now.ToString() + dBServer.RecordViewData;return View("RecordInfo", dBServer.SNInfoLists);}[HttpPost]public string PostInfo(string SN, string DateTime, string Info){if (dBServer.UpDataDetailedInformation(SN, DateTime, Info)){return "更新成功!";}return "更新失败!";}public IActionResult About(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}} public class HomeController : Controller{private readonly ILogger<HomeController> _logger;private readonly IDBServer dBServer;public HomeController(ILogger<HomeController> logger, IDBServer dBServer){_logger = logger;this.dBServer = dBServer;}public IActionResult Index(){dBServer.UpDataHomeViewData();return View("Index", dBServer.HomeViewData);}public IActionResult HistoricalSummary(string? SN){dBServer.UpDataHistoricalSummaryViewData(SN);return View("HistoricalSummary", dBServer.HomeViewData);}public IActionResult RecordInfo(){dBServer.UpData();this.ViewData["info"] = DateTime.Now.ToString() + dBServer.RecordViewData;return View("RecordInfo", dBServer.SNInfoLists);}[HttpPost]public string PostInfo(string SN, string DateTime, string Info){if (dBServer.UpDataDetailedInformation(SN, DateTime, Info)){return "更新成功!";}return "更新失败!";}public IActionResult About(){return View();}[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]public IActionResult Error(){return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });}}

Demo下载:https://download.csdn.net/download/weixin_45114627/89594941


http://www.ppmy.cn/embedded/90392.html

相关文章

使用Rust编写一个web todolist应用

使用rust编写一个web服务不如使用java提供的spring boot一样简单&#xff0c;需要手工去添加依赖&#xff0c;目前rust web生态已趋近成熟&#xff0c;可以尝试进行web开发。 本次开发的服务使用的依赖有 axum&#xff1a;一个专注于生态和模块化的web应用开发框架serde&…

selenium自动化输入用户名和密码和验证码并登陆成功

#本文供学习交流之用 注意&#xff1a;图形验证码的识别from selenium.webdriver import Chrome from selenium.webdriver.common.by import By from chaojiying import Chaojiying_Client import time web Chrome() web.maximize_window() web.get("https://www.chaojiy…

【Mode Management】CanNm处于PBS状态下接收到一帧诊断报文DCM会响应吗

目录 前言 正文 1.CanNm从RSS状态切换到PBS状态行为分析 1.1.CanNm动作 1.2.ComM动作 1.3.DCM动作 1.4 小结 2.CanNM在PBS状态下收到一帧诊断报文行为分析 2.1.DCM动作1 2.2. ComM动作 2.3. DCM动作2 2.3. CanNm动作 2.4 问题 2.5 分析 3.总结 前言 我们知道EC…

aspeed2600 GPIO分析与适配ipmitool power status, ipmitool power on/off

1.说明 本节以x86-power-control/src/power_control.cpp为基础&#xff0c;分析整个GPIO的调用流程&#xff0c;实现简单的ipmitool power on/off,ipmitool power status的管理。 1.资源:x86-power-control:https://github.com/openbmc/x86-power-control2.相关文件: meta-ph…

【C++】STL-哈希表封装unorder_set和unordered_map

目录 1、实现哈希表的泛型 2、unordered_set和unordered_map的插入 3、迭代器 3.1 operator 3.2 const迭代器 4、find 5、unordered_map的operator[] 6、对于无法取模的类型 7、介绍unordered_set的几个函数 7.1 bucket_count 7.2 bucket_size 7.3 bucket 7.4 rese…

大厂面试必备的软件测试八股文【附答案】

&#x1f345; 点击文末小卡片 &#xff0c;免费获取软件测试全套资料&#xff0c;资料在手&#xff0c;涨薪更快 前言 最近有很多粉丝问我&#xff0c;有什么方法能够快速提升自己&#xff0c;通过阿里、腾讯、字节跳动、京东等互联网大厂的面试&#xff0c;我觉得短时间提升…

【深度学习】【框架】【基本结构】transformer

论文地址:https://arxiv.org/pdf/1706.03762 1. 整体结构 2. 内部结构 3. 公式 Transformer工作原理四部曲:Embedding(向量化)、Attention(注意力机制)、MLPs(多层感知机)和Unembedding(模型输出)。

被遗忘的哑终端 —— 键盘键位演变的启发者

注&#xff1a;机翻&#xff0c;未校对。 The Forgotten World of Dumb Terminals 被遗忘的哑终端世界 A quick journey through the lost age of “glass teletypes.” 快速穿越失落的“玻璃电传打字机”时代。 From the earliest days of digital computers, researchers o…

【C语言】Top K问题【建小堆】

前言 TopK问题&#xff1a;从n个数中&#xff0c;找出最大&#xff08;或最小&#xff09;的前k个数。 在我们生活中&#xff0c;经常会遇到TopK问题 比如外卖的必吃榜&#xff1b;成单的前K名&#xff1b;各种数据的最值筛选 问题分析 显然想开出40G的空间是不现实的&#…

Centos 8系统ext4文件系统类型进行扩容缩容 (LVM)

Centos 8系统ext4文件系统类型进行扩容缩容 &#xff08;LVM&#xff09; 1.磁盘情况&#xff1a;2.缩容home分区1.备份home数据&#xff1a;2.查找使用 /home 的进程&#xff1a;3.终止这些进程&#xff1a;4.卸载 /home 分区5.检查文件系统一致性 (e2fsck)&#xff1a;6.调整…

SSRF-labs-master靶场

目录 file_get_content.php sql_connect.php download.php dns-spoofing.php dns_rebinding.php 访问链接 http://127.0.0.1/SSRF/# file_get_content.php 在编程语言中&#xff0c;有一些函数可以获取本地保存文件的内容。这些功能可能能够从远程URL以及本地文件 如果没…

JS中运算符优先级

优先级顺序从高到低为&#xff1a; 括号 ()成员访问 . 和 函数调用 ()一元运算符 !、、-、~乘法 *、除法 /、取余 %加法 、减法 -位移运算符 <<、>>、>>>比较运算符 <、<、>、>等于 、不等于 !、严格等于 、严格不等于 !位与 &位异或 ^位…

Python | Leetcode Python题解之第315题计算右侧小于当前元素的个数

题目&#xff1a; 题解&#xff1a; import numpy as np from bisect import bisect_leftclass Solution:max_len 10000c []buckets []def countSmaller(self, nums: List[int]) -> List[int]:self.c [0 for _ in range(len(nums) 5)]counts [0 for _ in range(len(…

旧版本的Oracle OCM证书怎么升级到最新版本?

一、先来说一下OCM认证&#xff0c;全称是&#xff1a;Oracle Certified Master - Oracle认证大师&#xff0c;是Oracle数据管理员的最高级别的认证。 有了OCM证书&#xff0c;可以证明你的专业能力&#xff0c;是 Oracle 数据库管理方面具备高级和全面技能的权威认证。在竞争…

游戏加速器推荐 网游加速器排行榜

游戏加速器推荐&#xff0c;玩游戏用什么加速器&#xff01;我得给你推荐一款我常用的。首先呢&#xff0c;就是深度加速器&#xff0c;它针对目前手游网游的游戏加速效果特别棒&#xff0c;而且界面也很友好。 另外&#xff0c;还有深度加速器&#xff0c;这款加速器不仅支持国…

php的mysql操作可实现简单登录功能

文章目录 1. 表单和请求(1) 表单操作(2) 网络请求(3) $_REQUEST超全局变量 2. mysql数据库操作1) mysqli连接操作2) 操作数据库3) 预处理语句4) pdo操作数据库5) 创建连接并执行查询语句 1. 表单和请求 主要使用到**$_GET** 和 $_POST这两个超全局变量,分别对应两种请求 (1) …

deploy local llm ragflow

CPU > 4 cores RAM > 16 GB Disk > 50 GB Docker > 24.0.0 & Docker Compose > v2.26.1 下载docker&#xff1a; 官方下载方式&#xff1a;https://docs.docker.com/desktop/install/ubuntu/ 其中 DEB package需要手动下载并传输到服务器 国内下载方式&…

Jupyter NoteBook未授权访问漏洞

Jupyter NoteBook未授权访问漏洞 Jupyter Notebook(此前被称为 IPython notebook)是一个交互式笔记本&#xff0c;支持运行 40多种编程语言。如果管理员未为Jupyter Notebook配置密码&#xff0c;将导致未授权访问漏洞&#xff0c;游客可在其中创建一个console并执行任意Python…

Python | SyntaxError: invalid syntax 深度解析

Python | SyntaxError: invalid syntax 深度解析 在Python编程中&#xff0c;SyntaxError: invalid syntax是一个常见的错误&#xff0c;它表明Python解释器在尝试解析代码时遇到了语法问题。这个错误通常是由于代码中存在拼写错误、缺少符号&#xff08;如括号、冒号或逗号&a…

springboot书店销售管理系统-计算机毕业设计源码09304

摘要 随着互联网的普及和发展&#xff0c;线上书店越来越受到人们的欢迎。为了更好地管理书店的销售活动&#xff0c;提高用户体验&#xff0c;开发一个基于Springboot的书店销售管理系统是至关重要的。这种系统可以帮助书店管理员更高效地管理书籍、订单和用户信息&#xff0c…