Utility常用功能类 MD5 ClientIP JS弹窗消息
UTILITY
Utility
1
using System;
2
using System.Collections.Generic;
3
using System.Text;
4
using Microsoft.Practices.EnterpriseLibrary.Logging;
5
using System.Security.Cryptography;
6
using System.Web;
7
using System.Collections;
8
using System.Text.RegularExpressions;
9
using Dart.PowerTCP.SecureMail;
10
using System.Net.Sockets;
11
using System.IO;
12
using System.Data.SqlClient;
13
using System.Data;
14
using System.Collections.Specialized;
15
16
namespace ChinaValue.CommonV2008
17
{
18
/// <summary>
19
/// 常用功能类
20
/// </summary>
21
public class Utility
22
{
23
/// <summary>
24
/// 检测非法Post字符
25
/// </summary>
26
/// <param name="content"></param>
27
/// <returns></returns>
28
public static Boolean ValidatePostContent(String content)
29
{
30
Regex regexBadString = new Regex(@"<\s*?(/form)|(form)|(iframe)|(frame)|(meta)|(script).+?>", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
31
return !regexBadString.Match(content).Success;
32
}
33
34
/// <summary>
35
/// 写错误日志
36
/// </summary>
37
/// <param name="strInformation"></param>
38
/// <param name="strTitle"></param>
39
public static void LogInfo(String strTitle, String strInformation)
40
{
41
LogEntry logEntry = new LogEntry();
42
logEntry.Title = strTitle;
43
logEntry.Message = strInformation;
44
logEntry.Categories.Add("General");
45
logEntry.TimeStamp = DateTime.Now;
46
Logger.Write(logEntry);
47
}
48
49
/// <summary>
50
/// 写指定路径的日志
51
/// </summary>
52
/// <param name="logUrl">日志路径,物理地址</param>
53
/// <param name="title"></param>
54
/// <param name="information"></param>
55
public static void LogInfo(String logUrl, String title, String information)
56
{
57
using (FileStream fs = new FileStream(logUrl, FileMode.Append, FileAccess.Write))
58
{
59
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
60
sw.WriteLine(information);
61
sw.Flush();
62
sw.Close();
63
fs.Close();
64
}
65
}
66
67
/// <summary>
68
/// MD5加密
69
/// </summary>
70
/// <param name="toCryString"></param>
71
/// <returns></returns>
72
public static String MD5(String toCryString)
73
{
74
MD5CryptoServiceProvider hashmd5;
75
hashmd5 = new MD5CryptoServiceProvider();
76
return BitConverter.ToString(hashmd5.ComputeHash(Encoding.Default.GetBytes(toCryString))).Replace("-", "").ToLower();
77
}
78
79
/// <summary>
80
/// 获取客户端的IP地址
81
/// </summary>
82
/// <returns></returns>
83
public static String ClientIP()
84
{
85
//判断是否通过代理服务器上网
86
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
87
{
88
return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); //真实的IP
89
}
90
else
91
{
92
return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
93
}
94
}
95
96
/// <summary>
97
/// 在客户端弹出一个消息框(Page)
98
/// </summary>
99
/// <param name="strMsg">待显示的信息</param>
100
public static void ShowClientMessegeBox(System.Web.UI.Page pageFor, String strMessage)
101
{
102
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("<script>alert(\"");
103
strBuilder.Append(strMessage.Replace("\r\n", "\\r\\n"));
104
strBuilder.Append("\")</script>");
105
pageFor.ClientScript.RegisterStartupScript(pageFor.GetType(), "alertBox", strBuilder.ToString());
106
}
107
108
/// <summary>
109
/// 在客户端弹出一个消息框(UserControl)
110
/// </summary>
111
/// <param name="strMsg">待显示的信息</param>
112
public static void ShowClientMessegeBox(System.Web.UI.UserControl ucFor, String strMessage)
113
{
114
System.Text.StringBuilder strBuilder = new System.Text.StringBuilder("<script>alert(\"");
115
strBuilder.Append(strMessage.Replace("\r\n", "\\r\\n"));
116
strBuilder.Append("\")</script>");
117
ucFor.Page.ClientScript.RegisterStartupScript(ucFor.GetType(), "alertBox", strBuilder.ToString());
118
}
119
120
/// <summary>
121
/// 在客户端跳转页面
122
/// </summary>
123
/// <param name="Url"></param>
124
public static void RedirectAtClient(String redirectUrl)
125
{
126
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
127
HttpContext.Current.Response.Write("location.href='" + redirectUrl + "';");
128
HttpContext.Current.Response.Write("</script>");
129
HttpContext.Current.Response.End();
130
}
131
132
/// <summary>
133
/// 在客户端弹出消息框并跳转
134
/// </summary>
135
/// <param name="pageFor"></param>
136
/// <param name="message">待显示的信息</param>
137
/// <param name="redirectUrl">待跳转的地址</param>
138
public static void ShowClientMessegeBoxAndRedirect(String message, String redirectUrl)
139
{
140
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
141
HttpContext.Current.Response.Write("alert('" + message + "');");
142
HttpContext.Current.Response.Write("location.href='" + redirectUrl + "';");
143
HttpContext.Current.Response.Write("</script>");
144
HttpContext.Current.Response.End();
145
}
146
147
/// <summary>
148
/// 在客户端弹出消息框并关闭窗口
149
/// </summary>
150
/// <param name="message">待显示的信息</param>
151
public static void ShowClientMessegeBoxAndClose(String message)
152
{
153
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
154
HttpContext.Current.Response.Write("alert('" + message + "');");
155
HttpContext.Current.Response.Write("window.close();");
156
HttpContext.Current.Response.Write("</script>");
157
HttpContext.Current.Response.End();
158
}
159
160
161
/// <summary>
162
/// 在客户端弹出消息框并父窗口跳转
163
/// </summary>
164
/// <param name="message">待显示的信息</param>
165
public static void ShowClientMessegeBoxAndRedirectAtParent(String message, String redirectUrl)
166
{
167
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
168
HttpContext.Current.Response.Write("alert('" + message + "');");
169
HttpContext.Current.Response.Write("window.parent.location.href='" + redirectUrl + "';");
170
HttpContext.Current.Response.Write("</script>");
171
HttpContext.Current.Response.End();
172
}
173
174
/// <summary>
175
/// 在客户端关闭新开窗口并刷新Opener
176
/// </summary>
177
/// <param name="pageFor"></param>
178
/// <param name="message">待显示的信息</param>
179
/// <param name="redirectUrl">待跳转的地址</param>
180
public static void CloseAndRefreshOpener()
181
{
182
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
183
HttpContext.Current.Response.Write("window.opener.location.href=window.opener.location.href;");
184
HttpContext.Current.Response.Write("window.focus();");
185
HttpContext.Current.Response.Write("window.opener=null;");
186
HttpContext.Current.Response.Write("window.close();");
187
HttpContext.Current.Response.Write("</script>");
188
HttpContext.Current.Response.End();
189
}
190
191
/// <summary>
192
/// 在客户端刷新Opener
193
/// </summary>
194
/// <param name="pageFor"></param>
195
/// <param name="message">待显示的信息</param>
196
/// <param name="redirectUrl">待跳转的地址</param>
197
public static void RefreshOpener()
198
{
199
HttpContext.Current.Response.Write("<script language=\"javascript\" type=\"text/javascript\">");
200
HttpContext.Current.Response.Write("window.opener.location.href=window.opener.location.href;");
201
HttpContext.Current.Response.Write("window.focus();");
202
HttpContext.Current.Response.Write("</script>");
203
}
204
205
/// <summary>
206
/// 替换瘦文本框中的空格、大于号、小于号以及软回车,自动转换Email、HTTP地址
207
/// </summary>
208
/// <param name="content"></param>
209
/// <returns></returns>
210
public static String EncodeTextBox(String content)
211
{
212
StringBuilder sbContent = new StringBuilder(content);
213
214
sbContent = sbContent.Replace("<", "<");//处理小于号
215
sbContent = sbContent.Replace(">", ">");//处理大于号
216
sbContent = sbContent.Replace("\"", """);//处理双引号
217
218
//替换URL
219
Regex regUrl = new Regex(@"(http:\/\/[\w.]+(\/?\w+)+[.a-zA-Z0-9\?=]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
220
sbContent = new StringBuilder(regUrl.Replace(sbContent.ToString(), "<a href=\"$0\" target=\"_blank\">$0</a>"));
221
222
//替换Email
223
Regex regEmail = new Regex(@"([a-zA-Z_0-9.-]+\@[a-zA-Z_0-9.-]+\.\w+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
224
sbContent = new StringBuilder(regEmail.Replace(sbContent.ToString(), "<a href=\"mailto:$0\">$0</a>"));
225
226
sbContent = sbContent.Replace("\n", "<br />");//处理换行
227
sbContent = sbContent.Replace(" ", " ");//处理空格
228
229
return sbContent.ToString();
230
}
231
232
/// <summary>
233
/// 与EncodeTextBox方法作用相反
234
/// </summary>
235
/// <param name="content"></param>
236
/// <returns></returns>
237
public static String DecodeTextBox(String content)
238
{
239
StringBuilder sbContent = new StringBuilder(Utility.DropHtmlTags(content)); //去掉html标签
240
241
sbContent = sbContent.Replace(""", "\"");//处理双引号
242
sbContent = sbContent.Replace(" ", " ");//处理空格
243
sbContent = sbContent.Replace("<", "<");//处理小于号
244
sbContent = sbContent.Replace(">", ">");//处理大于号
245
sbContent = sbContent.Replace("<br />", "\n");//处理换行
246
247
return sbContent.ToString();
248
}
249
250
/// <summary>
251
/// 对字符串进行Base64编码
252
/// </summary>
253
/// <param name="content"></param>
254
/// <returns></returns>
255
public static String EncodeBase64(String content)
256
{
257
String encode = "";
258
Byte[] bytes = Encoding.Default.GetBytes(content);
259
260
try
261
{
262
encode = Convert.ToBase64String(bytes);
263
}
264
catch
265
{
266
encode = content;
267
}
268
269
return encode;
270
}
271
272
/// <summary>
273
/// 对字符串进行Base64解码
274
/// </summary>
275
/// <param name="content"></param>
276
/// <returns></returns>
277
public static String DecodeBase64(String content)
278
{
279
String decode = "";
280
Byte[] bytes = Convert.FromBase64String(content);
281
282
try
283
{
284
decode = Encoding.Default.GetString(bytes);
285
}
286
catch
287
{
288
decode = content;
289
}
290
291
return decode;
292
}
293
294
/// <summary>
295
/// DES加密
296
/// </summary>
297
/// <param name="pToEncrypt">要加密的字符串</param>
298
/// <param name="sKey">密钥</param>
299
/// <returns></returns>
300
public static String EncodeDES(String pToEncrypt, String sKey)
301
{
302
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
303
304
//把字符串放到byte数组中
305
Byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
306
307
//建立加密对象的密钥和偏移量
308
//原文使用ASCIIEncoding.ASCII方法的GetBytes方法
309
//使得输入密码必须输入英文文本
310
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
311
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
312
MemoryStream ms = new MemoryStream();
313
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
314
315
//Write the byte array into the crypto stream
316
//(It will end up in the memory stream)
317
cs.Write(inputByteArray, 0, inputByteArray.Length);
318
cs.FlushFinalBlock();
319
320
//Get the data back from the memory stream, and into a string
321
StringBuilder ret = new StringBuilder();
322
foreach (Byte b in ms.ToArray())
323
{
324
//Format as hex
325
ret.AppendFormat("{0:X2}", b);
326
}
327
328
ret.ToString();
329
330
return ret.ToString();
331
}
332
333
/// <summary>
334
/// DES解密
335
/// </summary>
336
/// <param name="pToDecrypt">要解密的字符串</param>
337
/// <param name="sKey">密钥</param>
338
/// <returns></returns>
339
public static String DecodeDES(String pToDecrypt, String sKey)
340
{
341
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
342
343
Byte[] inputByteArray = new Byte[pToDecrypt.Length / 2];
344
345
for (Int32 x = 0; x < pToDecrypt.Length / 2; x++)
346
{
347
Int32 i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
348
inputByteArray[x] = (Byte)i;
349
}
350
351
//建立加密对象的密钥和偏移量,此值重要,不能修改
352
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
353
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
354
MemoryStream ms = new MemoryStream();
355
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
356
357
//Flush the data through the crypto stream into the memory stream
358
cs.Write(inputByteArray, 0, inputByteArray.Length);
359
cs.FlushFinalBlock();
360
361
//Get the decrypted data back from the memory stream
362
return Encoding.Default.GetString(ms.ToArray());
363
}
364
365
/// <summary>
366
/// DES与Base64组合加密
367
/// </summary>
368
/// <param name="data"></param>
369
/// <param name="key"></param>
370
/// <returns></returns>
371
public static String EncodeDESAndBase64(String data, String key)
372
{
373
Byte[] byKey = Encoding.Default.GetBytes(key);
374
Byte[] byIV = Encoding.Default.GetBytes(key);
375
376
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
377
Int32 i = cryptoProvider.KeySize;
378
MemoryStream ms = new MemoryStream();
379
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
380
381
StreamWriter sw = new StreamWriter(cst);
382
cst.Write(System.Text.Encoding.Default.GetBytes(data), 0, System.Text.Encoding.Default.GetByteCount(data));
383
sw.Flush();
384
cst.FlushFinalBlock();
385
sw.Flush();
386
387
return Convert.ToBase64String(ms.GetBuffer(), 0, (Int32)ms.Length);
388
}
389
390
/// <summary>
391
/// DES与Base64组合解密
392
/// </summary>
393
/// <param name="data"></param>
394
/// <param name="key"></param>
395
/// <returns></returns>
396
public static String DecodeDESAndBase64(String data, String key)
397
{
398
//把密钥转成二进制数组
399
Byte[] byKey = Encoding.Default.GetBytes(key);
400
Byte[] byIV = Encoding.Default.GetBytes(key);
401
402
Byte[] byEnc;
403
404
try
405
{
406
//base64解码
407
byEnc = Convert.FromBase64String(data);
408
}
409
catch
410
{
411
return null;
412
}
413
414
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
415
MemoryStream ms = new MemoryStream(byEnc);
416
CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
417
StreamReader sr = new StreamReader(cst);
418
Byte[] tmp = new Byte[ms.Length];
419
cst.Read(tmp, 0, tmp.Length);
420
String result = System.Text.Encoding.Default.GetString(tmp);
421
422
return result;
423
}
424
425
/// <summary>
426
/// 数组转换为ArrayList
427
/// </summary>
428
/// <param name="array">待转换的数组</param>
429
/// <returns></returns>
430
public static ArrayList ArrayToArrayList(String[] array)
431
{
432
ArrayList arrayList = new ArrayList();
433
434
for (Int32 i = 0; i < array.Length; i++)
435
{
436
arrayList.Add(array[i]);
437
}
438
439
return arrayList;
440
}
441
442
/// <summary>
443
/// 数组转换为ArrayList
444
/// </summary>
445
/// <param name="array">待转换的数组</param>
446
/// <returns></returns>
447
public static ArrayList ArrayToArrayList(Char[] array)
448
{
449
ArrayList arrayList = new ArrayList();
450
451
for (Int32 i = 0; i < array.Length; i++)
452
{
453
arrayList.Add(array[i]);
454
}
455
456
return arrayList;
457
}
458
459
/// <summary>
460
/// 截断字符串,截断结果的长度将不会超过制定的最大长度
461
/// </summary>
462
/// <param name="strContent"></param>
463
/// <param name="intMaxLength"></param>
464
/// <returns></returns>
465
public static String CompressString(String strContent, Int32 intMaxLength)
466
{
467
return CompressString(strContent, intMaxLength, true);
468
}
469
470
/// <summary>
471
/// 截断字符串,截断结果的长度将不会超过制定的最大长度,并且可以指定是否添加省略号
472
/// </summary>
473
/// <param name="strContent"></param>
474
/// <param name="intMaxLength"></param>
475
/// <param name="appendSuffix"></param>
476
/// <returns></returns>
477
public static String CompressString(String strContent, Int32 intMaxLength, Boolean appendSuffix)
478
{
479
if (String.IsNullOrEmpty(strContent))
480
{
481
return String.Empty;
482
}
483
else
484
{
485
int intUnicodeLength = 0;
486
int intCharCount = 0;
487
for (Int32 i = 0; i < strContent.Length && intUnicodeLength < intMaxLength; i++)
488
{
489
if (strContent[i] > 255)
490
intUnicodeLength += 2;
491
else
492
intUnicodeLength++;
493
494
intCharCount++;
495
}
496
497
if (intUnicodeLength >= intMaxLength)
498
{
499
if (appendSuffix)
500
{
501
return strContent.Substring(0, intCharCount) + "…";
502
}
503
else
504
{
505
return strContent.Substring(0, intCharCount);
506
}
507
}
508
else
509
{
510
return strContent;
511
}
512
}
513
}
514
515
/// <summary>
516
/// 去掉字符串中的所有空格
517
/// </summary>
518
/// <param name="HtmlText"></param>
519
/// <returns></returns>
520
public static String DropBlanks(string HtmlText)
521
{
522
if (!String.IsNullOrEmpty(HtmlText))
523
{
524
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"[\s| ]", System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.Compiled);
525
return reg.Replace(HtmlText, string.Empty).Replace(" ", " ");
526
}
527
else
528
{
529
return String.Empty;
530
}
531
}
532
533
/// <summary>
534
/// 去除Html"标签"
535
/// </summary>
536
/// <param name="HtmlText"></param>
537
/// <returns></returns>
538
public static String DropHtmlTags(string HtmlText)
539
{
540
if (string.IsNullOrEmpty(HtmlText))
541
{
542
return String.Empty;
543
}
544
else
545
{
546
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"<.*?>", System.Text.RegularExpressions.RegexOptions.Singleline | System.Text.RegularExpressions.RegexOptions.Compiled);
547
return reg.Replace(HtmlText, string.Empty);
548
}
549
}
550
551
/// <summary>
552
/// 发送邮件(账户友好名称为:“价值中国网”)
553
/// </summary>
554
/// <param name="userID">邮件发送目的用户ID</param>
555
/// <param name="subject">邮件主题</param>
556
/// <param name="body">邮件内容</param>
557
/// <returns></returns>
558
public static Boolean SendMail(Int32 userID, String subject, String body)
559
{
560
SqlParameter[] para = new SqlParameter[1];
561
para[0] = new SqlParameter("@ID", SqlDbType.Int, 4);
562
para[0].Value = userID;
563
564
String sqlStr = "SELECT Email FROM huiyuan WHERE [ID] = @ID";
565
566
Object objEmail = SqlHelper.ExecuteScalar(WebConfig.ConnStrWWW, CommandType.Text, sqlStr, para);
567
568
if (objEmail != null)
569
{
570
return SendMail("价值中国网", objEmail.ToString(), subject, body);
571
}
572
573
return false;
574
}
575
576
/// <summary>
577
/// 发送邮件(账户友好名称为:“价值中国网”)
578
/// </summary>
579
/// <param name="toEmail">邮件发送目的Email</param>
580
/// <param name="subject">邮件主题</param>
581
/// <param name="body">邮件内容</param>
582
/// <returns></returns>
583
public static Boolean SendMail(String toEmail, String subject, String body)
584
{
585
return SendMail("价值中国网", toEmail, subject, body);
586
}
587
588
/// <summary>
589
/// 发送邮件
590
/// </summary>
591
/// <param name="fromFriendlyName">收件人看到的友好名称</param>
592
/// <param name="toEmail">邮件发送目的Email</param>
593
/// <param name="subject">邮件主题</param>
594
/// <param name="body">邮件内容</param>
595
/// <returns></returns>
596
public static Boolean SendMail(String fromFriendlyName, String toEmail, String subject, String body)
597
{
598
return SendMail(fromFriendlyName, WebConfig.SMTPMailAccount, toEmail, subject, body);
599
}
600
601
/// <summary>
602
/// 发送邮件
603
/// </summary>
604
/// <param name="fromFriendlyName">收件人看到的友好名称</param>
605
/// <param name="fromFriendlyMail">收件人看到的友好Email</param>
606
/// <param name="toEmail">邮件发送目的Email</param>
607
/// <param name="subject">邮件主题</param>
608
/// <param name="body">邮件内容</param>
609
/// <returns></returns>
610
public static Boolean SendMail(String fromFriendlyName, String fromFriendlyMail, String toEmail, String subject, String body)
611
{
612
Boolean sendResult = false;
613
614
String fromTrueUser = WebConfig.SMTPMailAccount.Substring(0, WebConfig.SMTPMailAccount.IndexOf('@'));
615
String fromTrueDomain = WebConfig.SMTPMailAccount.Substring(WebConfig.SMTPMailAccount.IndexOf('@') + 1, WebConfig.SMTPMailAccount.Length - fromTrueUser.Length - 1);
616
617
String fromUser = fromFriendlyMail.Substring(0, fromFriendlyMail.IndexOf('@'));
618
String fromDomain = fromFriendlyMail.Substring(fromFriendlyMail.IndexOf('@') + 1, fromFriendlyMail.Length - fromUser.Length - 1);
619
620
Smtp smtpServer = new Smtp();
621
smtpServer.UseAuthentication = true;
622
smtpServer.Server = WebConfig.SMTPServerAddress;
623
smtpServer.Username = WebConfig.SMTPUserName;
624
smtpServer.Password = WebConfig.SMTPPassword;
625
smtpServer.MailFrom = new MailAddress(fromFriendlyName, fromTrueUser, fromTrueDomain);
626
627
StringBuilder sbMailBody = new StringBuilder();
628
sbMailBody.Append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\" /><body>");
629
sbMailBody.Append(body);
630
sbMailBody.Append("</body></html>");
631
632
MessageStream msgStream = new MessageStream();
633
msgStream.Type = "text/html";
634
msgStream.From.Domain = fromDomain;
635
msgStream.From.User = fromUser;
636
msgStream.From.Friendly = fromFriendlyName;
637
msgStream.To.Add(new MailAddress(toEmail));
638
639
msgStream.Charset = "gb2312";
640
//以下各种时间格式都会造成用户收到的邮件时间不准,暂时没有好的解决办法
641
//msgStream.Date = DateTime.Now.ToString("r") + " +0800";
642
//msgStream.Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
643
//msgStream.Date = DateTime.Now.ToString("g");
644
//msgStream.Date = DateTime.Now.ToString();
645
msgStream.Mailer = "www.chinavalue.net";
646
647
msgStream.Subject = subject;
648
msgStream.Text = sbMailBody.ToString();
649
650
try
651
{
652
smtpServer.Send(msgStream);
653
smtpServer.Close();
654
655
sendResult = true;
656
}
657
catch (ProtocolException exProtocol)
658
{
659
//TODO: Log exception
660
Utility.LogInfo("ChinaValue.Info.Common.SendMail Error", exProtocol.ToString());
661
}
662
catch (SocketException exSocket)
663
{
664
//TODO: Log exception
665
Utility.LogInfo("ChinaValue.Info.Common.SendMail Error", exSocket.ToString());
666
}
667
catch (IOException exIO)
668
{
669
//TODO: Log IOException
670
Utility.LogInfo("ChinaValue.Info.Common.SendMail Error", exIO.ToString());
671
}
672
catch (ArgumentException exArg)
673
{
674
//TODO: Log Argument Exception
675
Utility.LogInfo("ChinaValue.Info.Common.SendMail Error", exArg.ToString());
676
}
677
678
return sendResult;
679
}
680
681
/// <summary>
682
/// 发送站内信息
683
/// </summary>
684
/// <param name="intFromUserId">发送用户的ID</param>
685
/// <param name="intToUserId">接收用户的ID</param>
686
/// <param name="msgSubject">消息标题</param>
687
/// <param name="msgBody">消息内容</param>
688
/// <returns></returns>
689
public static Boolean SendMessage(Int32 fromUserID, Int32 toUserID, String msgSubject, String msgBody)
690
{
691
return SendMessage(fromUserID, toUserID, msgSubject, msgBody, String.Empty);
692
}
693
694
/// <summary>
695
/// 发送系统消息
696
/// </summary>
697
/// <param name="toUserID">接收用户的ID</param>
698
/// <param name="msgSubject">消息标题</param>
699
/// <param name="msgBody">消息内容</param>
700
/// <returns></returns>
701
public static Boolean SendMessage(Int32 toUserID, String msgSubject, String msgBody)
702
{
703
return SendMessage(0, toUserID, msgSubject, msgBody, "价值中国");
704
}
705
706
/// <summary>
707
/// 发送站内信息
708
/// </summary>
709
/// <param name="fromUserID">发送用户的ID</param>
710
/// <param name="toUserID">接收用户的ID</param>
711
/// <param name="msgSubject">消息标题</param>
712
/// <param name="msgBody">消息内容</param>
713
/// <param name="systemUserName">系统消息的发送者姓名</param>
714
/// <returns></returns>
715
public static Boolean SendMessage(Int32 fromUserID, Int32 toUserID, String msgSubject, String msgBody, String systemUserName)
716
{
717
SqlParameter[] para = new SqlParameter[5];
718
para[0] = new SqlParameter("@title", SqlDbType.NText);
719
para[0].Value = msgSubject;
720
para[1] = new SqlParameter("@content", SqlDbType.NText);
721
para[1].Value = msgBody;
722
para[2] = new SqlParameter("@toUserID", SqlDbType.Int, 4);
723
para[2].Value = toUserID;
724
para[3] = new SqlParameter("@fromUserID", SqlDbType.Int, 4);
725
para[3].Value = fromUserID;
726
para[4] = new SqlParameter("@systemUserName", SqlDbType.NVarChar, 20);
727
para[4].Value = systemUserName;
728
729
if (SqlHelper.ExecuteNonQuery(WebConfig.DBConnectionString, CommandType.StoredProcedure, "pr_Message_Send", para) > 0)
730
{
731
return true;
732
}
733
734
return false;
735
}
736
737
/// <summary>
738
/// 发送站内消息 + Email
739
/// </summary>
740
/// <param name="toUserID">收件人ID</param>
741
/// <param name="subject">消息主题</param>
742
/// <param name="body">消息内容</param>
743
/// <returns></returns>
744
public static Boolean SendMailAndMessage(Int32 toUserID, String subject, String body)
745
{
746
return SendMail(toUserID, subject, body) & SendMessage(toUserID, subject, body);
747
}
748
749
/// <summary>
750
/// 清除Word冗余格式
751
/// </summary>
752
/// <param name="str"></param>
753
/// <returns></returns>
754
public static string CleanWordStyle(String str)
755
{
756
StringCollection sc = new StringCollection();
757
758
// get rid of unnecessary tag spans (comments and title)
759
sc.Add(@"<!--(\w|\W)+?-->");
760
sc.Add(@"<title>(\w|\W)+?</title>");
761
762
// Get rid of classes and styles
763
sc.Add(@"\s?class=\w+");
764
sc.Add(@"\s+style='[^']+'");
765
766
// Get rid of unnecessary tags
767
sc.Add(
768
@"<(meta|link|/?o:|/?style|/?st\d|/?head|/?html|body|/?body|/?span|!\[)[^>]*?>");
769
770
// Get rid of empty paragraph tags
771
sc.Add(@"(<[^>]+>)+ (</\w+>)+");
772
773
// remove bizarre v: element attached to <img> tag
774
sc.Add(@"\s+v:\w+=""[^""]+""");
775
776
// remove extra lines
777
sc.Add(@"(\n\r){2,}");
778
779
// remove font tags
780
sc.Add(@"</?font.*?>");
781
782
// remove font tags
783
sc.Add(@"</?b\W+.*?>");
784
785
// remove font tags
786
sc.Add(@"<\?xml.*?>");
787
788
foreach (String s in sc)
789
{
790
str = Regex.Replace(str, s, "", RegexOptions.IgnoreCase | RegexOptions.Multiline);
791
}
792
793
String pattern = @"<p.*?>";
794
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
795
str = reg.Replace(str, "<p>");
796
797
pattern = @"<div.*?>";
798
reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
799
str = reg.Replace(str, "<div>");
800
801
return str;
802
}
803
804
/// <summary>
805
/// 检测操作是否已进行,用于限制规定时间内只能进行一次的操作
806
/// </summary>
807
/// <param name="key">用户监测的Cookie、Session键</param>
808
/// <param name="expireTime">下次操作的间隔时间(分钟)</param>
809
/// <param name="userSession">是否启用Session(默认只用Cookie)</param>
810
/// <returns></returns>
811
public static Boolean OperationDone(String key, Int32 expireTime, Boolean userSession)
812
{
813
if (!String.IsNullOrEmpty(CVCookie.Read(key))) //Cookie最省服务器资源,Cookie存在的情况下,直接返回-1,不再继续
814
{
815
return true;
816
}
817
818
if (userSession)
819
{
820
if (HttpContext.Current.Session[key] != null)
821
{
822
if (!String.IsNullOrEmpty(HttpContext.Current.Session[key].ToString()))
823
{
824
return true;
825
}
826
}
827
}
828
829
//Cookie、Session的默认值
830
String defaultValue = "1";
831
832
CVCookie.Set(key, defaultValue, expireTime * 60); //expireTime秒内只能操作一次
833
834
if (userSession)
835
{
836
HttpContext.Current.Session.Timeout = expireTime;
837
HttpContext.Current.Session[key] = defaultValue; //用Session可以避免Cookie被删除
838
}
839
840
return false;
841
}
842
843
/// <summary>
844
/// 检测操作是否已进行,用于限制规定时间内只能进行一次的操作(Cookie、Session并用)
845
/// </summary>
846
/// <param name="key">用户监测的Cookie、Session键</param>
847
/// <param name="expireTime">下次操作的间隔时间(秒)</param>
848
/// <returns></returns>
849
public static Boolean OperationDone(String key, Int32 expireTime)
850
{
851
return OperationDone(key, expireTime, true);
852
}
853
}
854
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

Ajax.jQuery.Java.