初始化上传

This commit is contained in:
2025-08-26 08:37:44 +08:00
commit 31d81b91b6
448 changed files with 80981 additions and 0 deletions

View File

@@ -0,0 +1,123 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using .Base;
using EasyModbus;
using MES.Utility.Core;
using System.Windows;
using .Utility.Network.Mitsubishi;
using System.Linq;
using Avalonia.Threading;
namespace .ViewModel._01PLC通信调试
{
public class MC3E服务模拟ViewModel : ViewModelBase
{
internal static MC3EServer server;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public int Port { get; set; } = 5001;
private List<string> logMessageList = new List<string>();
public string Message
{
get
{
return logMessageList.GetStrArray("\r\n");
}
set
{
NotifyPropertyChanged();
}
}
public string ButtonText { get; set; } = "开启服务";
private ushort _startAddess = 1;
public ushort StartAddress
{
get { return _startAddess; }
set
{
_startAddess = value;
SetEveryList();
NotifyPropertyChanged();
}
}
public int SelectIndex1 { get; set; } = -1;
public ObservableCollection<MyDataGrid> List1 { get; set; } = new ObservableCollection<MyDataGrid>();
public DelegateCommand StartCmd { get; set; }
public DelegateCommand CellClickCmd { get; set; }
public MC3E服务模拟ViewModel()
{
StartCmd = new DelegateCommand(StartCmdFunc);
}
private void StartCmdFunc(object obj)
{
if (ButtonText == "开启服务")
{
server = new MC3EServer(Port);
server.Start();
//监听数据变化
server.DataChangedEvent += DataChanged;
server.LogChangedEvent += LogDataChanged;
SetEveryList();
Enabled1 = false;
Enabled2 = true;
ButtonText = "停止服务";
}
else
{
logMessageList.Clear();
Message = Guid.NewGuid().ToString();
server.Stop();
server = null;
List1.Clear();
Enabled1 = true;
Enabled2 = false;
ButtonText = "开启服务";
}
}
private void LogDataChanged(string message)
{
try
{
logMessageList.Insert(0, message);
while (logMessageList.Count > 50)
{
logMessageList.RemoveAt(logMessageList.Count - 1);
}
}
catch (Exception) { }
Message = Guid.NewGuid().ToString();
}
private void SetEveryList()
{
Dispatcher.UIThread.Invoke(() =>
{
ushort startAddress = StartAddress;
List1.Clear();
for (int i = startAddress; i < 10 + startAddress; i++)
{
MyDataGrid data = new MyDataGrid { Which = 3, Address = i, Value2 = MC3EServer._dataStorage[i] };
List1.Add(data);
}
});
}
private void DataChanged(int address)
{
SetEveryList();
}
}
}

View File

