Initial commit

This commit is contained in:
2023-05-22 09:29:58 +08:00
commit 18388c26eb
32 changed files with 1651 additions and 0 deletions

8
.gitignore vendored Normal file
View File

@@ -0,0 +1,8 @@
.idea
*.iml
*.suo
.vs
Debug
bin
obj
target

View File

@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class CommonHelper
{ /// <summary>
/// 通过字符串获取MD5值返回32位字符串。
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string GetMD5String(string str)
{
MD5 md5 = MD5.Create();
byte[] data = Encoding.UTF8.GetBytes(str);
byte[] data2 = md5.ComputeHash(data);
return GetbyteToString(data2);
//return BitConverter.ToString(data2).Replace("-", "").ToLower();
}
/// <summary>
/// 获取MD5值。HashAlgorithm.Create("MD5") 或 MD5.Create() HashAlgorithm.Create("SHA256") 或 SHA256.Create()
/// </summary>
/// <param name="str"></param>
/// <param name="hash"></param>
/// <returns></returns>
public static string GetMD5String(string str, HashAlgorithm hash)
{
byte[] data = Encoding.UTF8.GetBytes(str);
byte[] data2 = hash.ComputeHash(data);
return GetbyteToString(data2);
//return BitConverter.ToString(data2).Replace("-", "").ToLower();
}
public static string GetMD5FromFile(string path)
{
MD5 md5 = MD5.Create();
if (!File.Exists(path))
{
return "";
}
FileStream stream = File.OpenRead(path);
byte[] data2 = md5.ComputeHash(stream);
return GetbyteToString(data2);
//return BitConverter.ToString(data2).Replace("-", "").ToLower();
}
private static string GetbyteToString(byte[] data)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sb.Append(data[i].ToString("x2"));
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>DLL\Newtonsoft.Json.dll</HintPath>
</Reference>
</ItemGroup>
</Project>

151
LightSetupBase/Md5Config.cs Normal file
View File

@@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json.Serialization;
using System.Text.Json;
using System.Text.Unicode;
using System.Threading.Tasks;
namespace LightSetupBase
{
/// <summary>
/// MD5打包文件配置
/// </summary>
public class Md5Config
{
/// <summary>
/// Json配置参数
/// </summary>
/// <returns>返回值</returns>
public static JsonSerializerOptions getOption()
{
JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
{
// 整齐打印
WriteIndented = true,
// 忽略值为Null的属性
// IgnoreNullValues = true,
// 设置Json字符串支持的编码默认情况下序列化程序会转义所有非 ASCII 字符。 即,会将它们替换为 \uxxxx其中 xxxx 为字符的 Unicode
// 代码。 可以通过设置Encoder来让生成的josn字符串不转义指定的字符集而进行序列化 下面指定了基础拉丁字母和中日韩统一表意文字的基础Unicode 块
// (U+4E00-U+9FCC)。 基本涵盖了除使用西里尔字母以外所有西方国家的文字和亚洲中日韩越的文字
Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.CjkUnifiedIdeographs),
// 反序列化不区分大小写
PropertyNameCaseInsensitive = true,
// 驼峰命名
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
// 对字典的键进行驼峰命名
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
// 序列化的时候忽略null值属性
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
// 忽略只读属性因为只读属性只能序列化而不能反序列化所以在以json为储存数据的介质的时候序列化只读属性意义不大
IgnoreReadOnlyFields = true,
// 不允许结尾有逗号的不标准json
AllowTrailingCommas = false,
// 不允许有注释的不标准json
ReadCommentHandling = JsonCommentHandling.Disallow,
// 允许在反序列化的时候原本应为数字的字符串(带引号的数字)转为数字
NumberHandling = JsonNumberHandling.AllowReadingFromString,
// 处理循环引用类型比如Book类里面有一个属性也是Book类
ReferenceHandler = ReferenceHandler.Preserve
};
return jsonSerializerOptions;
}
public Md5Config()
{
this.Filter = String.Empty;
this.Contain = String.Empty;
this.FileName = String.Empty;
this.FileFormat = String.Empty;
this.GetHttpUrl = String.Empty;
this.GetHttpFormat = String.Empty;
this.PostHttpUrl = String.Empty;
this.PostHttpFormat = String.Empty;
}
/// <summary>
/// 过滤文件,请用换行符分割,支持正则表示、普通文本
/// </summary>
[Md5ConfigAttribute("过滤文件","请用换行符分割,支持正则表示、普通文本")]
public string Filter
{
get;
set;
}
/// <summary>
/// 包含文件,请用换行符分割,支持正则表示、普通文本
/// </summary>
[Md5ConfigAttribute("包含文件", "请用换行符分割,支持正则表示、普通文本")]
public string Contain
{
get;
set;
}
/// <summary>
/// 配置文件路径,默认为UTF-8格式
/// </summary>
[Md5ConfigAttribute("配置文件路径", "默认为UTF-8格式")]
public string FileName
{
get;
set;
}
/// <summary>
/// 可支持 {md5}、{其他扩展参数}其他扩展参数请通过GetHttpUrl来请求获取.返回的为Json并只支持包含1级
/// </summary>
[Md5ConfigAttribute("配置文件内容", "可支持 {md5}、{ip}、{computerName}、{其他扩展参数},其他扩展参数请通过‘获取扩展参数’来请求获取.")]
public string FileFormat
{
get;
set;
}
/// <summary>
/// 获取扩展参数Http地址请求方式为UTF-8的Application/json返回的内容为Json并只支持包含1级。
/// 包含的字段用于对配置文件格式提交Http请求的内容进行扩展。
/// </summary>
[Md5ConfigAttribute("获取扩展参数Http地址", "请求方式为UTF-8的Application/json返回的内容为Json并只支持包含1级。" +
"包含的字段用于对配置文件格式提交Http请求的内容进行扩展。")]
public string GetHttpUrl
{
get;
set;
}
/// <summary>
/// 获取扩展参数Http格式,可支持 {md5}.
/// </summary>
[Md5ConfigAttribute("获取扩展参数Http内容", "可支持 {md5}、{ip}、{computerName}.")]
public string GetHttpFormat
{
get;
set;
}
/// <summary>
/// 提交结果Http地址请求方式为UTF-8的Application/json。
/// </summary>
[Md5ConfigAttribute("提交结果Http地址", "请求方式为UTF-8的Application/json。")]
public string PostHttpUrl
{
get;
set;
}
/// <summary>
/// 提交结果Http内容,可支持 {md5}、{其他扩展参数},其他扩展参数请通过‘获取扩展参数’来请求获取.
/// </summary>
[Md5ConfigAttribute("提交结果Http内容", "可支持 {md5}、{ip}、{computerName}、{其他扩展参数},其他扩展参数请通过‘获取扩展参数’来请求获取.")]
public string PostHttpFormat
{
get;
set;
}
}
}

