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;
///
/// 默认工位
///
public static string DefaultPosition = "";//名称
public static string DefaultPositionName = "";//名称
///
/// 机器所有工位
///
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;
}
///
/// 下载文件到本地
///
///
///
///
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;
}
}
///
/// 获取本机mac地址
///
///
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
{
}
}
///
/// 获取本机mac地址
///
///
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
{
}
}
///
/// 获取配置文件xml
///
///
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 "";
}
}
///
/// 获取本机活动物理网卡的ip
///
///
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;
}
///
/// 实体转键值对
///
/// 泛型
///
///
public static Dictionary EntityToDictionary(T obj) where T : class
{
//初始化定义一个键值对,注意最后的括号
Dictionary dic = new Dictionary();
//返回当前 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;
}
///
/// 变量管理,用于数据交互
///
public static Dictionary Variables = new Dictionary();
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 读取配置文件
///
/// 读取配置文件
///
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);
}
}
///
/// 写入INI文件
///
/// 项目名称(如 [TypeName] )
/// 键
/// 值
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);
}
}
///
/// 读出INI文件
///
/// 项目名称(如 [TypeName] )
/// 键
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 "";
}
///
/// 将配置文件中的信息存到Contexts中
///
///
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
///
/// 设置变量
///
/// 名称
/// 值
public static void SetValue(string strVarName, object objVarValue)
{
try
{
Variables[strVarName] = objVarValue;
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量赋值出错:" + ex.Message + " [" + strVarName + "]");
}
}
///
/// 获取变量值
///
/// 名称
///
public static object GetValue(string strVarName)
{
try
{
return Variables[strVarName];
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量取值出错:" + ex.Message + " [" + strVarName + "]");
return "";
}
}
///
/// 获取变量值
///
/// 名称
///
public static string GetString(string strVarName)
{
try
{
return Variables[strVarName].ToString();
}
catch (Exception ex)
{
LogHelper.instance.log.Error("==========>变量取值出错:" + ex.Message + " [" + strVarName + "]");
return null;
}
}
///
/// 获取32位随机码
///
/// 名称
///
public static string GetUUID()
{
return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 32);
}
}
}