备份C#的两个类

GuestIP依赖项:

cs 复制代码
using System.Data.SQLite; //这是第三方依赖项,要从nuget下载
cs 复制代码
static class GuestIP
{
    public static void ReadLastGuestIP(string constr = "Data Source=guestip_log.db;")
    {
        using (var connection = new SQLiteConnection(constr))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SELECT * FROM ip_guest ORDER BY id DESC LIMIT 1;";
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var id = reader.GetInt32(0); // 假设id是第一列  
                        var ts = reader.GetDateTime(1).AddHours(8); // 假设ts是第二列(日期时间)  //将UTC时间转换成北京时间 
                        var ip = reader.GetString(2); // 假设ip是第三列(文本)  
                                                      //var id = reader.GetInt32(reader.GetOrdinal("id"));
                                                      //var ts = reader.GetDateTime(reader.GetOrdinal("ts"));
                                                      //var ip = reader.GetString(reader.GetOrdinal("ip"));
                        Console.WriteLine($"ID: {id}, Timestamp: {ts}, IP: {ip}");
                    }
                }
            }
            connection.Close();
            connection.Dispose();
        }
    }
    /// <summary>
    /// 读取时间时将UTC时间处理成北京时间
    /// </summary>
    /// <param name="constr"></param>
    public static void ReadGuestIPlog(string constr = "Data Source=guestip_log.db;")
    {
        using (var connection = new SQLiteConnection(constr))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = "SELECT * FROM ip_guest";
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        var id = reader.GetInt32(0); // 假设id是第一列  
                        var ts = reader.GetDateTime(1).AddHours(8); // 假设ts是第二列(日期时间) //将UTC时间转换成北京时间 
                        var ip = reader.GetString(2); // 假设ip是第三列(文本)  
                                                      //var id = reader.GetInt32(reader.GetOrdinal("id"));
                                                      //var ts = reader.GetDateTime(reader.GetOrdinal("ts"));
                                                      //var ip = reader.GetString(reader.GetOrdinal("ip"));
                        Console.WriteLine($"ID: {id}, Timestamp: {ts}, IP: {ip}");
                    }
                }
            }
            connection.Close();
            connection.Dispose();
        }
    }
    /// <summary>
    /// 注意SQLite只存储UTC时间,读取时可以处理成北京时间。
    /// </summary>
    /// <param name="constr"></param>
    public static void CreateTableIfNotExists(string constr = "Data Source=guestip_log.db;")
    {
        using (var sqliteConnection = new SQLiteConnection(constr))
        {
            // 开始事务  
            var transaction = sqliteConnection.BeginTransaction();

            try
            {
                using (var command = sqliteConnection.CreateCommand())
                {
                    command.Transaction = transaction;
                    command.CommandText = @"  
        CREATE TABLE IF NOT EXISTS ip_guest (  
            id INTEGER PRIMARY KEY AUTOINCREMENT,  
            ts DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
            ip TEXT NOT NULL  
        )";
                    command.ExecuteNonQuery();

                    // 提交事务  
                    transaction.Commit();
                }
            }
            catch (Exception e)
            {
                // 如果出现异常,则回滚事务  
                Console.WriteLine($"An error occurred: {e.Message}");
                transaction.Rollback();
            }

            sqliteConnection.Close();
        }
    }
    public static void RecordIpToDatabase(string ip, string constr = "Data Source=guestip_log.db;")
    {
        using (var sqliteConnection = new SQLiteConnection(constr))
        {

            sqliteConnection.Open();
            using (var command = sqliteConnection.CreateCommand())
            {
                // 开始事务  
                var transaction = sqliteConnection.BeginTransaction();
                try
                {
                    command.Transaction = transaction;
                    command.CommandText = @"  
            CREATE TABLE IF NOT EXISTS ip_guest (  
                id INTEGER PRIMARY KEY AUTOINCREMENT,  
                ts DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL,
                ip TEXT NOT NULL  
            )";
                    command.ExecuteNonQuery();
                    command.CommandText = "INSERT INTO ip_guest (ip) VALUES (@ip)";
                    command.Parameters.AddWithValue("@ip", ip);
                    command.ExecuteNonQuery();

                    // 提交事务  
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    // 如果出现异常,则回滚事务  
                    Console.WriteLine($"An error occurred: {e.Message}");
                    transaction.Rollback();
                }

            }
            sqliteConnection.Close();
        }
    }
    public static void RecordIpToDatabase(TcpClient client, string constr = "Data Source=guestip_log.db;")
    {
        try
        {
            string ipAddress = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
            Console.WriteLine("Accepted connection from " + ipAddress);

            // 记录IP地址到SQLite数据库  
            RecordIpToDatabase(ipAddress, constr);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception: " + ex.Message);
        }
    }
    public static async Task RecordIpToDatabaseAsync(string ipAddress, string constr = "Data Source=guestip_log.db;")
    {
        using (var conection = new SQLiteConnection(constr))
        {
            await conection.OpenAsync();
            // 开始事务  
            var transaction = conection.BeginTransaction();
            using (var command = new SQLiteCommand())
            {
                command.Connection = conection;
                command.Transaction = transaction;
                command.CommandText = "INSERT INTO ip_guest (ip) VALUES (@ip)";
                command.Parameters.AddWithValue("@ip", ipAddress);

                await command.ExecuteNonQueryAsync();
                // 提交事务  
                transaction.Commit();
            }
            conection.Close();
        }
    }
}