View File

@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupBase
{
/// <summary>
/// 名称
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class Md5ConfigAttribute : Attribute
{
public Md5ConfigAttribute()
{
this.Name = String.Empty;
this.Comment = String.Empty;
}
public Md5ConfigAttribute(string name, string comment)
{
this.Name = name;
this.Comment = comment;
}
/// <summary>
/// 属性名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 属性说明
/// </summary>
public string Comment { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupBase
{
/// <summary>
/// 配置属性
/// </summary>
public class Md5ConfigAttributeProperty : Md5ConfigAttribute
{
public Md5ConfigAttributeProperty()
{
this.PropertyName = String.Empty;
this.PropertyInfo = null;
}
/// <summary>
/// 属性名称
/// </summary>
public string PropertyName { get; set; }
/// <summary>
/// 属性信息
/// </summary>
public PropertyInfo PropertyInfo { get; set; }
}
}

View File

@@ -0,0 +1,190 @@
namespace LightSetupConfig
{
partial class FrmLightSteupConfig
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
lb_list = new ListBox();
pn_bottom = new Panel();
lb_status = new Label();
pn_top = new Panel();
bt_save_other = new Button();
bt_save = new Button();
bt_new = new Button();
bt_open = new Button();
tb_content = new TextBox();
pn_left = new Panel();
pn_bottom.SuspendLayout();
pn_top.SuspendLayout();
pn_left.SuspendLayout();
SuspendLayout();
//
// lb_list
//
lb_list.Dock = DockStyle.Fill;
lb_list.FormattingEnabled = true;
lb_list.ItemHeight = 17;
lb_list.Location = new Point(0, 0);
lb_list.Name = "lb_list";
lb_list.Size = new Size(200, 394);
lb_list.TabIndex = 2;
lb_list.SelectedIndexChanged += lb_list_SelectedIndexChanged;
//
// pn_bottom
//
pn_bottom.AutoSize = true;
pn_bottom.Controls.Add(lb_status);
pn_bottom.Dock = DockStyle.Bottom;
pn_bottom.Location = new Point(0, 433);
pn_bottom.Name = "pn_bottom";
pn_bottom.Size = new Size(800, 17);
pn_bottom.TabIndex = 3;
//
// lb_status
//
lb_status.AutoSize = true;
lb_status.Dock = DockStyle.Fill;
lb_status.Location = new Point(0, 0);
lb_status.Name = "lb_status";
lb_status.Size = new Size(44, 17);
lb_status.TabIndex = 6;
lb_status.Text = "状态栏";
//
// pn_top
//
pn_top.Controls.Add(bt_save_other);
pn_top.Controls.Add(bt_save);
pn_top.Controls.Add(bt_new);
pn_top.Controls.Add(bt_open);
pn_top.Dock = DockStyle.Top;
pn_top.Location = new Point(0, 0);
pn_top.Name = "pn_top";
pn_top.Size = new Size(800, 39);
pn_top.TabIndex = 4;
//
// bt_save_other
//
bt_save_other.Location = new Point(269, 10);
bt_save_other.Name = "bt_save_other";
bt_save_other.Size = new Size(75, 23);
bt_save_other.TabIndex = 4;
bt_save_other.Text = "另存为(&W)";
bt_save_other.UseVisualStyleBackColor = true;
bt_save_other.Click += tb_save_other_Click;
bt_save_other.MouseEnter += bt_save_other_MouseEnter;
bt_save_other.MouseLeave += bt_open_MouseLeave;
//
// bt_save
//
bt_save.Location = new Point(182, 10);
bt_save.Name = "bt_save";
bt_save.Size = new Size(75, 23);
bt_save.TabIndex = 3;
bt_save.Text = "保存(&S)";
bt_save.UseVisualStyleBackColor = true;
bt_save.Click += bt_save_Click;
bt_save.MouseEnter += bt_save_MouseEnter;
bt_save.MouseLeave += bt_open_MouseLeave;
//
// bt_new
//
bt_new.Location = new Point(8, 10);
bt_new.Name = "bt_new";
bt_new.Size = new Size(75, 23);
bt_new.TabIndex = 2;
bt_new.Text = "新建(&N)";
bt_new.UseVisualStyleBackColor = true;
bt_new.Click += bt_new_Click;
bt_new.MouseEnter += bt_new_MouseEnter;
bt_new.MouseLeave += bt_open_MouseLeave;
//
// bt_open
//
bt_open.Location = new Point(95, 10);
bt_open.Name = "bt_open";
bt_open.Size = new Size(75, 23);
bt_open.TabIndex = 2;
bt_open.Text = "打开(&O)";
bt_open.UseVisualStyleBackColor = true;
bt_open.Click += bt_open_Click;
bt_open.MouseEnter += bt_open_MouseEnter;
bt_open.MouseLeave += bt_open_MouseLeave;
//
// tb_content
//
tb_content.Dock = DockStyle.Fill;
tb_content.Location = new Point(200, 39);
tb_content.Multiline = true;
tb_content.Name = "tb_content";
tb_content.ScrollBars = ScrollBars.Vertical;
tb_content.Size = new Size(600, 394);
tb_content.TabIndex = 5;
tb_content.TextChanged += tb_content_TextChanged;
//
// pn_left
//
pn_left.Controls.Add(lb_list);
pn_left.Dock = DockStyle.Left;
pn_left.Location = new Point(0, 39);
pn_left.Name = "pn_left";
pn_left.Size = new Size(200, 394);
pn_left.TabIndex = 6;
//
// FrmLightSteupConfig
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(tb_content);
Controls.Add(pn_left);
Controls.Add(pn_top);
Controls.Add(pn_bottom);
Name = "FrmLightSteupConfig";
Text = "安装目录MD5编码生成器-配置文件管理(颜佐光)";
Load += FrmLightSteupConfig_Load;
KeyDown += FrmLightSetupConfig_KeyDown;
pn_bottom.ResumeLayout(false);
pn_bottom.PerformLayout();
pn_top.ResumeLayout(false);
pn_left.ResumeLayout(false);
ResumeLayout(false);
PerformLayout();
}
#endregion
private ListBox lb_list;
private Panel pn_bottom;
private Panel pn_top;
private TextBox tb_content;
private Label lb_status;
private Button bt_save_other;
private Button bt_save;
private Button bt_open;
private Panel pn_left;
private Button bt_new;
}
}

View File

@@ -0,0 +1,255 @@
using LightSetupBase;
using System.Reflection;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Unicode;
using System.Web;
namespace LightSetupConfig
{
public partial class FrmLightSteupConfig : Form
{
private string path;
private Md5Config md5Config = new Md5Config();
public FrmLightSteupConfig()
{
InitializeComponent();
}
private void FrmLightSteupConfig_Load(object sender, EventArgs e)
{
this.initBind();
}
private void bt_new_Click(object sender, EventArgs e)
{
NewFile();
}
private void bt_open_Click(object sender, EventArgs e)
{
Open();
}
private void bt_save_Click(object sender, EventArgs e)
{
Save();
}
private void tb_save_other_Click(object sender, EventArgs e)
{
SaveOther();
}
private void lb_list_SelectedIndexChanged(object sender, EventArgs e)
{
readToContent();
}
private void tb_content_TextChanged(object sender, EventArgs e)
{
writeFromContent();
}
private void FrmLightSetupConfig_KeyDown(object sender, KeyEventArgs e)
{
// <20><><EFBFBD>ϼ<EFBFBD>
if (e.KeyCode == Keys.O && e.Modifiers == Keys.Control) //Ctrl+O
{
Open();
}
else if (e.KeyCode == Keys.S && e.Modifiers == Keys.Control) //Ctrl+S
{
Save();
}
else if (e.KeyCode == Keys.S && (int)e.Modifiers == ((int)Keys.Control + (int)Keys.Alt)) //Ctrl+Alt+S
{
SaveOther();
}
}
private void bt_new_MouseEnter(object sender, EventArgs e)
{
showStatus("<22><><EFBFBD>ݼ<EFBFBD>: Ctrl + N , Alt + N ");
}
private void bt_open_MouseEnter(object sender, EventArgs e)
{
showStatus("<22><><EFBFBD>ݼ<EFBFBD>: Ctrl + O , Alt + O ");
}
private void bt_save_MouseEnter(object sender, EventArgs e)
{
showStatus("<22><><EFBFBD>ݼ<EFBFBD>: Ctrl + S <20><> Alt + S ");
}
private void bt_save_other_MouseEnter(object sender, EventArgs e)
{
showStatus("<22><><EFBFBD>ݼ<EFBFBD>: Ctrl + Alt + S , Alt + W");
}
private void bt_open_MouseLeave(object sender, EventArgs e)
{
this.showStatus(String.Empty);
}
private void NewFile()
{
this.md5Config = new Md5Config();
this.initBind();
}
private void Open()
{
try
{
OpenFileDialog fbd = new OpenFileDialog();
fbd.Filter = "Image Files (*.config)|*.config";
if (fbd.ShowDialog() == DialogResult.OK)
{
this.path = fbd.FileName;
string json = File.ReadAllText(this.path, Encoding.UTF8);
this.md5Config = JsonSerializer.Deserialize<Md5Config>(json, Md5Config.getOption());
this.initBind();
}
}
catch (Exception ex)
{
showError(ex);
}
}
private void Save()
{
try
{
if (String.IsNullOrEmpty(this.path))
{
this.SaveOther();
}
else
{
this.saveHandle();
}
}
catch (Exception ex)
{
showError(ex);
}
}
private void SaveOther()
{
try
{
if (this.showSaveDialog())
{
this.saveHandle();
}
}
catch (Exception ex)
{
showError(ex);
}
}
private void saveHandle()
{
string json = JsonSerializer.Serialize(this.md5Config, Md5Config.getOption());
File.WriteAllText(this.path, json, Encoding.UTF8);
}
private bool showSaveDialog()
{
SaveFileDialog saveImageDialog = new SaveFileDialog();
saveImageDialog.Filter = "Image Files (*.config)|*.config";
//openImageDialog.Multiselect = false;
if (saveImageDialog.ShowDialog() == DialogResult.OK)
{
this.path = saveImageDialog.FileName;
return true;
}
return false;
}
private void initBind()
{
// <20>б<EFBFBD>
List<Md5ConfigAttributeProperty> list = new List<Md5ConfigAttributeProperty>();
// <20><><EFBFBD><EFBFBD>
Type info = typeof(Md5Config);
PropertyInfo[] propertyInfos = info.GetProperties();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
Md5ConfigAttribute? md5ConfigAttribute = propertyInfo.GetCustomAttribute<Md5ConfigAttribute>();
Md5ConfigAttributeProperty item = new Md5ConfigAttributeProperty();
item.PropertyName = propertyInfo.Name;
item.PropertyInfo = propertyInfo;
if (md5ConfigAttribute == null)
{
item.Name = propertyInfo.Name;
item.Comment = "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֶ<EFBFBD>" + propertyInfo.Name;
}
else
{
item.Name = md5ConfigAttribute.Name;
item.Comment = md5ConfigAttribute.Comment;
}
list.Add(item);
}
this.lb_list.DataSource = null;
this.lb_list.DisplayMember = "Name";
this.lb_list.ValueMember = "PropertyName";
this.lb_list.DataSource = list;
}
private void readToContent()
{
Md5ConfigAttributeProperty selectedItem = (Md5ConfigAttributeProperty)this.lb_list.SelectedItem;
if (selectedItem == null)
{
return;
}
this.showStatus(selectedItem.Comment);
this.tb_content.Text = (string)selectedItem.PropertyInfo.GetValue(this.md5Config);
}
private void writeFromContent()
{
Md5ConfigAttributeProperty selectedItem = (Md5ConfigAttributeProperty)this.lb_list.SelectedItem;
if (selectedItem == null)
{
return;
}
selectedItem.PropertyInfo.SetValue(this.md5Config, this.tb_content.Text);
}
private void showError(Exception ex)
{
MessageBox.Show(ex.ToString(), "<22><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʾ");
}
private void showStatus(string msg)
{
if (String.IsNullOrEmpty(msg) && String.IsNullOrEmpty(this.path))
{
this.lb_status.Text = "״̬<D7B4><CCAC>,<2C><><EFBFBD>ǵñ<C7B5><C3B1><EFBFBD><EFBFBD>ļ<EFBFBD>!";
}
else if (String.IsNullOrEmpty(msg))
{
this.lb_status.Text = "״̬<D7B4><CCAC>,<2C>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD>·<EFBFBD><C2B7>Ϊ:" + this.path;
}
else
{
this.lb_status.Text = msg;
}
}
}
}

