PageRenderTime 114ms CodeModel.GetById 24ms RepoModel.GetById 6ms app.codeStats 0ms

/projects/PigeonCms.Core/Helpers/Utility.cs

http://pigeoncms.googlecode.com/
C# | 1647 lines | 1335 code | 118 blank | 194 comment | 162 complexity | ec1373aa34e3576925b0b0aa82e4116e MD5 | raw file
Possible License(s): LGPL-3.0, GPL-3.0, LGPL-2.1, GPL-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.IO;
  13. using System.Web.Routing;
  14. using System.Threading;
  15. using System.Text.RegularExpressions;
  16. using System.Collections.Specialized;
  17. using System.Collections;
  18. using System.Security.Cryptography;
  19. namespace PigeonCms
  20. {
  21. /// <summary>
  22. /// Useful static functions
  23. /// </summary>
  24. public static class Utility
  25. {
  26. /// <summary>
  27. /// useful methods to manage to work with html
  28. /// </summary>
  29. public class Html
  30. {
  31. /// <summary>
  32. /// parse textToParse filling existing [[placeholders]] e {{session_vars}}
  33. /// </summary>
  34. /// <param name="textToParse">text to parse</param>
  35. /// <returns>text parsed</returns>
  36. public static string FillPlaceholders(string textToParse)
  37. {
  38. string key = "";
  39. string value = "";
  40. if (!string.IsNullOrEmpty(textToParse))
  41. {
  42. //fill placeholders
  43. //ex: [[yourname]] --> nicola
  44. Regex regPlace = new Regex("(\\[\\[[a-zA-Z_][a-zA-Z0-9_]+\\]\\])");
  45. string[] placeholderTags;
  46. placeholderTags = regPlace.Split(textToParse);
  47. for (int i = 0; i < placeholderTags.Length; i++)
  48. {
  49. key = placeholderTags[i];
  50. if (key.StartsWith("[[") && key.EndsWith("]]"))
  51. {
  52. key = key.Remove(0, 2);
  53. key = key.Remove(key.Length - 2);
  54. value = "";
  55. Placeholder ph1 = new PlaceholdersManager().GetByName(key);
  56. if (ph1.Visible)
  57. {
  58. value = ph1.Content;
  59. }
  60. Regex r1 = new Regex("(\\[\\[" + key + "\\]\\])");
  61. textToParse = r1.Replace(textToParse, value);
  62. }
  63. }
  64. //fill session vars
  65. //ex: {{yourname}} --> session["yourname"] --> nicola
  66. Regex regSessions = new Regex("(\\{\\{[a-zA-Z_][a-zA-Z0-9_]+\\}\\})");
  67. string[] sessionTags;
  68. sessionTags = regSessions.Split(textToParse);
  69. for (int i = 0; i < sessionTags.Length; i++)
  70. {
  71. key = sessionTags[i];
  72. if (key.StartsWith("{{") && key.EndsWith("}}"))
  73. {
  74. key = key.Remove(0, 2);
  75. key = key.Remove(key.Length - 2);
  76. value = "";
  77. if (HttpContext.Current.Session[key] != null)
  78. value = HttpContext.Current.Session[key].ToString();
  79. Regex r1 = new Regex("(\\{\\{" + key + "\\}\\})");
  80. textToParse = r1.Replace(textToParse, value);
  81. }
  82. }
  83. //parse special chars
  84. //ex: \[\]\{\} --> []{}
  85. textToParse = textToParse.Replace("\\[", "[");
  86. textToParse = textToParse.Replace("\\]", "]");
  87. textToParse = textToParse.Replace("\\{", "{");
  88. textToParse = textToParse.Replace("\\}", "}");
  89. }
  90. return textToParse;
  91. }
  92. /// <summary>
  93. /// create a text preview
  94. /// </summary>
  95. /// <param name="theText">the text to preview</param>
  96. /// <param name="charNo">num of chars in result string.
  97. /// 0: no preview
  98. /// -1: empty result
  99. /// >0: return the text preview</param>
  100. /// <param name="textEtcetera">default: ...</param>
  101. /// <param name="removeTags">chenage theText in plain text, removing all html tags</param>
  102. /// <returns>the preview text</returns>
  103. public static string GetTextPreview(string theText, int charNo, string textEtcetera, bool removeTags)
  104. {
  105. const int MAX_EXTRALEN = 5;
  106. string res = "";
  107. if (textEtcetera == "")
  108. textEtcetera = "...";
  109. if (!string.IsNullOrEmpty(theText))
  110. res = theText;
  111. if (charNo > 0)
  112. {
  113. if (removeTags)
  114. res = Html.StripTagsCharArray(res);
  115. int i = charNo;
  116. char c = ' ';
  117. while (i < res.Length)
  118. {
  119. c = res[i];
  120. if (res[i] == ' ' || i == charNo + MAX_EXTRALEN)
  121. {
  122. res = res.Substring(0, i) + textEtcetera;
  123. break;
  124. }
  125. i++;
  126. }
  127. }
  128. else if (charNo == -1)
  129. {
  130. res = "";
  131. }
  132. else if (charNo == 0)
  133. { }
  134. return res;
  135. }
  136. public static string GetTextPreview(string theText, int charNo, string textEtcetera)
  137. {
  138. return GetTextPreview(theText, charNo, textEtcetera, true);
  139. }
  140. /// <summary>
  141. /// returns the text until readmore system tag
  142. /// if tag does not exist returns empty text
  143. /// </summary>
  144. /// <param name="theText">the text to parse</param>
  145. /// <returns></returns>
  146. public static string GetTextIntro(string theText)
  147. {
  148. string res = "";
  149. int readMoreIndex = theText.LastIndexOf(ContentEditorProvider.SystemReadMoreTag);
  150. if (readMoreIndex > 0)
  151. res = theText.Substring(0, readMoreIndex);
  152. return res;
  153. //TODO: close not closed tags if any,
  154. //see http://www.kad1r.com/article.aspx?articleId=190&Category=ASP.Net&title=Read-more-or-continue-reading-function-in-Asp.net
  155. }
  156. /// <summary>
  157. /// rempove the system tags before render the text on browser
  158. /// </summary>
  159. /// <param name="theText"></param>
  160. /// <returns>the clean text</returns>
  161. public static string RemoveSystemTags(string theText)
  162. {
  163. string res = theText;
  164. if (!string.IsNullOrEmpty(res))
  165. {
  166. res = res.Replace(ContentEditorProvider.SystemReadMoreTag, "");
  167. res = res.Replace(ContentEditorProvider.SystemPagebreakTag, "");
  168. }
  169. return res;
  170. }
  171. /// <summary>
  172. /// Remove HTML from string with Regex.
  173. /// speed: 1(slow)
  174. /// see url: http://dotnetperls.com/remove-html-tags
  175. /// see url: http://dotnetperls.com/xhtml-validator
  176. /// </summary>
  177. public static string StripTagsRegex(string source)
  178. {
  179. return Regex.Replace(source, "<.*?>", string.Empty);
  180. }
  181. /// <summary>
  182. /// Compiled regular expression for performance.
  183. /// </summary>
  184. static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);
  185. /// <summary>
  186. /// Remove HTML from string with compiled Regex.
  187. /// speed: 2(medium)
  188. /// see url: http://dotnetperls.com/remove-html-tags
  189. /// see url: http://dotnetperls.com/xhtml-validator
  190. /// </summary>
  191. public static string StripTagsRegexCompiled(string source)
  192. {
  193. return _htmlRegex.Replace(source, string.Empty);
  194. }
  195. /// <summary>
  196. /// Remove HTML tags from string using char array.
  197. /// speed: 3(fast)
  198. /// see url: http://dotnetperls.com/remove-html-tags
  199. /// see url: http://dotnetperls.com/xhtml-validator
  200. /// </summary>
  201. public static string StripTagsCharArray(string source)
  202. {
  203. char[] array = new char[source.Length];
  204. int arrayIndex = 0;
  205. bool inside = false;
  206. for (int i = 0; i < source.Length; i++)
  207. {
  208. char let = source[i];
  209. if (let == '<')
  210. {
  211. inside = true;
  212. continue;
  213. }
  214. if (let == '>')
  215. {
  216. inside = false;
  217. continue;
  218. }
  219. if (!inside)
  220. {
  221. array[arrayIndex] = let;
  222. arrayIndex++;
  223. }
  224. }
  225. return new string(array, 0, arrayIndex);
  226. }
  227. /// <summary>
  228. /// Whether the HTML is likely valid. Error parameter will be empty
  229. /// if no errors were found.
  230. /// </summary>
  231. static public void CheckHtml(string html, out string error)
  232. {
  233. // Store our tags in a stack
  234. Stack<string> tags = new Stack<string>();
  235. // Initialize out parameter to empty
  236. error = string.Empty;
  237. // Count of parenthesis
  238. int parenthesisR = 0;
  239. int parenthesisL = 0;
  240. // Traverse entire HTML
  241. for (int i = 0; i < html.Length; i++)
  242. {
  243. char c = html[i];
  244. if (c == '<')
  245. {
  246. bool isClose;
  247. bool isSolo;
  248. // Look ahead at this tag
  249. string tag = lookAhead(html, i, out isClose, out isSolo);
  250. // Make sure tag is lowercase
  251. if (tag.ToLower() != tag)
  252. {
  253. error = "upper: " + tag;
  254. return;
  255. }
  256. // Make sure solo tags are parsed as solo tags
  257. if (_soloTags.ContainsKey(tag))
  258. {
  259. if (!isSolo)
  260. {
  261. error = "!solo: " + tag;
  262. return;
  263. }
  264. }
  265. else
  266. {
  267. // We are on a regular end or start tag
  268. if (isClose)
  269. {
  270. // We can't close a tag that isn't on the stack
  271. if (tags.Count == 0)
  272. {
  273. error = "closing: " + tag;
  274. return;
  275. }
  276. // Tag on stack must be equal to this closing tag
  277. if (tags.Peek() == tag)
  278. {
  279. // Remove the start tag from the stack
  280. tags.Pop();
  281. }
  282. else
  283. {
  284. // Mismatched closing tag
  285. error = "!match: " + tag;
  286. return;
  287. }
  288. }
  289. else
  290. {
  291. // Add tag to stack
  292. tags.Push(tag);
  293. }
  294. }
  295. i += tag.Length;
  296. }
  297. else if (c == '&')
  298. {
  299. // & must never be followed by space or other &
  300. if ((i + 1) < html.Length)
  301. {
  302. char next = html[i + 1];
  303. if (char.IsWhiteSpace(next) ||
  304. next == '&')
  305. {
  306. error = "ampersand";
  307. return;
  308. }
  309. }
  310. }
  311. else if (c == '\t')
  312. {
  313. error = "tab";
  314. return;
  315. }
  316. else if (c == '(')
  317. {
  318. parenthesisL++;
  319. }
  320. else if (c == ')')
  321. {
  322. parenthesisR++;
  323. }
  324. }
  325. // If we have tags in the stack, write them to error
  326. foreach (string tagName in tags)
  327. {
  328. error += "extra:" + tagName + " ";
  329. }
  330. // Require even number of parenthesis
  331. if (parenthesisL != parenthesisR)
  332. {
  333. error = "!even ";
  334. }
  335. }
  336. /// <summary>
  337. /// Called at the start of an html tag. We look forward and record information
  338. /// about our tag. Handles start tags, close tags, and solo tags. 'Collects'
  339. /// an entire tag.
  340. /// </summary>
  341. /// <returns>Tag name.</returns>
  342. static private string lookAhead(string html, int start, out bool isClose,
  343. out bool isSolo)
  344. {
  345. isClose = false;
  346. isSolo = false;
  347. StringBuilder tagName = new StringBuilder();
  348. int slashPos = -1; // Stores the position of the final slash
  349. bool space = false; // Whether we have encountered a space
  350. bool quote = false; // Whether we are in a quote
  351. // Begin scanning the tag
  352. int i;
  353. for (i = 0; ; i++)
  354. {
  355. // Get the position in main html
  356. int pos = start + i;
  357. // Don't go outside the html
  358. if (pos >= html.Length)
  359. {
  360. return "x";
  361. }
  362. // The character we are looking at
  363. char c = html[pos];
  364. // See if a space has been encountered
  365. if (char.IsWhiteSpace(c))
  366. {
  367. space = true;
  368. }
  369. // Add to our tag name if none of these are present
  370. if (space == false &&
  371. c != '<' &&
  372. c != '>' &&
  373. c != '/')
  374. {
  375. tagName.Append(c);
  376. }
  377. // Record position of slash if not inside a quoted area
  378. if (c == '/' &&
  379. quote == false)
  380. {
  381. slashPos = i;
  382. }
  383. // End at the > bracket
  384. if (c == '>')
  385. {
  386. break;
  387. }
  388. // Record whether we are in a quoted area
  389. if (c == '\"')
  390. {
  391. quote = !quote;
  392. }
  393. }
  394. // Determine if this is a solo or closing tag
  395. if (slashPos != -1)
  396. {
  397. // If slash is at the end so this is solo
  398. if (slashPos + 1 == i)
  399. {
  400. isSolo = true;
  401. }
  402. else
  403. {
  404. isClose = true;
  405. }
  406. }
  407. // Return the name of the tag collected
  408. string name = tagName.ToString();
  409. if (name.Length == 0)
  410. {
  411. return "empty";
  412. }
  413. else
  414. {
  415. return name;
  416. }
  417. }
  418. /// <summary>
  419. /// Tags that must be closed in the start
  420. /// </summary>
  421. static Dictionary<string, bool> _soloTags = new Dictionary<string, bool>()
  422. {
  423. {"img", true},{"br", true}
  424. };
  425. }
  426. /// <summary>
  427. /// useful methods for mobile devices
  428. /// </summary>
  429. public class Mobile
  430. {
  431. public enum DeviceTypeEnum
  432. {
  433. Android,
  434. Iphone,
  435. Ipad,
  436. Kindle,
  437. Blackbarry,
  438. Unknown
  439. }
  440. public static bool IsMobileDevice(HttpContext ctx)
  441. {
  442. string userAgent = ctx.Request.UserAgent.ToLower();
  443. if (userAgent.Contains("blackberry")
  444. || userAgent.Contains("iphone")
  445. || userAgent.Contains("ipad")
  446. || userAgent.Contains("kindle")
  447. || userAgent.Contains("android"))
  448. return true;
  449. return ctx.Request.Browser.IsMobileDevice;
  450. }
  451. public static DeviceTypeEnum DeviceType(HttpContext ctx)
  452. {
  453. DeviceTypeEnum res = DeviceTypeEnum.Unknown;
  454. string userAgent = ctx.Request.UserAgent.ToLower();
  455. switch (userAgent)
  456. {
  457. case "android":
  458. res = DeviceTypeEnum.Android;
  459. break;
  460. case "blackberry":
  461. res = DeviceTypeEnum.Blackbarry;
  462. break;
  463. case "iphone":
  464. res = DeviceTypeEnum.Iphone;
  465. break;
  466. case "ipad":
  467. res = DeviceTypeEnum.Ipad;
  468. break;
  469. case "kindle":
  470. res = DeviceTypeEnum.Kindle;
  471. break;
  472. }
  473. return res;
  474. }
  475. }
  476. /// <summary>
  477. /// useful methods to manage js scripts
  478. /// </summary>
  479. public class Script
  480. {
  481. public static void RegisterClientScriptBlock(Control control, string key, string script)
  482. {
  483. RegisterClientScriptBlock(control, key, script, true);
  484. }
  485. public static void RegisterClientScriptBlock(Control control, string key, string script, bool addScriptTags)
  486. {
  487. ScriptManager.RegisterClientScriptBlock(control, typeof(bool)/*GetType()*/, key, script, addScriptTags);
  488. }
  489. public static void RegisterClientScriptInclude(Control control, string key, string url)
  490. {
  491. ScriptManager.RegisterClientScriptInclude(control, typeof(bool)/*GetType()*/, key, url);
  492. }
  493. public static void RegisterClientScriptInclude(Page page, string key, string url)
  494. {
  495. ScriptManager.RegisterClientScriptInclude(page, typeof(bool)/*GetType()*/, key, url);
  496. }
  497. public static void RegisterStartupScript(Control control, string key, string script)
  498. {
  499. RegisterStartupScript(control, key, script, true);
  500. }
  501. public static void RegisterStartupScript(Control control, string key, string script, bool addScriptTags)
  502. {
  503. ScriptManager.RegisterStartupScript(control, typeof(bool), key, script, addScriptTags);
  504. }
  505. /// <summary>
  506. /// Encodes a string to be represented as a string literal. The format
  507. /// is essentially a JSON string.
  508. /// The string returned includes outer quotes
  509. /// Example Output: "Hello \"Rick\"!\r\nRock on"
  510. /// </summary>
  511. /// <param name="s"></param>
  512. /// <returns></returns>
  513. public static string EncodeJsString(string s)
  514. {
  515. StringBuilder sb = new StringBuilder();
  516. //sb.Append("\"");
  517. if (!string.IsNullOrEmpty(s))
  518. {
  519. foreach (char c in s)
  520. {
  521. switch (c)
  522. {
  523. case '\"':
  524. sb.Append("\\\"");
  525. break;
  526. case '\'':
  527. sb.Append("\\\'");
  528. break;
  529. case '\\':
  530. sb.Append("\\\\");
  531. break;
  532. case '\b':
  533. sb.Append("\\b");
  534. break;
  535. case '\f':
  536. sb.Append("\\f");
  537. break;
  538. case '\n':
  539. sb.Append("\\n");
  540. break;
  541. case '\r':
  542. sb.Append("\\r");
  543. break;
  544. case '\t':
  545. sb.Append("\\t");
  546. break;
  547. default:
  548. int i = (int)c;
  549. if (i < 32 || i > 127)
  550. {
  551. sb.AppendFormat("\\u{0:X04}", i);
  552. }
  553. else
  554. {
  555. sb.Append(c);
  556. }
  557. break;
  558. }
  559. }
  560. }
  561. //sb.Append("\"");
  562. return sb.ToString();
  563. }
  564. }
  565. /// <summary>
  566. /// useful crypt decript methods
  567. /// </summary>
  568. public class Encryption
  569. {
  570. public static string Decrypt(string textToDecrypt, string key)
  571. {
  572. RijndaelManaged rijndaelCipher = new RijndaelManaged(); //AES
  573. rijndaelCipher.Mode = CipherMode.CBC;
  574. rijndaelCipher.Padding = PaddingMode.PKCS7;
  575. rijndaelCipher.KeySize = 0x80;
  576. rijndaelCipher.BlockSize = 0x80;
  577. byte[] encryptedData = Convert.FromBase64String(textToDecrypt);
  578. byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
  579. byte[] keyBytes = new byte[0x10];
  580. int len = pwdBytes.Length;
  581. if (len > keyBytes.Length)
  582. {
  583. len = keyBytes.Length;
  584. }
  585. Array.Copy(pwdBytes, keyBytes, len);
  586. rijndaelCipher.Key = keyBytes;
  587. rijndaelCipher.IV = keyBytes;
  588. byte[] plainText = rijndaelCipher.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
  589. return Encoding.UTF8.GetString(plainText);
  590. }
  591. public static string Encrypt(string textToEncrypt, string key)
  592. {
  593. RijndaelManaged rijndaelCipher = new RijndaelManaged();
  594. rijndaelCipher.Mode = CipherMode.CBC;
  595. rijndaelCipher.Padding = PaddingMode.PKCS7;
  596. rijndaelCipher.KeySize = 0x80;
  597. rijndaelCipher.BlockSize = 0x80;
  598. byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
  599. byte[] keyBytes = new byte[0x10];
  600. int len = pwdBytes.Length;
  601. if (len > keyBytes.Length)
  602. {
  603. len = keyBytes.Length;
  604. }
  605. Array.Copy(pwdBytes, keyBytes, len);
  606. rijndaelCipher.Key = keyBytes;
  607. rijndaelCipher.IV = keyBytes;
  608. ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
  609. byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
  610. return Convert.ToBase64String(transform.TransformFinalBlock(plainText, 0, plainText.Length));
  611. }
  612. }
  613. public class StaticData
  614. {
  615. public static Dictionary<string, string> Nations
  616. {
  617. get
  618. {
  619. var list = new Dictionary<string, string>();
  620. list.Add("IT", "Italy");
  621. list.Add("AF", "Afghanistan");
  622. list.Add("AL", "Albania");
  623. list.Add("DZ", "Algeria");
  624. list.Add("AS", "American Samoa");
  625. list.Add("AD", "Andorra");
  626. list.Add("AO", "Angola");
  627. list.Add("AI", "Anguilla");
  628. list.Add("AQ", "Antarctica");
  629. list.Add("AG", "Antigua And Barbuda");
  630. list.Add("AR", "Argentina");
  631. list.Add("AM", "Armenia");
  632. list.Add("AW", "Aruba");
  633. list.Add("AU", "Australia");
  634. list.Add("AT", "Austria");
  635. list.Add("AZ", "Azerbaijan");
  636. list.Add("BS", "Bahamas");
  637. list.Add("BH", "Bahrain");
  638. list.Add("BD", "Bangladesh");
  639. list.Add("BB", "Barbados");
  640. list.Add("BY", "Belarus");
  641. list.Add("BE", "Belgium");
  642. list.Add("BZ", "Belize");
  643. list.Add("BJ", "Benin");
  644. list.Add("BM", "Bermuda");
  645. list.Add("BT", "Bhutan");
  646. list.Add("BO", "Bolivia, Plurinational State Of");
  647. list.Add("BA", "Bosnia And Herzegovina");
  648. list.Add("BW", "Botswana");
  649. list.Add("BV", "Bouvet Island");
  650. list.Add("BR", "Brazil");
  651. list.Add("IO", "British Indian Ocean Territory");
  652. list.Add("BN", "Brunei Darussalam");
  653. list.Add("BG", "Bulgaria");
  654. list.Add("BF", "Burkina Faso");
  655. list.Add("BI", "Burundi");
  656. list.Add("KH", "Cambodia");
  657. list.Add("CM", "Cameroon");
  658. list.Add("CA", "Canada");
  659. list.Add("CV", "Cape Verde");
  660. list.Add("KY", "Cayman Islands");
  661. list.Add("CF", "Central African Republic");
  662. list.Add("TD", "Chad");
  663. list.Add("CL", "Chile");
  664. list.Add("CN", "China");
  665. list.Add("CX", "Christmas Island");
  666. list.Add("CC", "Cocos (Keeling) Islands");
  667. list.Add("CO", "Colombia");
  668. list.Add("KM", "Comoros");
  669. list.Add("CG", "Congo");
  670. list.Add("CD", "Congo, The Democratic Republic Of The");
  671. list.Add("CK", "Cook Islands");
  672. list.Add("CR", "Costa Rica");
  673. list.Add("CI", "Côte D'Ivoire");
  674. list.Add("HR", "Croatia");
  675. list.Add("CU", "Cuba");
  676. list.Add("CY", "Cyprus");
  677. list.Add("CZ", "Czech Republic");
  678. list.Add("DK", "Denmark");
  679. list.Add("DJ", "Djibouti");
  680. list.Add("DM", "Dominica");
  681. list.Add("DO", "Dominican Republic");
  682. list.Add("EC", "Ecuador");
  683. list.Add("EG", "Egypt");
  684. list.Add("SV", "El Salvador");
  685. list.Add("GQ", "Equatorial Guinea");
  686. list.Add("ER", "Eritrea");
  687. list.Add("EE", "Estonia");
  688. list.Add("ET", "Ethiopia");
  689. list.Add("FK", "Falkland Islands (Malvinas)");
  690. list.Add("FO", "Faroe Islands");
  691. list.Add("FJ", "Fiji");
  692. list.Add("FI", "Finland");
  693. list.Add("FR", "France");
  694. list.Add("GF", "French Guiana");
  695. list.Add("PF", "French Polynesia");
  696. list.Add("TF", "French Southern Territories");
  697. list.Add("GA", "Gabon");
  698. list.Add("GM", "Gambia");
  699. list.Add("GE", "Georgia");
  700. list.Add("DE", "Germany");
  701. list.Add("GH", "Ghana");
  702. list.Add("GI", "Gibraltar");
  703. list.Add("GR", "Greece");
  704. list.Add("GL", "Greenland");
  705. list.Add("GD", "Grenada");
  706. list.Add("GP", "Guadeloupe");
  707. list.Add("GU", "Guam");
  708. list.Add("GT", "Guatemala");
  709. list.Add("GG", "Guernsey");
  710. list.Add("GN", "Guinea");
  711. list.Add("GW", "Guinea-Bissau");
  712. list.Add("GY", "Guyana");
  713. list.Add("HT", "Haiti");
  714. list.Add("HM", "Heard Island And Mcdonald Islands");
  715. list.Add("HN", "Honduras");
  716. list.Add("HK", "Hong Kong");
  717. list.Add("HU", "Hungary");
  718. list.Add("IS", "Iceland");
  719. list.Add("IN", "India");
  720. list.Add("ID", "Indonesia");
  721. list.Add("IR", "Iran, Islamic Republic Of");
  722. list.Add("IQ", "Iraq");
  723. list.Add("IE", "Ireland");
  724. list.Add("IM", "Isle Of Man");
  725. list.Add("IL", "Israel");
  726. list.Add("JM", "Jamaica");
  727. list.Add("JP", "Japan");
  728. list.Add("JE", "Jersey");
  729. list.Add("JO", "Jordan");
  730. list.Add("KZ", "Kazakhstan");
  731. list.Add("KE", "Kenya");
  732. list.Add("KI", "Kiribati");
  733. list.Add("KP", "Korea, Democratic People's Republic Of");
  734. list.Add("KR", "Korea, Republic Of");
  735. list.Add("KW", "Kuwait");
  736. list.Add("KG", "Kyrgyzstan");
  737. list.Add("LA", "Lao People's Democratic Republic");
  738. list.Add("LV", "Latvia");
  739. list.Add("LB", "Lebanon");
  740. list.Add("LS", "Lesotho");
  741. list.Add("LR", "Liberia");
  742. list.Add("LY", "Libyan Arab Jamahiriya");
  743. list.Add("LI", "Liechtenstein");
  744. list.Add("LT", "Lithuania");
  745. list.Add("LU", "Luxembourg");
  746. list.Add("MO", "Macao");
  747. list.Add("MK", "Macedonia, The Former Yugoslav Republic Of");
  748. list.Add("MG", "Madagascar");
  749. list.Add("MW", "Malawi");
  750. list.Add("MY", "Malaysia");
  751. list.Add("MV", "Maldives");
  752. list.Add("ML", "Mali");
  753. list.Add("MT", "Malta");
  754. list.Add("MH", "Marshall Islands");
  755. list.Add("MQ", "Martinique");
  756. list.Add("MR", "Mauritania");
  757. list.Add("MU", "Mauritius");
  758. list.Add("YT", "Mayotte");
  759. list.Add("MX", "Mexico");
  760. list.Add("FM", "Micronesia, Federated States Of");
  761. list.Add("MD", "Moldova, Republic Of");
  762. list.Add("MC", "Monaco");
  763. list.Add("MN", "Mongolia");
  764. list.Add("ME", "Montenegro");
  765. list.Add("MS", "Montserrat");
  766. list.Add("MA", "Morocco");
  767. list.Add("MZ", "Mozambique");
  768. list.Add("MM", "Myanmar");
  769. list.Add("NA", "Namibia");
  770. list.Add("NR", "Nauru");
  771. list.Add("NP", "Nepal");
  772. list.Add("NL", "Netherlands");
  773. list.Add("AN", "Netherlands Antilles");
  774. list.Add("NC", "New Caledonia");
  775. list.Add("NZ", "New Zealand");
  776. list.Add("NI", "Nicaragua");
  777. list.Add("NE", "Niger");
  778. list.Add("NG", "Nigeria");
  779. list.Add("NU", "Niue");
  780. list.Add("NF", "Norfolk Island");
  781. list.Add("MP", "Northern Mariana Islands");
  782. list.Add("NO", "Norway");
  783. list.Add("OM", "Oman");
  784. list.Add("PK", "Pakistan");
  785. list.Add("PW", "Palau");
  786. list.Add("PS", "Palestinian Territory, Occupied");
  787. list.Add("PA", "Panama");
  788. list.Add("PG", "Papua New Guinea");
  789. list.Add("PY", "Paraguay");
  790. list.Add("PE", "Peru");
  791. list.Add("PH", "Philippines");
  792. list.Add("PN", "Pitcairn");
  793. list.Add("PL", "Poland");
  794. list.Add("PT", "Portugal");
  795. list.Add("PR", "Puerto Rico");
  796. list.Add("QA", "Qatar");
  797. list.Add("RE", "Réunion");
  798. list.Add("RO", "Romania");
  799. list.Add("RU", "Russian Federation");
  800. list.Add("RW", "Rwanda");
  801. list.Add("BL", "Saint Barthélemy");
  802. list.Add("SH", "Saint Helena, Ascension And Tristan Da Cunha");
  803. list.Add("KN", "Saint Kitts And Nevis");
  804. list.Add("LC", "Saint Lucia");
  805. list.Add("MF", "Saint Martin");
  806. list.Add("PM", "Saint Pierre And Miquelon");
  807. list.Add("VC", "Saint Vincent And The Grenadines");
  808. list.Add("WS", "Samoa");
  809. list.Add("SM", "San Marino");
  810. list.Add("ST", "Sao Tome And Principe");
  811. list.Add("SA", "Saudi Arabia");
  812. list.Add("SN", "Senegal");
  813. list.Add("RS", "Serbia");
  814. list.Add("SC", "Seychelles");
  815. list.Add("SL", "Sierra Leone");
  816. list.Add("SG", "Singapore");
  817. list.Add("SK", "Slovakia");
  818. list.Add("SI", "Slovenia");
  819. list.Add("SB", "Solomon Islands");
  820. list.Add("SO", "Somalia");
  821. list.Add("ZA", "South Africa");
  822. list.Add("GS", "South Georgia And The South Sandwich Islands");
  823. list.Add("ES", "Spain");
  824. list.Add("LK", "Sri Lanka");
  825. list.Add("SD", "Sudan");
  826. list.Add("SR", "Suriname");
  827. list.Add("SJ", "Svalbard And Jan Mayen");
  828. list.Add("SZ", "Swaziland");
  829. list.Add("SE", "Sweden");
  830. list.Add("CH", "Switzerland");
  831. list.Add("SY", "Syrian Arab Republic");
  832. list.Add("TW", "Taiwan, Province Of China");
  833. list.Add("TJ", "Tajikistan");
  834. list.Add("TZ", "Tanzania, United Republic Of");
  835. list.Add("TH", "Thailand");
  836. list.Add("TL", "Timor-Leste");
  837. list.Add("TG", "Togo");
  838. list.Add("TK", "Tokelau");
  839. list.Add("TO", "Tonga");
  840. list.Add("TT", "Trinidad And Tobago");
  841. list.Add("TN", "Tunisia");
  842. list.Add("TR", "Turkey");
  843. list.Add("TM", "Turkmenistan");
  844. list.Add("TC", "Turks And Caicos Islands");
  845. list.Add("TV", "Tuvalu");
  846. list.Add("UG", "Uganda");
  847. list.Add("UA", "Ukraine");
  848. list.Add("AE", "United Arab Emirates");
  849. list.Add("GB", "United Kingdom");
  850. list.Add("US", "United States");
  851. list.Add("UM", "United States Minor Outlying Islands");
  852. list.Add("UY", "Uruguay");
  853. list.Add("UZ", "Uzbekistan");
  854. list.Add("VU", "Vanuatu");
  855. list.Add("VA", "Vatican City State");
  856. list.Add("VE", "Venezuela, Bolivarian Republic Of");
  857. list.Add("VN", "Viet Nam");
  858. list.Add("VG", "Virgin Islands, British");
  859. list.Add("VI", "Virgin Islands, U.S.");
  860. list.Add("WF", "Wallis And Futuna");
  861. list.Add("EH", "Western Sahara");
  862. list.Add("YE", "Yemen");
  863. list.Add("ZM", "Zambia");
  864. list.Add("ZW ", "Zimbabwe");
  865. list.Add("AX", "?land Islands");
  866. return list;
  867. }
  868. }
  869. }
  870. /// <summary>
  871. /// Gets the first day of a week where day (parameter) belongs. weekStart (parameter) specifies the starting day of week.
  872. /// </summary>
  873. /// <returns></returns>
  874. public static DateTime FirstDayOfWeek(DateTime day, DayOfWeek weekStarts)
  875. {
  876. DateTime d = day;
  877. while (d.DayOfWeek != weekStarts)
  878. {
  879. d = d.AddDays(-1);
  880. }
  881. return d;
  882. }
  883. /// <summary>
  884. /// Add a glyph to the ordered column in a gridview
  885. /// </summary>
  886. /// <example>
  887. ///protected void GridViewProducts_RowCreated(object sender, GridViewRowEventArgs e)
  888. ///{
  889. /// if (e.Row.RowType == DataControlRowType.Header)
  890. /// AddGlyph(GridViewProducts, e.Row);
  891. ///}
  892. /// </example>
  893. /// <param name="grid">the GridView</param>
  894. /// <param name="item">the Row</param>
  895. public static void AddGlyph(GridView grid, GridViewRow item)
  896. {
  897. //Label glyph = new Label();
  898. //glyph.EnableTheming = false;
  899. //glyph.Font.Name = "Webdings";
  900. //glyph.Font.Size = FontUnit.XSmall;
  901. //glyph.Font.Bold = true;
  902. //glyph.ForeColor = System.Drawing.Color.DarkGray;
  903. //glyph.Text = (grid.SortDirection == SortDirection.Ascending ? "?" : "?");
  904. Label space = new Label();
  905. space.Text = " ";
  906. Image imgSort = new Image();
  907. imgSort.SkinID = (grid.SortDirection == SortDirection.Ascending ? "ImgSortAsc" : "ImgSortDesc");
  908. for (int i = 0; i < grid.Columns.Count; i++)
  909. {
  910. string colExpr = grid.Columns[i].SortExpression;
  911. if (colExpr != "" && colExpr == grid.SortExpression)
  912. //item.Cells[i].Controls.Add(space);
  913. item.Cells[i].Controls.Add(imgSort);
  914. }
  915. }
  916. /// <summary>
  917. /// add onclick script to allow static file tracking
  918. /// </summary>
  919. /// <param name="trackParam">the param in for the script</param>
  920. /// <param name="addScript">false:do nothing</param>
  921. /// <returns></returns>
  922. public static string AddTracking(string trackParam, bool addScript)
  923. {
  924. string res = "";
  925. string currUrl = HttpContext.Current.Request.FilePath + "#";
  926. if (addScript && !string.IsNullOrEmpty(trackParam))
  927. res = " onclick=\"pageTracker._trackPageview('"+ currUrl + trackParam + "');\" ";
  928. return res;
  929. }
  930. /// <summary>
  931. /// add onclick script to allow static file tracking
  932. /// </summary>
  933. /// <param name="trakParams">list of params used to build the param path</param>
  934. /// <param name="addScript">false:do nothing</param>
  935. /// <returns></returns>
  936. public static string AddTracking(string[]trakParams, bool addScript)
  937. {
  938. string res = "";
  939. if (trakParams != null)
  940. {
  941. string path = "";
  942. foreach (string param in trakParams)
  943. {
  944. if (!string.IsNullOrEmpty(param))
  945. path += "/" + param;
  946. }
  947. res = AddTracking(path, addScript);
  948. }
  949. return res;
  950. }
  951. /// <summary>
  952. /// transform an url in a valid alias
  953. /// </summary>
  954. /// <param name="url">url or string to sanitize</param>
  955. /// <returns>a valid url</returns>
  956. public static string GetUrlAlias(string url)
  957. {
  958. string res = url.ToLower();
  959. res = res.Replace(" ","-");
  960. res = HttpUtility.UrlEncode(res);
  961. return res;
  962. }
  963. public static string GetCurrCultureName()
  964. {
  965. return Thread.CurrentThread.CurrentCulture.Name;
  966. }
  967. /// <summary>
  968. ///
  969. /// </summary>
  970. /// <param name="month">the month</param>
  971. /// <returns>month name in current culture</returns>
  972. public static string GetMonthName(int month)
  973. {
  974. string res = "";
  975. string label = "month";
  976. if (month >= 1 && month <= 12)
  977. {
  978. label += month.ToString();
  979. res = GetLabel(label);
  980. }
  981. return res;
  982. }
  983. public static string GetAbsoluteUrl()
  984. {
  985. return GetAbsoluteUrl("");
  986. }
  987. public static string GetAbsoluteUrl(string url)
  988. {
  989. string res = "http://" +
  990. HttpContext.Current.Request.Url.Authority +
  991. HttpContext.Current.Request.ApplicationPath;
  992. if (!res.EndsWith("/")) res += "/";
  993. if (url.StartsWith("/"))
  994. url = url.Substring(1);
  995. res += url;
  996. return res;
  997. }
  998. public static string GetRoutedUrl(Menu menuEntry)
  999. {
  1000. return GetRoutedUrl(menuEntry, null, "", true);
  1001. }
  1002. public static string GetRoutedUrl(Menu menuEntry, string queryString, bool addPagePostFix)
  1003. {
  1004. return GetRoutedUrl(menuEntry, null, queryString, addPagePostFix);
  1005. }
  1006. public static string GetRoutedUrl(Menu menuEntry,
  1007. RouteValueDictionary routeValueDictionary, string queryString, bool addPagePostFix)
  1008. {
  1009. var res = new StringBuilder();
  1010. try
  1011. {
  1012. var defaults = new RouteValueDictionary { { "pagename", menuEntry.Alias.ToLower() } };
  1013. if (routeValueDictionary != null)
  1014. {
  1015. foreach (var item in routeValueDictionary)
  1016. {
  1017. if (defaults.ContainsKey(item.Key))
  1018. defaults.Remove(item.Key);
  1019. defaults.Add(item.Key, item.Value);
  1020. }
  1021. }
  1022. res = res.Append(
  1023. RouteTable.Routes.GetVirtualPath(
  1024. null, menuEntry.RouteName, defaults).VirtualPath
  1025. );
  1026. if (addPagePostFix)
  1027. res = res.Append(".aspx");
  1028. if (!string.IsNullOrEmpty(queryString))
  1029. {
  1030. res = res.Append("?");
  1031. res = res.Append(queryString);
  1032. }
  1033. }
  1034. catch (Exception ex)
  1035. {
  1036. Tracer.Log("GetRoutedUrl, missing RouteValueDictionary: " + ex.ToString(), TracerItemType.Error);
  1037. throw new ArgumentException("missing RouteValueDictionary", ex);
  1038. }
  1039. return res.ToString();
  1040. }
  1041. public static string GetThemedImageSrc(string fileName)
  1042. {
  1043. return GetThemedImageSrc(fileName, "", "");
  1044. }
  1045. public static string GetThemedImageSrc(string fileName, string pageTheme)
  1046. {
  1047. return GetThemedImageSrc(fileName, pageTheme, "");
  1048. }
  1049. /// <summary>
  1050. /// get image url for current page theme
  1051. /// </summary>
  1052. /// <param name="fileName">the image file name</param>
  1053. /// <param name="pageTheme">name of theme; "" for current theme</param>
  1054. /// <param name="defaultFileName">file to use if filename is not found; "" for no default file</param>
  1055. /// <returns>absolute path of the image</returns>
  1056. public static string GetThemedImageSrc(string fileName, string pageTheme, string defaultFileName)
  1057. {
  1058. string res = "";
  1059. if (string.IsNullOrEmpty(pageTheme))
  1060. {
  1061. Page page = (Page)HttpContext.Current.CurrentHandler;
  1062. pageTheme = page.Theme;
  1063. }
  1064. if (!string.IsNullOrEmpty(defaultFileName))
  1065. {
  1066. if (File.Exists(
  1067. HttpContext.Current.Server.MapPath(
  1068. "~/App_Themes/" + pageTheme + "/Images/" + fileName)))
  1069. res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + fileName;
  1070. else
  1071. res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + defaultFileName;
  1072. }
  1073. else
  1074. res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme + "/Images/" + fileName;
  1075. return res;
  1076. }
  1077. /// <summary>
  1078. /// get css url for current page theme
  1079. /// </summary>
  1080. /// <param name="fileName">the css file name</param>
  1081. /// <returns></returns>
  1082. public static string GetThemedCssSrc(string fileName)
  1083. {
  1084. Page page = (Page)HttpContext.Current.CurrentHandler;
  1085. return GetThemedCssSrc(fileName, page.Theme);
  1086. }
  1087. public static string GetThemedCssSrc(string fileName, string pageTheme)
  1088. {
  1089. string res = VirtualPathUtility.ToAbsolute("~/") + "App_Themes/" + pageTheme /*Config.CurrentTheme*/ + "/" + fileName;
  1090. return res;
  1091. }
  1092. public static string GetLabel(string stringKey)
  1093. {
  1094. string res = "";
  1095. if (HttpContext.GetGlobalResourceObject("PublicLabels", stringKey) != null)
  1096. res = HttpContext.GetGlobalResourceObject("PublicLabels", stringKey).ToString();
  1097. //if (Resources.AdminLabels.ResourceManager.GetString(stringKey) != null)
  1098. // res = Resources.AdminLabels.ResourceManager.GetString(stringKey);
  1099. return res;
  1100. }
  1101. public static string GetLabel(string stringKey, string defaultValue)
  1102. {
  1103. string res = GetLabel(stringKey);
  1104. if (res == "")
  1105. res = defaultValue;
  1106. return res;
  1107. }
  1108. public static string GetLabel(string stringKey, string defaultValue, Control targetControl)
  1109. {
  1110. return GetLabel(stringKey, defaultValue, targetControl, "");
  1111. }
  1112. public static string GetLabel(string stringKey, string defaultValue, Control targetControl, string title)
  1113. {
  1114. if (!string.IsNullOrEmpty(title))
  1115. title = "title='" + title + "'";
  1116. string clientID = "";
  1117. if (targetControl != null)
  1118. clientID = targetControl.ClientID;
  1119. string res = GetLabel(stringKey, defaultValue);
  1120. res = "<label for='" + clientID + "' " + title + ">" + res + "</label>";
  1121. return res;
  1122. }
  1123. public static string GetErrorLabel(string stringKey, string defaultValue)
  1124. {
  1125. string res = GetLabel("Err" + stringKey);
  1126. if (res == "")
  1127. res = defaultValue;
  1128. return "<span class='error'>" + res + "</span>";
  1129. }
  1130. public static string List2String(List<string> stringList)
  1131. {
  1132. return List2String(stringList, "|");
  1133. }
  1134. public static string List2String(List<string> stringList, string separator)
  1135. {
  1136. string res = "";
  1137. foreach (string item in stringList)
  1138. {
  1139. if (!string.IsNullOrEmpty(item))
  1140. res += item + separator;
  1141. }
  1142. return res;
  1143. }
  1144. public static List<string> String2List(string theString)
  1145. {
  1146. return String2List(theString, '|');
  1147. }
  1148. public static List<string> String2List(string theString, char stringSepataror)
  1149. {
  1150. var res = new List<string>();
  1151. if (theString != null)
  1152. {
  1153. string[] arr = theString.Split(stringSepataror);
  1154. foreach (string item in arr)
  1155. {
  1156. res.Add(item);
  1157. }
  1158. }
  1159. return res;
  1160. }
  1161. public static List<string> String2List(string theString, string stringSepataror)
  1162. {
  1163. var res = new List<string>();
  1164. string[] splitter = { stringSepataror };
  1165. if (theString != null)
  1166. {
  1167. string[] arr = theString.Split(splitter, StringSplitOptions.None);
  1168. foreach (string item in arr)
  1169. {
  1170. res.Add(item);
  1171. }
  1172. }
  1173. return res;
  1174. }
  1175. public static List<string> RemoveDuplicatesFromList(List<string> stringList)
  1176. {
  1177. var res = new List<string>();
  1178. foreach (string item in stringList)
  1179. {
  1180. if (!string.IsNullOrEmpty(item))
  1181. {
  1182. if (!res.Contains(item)) res.Add(item);
  1183. }
  1184. }
  1185. return res;
  1186. }
  1187. /// <summary>
  1188. /// get params dictionary result from serialize string
  1189. /// ex: paramString = "par1:=xx|par2:=yy"
  1190. /// result={par1,xx},{par2,yy}
  1191. /// </summary>
  1192. /// <param name="paramString">inline serialized params</param>
  1193. /// <returns>dictionary object, (paramkey,paramvalue)</returns>
  1194. public static Dictionary<string, string> GetParamsDictFromString(string paramString)
  1195. {
  1196. string[] splitter = { ":=" };
  1197. Dictionary<String, String> result = new Dictionary<string, string>();
  1198. List<string> paramsList = Utility.String2List(paramString);
  1199. foreach (string item in paramsList)
  1200. {
  1201. string[] arr = item.Split(splitter, StringSplitOptions.None);
  1202. string key = "";
  1203. if (arr.Length > 0) key = arr[0];
  1204. string value = "";
  1205. if (arr.Length > 1) value = arr[1];
  1206. if (!string.IsNullOrEmpty(key))
  1207. {
  1208. result.Add(key, value);
  1209. }
  1210. }
  1211. return result;
  1212. }
  1213. /// <summary>
  1214. /// set drop selected value
  1215. /// </summary>
  1216. /// <param name="drop">the DropDownList</param>
  1217. /// <param name="value">the value</param>
  1218. public static void SetDropByValue(DropDownList drop, string value)
  1219. {
  1220. drop.SelectedIndex = drop.Items.IndexOf(drop.Items.FindByValue(value));
  1221. }
  1222. /// <summary>
  1223. /// set ListItem values
  1224. /// </summary>
  1225. /// <param name="list">the ListBox control</param>
  1226. /// <param name="values">a list of string</param>
  1227. public static void SetListBoxByValues(ListBox list, List<string> values, bool clearSelectionBefore)
  1228. {
  1229. if (clearSelectionBefore)
  1230. list.ClearSelection();
  1231. foreach (ListItem item in list.Items)
  1232. {
  1233. if (values.Contains(item.Value))
  1234. item.Selected = true;
  1235. }
  1236. }
  1237. public static void SetListBoxByValues(ListBox list, List<string> values)
  1238. {
  1239. SetListBoxByValues(list, values, true);
  1240. }
  1241. public static void SetListBoxByValues(ListBox list, string value)
  1242. {
  1243. List<string> values = new List<string>();
  1244. values.Add(value);
  1245. SetListBoxByValues(list, values, true);
  1246. }
  1247. public static void SetListBoxByValues(ListBox list, int value)
  1248. {
  1249. List<string> values = new List<string>();
  1250. values.Add(value.ToString());
  1251. SetListBoxByValues(list, values, true);
  1252. }
  1253. public static void SetListBoxByValues(ListBox list, List<int> values)
  1254. {
  1255. List<string> stringValues = new List<string>();
  1256. foreach (int item in values)
  1257. {
  1258. stringValues.Add(item.ToString());
  1259. }
  1260. SetListBoxByValues(list, stringValues, true);
  1261. }
  1262. /// <summary>
  1263. /// check if inputemail is syntactically valid or not
  1264. /// </summary>
  1265. /// <param name="inputEmail"></param>
  1266. /// <returns></returns>
  1267. public static bool IsValidEmail(string inputEmail)
  1268. {
  1269. if (string.IsNullOrEmpty(inputEmail))
  1270. return false;
  1271. string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
  1272. @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
  1273. @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
  1274. Regex re = new Regex(strRegex);
  1275. return re.IsMatch(inputEmail);
  1276. }
  1277. /// <summary>
  1278. /// tell if the field is empty or contains the default fck value
  1279. /// that can be deleted only in 'source code' fck editor mode
  1280. /// </summary>
  1281. /// <param name="fieldValue">the fck field content</param>
  1282. /// <returns></returns>
  1283. public static bool IsEmptyFckField(string fieldValue)
  1284. {
  1285. bool result = false;
  1286. if (string.IsNullOrEmpty(fieldValue))
  1287. result = true;
  1288. else
  1289. {
  1290. if (fieldValue.Trim() == "<br />")
  1291. result = true;
  1292. else if (fieldValue.Trim() == "<br type=\"_moz\" />")
  1293. result = true;
  1294. else if (fieldValue.Trim() == "&nbsp;")
  1295. result = true;
  1296. }
  1297. return result;
  1298. }
  1299. /// <summary>
  1300. /// <see cref="Utility._Session()" />
  1301. /// </summary>
  1302. public static Object _Session(string name)
  1303. {
  1304. return _Session(name, false);
  1305. }
  1306. /// <summary>
  1307. /// retrieve a session obj using HttpContext.Current.Session[name] to prevent NullReferenceException
  1308. /// given by Page.Session[name] on session timed out
  1309. /// </summary>
  1310. /// <param name="name">identify the object to retrieve from sessionastate</param>
  1311. /// <param name="redirTimeOutOnNull">redirect to default timeout page</param>
  1312. /// <returns>an Object to cast</returns>
  1313. public static Object _Session(string name, bool redirTimeOutOnNull)
  1314. {
  1315. Object result;
  1316. result = HttpContext.Current.Session[name];
  1317. if (result == null && redirTimeOutOnNull)
  1318. HttpContext.Current.Response.Redirect(Config.SessionTimeOutUrl);
  1319. return result;
  1320. }
  1321. public static Object _Application(string name)
  1322. {
  1323. Object result;
  1324. result = HttpContext.Current.Application[name];
  1325. if (result == null)
  1326. {
  1327. //HttpContext.Current.Response.Redirect(Config.SessionTimeOutUrl);
  1328. throw new PigeonCms.CustomException("Missed _Application '" + name + "'", CustomExceptionSeverity.Warning, CustomExceptionLogLevel.Log);
  1329. }
  1330. else
  1331. {
  1332. return result;
  1333. }
  1334. }
  1335. public static string _SessionID()
  1336. {
  1337. string res = "";
  1338. if (HttpContext.Current.Session != null)
  1339. res = HttpContext.Current.Session.SessionID;
  1340. return res;
  1341. }
  1342. public static string BuildQueryString(string url, NameValueCollection parameters)
  1343. {
  1344. return BuildQueryString(url, parameters, false);
  1345. }
  1346. public static string BuildQueryString(string url, NameValueCollection parameters, bool addAuthority)
  1347. {
  1348. if (string.IsNullOrEmpty(url))
  1349. {
  1350. url = "";
  1351. if (addAuthority)
  1352. url += HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority;
  1353. url += HttpContext.Current.Request.Path;
  1354. }
  1355. StringBuilder sb = new StringBuilder(url);
  1356. /*if (url.Contains(".aspx?"))
  1357. sb.Append("&");
  1358. else*/
  1359. sb.Append("?");
  1360. IEnumerator parEnumerator = parameters.GetEnumerator();
  1361. while (parEnumerator.MoveNext())
  1362. {
  1363. // get the current query parameter
  1364. string key = parEnumerator.Current.ToString();
  1365. // insert the parameter into the url
  1366. sb.Append(string.Format("{0}={1}&", key, HttpUtility.UrlEncode(parameters[key])));
  1367. }
  1368. var qry = HttpContext.Current.Request.QueryString;
  1369. IEnumerator qryEnumerator = qry.GetEnumerator();
  1370. while (qryEnumerator.MoveNext())
  1371. {
  1372. bool add = true;
  1373. // get the current query parameter
  1374. string key = qryEnumerator.Current.ToString();
  1375. parEnumerator.Reset();
  1376. while (parEnumerator.MoveNext())
  1377. {
  1378. if (key == parEnumerator.Current.ToString())
  1379. {
  1380. add = false;
  1381. break;
  1382. }
  1383. }
  1384. if (add)
  1385. sb.Append(string.Format("{0}={1}&", key, HttpUtility.UrlEncode(qry[key])));
  1386. }
  1387. // remove the last ampersand
  1388. sb.Remove(sb.Length - 1, 1);
  1389. return sb.ToString();
  1390. }
  1391. /// <summary>
  1392. /// wrapper for HttpContext.Current.Request.QueryString
  1393. /// </summary>
  1394. /// <param name="name">the param name</param>
  1395. /// <returns>the query string value. "" if param is null</returns>
  1396. public static string _QueryString(string name)
  1397. {
  1398. string result = "";
  1399. if (HttpContext.Current.Request.QueryString[name] != null)
  1400. result = HttpContext.Current.Request.QueryString[name].ToString();
  1401. return result;
  1402. }
  1403. /// <summary>
  1404. /// Generic Recursive overload of Page.FindControl
  1405. /// </summary>
  1406. /// <typeparam name="T">type of the control</typeparam>
  1407. /// <param name="parentControl">root control</param>
  1408. /// <param name="id">Cotrol Id identifier</param>
  1409. /// <returns></returns>
  1410. public static T FindControlRecursive<T>(Control parentControl, string id) where T: Control
  1411. {
  1412. T ctrl = default(T);
  1413. if ((parentControl is T) && (parentControl.ID == id))
  1414. return (T)parentControl;
  1415. foreach (Control c in parentControl.Controls)
  1416. {
  1417. ctrl = FindControlRecursive<T>(c, id);
  1418. if (ctrl != null) break;
  1419. }
  1420. return ctrl;
  1421. }
  1422. private static Control FindControlRecursive(Control parentControl, string id)
  1423. {
  1424. return FindControlRecursive<Control>(parentControl, id);
  1425. }
  1426. public enum TristateBool
  1427. {
  1428. False = 0,
  1429. True,
  1430. NotSet
  1431. }
  1432. public static void CopyFolder(string sourceFolder, string destFolder)
  1433. {
  1434. if (!Directory.Exists(sourceFolder))
  1435. throw new Exception("source folder not found ("+ sourceFolder +")");
  1436. if (!Directory.Exists( destFolder ))
  1437. Directory.CreateDirectory( destFolder );
  1438. string[] files = Directory.GetFiles( sourceFolder );
  1439. foreach (string file in files)
  1440. {
  1441. string name = Path.GetFileName(file);
  1442. string dest = Path.Combine(destFolder, name);
  1443. File.Copy(file, dest, true);
  1444. }
  1445. string[] folders = Directory.GetDirectories( sourceFolder );
  1446. foreach (string folder in folders)
  1447. {
  1448. string name = Path.GetFileName(folder);
  1449. string dest = Path.Combine(destFolder, name);
  1450. CopyFolder(folder, dest);
  1451. }
  1452. }
  1453. public static void DeleteFolderContent(string path)
  1454. {
  1455. DirectoryInfo dir = new DirectoryInfo(path);
  1456. if (dir.Exists)
  1457. {
  1458. FileInfo[] files = dir.GetFiles();
  1459. foreach (FileInfo file in files)
  1460. {
  1461. try
  1462. {
  1463. file.Delete();
  1464. }
  1465. catch { }
  1466. }
  1467. }
  1468. }
  1469. public static long GetDirectorySize(string virtualPath)
  1470. {
  1471. long res = 0;
  1472. string path = HttpContext.Current.Request.MapPath(virtualPath);
  1473. if (Directory.Exists(path))
  1474. {
  1475. string[] a = Directory.GetFiles(path, "*.*");
  1476. foreach (string name in a)
  1477. {
  1478. FileInfo info = new FileInfo(name);
  1479. res += info.Length;
  1480. }
  1481. }
  1482. return res;
  1483. }
  1484. /// <summary>
  1485. /// file length in B, KB, MB, GB
  1486. /// tnx to http://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-using-net
  1487. /// </summary>
  1488. public static string GetFileHumanLength(long fileLength)
  1489. {
  1490. string result = "";
  1491. if (fileLength > 0)
  1492. {
  1493. string[] sizes = { "B", "KB", "MB", "GB" };
  1494. double len = fileLength;
  1495. int order = 0;
  1496. while (len >= 1024 && order + 1 < sizes.Length)
  1497. {
  1498. order++;
  1499. len = len / 1024;
  1500. }
  1501. result = String.Format("{0:0.##} {1}", len, sizes[order]);
  1502. }
  1503. return result;
  1504. }
  1505. public static string GetFileExt(string fileName)
  1506. {
  1507. return fileName.Substring(fileName.LastIndexOf(".") + 1);
  1508. }
  1509. }
  1510. }