You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

437 lines
14 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using System;
using System.IO;
using System.Xml;
using System.Management;
using System.Net;
using System.Collections.Generic;
using System.Reflection;
using XGL.Models;
using System.Runtime.InteropServices;
using System.Text;
namespace CommonFunc
{
public class Common
{
public static string ThriftConfigIp = "";
public static string ThriftConfigPort = "";
public static string thriftBoxPort = "";
public static string FormBoardThriftPort = "";
public static string LocatHostMac = "";
public static string HostIp = "";
public static string mySqlConnectStr = "";
public static string PortName = "";
public static string ApplicationDicStr = "";
public static int noticeserch = 0;
public static int downloadPDF = 0;
public static int stoplineset = 0;
/// <summary>
/// 默认工位
/// </summary>
public static string DefaultPosition = "";//名称
public static string DefaultPositionName = "";//名称
/// <summary>
/// 机器所有工位
/// </summary>
public static string CSPosition = "";
public static string CSPositionCodes = string.Empty;
public static string PostType = string.Empty;
public static string LineCode = string.Empty;
public static Logger Log = new Logger();
public static string LocalIPAddress = "";
public static common_auth_userModel currUser = new common_auth_userModel();
//public static basedata_lineinfo Lineinfo = new basedata_lineinfo();
public static string LineId = string.Empty;
public static int BoardRefresh { get; set; }
public static int TakeOffRefresh { get; set; }
public static int EmptyRefresh { get; set; }
private static byte[] GetBytesFromString(string str, char splitChar)
{
if (str == "")
{
return new byte[0];
}
string[] strs = str.Split(splitChar);
byte[] bytes = new byte[strs.Length];
for (int i = 0; i < strs.Length; i++)
{
bytes[i] = Convert.ToByte(strs[i], 16);
}
return bytes;
}
//解析小车号
public static string getCarNoByPlcPoint(object carnopoint)
{
string carno = "";
if (carnopoint != null && carnopoint.ToString().Length == 80)
{
string pointval = carnopoint.ToString();
carno = pointval.Substring(12, 1) + pointval.Substring(15, 1) + pointval.Substring(18, 1);
}
return carno;
}
/// <summary>
/// 下载文件到本地
/// </summary>
/// <param name="url"></param>
/// <param name="path"></param>
/// <returns></returns>
public static bool GetHttpFileSaveLocal(String url, string path)
{
if (string.IsNullOrWhiteSpace(url))
{
return false;
}
try
{
WebClient webclient = new WebClient();
webclient.DownloadFile(url, path);
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 获取本机mac地址
/// </summary>
/// <returns></returns>
public static string GetLocationHostMac()
{
try
{
//获取网卡硬件地址
string mac = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString();
break;
}
}
moc = null;
mc = null;
return mac;
}
catch
{
return "";
}
finally
{
}
}
/// <summary>
/// 获取本机mac地址
/// </summary>
/// <returns></returns>
public static string GetLocationHostAddress()
{
try
{
//获取IP地址
string st = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
//st=mo["IpAddress"].ToString();
System.Array ar;
ar = (System.Array)(mo.Properties["IpAddress"].Value);
st = ar.GetValue(0).ToString();
break;
}
}
moc = null;
mc = null;
return st;
}
catch
{
return "";
}
finally
{
}
}
/// <summary>
/// 获取配置文件xml
/// </summary>
/// <returns></returns>
public static string ReadConfigXmlString(string xmlFilePath)
{
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + xmlFilePath, FileMode.Open, FileAccess.Read);
StreamReader sw = new StreamReader(fs);
string xml = sw.ReadToEnd();
sw.Close();
fs.Close();
return xml;
}
public static string ReadNodeText(string xml, string nodeurl)
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
XmlNode xmlnode = xmldoc.SelectSingleNode(nodeurl);
if (xmlnode != null)
{
return xmlnode.InnerText;
}
else
{
return "";
}
}
/// <summary>
/// 获取本机活动物理网卡的ip
/// </summary>
/// <returns></returns>
public static string IPAddress()
{
string userIP = "";
System.Net.NetworkInformation.NetworkInterface[] fNetworkInterfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
foreach (System.Net.NetworkInformation.NetworkInterface adapter in fNetworkInterfaces)
{
string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection";
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
// 区分 PnpInstanceID
// 如果前面有 PCI 就是本机的真实网卡
//System.Net.NetworkInformation.OperationalStatus.Up 活动网卡
string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0));
if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI" && adapter.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
{
System.Net.NetworkInformation.IPInterfaceProperties fIPInterfaceProperties = adapter.GetIPProperties();
System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = fIPInterfaceProperties.UnicastAddresses;
foreach (System.Net.NetworkInformation.UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection)
{
if (UnicastIPAddressInformation.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
userIP = UnicastIPAddressInformation.Address.ToString(); // Ip 地址
}
break;
}
}
}
return userIP;
}
/// <summary>
/// 实体转键值对
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static Dictionary<string, string> EntityToDictionary<T>(T obj) where T : class
{
//初始化定义一个键值对,注意最后的括号
Dictionary<string, string> dic = new Dictionary<string, string>();
//返回当前 Type 的所有公共属性Property集合
PropertyInfo[] props = typeof(T).GetProperties();
foreach (PropertyInfo p in props)
{
var property = obj.GetType().GetProperty(p.Name);//获取property对象
var value = p.GetValue(obj, p.GetIndexParameters());//获取属性值
dic.Add(p.Name, value == null ? "" : obj.ToString());
}
return dic;
}
/// <summary>
/// 变量管理,用于数据交互
/// </summary>
public static Dictionary<string, object> Variables = new Dictionary<string, object>();
public static string s_config;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
#region 读取配置文件
/// <summary>
/// 读取配置文件
/// </summary>
public static void ReadConfig()
{
try
{
string path = AppDomain.CurrentDomain.BaseDirectory;
s_config = path + "\\System.ini";
SetConfigToContexts(s_config);
}
catch (Exception ex)
{
LogHelper.instance.log.Error(" ReadConfig() 异常(配置文件格式不正确)" + ex.Message);
}
}
/// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
public static void IniWriteValue(string Section, string Key, string Value)
{
try
{
WritePrivateProfileString(Section, Key, Value, s_config);
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量赋值出错:" + ex.Message);
}
}
/// <summary>
/// 读出INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
public static string IniReadValue(string Section, string Key)
{
try
{
StringBuilder temp = new StringBuilder(500);
int i = GetPrivateProfileString(Section, Key, "", temp, 500, s_config);
return temp.ToString();
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量读取出错:" + ex.Message);
}
return "";
}
/// <summary>
/// 将配置文件中的信息存到Contexts中
/// </summary>
/// <param name="path"></param>
private static void SetConfigToContexts(string path)
{
string[] allLines = File.ReadAllLines(path);
foreach (string str in allLines)
{
string[] config = str.Split('=');
if (config.Length >= 2)
{
if (config[0].Trim() == "" || config[1].Trim() == "") continue;
if (GetValue(config[0].Trim()).ToString() != "")
{
LogHelper.instance.log.Error("在" + path + "中已经存在相同的配置项:" + config[0].Trim());
}
SetValue(config[0].Trim(), str.Substring(config[0].Length + 1));
}
}
}
#endregion
/// <summary>
/// 设置变量
/// </summary>
/// <param name="strVarName">名称</param>
/// <param name="objVarValue">值</param>
public static void SetValue(string strVarName, object objVarValue)
{
try
{
Variables[strVarName] = objVarValue;
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量赋值出错:" + ex.Message + " [" + strVarName + "]");
}
}
/// <summary>
/// 获取变量值
/// </summary>
/// <param name="strVarName">名称</param>
/// <returns></returns>
public static object GetValue(string strVarName)
{
try
{
return Variables[strVarName];
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量取值出错:" + ex.Message + " [" + strVarName + "]");
return "";
}
}
/// <summary>
/// 获取变量值
/// </summary>
/// <param name="strVarName">名称</param>
/// <returns></returns>
public static string GetString(string strVarName)
{
try
{
return Variables[strVarName].ToString();
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量取值出错:" + ex.Message + " [" + strVarName + "]");
return null;
}
}
/// <summary>
/// 获取32位随机码
/// </summary>
/// <param name="strVarName">名称</param>
/// <returns></returns>
public static string GetUUID()
{
return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32);
}
}
}