Refresh依赖项:

cs 复制代码
using System.Collections.Generic;
using System.Timers;
using System;
cs 复制代码
public class Refresh
{
    private System.Timers.Timer timer = new System.Timers.Timer();
    private List<(Action updateMethod, int interval)> tasks = new List<(Action, int)>();

    public void AddTask(Action updateMethod, int interval)
    {
        tasks.Add((updateMethod, interval));
    }

    public void StartTimer()
    {
        if (timer == null)
        {
            this.timer = new System.Timers.Timer();
        }
        if (tasks.Count > 0)
        {
            int gcdInterval = GCD(tasks.Select(t => t.interval).ToArray()); // 计算所有任务间隔时间的最大公约数
            timer.Interval = gcdInterval;
        }
        else
        {
            timer.Interval = 1000 * 10; // 默认时间间隔为1000*10毫秒,10秒
        }

        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true; // 设置为true,以便定时器在每次触发后自动重置
        timer.Enabled = true;
        timer.Start();
    }
    public void RestartTimer()
    {
        timer.Stop();
        if (tasks.Count > 0)
        {
            int gcdInterval = GCD(tasks.Select(t => t.interval).ToArray()); // 计算所有任务间隔时间的最大公约数
            timer.Interval = gcdInterval;
        }
        else
        {
            timer.Interval = 1000 * 10; // 默认时间间隔为1000*10毫秒,10秒
        }

        timer.Elapsed += OnTimedEvent;
        timer.AutoReset = true; // 设置为true,以便定时器在每次触发后自动重置
        timer.Enabled = true;
        timer.Start();
    }
    public void StopTimer()
    {
        timer.Stop();
        timer.Dispose();
    }
    private void OnTimedEvent(Object source, ElapsedEventArgs e)
    {
        foreach (var task in tasks)
        {
            if (DateTime.Now.Ticks % task.interval == 0) // Check if it's time to run the task
            {
                try
                {
                    task.updateMethod();
                }
                catch (Exception ex)
                {
                    // Log or handle exception
                    Console.WriteLine($"Error executing task: {ex.Message}");
                }
            }
        }
    }
    private int GCD(int a, int b)
    {
        while (b != 0)
        {
            int temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    private int GCD(int[] numbers)
    {
        int result = numbers[0];
        for (int i = 1; i < numbers.Length; i++)
        {
            result = GCD(result, numbers[i]);
            if (result == 1) // 如果GCD已经是1,则无需继续计算
            {
                break;
            }
        }
        return result;
    }
}
相关推荐
我不是程序猿儿1 小时前
【C#】Thread.Join()、异步等待和直接join
开发语言·c#
FAREWELL000752 小时前
Unity学习总结篇(1)关于各种坐标系
学习·unity·c#·游戏引擎
编程乐趣3 小时前
一个可拖拉实现列表排序的WPF开源控件
开源·c#·.net·wpf
csdn_aspnet5 小时前
C# WinForm treeView 全选反选 点击过快节点选中状态未选中或选中状态未取消
c#·winform
爱编程的鱼5 小时前
C#接口(Interface)全方位讲解:定义、特性、应用与实践
java·前端·c#
Dongwoo Jeong7 小时前
UI架构的历史与基础入门
c#·mvc·mvvm·mvp·mvi·architecture
mascon7 小时前
C#自定义扩展方法 及 EventHandler<TEventArgs> 委托
开发语言·c#
冰茶_11 小时前
掌握LINQ:查询语法与方法语法全解析
sql·学习·microsoft·微软·c#·linq
与火星的孩子对话11 小时前
Unity3D开发AI桌面精灵/宠物系列 【六】 人物模型 语音口型同步 LipSync 、梅尔频谱MFCC技术、支持中英文自定义编辑- 基于 C# 语言开发
人工智能·unity·c#·游戏引擎·宠物·lipsync