CommonFunction 中的方法 随机数字,验证 等

View Code
  1 using System;

  2 using System.Collections;

  3 using System.Collections.Generic;

  4 using System.Linq;

  5 using System.Text;

  6 using System.Text.RegularExpressions;

  7 using System.Web;

  8 using System.Data;

  9 using System.Data.SqlClient;

 10 using System.Web.UI;

 11 using System.IO;

 12 

 13 

 14 namespace TopWin.DongFengYL.SQLMemberShip.Utility

 15 {

 16     public class CommonFunction

 17     {

 18         /// <summary>

 19         /// 截取字符串方法

 20         /// </summary>

 21         /// <param name="str"></param>

 22         /// <param name="len"></param>

 23         /// <param name="withToken"></param>

 24         /// <returns></returns>

 25         public static string SubStringByLength(ref string str, int len, bool withToken)

 26         {

 27             char[] charArray = str.ToCharArray();

 28             StringBuilder builder = new StringBuilder(len + 10);

 29             int n = 0;

 30             bool isCut = false;

 31             int clen = charArray.Length;

 32             for (int i = 0; i != clen; ++i)

 33             {

 34                 if ((charArray[i] >= 0x4E00 && charArray[i] <= 0x9FA5) || (charArray[i] > 65280 && charArray[i] < 65375))

 35                 {

 36                     n += 2;

 37                     if (n > len)

 38                     {

 39                         isCut = true;

 40                         break;

 41                     }

 42                     builder.Append(charArray[i]);

 43                 }

 44                 else

 45                 {

 46                     ++n;

 47                     if (n > len)

 48                     {

 49                         isCut = true;

 50                         break;

 51                     }

 52                     builder.Append(charArray[i]);

 53                 }

 54 

 55             }

 56             builder.Append(isCut ? withToken ? "..." : string.Empty : string.Empty);

 57             return builder.ToString();

 58         }

 59 

 60         /// <summary>

 61         /// 替换HTML代码中图片的相对路径为绝对路径

 62         /// </summary>

 63         /// <param name="htmlValue">HTML代码</param>

 64         /// <param name="absPath">绝对路径</param>

 65         /// <returns></returns>

 66         public static string ReplaceVirtualImgPath(string htmlValue, string absPath)

 67         {

 68             string regexp = "src=[\"']/";

 69             string token = Guid.NewGuid().ToString();

 70             string repString = System.Text.RegularExpressions.Regex.Replace(htmlValue, regexp, token);

 71             MatchCollection mc = Regex.Matches(htmlValue, regexp, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

 72             int offset1 = 0;

 73             int offset2 = 0;

 74             int len = repString.Length;

 75             StringBuilder builder = new StringBuilder(15000);

 76             IEnumerator iterator = mc.GetEnumerator();

 77             while (iterator.MoveNext())

 78             {

 79                 Match m = iterator.Current as Match;

 80                 offset2 = repString.IndexOf(token, offset1);

 81                 if (offset2 + token.Length > len) break;

 82                 string tempStr = repString.Substring(offset1, offset2 - offset1 + token.Length);

 83                 string url = Regex.Replace(m.Value, "/", absPath);

 84                 builder.Append(tempStr.Replace(token, url));

 85                 offset1 = offset2 + token.Length;

 86             }

 87 

 88             if (offset1 < repString.Length)

 89             {

 90                 builder.Append(repString.Substring(offset1, repString.Length - offset1));

 91             }

 92 

 93             return builder.ToString();

 94         }

 95 

 96         /// <summary>

 97         /// 获取HTML代码中图片的路径

 98         /// </summary>

 99         /// <param name="htmlValue"></param>

100         /// <returns></returns>

101         public static ArrayList GetImgTagSrc(string htmlValue)

102         {

103             ArrayList resultList = new ArrayList();

104             string regexp = @"<IMG[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>";

105             MatchCollection mc = Regex.Matches(htmlValue, regexp, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

106             foreach (Match m in mc)

107             {

108                 resultList.Add(m.Groups["src"].Value.ToLower());

109             }

110             if (resultList.Count == 0)

111             {

112                 resultList.Add(string.Empty);

113             }

114             return resultList;

115         }

116 

117         /// <summary>

118         /// 将包含HTML标记的字符串去掉HTML标记之后按指定长度截取

119         /// </summary>

120         /// <param name="original"></param>

121         /// <param name="length"></param>

122         /// <returns></returns>

123         public static string TrimString(string original, int length)

124         {

125             string str = string.Empty;

126             string tempStr = original;

127             System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("(<\\s*[a-zA-Z][^>]*>)|(</\\s*[a-zA-Z][^>]*>)|(\\s)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);

128             if (original.Length > 0)

129             {

130                 tempStr = reg.Replace(original, "").Trim();

131             }

132 

133             int sLen = tempStr.Length;

134             if (length == 0)

135             {

136                 str = tempStr;

137             }

138             else

139             {

140                 if (sLen <= length || sLen == length + 2 || sLen == length + 1)

141                 {

142                     str = tempStr;

143                 }

144                 else

145                 {

146                     str = tempStr.Substring(0, length) + "...";

147                 }

148             }

149             return str;

150         }

151 

152         public static string ToHtmlLF(string input)

153         {

154             return input.Replace("\r\n", @"<br/>").Replace("\n", @"<br/>").Replace(" ", "&nbsp");

155         }

156 

157         public static string GetGenGuid()

158         {

159             string genGuid = Guid.NewGuid().ToString().Replace("-", string.Empty);

160             return genGuid;

161         }

162 

163         public static string GetCurWebUrl(string webUrl)

164         {

165             string[] stages = webUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

166             if (webUrl.IndexOf("http://", StringComparison.CurrentCultureIgnoreCase) == 0)

167             {

168                 return stages[0] + "//" + stages[1] + "/" + stages[2];

169             }

170             else

171             {

172                 return stages[0] + "/" + stages[1];

173             }

174         }

175 

176         public static string GetFolderUrl(string serverRelationUrl)

177         {

178             string targetUrl = string.Empty;

179             string[] stages = serverRelationUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

180             targetUrl = serverRelationUrl.Substring(stages[0].Length + 1, serverRelationUrl.Length - (stages[0].Length + 1));

181             return targetUrl;

182         }

183 

184         public static string GetCurSiteUrl(string webUrl)

185         {

186             string[] stages = webUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

187             if (webUrl.IndexOf("http://", StringComparison.CurrentCultureIgnoreCase) == 0)

188             {

189                 return stages[0] + "//" + stages[1];

190             }

191             else

192             {

193                 return stages[0];

194             }

195         }

196 

197         /// <summary>

198         /// 消息对话框alert

199         /// </summary>

200         /// <param name="page"></param>

201         /// <param name="message"></param>

202         public static void ShowMessage(Page page, string message)

203         {

204             page.ClientScript.RegisterStartupScript(

205                 page.GetType(),

206                 Guid.NewGuid().ToString(),

207                 string.Format(@"<script language=javascript>alert(""{0}"");</script>",

208                               message.Replace(@"""", "'").Replace("\r\n", @"\n").Replace("\n", @"\n").Replace("\\",

209                                                                                                               "\\\\").

210                                   Replace(@"\\n", @"\n")));

211         }

212 

213         /// <summary>

214         /// 消息对话框 alert

215         /// </summary>

216         /// <param name="page"></param>

217         /// <param name="message"></param>

218         /// <param name="target"></param>

219         public static void ShowMessage(Page page, string message, string target)

220         {

221             page.ClientScript.RegisterStartupScript(

222                 page.GetType(),

223                 Guid.NewGuid().ToString(),

224                 string.Format(@"<script language=javascript>alert(""{0}"");window.location.href=""{1}"";</script>",

225                               message.Replace(@"""", "'").Replace("\r\n", @"\n").Replace("\n", @"\n").Replace("\\",

226                                                                                                               "\\\\").

227                                   Replace(@"\\n", @"\n"), target));

228         }

229 

230 

231 

232 

233         /// <summary>

234         /// 获取复杂性要求随机数

235         /// </summary>

236         /// <param name="VcodeNum"></param>

237         /// <returns></returns>

238         public static string RndNumADComplex(int VcodeNum)

239         {

240             string strValue = "!,$,#,%";

241             string[] valueArray = strValue.Split(new char[] { ',' });

242             Random rand = new Random();

243             int t = rand.Next(4);

244             string strNum = RndNum(VcodeNum);

245             if (strNum.Length > 1)

246             {

247                 strNum = strNum.Substring(0, strNum.Length - 1);

248                 strNum = strNum + valueArray[t];

249             }

250             return strNum;

251         }

252 

253         /// <summary>

254         /// 获取随机数

255         /// </summary>

256         /// <param name="VcodeNum">随机数位数</param>

257         /// <returns></returns>

258         public static string RndNum(int VcodeNum)

259         {

260             string strValue = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";

261             string[] valueArray = strValue.Split(new char[] { ',' });

262             string strNum = string.Empty;

263             int temp = -1;

264 

265             Random rand = new Random();

266             for (int i = 1; i < VcodeNum + 1; i++)

267             {

268                 if (temp != -1)

269                 {

270                     rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));

271                 }

272                 int t = rand.Next(62);

273                 if (temp != -1 && temp == t)

274                 {

275                     return RndNum(VcodeNum);

276                 }

277                 temp = t;

278                 strNum += valueArray[t];

279             }

280             return strNum;

281         }

282 

283         /// <summary>

284         /// 获取图片中的第一张图片

285         /// </summary>

286         /// <param name="content">内容</param>

287         /// <returns></returns>

288         public static string GetFirstImgUrlFromContent(string content)

289         {

290             string imgUrl = string.Empty;

291             try

292             {

293                 string str = @"<IMG[^>]+src=\s*(?:'(?<src>[^']+)'|""(?<src>[^""]+)""|(?<src>[^>\s]+))\s*[^>]*>";

294                 MatchCollection mc = Regex.Matches(content, str, RegexOptions.Multiline | RegexOptions.IgnoreCase | RegexOptions.Compiled);

295                 if (mc.Count > 0)

296                 {

297                     imgUrl = mc[0].Groups["src"].Value.ToLower();

298                 }

299             }

300             catch

301             {

302             }

303             return imgUrl;

304         }

305 

306 

307         /// <summary>

308         /// 判断用户是否在预算管控组

309         /// </summary>

310         /// <returns></returns>

311         public bool UserIstrBudgetMan(string userAccount)

312         {

313             IDbConnection conn = Config.Instance.CreateDbConnection();

314             conn.Open();

315 

316             SqlParameter[] aParms = new SqlParameter[]

317             {

318                 new SqlParameter("@userAccount",userAccount)

319             };

320             DataSet ds = DbHelper.ExecuteDataset(conn, CommandType.StoredProcedure, "sp_DY_UserIstrBudgetMan", aParms);

321 

322             if (ds != null && ds.Tables[0].Rows.Count != 0)

323                 return true;

324             else

325                 return false;

326         }

327         /// <summary>

328         /// 判断文件是否存在,如果存在删除

329         /// </summary>

330         /// <param name="path"></param>

331         /// <returns></returns>

332         public static void IsExsiteDelFile(string path)

333         {

334             if (File.Exists(path))

335             {

336                 File.Delete(path);

337             }

338         }

339         public static string CreateDirectory(string path)

340         {

341             if (!Directory.Exists(path))

342             {

343                 Directory.CreateDirectory(path);

344             }

345             return path;

346         }

347         /// <summary>

348         /// 删除UserCopyImport文件夹中七天之前的文件

349         /// </summary>

350         /// <returns></returns>

351         public static void DeleteFilesForOverServeDays()

352         {

353             Config config = new Config();

354             TimeSpan ts1 = new TimeSpan(DateTime.Now.Ticks);

355             string directoryPath = System.Web.HttpContext.Current.Server.MapPath(config.GetUserCopyImportPath());

356             string overDays = config.GetUserCopyImportFilesOverDays();

357             DirectoryInfo mydir = new DirectoryInfo(directoryPath);

358             foreach (FileSystemInfo fsi in mydir.GetFileSystemInfos())

359             {

360                 if (fsi is FileInfo)

361                 {

362                     FileInfo fi = (FileInfo)fsi;

363                     DateTime dt = DateTime.ParseExact(fi.Name.ToString().Split('.')[0], "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture);

364                     TimeSpan ts2 = new TimeSpan(dt.Ticks);

365 

366                     if (ts1.Subtract(ts2).Duration().Days >= Convert.ToInt32(overDays))

367                     {

368                         fi.Delete();

369                     }

370                 }

371             }

372         }

373         public static string GetNums()

374         {

375             string arr = "0,1,2,3,4,5,6,7,8,9";

376             return GenerateRandomNumber(arr, 4);

377         }

378         public static string GetChars()

379         {

380             string arr = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";

381             return GenerateRandomNumber(arr, 3);

382         }

383         public static string GetSpecialChars()

384         {

385             string arr = "~,!,@,#,¥,%,&,*,(,),+,=,{,},|";

386             return GenerateRandomNumber(arr, 1);

387         }

388         public static string GenerateRandomNumber(string content, int Length)

389         {

390             string[] constant = content.Split(',');

391             System.Text.StringBuilder newRandom = new System.Text.StringBuilder(8);

392             Random rd = new Random();

393             for (int i = 0; i < Length; i++)

394             {

395                 newRandom.Append(constant[rd.Next(constant.Length)]);

396             }

397             return newRandom.ToString();

398         }

399         /// <summary>

400         /// 自动生成密码

401         /// </summary>

402         /// <returns></returns>

403         public static string GetPassword()

404         {

405             return GetNums() + GetChars() + GetSpecialChars();

406         }

407 

408         /// <summary>

409         /// 检查密码是否通过正则表达式验证

410         /// </summary>

411         public static bool IsMatchRight(string inValue,string reg)

412         {

413             string emailPattern = @"" + reg + "";

414             bool match = Regex.IsMatch(inValue, emailPattern);

415             return match;

416         }

417     }

418 }

 

你可能感兴趣的:(function)