PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/Prebuild/src/Core/Utilities/Helper.cs

https://github.com/UbitUmarov/Ubit-opensim
C# | 575 lines | 335 code | 66 blank | 174 comment | 92 complexity | 7a0749dec0ce5453fc73dd11f89ce613 MD5 | raw file
  1. #region BSD License
  2. /*
  3. Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
  4. Redistribution and use in source and binary forms, with or without modification, are permitted
  5. provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice, this list of conditions
  7. and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
  9. and the following disclaimer in the documentation and/or other materials provided with the
  10. distribution.
  11. * The name of the author may not be used to endorse or promote products derived from this software
  12. without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
  14. BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  15. ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  16. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  17. OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  18. OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
  19. IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  20. */
  21. #endregion
  22. using System;
  23. using System.Collections.Generic;
  24. using System.Diagnostics;
  25. using System.IO;
  26. using System.Runtime.InteropServices;
  27. using System.Text.RegularExpressions;
  28. using System.Collections.Specialized;
  29. using System.Xml;
  30. using Prebuild.Core.Nodes;
  31. namespace Prebuild.Core.Utilities
  32. {
  33. /// <summary>
  34. ///
  35. /// </summary>
  36. public class Helper
  37. {
  38. #region Fields
  39. static bool checkForOSVariables;
  40. /// <summary>
  41. ///
  42. /// </summary>
  43. public static bool CheckForOSVariables
  44. {
  45. get
  46. {
  47. return checkForOSVariables;
  48. }
  49. set
  50. {
  51. checkForOSVariables = value;
  52. }
  53. }
  54. #endregion
  55. #region Public Methods
  56. #region String Parsing
  57. public delegate string StringLookup(string key);
  58. /// <summary>
  59. /// Gets a collection of StringLocationPair objects that represent the matches
  60. /// </summary>
  61. /// <param name="target">The target.</param>
  62. /// <param name="beforeGroup">The before group.</param>
  63. /// <param name="afterGroup">The after group.</param>
  64. /// <param name="includeDelimitersInSubstrings">if set to <c>true</c> [include delimiters in substrings].</param>
  65. /// <returns></returns>
  66. public static StringCollection FindGroups(string target, string beforeGroup, string afterGroup, bool includeDelimitersInSubstrings)
  67. {
  68. if( beforeGroup == null )
  69. {
  70. throw new ArgumentNullException("beforeGroup");
  71. }
  72. if( afterGroup == null )
  73. {
  74. throw new ArgumentNullException("afterGroup");
  75. }
  76. StringCollection results = new StringCollection();
  77. if(target == null || target.Length == 0)
  78. {
  79. return results;
  80. }
  81. int beforeMod = 0;
  82. int afterMod = 0;
  83. if(includeDelimitersInSubstrings)
  84. {
  85. //be sure to not exlude the delims
  86. beforeMod = beforeGroup.Length;
  87. afterMod = afterGroup.Length;
  88. }
  89. int startIndex = 0;
  90. while((startIndex = target.IndexOf(beforeGroup,startIndex)) != -1) {
  91. int endIndex = target.IndexOf(afterGroup,startIndex);//the index of the char after it
  92. if(endIndex == -1)
  93. {
  94. break;
  95. }
  96. int length = endIndex - startIndex - beforeGroup.Length;//move to the first char in the string
  97. string substring = substring = target.Substring(startIndex + beforeGroup.Length - beforeMod,
  98. length - afterMod);
  99. results.Add(substring);
  100. //results.Add(new StringLocationPair(substring,startIndex));
  101. startIndex = endIndex + 1;
  102. //the Interpolate*() methods will not work if expressions are expandded inside expression due to an optimization
  103. //so start after endIndex
  104. }
  105. return results;
  106. }
  107. /// <summary>
  108. /// Replaces the groups.
  109. /// </summary>
  110. /// <param name="target">The target.</param>
  111. /// <param name="beforeGroup">The before group.</param>
  112. /// <param name="afterGroup">The after group.</param>
  113. /// <param name="lookup">The lookup.</param>
  114. /// <returns></returns>
  115. public static string ReplaceGroups(string target, string beforeGroup, string afterGroup, StringLookup lookup) {
  116. if( target == null )
  117. {
  118. throw new ArgumentNullException("target");
  119. }
  120. //int targetLength = target.Length;
  121. StringCollection strings = FindGroups(target,beforeGroup,afterGroup,false);
  122. if( lookup == null )
  123. {
  124. throw new ArgumentNullException("lookup");
  125. }
  126. foreach(string substring in strings)
  127. {
  128. target = target.Replace(beforeGroup + substring + afterGroup, lookup(substring) );
  129. }
  130. return target;
  131. }
  132. /// <summary>
  133. /// Replaces ${var} statements in a string with the corresonding values as detirmined by the lookup delegate
  134. /// </summary>
  135. /// <param name="target">The target.</param>
  136. /// <param name="lookup">The lookup.</param>
  137. /// <returns></returns>
  138. public static string InterpolateForVariables(string target, StringLookup lookup)
  139. {
  140. return ReplaceGroups(target, "${" , "}" , lookup);
  141. }
  142. /// <summary>
  143. /// Replaces ${var} statements in a string with the corresonding environment variable with name var
  144. /// </summary>
  145. /// <param name="target"></param>
  146. /// <returns></returns>
  147. public static string InterpolateForEnvironmentVariables(string target)
  148. {
  149. return InterpolateForVariables(target, new StringLookup(Environment.GetEnvironmentVariable));
  150. }
  151. #endregion
  152. /// <summary>
  153. /// Translates the value.
  154. /// </summary>
  155. /// <param name="translateType">Type of the translate.</param>
  156. /// <param name="translationItem">The translation item.</param>
  157. /// <returns></returns>
  158. public static object TranslateValue(Type translateType, string translationItem)
  159. {
  160. if(translationItem == null)
  161. {
  162. return null;
  163. }
  164. try
  165. {
  166. string lowerVal = translationItem.ToLower();
  167. if(translateType == typeof(bool))
  168. {
  169. return (lowerVal == "true" || lowerVal == "1" || lowerVal == "y" || lowerVal == "yes" || lowerVal == "on");
  170. }
  171. else if(translateType == typeof(int))
  172. {
  173. return (Int32.Parse(translationItem));
  174. }
  175. else
  176. {
  177. return translationItem;
  178. }
  179. }
  180. catch(FormatException)
  181. {
  182. return null;
  183. }
  184. }
  185. /// <summary>
  186. /// Deletes if exists.
  187. /// </summary>
  188. /// <param name="file">The file.</param>
  189. /// <returns></returns>
  190. public static bool DeleteIfExists(string file)
  191. {
  192. string resFile = null;
  193. try
  194. {
  195. resFile = ResolvePath(file);
  196. }
  197. catch(ArgumentException)
  198. {
  199. return false;
  200. }
  201. if(!File.Exists(resFile))
  202. {
  203. return false;
  204. }
  205. File.Delete(resFile);
  206. return true;
  207. }
  208. static readonly char seperator = Path.DirectorySeparatorChar;
  209. // This little gem was taken from the NeL source, thanks guys!
  210. /// <summary>
  211. /// Makes a relative path
  212. /// </summary>
  213. /// <param name="startPath">Path to start from</param>
  214. /// <param name="endPath">Path to end at</param>
  215. /// <returns>Path that will get from startPath to endPath</returns>
  216. public static string MakePathRelativeTo(string startPath, string endPath)
  217. {
  218. string tmp = NormalizePath(startPath, seperator);
  219. string src = NormalizePath(endPath, seperator);
  220. string prefix = "";
  221. while(true)
  222. {
  223. if((String.Compare(tmp, 0, src, 0, tmp.Length) == 0))
  224. {
  225. string ret;
  226. int size = tmp.Length;
  227. if(size == src.Length)
  228. {
  229. return "./";
  230. }
  231. if((src.Length > tmp.Length) && src[tmp.Length - 1] != seperator)
  232. {
  233. }
  234. else
  235. {
  236. ret = prefix + endPath.Substring(size, endPath.Length - size);
  237. ret = ret.Trim();
  238. if(ret[0] == seperator)
  239. {
  240. ret = "." + ret;
  241. }
  242. return NormalizePath(ret);
  243. }
  244. }
  245. if(tmp.Length < 2)
  246. {
  247. break;
  248. }
  249. int lastPos = tmp.LastIndexOf(seperator, tmp.Length - 2);
  250. int prevPos = tmp.IndexOf(seperator);
  251. if((lastPos == prevPos) || (lastPos == -1))
  252. {
  253. break;
  254. }
  255. tmp = tmp.Substring(0, lastPos + 1);
  256. prefix += ".." + seperator.ToString();
  257. }
  258. return endPath;
  259. }
  260. /// <summary>
  261. /// Resolves the path.
  262. /// </summary>
  263. /// <param name="path">The path.</param>
  264. /// <returns></returns>
  265. public static string ResolvePath(string path)
  266. {
  267. string tmpPath = NormalizePath(path);
  268. if(tmpPath.Length < 1)
  269. {
  270. tmpPath = ".";
  271. }
  272. tmpPath = Path.GetFullPath(tmpPath);
  273. if(!File.Exists(tmpPath) && !Directory.Exists(tmpPath))
  274. {
  275. throw new ArgumentException("Path could not be resolved: " + tmpPath);
  276. }
  277. return tmpPath;
  278. }
  279. /// <summary>
  280. /// Normalizes the path.
  281. /// </summary>
  282. /// <param name="path">The path.</param>
  283. /// <param name="separatorCharacter">The separator character.</param>
  284. /// <returns></returns>
  285. public static string NormalizePath(string path, char separatorCharacter)
  286. {
  287. if(path == null || path == "" || path.Length < 1)
  288. {
  289. return "";
  290. }
  291. string tmpPath = path.Replace('\\', '/');
  292. tmpPath = tmpPath.Replace('/', separatorCharacter);
  293. return tmpPath;
  294. }
  295. /// <summary>
  296. /// Normalizes the path.
  297. /// </summary>
  298. /// <param name="path">The path.</param>
  299. /// <returns></returns>
  300. public static string NormalizePath(string path)
  301. {
  302. return NormalizePath(path, Path.DirectorySeparatorChar);
  303. }
  304. /// <summary>
  305. /// Ends the path.
  306. /// </summary>
  307. /// <param name="path">The path.</param>
  308. /// <param name="separatorCharacter">The separator character.</param>
  309. /// <returns></returns>
  310. public static string EndPath(string path, char separatorCharacter)
  311. {
  312. if(path == null || path == "" || path.Length < 1)
  313. {
  314. return "";
  315. }
  316. if(!path.EndsWith(separatorCharacter.ToString()))
  317. {
  318. return (path + separatorCharacter);
  319. }
  320. return path;
  321. }
  322. /// <summary>
  323. /// Ends the path.
  324. /// </summary>
  325. /// <param name="path">The path.</param>
  326. /// <returns></returns>
  327. public static string EndPath(string path)
  328. {
  329. return EndPath(path, Path.DirectorySeparatorChar);
  330. }
  331. /// <summary>
  332. /// Makes the file path.
  333. /// </summary>
  334. /// <param name="path">The path.</param>
  335. /// <param name="name">The name.</param>
  336. /// <param name="ext">The ext.</param>
  337. /// <returns></returns>
  338. public static string MakeFilePath(string path, string name, string ext)
  339. {
  340. string ret = EndPath(NormalizePath(path));
  341. if( name == null )
  342. {
  343. throw new ArgumentNullException("name");
  344. }
  345. ret += name;
  346. if(!name.EndsWith("." + ext))
  347. {
  348. ret += "." + ext;
  349. }
  350. //foreach(char c in Path.GetInvalidPathChars())
  351. //{
  352. // ret = ret.Replace(c, '_');
  353. //}
  354. return ret;
  355. }
  356. /// <summary>
  357. /// Makes the file path.
  358. /// </summary>
  359. /// <param name="path">The path.</param>
  360. /// <param name="name">The name.</param>
  361. /// <returns></returns>
  362. public static string MakeFilePath(string path, string name)
  363. {
  364. string ret = EndPath(NormalizePath(path));
  365. if( name == null )
  366. {
  367. throw new ArgumentNullException("name");
  368. }
  369. ret += name;
  370. //foreach (char c in Path.GetInvalidPathChars())
  371. //{
  372. // ret = ret.Replace(c, '_');
  373. //}
  374. return ret;
  375. }
  376. /// <summary>
  377. ///
  378. /// </summary>
  379. /// <param name="path"></param>
  380. /// <returns></returns>
  381. public static string MakeReferencePath(string path)
  382. {
  383. string ret = EndPath(NormalizePath(path));
  384. //foreach (char c in Path.GetInvalidPathChars())
  385. //{
  386. // ret = ret.Replace(c, '_');
  387. //}
  388. return ret;
  389. }
  390. /// <summary>
  391. /// Sets the current dir.
  392. /// </summary>
  393. /// <param name="path">The path.</param>
  394. public static void SetCurrentDir(string path)
  395. {
  396. if( path == null )
  397. {
  398. throw new ArgumentNullException("path");
  399. }
  400. if(path.Length < 1)
  401. {
  402. return;
  403. }
  404. Environment.CurrentDirectory = path;
  405. }
  406. /// <summary>
  407. /// Checks the type.
  408. /// </summary>
  409. /// <param name="typeToCheck">The type to check.</param>
  410. /// <param name="attr">The attr.</param>
  411. /// <param name="inter">The inter.</param>
  412. /// <returns></returns>
  413. public static object CheckType(Type typeToCheck, Type attr, Type inter)
  414. {
  415. if(typeToCheck == null || attr == null)
  416. {
  417. return null;
  418. }
  419. object[] attrs = typeToCheck.GetCustomAttributes(attr, false);
  420. if(attrs == null || attrs.Length < 1)
  421. {
  422. return null;
  423. }
  424. if( inter == null )
  425. {
  426. throw new ArgumentNullException("inter");
  427. }
  428. if(typeToCheck.GetInterface(inter.FullName) == null)
  429. {
  430. return null;
  431. }
  432. return attrs[0];
  433. }
  434. /// <summary>
  435. /// Attributes the value.
  436. /// </summary>
  437. /// <param name="node">The node.</param>
  438. /// <param name="attr">The attr.</param>
  439. /// <param name="def">The def.</param>
  440. /// <returns></returns>
  441. public static string AttributeValue(XmlNode node, string attr, string def)
  442. {
  443. if( node == null )
  444. {
  445. throw new ArgumentNullException("node");
  446. }
  447. if(node.Attributes[attr] == null)
  448. {
  449. return def;
  450. }
  451. string val = node.Attributes[attr].Value;
  452. if(!CheckForOSVariables)
  453. {
  454. return val;
  455. }
  456. return InterpolateForEnvironmentVariables(val);
  457. }
  458. /// <summary>
  459. /// Parses the boolean.
  460. /// </summary>
  461. /// <param name="node">The node.</param>
  462. /// <param name="attr">The attr.</param>
  463. /// <param name="defaultValue">if set to <c>true</c> [default value].</param>
  464. /// <returns></returns>
  465. public static bool ParseBoolean(XmlNode node, string attr, bool defaultValue)
  466. {
  467. if( node == null )
  468. {
  469. throw new ArgumentNullException("node");
  470. }
  471. if(node.Attributes[attr] == null)
  472. {
  473. return defaultValue;
  474. }
  475. return bool.Parse(node.Attributes[attr].Value);
  476. }
  477. /// <summary>
  478. /// Enums the attribute value.
  479. /// </summary>
  480. /// <param name="node">The node.</param>
  481. /// <param name="attr">The attr.</param>
  482. /// <param name="enumType">Type of the enum.</param>
  483. /// <param name="def">The def.</param>
  484. /// <returns></returns>
  485. public static object EnumAttributeValue(XmlNode node, string attr, Type enumType, object def)
  486. {
  487. if( def == null )
  488. {
  489. throw new ArgumentNullException("def");
  490. }
  491. string val = AttributeValue(node, attr, def.ToString());
  492. return Enum.Parse(enumType, val, true);
  493. }
  494. /// <summary>
  495. ///
  496. /// </summary>
  497. /// <param name="assemblyName"></param>
  498. /// <param name="projectType"></param>
  499. /// <returns></returns>
  500. public static string AssemblyFullName(string assemblyName, ProjectType projectType)
  501. {
  502. return assemblyName + (projectType == ProjectType.Library ? ".dll" : ".exe");
  503. }
  504. #endregion
  505. }
  506. }