using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Windows.Forms;
using UAS_LabelMachine.CustomControl;
using UAS_LabelMachine.CustomControl.GroupBoxWithBorder;
using System.Security.Cryptography;
using static System.Windows.Forms.Control;
using System.IO;
namespace UAS_LabelMachine
{
class BaseUtil
{
static string SysDisc;
private string Key = "96878265";
public static string SysDisc1
{
get
{
return SysDisc = Environment.GetEnvironmentVariable("windir").Substring(0, 1);
}
set
{
SysDisc = value;
}
}
public static byte[] hexStr2ByteArr(string strIn)
{
byte[] arrB = Encoding.UTF8.GetBytes(strIn);
int iLen = arrB.Length;
// 两个字符表示一个字节,所以字节数组长度是字符串长度除以2
byte[] arrOut = new byte[iLen / 2];
for (int i = 0; i < iLen; i = i + 2)
{
string strTmp = new string(Encoding.UTF8.GetChars(arrB), i, 2);
arrOut[i / 2] = (byte)int.Parse(strTmp, System.Globalization.NumberStyles.HexNumber);
}
return arrOut;
}
public byte[] decrypt(byte[] arrB)
{
return null;
//return decryptCipher.doFinal(arrB);
}
public string decrypt(string strIn)
{
return new string(Encoding.ASCII.GetChars(decrypt(hexStr2ByteArr(strIn))));
}
public static string DESEnCode(string pToEncrypt, string sKey)
{
// string pToEncrypt1 = HttpContext.Current.Server.UrlEncode(pToEncrypt);
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
//建立加密对象的密钥和偏移量
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
des.Key = Encoding.UTF8.GetBytes(sKey);
des.IV = Encoding.UTF8.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
public static string DESDeCode(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = Encoding.UTF8.GetBytes(sKey);
des.IV = Encoding.UTF8.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
public static byte[] Des3EncodeCBC(byte[] key, byte[] iv, byte[] data)
{
//复制于MSDN
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.CBC; //默认值
tdsp.Padding = PaddingMode.PKCS7; //默认值
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(mStream,
tdsp.CreateEncryptor(key, iv),
CryptoStreamMode.Write);
// Write the byte array to the crypto stream and flush it.
cStream.Write(data, 0, data.Length);
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
///
/// DES3 CBC模式解密
///
/// 密钥
/// IV
/// 密文的byte数组
/// 明文的byte数组
public static byte[] Des3DecodeCBC(byte[] key, byte[] iv, byte[] data)
{
try
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream(data);
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.CBC;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt, tdsp.CreateDecryptor(key, iv), CryptoStreamMode.Read);
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
//Convert the buffer into a string and return it.
return fromEncrypt;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
///
/// DES3 ECB模式加密
///
/// 密钥
/// IV(当模式为ECB时,IV无用)
/// 明文的byte数组
/// 密文的byte数组
public static byte[] Des3EncodeECB(byte[] key, byte[] iv, byte[] data)
{
try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream();
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(mStream, tdsp.CreateEncryptor(key, iv), CryptoStreamMode.Write);
// Write the byte array to the crypto stream and flush it.
cStream.Write(data, 0, data.Length);
cStream.FlushFinalBlock();
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
}
///
/// DES3 ECB模式解密
///
/// 密钥
/// IV(当模式为ECB时,IV无用)
/// 密文的byte数组
/// 明文的byte数组
public static byte[] Des3DecodeECB(byte[] key, byte[] iv, byte[] data)
{
// Create a new MemoryStream using the passed
// array of encrypted data.
MemoryStream msDecrypt = new MemoryStream(data);
TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider();
tdsp.Mode = CipherMode.ECB;
tdsp.Padding = PaddingMode.PKCS7;
// Create a CryptoStream using the MemoryStream
// and the passed key and initialization vector (IV).
CryptoStream csDecrypt = new CryptoStream(msDecrypt, tdsp.CreateDecryptor(key, iv), CryptoStreamMode.Read);
// Create buffer to hold the decrypted data.
byte[] fromEncrypt = new byte[data.Length];
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
//Convert the buffer into a string and return it.
return fromEncrypt;
}
///
/// 通过DataTable的ColumnName和Caption来拼接一条语句
///
///
///
public static string GetGridViewSelectContent(DataGridView d)
{
StringBuilder selectConetnt = new StringBuilder();
DataTable dt = (DataTable)d.DataSource;
if (dt == null)
{
foreach (DataGridViewColumn dc in d.Columns)
{
if (dc.DataPropertyName != "" && dc.DataPropertyName != null)
{
selectConetnt.Append(dc.DataPropertyName + " as " + dc.DataPropertyName + ",");
}
}
}
else
{
foreach (DataColumn dc in dt.Columns)
{
selectConetnt.Append(dc.Caption + " as " + dc.ColumnName + ",");
}
}
return selectConetnt.Remove(selectConetnt.Length - 1, 1).ToString();
}
///
/// 通过字段和其展示的中文值获取查询的内容
///
///
///
///
public static string GetSelectContentByStringArray(string[] field, string[] cnfield)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < field.Length; i++)
{
sb.Append(field[i] + " as " + cnfield[i] + ",");
}
//去掉多余的逗号
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
///
/// 传入控件的集合和DataTable,通过判断控件的名称和数据源的列的描述来匹配,支持单层的GroupBox和Panel
///
///
///
public static void SetFormValue(ControlCollection collection, DataTable dt)
{
//DataTable存在数据才进行赋值操作
if (dt.Rows.Count > 0)
{
for (int i = 0; i < collection.Count; i++)
{
string controlName = collection[i].Name;
//默认给TextBox和Label赋值
if (collection[i] is TextBox || collection[i] is Label || collection[i] is SearchTextBox)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (controlName.ToUpper() == dt.Columns[j].Caption.ToUpper())
{
//字段含有Status内容的才进行转换
if (controlName.ToUpper().Contains("STATUS"))
{
//对审批状态进行判断
switch (dt.Rows[0][j].ToString().ToUpper())
{
case "ENTERING":
collection[i].Text = "在录入";
break;
case "UNAPPROVED":
collection[i].Text = "未批准";
break;
case "COMMITED":
collection[i].Text = "已提交";
break;
case "APPROVE":
collection[i].Text = "已批准";
break;
case "AUDITED":
collection[i].Text = "已审核";
break;
case "STARTED":
collection[i].Text = "已下发";
break;
case "UNCHECK":
collection[i].Text = "待检验";
break;
case "CHECKING":
collection[i].Text = "检验中";
break;
default:
collection[i].Text = dt.Rows[0][j].ToString();
break;
}
}
else
{
collection[i].Text = dt.Rows[0][j].ToString();
}
}
}
}
//对封装在GroupBox的和Panel的控件进行批量赋值
if (collection[i] is GroupBox || collection[i] is Panel || collection[i] is GroupBoxWithBorder)
{
for (int j = 0; j < collection[i].Controls.Count; j++)
{
controlName = collection[i].Controls[j].Name;
if (collection[i].Controls[j] is TextBox || collection[i].Controls[j] is Label || collection[i].Controls[j] is SearchTextBox)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
if (controlName.ToUpper() == dt.Columns[k].Caption.ToUpper())
{
collection[i].Controls[j].Text = dt.Rows[0][k].ToString();
}
}
}
}
}
}
}
//如果没有记录的话,将dt中含有的列的对应值设置为空
else
{
for (int i = 0; i < collection.Count; i++)
{
if (collection[i] is TextBox || collection[i] is Label || collection[i] is SearchTextBox)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
if (collection[i].Name.ToUpper() == dt.Columns[j].Caption.ToUpper())
{
collection[i].Text = "";
}
}
}
}
}
}
///
/// 获取标签的路径
///
///
///
///
public static string GetLabelUrl(string URL, string LabelName, DateTime time)
{
//如果是传入的数据是从FTP取的文件
if (URL.Contains("ftp:"))
{
ftpOperater ftp = new ftpOperater();
return ftp.Download(LabelName, time);
}
else
{
return URL;
}
}
///
/// 从DGV获取指定的列的数据形式是数组的形式
///
public static ArrayList[] GetColumnDataFromDGV(DataGridView dgv, string[] ColumnName)
{
ArrayList[] array = new ArrayList[ColumnName.Length];
//实例化和查询参数个数一样的ArrayList
for (int i = 0; i < ColumnName.Length; i++)
{
array[i] = new ArrayList();
}
DataTable dt = (DataTable)dgv.DataSource;
//如果第一列是否选框的话
if (dgv.Columns[0] is DataGridViewCheckBoxColumn)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dgv.Rows[i].Cells[0].FormattedValue.ToString() == "True")
{
for (int j = 0; j < ColumnName.Length; j++)
{
array[j].Add(dt.Rows[i][ColumnName[j]]);
}
}
}
}
//否则直接获取全部的数据
else
{
for (int i = 0; i < dgv.RowCount; i++)
{
for (int j = 0; j < ColumnName.Length; j++)
{
array[j].Add(dt.Rows[i][ColumnName[j]]);
}
}
}
return array;
}
///
/// 通过DataGridView和需要隐藏的字段的数组来对字段进行隐藏
///
///
///
public static void HideField(DataGridView dgv, string[] field)
{
DataTable dt = (DataTable)dgv.DataSource;
foreach (DataColumn dc in dt.Columns)
{
foreach (string s in field)
{
if (dc.Caption == s)
{
dgv.Columns[dc.ColumnName].Visible = false;
}
}
}
}
///
/// 通过查询的内容获取到字段的描述
///
///
///
public static string[] GetCaptionFromField(string field)
{
string[] caption = field.Split(',');
for (int i = 0; i < caption.Length; i++)
{
caption[i] = caption[i].Substring(0, caption[i].LastIndexOf("as")).Trim();
}
return caption;
}
///
/// 通过查询的语句获取查询的字段
///
///
///
public static string[] GetField(string field)
{
string[] fields = field.Split(',');
for (int i = 0; i < fields.Length; i++)
{
fields[i] = fields[i].Substring(fields[i].LastIndexOf("as") + 2, fields[i].Length - fields[i].LastIndexOf("as") - 2).Trim();
}
return fields;
}
///
/// 将DataTable转换为List的键值对
///
///
///
public static List> DataTableToListDictionary(DataTable dt)
{
List> list = new List>();
foreach (DataRow dr in dt.Rows)
{
Dictionary dictionary = new Dictionary();
foreach (DataColumn dc in dt.Columns)
{
dictionary.Add(dc.Caption, dr[dt.Columns.IndexOf(dc)].ToString());
}
list.Add(dictionary);
}
return list;
}
///
/// 通过描述取DataTable的列名,主要用于从配置中取数据
///
///
///
///
public static string GetColumnNameByCaption(DataTable dt, string caption)
{
foreach (DataColumn dc in dt.Columns)
{
if (dc.Caption.ToLower() == caption)
{
return dc.ColumnName;
}
}
return null;
}
//用于封装异常,也可以用于错误的提示
public static void ShowError(string errorMessage)
{
throw new Exception(errorMessage);
}
///
/// 清除DataTable的结构和数据,清除列结构时需要从最后的一列开始删
///
///
public static void CleanDataTable(DataTable dt)
{
for (int i = dt.Columns.Count - 1; i >= 0; i--)
{
dt.Columns.Remove(dt.Columns[i]);
}
}
///
/// 不清楚表结构,只清楚数据
///
///
public static void CleanDataTableData(DataTable dt)
{
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
dt.Rows.Remove(dt.Rows[i]);
}
}
///
/// 获取拼接的字段
///
///
///
public static string GetFieldFromDataTable(DataTable dt)
{
StringBuilder sb = new StringBuilder();
foreach (DataColumn dc in dt.Columns)
{
sb.Append(dc.Caption + ",");
}
return sb.ToString().Substring(sb.ToString().Length - 1, 1);
}
///
/// 已经定义好的DataGridView绑定数据,operate是用来添加操作列的
///
///
///
///
///
public static void FillDgvWithDataTable(DataGridView dgv, DataTable dt, params DataGridViewImageColumn[] operate)
{
dgv.AutoGenerateColumns = false;
dgv.DataSource = dt;
if (operate.Length > 0)
{
if (dgv.Columns[operate[0].Name] != null)
{
dgv.Columns.Remove(dgv.Columns[operate[0].Name]);
}
dgv.Columns.Add(operate[0]);
}
//纯英文的列不予展示
//Regex regEnglish = new Regex("^[_][a-z]$");
//foreach (DataGridViewColumn dgvc in dgv.Columns)
//{
// if (dgvc.HeaderText.IndexOf("_id") > 0)
// {
// dgvc.Visible = false;
// }
//}
}
///
/// 清除DataGridView的数据
///
///
public static void CleanDGVData(DataGridView dgv)
{
for (int i = dgv.Rows.Count - 1; i >= 0; i--)
{
dgv.Rows.RemoveAt(i);
}
}
///
/// 清除Form的指定类型的数据
///
///
public static void CleanForm(Form Form)
{
for (int i = 0; i < Form.Controls.Count; i++)
{
if (Form.Controls[i] is EnterTextBox || Form.Controls[i] is TextBox || Form.Controls[i] is RichTextBox || Form.Controls[i] is SearchTextBox)
Form.Controls[i].Text = "";
if (Form.Controls[i] is DataGridView)
CleanDGVData((DataGridView)Form.Controls[i]);
}
}
///
/// 用于给DGV中的Combox列赋静态值
///
///
///
///
///
///
public static void SetDgvColumnComboxData(DataGridViewComboBoxColumn dgvc, string DataPropertyName, string displayField, string valueField, string[] Value)
{
DataTable dt = new DataTable();
dt.Columns.Add(displayField);
dt.Columns.Add(valueField);
for (int i = 0; i < Value.Length; i++)
{
DataGridViewRow row = new DataGridViewRow();
dt.Rows.Add(row);
dt.Rows[i][displayField] = Value[i].Split('#')[0];
dt.Rows[i][valueField] = Value[i].Split('#')[1];
}
dgvc.DataPropertyName = DataPropertyName;
dgvc.DataSource = dt;
dgvc.DisplayMember = displayField;
dgvc.ValueMember = valueField;
}
///
/// 用于给DGV中的ComboxCell赋静态值
///
///
///
///
///
public static void SetDGVCellComboxData(DataGridViewComboBoxCell dgvcc, string displayField, string valueField, string[] Value)
{
DataTable dt = new DataTable();
dt.Columns.Add(displayField);
dt.Columns.Add(valueField);
for (int i = 0; i < Value.Length; i++)
{
DataRow dr = dt.NewRow();
dr[displayField] = Value[i].Split('#')[0];
dr[valueField] = Value[i].Split('#')[1];
dt.Rows.Add(dr);
}
dgvcc.DisplayMember = displayField;
dgvcc.ValueMember = valueField;
dgvcc.DataSource = dt;
}
///
/// 用于给DGV中的ComboxCell赋静态值
///
///
///
///
///
public static void SetComboxData(ComboBox dgvcc, string displayField, string valueField, string[] Value)
{
DataTable dt = new DataTable();
dt.Columns.Add(displayField);
dt.Columns.Add(valueField);
for (int i = 0; i < Value.Length; i++)
{
DataRow dr = dt.NewRow();
dr[displayField] = Value[i].Split('#')[0];
dr[valueField] = Value[i].Split('#')[1];
dt.Rows.Add(dr);
}
dgvcc.DisplayMember = displayField;
dgvcc.ValueMember = valueField;
dgvcc.DataSource = dt;
}
///
/// 获取刷选的SQL语句,传入的是TextBox的Control,传入的SQL不带Where条件
///
///
///
///
public static string GetScreenSqlCondition(params Control[] Condition)
{
string condition = " where ";
for (int i = 0; i < Condition.Length; i++)
{
if (i != Condition.Length - 1)
{
if (Condition[i] is ComboBox)
{
condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' or " + Condition[i].Tag + " is null) and ";
}
else
{
condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' or " + Condition[i].Tag + " is null) and ";
}
}
else
{
if (Condition[i] is ComboBox)
{
condition += "(" + Condition[i].Tag + " like " + "'%" + (Condition[i] as ComboBox).SelectedValue + "%' or " + Condition[i].Tag + " is null)";
}
else
{
condition += "(" + Condition[i].Tag + " like " + "'%" + Condition[i].Text + "%' or " + Condition[i].Tag + " is null)";
}
}
}
return condition;
}
public static void CleanDataGridView(DataGridView dgv)
{
for (int i = dgv.Columns.Count - 1; i >= 0; i--)
{
dgv.Columns.RemoveAt(i);
}
}
///
/// 取出SQL中的参数占位符
///
///
///
public static string[] GetParamFromSQL(string SQL)
{
string[] par = SQL.Split(':');
//用来存参数的数组
StringBuilder[] addpar = new StringBuilder[par.Length - 1];
string[] param = new string[par.Length - 1];
for (int i = 0; i < par.Length - 1; i++)
{
//新建一个char类型的数组用来存储每个字节的变量
char[] c = par[i + 1].ToCharArray();
addpar[i] = new StringBuilder();
for (int j = 0; j < c.Length; j++)
{
if (c[j] != ' ' && c[j] != ',' && c[j] != ')')
{
addpar[i].Append(c[j]);
}
else
{
break;
}
}
}
for (int i = 0; i < par.Length - 1; i++)
{
param[i] = addpar[i].ToString();
}
return param;
}
public static void SetFormCenter(Form form)
{
form.StartPosition = FormStartPosition.CenterParent;
}
///
/// 设置DataGridView的指定列可编辑
///
///
///
public static void SetDataGridViewReadOnly(DataGridView DGV, string[] EditAbleField)
{
foreach (DataGridViewColumn dc in DGV.Columns)
{
dc.ReadOnly = true;
foreach (string s in EditAbleField)
{
if (dc.Name.ToLower() == s.ToLower())
{
DGV.Columns[dc.Name].ReadOnly = false;
}
}
}
}
//判断带有CheckBox的DGV是否有项目勾选了
public static DataTable DGVIfChecked(DataGridView dgv)
{
int CheckCount = 0;
DataTable dt = new DataTable();
//第一列是勾选框,排除在循环之外
for (int i = 1; i < dgv.Columns.Count; i++)
{
dt.Columns.Add(dgv.Columns[i].Name);
}
for (int i = 0; i < dgv.RowCount; i++)
{
if (dgv.Rows[i].Cells[0].Value != null)
{
if (dgv.Rows[i].Cells[0].Value.ToString() == "True")
{
if (dgv.Rows[i].Tag.ToString() == "SonRow")
{
DataRow dr = dt.NewRow();
for (int j = 1; j < dgv.ColumnCount; j++)
{
dr[dgv.Columns[j].Name] = dgv.Rows[i].Cells[j].FormattedValue;
}
dt.Rows.Add(dr);
CheckCount++;
}
}
}
}
//判断是否勾选了明细
if (CheckCount == 0)
{
return null;
}
return dt;
}
///
/// 设置只允许输入数字
///
///
///
public static void NumOnly(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')//这是允许输入退格键
{
if ((e.KeyChar < '0') || (e.KeyChar > '9'))//这是允许输入0-9数字
{
e.Handled = true;
}
}
}
public static string AddField(string[] Fields)
{
string sql = " ";
foreach (string field in Fields)
{
sql += field + ",";
}
return sql.Substring(0, sql.Length - 1);
}
}
}