View File

@@ -0,0 +1,60 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\LightSetupBase\LightSetupBase.csproj" />
<ProjectReference Include="..\LightSetupMd5\LightSetupMd5.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Update="FrmLightSteupConfig.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project>

View File

@@ -0,0 +1,17 @@
namespace LightSetupConfig
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new FrmLightSteupConfig());
}
}
}

View File

@@ -0,0 +1,17 @@
namespace LightSetupMd5
{
internal class ComputerHelper
{
internal string GetComputerName()
{
try
{
return System.Environment.MachineName;
}
catch (Exception e)
{
return "不能获取计算机名称";
}
}
}
}

24
LightSetupMd5/IpHelper.cs Normal file
View File

@@ -0,0 +1,24 @@
using System.Net;
using System.Text;
namespace LightSetupMd5
{
internal class IpHelper
{
internal string GetIp()
{
StringBuilder sb = new StringBuilder();
IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in ipEntry.AddressList)
{
if (sb.Length > 0)
{
sb.Append(",");
}
sb.Append(ip.ToString());
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\LightSetupBase\LightSetupBase.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,37 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33516.290
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LightSetupMd5", "LightSetupMd5.csproj", "{CCA3C50D-2B53-4314-BBF5-B5E192869014}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LightSetupConfig", "..\LightSetupConfig\LightSetupConfig.csproj", "{E6EB2AC1-2BD8-449D-8A55-863371E0F319}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LightSetupBase", "..\LightSetupBase\LightSetupBase.csproj", "{3670C18B-7146-44DE-BE40-F8F9B7F8FC19}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{CCA3C50D-2B53-4314-BBF5-B5E192869014}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CCA3C50D-2B53-4314-BBF5-B5E192869014}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CCA3C50D-2B53-4314-BBF5-B5E192869014}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CCA3C50D-2B53-4314-BBF5-B5E192869014}.Release|Any CPU.Build.0 = Release|Any CPU
{E6EB2AC1-2BD8-449D-8A55-863371E0F319}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E6EB2AC1-2BD8-449D-8A55-863371E0F319}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E6EB2AC1-2BD8-449D-8A55-863371E0F319}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E6EB2AC1-2BD8-449D-8A55-863371E0F319}.Release|Any CPU.Build.0 = Release|Any CPU
{3670C18B-7146-44DE-BE40-F8F9B7F8FC19}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3670C18B-7146-44DE-BE40-F8F9B7F8FC19}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3670C18B-7146-44DE-BE40-F8F9B7F8FC19}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3670C18B-7146-44DE-BE40-F8F9B7F8FC19}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {97A9193F-3D84-400C-8CB5-5A059853BD0C}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,21 @@
using LightSetupBase;
using System.Text;
namespace LightSetupMd5
{
internal class Md5ConfigFile
{
public void WriteFile(Md5MainArgs arg, Md5Config config, Dictionary<string, string> extendPara)
{
string content = Md5Format.GetFormat(config.FileFormat, extendPara);
string fileName = Path.GetFullPath(config.FileName);
string dic = Path.GetDirectoryName(fileName);
//如果目录不存在则创建该目录
if (!Directory.Exists(dic))
{
Directory.CreateDirectory(dic);
}
File.WriteAllText(fileName, content, Encoding.UTF8);
}
}
}