@@ -0,0 +1,293 @@
using MES.Utility.Network;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using .Base;
namespace .ViewModel._01PLC通信调试
{
public class ModbusRTUViewModel : ViewModelBase
{
public int SlaveId { get; set; } = 1;
//串口号下拉列表数据
public List<string> SerialList { get; set; }
public int SerialIndex { get; set; } = 0;
/// <summary>
/// 波特率
/// </summary>
public List<int> BaudRateList { get; set; }
public int BaudRateIndex { get; set; } = 0;
//校验
public List<string> ParityList { get; set; }
public int ParityIndex { get; set; } = 0;
//数据为
public List<int> DataBitList { get; set; }
public int DataBitIndex { get; set; } = 0;
//停止位
public List<string> StopBitList { get; set; }
public int StopBitIndex { get; set; } = 0;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public int Address { get; set; } = 4001;
public int StringLength { get; set; } = 100;
public string ReadedValue { get; set; } = "";
public string Message { get; set; } = "";
public string SendedBytesValue { get; set; } = "";
public string RecivedBytesValue { get; set; } = "";
public string Int16Value { get; set; } = "";
public string Int32Value { get; set; } = "";
public string RealValue { get; set; } = "";
public string StringValue { get; set; } = "";
public string DoubleValue { get; set; } = "";
public string LongValue { get; set; } = "";
//STRING DOUBLE INT64 INT32 INT16 REAL
private ModbusHelper modbus;
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public ModbusRTUViewModel()
{
//串口号
string[] portNames = SerialPort.GetPortNames();
if (portNames != null && portNames.Length > 0)
{
SerialList = portNames.ToList();
}
//波特率
BaudRateList = new List<int>() { 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, 128000 };
BaudRateIndex = 6;
//校验
ParityList = new List<string> { "None", "Odd", "Even", "Mark", "Space" };
ParityIndex = 0;
//数据位
DataBitList = new List<int> { 5, 6, 7, 8 };
DataBitIndex = 3;
//停止位
StopBitList = new List<string> { "None", "One", "Two", "OnePointFive" };
StopBitIndex = 1;
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
private void ConnectCmdFunc(object obj)
{
try
{
SharpModbus.SerialSettings setting = new SharpModbus.SerialSettings();
setting.PortName = SerialList[SerialIndex];
setting.BaudRate = BaudRateList[BaudRateIndex];
setting.DataBits = DataBitList[DataBitIndex];
setting.Parity = (Parity)ParityIndex;
setting.StopBits = (StopBits)StopBitIndex;
modbus = new ModbusHelper(setting, 500, (byte)SlaveId);
modbus.OnSended += Modbus_OnSended;
modbus.OnRecived += Modbus_OnRecived;
Enabled1 = false;
Enabled2 = true;
}
catch
{
return;
}
}
private void DisconnectCmdFunc(object obj)
{
modbus.OnSended -= Modbus_OnSended;
modbus.OnRecived -= Modbus_OnRecived;
modbus.Dispose();
modbus = null;
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
string cmd = obj.ToString();
ReadedValue = "";
Message = "";
SendedBytesValue = "";
RecivedBytesValue = "";
if (cmd == "INT16")
{
ushort value;
bool flag = modbus.ReadHoldRegisterInt16(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "INT32")
{
int value;
bool flag = modbus.ReadHoldRegisterInt32(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "INT64")
{
long value;
bool flag = modbus.ReadHoldRegisterInt64(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "REAL")
{
float value;
bool flag = modbus.ReadHoldRegisterFloat(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "DOUBLE")
{
double value;
bool flag = modbus.ReadHoldRegisterDouble(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "STRING")
{
string value;
bool flag = modbus.ReadHoldRegisterString(Address, StringLength, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
// DOUBLE
}
private void WriteCmdFunc(object obj)
{
string cmd = obj.ToString();
ReadedValue = "";
Message = "";
SendedBytesValue = "";
RecivedBytesValue = "";
if (cmd == "INT16")
{
ushort value;
bool flag = ushort.TryParse(Int16Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt16(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT32")
{
int value;
bool flag = int.TryParse(Int32Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt32(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT64")
{
long value;
bool flag = long.TryParse(LongValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt64(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "REAL")
{
float value;
bool flag = float.TryParse(RealValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterFloat(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "DOUBLE")
{
double value;
bool flag = double.TryParse(DoubleValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterDouble(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "STRING")
{
bool flag = modbus.WriteHoldRegisterString(Address, StringLength, StringValue);
Message = flag ? "写入成功" : "写入失败";
}
}
private void Modbus_OnRecived(byte[] bytes, string hexString)
{
RecivedBytesValue = hexString;
}
private void Modbus_OnSended(byte[] bytes, string hexString)
{
SendedBytesValue = hexString;
}
}
}

View File

@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using .Base;
using EasyModbus;
using MES.Utility.Core;
using System.Windows;
using Avalonia.Threading;
namespace .ViewModel._01PLC通信调试
{
public class Modbus服务ViewModel : ViewModelBase
{
internal static ModbusServer server;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public int Port { get; set; } = 502;
private List<string> logMessageList = new List<string>();
public string Message
{
get
{
return logMessageList.GetStrArray("\r\n");
}
set
{
NotifyPropertyChanged();
}
}
public string ButtonText { get; set; } = "开启服务";
private ushort _startAddess = 1;
public ushort StartAddress
{
get { return _startAddess; }
set
{
_startAddess = value;
SetEveryList();
NotifyPropertyChanged();
}
}
public int SelectIndex1 { get; set; } = -1;
public int SelectIndex2 { get; set; } = -1;
public int SelectIndex3 { get; set; } = -1;
public int SelectIndex4 { get; set; } = -1;
public ObservableCollection<MyDataGrid> List1 { get; set; } = new ObservableCollection<MyDataGrid>();
public ObservableCollection<MyDataGrid> List2 { get; set; } = new ObservableCollection<MyDataGrid>();
public ObservableCollection<MyDataGrid> List3 { get; set; } = new ObservableCollection<MyDataGrid>();
public ObservableCollection<MyDataGrid> List4 { get; set; } = new ObservableCollection<MyDataGrid>();
public DelegateCommand StartCmd { get; set; }
public DelegateCommand CellClickCmd { get; set; }
public Modbus服务ViewModel()
{
StartCmd = new DelegateCommand(StartCmdFunc);
}
private void StartCmdFunc(object obj)
{
if (ButtonText == "开启服务")
{
server = new ModbusServer(Port);
server.Start();
//监听数据变化
server.CoilsChanged += new ModbusServer.CoilsChangedHandler(CoilsChanged);
server.HoldingRegistersChanged += new ModbusServer.HoldingRegistersChangedHandler(HoldingRegistersChanged);
server.LogDataChanged += new ModbusServer.LogDataChangedHandler(LogDataChanged);
SetEveryList();
Enabled1 = false;
Enabled2 = true;
ButtonText = "停止服务";
}
else
{
logMessageList.Clear();
Message = Guid.NewGuid().ToString();
server.Dispose();
server = null;
List1.Clear(); List2.Clear(); List3.Clear(); List4.Clear();
Enabled1 = true;
Enabled2 = false;
ButtonText = "开启服务";
}
}
private void LogDataChanged()
{
Dispatcher.UIThread.Invoke(() =>
{
try
{
logMessageList.Clear();
string listBoxData;
for (int i = 0; i < server.ModbusLogData.Length; i++)
{
if (server.ModbusLogData[i] == null)
break;
if (server.ModbusLogData[i].request)
{
listBoxData = server.ModbusLogData[i].timeStamp.ToString("H:mm:ss.ff") + " Request from Client - Functioncode: " + server.ModbusLogData[i].functionCode.ToString();
if (server.ModbusLogData[i].functionCode <= 4)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " Quantity: " + server.ModbusLogData[i].quantity.ToString();
}
if (server.ModbusLogData[i].functionCode == 5)
{
listBoxData = listBoxData + " ; Output Address: " + server.ModbusLogData[i].startingAdress.ToString() + " Output Value: ";
if (server.ModbusLogData[i].receiveCoilValues[0] == 0)
listBoxData = listBoxData + "False";
if (server.ModbusLogData[i].receiveCoilValues[0] == 0xFF00)
listBoxData = listBoxData + "True";
}
if (server.ModbusLogData[i].functionCode == 6)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " Register Value: " + server.ModbusLogData[i].receiveRegisterValues[0].ToString();
}
if (server.ModbusLogData[i].functionCode == 15)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " Quantity: " + server.ModbusLogData[i].quantity.ToString() + " Byte Count: " + server.ModbusLogData[i].byteCount.ToString() + " Values Received: ";
for (int j = 0; j < server.ModbusLogData[i].quantity; j++)
{
int shift = j % 16;
if ((i == server.ModbusLogData[i].quantity - 1) & (server.ModbusLogData[i].quantity % 2 != 0))
{
if (shift < 8)
shift = shift + 8;
else
shift = shift - 8;
}
int mask = 0x1;
mask = mask << (shift);
if ((server.ModbusLogData[i].receiveCoilValues[j / 16] & (ushort)mask) == 0)
listBoxData = listBoxData + " False";
else
listBoxData = listBoxData + " True";
}
}
if (server.ModbusLogData[i].functionCode == 16)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " Quantity: " + server.ModbusLogData[i].quantity.ToString() + " Byte Count: " + server.ModbusLogData[i].byteCount.ToString() + " Values Received: ";
for (int j = 0; j < server.ModbusLogData[i].quantity; j++)
{
listBoxData = listBoxData + " " + server.ModbusLogData[i].receiveRegisterValues[j];
}
}
if (server.ModbusLogData[i].functionCode == 23)
{
listBoxData = listBoxData + " ; Starting Address Read: " + server.ModbusLogData[i].startingAddressRead.ToString() + " ; Quantity Read: " + server.ModbusLogData[i].quantityRead.ToString() + " ; Starting Address Write: " + server.ModbusLogData[i].startingAddressWrite.ToString() + " ; Quantity Write: " + server.ModbusLogData[i].quantityWrite.ToString() + " ; Byte Count: " + server.ModbusLogData[i].byteCount.ToString() + " ; Values Received: ";
for (int j = 0; j < server.ModbusLogData[i].quantityWrite; j++)
{
listBoxData = listBoxData + " " + server.ModbusLogData[i].receiveRegisterValues[j];
}
}
logMessageList.Add(listBoxData);
}
if (server.ModbusLogData[i].response)
{
if (server.ModbusLogData[i].exceptionCode > 0)
{
listBoxData = server.ModbusLogData[i].timeStamp.ToString("H:mm:ss.ff");
listBoxData = listBoxData + (" Response To Client - Error code: " + Convert.ToString(server.ModbusLogData[i].errorCode, 16));
listBoxData = listBoxData + " Exception Code: " + server.ModbusLogData[i].exceptionCode.ToString();
logMessageList.Add(listBoxData);
}
else
{
listBoxData = (server.ModbusLogData[i].timeStamp.ToString("H:mm:ss.ff") + " Response To Client - Functioncode: " + server.ModbusLogData[i].functionCode.ToString());
if (server.ModbusLogData[i].functionCode <= 4)
{
listBoxData = listBoxData + " ; Bytecount: " + server.ModbusLogData[i].byteCount.ToString() + " ; Send values: ";
}
if (server.ModbusLogData[i].functionCode == 5)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " ; Output Value: ";
if (server.ModbusLogData[i].receiveCoilValues[0] == 0)
listBoxData = listBoxData + "False";
if (server.ModbusLogData[i].receiveCoilValues[0] == 0xFF00)
listBoxData = listBoxData + "True";
}
if (server.ModbusLogData[i].functionCode == 6)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " ; Register Value: " + server.ModbusLogData[i].receiveRegisterValues[0].ToString();
}
if (server.ModbusLogData[i].functionCode == 15)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " ; Quantity: " + server.ModbusLogData[i].quantity.ToString();
}
if (server.ModbusLogData[i].functionCode == 16)
{
listBoxData = listBoxData + " ; Starting Address: " + server.ModbusLogData[i].startingAdress.ToString() + " ; Quantity: " + server.ModbusLogData[i].quantity.ToString();
}
if (server.ModbusLogData[i].functionCode == 23)
{
listBoxData = listBoxData + " ; ByteCount: " + server.ModbusLogData[i].byteCount.ToString() + " ; Send Register Values: ";
}
if (server.ModbusLogData[i].sendCoilValues != null)
{
for (int j = 0; j < server.ModbusLogData[i].sendCoilValues.Length; j++)
{
listBoxData = listBoxData + server.ModbusLogData[i].sendCoilValues[j].ToString() + " ";
}
}
if (server.ModbusLogData[i].sendRegisterValues != null)
{
for (int j = 0; j < server.ModbusLogData[i].sendRegisterValues.Length; j++)
{
listBoxData = listBoxData + server.ModbusLogData[i].sendRegisterValues[j].ToString() + " ";
}
}
logMessageList.Add(listBoxData);
}
}
}
}
catch (Exception) { }
Message = Guid.NewGuid().ToString();
});
}
private void SetEveryList()
{
ushort startAddress = StartAddress;
List1.Clear();
for (int i = startAddress; i < 10 + startAddress; i++)
{
MyDataGrid data = new MyDataGrid { Which = 1, Address = i, Value1 = server.coils[i + 1] };
if (server.coils[i + 1])
{
data.Color = "Green";
}
else
{
data.Color = "Red";
}
List1.Add(data);
}
List2.Clear();
for (int i = startAddress; i < 10 + startAddress; i++)
{
MyDataGrid data = new MyDataGrid { Which = 2, Address = i, Value1 = server.discreteInputs[i + 1] };
if (server.discreteInputs[i + 1])
{
data.Color = "Green";
}
else
{
data.Color = "Red";
}
List2.Add(data);
}
List3.Clear();
for (int i = startAddress; i < 10 + startAddress; i++)
{
MyDataGrid data = new MyDataGrid { Which = 3, Address = i, Value2 = server.holdingRegisters[i + 1] };
List3.Add(data);
}
List4.Clear();
for (int i = startAddress; i < 10 + startAddress; i++)
{
MyDataGrid data = new MyDataGrid { Which = 4, Address = i, Value2 = server.inputRegisters[i + 1] };
List4.Add(data);
}
}
private void HoldingRegistersChanged(int register, int numberOfRegisters)
{
Dispatcher.UIThread.Invoke(() => { SetEveryList(); });
}
private void CoilsChanged(int coil, int numberOfCoils)
{
Dispatcher.UIThread.Invoke(() => { SetEveryList(); });
}
}
public class MyDataGrid : ViewModelBase
{
public int Which { get; set; }
public int Address { get; set; }
public bool Value1 { get; set; }
public ushort Value2 { get; set; }
public string Color { get; set; }
}
}

View File

@@ -0,0 +1,190 @@
using System;
using System.Collections.Generic;
using System.Linq;
using .Base;
using MES.Utility.Network;
using MES.Utility.Core;
namespace .ViewModel._01PLC通信调试
{
public class Modbus调试1ViewModel : ViewModelBase
{
private ModbusHelper modbus;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string IpAddress { get; set; } = "192.168.1.100";
public int Port { get; set; } = 502;
public ushort ReadAddress { get; set; } = 100;
public ushort WriteAddress { get; set; } = 100;
public ushort ReadCount { get; set; } = 5;
public string ReadResult1 { get; set; } = "";
public string ReadResult2 { get; set; } = "";
public string ReadResult3 { get; set; } = "";
public string ReadResult4 { get; set; } = "";
public string WriteValue1 { get; set; } = "";
public string WriteValue2 { get; set; } = "";
public string WriteValue3 { get; set; } = "";
public string WriteValue4 { get; set; } = "";
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand ReadCmd { get; set; } //1线圈 2状态. 3保持.4输入
public DelegateCommand WriteCmd { get; set; } //1单个线圈 2单个保持. 3多个线圈 4多个保持
public Modbus调试1ViewModel()
{
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
private void ConnectCmdFunc(object obj)
{
try
{
modbus = new ModbusHelper(IpAddress, Port);
Enabled1 = false;
Enabled2 = true;
}
catch (Exception ex)
{
modbus = null;
GlobalValues.Error("连接失败");
}
}
private void DisconnectCmdFunc(object obj)
{
modbus.Dispose();
modbus = null;
ReadResult1 = ""; ReadResult2 = ""; ReadResult3 = ""; ReadResult4 = "";
WriteValue1 = ""; WriteValue2 = ""; WriteValue3 = ""; WriteValue4 = "";
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
int cmd = Convert.ToInt32(obj.ToString());
bool flag = false;
switch (cmd)
{
case 1:
flag = modbus.ReadCoils(ReadAddress, ReadCount, out bool[] values);
if (!flag)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(null);
return;
}
ReadResult1 = values.Select(it => it ? "1" : "0").ToList().GetStrArray(" ");
return;
case 2:
flag = modbus.ReadInputs(ReadAddress, ReadCount, out bool[] values2);
if (!flag)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(null);
return;
}
ReadResult2 = values2.Select(it => it ? "1" : "0").ToList().GetStrArray(" ");
return;
case 3:
flag = modbus.ReadHoldingRegisters(ReadAddress, ReadCount, out ushort[] values3);
if (!flag)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(null);
return;
}
ReadResult3 = values3.Select(it => Convert.ToString(it)).ToList().GetStrArray(" ");
return;
case 4:
flag = modbus.ReadInputRegisters(ReadAddress, ReadCount, out ushort[] values4);
if (!flag)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(null);
return;
}
ReadResult4 = values4.Select(it => Convert.ToString(it)).ToList().GetStrArray(" "); ;
return;
}
}
private void WriteCmdFunc(object obj)
{
try
{
int cmd = Convert.ToInt32(obj.ToString());
bool flag = false;
switch (cmd)
{
case 1:
flag = modbus.WriteCoil(WriteAddress, WriteValue1 == "1" ? true : false);
if (!flag)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(null);
}
else
{
GlobalValues.Success("写入成功");
}
return;
case 2:
flag = modbus.WriteRegister(WriteAddress, Convert.ToUInt16(WriteValue2));
if (!flag)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(null);
}
else
{
GlobalValues.Success("写入成功");
}
return;
case 3:
List<bool> data1 = WriteValue3.Split(' ').Where(it => !it.IsNullOrEmpty()).Select(it => it == "1" ? true : false).ToList();
flag = modbus.WriteCoils(WriteAddress, data1.ToArray());
if (!flag)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(null);
}
else
{
GlobalValues.Success("写入成功");
}
return;
case 4:
List<ushort> data2 = WriteValue4.Split(' ').Where(it => !it.IsNullOrEmpty()).Select(it => Convert.ToUInt16(it)).ToList();
flag = modbus.WriteRegisters(ReadAddress, data2.ToArray());
if (!flag)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(null);
}
else
{
GlobalValues.Success("写入成功");
}
return;
}
}
catch (Exception ex)
{
GlobalValues.Error($"写入失败:{ex.Message}");
}
}
}
}

View File

@@ -0,0 +1,253 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
using MES.Utility.Network;
using S7.Net;
namespace .ViewModel._01PLC通信调试
{
public class Modbus调试2ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string IpAddress { get; set; } = "192.168.1.10";
public int Port { get; set; } = 502;
public int Address { get; set; } = 4001;
public int StringLength { get; set; } = 100;
public string ReadedValue { get; set; } = "";
public string Message { get; set; } = "";
public string SendedBytesValue { get; set; } = "";
public string RecivedBytesValue { get; set; } = "";
public string Int16Value { get; set; } = "";
public string Int32Value { get; set; } = "";
public string RealValue { get; set; } = "";
public string StringValue { get; set; } = "";
public string DoubleValue { get; set; } = "";
public string LongValue { get; set; } = "";
//STRING DOUBLE INT64 INT32 INT16 REAL
private ModbusHelper modbus;
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public Modbus调试2ViewModel()
{
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
private void ConnectCmdFunc(object obj)
{
try
{
modbus = new ModbusHelper(IpAddress, Port);
modbus.OnSended += Modbus_OnSended;
modbus.OnRecived += Modbus_OnRecived;
Enabled1 = false;
Enabled2 = true;
}
catch
{
GlobalValues.Error("连接失败");
return;
}
}
private void DisconnectCmdFunc(object obj)
{
modbus.OnSended -= Modbus_OnSended;
modbus.OnRecived -= Modbus_OnRecived;
modbus.Dispose();
modbus = null;
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
string cmd = obj.ToString();
ReadedValue = "";
Message = "";
SendedBytesValue = "";
RecivedBytesValue = "";
if (cmd == "INT16")
{
ushort value;
bool flag = modbus.ReadHoldRegisterInt16(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "INT32")
{
int value;
bool flag = modbus.ReadHoldRegisterInt32(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "INT64")
{
long value;
bool flag = modbus.ReadHoldRegisterInt64(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "REAL")
{
float value;
bool flag = modbus.ReadHoldRegisterFloat(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "DOUBLE")
{
double value;
bool flag = modbus.ReadHoldRegisterDouble(Address, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
else if (cmd == "STRING")
{
string value;
bool flag = modbus.ReadHoldRegisterString(Address, StringLength, out value);
if (!flag)
{
Message = "读取失败";
DisconnectCmdFunc(null);
return;
}
Message = "读取成功";
ReadedValue = value.ToString();
}
// DOUBLE
}
private void WriteCmdFunc(object obj)
{
string cmd = obj.ToString();
ReadedValue = "";
Message = "";
SendedBytesValue = "";
RecivedBytesValue = "";
if (cmd == "INT16")
{
ushort value;
bool flag = ushort.TryParse(Int16Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt16(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT32")
{
int value;
bool flag = int.TryParse(Int32Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt32(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT64")
{
long value;
bool flag = long.TryParse(LongValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterInt64(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "REAL")
{
float value;
bool flag = float.TryParse(RealValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterFloat(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "DOUBLE")
{
double value;
bool flag = double.TryParse(DoubleValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = modbus.WriteHoldRegisterDouble(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "STRING")
{
bool flag = modbus.WriteHoldRegisterString(Address, StringLength, StringValue);
Message = flag ? "写入成功" : "写入失败";
}
}
private void Modbus_OnRecived(byte[] bytes, string hexString)
{
RecivedBytesValue = hexString;
}
private void Modbus_OnSended(byte[] bytes, string hexString)
{
SendedBytesValue = hexString;
}
}
}

View File

@@ -0,0 +1,389 @@
using System;
using System.Collections.ObjectModel;
using System.Linq;
using .Base;
using System.Threading;
using OpcUaHelper;
using Org.BouncyCastle.Crypto.Tls;
using System.Threading.Tasks;
using Opc.Ua.Client;
using Opc.Ua;
using Ursa.Controls;
namespace .ViewModel._01PLC通信调试
{
public class OPCUA调试ViewModel : ViewModelBase
{
private bool stop = false;
private OpcUaClient client;
private object _lock = new object();
private Thread thread;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string OpcServer { get; set; } = "opc.tcp://10.10.0.40";
public string Node { get; set; } = "ns=4;s=|var|Inovance-ARM-Linux.Application.StorageDatas.gStorageDatas[10].MaterialInfo.Width";
public string Result { get; set; } = "";
public string WriteValue { get; set; } = "";
public string SelecedValue { get; set; } = "";
public int SelectedIndex { get; set; } = -1;
public ObservableCollection<MyNode> NodeList { get; set; } = new ObservableCollection<MyNode>();
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand SubscribeCmd { get; set; }
public DelegateCommand ReadValueCmd { get; set; }
public DelegateCommand WriteValueCmd { get; set; }
public DelegateCommand CancelSubscribeCmd { get; set; }
public DelegateCommand OpenBrowerCmd { get; set; }
public OPCUA调试ViewModel()
{
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
SubscribeCmd = new DelegateCommand(SubscribeCmdFunc);
ReadValueCmd = new DelegateCommand(ReadValueCmdFunc);
WriteValueCmd = new DelegateCommand(WriteValueCmdFunc);
CancelSubscribeCmd = new DelegateCommand(CancelSubscribeCmdFunc);
OpenBrowerCmd = new DelegateCommand(OpenBrowerCmdFunc);
}
private void OpenBrowerCmdFunc(object obj)
{
//new OpcUaHelper.Forms.FormBrowseServer().Show();
}
/// <summary>
/// 建立连接
/// </summary>
/// <param name="obj"></param>
private void ConnectCmdFunc(object obj)
{
try
{
client = new OpcUaClient();
DateTime start = DateTime.Now;
bool connected = false;
Task task = client.ConnectServer(OpcServer);
while (true)
{
if (client.Connected)
{
connected = true;
break;
}
if ((DateTime.Now - start).TotalMilliseconds > 1000)
{
break;
}
}
if (!connected)
{
GlobalValues.Error($"连接失败");
client = null;
return;
}
Enabled1 = false;
Enabled2 = true;
stop = false;
thread = new Thread(() =>
{
while (true)
{
try
{
if (stop)
{
break;
}
Loop();
Thread.Sleep(1000);
}
catch (ThreadInterruptedException ex)
{
break;
}
catch (Exception e)
{
}
}
});
thread.Start();
}
catch (Exception ex)
{
GlobalValues.Error($"连接失败:{ex.Message}");
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="obj"></param>
private void DisconnectCmdFunc(object obj)
{
foreach (MyNode node in NodeList)
{
client.RemoveSubscription(node.NodeName);
}
NodeList.Clear();
client.Disconnect();
client = null;
Enabled1 = true;
Enabled2 = false;
stop = true;
thread.Interrupt();
thread = null;
}
private void SubscribeCmdFunc(object obj)
{
string node = Node;
if (NodeList.Any(x => x.NodeName == node))
return;
lock (_lock)
{
NodeList.Add(new MyNode { NodeName = node, Value = null });
}
client.AddSubscription(node, node, CallBack);
}
private void CallBack(string key, MonitoredItem item, MonitoredItemNotificationEventArgs itemNotify)
{
MonitoredItemNotification notification = itemNotify.NotificationValue as MonitoredItemNotification;
DataValue dataValue = notification.Value;
bool isGood = StatusCode.IsGood(dataValue.StatusCode);
if (isGood)
{
lock (_lock)
{
MyNode node = NodeList.Where(it => it.NodeName == key).FirstOrDefault();
node.Value = dataValue.Value;
}
}
else
{
lock (_lock)
{
MyNode node = NodeList.Where(it => it.NodeName == key).FirstOrDefault();
node.Value = null;
}
}
}
private void ReadValueCmdFunc(object obj)
{
try
{
DataValue dataValue = client.ReadNode(new NodeId(Node));
if (!StatusCode.IsGood(dataValue.StatusCode))
{
Result = "";
GlobalValues.Error("读取失败");
return;
}
Result = dataValue.Value.ToString();
GlobalValues.Success($"读取成功");
}
catch (Exception ex)
{
Result = "";
GlobalValues.Error($"读取失败:{ex.Message}");
}
}
private void WriteValueCmdFunc(object obj)
{
try
{
string cmd = obj.ToString();
if (cmd == "bool")
{
bool value;
bool flag = bool.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<bool>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "uint16")
{
ushort value;
bool flag = ushort.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<ushort>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "int16")
{
short value;
bool flag = short.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<short>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "int32")
{
int value;
bool flag = int.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<int>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "int64")
{
long value;
bool flag = long.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<long>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "float")
{
float value;
bool flag = float.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<float>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "double")
{
double value;
bool flag = double.TryParse(WriteValue, out value);
if (!flag)
{
GlobalValues.Error("数据转换失败,请输入正确的数据");
return;
}
flag = client.WriteNode<double>(Node, value);
if (!flag)
{
GlobalValues.Error("写入失败");
return;
}
GlobalValues.Success("写入成功");
}
}
catch (Exception ex)
{
MessageBox.ShowAsync(ex.Message);
}
}
/// <summary>
/// 取消订阅
/// </summary>
/// <param name="obj"></param>
private void CancelSubscribeCmdFunc(object obj)
{
try
{
if (SelectedIndex < 0)
{
return;
}
lock (_lock)
{
MyNode selectKey = NodeList[SelectedIndex];
client.RemoveSubscription(selectKey.NodeName);
NodeList.RemoveAt(SelectedIndex);
}
}
catch (Exception ex)
{
}
}
private void Loop()
{
if (SelectedIndex < 0)
{
return;
}
lock (_lock)
{
MyNode selectKey = NodeList[SelectedIndex];
object value = selectKey.Value;
if (value == null)
{
SelecedValue = "";
}
else
{
SelecedValue = value.ToString();
}
}
}
}
public class MyNode : ViewModelBase
{
public string NodeName { get; set; }
public object Value { get; set; }
}
}

View File

@@ -0,0 +1,363 @@
using MES.Utility.Core;
using SerialDebug;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using .Base;
using .Utility.Network;
using static EasyModbus.TCPHandler;
namespace .ViewModel._01PLC通信调试
{
public class Socket调试ViewModel : ViewModelBase
{
private System.IO.Ports.SerialPort serialPort;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string ButtonText { get; set; } = "打开";
public string IpAddress { get; set; } = "127.0.0.1";
public int Port { get; set; } = 502;
public int Timeout { get; set; } = 1000;
public bool ReciveASCChecked { get; set; } = true;
public bool ReciveHexChecked { get; set; } = false;
public bool SendASCChecked { get; set; } = true;
public bool SendHexChecked { get; set; } = false;
public bool ConvertChecked { get; set; } = true;
public bool CycleChecked { get; set; } = false;
public int CycleTime { get; set; } = 1000;
public string SendContent { get; set; } = "";
private object _lock = new object();
private List<string> msgList = new List<string>();
public string Message
{
get
{
lock (_lock)
{
return msgList.GetStrArray("\r\n");
}
}
set
{
NotifyPropertyChanged();
}
}
public DelegateCommand OpenSerialCmd { get; set; }
public DelegateCommand ClearReciveCmd { get; set; }
public DelegateCommand ClearSendCmd { get; set; }
public DelegateCommand SendCmd { get; set; }
private TcpClient client;
private Stream stream;
private Thread sendThread;
public Thread readThread;
public Socket调试ViewModel()
{
serialPort = new SerialPort();
//打开关闭串口
OpenSerialCmd = new DelegateCommand(OpenSerialCmdFunc);
ClearReciveCmd = new DelegateCommand(ClearReciveCmdFunc);
ClearSendCmd = new DelegateCommand(ClearSendCmdFunc);
SendCmd = new DelegateCommand(SendCmdFunc);
}
private void OpenSerialCmdFunc(object obj)
{
try
{
if (ButtonText == "打开")
{
client = new TcpClient();
IAsyncResult asyncResult = client.BeginConnect(IpAddress, Port, null, null);
if (!asyncResult.AsyncWaitHandle.WaitOne(Timeout))
{
GlobalValues.Error("连接超时");
return;
}
client.EndConnect(asyncResult);
stream = client.GetStream();
ButtonText = "关闭";
Enabled1 = false;
Enabled2 = true;
readThread = new Thread(ReadThread);
readThread.Start();
}
else
{
sendThread?.Interrupt();
sendThread = null;
readThread.Interrupt();
readThread = null;
stream.Close();
client.Close();
client.Dispose();
client = null;
ButtonText = "打开";
Enabled1 = true;
Enabled2 = false;
}
}
catch (Exception ex)
{
client.Close();
client = null;
GlobalValues.Error(ex.Message);
}
}
private void ClearReciveCmdFunc(object obj)
{
lock (_lock)
{
msgList.Clear();
}
Message = Guid.NewGuid().ToString();
}
private void ClearSendCmdFunc(object obj)
{
SendContent = string.Empty;
}
private void SendCmdFunc(object obj)
{
try
{
if (sendThread != null)
{
GlobalValues.Error("正在执行循环周期发送,不能发送数据");
return;
}
if (SendContent.IsNullOrEmpty())
{
GlobalValues.Error("没有任何可发送的数据");
return;
}
//要发送的数据
SendParamFormat format = SendParamFormat.ASCII;
if (SendHexChecked)
{
format = SendParamFormat.Hex;
}
int sendInterval = Convert.ToInt32(CycleTime);
CSendParam param = new CSendParam(format, SendParamMode.SendAfterLastSend, sendInterval, SendContent, ConvertChecked);
if (CycleChecked)
{
sendThread = new Thread(SendThread);
sendThread.Start(param);
}
else
{
SendData(param);
}
}
catch (Exception ex)
{
GlobalValues.Error(ex.Message);
}
}
private void sp_SendCompletedEvent(object sender, SendCompletedEventArgs e)
{
if (e.SendParam == null)
{
GlobalValues.Error("发送失败");
OpenSerialCmdFunc(null);
return;
}
lock (_lock)
{
msgList.Add($"{e.TimeString}[-->]");
if (SendASCChecked)
{
msgList.Add(e.SendParam.ASCIIString);
}
else
{
msgList.Add(e.SendParam.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
/// <summary>
/// 接收事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void sp_ReceivedEvent(object sender, SerialDebugReceiveData e)
{
if (e != null)
{
lock (_lock)
{
msgList.Add($"{e.TimeString}[<--]");
if (ReciveASCChecked)
{
msgList.Add(e.ASCIIString);
}
else
{
msgList.Add(e.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
}
void sp_SendOverEvent(object sender, EventArgs e)
{
}
private void ReadThread(object obj)
{
while (true)
{
try
{
var available = client.Available;
if (available > 0)
{
byte[] bytes = new byte[available];
stream.Read(bytes, 0, bytes.Length);
SerialDebugReceiveData data = new SerialDebugReceiveData(bytes);
lock (_lock)
{
msgList.Add($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}[<--]");
if (ReciveASCChecked)
{
msgList.Add(data.ASCIIString);
}
else
{
msgList.Add(data.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
Thread.Sleep(1);
}
catch (ThreadInterruptedException ex)
{
break;
}
catch (Exception ex)
{
}
}
}
private void SendData(CSendParam param)
{
try
{
stream.Write(param.DataBytes, 0, param.DataBytes.Length);
lock (_lock)
{
msgList.Add($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")}[<--]");
if (ReciveASCChecked)
{
msgList.Add(param.ASCIIString);
}
else
{
msgList.Add(param.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
catch (Exception ex)
{
}
}
private void SendThread(object obj)
{
CSendParam parm = (CSendParam)obj;
while (true)
{
try
{
SendData(parm);
Thread.Sleep(CycleTime);
}
catch (ThreadInterruptedException ex)
{
break;
}
catch (Exception ex)
{
}
}
}
}
}

View File

@@ -0,0 +1,242 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
using McProtocol;
using McProtocol.Mitsubishi;
namespace .ViewModel._01PLC通信调试
{
public class MC协议ViewModel : ViewModelBase
{
public List<string> MCList { get; set; } = new List<string>() { "MC1E", "MC3E", "MC4E" };
public int MCIndex { get; set; } = 1;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string IpAddress { get; set; } = "127.0.0.1";
public int Port { get; set; } = 5001;
public string Address { get; set; } = "D100";
public string Address2 { get; set; } = "D10";
public int StringLength { get; set; } = 50;
public string BoolValue { get; set; } = "true";
public string Int16Value { get; set; } = "";
public string Int32Value { get; set; } = "";
public string RealValue { get; set; } = "";
public string StringValue { get; set; } = "";
public int BytesCount { get; set; } = 50;
public string ReadedValue { get; set; } = "";
public string Message { get; set; } = "";
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
private McHelper plc;
public MC协议ViewModel()
{
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
/// <summary>
/// 连接
/// </summary>
/// <param name="obj"></param>
private void ConnectCmdFunc(object obj)
{
// // MC1E = 4, MC3E = 11, MC4E = 15
if (MCIndex == 0)
{
this.plc = new McHelper(IpAddress, Port, McFrame.MC1E);
}
else if (MCIndex == 1)
{
this.plc = new McHelper(IpAddress, Port, McFrame.MC3E);
}
else if (MCIndex == 2)
{
this.plc = new McHelper(IpAddress, Port, McFrame.MC4E);
}
else
{
this.plc = new McHelper(IpAddress, Port);
}
bool flag = plc.Connect();
if (flag)
{
Enabled2 = true;
Enabled1 = false;
}
else
{
GlobalValues.Error("PLC连接失败");
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="obj"></param>
private void DisconnectCmdFunc(object obj)
{
try { plc.Dispose(); } catch { }
plc = null;
Enabled1 = true;
Enabled2 = false;
}
/// <summary>
/// 读取操作
/// </summary>
/// <param name="obj"></param>
private void ReadCmdFunc(object obj)
{
ReadedValue = string.Empty;
Message = string.Empty;
string cmd = obj.ToString();
if (cmd == "BOOL")
{
//bool value;
//bool flag = plc.ReadBool(Address, out value);
//if (!flag)
//{
// ReadedValue = string.Empty;
// Message = "读取失败";
// return;
//}
//ReadedValue = value.ToString();
Message = "该功能暂未实现";
}
else if (cmd == "INT16")
{
short value;
bool flag = plc.ReadInt16(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "INT32")
{
int value;
bool flag = plc.ReadInt32(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "REAL")
{
float value;
bool flag = plc.ReadFloat(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "STRING")
{
string value;
bool flag = plc.ReadString(Address, StringLength, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "Bytes")
{
//ReadedValue = string.Empty;
//Message = string.Empty;
//byte[] value;
//bool flag = plc.ReadBytes(Address2, BytesCount, out value);
//if (!flag)
//{
// ReadedValue = string.Empty;
// Message = "读取失败";
// return;
//}
//ReadedValue = ToHexStrFromByte(value);
Message = "该功能暂未实现";
}
}
private void WriteCmdFunc(object obj)
{
ReadedValue = string.Empty;
Message = string.Empty;
string cmd = obj.ToString();
if (cmd == "BOOL")
{
Message = "该功能有问题,已弃用";
return;
}
else if (cmd == "INT16")
{
short value;
bool flag = short.TryParse(Int16Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = plc.WriteInt16(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT32")
{
int value;
bool flag = int.TryParse(Int32Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = plc.WriteInt32(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "REAL")
{
float value;
bool flag = float.TryParse(RealValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = plc.WriteFloat(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "STRING")
{
bool flag = plc.WriteString(Address, StringLength, StringValue);
Message = flag ? "写入成功" : "写入失败";
}
}
}
}

View File

@@ -0,0 +1,292 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SerialDebug;
using .Base;
using MES.Utility.Core;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
namespace .ViewModel._01PLC通信调试
{
public class ViewModel : ViewModelBase
{
private System.IO.Ports.SerialPort serialPort;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string ButtonText { get; set; } = "打开";
//串口号下拉列表数据
public List<string> SerialList { get; set; }
public int SerialIndex { get; set; } = 0;
/// <summary>
/// 波特率
/// </summary>
public List<int> BaudRateList { get; set; }
public int BaudRateIndex { get; set; } = 0;
//校验
public List<string> ParityList { get; set; }
public int ParityIndex { get; set; } = 0;
//数据为
public List<int> DataBitList { get; set; }
public int DataBitIndex { get; set; } = 0;
//数据为
public List<string> FlowControlList { get; set; } = new List<string>() { "None", "XOnXOff", "RequestToSend", "RequestToSendXOnXOff" };
public int FlowControlIndex { get; set; } = 0;
//停止位
public List<string> StopBitList { get; set; }
public int StopBitIndex { get; set; } = 0;
public int Timeout { get; set; } = 100;
public bool RTSChecked { get; set; } = true;
public bool DTRChecked { get; set; } = false;
public bool ReciveASCChecked { get; set; } = true;
public bool ReciveHexChecked { get; set; } = false;
public bool SendASCChecked { get; set; } = true;
public bool SendHexChecked { get; set; } = false;
public bool ConvertChecked { get; set; } = true;
public bool CycleChecked { get; set; } = false;
public int CycleTime { get; set; } = 1000;
public string SendContent { get; set; } = "";
private object _lock = new object();
private List<string> msgList = new List<string>();
public string Message
{
get
{
lock (_lock)
{
return msgList.GetStrArray("\r\n");
}
}
set
{
NotifyPropertyChanged();
}
}
public DelegateCommand OpenSerialCmd { get; set; }
public DelegateCommand ClearReciveCmd { get; set; }
public DelegateCommand ClearSendCmd { get; set; }
public DelegateCommand SendCmd { get; set; }
private CSerialDebug sp;
public ViewModel()
{
serialPort = new SerialPort();
sp = new CSerialDebug(serialPort);
//串口号
string[] portNames = SerialPort.GetPortNames();
if (portNames != null && portNames.Length > 0)
{
SerialList = portNames.ToList();
}
//波特率
BaudRateList = new List<int>() { 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, 128000 };
BaudRateIndex = 6;
//校验
ParityList = new List<string> { "None", "Odd", "Even", "Mark", "Space" };
ParityIndex = 0;
//数据位
DataBitList = new List<int> { 5, 6, 7, 8 };
DataBitIndex = 3;
//停止位
StopBitList = new List<string> { "None", "One", "Two", "OnePointFive" };
StopBitIndex = 1;
//打开关闭串口
OpenSerialCmd = new DelegateCommand(OpenSerialCmdFunc);
ClearReciveCmd = new DelegateCommand(ClearReciveCmdFunc);
ClearSendCmd = new DelegateCommand(ClearSendCmdFunc);
SendCmd = new DelegateCommand(SendCmdFunc);
}
private void OpenSerialCmdFunc(object obj)
{
try
{
if (ButtonText == "打开")
{
serialPort.PortName = SerialList[SerialIndex];
serialPort.BaudRate = BaudRateList[BaudRateIndex];
serialPort.Parity = (Parity)ParityIndex;
serialPort.DataBits = DataBitList[DataBitIndex];
serialPort.StopBits = (StopBits)StopBitIndex;
serialPort.Handshake = (Handshake)FlowControlIndex;
serialPort.DtrEnable = DTRChecked;
serialPort.RtsEnable = RTSChecked;
serialPort.ReadBufferSize = 2 * 1024 * 1024;// 2M
sp.ReceiveTimeOut = Timeout;
sp.Start();
sp.ReceivedEvent += new CSerialDebug.ReceivedEventHandler(sp_ReceivedEvent);
sp.SendCompletedEvent += new CSerialDebug.SendCompletedEventHandler(sp_SendCompletedEvent);
sp.SendOverEvent += new EventHandler(sp_SendOverEvent);
ButtonText = "关闭";
Enabled1 = false;
Enabled2 = true;
}
else
{
sp.StopSend();
sp.ReceivedEvent -= new CSerialDebug.ReceivedEventHandler(sp_ReceivedEvent);
sp.SendCompletedEvent -= new CSerialDebug.SendCompletedEventHandler(sp_SendCompletedEvent);
sp.SendOverEvent -= new EventHandler(sp_SendOverEvent);
sp.Stop();
ButtonText = "打开";
Enabled1 = true;
Enabled2 = false;
}
}
catch (Exception ex)
{
GlobalValues.Error(ex.Message);
}
}
private void ClearReciveCmdFunc(object obj)
{
lock (_lock)
{
msgList.Clear();
}
Message = Guid.NewGuid().ToString();
}
private void ClearSendCmdFunc(object obj)
{
SendContent = string.Empty;
}
private void SendCmdFunc(object obj)
{
try
{
if (SendContent.IsNullOrEmpty())
{
GlobalValues.Error("没有任何可发送的数据");
return;
}
//要发送的数据
List<CSendParam> list = new List<CSendParam>();
SendParamFormat format = SendParamFormat.ASCII;
if (SendHexChecked)
{
format = SendParamFormat.Hex;
}
int sendInterval = Convert.ToInt32(CycleTime);
CSendParam param = new CSendParam(format, SendParamMode.SendAfterLastSend, sendInterval, SendContent, ConvertChecked);
list.Add(param);
if (CycleChecked)
{
sp.Send(list, 0);
}
else
{
sp.Send(list, 1);
}
}
catch (Exception ex)
{
GlobalValues.Error(ex.Message);
}
}
private void sp_SendCompletedEvent(object sender, SendCompletedEventArgs e)
{
if (e.SendParam == null)
{
GlobalValues.Error("发送失败");
OpenSerialCmdFunc(null);
return;
}
lock (_lock)
{
msgList.Add($"{e.TimeString}[-->]");
if (SendASCChecked)
{
msgList.Add(e.SendParam.ASCIIString);
}
else
{
msgList.Add(e.SendParam.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
/// <summary>
/// 接收事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void sp_ReceivedEvent(object sender, SerialDebugReceiveData e)
{
if (e != null)
{
lock (_lock)
{
msgList.Add($"{e.TimeString}[<--]");
if (ReciveASCChecked)
{
msgList.Add(e.ASCIIString);
}
else
{
msgList.Add(e.HexString);
}
if (msgList.Count > 300)
{
int cha = msgList.Count - 300;
//lines.Reverse();
//差多少,删多少
for (int i = 0; i < cha; i++)
{
msgList.RemoveAt(0);
}
}
}
Message = Guid.NewGuid().ToString();
}
}
void sp_SendOverEvent(object sender, EventArgs e)
{
}
}
}

View File

@@ -0,0 +1,635 @@
using System;
using .Base;
using System.Collections.Generic;
using MES.Utility.Core;
using System.Text;
using System.Linq;
using TwinCAT.Ads.TypeSystem;
using TwinCAT.Ads;
namespace .ViewModel._01PLC通信调试
{
public class ADS调试ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string NetId { get; set; } = "192.168.1.10.1.1";
public int Port { get; set; } = 851;
public string VarName { get; set; } = "Global_LaserCutting.gHmiPlc.Output.Mes.DeviceStatus.bEMG";
public int StringLength { get; set; } = 80;
public string DataType { get; set; } = "";
public string ReadedValue { get; set; } = "";
public string Message1 { get; set; } = "";
public string Message2 { get; set; } = "";
public string BoolValue { get; set; } = "";
private AdsServer ads;
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public ADS调试ViewModel()
{
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
private void ConnectCmdFunc(object obj)
{
try
{
ads = new AdsServer(NetId, Port);
ads.Connect();
Enabled1 = false;
Enabled2 = true;
}
catch
{
GlobalValues.Error("连接失败");
return;
}
}
private void DisconnectCmdFunc(object obj)
{
ads.Disconnect();
ads = null;
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
string cmd = obj.ToString();
ReadedValue = "";
Message1 = "";
DataType = "";
try
{
object value = ads.Read(VarName, out string type);
Message1 = "读取成功";
DataType = type;
if (value.GetType().IsArray)
{
Array array = value as Array;
List<string> list = new List<string>();
for (int i = 0; i < array.Length; i++)
{
list.Add(array.GetValue(i).ToString());
}
ReadedValue = list.GetStrArray(" ");
}
else
{
ReadedValue = value.ToString();
}
}
catch (Exception ex)
{
Message1 = $"读取失败:{ex.Message}";
return;
}
}
private void WriteCmdFunc(object obj)
{
string cmd = obj.ToString();
try
{
if (string.IsNullOrEmpty(BoolValue))
{
Message2 = "请输入数据";
return;
}
ads.Write(VarName, BoolValue);
Message2 = $"写入成功";
}
catch (Exception ex)
{
Message2 = $"写入失败:{ex.Message}";
}
}
}
public class AdsServer
{
Dictionary<string, IAdsSymbol> symbolDict = new Dictionary<string, IAdsSymbol>();
public delegate void TcAdsStateChangedEventHandler(AdsState state);
public delegate void TcAdsRouteChangedEventHandler(AmsRouterState state);
public AmsRouterState AsmRouteState { get; set; } = AmsRouterState.Stop;
public AdsState AdsState { get; set; } = AdsState.Stop;
public AdsClient ads;
public bool SystemIsRunning => ads.IsConnected;
private TcAdsRouteChangedEventHandler tcAdsSystemStateChangedHandler;
public event TcAdsRouteChangedEventHandler TcSystemStateChanged
{
add
{
this.tcAdsSystemStateChangedHandler = (TcAdsRouteChangedEventHandler)Delegate.Combine(this.tcAdsSystemStateChangedHandler, value);
value(AsmRouteState);
}
remove
{
this.tcAdsSystemStateChangedHandler = (TcAdsRouteChangedEventHandler)Delegate.Remove(this.tcAdsSystemStateChangedHandler, value);
}
}
private TcAdsStateChangedEventHandler tcAdsClientStateChangedHandler;
public event TcAdsStateChangedEventHandler TcPlcStateChanged
{
add
{
this.tcAdsClientStateChangedHandler = (TcAdsStateChangedEventHandler)Delegate.Combine(this.tcAdsClientStateChangedHandler, value);
value(AdsState);
}
remove
{
this.tcAdsClientStateChangedHandler = (TcAdsStateChangedEventHandler)Delegate.Remove(this.tcAdsClientStateChangedHandler, value);
}
}
private int _clientPortNr = 801;
private string _netId = "";
public AdsServer(string netId, int portNr)
{
this._netId = netId;
this._clientPortNr = portNr;
ads = new AdsClient();
ads.RouterStateChanged += Client_AmsRouterNotification;
ads.AdsStateChanged += Client_AdsStateChanged;
}
private void Client_AmsRouterNotification(object sender, AmsRouterNotificationEventArgs e)
{
AsmRouteState = e.State;
tcAdsSystemStateChangedHandler?.Invoke(AsmRouteState);
}
public void Connect()
{
ads.Connect(this._netId, this._clientPortNr);
}
public void Disconnect()
{
ads.Disconnect();
ads.Dispose();
}
private void Client_AdsStateChanged(object sender, AdsStateChangedEventArgs e)
{
AdsState = e.State.AdsState;
tcAdsClientStateChangedHandler?.Invoke(AdsState);
}
public object Read(string symbolPath, out string oDataType)
{
if (!SystemIsRunning)
{
throw new Exception("PLC链接失败");
}
//bool isArray = symbolPath.Contains("[") && symbolPath.Contains("]");
//int index1 = symbolPath.IndexOf("["); int index2 = symbolPath.IndexOf("]");
//uint index = uint.Parse(symbolPath.Substring(index1 + 1, index2 - index1 - 1));
//symbolPath = symbolPath.Substring(0, index1);
IAdsSymbol symbol = null;
if (symbolDict.ContainsKey(symbolPath))
{
symbol = symbolDict[symbolPath];
}
else
{
symbol = ads.ReadSymbol(symbolPath);
if (symbol == null)
throw new Exception("找不到该变量");
symbolDict.Add(symbolPath, symbol);
}
oDataType = symbol.TypeName;
if (symbol.TypeName.Substring(0, 3) != "ARR")
{
AdsDataTypeId datatype = symbol.DataTypeId;
//BOOL
if (datatype == AdsDataTypeId.ADST_BIT)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(bool));
//byte
if (datatype == AdsDataTypeId.ADST_UINT8)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(byte));
//sbyte
if (datatype == AdsDataTypeId.ADST_INT8)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(sbyte));
//ushort
if (datatype == AdsDataTypeId.ADST_UINT16)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(ushort));
//short
if (datatype == AdsDataTypeId.ADST_INT16)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(short));
if (datatype == AdsDataTypeId.ADST_UINT32)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(uint));
if (datatype == AdsDataTypeId.ADST_INT32)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(int));
if (datatype == AdsDataTypeId.ADST_REAL32)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(float));
if (datatype == AdsDataTypeId.ADST_REAL64)
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(double));
if (datatype == AdsDataTypeId.ADST_STRING)
return ads.ReadAnyString((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, symbol.Size, Encoding.Default);
if (datatype == AdsDataTypeId.ADST_WSTRING)
{
Memory<byte> stream = new Memory<byte>(new byte[symbol.Size]);
int readLength = ads.Read((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, stream);
byte[] bytes = stream.ToArray().ToList().Take(readLength).ToArray();
int charCount = readLength / 2;
char[] charArray = new char[charCount];
for (int i = 0; i < charCount; i++)
{
char value = (char)(bytes[i * 2 + 1] << 8 | bytes[i * 2]);
charArray[i] = value;
if (value == 0)
break;
}
return new String(charArray).Trim('\0');
}
if (datatype == AdsDataTypeId.ADST_BIGTYPE)
{
if (symbol.TypeName.StartsWith("TIME") || symbol.TypeName.StartsWith("DATE") || symbol.TypeName.StartsWith("TOD"))
{
return ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, typeof(DateTime));
}
}
}
else
{
AdsDataTypeId datatype = symbol.DataTypeId;
if (datatype == AdsDataTypeId.ADST_BIT)
{
//if (isArray)
//{
// return (bool)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + index, typeof(bool));
//}
bool[] values = new bool[symbol.Size];
for (uint i = 0; i < symbol.Size; i++)
{
values[i] = (bool)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + i, typeof(bool));
}
return values;
}
//byte
if (datatype == AdsDataTypeId.ADST_UINT8)
{
//if (isArray)
//{
// return (byte)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + index, typeof(byte)); ;
//}
byte[] values = new byte[symbol.Size];
for (uint i = 0; i < symbol.Size; i++)
{
values[i] = (byte)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + i, typeof(byte));
}
return values;
}
//sbyte
if (datatype == AdsDataTypeId.ADST_INT8)
{
//if (isArray)
//{
// return (sbyte)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + index, typeof(sbyte));
//}
sbyte[] values = new sbyte[symbol.Size];
for (uint i = 0; i < symbol.Size; i++)
{
values[i] = (sbyte)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + i, typeof(sbyte));
}
return values;
}
//ushort
if (datatype == AdsDataTypeId.ADST_UINT16)
{
//if (isArray)
//{
// return (ushort)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 2U), typeof(ushort));
//}
int count = symbol.Size / 2;
ushort[] values = new ushort[count];
for (uint i = 0; i < count; i++)
{
values[i] = (ushort)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 2U), typeof(ushort));
}
return values;
}
//short
if (datatype == AdsDataTypeId.ADST_INT16)
{
//if (isArray)
//{
// return (short)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 2U), typeof(short));
//}
int count = symbol.Size / 2;
short[] values = new short[count];
for (uint i = 0; i < count; i++)
{
values[i] = (short)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 2U), typeof(short));
}
return values;
}
if (datatype == AdsDataTypeId.ADST_UINT32)
{
//if (isArray)
//{
// return (uint)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 4U), typeof(uint));
//}
int count = symbol.Size / 4;
uint[] values = new uint[count];
for (uint i = 0; i < count; i++)
{
values[i] = (uint)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 4U), typeof(uint));
}
return values;
}
if (datatype == AdsDataTypeId.ADST_INT32)
{
//if (isArray)
//{
// return (int)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 4U), typeof(int));
//}
int count = symbol.Size / 4;
int[] values = new int[count];
for (uint i = 0; i < count; i++)
{
values[i] = (int)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 4U), typeof(int));
}
return values;
}
if (datatype == AdsDataTypeId.ADST_REAL32)
{
//if (isArray)
//{
// return (float)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 4U), typeof(float));
//}
int count = symbol.Size / 4;
float[] values = new float[count];
for (uint i = 0; i < count; i++)
{
values[i] = (float)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 4U), typeof(float));
}
return values;
}
if (datatype == AdsDataTypeId.ADST_REAL64)
{
//if (isArray)
//{
// return (double)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 8U), typeof(double));
//}
int count = symbol.Size / 8;
double[] values = new double[count];
for (uint i = 0; i < count; i++)
{
values[i] = (double)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 8U), typeof(double));
}
return values;
}
//TC3 字符串数组为 ADST_STRING
if (datatype == AdsDataTypeId.ADST_STRING)
{
int every = 81;
if (symbol.TypeName.Contains("OF STRING"))
{
int index = symbol.TypeName.IndexOf("OF STRING(");
if (index != 1)
{
int index2 = symbol.TypeName.LastIndexOf(")");
every = Convert.ToInt32(symbol.TypeName.Substring(index + 10, index2 - index - 10)) + 1;
}
int count = symbol.Size / every;
string[] values = new string[count];
for (uint i = 0; i < count; i++)
{
values[i] = ads.ReadAnyString((uint)symbol.IndexGroup, (uint)(symbol.IndexOffset + (i * every)), every, Encoding.Default);
}
return values;
}
}
if (datatype == AdsDataTypeId.ADST_WSTRING)
{
int every = 512;
if (symbol.TypeName.Contains("OF WSTRING"))
{
int index = symbol.TypeName.IndexOf("OF WSTRING(");
if (index != 1)
{
int index2 = symbol.TypeName.LastIndexOf(")");
every = (Convert.ToInt32(symbol.TypeName.Substring(index + 11, index2 - index - 11)) + 1) * 2;
}
int count = symbol.Size / every;
string[] values = new string[count];
for (uint i = 0; i < count; i++)
{
Memory<byte> stream = new Memory<byte>(new byte[every]);
int readLength = ads.Read((uint)symbol.IndexGroup, (uint)(symbol.IndexOffset + (i * every)), stream);
byte[] bytes = stream.ToArray().ToList().Take(readLength).ToArray();
int charCount = readLength / 2;
char[] charArray = new char[charCount];
for (int j = 0; j < charCount; j++)
{
char value = (char)(bytes[j * 2 + 1] << 8 | bytes[j * 2]);
charArray[j] = value;
if (value == 0)
break;
}
values[i] = new String(charArray).Trim('\0');
}
return values;
}
}
if (datatype == AdsDataTypeId.ADST_BIGTYPE)
{
//TC2 字符串为ADST_BIGTYPE
if (symbol.TypeName.Contains("OF STRING"))
{
//if (isArray)
//{
// return ads.ReadAnyString((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 81U), 81, Encoding.Default);
//}
int count = symbol.Size / 81;
string[] values = new string[count];
for (uint i = 0; i < count; i++)
{
values[i] = ads.ReadAnyString((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 81U), 81, Encoding.Default);
}
return values;
}
if (symbol.TypeName.Contains("OF TIME") || symbol.TypeName.Contains("OF DATE"))
{
//if (isArray)
//{
// return (DateTime)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 4), typeof(DateTime));
//}
int count = symbol.Size / 4;
DateTime[] values = new DateTime[count];
for (uint i = 0; i < count; i++)
{
values[i] = (DateTime)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 4), typeof(DateTime));
}
return values;
}
if (symbol.TypeName.Contains("OF TOD"))
{
//if (isArray)
//{
// return (DateTime)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (index * 4), typeof(DateTime));
//}
int count = symbol.Size / 4;
DateTime[] values = new DateTime[count];
for (uint i = 0; i < count; i++)
{
values[i] = (DateTime)ads.ReadAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset + (i * 4), typeof(DateTime));
}
return values;
}
}
}
throw new Exception("不支持的数据类型");
}
public void Write(string symbolPath, string value)
{
if (!SystemIsRunning)
{
throw new Exception("PLC链接失败");
}
IAdsSymbol symbol = null;
if (symbolDict.ContainsKey(symbolPath))
{
symbol = symbolDict[symbolPath];
}
else
{
symbol = ads.ReadSymbol(symbolPath);
if (symbol == null)
throw new Exception("找不到该变量");
symbolDict.Add(symbolPath, symbol);
}
if (symbol.TypeName.Substring(0, 3) != "ARR")
{
AdsDataTypeId datatype = symbol.DataTypeId;
//BOOL
if (datatype == AdsDataTypeId.ADST_BIT)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, bool.Parse(value));
return;
}
//byte
if (datatype == AdsDataTypeId.ADST_UINT8)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, byte.Parse(value));
return;
}
//sbyte
if (datatype == AdsDataTypeId.ADST_INT8)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, sbyte.Parse(value));
return;
}
//ushort
if (datatype == AdsDataTypeId.ADST_UINT16)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, ushort.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_INT16)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, short.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_UINT32)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, uint.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_INT32)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, int.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_REAL32)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, float.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_REAL64)
{
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, double.Parse(value));
return;
}
if (datatype == AdsDataTypeId.ADST_STRING)
{
ads.WriteAnyString(symbolPath, value, symbol.Size,Encoding.Default);
//ads.WriteAnyString((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, value, symbol.Size, Encoding.Default);
return;
}
if (datatype == AdsDataTypeId.ADST_WSTRING)
{
char[] charArray = value.ToCharArray();
byte[] bytes = new byte[charArray.Length * 2];
for (int i = 0; i < charArray.Length; i++)
{
bytes[i * 2] = (byte)(charArray[i] & 0xFF);
bytes[i * 2 + 1] = (byte)(charArray[i] >> 8 & 0xFF);
}
if (bytes.Length > symbol.Size)
{
ads.Write((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, new ReadOnlyMemory<byte>(bytes));
}
else
{
byte[] newBytes = new byte[symbol.Size];
for (int i = 0; i < bytes.Length; i++)
{
newBytes[i] = bytes[i];
}
ads.Write((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, new ReadOnlyMemory<byte>(newBytes));
}
return;
}
if (datatype == AdsDataTypeId.ADST_BIGTYPE)
{
if (symbol.TypeName.StartsWith("TIME") || symbol.TypeName.StartsWith("DATE") || symbol.TypeName.StartsWith("TOD"))
{
bool flag = DateTime.TryParse(value, out DateTime result);
if (!flag)
throw new Exception("格式转换失败");
ads.WriteAny((uint)symbol.IndexGroup, (uint)symbol.IndexOffset, result);
return;
}
}
throw new Exception("不支持的数据类型");
}
else
{
throw new Exception("不支持数组批量写入");
}
}
}
}

View File

@@ -0,0 +1,218 @@
using System;
using System.Collections.Generic;
using System.Linq;
using .Base;
using OmronLib;
using MES.Utility.Core;
using Ursa.Controls;
namespace .ViewModel._01PLC通信调试
{
public class Fins调试ViewModel : ViewModelBase
{
private Omron omron;
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string IpAddress { get; set; } = "192.168.1.3";
public int Port { get; set; } = 9600;
public List<string> AreaList { get; set; }
public List<Omron.AreaType> AreaTypeList { get; set; }
public int WriteAreaIndex { get; set; } = 0;
public int ReadAreaIndex { get; set; } = 0;
public int ReadAddress { get; set; } = 1042;
public int WriteAddress { get; set; } = 1042;
public int ReadCount { get; set; } = 1;
public string ReadResult { get; set; } = "";
public int StrLength { get; set; } = 50;
public string WriteValue { get; set; } = "";
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }//1读取 2字符串 3Float 4Short
public DelegateCommand WriteCmd { get; set; }//1写入 2.Float 3Short 4字符串
public Fins调试ViewModel()
{
AreaList = new List<string>
{
"CIO_Bit","WR_Bit","HR_Bit","AR_Bit",
"DM_Bit","CIO_Word","WR_Word","HR_Word","AR_Word","DM_Word"
};
AreaTypeList = new List<Omron.AreaType>
{
Omron.AreaType.CIO_Bit,Omron.AreaType.WR_Bit,Omron.AreaType.HR_Bit,Omron.AreaType.AR_Bit,
Omron.AreaType.DM_Bit,Omron.AreaType.CIO_Word,Omron.AreaType.WR_Word,Omron.AreaType.HR_Word,Omron.AreaType.AR_Word,Omron.AreaType.DM_Word
};
ReadAreaIndex = 9;
WriteAreaIndex = 9;
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
private void ConnectCmdFunc(object obj)
{
try
{
omron = new Omron();
omron.IPAddr = System.Net.IPAddress.Parse(IpAddress);
omron.Port = Port;
string info;
if (!omron.PlcConnect(out info))
{
GlobalValues.Error($"连接失败");
}
else
{
GlobalValues.Success("连接成功");
Enabled1 = false;
Enabled2 = true;
}
}
catch (Exception ex)
{
GlobalValues.Error($"连接失败:{ex.Message}");
}
}
private void DisconnectCmdFunc(object obj)
{
omron.DisConnect();
omron = null;
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
string cmd = obj.ToString();
if (cmd == "1")
{
string[] res;
bool isSucess = omron.Read(AreaTypeList[ReadAreaIndex], ReadAddress, 0, ReadCount, out res);
if (!isSucess)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(obj);
return;
}
ReadResult = res.ToList().GetStrArray(" ");
}
else if (cmd == "2")
{
string res;
bool isSucess = omron.ReadString(ReadAddress, ReadCount, out res);
if (!isSucess)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(obj);
return;
}
ReadResult = res;
}
else if (cmd == "3")
{
float[] res;
bool isSucess = omron.ReadFloats(ReadAddress, ReadCount, out res);
if (!isSucess)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(obj);
return;
}
ReadResult = res.Select(it => Convert.ToString(it)).ToList().GetStrArray(" ");
}
else if (cmd == "4")
{
short[] res;
bool isSucess = omron.ReadShorts(ReadAddress, ReadCount, out res);
if (!isSucess)
{
GlobalValues.Error("读取失败");
DisconnectCmdFunc(obj);
return;
}
ReadResult = res.Select(it => Convert.ToString(it)).ToList().GetStrArray(" ");
}
}
private void WriteCmdFunc(object obj)
{
try
{
//1写入 2.Float 3Short 4字符串
string cmd = obj.ToString();
if (cmd == "1")
{
int[] intValues = WriteValue.Split(' ').Where(it => !it.IsNullOrEmpty()).Select(it => Convert.ToInt32(it)).ToArray();
if (WriteAreaIndex < 5)
{
bool[] values = intValues.Select(it => it == 1 ? true : false).ToArray();
bool isSucess = omron.WriteBits(AreaTypeList[WriteAreaIndex], WriteAddress, 0, values.Length, values);
if (!isSucess)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(obj);
return;
}
GlobalValues.Success("写入成功");
}
else
{
bool isSucess = omron.WriteWords(AreaTypeList[WriteAreaIndex], WriteAddress, intValues.Length, intValues);
if (!isSucess)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(obj);
return;
}
GlobalValues.Success("写入成功");
}
}
else if (cmd == "2")
{
float[] floatValues = WriteValue.Split(' ').Where(it => !it.IsNullOrEmpty()).Select(it => Convert.ToSingle(it)).ToArray();
bool isSucess = omron.WriteFloat(WriteAddress, floatValues);
if (!isSucess)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(obj);
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "3")
{
short[] floatValues = WriteValue.Split(' ').Where(it => !it.IsNullOrEmpty()).Select(it => Convert.ToInt16(it)).ToArray();
bool isSucess = omron.WriteShort(WriteAddress, floatValues);
if (!isSucess)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(obj);
return;
}
GlobalValues.Success("写入成功");
}
else if (cmd == "4")
{
bool isSucess = omron.WriteString(WriteAddress, WriteValue, StrLength);
if (!isSucess)
{
GlobalValues.Error("写入失败");
DisconnectCmdFunc(obj);
return;
}
GlobalValues.Success("写入成功");
}
}
catch (Exception ex)
{
MessageBox.ShowAsync($"操作异常:{ex.Message}");
}
}
}
}

View File

@@ -0,0 +1,264 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
using MES.Utility.Network.S7netplus;
using S7.Net;
namespace .ViewModel._01PLC通信调试
{
public class 西PLC调试ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public string IpAddress { get; set; } = "192.168.1.11";
public string Address { get; set; } = "DB44.DBD80";
public List<string> PlcTypeList { get; set; }
public List<CpuType> PlcTypeEnumList { get; set; }
public int PlcTypeIndex { get; set; } = 0;
public short R { get; set; } = 0;
public short S { get; set; } = 1;
public int DBAddress2 { get; set; } = 40;
public int Address2 { get; set; } = 80;
public int StringLength { get; set; } = 50;
public string BoolValue { get; set; } = "true";
public string Int16Value { get; set; } = "";
public string Int32Value { get; set; } = "";
public string RealValue { get; set; } = "";
public string StringValue { get; set; } = "";
public string StringValue1 { get; set; } = "";
public int BytesCount { get; set; } = 50;
public string ReadedValue { get; set; } = "";
public string Message { get; set; } = "";
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
private S7Helper plc;
public 西PLC调试ViewModel()
{
PlcTypeList = new List<string> { "S7-1200", "S7-1500", "S7-200", "S7-300", "S7-400" };
PlcTypeEnumList = new List<CpuType> { CpuType.S71200, CpuType.S71500, CpuType.S7200, CpuType.S7300, CpuType.S7400 };
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
}
/// <summary>
/// 连接
/// </summary>
/// <param name="obj"></param>
private void ConnectCmdFunc(object obj)
{
try
{
this.plc = new S7Helper(PlcTypeEnumList[PlcTypeIndex], IpAddress, R, S);
Enabled2 = true;
Enabled1 = false;
}
catch
{
GlobalValues.Error("PLC连接失败");
}
}
/// <summary>
/// 断开连接
/// </summary>
/// <param name="obj"></param>
private void DisconnectCmdFunc(object obj)
{
try { plc.Dispose(); } catch { }
plc = null;
Enabled1 = true;
Enabled2 = false;
}
/// <summary>
/// 读取操作
/// </summary>
/// <param name="obj"></param>
private void ReadCmdFunc(object obj)
{
ReadedValue = string.Empty;
Message = string.Empty;
string cmd = obj.ToString();
if (cmd == "BOOL")
{
bool value;
bool flag = plc.ReadBool(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "INT16")
{
ushort value;
bool flag = plc.ReadInt16(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "INT32")
{
int value;
bool flag = plc.ReadInt32(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "REAL")
{
float value;
bool flag = plc.ReadSingle(Address, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "STRING1")
{
string value;
bool flag = plc.ReadString(Address, StringLength, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "STRING")
{
string value;
bool flag = plc.ReadBytesString(Address, StringLength, out value);
if (!flag)
{
ReadedValue = string.Empty;
Message = "读取失败";
return;
}
ReadedValue = value.ToString();
Message = "读取成功";
}
else if (cmd == "Bytes")
{
byte[] value;
bool flag = plc.ReadBytes(DBAddress2, Address2, BytesCount, out value);
if (!flag)
{
Message = "读取失败";
return;
}
ReadedValue = ToHexStrFromByte(value);
Message = "读取成功";
}
}
private void WriteCmdFunc(object obj)
{
ReadedValue = string.Empty;
Message = string.Empty;
string cmd = obj.ToString();
if (cmd == "BOOL")
{
bool value;
bool flag = bool.TryParse(BoolValue, out value);
if (!flag)
{
Message = "请输入true或者false";
return;
}
flag = plc.WriteBool(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT16")
{
ushort value;
bool flag = ushort.TryParse(Int16Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = plc.WriteInt16(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "INT32")
{
int value;
bool flag = int.TryParse(Int32Value, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
flag = plc.WriteInt32(Address, value);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "REAL")
{
float value;
bool flag = float.TryParse(RealValue, out value);
if (!flag)
{
Message = "请输入正确的数据";
return;
}
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "STRING1")
{
bool flag = plc.WriteString(Address, StringValue1, StringLength);
Message = flag ? "写入成功" : "写入失败";
}
else if (cmd == "STRING")
{
bool flag = plc.WriteBytesString(Address, StringValue, StringLength);
Message = flag ? "写入成功" : "写入失败";
}
}
/// <summary>
/// 字节数组转16进制字符串空格分隔
/// </summary>
/// <param name="byteDatas"></param>
/// <returns></returns>
private string ToHexStrFromByte(byte[] byteDatas)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < byteDatas.Length; i++)
{
builder.Append(string.Format("{0:X2} ", byteDatas[i]));
}
return builder.ToString().Trim();
}
}
}

View File

@@ -0,0 +1,766 @@
using Avalonia.Threading;
using MES.Utility.Core;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Ursa.Controls;
using .Base;
using .Utility.Network;
namespace .ViewModel._02网络相关
{
public class FTP客户端ViewModel : ViewModelBase
{
public List<Encoding> EncodingList { get; set; } = new List<Encoding>() { Encoding.UTF8 };
public List<string> StrEncodingList { get; set; } = new List<string>() { "UTF-8" };
public int EncodingIndex { get; set; } = 0;
private object _lock = new object();
private List<string> msgList = new List<string>();
public string Message
{
get
{
lock (_lock)
{
return msgList.GetStrArray("\r\n");
}
}
set
{
lock (_lock)
{
msgList.Add(value);
}
NotifyPropertyChanged();
}
}
public string IpAddress { get; set; } = "127.0.0.1";
public string UserName { get; set; } = "admin";
public string Password { get; set; } = "123456";
public int Port { get; set; } = 21;
public bool IsAnonymous { get; set; } = false;
public bool EnableFlag1 { get; set; } = true;
public bool EnableFlag2 { get; set; } = false;
private FtpHelper ftp;
public DelegateCommand ConnectCmd { get; set; }
public DelegateCommand DisconnectCmd { get; set; }
public DelegateCommand LocalDoubleClickCommand { get; set; }
public DelegateCommand LocalHomeClickCommand { get; set; }
public DelegateCommand RemoteHomeClickCommand { get; set; }
public DelegateCommand RemoteDoubleClickCommand { get; set; }
public DelegateCommand DownloadClickCommand { get; set; }
public DelegateCommand UploadClickCommand { get; set; }
public DelegateCommand RemoteRenameClickCommand { get; set; }
public DelegateCommand RemoteDeleteClickCommand { get; set; }
public string LocalPath1 { get; set; } = "本地";
public string CurrentLocalPath { get; set; } = "";
public ObservableCollection<MyDir> LocalTree { get; set; }
public MyDir LocalTreeSelectedItem { get; set; } = null;
public string RemotePath1 { get; set; } = "远程";
public string CurrentRemotePath { get; set; } = "";
public ObservableCollection<MyDir> RemoteTree { get; set; }
public MyDir RemoteTreeSelectedItem { get; set; } = null;
public FTP客户端ViewModel()
{
LocalTree = GetFoldersAndFiles();
ConnectCmd = new DelegateCommand(ConnectCmdFunc);
DisconnectCmd = new DelegateCommand(DisconnectCmdFunc);
RemoteHomeClickCommand = new DelegateCommand(RemoteHomeClickCommandFunc);
LocalHomeClickCommand = new DelegateCommand(LocalHomeClickCommandFunc);
LocalDoubleClickCommand = new DelegateCommand(LocalDoubleClickCommandFunc);
RemoteDoubleClickCommand = new DelegateCommand(RemoteDoubleClickCommandFunc);
DownloadClickCommand = new DelegateCommand(DownloadClickCommandFunc);
UploadClickCommand = new DelegateCommand(UploadClickCommandFunc);
RemoteDeleteClickCommand = new DelegateCommand(RemoteDeleteClickCommandFunc);
RemoteRenameClickCommand = new DelegateCommand(RemoteRenameClickCommandFunc);
}
private void ConnectCmdFunc(object obj)
{
if (IsAnonymous)
{
try
{
ftp = new FtpHelper(IpAddress, Port, EncodingList[EncodingIndex]);
RemoteTree = GetRemoteFoldersAndFiles();
}
catch
{
GlobalValues.Error("FTP连接失败");
return;
}
}
else
{
try
{
ftp = new FtpHelper(IpAddress, Port, UserName, Password, EncodingList[EncodingIndex]);
RemoteTree = GetRemoteFoldersAndFiles();
}
catch
{
GlobalValues.Error("FTP连接失败");
return;
}
}
EnableFlag1 = false;
EnableFlag2 = true;
}
private void DisconnectCmdFunc(object obj)
{
ftp = null;
RemoteTree = new ObservableCollection<MyDir>();
RemotePath1 = "远程";
CurrentRemotePath = "";
EnableFlag1 = true;
EnableFlag2 = false;
}
private void RemoteDoubleClickCommandFunc(object obj)
{
try
{
MyDir current = (MyDir)obj;
if (current == null)
return;
if (current.IsBack)
{
string path = CurrentRemotePath;
if (path.EndsWith("/"))
path = path.Substring(0, path.Length - 1);
int index = path.LastIndexOf("/");
if (index == -1)
{
path = "";
}
else
{
path = path.Substring(0, index + 1);
}
if (path == "")
{
CurrentRemotePath = "";
RemotePath1 = "远程";
}
else
{
CurrentRemotePath = path;
RemotePath1 = "远程:" + CurrentRemotePath;
}
RemoteTree = GetRemoteFoldersAndFiles();
return;
}
//文件不能双击
if (!current.IsDirectory)
{
return;
}
CurrentRemotePath = current.Path;
RemotePath1 = "远程:" + CurrentRemotePath;
RemoteTree = GetRemoteFoldersAndFiles();
}
catch (Exception ex)
{
GlobalValues.Error("FTP连接失败");
DisconnectCmdFunc(null);
}
}
private void LocalDoubleClickCommandFunc(object obj)
{
MyDir current = (MyDir)obj;
if (current == null)
return;
if (current.IsBack)
{
string path = CurrentLocalPath;
if (path.EndsWith("/"))
path = path.Substring(0, path.Length - 1);
int index = path.LastIndexOf("/");
if (index == -1)
{
path = "";
}
else
{
path = path.Substring(0, index + 1);
}
if (path == "")
{
CurrentLocalPath = "";
LocalPath1 = "本地";
}
else
{
CurrentLocalPath = path.Replace("\\", "/");
LocalPath1 = "本地:" + CurrentLocalPath;
}
LocalTree = GetFoldersAndFiles();
return;
}
//文件不能双击
if (!current.IsDirectory)
{
return;
}
CurrentLocalPath = current.Path;
LocalPath1 = "本地:" + CurrentLocalPath;
LocalTree = GetFoldersAndFiles();
}
private ObservableCollection<MyDir> GetRemoteFoldersAndFiles()
{
ObservableCollection<MyDir> list = new ObservableCollection<MyDir>();
List<FtpFileInfo> list2 = ftp.GetList(CurrentRemotePath).OrderByDescending(it => it.IsDirectory).ToList();
if (CurrentRemotePath != "")
{
list.Add(new MyDir
{
Name = $"...",
Path = $"",
IsDirectory = true,
IsBack = true,
});
}
foreach (var ftpFileInfo in list2)
{
if (ftpFileInfo.IsDirectory)
{
list.Add(new MyDir
{
Name = $"{ftpFileInfo.Name}",
Path = $"{CurrentRemotePath}{ftpFileInfo.Name}/",
IsDirectory = true
});
}
else
{
list.Add(new MyDir
{
Name = $"{ftpFileInfo.Name}",
Path = $"{CurrentRemotePath}{ftpFileInfo.Name}",
IsDirectory = false
});
}
}
return list;
}
private ObservableCollection<MyDir> GetFoldersAndFiles()
{
ObservableCollection<MyDir> list = new ObservableCollection<MyDir>();
if (CurrentLocalPath == "")
{
list.Add(new MyDir
{
Name = "桌面",
Path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory).Replace("\\", "/"),
IsDirectory = true
});
// 获取所有盘符
DriveInfo[] allDrives = DriveInfo.GetDrives();
// 过滤出固态硬盘SSD和机械硬盘HDD
List<string> systemDrives = allDrives.Where(drive => drive.IsReady) // 确保驱动器已准备好访问
.Where(drive => drive.DriveType == DriveType.Fixed) // 仅固定类型的驱动器
.Select(drive => drive.Name.Substring(0, 1)) // 获取盘符
.ToList();
// 输出系统盘符
foreach (var drive in systemDrives)
{
list.Add(new MyDir
{
Name = $"{drive}",
Path = $"{drive}:/",
IsDirectory = true
});
}
}
else
{
list.Add(new MyDir
{
Name = "...",
Path = "",
IsDirectory = true,
IsBack = true,
});
List<string> dirList = Directory.GetDirectories(CurrentLocalPath).Select(it => it.Replace("\\", "/")).ToList();
foreach (string dirPath in dirList)
{
list.Add(new MyDir
{
Name = System.IO.Path.GetFileName(dirPath),
Path = dirPath + "/",
IsDirectory = true,
});
}
List<string> fileList = Directory.GetFiles(CurrentLocalPath).Select(it => it.Replace("\\", "/")).ToList();
foreach (string filePath in fileList)
{
list.Add(new MyDir
{
Name = System.IO.Path.GetFileName(filePath),
Path = filePath,
IsDirectory = false,
});
}
}
return list;
}
private void LocalHomeClickCommandFunc(object obj)
{
CurrentLocalPath = "";
LocalPath1 = "本地";
LocalTree = GetFoldersAndFiles();
}
private void RemoteHomeClickCommandFunc(object obj)
{
try
{
CurrentRemotePath = "";
RemotePath1 = "远程";
RemoteTree = GetRemoteFoldersAndFiles();
}
catch (Exception ex)
{
GlobalValues.Error("FTP连接失败");
DisconnectCmdFunc(null);
}
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="obj"></param>
private async void UploadClickCommandFunc(object obj)
{
if (LocalTreeSelectedItem == null)
{
await MessageBox.ShowAsync("请选择要上传的文件或文件夹");
return;
}
if (LocalTreeSelectedItem.IsBack)
{
return;
}
bool cover = false;
var result = await MessageBox.ShowOverlayAsync("上传过程中可能文件存在,是否覆盖上传", "提示", button: MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
{
cover = false;
}
else
{
cover = true;
}
//上传文件夹
if (LocalTreeSelectedItem.IsDirectory)
{
new Thread(() =>
{
UploadDir(LocalTreeSelectedItem, CurrentRemotePath, cover);
Message = $"文件夹上传完成:{LocalTreeSelectedItem.Name}";
Dispatcher.UIThread.Invoke(() =>
{
RemoteTree = GetRemoteFoldersAndFiles();
});
}).Start();
}
//上传文件
else
{
new Thread(() =>
{
try
{
//判断远端是否存在文件,是否覆盖
bool isExist = ftp.IsFileExist(CurrentRemotePath, LocalTreeSelectedItem.Name);
if (isExist && !cover)
{
return;
}
Message = $"准备上传:{LocalTreeSelectedItem.Path}";
ftp.UploadFile(LocalTreeSelectedItem.Path, CurrentRemotePath + LocalTreeSelectedItem.Name);
Message = $"上传完成:{LocalTreeSelectedItem.Path}";
}
catch (Exception ex)
{
Message = $"上传失败:{LocalTreeSelectedItem.Path}";
}
Dispatcher.UIThread.Invoke(() =>
{
RemoteTree = GetRemoteFoldersAndFiles();
});
}).Start();
}
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="obj"></param>
private async void DownloadClickCommandFunc(object obj)
{
if (RemoteTreeSelectedItem == null)
{
await MessageBox.ShowAsync("请选择要下载的文件或文件夹");
return;
}
if (CurrentLocalPath == "")
{
await MessageBox.ShowAsync("请选择本地路径");
return;
}
if (RemoteTreeSelectedItem.IsBack)
{
return;
}
bool cover = false;
var result = await MessageBox.ShowOverlayAsync("下载过程中可能文件存在,是否覆盖下载", "提示", button: MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
{
cover = false;
}
else
{
cover = true;
}
//下载文件夹
if (RemoteTreeSelectedItem.IsDirectory)
{
new Thread(() =>
{
DownloadDir(RemoteTreeSelectedItem, CurrentLocalPath, cover);
Message = $"文件夹下载完成:{RemoteTreeSelectedItem.Name}";
Dispatcher.UIThread.Invoke(() =>
{
LocalTree = GetFoldersAndFiles();
});
}).Start();
}
//下载文件
else
{
new Thread(() =>
{
try
{
if (File.Exists(CurrentLocalPath + "/" + RemoteTreeSelectedItem.Name) && !cover)
{
return;
}
Message = $"准备下载:{RemoteTreeSelectedItem.Name}";
ftp.DownloadFile(RemoteTreeSelectedItem.Path, CurrentLocalPath + "/" + RemoteTreeSelectedItem.Name);
Message = $"下载完成:{RemoteTreeSelectedItem.Name}";
}
catch (Exception ex)
{
Message = $"下载失败:{ex.Message}";
}
Dispatcher.UIThread.Invoke(() =>
{
LocalTree = GetFoldersAndFiles();
});
}).Start();
}
}
/// <summary>
/// 删除FTP文件
/// </summary>
/// <param name="obj"></param>
/// <exception cref="NotImplementedException"></exception>
private async void RemoteDeleteClickCommandFunc(object obj)
{
try
{
if (RemoteTreeSelectedItem == null)
{
await MessageBox.ShowAsync("请选择要删除的文件或文件夹");
return;
}
if (RemoteTreeSelectedItem.IsBack)
{
return;
}
var result = await MessageBox.ShowOverlayAsync("是否确定删除", "提示", button: MessageBoxButton.YesNo);
if (result != MessageBoxResult.Yes)
{
return;
}
if (RemoteTreeSelectedItem.IsDirectory)
{
new Thread(() =>
{
try
{
DeleteDirecory(RemoteTreeSelectedItem.Path);
Message = $"删除成功:{RemoteTreeSelectedItem.Path}";
}
catch (Exception ex)
{
Message = $"删除失败:{ex.Message}";
}
Dispatcher.UIThread.Invoke(() =>
{
RemoteTree = GetRemoteFoldersAndFiles();
});
}).Start();
}
else
{
new Thread(() =>
{
Message = $"准备删除:{RemoteTreeSelectedItem.Path}";
try
{
ftp.DeleteFile(RemoteTreeSelectedItem.Path);
Message = $"删除成功:{RemoteTreeSelectedItem.Path}";
}
catch (Exception ex)
{
Message = $"删除失败:{ex.Message}";
}
Dispatcher.UIThread.Invoke(() =>
{
RemoteTree = GetRemoteFoldersAndFiles();
});
}).Start();
}
}
catch (Exception ex)
{
await MessageBox.ShowAsync(ex.Message);
}
}
private void DeleteDirecory(string path)
{
List<FtpFileInfo> list = ftp.GetList(path);
foreach (FtpFileInfo info in list)
{
if (info.IsDirectory)
{
DeleteDirecory(path + info.Name + "/");
}
else
{
Message = $"准备删除:{path + info.Name}";
try
{
ftp.DeleteFile(path + info.Name);
Message = $"删除成功:{path + info.Name}";
}
catch (Exception ex)
{
Message = $"删除失败:{ex.Message}";
}
}
}
ftp.DeleteDirectory(path);
}
/// <summary>
/// 递归调用
/// </summary>
/// <param name="remoteTreeSelectedItem"></param>
/// <param name="currentLocalPath"></param>
/// <exception cref="NotImplementedException"></exception>
private void DownloadDir(MyDir remoteTreeSelectedItem, string currentLocalPath, bool cover)
{
//文件夹是否存在
string localPath = currentLocalPath + "/" + remoteTreeSelectedItem.Name;
if (!Directory.Exists(localPath))
{
Directory.CreateDirectory(localPath);
}
List<FtpFileInfo> myDirs = ftp.GetList(remoteTreeSelectedItem.Path);
foreach (FtpFileInfo f in myDirs)
{
if (f.IsDirectory)
{
MyDir dir = new MyDir { IsDirectory = true, Name = f.Name, Path = remoteTreeSelectedItem.Path + f.Name + "/" };
DownloadDir(dir, localPath, cover);
}
else
{
try
{
if (File.Exists(localPath + "/" + f.Name) && !cover)
{
return;
}
Message = $"准备下载:{remoteTreeSelectedItem.Path + f.Name}";
ftp.DownloadFile(remoteTreeSelectedItem.Path + f.Name, localPath + "/" + f.Name);
Message = $"下载完成:{remoteTreeSelectedItem.Path + f.Name}";
}
catch (Exception ex)
{
Message = $"下载失败:{ex.Message}";
}
}
}
}
private void UploadDir(MyDir localTreeSelectedItem, string currentRemotePath, bool cover)
{
//文件夹是否存在
string remotePath = currentRemotePath + localTreeSelectedItem.Name + "/";
if (!ftp.FolderExists(currentRemotePath, localTreeSelectedItem.Name))
{
ftp.CreateFolder(remotePath);
}
string[] dirList = Directory.GetDirectories(localTreeSelectedItem.Path).Select(it => it.Replace("\\", "/")).ToArray();
string[] fileList = Directory.GetFiles(localTreeSelectedItem.Path).Select(it => it.Replace("\\", "/")).ToArray();
foreach (string f in dirList)
{
MyDir dir = new MyDir { IsDirectory = true, Name = System.IO.Path.GetFileName(f), Path = f };
UploadDir(dir, remotePath, cover);
}
foreach (string f in fileList)
{
try
{
bool isExist = ftp.IsFileExist(remotePath + "/", System.IO.Path.GetFileName(f));
if (isExist)
{
continue;
}
Message = $"准备上传:{localTreeSelectedItem.Path + System.IO.Path.GetFileName(f)}";
ftp.UploadFile(localTreeSelectedItem.Path + "/" + System.IO.Path.GetFileName(f), remotePath + "/" + System.IO.Path.GetFileName(f));
Message = $"上传完成:{localTreeSelectedItem.Path + System.IO.Path.GetFileName(f)}";
}
catch (Exception ex)
{
Message = $"上传失败:{ex.Message}";
}
}
}
private void RemoteRenameClickCommandFunc(object obj)
{
if (RemoteTreeSelectedItem == null)
{
MessageBox.ShowAsync("请选择要重命名的文件或文件夹");
return;
}
if (RemoteTreeSelectedItem.IsBack)
{
return;
}
string newName = Interaction.InputBox("请输入新名字", "", "", 200, 100);
if (newName.IsNullOrEmpty())
{
MessageBox.ShowAsync("请输入新文件名");
return;
}
string path = "";
if (RemoteTreeSelectedItem.IsDirectory)
{
path = CurrentRemotePath;
if (path.EndsWith("/"))
path = path.Substring(0, path.Length - 1);
int index = path.LastIndexOf("/");
if (index == -1)
{
path = "";
}
else
{
path = path.Substring(0, index + 1);
}
path += newName + "/";
}
else
{
path = CurrentRemotePath;
if (path.EndsWith("/"))
path = path.Substring(0, path.Length - 1);
int index = path.LastIndexOf("/");
if (index == -1)
{
path = "";
}
else
{
path = path.Substring(0, index + 1);
}
string ext = System.IO.Path.GetExtension(RemoteTreeSelectedItem.Path);
if (!newName.ToLower().EndsWith(ext.ToLower()))
{
path = path + newName + ext;
}
}
new Thread(() =>
{
try
{
ftp.Rename(RemoteTreeSelectedItem.Path, path);
Dispatcher.UIThread.Invoke(() =>
{
RemoteTree = GetRemoteFoldersAndFiles();
});
}
catch (Exception ex)
{
Message = $"重命名失败:{ex.Message}";
}
}).Start();
}
}
public class MyDir
{
public string Path { get; set; }
public string Name { get; set; }
public bool IsDirectory { get; set; }
public bool IsBack { get; set; }
}
}

View File

@@ -0,0 +1,159 @@
using Avalonia.Platform.Storage;
using FubarDev.FtpServer;
using FubarDev.FtpServer.AccountManagement;
using FubarDev.FtpServer.FileSystem.DotNet;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Ursa.Controls;
using .Base;
namespace .ViewModel._02网络相关
{
public class FTP服务ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public string ButtonName { get; set; } = "开启服务";
public string Path { get; set; } = "d:/";
public int Port { get; set; } = 21;
public string UserName { get; set; } = "admin";
public string Password { get; set; } = "123456";
public bool Anonymous { get; set; } = true;
public int MaxConnectCount { get; set; } = 100;
public DelegateCommand SelectPathCmd { get; set; }
public DelegateCommand StartCmd { get; set; }
public FTP服务ViewModel()
{
SelectPathCmd = new DelegateCommand(SelectPathCmdFunc);
StartCmd = new DelegateCommand(StartCmdFunc);
}
private void StartCmdFunc(object obj)
{
if (ButtonName == "开启服务")
{
bool flag = Start(UserName, Password, Path, Port, Anonymous, MaxConnectCount);
if (!flag)
{
return;
}
Enabled1 = false;
ButtonName = "停止服务";
}
else
{
bool flag = Stop();
if (!flag)
return;
Enabled1 = true;
ButtonName = "开启服务";
}
}
private async void SelectPathCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
var result = await sp.OpenFolderPickerAsync(new FolderPickerOpenOptions()
{
Title = "选择FTP主目录",
AllowMultiple = false,
});
if (result == null || result.Count == 0)
{
await MessageBox.ShowAsync("文件夹路径不能为空");
return;
}
Path = result.FirstOrDefault()?.Path.LocalPath;
}
internal static string UserName1 { get; set; }
internal static string Password1 { get; set; }
public ServiceProvider serviceProvider;
public IFtpServerHost ftpServerHost;
private bool Start(string userName, string password, string path, int port, bool anonymous, int maxConnectCount)
{
try
{
UserName1 = userName;
Password1 = password;
// 设置依赖项注入
var services = new ServiceCollection();
// 使用%TEMP%/TestFtpServer作为根文件夹
services.Configure<DotNetFileSystemOptions>(opt =>
{
opt.RootPath = path;
});
services.Configure<FtpConnectionOptions>(opt => opt.DefaultEncoding = Encoding.GetEncoding("GB2312"));
// 添加FTP服务器服务
// DotNetFileSystemProvider = 使用.NET文件系统功能
// AnonymousMembershipProvider = 仅允许匿名登录
services.AddFtpServer(builder =>
{
builder.UseDotNetFileSystem(); // 使用.NET文件系统功能
if (anonymous)
{
builder.EnableAnonymousAuthentication();// 允许匿名登录
}
builder.Services.AddSingleton<IMembershipProvider, TestMembershipProvider>();//用户登录
});
// 配置FTP服务器
services.Configure<FtpServerOptions>(opt =>
{
opt.ServerAddress = "*";
opt.Port = port;
opt.MaxActiveConnections = maxConnectCount;
});
serviceProvider = services.BuildServiceProvider();
ftpServerHost = serviceProvider.GetRequiredService<IFtpServerHost>();
ftpServerHost.StartAsync(CancellationToken.None);
return true;
}
catch (Exception ex)
{
return false;
}
}
public class TestMembershipProvider : IMembershipProvider
{
public Task<MemberValidationResult> ValidateUserAsync(string name, string password)
{
if (UserName1 == name && password == Password1)
{
var identity = new ClaimsIdentity();
identity.AddClaim(new Claim(ClaimTypes.Name, name));
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
return Task.FromResult(new MemberValidationResult(MemberValidationStatus.AuthenticatedUser, new ClaimsPrincipal(identity)));
}
return Task.FromResult(new MemberValidationResult(MemberValidationStatus.InvalidLogin));
}
}
private bool Stop()
{
try
{
// 停止FTP服务器
ftpServerHost.StopAsync(CancellationToken.None).Wait();
serviceProvider.Dispose();
ftpServerHost = null;
serviceProvider = null;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}

View File

@@ -0,0 +1,271 @@
using MES.Utility.Core;
using System;
using System.Collections.Generic;
using .Base;
using System.Threading;
using .Utility.Network;
using System.IO;
using Ursa.Controls;
using Avalonia.Threading;
using Avalonia.Platform.Storage;
namespace .ViewModel._02网络相关
{
public class HTTP调试ViewModel : ViewModelBase
{
private bool getChecked = true;
public bool GetChecked
{
get { return getChecked; }
set
{
getChecked = value;
if (value)
{
Visiable =false;
}
NotifyPropertyChanged();
}
}
private bool downloadChecked = false;
public bool DownloadChecked
{
get { return downloadChecked; }
set
{
downloadChecked = value;
if (value)
{
Visiable = false;
}
NotifyPropertyChanged();
}
}
private bool postChecked = false;
public bool PostChecked
{
get { return postChecked; }
set
{
postChecked = value;
if (value)
{
Visiable = true;
}
NotifyPropertyChanged();
}
}
public string Url { get; set; } = "";
public DelegateCommand ButtonCmd { get; set; }
public bool JsonChecked { get; set; } = true;
public bool FormChecked { get; set; } = false;
public int Timeout { get; set; } = 1000;
public bool Visiable { get; set; } = false;
public string Parms { get; set; } = "";
public string Result { get; set; } = "";
public bool ButtonEnabled { get; set; } = true;
public HTTP调试ViewModel()
{
ButtonCmd = new DelegateCommand(ButtonCmdFunc);
}
private void ButtonCmdFunc(object obj)
{
if (Url.IsNullOrEmpty())
{
MessageBox.ShowAsync("请输入URL");
return;
}
string url = Url;
if (!url.ToLower().StartsWith("http"))
{
url = "http://" + url;
}
int timeout = Timeout;
if (GetChecked)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (url.Contains("?"))
{
int index = url.IndexOf("?");
string parms = url.Substring(index + 1, url.Length - index - 1);
string[] parmsArray = parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
parmsArray = Parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
url = url.Substring(0, index);
}
else
{
string[] parmsArray = Parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
}
ButtonEnabled = false;
Result = string.Empty;
new Thread(() =>
{
string ret = HttpUtils.DoGet(url, dict, timeout);
if (!ret.IsNullOrEmpty())
{
Result = ret;
}
else
{
Result = "网络或服务器异常";
}
ButtonEnabled = true;
}).Start();
}
else if (DownloadChecked)
{
Dictionary<string, string> dict = new Dictionary<string, string>();
if (url.Contains("?"))
{
int index = url.IndexOf("?");
string parms = url.Substring(index + 1, url.Length - index - 1);
string[] parmsArray = parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
parmsArray = Parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
url = url.Substring(0, index);
}
else
{
string[] parmsArray = Parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
}
ButtonEnabled = false;
Result = string.Empty;
new Thread(() =>
{
byte[] ret = HttpUtils.DoGetFile(url, timeout);
if (ret == null)
{
Result = "网络或服务器异常";
}
else
{
Dispatcher.UIThread.Invoke(async () =>
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
var result = await sp.SaveFilePickerAsync(new FilePickerSaveOptions()
{
Title = "保存文件"
});
if (result == null) return;
string filePath = result.Path.LocalPath;
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
fs.Write(ret, 0, ret.Length);
}
await MessageBox.ShowAsync("下载完成");
});
}
ButtonEnabled = true;
}).Start();
}
else
{
//JSON
if (JsonChecked)
{
ButtonEnabled = false;
Result = string.Empty;
new Thread(() =>
{
string ret = HttpUtils.DoPostJson(url, Parms, timeout);
if (!ret.IsNullOrEmpty())
{
Result = ret;
}
else
{
Result = "网络或服务器异常";
}
ButtonEnabled = true;
}).Start();
}
else
{
Dictionary<string, string> dict = new Dictionary<string, string>();
string[] parmsArray = Parms.Split('&');
foreach (string parm in parmsArray)
{
if (parm.Contains("="))
{
string[] array = parm.Split('=');
dict.Add(array[0], array[1]);
}
}
ButtonEnabled = false;
Result = string.Empty;
new Thread(() =>
{
string ret = HttpUtils.DoPostForm(url, dict, timeout);
if (!ret.IsNullOrEmpty())
{
Result = ret;
}
else
{
Result = "网络或服务器异常";
}
ButtonEnabled = true;
}).Start();
}
}
}
}
}

View File

@@ -0,0 +1,200 @@
using Avalonia.Threading;
using MES.Utility.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using .Base;
namespace .ViewModel._02网络相关
{
public class ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
public int SelectedIndex { get; set; } = -1;
public ObservableCollection<ScanResult> DataList { get; set; } = new ObservableCollection<ScanResult>();
public int ProgressValue { get; set; } = 0;
public int ProgressMax { get; set; } = 100;
public DelegateCommand StartScanCmd { get; set; }
public DelegateCommand CloseProcessCmd { get; set; }
public ViewModel()
{
StartScanCmd = new DelegateCommand(StartScanCmdFunc);
CloseProcessCmd = new DelegateCommand(CloseProcessCmdFunc);
}
private void CloseProcessCmdFunc(object obj)
{
if (SelectedIndex < 0)
{
return;
}
int pid = DataList[SelectedIndex].PID;
Process process = Process.GetProcessById(pid);
if (process == null)
{
GlobalValues.Error("获取进程相关信息失败,请尝试重新操作");
return;
}
try
{
process.Kill();
process.WaitForExit();
process.Close();
DataList.RemoveAt(SelectedIndex);
GlobalValues.Success("操作成功");
}
catch (Exception ex)
{
GlobalValues.Error($"结束进程失败:{ex.Message}");
}
}
private void StartScanCmdFunc(object obj)
{
Enabled1 = false;
Enabled2 = false;
ProgressValue = 0;
DataList.Clear();
new Thread(() =>
{
ProcessStartInfo startInfo = new ProcessStartInfo("netstat", "-ano")
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
string result = "";
using (Process process = Process.Start(startInfo))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
}
}
List<string> lines = result.Split('\n').Select(it => it.Trim('\r').Trim()).Where(it => !it.IsNullOrEmpty()).ToList();
List<ScanResult> results = new List<ScanResult>();
foreach (string line in lines)
{
string[] splitArray = line.Split(' ').Where(it => !it.IsNullOrEmpty()).ToArray();
if (!line.StartsWith("TCP") && !line.StartsWith("UDP"))
continue;
if (splitArray.Length == 5)
{
int pid;
bool flag = int.TryParse(splitArray[4], out pid);
if (!flag)
continue;
if (!splitArray[1].Contains(":"))
{
continue;
}
string[] splitArray2 = splitArray[1].Split(':');
int port;
flag = int.TryParse(splitArray2[1], out port);
if (!flag)
continue;
results.Add(new ScanResult
{
Protocol = splitArray[0],
LocalAddress = splitArray[1],
Port = port,
RemoteAddress = splitArray[2],
State = splitArray[3],
PID = pid,
ProcessName = ""
});
}
else if (splitArray.Length == 4)
{
int pid;
bool flag = int.TryParse(splitArray[3], out pid);
if (!flag)
continue;
if (!splitArray[1].Contains(":"))
{
continue;
}
string[] splitArray2 = splitArray[1].Split(':');
int port;
flag = int.TryParse(splitArray2[1], out port);
if (!flag)
continue;
results.Add(new ScanResult
{
Protocol = splitArray[0],
LocalAddress = splitArray[1],
Port = port,
RemoteAddress = splitArray[2],
State = "",
PID = pid,
ProcessName = ""
});
}
}
results = results.OrderBy(it => it.Port).ToList();
Dictionary<int, string> pidName = new Dictionary<int, string>();
foreach (ScanResult scan in results)
{
try
{
if (pidName.ContainsKey(scan.PID))
{
scan.ProcessName = pidName[scan.PID];
}
else
{
Process process = Process.GetProcessById(scan.PID);
if (process != null)
{
pidName.Add(scan.PID, process.ProcessName);
scan.ProcessName = process.ProcessName;
}
}
Dispatcher.UIThread.Invoke(new Action(() =>
{
DataList.Add(scan);
}));
}
catch
{
Dispatcher.UIThread.Invoke(new Action(() =>
{
DataList.Add(scan);
}));
}
}
Dispatcher.UIThread.Invoke(new Action(() =>
{
Enabled1 = true;
Enabled2 = true;
}));
}).Start();
}
}
public class ScanResult
{
public string Protocol { get; set; }
public string LocalAddress { get; set; }
public int Port { get; set; }
public string RemoteAddress { get; set; }
public string State { get; set; }
public int PID { get; set; }
public string ProcessName { get; set; }
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._02网络相关
{
public class ViewModel : ViewModelBase
{
}
}

View File

@@ -0,0 +1,241 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net.NetworkInformation;
using System.Threading;
using Ursa.Controls;
using .Base;
namespace .ViewModel._02网络相关
{
public class ViewModel : ViewModelBase
{
#region
public ObservableCollection<MyPingStatus> PingStatus { get; set; }
private int ip1 { get; set; } = 172;
public int IP1 { get { return ip1; } set { ip1 = value; SetTip(); NotifyPropertyChanged(); } }
private int ip2 { get; set; } = 16;
public int IP2 { get { return ip2; } set { ip2 = value; SetTip(); NotifyPropertyChanged(); } }
private int ip3 { get; set; } = 0;
public int IP3 { get { return ip3; } set { ip3 = value; SetTip(); NotifyPropertyChanged(); } }
#endregion
public DelegateCommand Button1Cmd { get; set; }
public DelegateCommand Button2Cmd { get; set; }
public ViewModel()
{
lock (_lock)
{
PingStatus = new ObservableCollection<MyPingStatus>();
for (int i = 1; i <= 255; i++)
{
PingStatus.Add(new MyPingStatus
{
Index = i,
IpAddress = $"{IP1}.{IP2}.{IP3}.{i}",
Color = "#FFFF80",
Tip = $"{IP1}.{IP2}.{IP3}.{i}",
Status = false
});
}
}
threadList = new List<MyThread>();
SetTip();
Button1Cmd = new DelegateCommand(Button1CmdFunc);
Button2Cmd = new DelegateCommand(Button2CmdFunc);
}
private List<MyThread> threadList;
private void Button1CmdFunc(object obj)
{
lock (pingLock)
{
if (IPPool.Count > 0)
{
MessageBox.ShowAsync("上一次操作还没结束,请等待完成后继续");
return;
}
}
lock (_lock)
{
SetColor("#FFFF80");//开始之前清除一下
}
foreach (MyThread myThread in threadList)
{
myThread.Stop();
myThread.OnSendResult -= Thread_OnSendResult;
}
threadList.Clear();
lock (_lock)
{
for (int i = 1; i <= 255; i++)
{
IPPool.Add(i);
}
}
string ip = $"{IP1}.{IP2}.{IP3}.";
for (int i = 0; i < 10; i++)
{
MyThread thread = new MyThread(ip);
thread.OnSendResult += Thread_OnSendResult;
thread.Start();
threadList.Add(thread);
}
}
private void Thread_OnSendResult(int endIndex, bool state)
{
if (state)
{
SetColor(endIndex, "#00FF00");
}
else
{
SetColor(endIndex, "#FF0000");
}
}
private void Button2CmdFunc(object obj)
{
lock (pingLock)
{
if (IPPool.Count > 0)
{
MessageBox.ShowAsync("上一次操作还没结束,请等待完成后继续");
return;
}
}
lock (_lock)
{
SetColor("#FFFF80");
}
}
/// <summary>
/// 设置提示
/// </summary>
private void SetTip()
{
foreach (MyPingStatus status in PingStatus)
{
status.Tip = $"{IP1}.{IP2}.{IP3}.{status.Index}";
}
}
/// <summary>
/// 设置提示
/// </summary>
private void SetColor(string color)
{
foreach (MyPingStatus status in PingStatus)
{
status.Color = color;
}
}
internal static List<int> IPPool = new List<int>();
internal static object pingLock = new object();
internal object _lock = new object();
private void SetColor(int index, string color)
{
lock (_lock)
{
foreach (MyPingStatus status in PingStatus)
{
if (status.Index == index)
{
status.Color = color;
break;
}
}
}
}
}
public class MyPingStatus : ViewModelBase
{
public int Index { get; set; }
public string Color { get; set; }
public string Tip { get; set; }
public string IpAddress { get; set; }
public bool Status { get; set; }
}
internal class MyThread
{
public delegate void SendResult(int endIndex, bool state);
public event SendResult OnSendResult;
private Thread thread;
private string ipAddress;
private bool stop;
public MyThread(string ip)
{
this.ipAddress = ip;
}
public MyThread Start()
{
thread = new Thread(() =>
{
while (true)
{
try
{
if (stop)
break;
//从IP池取出一个
int ipIndex = 0;
lock (ViewModel.pingLock)
{
if (ViewModel.IPPool.Count > 0)
{
ipIndex = ViewModel.IPPool[0];
ViewModel.IPPool.RemoveAt(0);
}
}
if (ipIndex == 0)
break;
bool flag = Ping($"{ipAddress}{ipIndex}");
OnSendResult?.Invoke(ipIndex, flag);
}
catch (Exception ex)
{
if (ex is ThreadInterruptedException)
break;
}
}
});
thread.Start();
return this;
}
public void Stop()
{
stop = true;
thread.Interrupt();
}
private bool Ping(string ip)
{
byte[] bytes = new byte[32];
for (int i = 0; i < bytes.Length; i++)
{
bytes[i] = (byte)(i + 1);
}
Ping ping = new Ping();
if (ping.Send(ip, 300, bytes, new PingOptions { Ttl = 255 }).Status == IPStatus.Success)
{
return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,125 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Avalonia;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using Ursa.Controls;
using .Base;
namespace .ViewModel._03图片相关
{
public class GIF分割ViewModel : ViewModelBase
{
public List<string> Paths { get; set; } = new List<string>();
public string ButtonName { get; set; } = "导出文件";
public string Path1 { get; set; } = "";
public string Path2 { get; set; } = "";
public DelegateCommand SelectGifCmd { get; set; }
public DelegateCommand SelectExportPathCmd { get; set; }
public DelegateCommand ExportCmd { get; set; }
public GIF分割ViewModel()
{
SelectGifCmd = new DelegateCommand(SelectGifCmdFunc);
SelectExportPathCmd = new DelegateCommand(SelectExportPathCmdFunc);
ExportCmd = new DelegateCommand(ExportCmdFunc);
}
private async void SelectGifCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
FilePickerOpenOptions options = new FilePickerOpenOptions();
options.Title = "选择GIF文件";
options.AllowMultiple = false;
options.FileTypeFilter = [
new FilePickerFileType("GIF文件")
{
Patterns = new[] { "*.gif" },
AppleUniformTypeIdentifiers = new[] { "public.gif" },
MimeTypes = new[] { "image/gif" }
}];
var result = await sp.OpenFilePickerAsync(options);
if (result == null || result.Count == 0) return;
Path1 = result.FirstOrDefault()?.Path.LocalPath;
}
private async void SelectExportPathCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
var result = await sp.OpenFolderPickerAsync(new FolderPickerOpenOptions()
{
Title = "Select Folder",
AllowMultiple = false,
});
if (result == null || result.Count == 0) return;
Path2 = result.FirstOrDefault()?.Path.LocalPath;
}
private void ExportCmdFunc(object obj)
{
string gifPath = Path1.Trim();
string folderPaht = Path2.Trim();
if (string.IsNullOrEmpty(gifPath) || string.IsNullOrEmpty(folderPaht))
{
MessageBox.ShowAsync("请选择gif路径或者导出路径!");
return;
}
if (ButtonName == "导出文件")
{
ButtonName = "导出中...";
//开启线程导出图片
Thread thread = new Thread(Export);
thread.Start();
}
else
{
MessageBox.ShowAsync("正在导出中!");
return;
}
}
/// <summary>
/// 导出jpg图片
/// </summary>
private void Export()
{
string gifPath = Path1.Trim();
string folderPaht = Path2.Trim();
Image img = Image.FromFile(gifPath);
FrameDimension fd = new FrameDimension(img.FrameDimensionsList[0]);
//获取gif帧的数量
int count = img.GetFrameCount(fd);
//遍历保存图片
for (int i = 0; i < count; i++)
{
img.SelectActiveFrame(fd, i);
string imgPath = folderPaht + "\\frame" + (i + 1) + ".png";
//判断同名文件是否存在
if (File.Exists(imgPath))
{
File.Delete(imgPath);
}
//保存图片 一定要设置格式 否则保存出来的图片都是一张图片
img.Save(imgPath, ImageFormat.Png);
}
Dispatcher.UIThread.Invoke(() =>
{
GlobalValues.Success("文件导出成功!");
ButtonName = "导出文件";
});
}
}
}

View File

@@ -0,0 +1,89 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Avalonia.Media.Imaging;
using Avalonia.Platform.Storage;
using SkiaSharp;
using ZXing;
using ZXing.Common;
using ZXing.SkiaSharp;
using .Base;
namespace .ViewModel._03图片相关
{
public class ViewModel : ViewModelBase
{
public string ImagePath { get; set; } = "";
public string Result { get; set; } = "";
public DelegateCommand SelectPathCmd { get; set; }
public DelegateCommand GetResultCmd { get; set; }
public ViewModel()
{
SelectPathCmd = new DelegateCommand(SelectPathCmdFunc);
GetResultCmd = new DelegateCommand(GetResultCmdFunc);
}
/// <summary>
/// 选择文件
/// </summary>
/// <param name="obj"></param>
private async void SelectPathCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
FilePickerOpenOptions options = new FilePickerOpenOptions();
options.Title = "选择二维码图片";
options.AllowMultiple = false;
options.FileTypeFilter = [
FilePickerFileTypes.ImageAll
];
var result = await sp.OpenFilePickerAsync(options);
if (result == null || result.Count == 0) return;
ImagePath = result.FirstOrDefault()?.Path.LocalPath;
}
private void GetResultCmdFunc(object obj)
{
try
{
MultiFormatReader formatReader = new MultiFormatReader();
Dictionary<DecodeHintType, object> hints = new Dictionary<DecodeHintType, object>();
hints.Add(DecodeHintType.CHARACTER_SET, Encoding.UTF8.HeaderName);
// 优化精度
hints.Add(DecodeHintType.TRY_HARDER, true);
// 复杂模式开启PURE_BARCODE模式
hints.Add(DecodeHintType.PURE_BARCODE, true);
formatReader.Hints = hints;
SKBitmap bitmap = SKBitmap.Decode(ImagePath);
LuminanceSource source = new SKBitmapLuminanceSource(bitmap);
Result result = formatReader.decode(new BinaryBitmap(new HybridBinarizer(source)));
if (null == result)
{
result = formatReader.decode(new BinaryBitmap(new GlobalHistogramBinarizer(source)));
}
bitmap.Dispose();
if (result != null)
{
Result = result.Text; // 显示解析出的一维码文本内容
}
else
{
Result = "未能解析条码";
}
}
catch (Exception ex)
{
Result = ex.Message;
}
}
}
}

View File

@@ -0,0 +1,118 @@
using System;
using .Base;
using Avalonia.Media.Imaging;
using SkiaSharp;
using Ursa.Controls;
using Avalonia.Platform.Storage;
using System.Linq;
using System.IO;
using ImageMagick;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace .ViewModel._03图片相关
{
public class ICOViewModel : ViewModelBase
{
public string ImagePath { get; set; }
public Bitmap ImageSource { get; set; }
public DelegateCommand SelectImageCmd { get; set; }
public DelegateCommand ExportCmd { get; set; }
public ICOViewModel()
{
SelectImageCmd = new DelegateCommand(SelectImageCmdFunc);
ExportCmd = new DelegateCommand(ExportCmdFunc);
}
private async void SelectImageCmdFunc(object obj)
{
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
FilePickerOpenOptions options = new FilePickerOpenOptions();
options.Title = "选择图片";
options.AllowMultiple = false;
options.FileTypeFilter = [FilePickerFileTypes.ImageAll];
var result = await sp.OpenFilePickerAsync(options);
if (result == null || result.Count == 0) return;
ImagePath = result.FirstOrDefault()?.Path.LocalPath;
ImageSource = new Bitmap(ImagePath);
}
private async void ExportCmdFunc(object obj)
{
int size = Convert.ToInt32(obj);
SKBitmap sbitmap = SKBitmap.Decode(ImagePath);
SKBitmap bitmap = ResizeImage(sbitmap, size, size);
//Icon icon = ConvertToIcon(bitmap);
//IconDir icon = new IconDir();
//icon.AddImage(bitmap, bitmap.Width, bitmap.Height);
var sp = GlobalValues.StorageProvider;
if (sp is null) return;
var result = await sp.OpenFolderPickerAsync(new FolderPickerOpenOptions()
{
Title = "请选择要生成的目录",
AllowMultiple = false,
});
if (result == null || result.Count == 0)
{
await MessageBox.ShowAsync("文件夹路径不能为空");
return;
}
string filePath = result.FirstOrDefault()?.Path.LocalPath;
if (!filePath.EndsWith("/"))
{
filePath += "/";
}
string fileName = "favicon_" + size + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");
byte[] bytes = null;
using (MemoryStream stream = new MemoryStream())
{
SKData data = bitmap.Encode(SKEncodedImageFormat.Png, 100);
data.SaveTo(stream);
bytes = stream.ToArray();
}
using (MemoryStream stream = new MemoryStream(bytes))
{
using (MagickImage image = new MagickImage(stream))
{
image.Format = MagickFormat.Ico;
image.Write(filePath + fileName + ".ico");
}
}
await MessageBox.ShowAsync("生成成功");
//icon.Dispose();
bitmap.Dispose();
sbitmap.Dispose();
}
/// <summary>
/// 图片缩放
/// </summary>
/// <param name="bmp"></param>
/// <param name="newW"></param>
/// <param name="newH"></param>
/// <returns></returns>
public static SKBitmap ResizeImage(SKBitmap bmp, int newW, int newH)
{
try
{
SKBitmap b = new SKBitmap(newW, newH, SKColorType.Argb4444, SKAlphaType.Opaque);
SKCanvas g = new SKCanvas(b);
g.DrawBitmap(bmp, new SKRect(0, 0, newW, newH));
g.Dispose();
return b;
}
catch
{
return null;
}
}
}
}

View File

@@ -0,0 +1,25 @@
using System;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using .Base;
namespace .ViewModel._03图片相关
{
public class ViewModel : ViewModelBase
{
public Bitmap ImageSource { get; set; } = null;
public DelegateCommand ButtonCmd { get; set; }
public ViewModel()
{
ButtonCmd = new DelegateCommand(ButtonCmdFunc);
}
private void ButtonCmdFunc(object obj)
{
string fileName = obj.ToString();
// 获取Pack URI
string packUri = $"avares://常用工具集/Assets/ColorBag/{fileName}.gif";
ImageSource = new Bitmap(AssetLoader.Open(new Uri(packUri)));
}
}
}

View File

@@ -0,0 +1,108 @@
using Avalonia;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Platform;
using MES.Utility.Core;
using Microsoft.Win32;
using System;
using System.IO;
using Ursa.Controls;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class AdobeAcrobatXI破解ViewModel : ViewModelBase
{
public string FilePath { get; set; } = "";
public DelegateCommand FindPathCmd { get; set; }
public DelegateCommand CrackCmd { get; set; }
public AdobeAcrobatXI破解ViewModel()
{
FindPathCmd = new DelegateCommand(FindPathCmdFunc);
CrackCmd = new DelegateCommand(CrackCmdFunc);
}
private void FindPathCmdFunc(object obj)
{
RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("Software");
registryKey = registryKey.OpenSubKey("Adobe");
if (registryKey == null)
{
MessageBox.ShowAsync("当前计算机未安装Adobe Acrobat XI");
return;
}
registryKey = registryKey.OpenSubKey("Adobe Acrobat");
if (registryKey == null)
{
MessageBox.ShowAsync("当前计算机未安装Adobe Acrobat XI");
return;
}
registryKey = registryKey.OpenSubKey("11.0");
if (registryKey == null)
{
MessageBox.ShowAsync("当前计算机未安装Adobe Acrobat XI");
return;
}
registryKey = registryKey.OpenSubKey("InstallPath");
if (registryKey == null)
{
MessageBox.ShowAsync("获得路径失败,请手动输入路径");
return;
}
string path = registryKey.GetValue("").ToString();
FilePath = path;
}
private void CrackCmdFunc(object obj)
{
try
{
string path = FilePath;
if (path.IsNullOrEmpty())
{
MessageBox.ShowAsync("请查找或者输入Adobe Acrobat XI安装目录");
return;
}
if (!Directory.Exists(path))
{
MessageBox.ShowAsync("文件夹不存在,破解失败");
return;
}
path = path.Replace("\\", "/");
if (!path.EndsWith("/"))
path += "/";
path += "amtlib.dll";
byte[] bytes = null;
// 获取Pack URI
string packUri = "avares://常用工具集/Assets/AcrobatXI/amtlib.dll";
// 使用Pack URI打开文件并读取内容
if (!File.Exists(path))
{
MessageBox.ShowAsync("amtlib.dll文件不存在请手动输入路径");
return;
}
using (Stream stream = AssetLoader.Open(new Uri(packUri)))
{
bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
}
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(bytes);
}
}
MessageBox.ShowAsync("破解完成");
}
catch (Exception ex)
{
MessageBox.ShowAsync("破解失败:" + ex.Message);
}
}
}
}

View File

@@ -0,0 +1,92 @@
using Microsoft.Win32.TaskScheduler;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Ursa.Controls;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class MySQL定时备份ViewModel : ViewModelBase
{
public string FilePath { get; set; } = "";
public string UserName { get; set; } = "root";
public string Password { get; set; } = "root";
public string DatabaseName { get; set; } = "test";
public TimeSpan SelectedTime { get; set; } = TimeSpan.Zero;
public string BackPath { get; set; } = "d:/test.sql";
public DelegateCommand FindPathCmd { get; set; }
public DelegateCommand CreateBackPlanCmd { get; set; }
public MySQL定时备份ViewModel()
{
FindPathCmd = new DelegateCommand(FindPathCmdFunc);
CreateBackPlanCmd = new DelegateCommand(CreateBackPlanCmdFunc);
}
private void FindPathCmdFunc(object obj)
{
try
{
Process process = Process.GetProcesses().Where(it => it.ProcessName.ToLower().Contains("mysql")).FirstOrDefault();
if (process == null)
{
MessageBox.ShowAsync("找不到MySQL安装路径");
return;
}
string path = process.MainModule.FileName;
path = Directory.GetParent(path).FullName;
FilePath = path;
}
catch
{
MessageBox.ShowAsync("找不到MySQL安装路径");
}
}
private void CreateBackPlanCmdFunc(object obj)
{
string binPath = FilePath.Replace("\\", "/");
if (string.IsNullOrEmpty(binPath))
{
MessageBox.ShowAsync("请输入mysqldump所在目录");
return;
}
if (!binPath.EndsWith("/"))
{
binPath = binPath + "/";
}
if (!Directory.Exists(binPath))
{
MessageBox.ShowAsync("mysqldump所在目录不存在");
return;
}
string userName = UserName;
string password = Password;
string dbName = DatabaseName;
string backupFile = BackPath;
string cmd = $"mysqldump -u {userName} -p{password} {dbName} > {backupFile}";
string batPath = $"{dbName}_back.bat";
File.WriteAllText(binPath + batPath, cmd);
using (TaskService ts = new TaskService())
{
// 创建新的任务定义并指定任务的名称
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "MySQL定时备份";
// 创建触发器,设置为每天的特定时间
DailyTrigger dailyTrigger = new DailyTrigger();
dailyTrigger.StartBoundary = DateTime.Today.Add(SelectedTime); //指定时间
td.Triggers.Add(dailyTrigger);
// 创建操作 - 运行一个程序
td.Actions.Add(new ExecAction(batPath, "", binPath));
// 注册任务到根文件夹下
ts.RootFolder.RegisterTaskDefinition("MySQLBackup", td);
}
GlobalValues.Success("已创建备份计划");
}
}
}

View File

@@ -0,0 +1,176 @@
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using Ursa.Controls;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
private SerialHelper helper;
public bool Enabled { get; set; } = true;
public string ButtonText { get; set; } = "打开";
public DelegateCommand ButtonCmd { get; set; }
//串口号下拉列表数据
public List<string> SerialList { get; set; }
public int SerialIndex { get; set; } = 0;
/// <summary>
/// 波特率
/// </summary>
public List<int> BaudRateList { get; set; }
public int BaudRateIndex { get; set; } = 0;
//校验
public List<string> ParityList { get; set; }
public int ParityIndex { get; set; } = 0;
//数据为
public List<int> DataBitList { get; set; }
public int DataBitIndex { get; set; } = 0;
//停止位
public List<string> StopBitList { get; set; }
public int StopBitIndex { get; set; } = 0;
public int Timeout { get; set; } = 1000;
public ViewModel()
{
//串口号
string[] portNames = SerialPort.GetPortNames();
if (portNames != null && portNames.Length > 0)
{
SerialList = portNames.ToList();
}
//波特率
BaudRateList = new List<int>() { 110, 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 56000, 57600, 115200, 128000 };
BaudRateIndex = 6;
//校验
ParityList = new List<string> { "None", "Odd", "Even", "Mark", "Space" };
ParityIndex = 0;
//数据位
DataBitList = new List<int> { 5, 6, 7, 8 };
DataBitIndex = 3;
//停止位
StopBitList = new List<string> { "None", "One", "Two", "OnePointFive" };
StopBitIndex = 1;
ButtonCmd = new DelegateCommand(ButtonCmdFunc);
}
private void ButtonCmdFunc(object obj)
{
if (ButtonText == "打开")
{
try
{
helper = new SerialHelper(
SerialList[SerialIndex],
BaudRateList[BaudRateIndex],
DataBitList[DataBitIndex],
(StopBits)StopBitIndex,
(Parity)ParityIndex,
Timeout
);
helper.Open();
}
catch
{
MessageBox.ShowAsync("串口打开失败");
return;
}
Enabled = false;
ButtonText = "关闭";
GlobalValues.MainWindow.WindowState = Avalonia.Controls.WindowState.Minimized;
}
else
{
helper.Close();
helper = null;
Enabled = true;
ButtonText = "打开";
}
}
public class SerialHelper
{
[DllImport("user32")]
static extern void keybd_event(byte bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
const uint KEYEVENTF_EXTENDEDKEY = 0x1;
const uint KEYEVENTF_KEYUP = 0x2;
private SerialPort serialPort;
public SerialHelper(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity, int timeout)
{
serialPort = new SerialPort();
serialPort.PortName = portName;
serialPort.BaudRate = baudRate;
serialPort.DataBits = dataBits;
serialPort.StopBits = stopBits;
serialPort.Parity = parity;
serialPort.ReadTimeout = timeout;
serialPort.DataReceived += SerialPort1_DataReceived;
}
/// <summary>
/// 打开串口
/// </summary>
public void Open()
{
if (serialPort.IsOpen)
return;
serialPort.Open();
}
/// <summary>
/// 关闭串口
/// </summary>
public void Close()
{
if (!serialPort.IsOpen)
return;
serialPort.Close();
}
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int n = serialPort.BytesToRead;
byte[] buf = new byte[n];
serialPort.Read(buf, 0, n);
foreach (byte b in buf)
{
if (b >= '0' && b <= '9')
{
keybd_event(b, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event(b, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
else if (b >= 'a' && b <= 'z')
{
keybd_event((byte)(b - 32), 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event((byte)(b - 32), 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
else if (b >= 'A' && b <= 'Z')
{
keybd_event(16, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);//按下Shift键
keybd_event(b, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event(b, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
keybd_event(16, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);//松开Shift键
}
else if (b == 0x0D || b == 0x0A)
{
keybd_event(0x0D, 0x45, KEYEVENTF_EXTENDEDKEY | 0, 0);
keybd_event(0x0D, 0x45, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0);
}
}
}
}
}
}

View File

@@ -0,0 +1,78 @@
using Base.Utility;
using Microsoft.Win32;
using System.Collections.Generic;
using System.Linq;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class WPS图标ViewModel : ViewModelBase
{
private string name1 = "{7AE6DE87-C956-4B40-9C89-3D166C9841D3}";
private string name2 = "{5FCD4425-CA3A-48F4-A57C-B8A75C32ACB1}";
private string name3 = "{19ADA707-057F-45EF-8985-305FEE233FAB}";
public DelegateCommand ClearCmd { get; set; }
public WPS图标ViewModel()
{
ClearCmd = new DelegateCommand(ClearCmdFunc);
}
private void ClearCmdFunc(object obj)
{
Delete(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace\", name2);
Delete(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\", name1);
Delete(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\", name2);
Delete(@"SOFTWARE\Classes\CLSID", name1);
Delete(@"SOFTWARE\Classes\CLSID", name2);
Delete(@"SOFTWARE\Classes\SOFTWARE\Classes\CLSID", name1);
Delete(@"SOFTWARE\Classes\SOFTWARE\Classes\CLSID", name2);
Delete(@"SOFTWARE\Classes\SOFTWARE\Classes\Wow6432Node\CLSID", name3);
Delete(@"SOFTWARE\Classes\SOFTWARE\Classes\Wow6432Node\CLSID", name2);
Delete(@"SOFTWARE\Classes\SOFTWARE\Classes\Wow6432Node\CLSID", name1);
Delete(@"SOFTWARE\Classes\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace", name1);
Delete(@"SOFTWARE\Classes\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace", name2);
Delete(@"SOFTWARE\Classes\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace", name1);
Delete(@"SOFTWARE\Classes\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\MyComputer\NameSpace", name2);
DeleteKey(@"SOFTWARE\Classes\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name1);
DeleteKey(@"SOFTWARE\Classes\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name2);
DeleteKey(@"SOFTWARE\Classes\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name1);
DeleteKey(@"SOFTWARE\Classes\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name2);
DeleteKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name1);
DeleteKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name2);
DeleteKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name1);
DeleteKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Shell Extensions\Approved", name2);
Delete(@"SOFTWARE\Classes\WOW6432Node\CLSID", name3);
Delete(@"SOFTWARE\Classes\WOW6432Node\CLSID", name2);
Delete(@"SOFTWARE\Classes\WOW6432Node\CLSID", name1);
Delete(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace", name1);
//重新打开桌面
DesktopRefurbish.DeskRef();
}
private void DeleteKey(string path, string name1)
{
try
{
RegistryKey user = Registry.CurrentUser;
RegistryKey key = user.OpenSubKey(path, true);
key.DeleteValue(name1);
}
catch { }
}
private void Delete(string path, string name1)
{
try
{
RegistryKey user = Registry.CurrentUser;
RegistryKey key = user.OpenSubKey(path, true);
List<string> names = key.GetSubKeyNames().ToList();
if (names.Contains(name1))
{
key.DeleteSubKey(name1);
}
}
catch { }
}
}
}

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
public DelegateCommand ClearCmd { get; set; }
public ViewModel()
{
ClearCmd = new DelegateCommand(ClearCmdFunc);
}
public void ClearCmdFunc(object obj)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("rem 关闭Windows外壳程序explorer");
sb.AppendLine("taskkill /f /im explorer.exe");
sb.AppendLine("rem 清理系统图标缓存数据库");
sb.AppendLine("attrib -h -s -r \"%userprofile%\\AppData\\Local\\IconCache.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\IconCache.db\"");
sb.AppendLine("attrib /s /d -h -s -r \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\*\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_32.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_96.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_102.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_256.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_1024.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_idx.db\"");
sb.AppendLine("del /f \"%userprofile%\\AppData\\Local\\Microsoft\\Windows\\Explorer\\thumbcache_sr.db\"");
sb.AppendLine("rem 清理 系统托盘记忆的图标");
sb.AppendLine("echo y|reg delete \"HKEY_CLASSES_ROOT\\Local Settings\\Software\\Microsoft\\Windows\\CurrentVersion\\TrayNotify\" /v IconStreams");
sb.AppendLine("echo y|reg delete \"HKEY_CLASSES_ROOT\\Local Settings\\Software\\Microsoft\\Windows\\CurrentVersion\\TrayNotify\" /v PastIconsStream");
sb.AppendLine("rem 重启Windows外壳程序explorer");
sb.AppendLine("start explorer");
string tempPath = Path.GetTempFileName();
tempPath += ".bat";
try
{
File.WriteAllText(tempPath, sb.ToString(), Encoding.GetEncoding("GB2312"));
}
catch
{
File.WriteAllText(tempPath, sb.ToString(), Encoding.UTF8);
}
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = tempPath,
UseShellExecute = true, //不使用操作系统外壳程序启动
CreateNoWindow = true
};
using (Process process = Process.Start(startInfo))
{
process.WaitForExit(); // 等待批处理执行完成
File.Delete(tempPath);
}
}
}
}

View File

@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
public DelegateCommand ButtonCmd { get; set; }
public ViewModel()
{
ButtonCmd = new DelegateCommand(ButtonCmdFunc);
}
private void ButtonCmdFunc(object obj)
{
var p = new Process();
p.StartInfo = new ProcessStartInfo(@"ncpa.cpl")
{
UseShellExecute = true
};
p.Start();
}
}
}

View File

@@ -0,0 +1,133 @@
using CZGL.SystemInfo;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
public string OSArchitecture { get; set; } = "";
public string OSPlatformID { get; set; } = "";
public string OSVersion { get; set; } = "";
public string OSDescription { get; set; } = "";
public string ProcessArchitecture { get; set; } = "";
public string ProcessorCount { get; set; } = "";
public string MachineName { get; set; } = "";
public string FrameworkVersion { get; set; } = "";
public string FrameworkDescription { get; set; } = "";
public string CPURate { get; set; } = "";
public string MemoryRate { get; set; } = "";
public string UploadSpeed { get; set; } = "";
public string DownloadSpeed { get; set; } = "";
public ObservableCollection<MyDisk> DataList { get; set; }
public ViewModel()
{
DataList = new ObservableCollection<MyDisk>();
DiskInfo[] diskInfo = DiskInfo.GetDisks();
foreach (DiskInfo info in diskInfo)
{
MyDisk myDisk = new MyDisk();
myDisk.Name = info.Name;
myDisk.SetValue(info.TotalSize, info.UsedSize, info.FreeSpace);
DataList.Add(myDisk);
}
OSArchitecture = SystemPlatformInfo.OSArchitecture;
OSPlatformID = SystemPlatformInfo.OSPlatformID;
OSVersion = SystemPlatformInfo.OSVersion;
OSDescription = SystemPlatformInfo.OSDescription;
ProcessArchitecture = SystemPlatformInfo.ProcessArchitecture;
ProcessorCount = SystemPlatformInfo.ProcessorCount.ToString();
MachineName = SystemPlatformInfo.MachineName;
FrameworkVersion = SystemPlatformInfo.FrameworkVersion;
FrameworkDescription = SystemPlatformInfo.FrameworkDescription;
new Thread(() =>
{
CPUTime v1 = CPUHelper.GetCPUTime();
var network = NetworkInfo.TryGetRealNetworkInfo();
var oldRate = network.GetIpv4Speed();
while (true)
{
try
{
Thread.Sleep(1000);
var v2 = CPUHelper.GetCPUTime();
var value = CPUHelper.CalculateCPULoad(v1, v2);
v1 = v2;
var memory = MemoryHelper.GetMemoryValue();
var newRate = network.GetIpv4Speed();
var speed = NetworkInfo.GetSpeed(oldRate, newRate);
oldRate = newRate;
CPURate = $"{(int)(value * 100)} %";
MemoryRate = $"{memory.UsedPercentage}%";
UploadSpeed = $"{speed.Sent.Size} {speed.Sent.SizeType}/S";
DownloadSpeed = $"{speed.Received.Size} {speed.Received.SizeType}/S";
DiskInfo[] diskInfos = DiskInfo.GetDisks();
foreach (DiskInfo info1 in diskInfos)
{
MyDisk disk = DataList.Where(it => it.Name == info1.Name).FirstOrDefault();
if (disk != null)
{
disk.SetValue(info1.TotalSize, info1.UsedSize, info1.FreeSpace);
}
}
}
catch
{
Thread.Sleep(10);
}
}
}).Start();
}
}
public class MyDisk : ViewModelBase
{
public void SetValue(long total, long used, long free)
{
Total = GetLength(total);
Used = GetLength(used);
Free = GetLength(free);
}
public string Name { get; set; }
public string Total { get; set; }
public string Used { get; set; }
public string Free { get; set; }
private string GetLength(long bytes)
{
double tb = Math.Pow(1024.0, 4);
if (bytes > tb)
{
return $"{((int)((bytes / tb) * 100)) / 100.0f}TB";
}
double gb = Math.Pow(1024.0, 3);
if (bytes > gb)
{
return $"{((int)((bytes / gb) * 100)) / 100.0f}GB";
}
double mb = Math.Pow(1024.0, 2);
if (bytes > mb)
{
return $"{((int)((bytes / mb) * 100)) / 100.0f}MB";
}
else if (bytes > 1024)
{
return $"{((int)((bytes / 1024.0f) * 100)) / 100.0f}KB";
}
else
{
return $"{bytes}Byte";
}
}
}
}

View File

@@ -0,0 +1,105 @@
using Avalonia.Platform;
using Base.Utility;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
public DelegateCommand Button1Cmd { get; set; }
public DelegateCommand Button2Cmd { get; set; }
public ViewModel()
{
Button1Cmd = new DelegateCommand(Button1CmdFunc);
Button2Cmd = new DelegateCommand(Button2CmdFunc);
}
/// <summary>
/// 编程猫猫回收站
/// </summary>
/// <param name="obj"></param>
private void Button1CmdFunc(object obj)
{
RegistryKey user = Registry.CurrentUser;
RegistryKey CLSID = user.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\CLSID\\");
RegistryKey icon = CLSID.OpenSubKey("{645FF040-5081-101B-9F08-00AA002F954E}", true);
RegistryKey defaultIcon = icon.CreateSubKey("DefaultIcon");
//把dll复制到c:/System目录下
byte[] fullDllBytes = null;
// 获取Pack URI
string packUri = "avares://常用工具集/Assets/Cat/full.dll";
// 使用Pack URI打开文件并读取内容
using (Stream stream = AssetLoader.Open(new Uri(packUri)))
{
fullDllBytes = new byte[stream.Length];
stream.Read(fullDllBytes, 0, fullDllBytes.Length);
}
byte[] emptyDllBytes = null;
// 获取Pack URI
string packUri2 = "avares://常用工具集/Assets/Cat/empty.dll";
// 使用Pack URI打开文件并读取内容
using (Stream stream = AssetLoader.Open(new Uri(packUri2)))
{
emptyDllBytes = new byte[stream.Length];
stream.Read(emptyDllBytes, 0, emptyDllBytes.Length);
}
string path = Environment.GetEnvironmentVariable("USERPROFILE");
string appData = path + "\\AppData";
DirectoryInfo directoryInfo = new DirectoryInfo(appData);
if (!directoryInfo.Exists)
directoryInfo.Create();
string myDir = appData + "\\catIco";
DirectoryInfo directoryInfo2 = new DirectoryInfo(myDir);
if (!directoryInfo2.Exists)
directoryInfo2.Create();
string fullDllPath = myDir + "\\full.dll";
string emptyDllPath = myDir + "\\empty.dll";
if (File.Exists(fullDllPath))
File.Delete(fullDllPath);
if (File.Exists(emptyDllPath))
File.Delete(emptyDllPath);
using (FileStream stream = new FileStream(fullDllPath, FileMode.Create))
stream.Write(fullDllBytes, 0, fullDllBytes.Length);
using (FileStream stream = new FileStream(emptyDllPath, FileMode.Create))
stream.Write(emptyDllBytes, 0, emptyDllBytes.Length);
defaultIcon.SetValue("", @"%USERPROFILE%\AppData\catIco\empty.dll,0", RegistryValueKind.ExpandString);
defaultIcon.SetValue("Full", @"%USERPROFILE%\AppData\catIco\full.dll,0", RegistryValueKind.ExpandString);
defaultIcon.SetValue("Empty", @"%USERPROFILE%\AppData\catIco\empty.dll,0", RegistryValueKind.ExpandString);
//重新打开桌面
DesktopRefurbish.DeskRef();
}
/// <summary>
/// 还原
/// </summary>
/// <param name="obj"></param>
private void Button2CmdFunc(object obj)
{
RegistryKey user = Registry.CurrentUser;
RegistryKey CLSID = user.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\CLSID\\");
RegistryKey icon = CLSID.OpenSubKey("{645FF040-5081-101B-9F08-00AA002F954E}", true);
RegistryKey defaultIcon = icon.CreateSubKey("DefaultIcon");
defaultIcon.SetValue("", @"%SystemRoot%\System32\imageres.dll,-55", RegistryValueKind.ExpandString);
defaultIcon.SetValue("Full", @"%SystemRoot%\System32\imageres.dll,-54", RegistryValueKind.ExpandString);
defaultIcon.SetValue("Empty", @"%SystemRoot%\System32\imageres.dll,-55", RegistryValueKind.ExpandString);
//重新打开桌面
DesktopRefurbish.DeskRef();
}
}
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Diagnostics;
using System.IO;
using Ursa.Controls;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase
{
public string RemotePath { get; set; } = "\\\\10.150.0.250\\运维软件";
public string LocalPath { get; set; } = "d:\\运维软件";
public DelegateCommand MakeLinkCmd { get; set; }
public ViewModel()
{
MakeLinkCmd = new DelegateCommand(MakeLinkCmdFunc);
}
private void MakeLinkCmdFunc(object obj)
{
if (string.IsNullOrEmpty(LocalPath) || string.IsNullOrEmpty(RemotePath))
{
MessageBox.ShowAsync("请输入路径");
return;
}
string remotePath = RemotePath;
string localPath = LocalPath.Replace("/", "\\");
bool flag = CreateSymbolicLink(remotePath, localPath);
if (flag)
{
GlobalValues.Success("创建成功");
}
else
{
GlobalValues.Error("创建失败");
}
}
private bool CreateSymbolicLink(string remotePath, string localPath)
{
try
{
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true
};
process.StartInfo = startInfo;
process.Start();
process.StandardInput.WriteLine($"mklink /d {localPath} {remotePath}");
process.StandardInput.AutoFlush = true;
process.StandardInput.WriteLine("exit");
StreamReader reader = process.StandardOutput;
string ret = "";
while (true)
{
string curLine = reader.ReadLine();
ret = ret + curLine + "\r\n";
Console.WriteLine(curLine);
if (reader.EndOfStream)
{
break;
}
}
reader.Close();
process.Close();
if (ret.Contains("<<===>>"))
return true;
return false;
}
catch
{
return false;
}
}
}
}

View File

@@ -0,0 +1,893 @@
using Avalonia.Controls;
using MES.Utility.EventBus;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using Weiz.EventBus.Core;
using .Base;
namespace .ViewModel._04破解及系统相关
{
public class ViewModel : ViewModelBase, IEventHandler<KeyBordHookEvent>
{
public string ButtonText { get; set; } = "开启键盘钩子";
public string Message { get; set; } = "";
public DelegateCommand StartStopCmd { get; set; }
public DelegateCommand CleanCmd { get; set; }
public DelegateCommand PageLoaedCommand { get; set; }
public ViewModel()
{
EventBus.Instance.Subscribe<KeyBordHookEvent>(this);
PageLoaedCommand = new DelegateCommand(PageLoaded);
StartStopCmd = new DelegateCommand(StartStopCmdFunc);
CleanCmd = new DelegateCommand(CleanCmdFunc);
}
private void PageLoaded(object obj)
{
}
private void StartStopCmdFunc(object obj)
{
if (ButtonText == "开启键盘钩子")
{
KeyboardHook.Start();
ButtonText = "停止键盘钩子";
GlobalValues.MainWindow.WindowState = WindowState.Minimized;
}
else
{
KeyboardHook.Stop();
ButtonText = "开启键盘钩子";
}
}
private void CleanCmdFunc(object obj)
{
Message = "";
}
public void Handle(KeyBordHookEvent evt)
{
Message += evt.Message;
}
}
public class KeyboardHook
{
private const int WH_KEYBOARD_LL = 13;
private static LowLevelKeyboardProc _proc = HookCallback;
private static IntPtr _hookID = IntPtr.Zero;
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr GetModuleHandle(string lpModuleName);
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
public static void Start()
{
_hookID = SetWindowsHookEx(WH_KEYBOARD_LL, _proc, GetModuleHandle(null), 0);
if (_hookID == IntPtr.Zero)
{
throw new Exception("Could not set keyboard hook");
}
}
public static void Stop()
{
bool ret = UnhookWindowsHookEx(_hookID);
if (!ret)
{
throw new Exception("Could not unset keyboard hook");
}
_hookID = IntPtr.Zero;
}
private static IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode >= 0 && wParam == (IntPtr)0x100)
{
int vkCode = Marshal.ReadInt32(lParam);
Console.WriteLine((Keys)vkCode);
EventBus.Instance.Publish(new KeyBordHookEvent(((Keys)vkCode).ToString()));
}
return CallNextHookEx(_hookID, nCode, wParam, lParam);
}
}
public enum Keys
{
//
// 摘要:
// The bitmask to extract modifiers from a key value.
Modifiers = -65536,
//
// 摘要:
// No key pressed.
None = 0,
//
// 摘要:
// The left mouse button.
LButton = 1,
//
// 摘要:
// The right mouse button.
RButton = 2,
//
// 摘要:
// The CANCEL key.
Cancel = 3,
//
// 摘要:
// The middle mouse button (three-button mouse).
MButton = 4,
//
// 摘要:
// The first x mouse button (five-button mouse).
XButton1 = 5,
//
// 摘要:
// The second x mouse button (five-button mouse).
XButton2 = 6,
//
// 摘要:
// The BACKSPACE key.
Back = 8,
//
// 摘要:
// The TAB key.
Tab = 9,
//
// 摘要:
// The LINEFEED key.
LineFeed = 10,
//
// 摘要:
// The CLEAR key.
Clear = 12,
//
// 摘要:
// The RETURN key.
Return = 13,
//
// 摘要:
// The ENTER key.
Enter = 13,
//
// 摘要:
// The SHIFT key.
ShiftKey = 16,
//
// 摘要:
// The CTRL key.
ControlKey = 17,
//
// 摘要:
// The ALT key.
Menu = 18,
//
// 摘要:
// The PAUSE key.
Pause = 19,
//
// 摘要:
// The CAPS LOCK key.
Capital = 20,
//
// 摘要:
// The CAPS LOCK key.
CapsLock = 20,
//
// 摘要:
// The IME Kana mode key.
KanaMode = 21,
//
// 摘要:
// The IME Hanguel mode key. (maintained for compatibility; use HangulMode)
HanguelMode = 21,
//
// 摘要:
// The IME Hangul mode key.
HangulMode = 21,
//
// 摘要:
// The IME Junja mode key.
JunjaMode = 23,
//
// 摘要:
// The IME final mode key.
FinalMode = 24,
//
// 摘要:
// The IME Hanja mode key.
HanjaMode = 25,
//
// 摘要:
// The IME Kanji mode key.
KanjiMode = 25,
//
// 摘要:
// The ESC key.
Escape = 27,
//
// 摘要:
// The IME convert key.
IMEConvert = 28,
//
// 摘要:
// The IME nonconvert key.
IMENonconvert = 29,
//
// 摘要:
// The IME accept key, replaces System.Windows.Forms.Keys.IMEAceept.
IMEAccept = 30,
//
// 摘要:
// The IME accept key. Obsolete, use System.Windows.Forms.Keys.IMEAccept instead.
IMEAceept = 30,
//
// 摘要:
// The IME mode change key.
IMEModeChange = 31,
//
// 摘要:
// The SPACEBAR key.
Space = 32,
//
// 摘要:
// The PAGE UP key.
Prior = 33,
//
// 摘要:
// The PAGE UP key.
PageUp = 33,
//
// 摘要:
// The PAGE DOWN key.
Next = 34,
//
// 摘要:
// The PAGE DOWN key.
PageDown = 34,
//
// 摘要:
// The END key.
End = 35,
//
// 摘要:
// The HOME key.
Home = 36,
//
// 摘要:
// The LEFT ARROW key.
Left = 37,
//
// 摘要:
// The UP ARROW key.
Up = 38,
//
// 摘要:
// The RIGHT ARROW key.
Right = 39,
//
// 摘要:
// The DOWN ARROW key.
Down = 40,
//
// 摘要:
// The SELECT key.
Select = 41,
//
// 摘要:
// The PRINT key.
Print = 42,
//
// 摘要:
// The EXECUTE key.
Execute = 43,
//
// 摘要:
// The PRINT SCREEN key.
Snapshot = 44,
//
// 摘要:
// The PRINT SCREEN key.
PrintScreen = 44,
//
// 摘要:
// The INS key.
Insert = 45,
//
// 摘要:
// The DEL key.
Delete = 46,
//
// 摘要:
// The HELP key.
Help = 47,
//
// 摘要:
// The 0 key.
D0 = 48,
//
// 摘要:
// The 1 key.
D1 = 49,
//
// 摘要:
// The 2 key.
D2 = 50,
//
// 摘要:
// The 3 key.
D3 = 51,
//
// 摘要:
// The 4 key.
D4 = 52,
//
// 摘要:
// The 5 key.
D5 = 53,
//
// 摘要:
// The 6 key.
D6 = 54,
//
// 摘要:
// The 7 key.
D7 = 55,
//
// 摘要:
// The 8 key.
D8 = 56,
//
// 摘要:
// The 9 key.
D9 = 57,
//
// 摘要:
// The A key.
A = 65,
//
// 摘要:
// The B key.
B = 66,
//
// 摘要:
// The C key.
C = 67,
//
// 摘要:
// The D key.
D = 68,
//
// 摘要:
// The E key.
E = 69,
//
// 摘要:
// The F key.
F = 70,
//
// 摘要:
// The G key.
G = 71,
//
// 摘要:
// The H key.
H = 72,
//
// 摘要:
// The I key.
I = 73,
//
// 摘要:
// The J key.
J = 74,
//
// 摘要:
// The K key.
K = 75,
//
// 摘要:
// The L key.
L = 76,
//
// 摘要:
// The M key.
M = 77,
//
// 摘要:
// The N key.
N = 78,
//
// 摘要:
// The O key.
O = 79,
//
// 摘要:
// The P key.
P = 80,
//
// 摘要:
// The Q key.
Q = 81,
//
// 摘要:
// The R key.
R = 82,
//
// 摘要:
// The S key.
S = 83,
//
// 摘要:
// The T key.
T = 84,
//
// 摘要:
// The U key.
U = 85,
//
// 摘要:
// The V key.
V = 86,
//
// 摘要:
// The W key.
W = 87,
//
// 摘要:
// The X key.
X = 88,
//
// 摘要:
// The Y key.
Y = 89,
//
// 摘要:
// The Z key.
Z = 90,
//
// 摘要:
// The left Windows logo key (Microsoft Natural Keyboard).
LWin = 91,
//
// 摘要:
// The right Windows logo key (Microsoft Natural Keyboard).
RWin = 92,
//
// 摘要:
// The application key (Microsoft Natural Keyboard).
Apps = 93,
//
// 摘要:
// The computer sleep key.
Sleep = 95,
//
// 摘要:
// The 0 key on the numeric keypad.
NumPad0 = 96,
//
// 摘要:
// The 1 key on the numeric keypad.
NumPad1 = 97,
//
// 摘要:
// The 2 key on the numeric keypad.
NumPad2 = 98,
//
// 摘要:
// The 3 key on the numeric keypad.
NumPad3 = 99,
//
// 摘要:
// The 4 key on the numeric keypad.
NumPad4 = 100,
//
// 摘要:
// The 5 key on the numeric keypad.
NumPad5 = 101,
//
// 摘要:
// The 6 key on the numeric keypad.
NumPad6 = 102,
//
// 摘要:
// The 7 key on the numeric keypad.
NumPad7 = 103,
//
// 摘要:
// The 8 key on the numeric keypad.
NumPad8 = 104,
//
// 摘要:
// The 9 key on the numeric keypad.
NumPad9 = 105,
//
// 摘要:
// The multiply key.
Multiply = 106,
//
// 摘要:
// The add key.
Add = 107,
//
// 摘要:
// The separator key.
Separator = 108,
//
// 摘要:
// The subtract key.
Subtract = 109,
//
// 摘要:
// The decimal key.
Decimal = 110,
//
// 摘要:
// The divide key.
Divide = 111,
//
// 摘要:
// The F1 key.
F1 = 112,
//
// 摘要:
// The F2 key.
F2 = 113,
//
// 摘要:
// The F3 key.
F3 = 114,
//
// 摘要:
// The F4 key.
F4 = 115,
//
// 摘要:
// The F5 key.
F5 = 116,
//
// 摘要:
// The F6 key.
F6 = 117,
//
// 摘要:
// The F7 key.
F7 = 118,
//
// 摘要:
// The F8 key.
F8 = 119,
//
// 摘要:
// The F9 key.
F9 = 120,
//
// 摘要:
// The F10 key.
F10 = 121,
//
// 摘要:
// The F11 key.
F11 = 122,
//
// 摘要:
// The F12 key.
F12 = 123,
//
// 摘要:
// The F13 key.
F13 = 124,
//
// 摘要:
// The F14 key.
F14 = 125,
//
// 摘要:
// The F15 key.
F15 = 126,
//
// 摘要:
// The F16 key.
F16 = 127,
//
// 摘要:
// The F17 key.
F17 = 128,
//
// 摘要:
// The F18 key.
F18 = 129,
//
// 摘要:
// The F19 key.
F19 = 130,
//
// 摘要:
// The F20 key.
F20 = 131,
//
// 摘要:
// The F21 key.
F21 = 132,
//
// 摘要:
// The F22 key.
F22 = 133,
//
// 摘要:
// The F23 key.
F23 = 134,
//
// 摘要:
// The F24 key.
F24 = 135,
//
// 摘要:
// The NUM LOCK key.
NumLock = 144,
//
// 摘要:
// The SCROLL LOCK key.
Scroll = 145,
//
// 摘要:
// The left SHIFT key.
LShiftKey = 160,
//
// 摘要:
// The right SHIFT key.
RShiftKey = 161,
//
// 摘要:
// The left CTRL key.
LControlKey = 162,
//
// 摘要:
// The right CTRL key.
RControlKey = 163,
//
// 摘要:
// The left ALT key.
LMenu = 164,
//
// 摘要:
// The right ALT key.
RMenu = 165,
//
// 摘要:
// The browser back key.
BrowserBack = 166,
//
// 摘要:
// The browser forward key.
BrowserForward = 167,
//
// 摘要:
// The browser refresh key.
BrowserRefresh = 168,
//
// 摘要:
// The browser stop key.
BrowserStop = 169,
//
// 摘要:
// The browser search key.
BrowserSearch = 170,
//
// 摘要:
// The browser favorites key.
BrowserFavorites = 171,
//
// 摘要:
// The browser home key.
BrowserHome = 172,
//
// 摘要:
// The volume mute key.
VolumeMute = 173,
//
// 摘要:
// The volume down key.
VolumeDown = 174,
//
// 摘要:
// The volume up key.
VolumeUp = 175,
//
// 摘要:
// The media next track key.
MediaNextTrack = 176,
//
// 摘要:
// The media previous track key.
MediaPreviousTrack = 177,
//
// 摘要:
// The media Stop key.
MediaStop = 178,
//
// 摘要:
// The media play pause key.
MediaPlayPause = 179,
//
// 摘要:
// The launch mail key.
LaunchMail = 180,
//
// 摘要:
// The select media key.
SelectMedia = 181,
//
// 摘要:
// The start application one key.
LaunchApplication1 = 182,
//
// 摘要:
// The start application two key.
LaunchApplication2 = 183,
//
// 摘要:
// The OEM Semicolon key on a US standard keyboard.
OemSemicolon = 186,
//
// 摘要:
// The OEM 1 key.
Oem1 = 186,
//
// 摘要:
// The OEM plus key on any country/region keyboard.
Oemplus = 187,
//
// 摘要:
// The OEM comma key on any country/region keyboard.
Oemcomma = 188,
//
// 摘要:
// The OEM minus key on any country/region keyboard.
OemMinus = 189,
//
// 摘要:
// The OEM period key on any country/region keyboard.
OemPeriod = 190,
//
// 摘要:
// The OEM question mark key on a US standard keyboard.
OemQuestion = 191,
//
// 摘要:
// The OEM 2 key.
Oem2 = 191,
//
// 摘要:
// The OEM tilde key on a US standard keyboard.
Oemtilde = 192,
//
// 摘要:
// The OEM 3 key.
Oem3 = 192,
//
// 摘要:
// The OEM open bracket key on a US standard keyboard.
OemOpenBrackets = 219,
//
// 摘要:
// The OEM 4 key.
Oem4 = 219,
//
// 摘要:
// The OEM pipe key on a US standard keyboard.
OemPipe = 220,
//
// 摘要:
// The OEM 5 key.
Oem5 = 220,
//
// 摘要:
// The OEM close bracket key on a US standard keyboard.
OemCloseBrackets = 221,
//
// 摘要:
// The OEM 6 key.
Oem6 = 221,
//
// 摘要:
// The OEM singled/double quote key on a US standard keyboard.
OemQuotes = 222,
//
// 摘要:
// The OEM 7 key.
Oem7 = 222,
//
// 摘要:
// The OEM 8 key.
Oem8 = 223,
//
// 摘要:
// The OEM angle bracket or backslash key on the RT 102 key keyboard.
OemBackslash = 226,
//
// 摘要:
// The OEM 102 key.
Oem102 = 226,
//
// 摘要:
// The PROCESS KEY key.
ProcessKey = 229,
//
// 摘要:
// Used to pass Unicode characters as if they were keystrokes. The Packet key value
// is the low word of a 32-bit virtual-key value used for non-keyboard input methods.
Packet = 231,
//
// 摘要:
// The ATTN key.
Attn = 246,
//
// 摘要:
// The CRSEL key.
Crsel = 247,
//
// 摘要:
// The EXSEL key.
Exsel = 248,
//
// 摘要:
// The ERASE EOF key.
EraseEof = 249,
//
// 摘要:
// The PLAY key.
Play = 250,
//
// 摘要:
// The ZOOM key.
Zoom = 251,
//
// 摘要:
// A constant reserved for future use.
NoName = 252,
//
// 摘要:
// The PA1 key.
Pa1 = 253,
//
// 摘要:
// The CLEAR key.
OemClear = 254,
//
// 摘要:
// The bitmask to extract a key code from a key value.
KeyCode = 65535,
//
// 摘要:
// The SHIFT modifier key.
Shift = 65536,
//
// 摘要:
// The CTRL modifier key.
Control = 131072,
//
// 摘要:
// The ALT modifier key.
Alt = 262144
}
}

View File

@@ -0,0 +1,84 @@
using CCS.Utility.Security;
using MES.Utility.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ursa.Controls;
using .Base;
namespace .ViewModel._05其他
{
public class MD5DESViewModel : ViewModelBase
{
public string DESKey { get; set; } = "";
public string DESSource { get; set; } = "";
public string DESDest { get; set; } = "";
public string MD5Source { get; set; } = "";
public string MD5Dest { get; set; } = "";
public DelegateCommand CalcMD5Cmd { get; set; }
public DelegateCommand DESEncryptCmd { get; set; }
public DelegateCommand DESDecryptCmd { get; set; }
public MD5DESViewModel()
{
CalcMD5Cmd = new DelegateCommand(CalcMD5CmdFunc);
DESEncryptCmd = new DelegateCommand(DESEncryptCmdFunc);
DESDecryptCmd = new DelegateCommand(DESDecryptCmdFunc);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="obj"></param>
private void DESDecryptCmdFunc(object obj)
{
try
{
if (DESKey.IsNullOrEmpty())
{
DESDest = DESHelper.DESDecrypt(DESSource);
}
else
{
DESDest = DESHelper.DESDecrypt(DESSource, DESKey);
}
}
catch (Exception ex)
{
DESDest = ex.Message;
}
}
private void DESEncryptCmdFunc(object obj)
{
try
{
if (DESKey.IsNullOrEmpty())
{
DESDest = DESHelper.DESEncrypt(DESSource);
}
else
{
DESDest = DESHelper.DESEncrypt(DESSource, DESKey);
}
}
catch (Exception ex)
{
DESDest = ex.Message;
}
}
private void CalcMD5CmdFunc(object obj)
{
if (MD5Source.IsNullOrEmpty())
{
MessageBox.ShowAsync("请输入内容");
return;
}
MD5Dest = MD5Source.MD5Encrypt();
}
}
}

View File

@@ -0,0 +1,606 @@
using MES.Utility.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using .Base;
using NHibernate.AdoNet.Util;
using System.Xml;
using System.IO;
namespace .ViewModel._05其他
{
public class SQLStringBuilder封装ViewModel : ViewModelBase
{
public string Button1Text { get; set; } = "生成";
public string TextBox1 { get; set; } = "";
public string TextBox2 { get; set; } = "";
public string TextBox3 { get; set; } = "strSql";
public string Text3Title { get; set; } = "StringBuilder参数:";
public bool TextBox3Visiable { get; set; } = true;
public List<string> FuncList { get; set; }
public int funcIndex = 0;
public int FuncIndex
{
get
{
return funcIndex;
}
set
{
funcIndex = value;
SelectChanged();
NotifyPropertyChanged();
}
}
public bool RadioButton1 { get; set; } = true;
public bool RadioButton2 { get; set; } = false;
public bool RadioButton3 { get; set; } = false;
public string RadioButton1Text { get; set; } = "Java";
public string RadioButton2Text { get; set; } = "C#";
public string RadioButton3Text { get; set; } = "JS";
public bool RadioButton1Visiable { get; set; } = true;
public bool RadioButton2Visiable { get; set; } = true;
public bool RadioButton3Visiable { get; set; } = true;
public bool CheckBox1 { get; set; } = false;
public bool CheckBox3 { get; set; } = true;
public bool CheckBox2 { get; set; } = true;
public bool CheckBox1Visiable { get; set; } = true;
public bool CheckBox3Visiable { get; set; } = true;
public bool CheckBox2Visiable { get; set; } = true;
public DelegateCommand GenerateCmd { get; set; }
public DelegateCommand ClearCmd { get; set; }
public SQLStringBuilder封装ViewModel()
{
FuncList = new List<string>() {
"SQL转StringBuilder",
"XML格式化",
"SQL格式化",
"StringBuilder转SQL",
"大小写转换",
"JSON格式化"
};
FuncIndex = 0;
GenerateCmd = new DelegateCommand(GenerateCmdFunc);
ClearCmd = new DelegateCommand(ClearCmdFunc);
}
private void GenerateCmdFunc(object obj)
{
//SQL转StringBuilder
if (FuncIndex == 0)
{
if (CheckBox1)
{
string text2 = FormatStyle.Basic.Formatter.Format(TextBox1);
TextBox1 = text2;
}
List<string> first = GetFirstContext();
List<string> second = new List<string>();
if (first.Count == 0)
{
TextBox2 = string.Empty;
return;
}
int maxLength = GetMaxLength(GetNewList(first));
if (RadioButton3)
{
second.Add("var " + GetParmName() + " = \"\";");
}
else
{
second.Add("StringBuilder " + GetParmName() + " = new StringBuilder();");
}
//循环处理每一行
foreach (string str in first)
{
if (!CheckBox3)
{
if (str.Trim().StartsWith("--"))
{
second.Add(str.Trim().Replace("--", "//"));
continue;
}
if (str.Contains("--"))
{
//分割
int index = str.IndexOf("--");
string str1 = str.Substring(0, index).TrimEnd();
string str2 = str.Substring(index, str.Length - index).Trim();
if (!CheckBox2)
{
second.Add(GetString2(str1, 0, CheckBox3) + " " + str2.Replace("--", "//"));
}
else
{
string retStr = GetString(str1, maxLength - System.Text.Encoding.Default.GetByteCount(str1), CheckBox3) + " " + str2.Replace("--", "//");
second.Add(retStr);
}
continue;
}
}
if (!CheckBox2)
{
second.Add(GetString2(str, 0, CheckBox3));
}
else
{
second.Add(GetString(str, maxLength - System.Text.Encoding.Default.GetByteCount(str), CheckBox3));
}
}
TextBox2 = second.GetStrArray("\r\n");
}
//XML格式化
else if (FuncIndex == 1)
{
if (TextBox1.IsNullOrEmpty())
{
TextBox2 = string.Empty;
return;
}
TextBox2 = FormatXml(TextBox1);
}
//SQL格式化
else if (FuncIndex == 2)
{
if (TextBox1.IsNullOrEmpty())
{
TextBox2 = string.Empty;
return;
}
TextBox2 = FormatStyle.Basic.Formatter.Format(TextBox1);
}
//StringBuilder转SQL
else if (FuncIndex == 3)
{
List<string> first = GetFirstContext();
List<string> second = new List<string>();
if (first.Count == 0)
{
return;
}
//判断是否每一行是否以StringBuilder开头
string parmName = GetStringBuilderParmName(first[0]);
if (parmName.IsNullOrEmpty())
{
return;
}
for (int i = 1; i < first.Count; i++)
{
string str = first[i];
string handlerStr = HandlerString(str, parmName);
if (!String.Empty.Equals(handlerStr))
{
second.Add(handlerStr);
}
}
if (second.Count != 0)
{
int spaceNum = second[0].IndexOf(second[0].Trim());
for (int i = 0; i < second.Count; i++)
{
second[i] = QuSpace(second[i], spaceNum);
}
}
TextBox2 = second.GetStrArray("\r\n");
}
//大小写转换
else if (FuncIndex == 4)
{
if (TextBox1.IsNullOrEmpty())
{
TextBox2 = string.Empty;
return;
}
List<string> first = GetFirstContext();
List<string> second = new List<string>();
if (RadioButton1)
{
foreach (string str in first)
{
second.Add(str.ToUpper());
}
}
else if (RadioButton2)
{
foreach (string str in first)
{
second.Add(str.ToLower());
}
}
TextBox2 = second.GetStrArray("\r\n");
}
//JSON格式化
else if (FuncIndex == 5)
{
if (TextBox1.IsNullOrEmpty())
{
TextBox2 = string.Empty;
return;
}
TextBox2 = TextBox1.FormatJson();
}
}
private void ClearCmdFunc(object obj)
{
TextBox1 = string.Empty;
TextBox2 = string.Empty;
}
private void SelectChanged()
{
//SQL转StringBuilder
if (FuncIndex == 0)
{
RadioButton1Visiable = true;
RadioButton2Visiable = true;
RadioButton3Visiable = true;
RadioButton1Text = "Java";
RadioButton2Text = "C#";
RadioButton3Text = "JS";
CheckBox1Visiable = true;
CheckBox2Visiable = true;
CheckBox3Visiable = true;
TextBox3Visiable = true;
Button1Text = "生成";
Text3Title = "StringBuilder参数";
TextBox3 = "strSql";
}
//StringBuilder转SQL
else if (FuncIndex == 3)
{
RadioButton1Visiable = false;
RadioButton2Visiable = false;
RadioButton3Visiable = false;
TextBox3Visiable = false;
CheckBox1Visiable =false;
CheckBox2Visiable =false;
CheckBox3Visiable = false;
Button1Text = "生成";
}
//XML格式化
else if (FuncIndex == 1)
{
RadioButton1Visiable = false;
RadioButton2Visiable = false;
RadioButton3Visiable = false;
TextBox3Visiable = false;
CheckBox1Visiable = false;
CheckBox2Visiable = false;
CheckBox3Visiable = false;
Button1Text = "格式化";
}
//JSON格式化
else if (FuncIndex == 5)
{
RadioButton1Visiable = false;
RadioButton2Visiable = false;
RadioButton3Visiable = false;
TextBox3Visiable = false;
CheckBox1Visiable = false;
CheckBox2Visiable = false;
CheckBox3Visiable = false;
Button1Text = "格式化";
}
//SQL格式化
else if (FuncIndex == 2)
{
RadioButton1Visiable = false;
RadioButton2Visiable = false;
RadioButton3Visiable = false;
TextBox3Visiable = false;
CheckBox1Visiable =false;
CheckBox2Visiable =false;
CheckBox3Visiable = false;
Button1Text = "格式化";
}
//大小写转换
else if (FuncIndex == 4)
{
RadioButton1Visiable = true;
RadioButton2Visiable = true;
RadioButton3Visiable = false;
RadioButton1Text = "转大写";
RadioButton2Text = "转小写";
RadioButton1 = true;
TextBox3Visiable = false;
CheckBox1Visiable = false;
CheckBox2Visiable = false;
CheckBox3Visiable = false;
Button1Text = "转换";
}
}
private string FormatXml(string sUnformattedXml)
{
XmlDocument xd = new XmlDocument();
xd.LoadXml(sUnformattedXml);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
XmlTextWriter xtw = null;
try
{
xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.Indentation = 1;
xtw.IndentChar = '\t';
xd.WriteTo(xtw);
}
finally
{
if (xtw != null)
xtw.Close();
}
return sb.ToString();
}
public string GetParmName()
{
string parm = TextBox3.Trim();
if (parm.IsNullOrEmpty())
{
return "strSql";
}
return parm;
}
#region
public List<string> GetNewList(List<string> list)
{
List<string> list2 = new List<string>();
foreach (string str in list)
{
//if (str.Trim().StartsWith("--"))
//{
// continue;
//}
//if (str.Contains("--"))
//{
// int index = str.IndexOf("--");
// list2.Add(str.Substring(0, index));
// continue;
//}
list2.Add(str.TrimEnd());
}
return list2;
}
#endregion
#region List得到其中最长的长度
public int GetMaxLength(List<string> list)
{
int maxLength = 0;
foreach (string str in list)
{
if (System.Text.Encoding.Default.GetByteCount(str) > maxLength)
{
maxLength = System.Text.Encoding.Default.GetByteCount(str);
}
}
return maxLength;
}
#endregion
#region
public string GetString(string strInfo, int spaceNum, bool appendLine)
{
string str = string.Empty;
if (RadioButton1)
{
if (appendLine)
{
str += GetParmName() + ".append(\" " + strInfo + GetSpace(spaceNum) + " \").append(\"\\n\");";
}
else
{
str += GetParmName() + ".append(\" " + strInfo + GetSpace(spaceNum) + " \");";
}
}
if (RadioButton2)
{
if (appendLine)
{
str += GetParmName() + ".Append(\" " + strInfo + GetSpace(spaceNum) + " \").AppendLine();";
}
else
{
str += GetParmName() + ".Append(\" " + strInfo + GetSpace(spaceNum) + " \");";
}
}
if (RadioButton3)
{
if (appendLine)
{
str += GetParmName() + " += \" " + strInfo + GetSpace(spaceNum) + " \\n\";";
}
else
{
str += GetParmName() + " += \" " + strInfo + GetSpace(spaceNum) + " \";";
}
}
return str;
}
public string GetString2(string strInfo, int spaceNum, bool appendLine)
{
string str = string.Empty;
if (RadioButton1)
{
if (appendLine)
{
str += GetParmName() + ".append(\" " + strInfo + GetSpace(spaceNum) + "\").append(\"\\n\");";
}
else
{
str += GetParmName() + ".append(\" " + strInfo + GetSpace(spaceNum) + "\");";
}
}
if (RadioButton2)
{
if (appendLine)
{
str += GetParmName() + ".Append(\" " + strInfo + GetSpace(spaceNum) + "\").AppendLine();";
}
else
{
str += GetParmName() + ".Append(\" " + strInfo + GetSpace(spaceNum) + "\");";
}
}
if (RadioButton3)
{
if (appendLine)
{
str += GetParmName() + " += \" " + strInfo + GetSpace(spaceNum) + "\\n\";";
}
else
{
str += GetParmName() + " += \" " + strInfo + GetSpace(spaceNum) + "\";";
}
}
return str;
}
#endregion
#region
public string GetSpace(int num)
{
string str = string.Empty;
for (int i = 0; i < num; i++)
{
str += " ";
}
return str;
}
#endregion
#region
public List<string> GetFirstContext()
{
List<string> list = new List<string>();
string content = TextBox1;
if (string.Empty.Equals(content.Trim()))
{
return list;
}
if (content.Contains("\t"))
{
content = content.Replace("\t", " ");
}
content = content.Replace("\r", "");
string[] str = content.Split('\n');
foreach (string strings in str)
{
if (!string.Empty.Equals(strings.Trim()))
{
list.Add(strings.TrimEnd());
}
}
return list;
}
#endregion
private string QuSpace(string str, int spaceNum)
{
string space = string.Empty;
for (int i = 0; i < spaceNum; i++)
{
space += " ";
}
if (!str.Contains(space))
{
return str;
}
return str.Substring(str.IndexOf(space) + spaceNum, str.Length - str.IndexOf(space) - spaceNum);
}
private string HandlerString(string str, string parmName)
{
if (str.Contains(parmName + ".Append"))
{
//得到StringBuilder中间的词
string sqlStr = GetStringBuilderText(str, parmName + ".Append");
//得到注释
string zhushi = GetZhuShi(str);
//拼接
if (string.Empty.Equals(zhushi))
{
return sqlStr.TrimEnd();
}
else
{
return sqlStr.TrimEnd() + " --" + zhushi;
}
}
if (str.Contains(parmName + ".append"))
{
//得到StringBuilder中间的词
string sqlStr = GetStringBuilderText(str, parmName + ".append");
//得到注释
string zhushi = GetZhuShi(str);
//拼接
if (string.Empty.Equals(zhushi))
{
return sqlStr.TrimEnd();
}
else
{
return sqlStr.TrimEnd() + " --" + zhushi;
}
}
return string.Empty;
}
private string GetStringBuilderText(string str, string startStr)
{
startStr = startStr + "(\"";
str = str.Substring(str.IndexOf(startStr), str.IndexOf("\")") - str.IndexOf(startStr));
str = str.Substring(startStr.Length, str.Length - startStr.Length);
return str;
}
private string GetZhuShi(string str)
{
string retStr = string.Empty;
if (str.Contains(@"//"))
{
retStr = str.Substring(str.IndexOf("//") + 2, str.Length - str.IndexOf("//") - 2);
}
return retStr;
}
private string GetStringBuilderParmName(string str)
{
string parmName = String.Empty;
if (!str.Contains("StringBuilder"))
{
return parmName;
}
str = str.Substring(str.IndexOf("StringBuilder"), str.IndexOf("=") - str.IndexOf("StringBuilder"));
str = str.Substring(str.IndexOf(" "), str.Length - str.IndexOf(" "));
parmName = str.Trim();
return parmName;
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._05其他
{
public class ViewModel : ViewModelBase
{
}
}

View File

@@ -0,0 +1,199 @@
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Ursa.Controls;
using .Base;
namespace .ViewModel._05其他
{
public class ViewModel : ViewModelBase
{
public bool Enabled1 { get; set; } = true;
public bool Enabled2 { get; set; } = false;
//串口号下拉列表数据
public List<string> SerialList { get; set; }
public int SerialIndex { get; set; } = 0;
public string Data { get; set; } = "";
public DelegateCommand OpenCmd { get; set; }
public DelegateCommand CloseCmd { get; set; }
public DelegateCommand ReadCmd { get; set; }
public DelegateCommand WriteCmd { get; set; }
public DelegateCommand ClearCmd { get; set; }
private SerialPort sp1;
public ViewModel()
{
this.sp1 = new SerialPort();
//串口号
string[] portNames = SerialPort.GetPortNames();
if (portNames != null && portNames.Length > 0)
{
SerialList = portNames.ToList();
}
OpenCmd = new DelegateCommand(OpenCmdFunc);
CloseCmd = new DelegateCommand(CloseCmdFunc);
ReadCmd = new DelegateCommand(ReadCmdFunc);
WriteCmd = new DelegateCommand(WriteCmdFunc);
ClearCmd = new DelegateCommand(ClearCmdFunc);
}
private void OpenCmdFunc(object obj)
{
try
{
this.sp1.PortName = SerialList[SerialIndex];
this.sp1.BaudRate = 19200;
this.sp1.DataBits = 8;
this.sp1.StopBits = StopBits.One;
this.sp1.Parity = Parity.None;
if (this.sp1.IsOpen)
{
this.sp1.Close();
}
this.sp1.Open();
Enabled1 = false;
Enabled2 = true;
}
catch (Exception ex)
{
MessageBox.ShowAsync(ex.Message);
}
}
private void CloseCmdFunc(object obj)
{
if (this.sp1.IsOpen)
{
this.sp1.Close();
}
Enabled1 = true;
Enabled2 = false;
}
private void ReadCmdFunc(object obj)
{
List<byte> list = this.sendData(this.getReadData());
if ((list != null) && (list.Count >= 15))
{
int num = 0;
num = (((((((list[9] << 8) | list[10]) << 8) | list[11]) << 8) | list[12]) << 8) | list[13];
Data = Convert.ToString(num);
this.sendData(this.getBeatData());
}
}
private void WriteCmdFunc(object obj)
{
if (this.sp1.IsOpen)
{
string str = Data;
int num = 0;
bool flag = int.TryParse(str, out num);
if (!flag)
{
MessageBox.ShowAsync("请输入数字");
return;
}
if ((num < 0) || (num >= 999999999))
{
MessageBox.ShowAsync("数字只能在0~999999999之间");
return;
}
byte a = (byte)((num & 0xff00000000L) >> 32);
byte b = (byte)((num & 0xff000000L) >> 24);
byte c = (byte)((num & 0xff0000) >> 16);
byte d = (byte)((num & 0xff00) >> 8);
byte num8 = (byte)(num & 0xff);
this.sendData(this.getWriteData(a, b, c, d, num8));
this.sendData(this.getBeatData());
}
}
private void ClearCmdFunc(object obj)
{
Data = "";
}
private List<byte> getBeatData()
{
return new List<byte> { 0xAA, 0xBB, 0x05, 0x00, 0x00, 0x00, 0x06, 0x01, 0x07 };
}
private List<byte> getReadData()
{
return new List<byte> { 0xAA, 0xBB, 0x05, 0x00, 0x00, 0x00, 0x10, 0x20, 0x30 };
}
private List<byte> getWriteData(byte a, byte b, byte c, byte d, byte e)
{
List<byte> list = new List<byte>();
list.Add(0xAA);
list.Add(0xBB);
list.Add(0x0A);
list.Add(0x00);
list.Add(0x00);
list.Add(0x00);
list.Add(0x09);
list.Add(0x03);
list.Add(a);
list.Add(b);
list.Add(c);
list.Add(d);
list.Add(e);
byte item = list[6];
for (int i = 7; i < 13; i++)
{
item ^= list[i];
}
list.Add(item);
return list;
}
public List<byte> sendData(List<byte> sendData)
{
if (!this.sp1.IsOpen)
{
return null;
}
this.sp1.Write(sendData.ToArray(), 0, sendData.Count);
while (this.sp1.BytesToRead == 0)
{
Thread.Sleep(1);
}
Thread.Sleep(50);
byte[] buffer = new byte[this.sp1.BytesToRead];
this.sp1.Read(buffer, 0, buffer.Length);
return buffer.ToList<byte>();
}
private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (this.sp1.IsOpen)
{
DateTime now = DateTime.Now;
try
{
byte[] buffer = new byte[this.sp1.BytesToRead];
this.sp1.Read(buffer, 0, buffer.Length);
}
catch (Exception exception)
{
MessageBox.ShowAsync(exception.Message, "出错提示!!!!!");
}
}
else
{
MessageBox.ShowAsync("请打开某个串口", "错误提示");
}
}
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._05其他
{
public class ViewModel : ViewModelBase
{
}
}

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using .Base;
namespace .ViewModel._05其他
{
public class ASCII转换ViewModel : ViewModelBase
{
}
}

View File

@@ -0,0 +1,25 @@
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using System;
using .Base;
namespace .ViewModels
{
public class ApplicationViewModel : ViewModelBase
{
public DelegateCommand ExitCommand { get; set; }
public ApplicationViewModel()
{
ExitCommand = new DelegateCommand(Exit);
}
private void Exit(object obj)
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
Environment.Exit(0);
//desktop.Shutdown();
}
}
}
}

File diff suppressed because one or more lines are too long