/// <summary> /// 获得指定枚举类型中,指定值的描述文本。 /// </summary> /// <param name="enumValue">枚举值,不要作任何类型转换</param> /// <returns>描述字符串</returns> public static string GetFieldText(object enumValue) { try { EnumDescriptionAttribute[] descriptions = GetFieldTexts(enumValue.GetType()); if (descriptions == null) { return(string.Empty); } foreach (EnumDescriptionAttribute ed in descriptions) { if (ed.fieldIno.Name == enumValue.ToString()) { return(ed.EnumDisplayText); } } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetFieldText", "EnumDescription"); return(string.Empty); } return(string.Empty); }
private void btnTestLog_Click(object sender, EventArgs e) { NLogUtility.InfoLog("test message", "prefix", "subDir"); NLogUtility.DebugLog("debug message", "prefix", "subDir"); Exception ex = null; try { TestEx(); } catch (Exception ex1) { ex = ex1; } NLogUtility.ExceptionLog(ex, "prefix", "subDir", "extInfo"); Dictionary <string, object> dictVariable = new Dictionary <string, object>(); //NLogUtility.CallInfoLog(DateTime.Now.AddMinutes(-1), DateTime.Now, 100010, "127.0.0.1", dictVariable, "call message"); dictVariable.Add("Action", "action"); dictVariable.Add("ProductId", "product"); dictVariable.Add("CallSource", "callSource"); dictVariable.Add("SessionId", "sessionId"); dictVariable.Add("SessionState", 1); dictVariable.Add("UserId", 100000); dictVariable.Add("UserName", "UserName"); dictVariable.Add("ResultCode", 0); NLogUtility.CallInfoLog(DateTime.Now.AddMinutes(-1), DateTime.Now, dictVariable, "call message"); //NLogUtility.CallErrorLog(100010, DateTime.Now.AddMinutes(-1), DateTime.Now, "action", "callSource", "127.0.0.1", "sessionId", 1, 100000, "UserName", 0, ex, "ext message"); NLogUtility.CallErrorLog(DateTime.Now.AddMinutes(-1), DateTime.Now, dictVariable, ex, "ext message"); }
private long CheckStoragesUsage() { try { MR_storages_usage _storagesUsage = Main.Current.RT.REST.Storages_Usage(); if (_storagesUsage != null) { int _queuedUnsendFiles = Main.Current.NewPostManager.GetQueuedUnsendFilesCount(); m_avail_month_total_objects = _storagesUsage.storages.waveface.available.avail_month_total_objects; m_month_total_objects = _storagesUsage.storages.waveface.quota.month_total_objects; //Hack if (m_month_total_objects == -1) { return(long.MaxValue); } return(m_avail_month_total_objects - _queuedUnsendFiles - imageListView.Items.Count); } } catch (Exception _e) { NLogUtility.Exception(s_logger, _e, "CheckStoragesUsage"); } return(long.MinValue); }
private string DecryptConnStr(string inStr) { try { switch (EncryptType) { case 1: inStr = inStr.TripleDesDecryptFromBase64ToString(); break; case 2: inStr = Net91ComCryptoHelper.DES_Decrypt(inStr); break; default: break; } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "ConnectionElement_DecryptConnStr", "CustomConfig"); } return(inStr); }
/// <summary> /// 监视的文件发生改变 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnWatcherChanged(object sender, FileSystemEventArgs e) { lock (this) { FileSystemWatcher watcher = (FileSystemWatcher)sender; NLogUtility.InfoLog(string.Format("文件已变更({0}): {1}\\{2}", e.ChangeType, watcher.Path, watcher.Filter), "OnWatcherChanged", "MultiFileWatcher"); if (OnChange != null) { OnChange(sender, e); } } }
/// <summary> /// 读取文件到UTF8字符串 /// </summary> /// <param name="filePath">含路径的全名</param> /// <returns>字节数组</returns> public static string LoadFileToUTF8String(string filePath) { try { return(File.ReadAllText(filePath, Encoding.UTF8)); } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "LoadFileToUTF8String", "FileUtility"); return(string.Empty); } }
/// <summary> /// 关闭Http请求 /// </summary> /// <param name="request"></param> /// <param name="response"></param> /// <param name="url"></param> /// <param name="statusCode">Http服务器返回的状态码</param> private static void CloseRequestResponse(HttpWebRequest request, HttpWebResponse response, string url, HttpStatusCode statusCode) { try { if (request != null) { request.Abort(); } if (response != null) { response.Close(); } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "CloseRequestResponse", "HttpPostManager", string.Format("{0}{1}StatusCode = {2}", url, Environment.NewLine, statusCode)); } }
/// <summary> /// 监视一个文件 /// </summary> /// <param name="fileName"></param> public void Watch(string fileName) { FileSystemWatcher watcher = new FileSystemWatcher() { Path = Path.GetDirectoryName(fileName), Filter = Path.GetFileName(fileName), NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.Security | NotifyFilters.Attributes, /* 开始监视*/ EnableRaisingEvents = true }; watcher.Created += OnWatcherChanged; watcher.Changed += OnWatcherChanged; watcher.Deleted += OnWatcherChanged; NLogUtility.InfoLog(string.Format("监视文件: {0}\\{1}", watcher.Path, watcher.Filter), "Watch", "MultiFileWatcher"); lock (this) { _watchers.Add(watcher); } }
/// <summary> /// 读取文件到Base64字符串 /// </summary> /// <param name="filePath">含路径的全名</param> /// <returns>字节数组</returns> public static string LoadFileToBase64(string filePath) { try { byte[] fileData = LoadFileToByteArray(filePath); if (fileData == null || fileData.Length == 0) { return(string.Empty); } else { return(fileData.Base64Encode()); } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "LoadFileToBase64", "FileUtility"); return(string.Empty); } }
/// <summary> /// 获取所有网卡的mac物理地址 /// </summary> /// <returns></returns> public static List <string> GetPhysicalAddresss() { List <string> macList = new List <string>(); try { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); // Console.WriteLine("Interface information for {0}.{1} ", computerProperties.HostName, computerProperties.DomainName); if (nics == null || nics.Length < 1) { // Console.WriteLine(" No network interfaces found."); return(null); } // Console.WriteLine(" Number of interfaces ... : {0}", nics.Length); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); // Console.WriteLine(); // Console.WriteLine(adapter.Description); // Console.WriteLine(string.Empty.PadLeft(adapter.Description.Length, '=')); // Console.WriteLine(" Interface type ......... : {0}", adapter.NetworkInterfaceType); // Console.Write(" Physical address ....... : "); PhysicalAddress address = adapter.GetPhysicalAddress(); byte[] bytes = address.GetAddressBytes(); var mac = StringEncode.ByteArrayToHexString(bytes); if (!string.IsNullOrEmpty(mac) && adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback) { macList.Add(mac); } // Console.WriteLine(mac); } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetPhysicalAddresss", "NetworkInterfaceHelper"); } return(macList); }
/// <summary> /// 获取本机所有IPV6地址列表 /// </summary> /// <returns>本机所有IPV6地址列表</returns> public static List <string> GetSelfIpv6List() { List <string> ips = new List <string>(); try { IPHostEntry IpEntry = Dns.GetHostEntry(Dns.GetHostName()); for (int i = 0; i < IpEntry.AddressList.Length; i++) { IPAddress ipa = IpEntry.AddressList[i]; if (ipa.AddressFamily == AddressFamily.InterNetworkV6) { ips.Add(ipa.ToString()); } } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetSelfIpv6List", "IPUtility"); } return(ips); }
/// <summary> /// 将字节数组存入新建文件 /// </summary> /// <param name="filePath">新建文件名</param> /// <param name="fileData">字节数组数据</param> /// <returns></returns> public static bool WriteByteArrayToNewFile(string filePath, byte[] fileData) { bool result = false; if (fileData != null) { try { using (FileStream myFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { myFile.Write(fileData, 0, fileData.Length); myFile.Close(); } result = true; } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "WriteByteArrayToFile", "FileUtility"); } } return(result); }
/// <summary> /// 读取文件到字节数组 /// </summary> /// <param name="filePath">含路径的全名</param> /// <returns>字节数组</returns> public static byte[] LoadFileToByteArray(string filePath) { byte[] fileData = null; try { if (File.Exists(filePath)) { using (FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { BinaryReader br = new BinaryReader(myFile); try { if (myFile.Length > int.MaxValue) { return(null); } fileData = br.ReadBytes((int)myFile.Length); } catch { return(null); } finally { br.Close(); myFile.Close(); } } } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "LoadFileToByteArray", "FileUtility"); return(null); } return(fileData); }
/// <summary> /// 发送邮件,所有参数 /// </summary> /// <param name="subject">标题</param> /// <param name="body">内容</param> /// <param name="priority">邮件优先级</param> /// <param name="isHtml">是否Html</param> /// <param name="mailTo">收件人列表</param> /// <param name="mailBCC">密送人列表</param> /// <param name="attetchments">附件地址列表</param> /// <returns></returns> public static bool SendMail(string subject, string body, MailPriority priority, bool isHtml, string mailTo, string mailBCC, string[] attetchments) { SmtpClient client = new SmtpClient(smtp) { UseDefaultCredentials = false, Credentials = new NetworkCredential(senderUserMail, senderPassword), DeliveryMethod = SmtpDeliveryMethod.Network }; MailMessage message = new MailMessage(); message.Sender = new MailAddress(senderUserMail, senderUserName); message.From = new MailAddress(senderUserMail, senderUserName); message.IsBodyHtml = isHtml; message.Priority = priority; message.BodyEncoding = Encoding.UTF8; // 收件人列表 mailTo = mailTo ?? string.Empty; string[] mails = mailTo.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (mails.Length == 0) { return(false); } foreach (string item in mails) { try { message.To.Add(new MailAddress(item, item)); } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "SendMail", "MailHelper", string.Format("TO:{0}", item)); } } // 密送人列表 mailBCC = mailBCC ?? string.Empty; string[] ccmails = mailBCC.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in ccmails) { try { message.Bcc.Add(new MailAddress(item, item)); } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "SendMail", "MailHelper", string.Format("BCC:{0}", item)); } } message.Subject = subject; message.Body = body; //添加附件 if (attetchments != null) { foreach (string file in attetchments) { if (File.Exists(file)) { message.Attachments.Add(new Attachment(file)); } } } try { client.Send(message); } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "SendMail", "MailHelper", string.Format("邮件内容:{1}{0}{2}", Environment.NewLine, subject, body)); return(false); } return(true); }
/// <summary> /// 提交Http请求,获取数据(基础方法) /// </summary> /// <param name="url">请求地址URL</param> /// <param name="httpMethod">HTTP请求的方法</param> /// <param name="requestContentType">HTTP 标头 Content-type 的值</param> /// <param name="postBytes">要发送的数据</param> /// <param name="responseStatusCode">Http服务器返回的状态码</param> /// <param name="responseTextEncoding">服务器返回的字符编码</param> /// <param name="responseContentType">服务器返回的Content-type 的值</param> /// <param name="httpRequestTimeOut">请求超时时间,不传或小于等于0使用配置中的超时时间</param> /// <param name="maxReadLen">最多读取的字节数</param> /// <returns>返回的二进制数据</returns> public static byte[] HttpRequest(string url, string httpMethod, string requestContentType, byte[] postBytes, out HttpStatusCode responseStatusCode, out Encoding responseTextEncoding, out string responseContentType, int httpRequestTimeOut = 0, /*int httpReadTimeOut = 0,*/ long maxReadLen = 0) { if (httpRequestTimeOut <= 0) { httpRequestTimeOut = Http_Request_TimeOut; } //if (httpReadTimeOut <= 0) // httpReadTimeOut = Http_Read_TimeOut; DateTime startTime = DateTime.Now; responseTextEncoding = Encoding.UTF8; responseStatusCode = (HttpStatusCode)0; responseContentType = string.Empty; byte[] responseData = null; bool isWebException = false; HttpWebRequest request = null; HttpWebResponse response = null; #region 发送请求 try { request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = httpRequestTimeOut; request.UserAgent = userAgent; request.Method = httpMethod; if (httpMethod == "POST") { if (postBytes != null && postBytes.Length > 0) { request.ContentType = requestContentType; request.ContentLength = postBytes.Length; Stream requestStream = request.GetRequestStream(); requestStream.Write(postBytes, 0, postBytes.Length); requestStream.Close(); } } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetPostData", "HttpPostManager", string.Format("{0}:{1}", startTime.ToFullDateTimeWithMsString(), url)); responseStatusCode = (HttpStatusCode)(-1); } #endregion if (responseStatusCode != (HttpStatusCode)(-1) && request != null) { #region 读取返回数据 try { WebException wex = null; try { response = (HttpWebResponse)request.GetResponse(); responseStatusCode = response.StatusCode; } catch (WebException ex) { isWebException = true; if (ex.Response != null) { // 出现Web异常时,使用异常中的响应信息 response = (HttpWebResponse)ex.Response; responseStatusCode = response.StatusCode; } else if (response != null) { responseStatusCode = response.StatusCode; } else if (ex.Status == WebExceptionStatus.Timeout) { responseStatusCode = HttpStatusCode.RequestTimeout; } else { responseStatusCode = (HttpStatusCode)(-1); } wex = ex; NLogUtility.ExceptionLog(wex, "GetPostData", "HttpPostManager", string.Format("WebException-1: {1}{2}{0}StatusCode = {3}", Environment.NewLine, startTime.ToFullDateTimeWithMsString(), url, responseStatusCode)); // 内部服务器错误,不读数据了 if (response != null && response.StatusCode == HttpStatusCode.InternalServerError) { response = null; } } if (response != null) { responseContentType = response.ContentType; if (!string.IsNullOrEmpty(response.CharacterSet)) { try { responseTextEncoding = Encoding.GetEncoding(response.CharacterSet); } catch { } } using (Stream stream = response.GetResponseStream()) { Stream streamForRead; if (response.ContentEncoding == "gzip") // 处理GZip编码的数据 { streamForRead = new GZipStream(stream, CompressionMode.Decompress); } else { streamForRead = stream; } // streamForRead.ReadTimeout = httpReadTimeOut; //接收数据 long responseDataLength = response.ContentLength; if (maxReadLen > 0 && (responseDataLength <= 0 || responseDataLength > maxReadLen)) { responseDataLength = maxReadLen; } if (responseDataLength > 0) { #region 正常读取返回数据 responseData = new byte[responseDataLength]; int len = 10240; // 每次读取10K int startIndex = 0; int readSize = 0; while (startIndex < responseDataLength) { readSize = (startIndex + len < responseDataLength) ? len : (int)responseDataLength - startIndex; int intRead = streamForRead.Read(responseData, startIndex, readSize); // 没有数据读了,不再判断 startIndex < responseDataLength,防止 response.ContentLength 不正确造成死循环 if (intRead <= 0) { break; } startIndex += intRead; } #endregion } else { #region 没有长度信息 // 使用MemoryStream来缓存后再读到数组缓存里 MemoryStream msTmp = new MemoryStream(); int readBytesTmp = 0; byte[] bufTmp = new byte[10240]; do { readBytesTmp = streamForRead.Read(bufTmp, 0, 10240); msTmp.Write(bufTmp, 0, readBytesTmp); }while (readBytesTmp > 0); msTmp.Position = 0; responseData = new byte[msTmp.Length]; msTmp.Read(responseData, 0, (int)msTmp.Length); // 以UTF8或HTTP指定的编码读取数据 //using (StreamReader sr = new StreamReader(streamForRead, responseTextEncoding)) //{ // if (sr != null) // { // string theText = sr.ReadToEnd(); // responseData = responseTextEncoding.GetBytes(theText); // } //} #endregion } CloseRequestResponse(request, response, url, responseStatusCode); } } if (isWebException && wex != null && responseData != null) { string exStr = string.Empty; if (responseData != null) { exStr = responseTextEncoding.GetString(responseData); } NLogUtility.ExceptionLog(wex, "GetPostData", "HttpPostManager", string.Format("WebException-2: {1}{0}{2}", Environment.NewLine, startTime.ToFullDateTimeWithMsString(), exStr)); } } catch (Exception ex) { if (response != null) { responseStatusCode = response.StatusCode; } else { responseStatusCode = (HttpStatusCode)(-1); } responseData = null; NLogUtility.ExceptionLog(ex, "GetPostData", "HttpPostManager", string.Format("WebException-1: {1}{2}{0}StatusCode = {3}", Environment.NewLine, startTime.ToFullDateTimeWithMsString(), url, responseStatusCode)); } #endregion } CloseRequestResponse(request, response, url, responseStatusCode); return(responseData); }
/// <summary> /// 通过Post提交带用户名密码验证头部的Http请求并获取返回值(仅用于调用91豆商城接口) /// </summary> /// <param name="url">Url地址</param> /// <param name="paramList">调用参数</param> /// <param name="userName">用户名</param> /// <param name="password">密码</param> /// <param name="statusCode">Http服务器返回的状态码</param> /// <param name="authResult">认证结果</param> /// <param name="isGetResponse">是否获取结果</param> /// <param name="httpRequestTimeOut">超时时间,不传或小于等于0使用配置中的超时时间</param> /// <returns>接口结果</returns> private static string PostRequest(string url, string paramList, string userName, string password, out HttpStatusCode statusCode, out string authResult, bool isGetResponse = true, int httpRequestTimeOut = 0) { DateTime startTime = DateTime.Now; statusCode = (HttpStatusCode)0; if (httpRequestTimeOut <= 0) { httpRequestTimeOut = Http_Request_TimeOut; } authResult = ""; string postResult = ""; HttpWebRequest request = null; HttpWebResponse response = null; Stream webStream = null; StreamReader sr = null; try { paramList = paramList.Replace(" ", "%20"); byte[] paramListByte = Encoding.UTF8.GetBytes(paramList); request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = httpRequestTimeOut; request.UserAgent = userAgent; request.Method = "POST"; request.ContentType = "Application/x-www-form-urlencoded"; request.ContentLength = paramListByte.Length; if (!string.IsNullOrEmpty(userName)) { SetRequestHeader(userName, password, request); } webStream = request.GetRequestStream(); webStream.Write(paramListByte, 0, paramListByte.Length); webStream.Close(); if (isGetResponse) { response = (HttpWebResponse)request.GetResponse(); statusCode = response.StatusCode; sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8); if (response.Headers["AuthResult"] != null) { authResult = response.Headers["AuthResult"].ToString(); } postResult = sr.ReadToEnd(); } } catch (WebException ex) { if (ex.Response != null) { // 出现Web异常时,使用异常中的响应信息 response = (HttpWebResponse)ex.Response; statusCode = response.StatusCode; } else if (response != null) { statusCode = response.StatusCode; } else if (ex.Status == WebExceptionStatus.Timeout) { statusCode = HttpStatusCode.RequestTimeout; } else { statusCode = (HttpStatusCode)(-1); } NLogUtility.ExceptionLog(ex, "PostRequest", "HttpPostManager", string.Format("WebException-1: {1}{2}{0}StatusCode = {3}", Environment.NewLine, startTime.ToFullDateTimeWithMsString(), url, statusCode)); // 内部服务器错误,不读数据了 if (response != null && response.StatusCode == HttpStatusCode.InternalServerError) { response = null; } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "PostRequest", "HttpPostManager", url + paramList); } finally { if (webStream != null) { webStream.Close(); } if (sr != null) { sr.Close(); } } CloseRequestResponse(request, response, url, statusCode); return(postResult); }
/// <summary> /// 得到枚举类型定义的所有文本 /// </summary> /// <exception cref="NotSupportedException"></exception> /// <param name="enumType">枚举类型</param> /// <param name="sortType">指定排序类型</param> /// <returns>所有定义的文本</returns> public static EnumDescriptionAttribute[] GetFieldTexts(Type enumType, SortType sortType) { EnumDescriptionAttribute[] descriptions = null; try { //// 加锁,防止并发下出错 //lock (lockobj) //{ try { //缓存中没有找到,通过反射获得字段的描述信息 if (!cachedEnum.Contains(enumType.FullName)) { FieldInfo[] fields = enumType.GetFields(); ArrayList edAL = new ArrayList(); foreach (FieldInfo fi in fields) { object[] eds = fi.GetCustomAttributes(typeof(EnumDescriptionAttribute), false); if (eds.Length != 1) { continue; } ((EnumDescriptionAttribute)eds[0]).fieldIno = fi; edAL.Add(eds[0]); } descriptions = (EnumDescriptionAttribute[])edAL.ToArray(typeof(EnumDescriptionAttribute)); if (!cachedEnum.Contains(enumType.FullName)) { cachedEnum.Add(enumType.FullName, descriptions); } } else { descriptions = (EnumDescriptionAttribute[])cachedEnum[enumType.FullName]; } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetFieldTexts", "EnumDescription", string.Format("通过反射获得{0}的字段的描述信息", enumType.Name)); } //} if (descriptions.Length <= 0) { throw new NotSupportedException(string.Format("枚举类型[{0}]未定义属性EnumValueDescription", enumType.Name)); } // 按指定的属性冒泡排序 for (int m = 0; m < descriptions.Length; m++) { // 默认不排序 if (sortType == SortType.Default) { break; } for (int n = m; n < descriptions.Length; n++) { EnumDescriptionAttribute temp; bool swap = false; switch (sortType) { case SortType.Default: break; case SortType.DisplayText: if (string.Compare(descriptions[m].EnumDisplayText, descriptions[n].EnumDisplayText) > 0) { swap = true; } break; case SortType.Rank: if (descriptions[m].EnumRank > descriptions[n].EnumRank) { swap = true; } break; } if (swap) { temp = descriptions[m]; descriptions[m] = descriptions[n]; descriptions[n] = temp; } } } } catch (Exception ex) { NLogUtility.ExceptionLog(ex, "GetFieldTexts", "EnumDescription", enumType.Name); } return(descriptions); }
private void button1_Click(object sender, EventArgs e) { // 代码执行时间测试,采用匿名方法 CodeTimer.Time("NLogUtility.GetLogger", 100000000, () => { NLogUtility.GetLogger("InfoLog"); }); CodeTimer.Time("NLog.LogManager.GetLogger", 100000000, () => { NLog.LogManager.GetLogger("ExceptionLog"); }); }