View File

@@ -0,0 +1,61 @@
using LightSetupBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5ConfigRead
{
private const string Separator = "\n";
public Md5Config ReadConfig(Md5MainArgs arg)
{
if (!File.Exists(arg.ConfigPath))
{
throw new Exception("配置文件" + arg.ConfigPath + "不存在");
}
string json = File.ReadAllText(arg.ConfigPath, Encoding.UTF8);
Md5Config config = JsonSerializer.Deserialize<Md5Config>(json, Md5Config.getOption());
if (String.IsNullOrEmpty(config.FileName))
{
config.FileName = "md5_version.json";
}
if (String.IsNullOrEmpty(config.FileFormat))
{
config.FileName = @"{
""md5"":""{md5}"",
""ip"":""{ip}"",
""computerName"":""{computerName}""
}";
}
config.Filter = convertFilter(config.Filter);
config.Contain = convertFilter(config.Contain);
return config;
}
private string convertFilter(string filter)
{
string[] strings = filter.Split(Separator);
StringBuilder sb = new StringBuilder();
foreach (string str in strings)
{
string to = str.Trim();
if (String.IsNullOrEmpty(to))
{
continue;
}
if (sb.Length > 0)
{
sb.Append(Separator);
}
sb.Append(to);
}
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,14 @@
namespace LightSetupMd5
{
internal class Md5DefaultParamter
{
internal Dictionary<string, string> getPara(string md5, string ip, string computerName)
{
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
keyValuePairs.Add("md5", md5);
keyValuePairs.Add("computerName", computerName);
keyValuePairs.Add("ip", ip);
return keyValuePairs;
}
}
}

View File

@@ -0,0 +1,70 @@
using LightSetupBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5FileFIlter
{
public List<FileInfo> GetFiles(Md5MainArgs arg, Md5Config config)
{
// 获取所有的文件信息
List<FileInfo> fileInfo = new List<FileInfo>();
string[] filter = config.Filter.Split("\n");
string[] contain = config.Contain.Split("\n");
addFileInfo(fileInfo, arg, config, filter, contain, new DirectoryInfo(arg.RunPath));
return fileInfo;
}
private void addFileInfo(List<FileInfo> fileInfo, Md5MainArgs arg, Md5Config config,
string[] filter, string[] contain, DirectoryInfo directoryInfo)
{
FileInfo[] fileInfos = directoryInfo.GetFiles();
foreach (FileInfo file in fileInfos)
{
if (fileFilter(arg, filter, contain, file))
{
fileInfo.Add(file);
}
}
DirectoryInfo[] directoryInfos = directoryInfo.GetDirectories();
foreach (DirectoryInfo dic in directoryInfos)
{
addFileInfo(fileInfo, arg, config, filter, contain, dic);
}
}
private bool fileFilter(Md5MainArgs arg, string[] filter, string[] contain, FileInfo file)
{
if (arg.ConfigPath == file.FullName)
{
return false;
}
string absoluteFile = file.FullName.Substring(arg.RunPath.Length);
bool b = false;
foreach (string item in contain)
{
bool isMatch = absoluteFile.Contains(item) || Regex.IsMatch(absoluteFile, item);
if (isMatch)
{
return true;
}
}
foreach (string item in filter)
{
bool isMatch = absoluteFile.Contains(item) || Regex.IsMatch(absoluteFile, item);
if (isMatch)
{
return false;
}
}
return true;
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5FileInfo
{
public Md5FileInfo() { }
public Md5FileInfo(string md5, string path)
{
this.Md5 = md5;
this.AbsolutePath = path;
}
/// <summary>
/// MD5文件名
/// </summary>
public string Md5 { get; set; }
/// <summary>
/// 相对路径
/// </summary>
public string AbsolutePath { get; set; }
}
}

View File

@@ -0,0 +1,75 @@
using System.Text.RegularExpressions;
using System.Text;
using LightSetupMd5;
using System.Linq;
namespace LightSetupMd5
{
internal class Md5Format
{
private static Regex reg = new Regex("\\{(.+?)\\}");
public static string GetFormat(string fileFormat, Dictionary<string, string> extendPara)
{
return getCodeStringArray(fileFormat, extendPara);
}
/**
* 获取字段替换值
*
* @param from 来源字符串
* @param targets  值对象
* @return 处理后的值对象
*/
public static string getCodeStringArray(string from, Dictionary<string, string> targets)
{
return getFormat(from, String.Empty, new StringFormatHandleDictionary(targets));
}
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="defaultField"></param>
/// <param name="fieldFormatHandle"></param>
/// <returns></returns>
public static string getFormat(string format, string defaultField, StringFormatHandle fieldFormatHandle)
{
StringBuilder sb = new StringBuilder();
MatchCollection matches = reg.Matches(format);
int start = 0;
foreach (Match match in matches)
{
if (!match.Success)
{
continue;
}
int index = match.Index;
int len = index - start;
if (len > 0)
{
sb.Append(format, start, index - start);
}
string group = match.Groups[0].Value;
string fieldFull = match.Groups[1].Value;
if (fieldFull.StartsWith("0") && !string.IsNullOrEmpty(defaultField))
{
fieldFull = defaultField + fieldFull.Substring(1);
}
string[] fields = fieldFull.Split(":");
string field = fields[0];
string fieldFormat = string.Empty;
if (fields.Length > 1)
{
fieldFormat = fieldFull.Substring(field.Length + 1);
}
fieldFormatHandle.addPos(sb, group, fieldFull, field, fieldFormat);
start = index + match.Length;
}
sb.Append(format.Substring(start));
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,48 @@
using LightSetupBase;
using System.Text.Json;
namespace LightSetupMd5
{
internal class Md5HttpExtend
{
public Dictionary<string, string> RequestAsync(Md5MainArgs arg, Md5Config config, Dictionary<string, string> defaultPara)
{
Dictionary<string, string> ret = new Dictionary<string, string>();
if (!arg.GetExtend)
{
WriteDefault(ret, defaultPara);
return ret;
}
string json = Md5HttpRequest.Request(config.GetHttpUrl, config.GetHttpFormat, defaultPara);
if (String.IsNullOrEmpty(json))
{
WriteDefault(ret, defaultPara);
return ret;
}
// 转换为合法的数据
Dictionary<string, object> res = JsonSerializer.Deserialize<Dictionary<string, object>>(json);
foreach (KeyValuePair<string, object> kvp in res)
{
if (kvp.Value == null)
{
continue;
}
ret.Add(kvp.Key, kvp.Value.ToString());
}
WriteDefault(ret, defaultPara);
return ret;
}
private void WriteDefault(Dictionary<string, string> ret, Dictionary<string, string> defaultPara)
{
foreach (KeyValuePair<string, string> kvp in defaultPara)
{
ret.Add(kvp.Key, kvp.Value.ToString());
}
}
}
}

View File

@@ -0,0 +1,17 @@
using LightSetupBase;
namespace LightSetupMd5
{
internal class Md5HttpPost
{
internal void Request(Md5MainArgs arg, Md5Config config, Dictionary<string, string> extendPara)
{
if (!arg.Post)
{
return;
}
Md5HttpRequest.Request(config.PostHttpUrl, config.PostHttpFormat, extendPara);
}
}
}

View File

@@ -0,0 +1,60 @@
using LightSetupBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5HttpRequest
{
public static string Request(string url, string format, Dictionary<string, string> para)
{
if (String.IsNullOrEmpty(url))
{
return String.Empty;
}
string contentFrom = Md5Format.GetFormat(format, para);
using (var client = new HttpClient())
{
Task<HttpResponseMessage> task;
if (!String.IsNullOrEmpty(contentFrom))
{
Console.WriteLine("POST:" + url + ":" + contentFrom);
StringContent content;
if (contentFrom.StartsWith("{"))
{
content = new StringContent(contentFrom, Encoding.UTF8, "application/json");
}
else if (contentFrom.StartsWith("<"))
{
content = new StringContent(contentFrom, Encoding.UTF8, "application/xml");
}
else
{
content = new StringContent(contentFrom, Encoding.UTF8);
}
task = client.PostAsync(url, content);
}
else
{
Console.WriteLine("GET:" + url);
task = client.GetAsync(url);
}
task.Wait();
HttpResponseMessage response = task.GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();//用来抛异常的
Task<string> taskResult = response.Content.ReadAsStringAsync();
taskResult.Wait();
string responseBody = taskResult.GetAwaiter().GetResult();
Console.WriteLine("Response:" + url + ":" + responseBody);
return responseBody;
}
}
}
}

View File

@@ -0,0 +1,59 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5InitMainArgs
{
public Md5MainArgs InitArgs(string[] args)
{
// string config = ". -c=md5_config.config ";
Md5MainArgs md5MainArgs = new Md5MainArgs();
foreach (string arg in args)
{
if (arg.StartsWith("-c="))
{
md5MainArgs.ConfigPath = arg.Substring("-c=".Length);
}
else if (arg.StartsWith("-h"))
{
md5MainArgs.Help = true;
}
else if (arg.StartsWith("-notPost"))
{
md5MainArgs.Post = false;
}
else if (arg.StartsWith("-notGetExtend"))
{
md5MainArgs.GetExtend = false;
}
else if (arg.StartsWith("-"))
{
}
else
{
md5MainArgs.RunPath = arg;
}
}
md5MainArgs.RunPath = Path.GetFullPath(md5MainArgs.RunPath);
md5MainArgs.ConfigPath = Path.GetFullPath(md5MainArgs.ConfigPath);
return md5MainArgs;
}
public void ShowHelper()
{
Console.WriteLine("MD5目录签名工具:\n");
Console.WriteLine("命令格式为: LightSetupMd5.exe [计算目录] [-h] [-c=配置文件] ");
Console.WriteLine("\n参数:\n");
Console.WriteLine("\t计算目录:默认为当前目录.");
Console.WriteLine("\t-h : 开启帮助。");
Console.WriteLine("\t-c=配置文件名 : 自定义配置文件,配置文件名为: md5_build.config 。");
Console.WriteLine("\t-notPost : 不提交HTTP服务器。");
Console.WriteLine("\t-notGetExtend : 不获取扩展参数。");
}
}
}

View File

@@ -0,0 +1,41 @@
using LightSetupBase;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class Md5MainArgs
{
public Md5MainArgs()
{
this.Help = false;
this.GetExtend = true;
this.Post = true;
this.RunPath = ".";
this.ConfigPath = "md5_build.config";
}
/// <summary>
/// 开启帮助
/// </summary>
public bool Help { get; set; }
/// <summary>
/// 扩展信息
/// </summary>
public bool GetExtend { get; set; }
/// <summary>
/// 发送到服务器
/// </summary>
public bool Post { get; set; }
/// <summary>
/// 运行路径
/// </summary>
public string RunPath { get; set; }
/// <summary>
/// 配置文件路径
/// </summary>
public string ConfigPath { get; set; }
}
}

View File

@@ -0,0 +1,95 @@
using LightSetupBase;
using LightSetupMd5;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Generic;
using System;
namespace LightSetupMd5
{
internal class Md5Release
{
public string GetMd5(Md5MainArgs arg, List<FileInfo> fileInfos)
{
List<Md5FileInfo> fileInfo = new List<Md5FileInfo>();
foreach (FileInfo file in fileInfos)
{
fileInfo.Add(new Md5FileInfo(Md5(file), getFilePath(arg, file)));
}
return filesToMd5(fileInfo);
}
private string Md5(FileInfo file)
{
try
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal;
using (FileStream fileStream = file.OpenRead())
{
retVal = md5.ComputeHash(fileStream);
fileStream.Close();
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
string fileMd5 = sb.ToString();
Console.WriteLine("文件" + file.FullName + "的md5值为" + fileMd5);
return fileMd5;
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
private string getFilePath(Md5MainArgs arg, FileInfo file)
{
return file.FullName.Substring(arg.RunPath.Length);
}
private string filesToMd5(List<Md5FileInfo> fileInfo)
{
//升序
fileInfo.Sort((a, b) => (a.Md5 + a.AbsolutePath).CompareTo(b.Md5 + b.AbsolutePath));
StringBuilder sb = new StringBuilder();
foreach (Md5FileInfo file in fileInfo)
{
if (sb.Length > 0)
{
sb.Append(":");
}
sb.Append(file.Md5);
sb.Append("_");
sb.Append(file.AbsolutePath);
}
string md5 = textMd5(sb.ToString());
Console.WriteLine("整个目录的md5值为:" + md5);
return md5;
}
private string textMd5(string text)
{
StringBuilder sb = new StringBuilder();
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
byte[] data = md5.ComputeHash(Encoding.UTF8.GetBytes(text));
int length = data.Length;
for (int i = 0; i < length; i++)
{
sb.Append(data[i].ToString("x2"));
}
return (sb.ToString());
}
}
}
}

52
LightSetupMd5/Program.cs Normal file
View File

@@ -0,0 +1,52 @@

// See https://aka.ms/new-console-template for more information
using System.Text.Json;
using System.Text;
using LightSetupBase;
using System.Reflection;
namespace LightSetupMd5 // Note: actual namespace depends on the project name.
{
internal class Program
{
static void Main(string[] args)
{
try
{
Md5InitMainArgs argsHandle = new Md5InitMainArgs();
Md5MainArgs arg = argsHandle.InitArgs(args);
if (arg.Help)
{
argsHandle.ShowHelper();
return;
}
Md5Config config = new Md5ConfigRead().ReadConfig(arg);
// 需要检测md5的文件名
List<FileInfo> fileInfos = new Md5FileFIlter().GetFiles(arg, config);
// 获取md5值
string md5 = new Md5Release().GetMd5(arg, fileInfos);
// 获取Ip
string ip = new IpHelper().GetIp();
// 获取Ip
string computerName = new ComputerHelper().GetComputerName();
// 获取默认参数
Dictionary<string, string> defaultPara = new Md5DefaultParamter().getPara(md5, ip, computerName);
// 获取扩展参数
Dictionary<string, string> extendPara = new Md5HttpExtend().RequestAsync(arg, config, defaultPara);
// 生成文件
new Md5ConfigFile().WriteFile(arg, config, extendPara);
// 生成文件
new Md5HttpPost().Request(arg, config, extendPara);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

View File

@@ -0,0 +1,9 @@
{
"profiles": {
"LightSetupMd5": {
"commandName": "Project",
"commandLineArgs": ". -c=md5_build_xx.config",
"workingDirectory": "D:\\Source\\demo\\LightSetupConfig\\bin\\Debug\\net6.0-windows"
}
}
}

View File

@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
/// <summary>
/// 字符串格式化参数
/// @author 颜佐光
/// </summary>
internal interface StringFormatHandle
{
/**
* 对模板进行格式化处理
*
* @param sb 返回得结果模板
* @param group 带{xxx}的全格式
* @param fieldFull 全格式
* @param field 字段
* @param command 字段格式化
*/
void addPos(StringBuilder sb, string group, string fieldFull, string field, string command);
}
}

View File

@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LightSetupMd5
{
internal class StringFormatHandleDictionary : StringFormatHandle
{
private Dictionary<string, string> targets;
public StringFormatHandleDictionary(Dictionary<string, string> targets)
{
this.targets = targets;
}
public void addPos(StringBuilder sb, string group, string fieldFull, string field, string command)
{
if (!targets.ContainsKey(field))
{
return;
}
string value = targets[field];
if (!string.IsNullOrEmpty(value))
{
sb.Append(value);
}
}
}
}