Util.cs 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Generic;
  30. using System.Data;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.IO.Compression;
  34. using System.Net;
  35. using System.Net.Sockets;
  36. using System.Reflection;
  37. using System.Runtime.Serialization;
  38. using System.Runtime.Serialization.Formatters.Binary;
  39. using System.Security.Cryptography;
  40. using System.Text;
  41. using System.Text.RegularExpressions;
  42. using System.Xml;
  43. using System.Threading;
  44. using log4net;
  45. using Nini.Config;
  46. using Nwc.XmlRpc;
  47. using BclExtras;
  48. using OpenMetaverse;
  49. using OpenMetaverse.StructuredData;
  50. using Amib.Threading;
  51. namespace OpenSim.Framework
  52. {
  53. /// <summary>
  54. /// The method used by Util.FireAndForget for asynchronously firing events
  55. /// </summary>
  56. public enum FireAndForgetMethod
  57. {
  58. UnsafeQueueUserWorkItem,
  59. QueueUserWorkItem,
  60. BeginInvoke,
  61. SmartThreadPool,
  62. Thread,
  63. }
  64. /// <summary>
  65. /// Miscellaneous utility functions
  66. /// </summary>
  67. public class Util
  68. {
  69. private static SmartThreadPool m_ThreadPool = null;
  70. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  71. private static uint nextXferID = 5000;
  72. private static Random randomClass = new Random();
  73. // Get a list of invalid file characters (OS dependent)
  74. private static string regexInvalidFileChars = "[" + new String(Path.GetInvalidFileNameChars()) + "]";
  75. private static string regexInvalidPathChars = "[" + new String(Path.GetInvalidPathChars()) + "]";
  76. private static object XferLock = new object();
  77. // Unix-epoch starts at January 1st 1970, 00:00:00 UTC. And all our times in the server are (or at least should be) in UTC.
  78. private static readonly DateTime unixEpoch =
  79. DateTime.ParseExact("1970-01-01 00:00:00 +0", "yyyy-MM-dd hh:mm:ss z", DateTimeFormatInfo.InvariantInfo).ToUniversalTime();
  80. public static readonly Regex UUIDPattern
  81. = new Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
  82. public static FireAndForgetMethod FireAndForgetMethod = FireAndForgetMethod.SmartThreadPool;
  83. /// <summary>
  84. /// Linear interpolates B<->C using percent A
  85. /// </summary>
  86. /// <param name="a"></param>
  87. /// <param name="b"></param>
  88. /// <param name="c"></param>
  89. /// <returns></returns>
  90. public static double lerp(double a, double b, double c)
  91. {
  92. return (b*a) + (c*(1 - a));
  93. }
  94. /// <summary>
  95. /// Bilinear Interpolate, see Lerp but for 2D using 'percents' X & Y.
  96. /// Layout:
  97. /// A B
  98. /// C D
  99. /// A<->C = Y
  100. /// C<->D = X
  101. /// </summary>
  102. /// <param name="x"></param>
  103. /// <param name="y"></param>
  104. /// <param name="a"></param>
  105. /// <param name="b"></param>
  106. /// <param name="c"></param>
  107. /// <param name="d"></param>
  108. /// <returns></returns>
  109. public static double lerp2D(double x, double y, double a, double b, double c, double d)
  110. {
  111. return lerp(y, lerp(x, a, b), lerp(x, c, d));
  112. }
  113. public static Encoding UTF8 = Encoding.UTF8;
  114. /// <value>
  115. /// Well known UUID for the blank texture used in the Linden SL viewer version 1.20 (and hopefully onwards)
  116. /// </value>
  117. public static UUID BLANK_TEXTURE_UUID = new UUID("5748decc-f629-461c-9a36-a35a221fe21f");
  118. #region Vector Equations
  119. /// <summary>
  120. /// Get the distance between two 3d vectors
  121. /// </summary>
  122. /// <param name="a">A 3d vector</param>
  123. /// <param name="b">A 3d vector</param>
  124. /// <returns>The distance between the two vectors</returns>
  125. public static double GetDistanceTo(Vector3 a, Vector3 b)
  126. {
  127. float dx = a.X - b.X;
  128. float dy = a.Y - b.Y;
  129. float dz = a.Z - b.Z;
  130. return Math.Sqrt(dx * dx + dy * dy + dz * dz);
  131. }
  132. /// <summary>
  133. /// Returns true if the distance beween A and B is less than amount. Significantly faster than GetDistanceTo since it eliminates the Sqrt.
  134. /// </summary>
  135. /// <param name="a"></param>
  136. /// <param name="b"></param>
  137. /// <param name="amount"></param>
  138. /// <returns></returns>
  139. public static bool DistanceLessThan(Vector3 a, Vector3 b, double amount)
  140. {
  141. float dx = a.X - b.X;
  142. float dy = a.Y - b.Y;
  143. float dz = a.Z - b.Z;
  144. return (dx*dx + dy*dy + dz*dz) < (amount*amount);
  145. }
  146. /// <summary>
  147. /// Get the magnitude of a 3d vector
  148. /// </summary>
  149. /// <param name="a">A 3d vector</param>
  150. /// <returns>The magnitude of the vector</returns>
  151. public static double GetMagnitude(Vector3 a)
  152. {
  153. return Math.Sqrt((a.X * a.X) + (a.Y * a.Y) + (a.Z * a.Z));
  154. }
  155. /// <summary>
  156. /// Get a normalized form of a 3d vector
  157. /// </summary>
  158. /// <param name="a">A 3d vector</param>
  159. /// <returns>A new vector which is normalized form of the vector</returns>
  160. /// <remarks>The vector paramater cannot be <0,0,0></remarks>
  161. public static Vector3 GetNormalizedVector(Vector3 a)
  162. {
  163. if (IsZeroVector(a))
  164. throw new ArgumentException("Vector paramater cannot be a zero vector.");
  165. float Mag = (float) GetMagnitude(a);
  166. return new Vector3(a.X / Mag, a.Y / Mag, a.Z / Mag);
  167. }
  168. /// <summary>
  169. /// Returns if a vector is a zero vector (has all zero components)
  170. /// </summary>
  171. /// <returns></returns>
  172. public static bool IsZeroVector(Vector3 v)
  173. {
  174. if (v.X == 0 && v.Y == 0 && v.Z == 0)
  175. {
  176. return true;
  177. }
  178. return false;
  179. }
  180. # endregion
  181. public static Quaternion Axes2Rot(Vector3 fwd, Vector3 left, Vector3 up)
  182. {
  183. float s;
  184. float tr = (float) (fwd.X + left.Y + up.Z + 1.0);
  185. if (tr >= 1.0)
  186. {
  187. s = (float) (0.5 / Math.Sqrt(tr));
  188. return new Quaternion(
  189. (left.Z - up.Y) * s,
  190. (up.X - fwd.Z) * s,
  191. (fwd.Y - left.X) * s,
  192. (float) 0.25 / s);
  193. }
  194. else
  195. {
  196. float max = (left.Y > up.Z) ? left.Y : up.Z;
  197. if (max < fwd.X)
  198. {
  199. s = (float) (Math.Sqrt(fwd.X - (left.Y + up.Z) + 1.0));
  200. float x = (float) (s * 0.5);
  201. s = (float) (0.5 / s);
  202. return new Quaternion(
  203. x,
  204. (fwd.Y + left.X) * s,
  205. (up.X + fwd.Z) * s,
  206. (left.Z - up.Y) * s);
  207. }
  208. else if (max == left.Y)
  209. {
  210. s = (float) (Math.Sqrt(left.Y - (up.Z + fwd.X) + 1.0));
  211. float y = (float) (s * 0.5);
  212. s = (float) (0.5 / s);
  213. return new Quaternion(
  214. (fwd.Y + left.X) * s,
  215. y,
  216. (left.Z + up.Y) * s,
  217. (up.X - fwd.Z) * s);
  218. }
  219. else
  220. {
  221. s = (float) (Math.Sqrt(up.Z - (fwd.X + left.Y) + 1.0));
  222. float z = (float) (s * 0.5);
  223. s = (float) (0.5 / s);
  224. return new Quaternion(
  225. (up.X + fwd.Z) * s,
  226. (left.Z + up.Y) * s,
  227. z,
  228. (fwd.Y - left.X) * s);
  229. }
  230. }
  231. }
  232. public static Random RandomClass
  233. {
  234. get { return randomClass; }
  235. }
  236. public static ulong UIntsToLong(uint X, uint Y)
  237. {
  238. return Utils.UIntsToLong(X, Y);
  239. }
  240. public static T Clamp<T>(T x, T min, T max)
  241. where T : IComparable<T>
  242. {
  243. return x.CompareTo(max) > 0 ? max :
  244. x.CompareTo(min) < 0 ? min :
  245. x;
  246. }
  247. public static uint GetNextXferID()
  248. {
  249. uint id = 0;
  250. lock (XferLock)
  251. {
  252. id = nextXferID;
  253. nextXferID++;
  254. }
  255. return id;
  256. }
  257. public static string GetFileName(string file)
  258. {
  259. // Return just the filename on UNIX platforms
  260. // TODO: this should be customisable with a prefix, but that's something to do later.
  261. if (Environment.OSVersion.Platform == PlatformID.Unix)
  262. {
  263. return file;
  264. }
  265. // Return %APPDATA%/OpenSim/file for 2K/XP/NT/2K3/VISTA
  266. // TODO: Switch this to System.Enviroment.SpecialFolders.ApplicationData
  267. if (Environment.OSVersion.Platform == PlatformID.Win32NT)
  268. {
  269. if (!Directory.Exists("%APPDATA%\\OpenSim\\"))
  270. {
  271. Directory.CreateDirectory("%APPDATA%\\OpenSim");
  272. }
  273. return "%APPDATA%\\OpenSim\\" + file;
  274. }
  275. // Catch all - covers older windows versions
  276. // (but those probably wont work anyway)
  277. return file;
  278. }
  279. /// <summary>
  280. /// Debug utility function to convert unbroken strings of XML into something human readable for occasional debugging purposes.
  281. ///
  282. /// Please don't delete me even if I appear currently unused!
  283. /// </summary>
  284. /// <param name="rawXml"></param>
  285. /// <returns></returns>
  286. public static string GetFormattedXml(string rawXml)
  287. {
  288. XmlDocument xd = new XmlDocument();
  289. xd.LoadXml(rawXml);
  290. StringBuilder sb = new StringBuilder();
  291. StringWriter sw = new StringWriter(sb);
  292. XmlTextWriter xtw = new XmlTextWriter(sw);
  293. xtw.Formatting = Formatting.Indented;
  294. try
  295. {
  296. xd.WriteTo(xtw);
  297. }
  298. finally
  299. {
  300. xtw.Close();
  301. }
  302. return sb.ToString();
  303. }
  304. public static bool IsEnvironmentSupported(ref string reason)
  305. {
  306. // Must have .NET 2.0 (Generics / libsl)
  307. if (Environment.Version.Major < 2)
  308. {
  309. reason = ".NET 1.0/1.1 lacks components that is used by OpenSim";
  310. return false;
  311. }
  312. // Windows 95/98/ME are unsupported
  313. if (Environment.OSVersion.Platform == PlatformID.Win32Windows &&
  314. Environment.OSVersion.Platform != PlatformID.Win32NT)
  315. {
  316. reason = "Windows 95/98/ME will not run OpenSim";
  317. return false;
  318. }
  319. // Windows 2000 / Pre-SP2 XP
  320. if (Environment.OSVersion.Version.Major == 5 &&
  321. Environment.OSVersion.Version.Minor == 0)
  322. {
  323. reason = "Please update to Windows XP Service Pack 2 or Server2003";
  324. return false;
  325. }
  326. return true;
  327. }
  328. public static int UnixTimeSinceEpoch()
  329. {
  330. return ToUnixTime(DateTime.UtcNow);
  331. }
  332. public static int ToUnixTime(DateTime stamp)
  333. {
  334. TimeSpan t = stamp.ToUniversalTime() - unixEpoch;
  335. return (int) t.TotalSeconds;
  336. }
  337. public static DateTime ToDateTime(ulong seconds)
  338. {
  339. DateTime epoch = unixEpoch;
  340. return epoch.AddSeconds(seconds);
  341. }
  342. public static DateTime ToDateTime(int seconds)
  343. {
  344. DateTime epoch = unixEpoch;
  345. return epoch.AddSeconds(seconds);
  346. }
  347. /// <summary>
  348. /// Return an md5 hash of the given string
  349. /// </summary>
  350. /// <param name="data"></param>
  351. /// <returns></returns>
  352. public static string Md5Hash(string data)
  353. {
  354. byte[] dataMd5 = ComputeMD5Hash(data);
  355. StringBuilder sb = new StringBuilder();
  356. for (int i = 0; i < dataMd5.Length; i++)
  357. sb.AppendFormat("{0:x2}", dataMd5[i]);
  358. return sb.ToString();
  359. }
  360. private static byte[] ComputeMD5Hash(string data)
  361. {
  362. MD5 md5 = MD5.Create();
  363. return md5.ComputeHash(Encoding.Default.GetBytes(data));
  364. }
  365. /// <summary>
  366. /// Return an SHA1 hash of the given string
  367. /// </summary>
  368. /// <param name="data"></param>
  369. /// <returns></returns>
  370. public static string SHA1Hash(string data)
  371. {
  372. byte[] hash = ComputeSHA1Hash(data);
  373. return BitConverter.ToString(hash).Replace("-", String.Empty);
  374. }
  375. private static byte[] ComputeSHA1Hash(string src)
  376. {
  377. SHA1CryptoServiceProvider SHA1 = new SHA1CryptoServiceProvider();
  378. return SHA1.ComputeHash(Encoding.Default.GetBytes(src));
  379. }
  380. public static int fast_distance2d(int x, int y)
  381. {
  382. x = Math.Abs(x);
  383. y = Math.Abs(y);
  384. int min = Math.Min(x, y);
  385. return (x + y - (min >> 1) - (min >> 2) + (min >> 4));
  386. }
  387. public static bool IsOutsideView(uint oldx, uint newx, uint oldy, uint newy)
  388. {
  389. // Eventually this will be a function of the draw distance / camera position too.
  390. return (((int)Math.Abs((int)(oldx - newx)) > 1) || ((int)Math.Abs((int)(oldy - newy)) > 1));
  391. }
  392. public static string FieldToString(byte[] bytes)
  393. {
  394. return FieldToString(bytes, String.Empty);
  395. }
  396. /// <summary>
  397. /// Convert a variable length field (byte array) to a string, with a
  398. /// field name prepended to each line of the output
  399. /// </summary>
  400. /// <remarks>If the byte array has unprintable characters in it, a
  401. /// hex dump will be put in the string instead</remarks>
  402. /// <param name="bytes">The byte array to convert to a string</param>
  403. /// <param name="fieldName">A field name to prepend to each line of output</param>
  404. /// <returns>An ASCII string or a string containing a hex dump, minus
  405. /// the null terminator</returns>
  406. public static string FieldToString(byte[] bytes, string fieldName)
  407. {
  408. // Check for a common case
  409. if (bytes.Length == 0) return String.Empty;
  410. StringBuilder output = new StringBuilder();
  411. bool printable = true;
  412. for (int i = 0; i < bytes.Length; ++i)
  413. {
  414. // Check if there are any unprintable characters in the array
  415. if ((bytes[i] < 0x20 || bytes[i] > 0x7E) && bytes[i] != 0x09
  416. && bytes[i] != 0x0D && bytes[i] != 0x0A && bytes[i] != 0x00)
  417. {
  418. printable = false;
  419. break;
  420. }
  421. }
  422. if (printable)
  423. {
  424. if (fieldName.Length > 0)
  425. {
  426. output.Append(fieldName);
  427. output.Append(": ");
  428. }
  429. output.Append(CleanString(Util.UTF8.GetString(bytes, 0, bytes.Length - 1)));
  430. }
  431. else
  432. {
  433. for (int i = 0; i < bytes.Length; i += 16)
  434. {
  435. if (i != 0)
  436. output.Append(Environment.NewLine);
  437. if (fieldName.Length > 0)
  438. {
  439. output.Append(fieldName);
  440. output.Append(": ");
  441. }
  442. for (int j = 0; j < 16; j++)
  443. {
  444. if ((i + j) < bytes.Length)
  445. output.Append(String.Format("{0:X2} ", bytes[i + j]));
  446. else
  447. output.Append(" ");
  448. }
  449. for (int j = 0; j < 16 && (i + j) < bytes.Length; j++)
  450. {
  451. if (bytes[i + j] >= 0x20 && bytes[i + j] < 0x7E)
  452. output.Append((char) bytes[i + j]);
  453. else
  454. output.Append(".");
  455. }
  456. }
  457. }
  458. return output.ToString();
  459. }
  460. /// <summary>
  461. /// Converts a URL to a IPAddress
  462. /// </summary>
  463. /// <param name="url">URL Standard Format</param>
  464. /// <returns>A resolved IP Address</returns>
  465. public static IPAddress GetHostFromURL(string url)
  466. {
  467. return GetHostFromDNS(url.Split(new char[] {'/', ':'})[3]);
  468. }
  469. /// <summary>
  470. /// Returns a IP address from a specified DNS, favouring IPv4 addresses.
  471. /// </summary>
  472. /// <param name="dnsAddress">DNS Hostname</param>
  473. /// <returns>An IP address, or null</returns>
  474. public static IPAddress GetHostFromDNS(string dnsAddress)
  475. {
  476. // Is it already a valid IP? No need to look it up.
  477. IPAddress ipa;
  478. if (IPAddress.TryParse(dnsAddress, out ipa))
  479. return ipa;
  480. IPAddress[] hosts = null;
  481. // Not an IP, lookup required
  482. try
  483. {
  484. hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  485. }
  486. catch (Exception e)
  487. {
  488. m_log.ErrorFormat("[UTIL]: An error occurred while resolving {0}, {1}", dnsAddress, e);
  489. // Still going to throw the exception on for now, since this was what was happening in the first place
  490. throw e;
  491. }
  492. foreach (IPAddress host in hosts)
  493. {
  494. if (host.AddressFamily == AddressFamily.InterNetwork)
  495. {
  496. return host;
  497. }
  498. }
  499. if (hosts.Length > 0)
  500. return hosts[0];
  501. return null;
  502. }
  503. public static Uri GetURI(string protocol, string hostname, int port, string path)
  504. {
  505. return new UriBuilder(protocol, hostname, port, path).Uri;
  506. }
  507. /// <summary>
  508. /// Gets a list of all local system IP addresses
  509. /// </summary>
  510. /// <returns></returns>
  511. public static IPAddress[] GetLocalHosts()
  512. {
  513. return Dns.GetHostAddresses(Dns.GetHostName());
  514. }
  515. public static IPAddress GetLocalHost()
  516. {
  517. string dnsAddress = "localhost";
  518. IPAddress[] hosts = Dns.GetHostEntry(dnsAddress).AddressList;
  519. foreach (IPAddress host in hosts)
  520. {
  521. if (!IPAddress.IsLoopback(host) && host.AddressFamily == AddressFamily.InterNetwork)
  522. {
  523. return host;
  524. }
  525. }
  526. if (hosts.Length > 0)
  527. {
  528. foreach (IPAddress host in hosts)
  529. {
  530. if (host.AddressFamily == AddressFamily.InterNetwork)
  531. return host;
  532. }
  533. // Well all else failed...
  534. return hosts[0];
  535. }
  536. return null;
  537. }
  538. /// <summary>
  539. /// Removes all invalid path chars (OS dependent)
  540. /// </summary>
  541. /// <param name="path">path</param>
  542. /// <returns>safe path</returns>
  543. public static string safePath(string path)
  544. {
  545. return Regex.Replace(path, regexInvalidPathChars, String.Empty);
  546. }
  547. /// <summary>
  548. /// Removes all invalid filename chars (OS dependent)
  549. /// </summary>
  550. /// <param name="path">filename</param>
  551. /// <returns>safe filename</returns>
  552. public static string safeFileName(string filename)
  553. {
  554. return Regex.Replace(filename, regexInvalidFileChars, String.Empty);
  555. ;
  556. }
  557. //
  558. // directory locations
  559. //
  560. public static string homeDir()
  561. {
  562. string temp;
  563. // string personal=(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
  564. // temp = Path.Combine(personal,".OpenSim");
  565. temp = ".";
  566. return temp;
  567. }
  568. public static string assetsDir()
  569. {
  570. return Path.Combine(configDir(), "assets");
  571. }
  572. public static string inventoryDir()
  573. {
  574. return Path.Combine(configDir(), "inventory");
  575. }
  576. public static string configDir()
  577. {
  578. return ".";
  579. }
  580. public static string dataDir()
  581. {
  582. return ".";
  583. }
  584. public static string logDir()
  585. {
  586. return ".";
  587. }
  588. // From: http://coercedcode.blogspot.com/2008/03/c-generate-unique-filenames-within.html
  589. public static string GetUniqueFilename(string FileName)
  590. {
  591. int count = 0;
  592. string Name;
  593. if (File.Exists(FileName))
  594. {
  595. FileInfo f = new FileInfo(FileName);
  596. if (!String.IsNullOrEmpty(f.Extension))
  597. {
  598. Name = f.FullName.Substring(0, f.FullName.LastIndexOf('.'));
  599. }
  600. else
  601. {
  602. Name = f.FullName;
  603. }
  604. while (File.Exists(FileName))
  605. {
  606. count++;
  607. FileName = Name + count + f.Extension;
  608. }
  609. }
  610. return FileName;
  611. }
  612. // Nini (config) related Methods
  613. public static IConfigSource ConvertDataRowToXMLConfig(DataRow row, string fileName)
  614. {
  615. if (!File.Exists(fileName))
  616. {
  617. //create new file
  618. }
  619. XmlConfigSource config = new XmlConfigSource(fileName);
  620. AddDataRowToConfig(config, row);
  621. config.Save();
  622. return config;
  623. }
  624. public static void AddDataRowToConfig(IConfigSource config, DataRow row)
  625. {
  626. config.Configs.Add((string) row[0]);
  627. for (int i = 0; i < row.Table.Columns.Count; i++)
  628. {
  629. config.Configs[(string) row[0]].Set(row.Table.Columns[i].ColumnName, row[i]);
  630. }
  631. }
  632. public static float Clip(float x, float min, float max)
  633. {
  634. return Math.Min(Math.Max(x, min), max);
  635. }
  636. public static int Clip(int x, int min, int max)
  637. {
  638. return Math.Min(Math.Max(x, min), max);
  639. }
  640. /// <summary>
  641. /// Convert an UUID to a raw uuid string. Right now this is a string without hyphens.
  642. /// </summary>
  643. /// <param name="UUID"></param>
  644. /// <returns></returns>
  645. public static String ToRawUuidString(UUID UUID)
  646. {
  647. return UUID.Guid.ToString("n");
  648. }
  649. public static string CleanString(string input)
  650. {
  651. if (input.Length == 0)
  652. return input;
  653. int clip = input.Length;
  654. // Test for ++ string terminator
  655. int pos = input.IndexOf("\0");
  656. if (pos != -1 && pos < clip)
  657. clip = pos;
  658. // Test for CR
  659. pos = input.IndexOf("\r");
  660. if (pos != -1 && pos < clip)
  661. clip = pos;
  662. // Test for LF
  663. pos = input.IndexOf("\n");
  664. if (pos != -1 && pos < clip)
  665. clip = pos;
  666. // Truncate string before first end-of-line character found
  667. return input.Substring(0, clip);
  668. }
  669. /// <summary>
  670. /// returns the contents of /etc/issue on Unix Systems
  671. /// Use this for where it's absolutely necessary to implement platform specific stuff
  672. /// </summary>
  673. /// <returns></returns>
  674. public static string ReadEtcIssue()
  675. {
  676. try
  677. {
  678. StreamReader sr = new StreamReader("/etc/issue.net");
  679. string issue = sr.ReadToEnd();
  680. sr.Close();
  681. return issue;
  682. }
  683. catch (Exception)
  684. {
  685. return "";
  686. }
  687. }
  688. public static void SerializeToFile(string filename, Object obj)
  689. {
  690. IFormatter formatter = new BinaryFormatter();
  691. Stream stream = null;
  692. try
  693. {
  694. stream = new FileStream(
  695. filename, FileMode.Create,
  696. FileAccess.Write, FileShare.None);
  697. formatter.Serialize(stream, obj);
  698. }
  699. catch (Exception e)
  700. {
  701. m_log.Error(e.ToString());
  702. }
  703. finally
  704. {
  705. if (stream != null)
  706. {
  707. stream.Close();
  708. }
  709. }
  710. }
  711. public static Object DeserializeFromFile(string filename)
  712. {
  713. IFormatter formatter = new BinaryFormatter();
  714. Stream stream = null;
  715. Object ret = null;
  716. try
  717. {
  718. stream = new FileStream(
  719. filename, FileMode.Open,
  720. FileAccess.Read, FileShare.None);
  721. ret = formatter.Deserialize(stream);
  722. }
  723. catch (Exception e)
  724. {
  725. m_log.Error(e.ToString());
  726. }
  727. finally
  728. {
  729. if (stream != null)
  730. {
  731. stream.Close();
  732. }
  733. }
  734. return ret;
  735. }
  736. public static string Compress(string text)
  737. {
  738. byte[] buffer = Util.UTF8.GetBytes(text);
  739. MemoryStream memory = new MemoryStream();
  740. using (GZipStream compressor = new GZipStream(memory, CompressionMode.Compress, true))
  741. {
  742. compressor.Write(buffer, 0, buffer.Length);
  743. }
  744. memory.Position = 0;
  745. byte[] compressed = new byte[memory.Length];
  746. memory.Read(compressed, 0, compressed.Length);
  747. byte[] compressedBuffer = new byte[compressed.Length + 4];
  748. Buffer.BlockCopy(compressed, 0, compressedBuffer, 4, compressed.Length);
  749. Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, compressedBuffer, 0, 4);
  750. return Convert.ToBase64String(compressedBuffer);
  751. }
  752. public static string Decompress(string compressedText)
  753. {
  754. byte[] compressedBuffer = Convert.FromBase64String(compressedText);
  755. using (MemoryStream memory = new MemoryStream())
  756. {
  757. int msgLength = BitConverter.ToInt32(compressedBuffer, 0);
  758. memory.Write(compressedBuffer, 4, compressedBuffer.Length - 4);
  759. byte[] buffer = new byte[msgLength];
  760. memory.Position = 0;
  761. using (GZipStream decompressor = new GZipStream(memory, CompressionMode.Decompress))
  762. {
  763. decompressor.Read(buffer, 0, buffer.Length);
  764. }
  765. return Util.UTF8.GetString(buffer);
  766. }
  767. }
  768. public static XmlRpcResponse XmlRpcCommand(string url, string methodName, params object[] args)
  769. {
  770. return SendXmlRpcCommand(url, methodName, args);
  771. }
  772. public static XmlRpcResponse SendXmlRpcCommand(string url, string methodName, object[] args)
  773. {
  774. XmlRpcRequest client = new XmlRpcRequest(methodName, args);
  775. return client.Send(url, 6000);
  776. }
  777. /// <summary>
  778. /// Returns an error message that the user could not be found in the database
  779. /// </summary>
  780. /// <returns>XML string consisting of a error element containing individual error(s)</returns>
  781. public static XmlRpcResponse CreateUnknownUserErrorResponse()
  782. {
  783. XmlRpcResponse response = new XmlRpcResponse();
  784. Hashtable responseData = new Hashtable();
  785. responseData["error_type"] = "unknown_user";
  786. responseData["error_desc"] = "The user requested is not in the database";
  787. response.Value = responseData;
  788. return response;
  789. }
  790. /// <summary>
  791. /// Converts a byte array in big endian order into an ulong.
  792. /// </summary>
  793. /// <param name="bytes">
  794. /// The array of bytes
  795. /// </param>
  796. /// <returns>
  797. /// The extracted ulong
  798. /// </returns>
  799. public static ulong BytesToUInt64Big(byte[] bytes)
  800. {
  801. if (bytes.Length < 8) return 0;
  802. return ((ulong)bytes[0] << 56) | ((ulong)bytes[1] << 48) | ((ulong)bytes[2] << 40) | ((ulong)bytes[3] << 32) |
  803. ((ulong)bytes[4] << 24) | ((ulong)bytes[5] << 16) | ((ulong)bytes[6] << 8) | (ulong)bytes[7];
  804. }
  805. // used for RemoteParcelRequest (for "About Landmark")
  806. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y)
  807. {
  808. byte[] bytes =
  809. {
  810. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  811. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  812. (byte)x, (byte)(x >> 8), 0, 0,
  813. (byte)y, (byte)(y >> 8), 0, 0 };
  814. return new UUID(bytes, 0);
  815. }
  816. public static UUID BuildFakeParcelID(ulong regionHandle, uint x, uint y, uint z)
  817. {
  818. byte[] bytes =
  819. {
  820. (byte)regionHandle, (byte)(regionHandle >> 8), (byte)(regionHandle >> 16), (byte)(regionHandle >> 24),
  821. (byte)(regionHandle >> 32), (byte)(regionHandle >> 40), (byte)(regionHandle >> 48), (byte)(regionHandle << 56),
  822. (byte)x, (byte)(x >> 8), (byte)z, (byte)(z >> 8),
  823. (byte)y, (byte)(y >> 8), 0, 0 };
  824. return new UUID(bytes, 0);
  825. }
  826. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y)
  827. {
  828. byte[] bytes = parcelID.GetBytes();
  829. regionHandle = Utils.BytesToUInt64(bytes);
  830. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  831. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  832. }
  833. public static void ParseFakeParcelID(UUID parcelID, out ulong regionHandle, out uint x, out uint y, out uint z)
  834. {
  835. byte[] bytes = parcelID.GetBytes();
  836. regionHandle = Utils.BytesToUInt64(bytes);
  837. x = Utils.BytesToUInt(bytes, 8) & 0xffff;
  838. z = (Utils.BytesToUInt(bytes, 8) & 0xffff0000) >> 16;
  839. y = Utils.BytesToUInt(bytes, 12) & 0xffff;
  840. }
  841. public static void FakeParcelIDToGlobalPosition(UUID parcelID, out uint x, out uint y)
  842. {
  843. ulong regionHandle;
  844. uint rx, ry;
  845. ParseFakeParcelID(parcelID, out regionHandle, out x, out y);
  846. Utils.LongToUInts(regionHandle, out rx, out ry);
  847. x += rx;
  848. y += ry;
  849. }
  850. /// <summary>
  851. /// Get operating system information if available. Returns only the first 45 characters of information
  852. /// </summary>
  853. /// <returns>
  854. /// Operating system information. Returns an empty string if none was available.
  855. /// </returns>
  856. public static string GetOperatingSystemInformation()
  857. {
  858. string os = String.Empty;
  859. if (Environment.OSVersion.Platform != PlatformID.Unix)
  860. {
  861. os = Environment.OSVersion.ToString();
  862. }
  863. else
  864. {
  865. os = ReadEtcIssue();
  866. }
  867. if (os.Length > 45)
  868. {
  869. os = os.Substring(0, 45);
  870. }
  871. return os;
  872. }
  873. /// <summary>
  874. /// Is the given string a UUID?
  875. /// </summary>
  876. /// <param name="s"></param>
  877. /// <returns></returns>
  878. public static bool isUUID(string s)
  879. {
  880. return UUIDPattern.IsMatch(s);
  881. }
  882. public static string GetDisplayConnectionString(string connectionString)
  883. {
  884. int passPosition = 0;
  885. int passEndPosition = 0;
  886. string displayConnectionString = null;
  887. // hide the password in the connection string
  888. passPosition = connectionString.IndexOf("password", StringComparison.OrdinalIgnoreCase);
  889. passPosition = connectionString.IndexOf("=", passPosition);
  890. if (passPosition < connectionString.Length)
  891. passPosition += 1;
  892. passEndPosition = connectionString.IndexOf(";", passPosition);
  893. displayConnectionString = connectionString.Substring(0, passPosition);
  894. displayConnectionString += "***";
  895. displayConnectionString += connectionString.Substring(passEndPosition, connectionString.Length - passEndPosition);
  896. return displayConnectionString;
  897. }
  898. public static T ReadSettingsFromIniFile<T>(IConfig config, T settingsClass)
  899. {
  900. Type settingsType = settingsClass.GetType();
  901. FieldInfo[] fieldInfos = settingsType.GetFields();
  902. foreach (FieldInfo fieldInfo in fieldInfos)
  903. {
  904. if (!fieldInfo.IsStatic)
  905. {
  906. if (fieldInfo.FieldType == typeof(System.String))
  907. {
  908. fieldInfo.SetValue(settingsClass, config.Get(fieldInfo.Name, (string)fieldInfo.GetValue(settingsClass)));
  909. }
  910. else if (fieldInfo.FieldType == typeof(System.Boolean))
  911. {
  912. fieldInfo.SetValue(settingsClass, config.GetBoolean(fieldInfo.Name, (bool)fieldInfo.GetValue(settingsClass)));
  913. }
  914. else if (fieldInfo.FieldType == typeof(System.Int32))
  915. {
  916. fieldInfo.SetValue(settingsClass, config.GetInt(fieldInfo.Name, (int)fieldInfo.GetValue(settingsClass)));
  917. }
  918. else if (fieldInfo.FieldType == typeof(System.Single))
  919. {
  920. fieldInfo.SetValue(settingsClass, config.GetFloat(fieldInfo.Name, (float)fieldInfo.GetValue(settingsClass)));
  921. }
  922. else if (fieldInfo.FieldType == typeof(System.UInt32))
  923. {
  924. fieldInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(fieldInfo.Name, ((uint)fieldInfo.GetValue(settingsClass)).ToString())));
  925. }
  926. }
  927. }
  928. PropertyInfo[] propertyInfos = settingsType.GetProperties();
  929. foreach (PropertyInfo propInfo in propertyInfos)
  930. {
  931. if ((propInfo.CanRead) && (propInfo.CanWrite))
  932. {
  933. if (propInfo.PropertyType == typeof(System.String))
  934. {
  935. propInfo.SetValue(settingsClass, config.Get(propInfo.Name, (string)propInfo.GetValue(settingsClass, null)), null);
  936. }
  937. else if (propInfo.PropertyType == typeof(System.Boolean))
  938. {
  939. propInfo.SetValue(settingsClass, config.GetBoolean(propInfo.Name, (bool)propInfo.GetValue(settingsClass, null)), null);
  940. }
  941. else if (propInfo.PropertyType == typeof(System.Int32))
  942. {
  943. propInfo.SetValue(settingsClass, config.GetInt(propInfo.Name, (int)propInfo.GetValue(settingsClass, null)), null);
  944. }
  945. else if (propInfo.PropertyType == typeof(System.Single))
  946. {
  947. propInfo.SetValue(settingsClass, config.GetFloat(propInfo.Name, (float)propInfo.GetValue(settingsClass, null)), null);
  948. }
  949. if (propInfo.PropertyType == typeof(System.UInt32))
  950. {
  951. propInfo.SetValue(settingsClass, Convert.ToUInt32(config.Get(propInfo.Name, ((uint)propInfo.GetValue(settingsClass, null)).ToString())), null);
  952. }
  953. }
  954. }
  955. return settingsClass;
  956. }
  957. public static string Base64ToString(string str)
  958. {
  959. UTF8Encoding encoder = new UTF8Encoding();
  960. Decoder utf8Decode = encoder.GetDecoder();
  961. byte[] todecode_byte = Convert.FromBase64String(str);
  962. int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
  963. char[] decoded_char = new char[charCount];
  964. utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
  965. string result = new String(decoded_char);
  966. return result;
  967. }
  968. public static Guid GetHashGuid(string data, string salt)
  969. {
  970. byte[] hash = ComputeMD5Hash(data + salt);
  971. //string s = BitConverter.ToString(hash);
  972. Guid guid = new Guid(hash);
  973. return guid;
  974. }
  975. public static byte ConvertMaturityToAccessLevel(uint maturity)
  976. {
  977. byte retVal = 0;
  978. switch (maturity)
  979. {
  980. case 0: //PG
  981. retVal = 13;
  982. break;
  983. case 1: //Mature
  984. retVal = 21;
  985. break;
  986. case 2: // Adult
  987. retVal = 42;
  988. break;
  989. }
  990. return retVal;
  991. }
  992. /// <summary>
  993. /// Produces an OSDMap from its string representation on a stream
  994. /// </summary>
  995. /// <param name="data">The stream</param>
  996. /// <param name="length">The size of the data on the stream</param>
  997. /// <returns>The OSDMap or an exception</returns>
  998. public static OSDMap GetOSDMap(Stream stream, int length)
  999. {
  1000. byte[] data = new byte[length];
  1001. stream.Read(data, 0, length);
  1002. string strdata = Util.UTF8.GetString(data);
  1003. OSDMap args = null;
  1004. OSD buffer;
  1005. buffer = OSDParser.DeserializeJson(strdata);
  1006. if (buffer.Type == OSDType.Map)
  1007. {
  1008. args = (OSDMap)buffer;
  1009. return args;
  1010. }
  1011. return null;
  1012. }
  1013. public static string[] Glob(string path)
  1014. {
  1015. string vol=String.Empty;
  1016. if (Path.VolumeSeparatorChar != Path.DirectorySeparatorChar)
  1017. {
  1018. string[] vcomps = path.Split(new char[] {Path.VolumeSeparatorChar}, 2, StringSplitOptions.RemoveEmptyEntries);
  1019. if (vcomps.Length > 1)
  1020. {
  1021. path = vcomps[1];
  1022. vol = vcomps[0];
  1023. }
  1024. }
  1025. string[] comps = path.Split(new char[] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries);
  1026. // Glob
  1027. path = vol;
  1028. if (vol != String.Empty)
  1029. path += new String(new char[] {Path.VolumeSeparatorChar, Path.DirectorySeparatorChar});
  1030. else
  1031. path = new String(new char[] {Path.DirectorySeparatorChar});
  1032. List<string> paths = new List<string>();
  1033. List<string> found = new List<string>();
  1034. paths.Add(path);
  1035. int compIndex = -1;
  1036. foreach (string c in comps)
  1037. {
  1038. compIndex++;
  1039. List<string> addpaths = new List<string>();
  1040. foreach (string p in paths)
  1041. {
  1042. string[] dirs = Directory.GetDirectories(p, c);
  1043. if (dirs.Length != 0)
  1044. {
  1045. foreach (string dir in dirs)
  1046. addpaths.Add(Path.Combine(path, dir));
  1047. }
  1048. // Only add files if that is the last path component
  1049. if (compIndex == comps.Length - 1)
  1050. {
  1051. string[] files = Directory.GetFiles(p, c);
  1052. foreach (string f in files)
  1053. found.Add(f);
  1054. }
  1055. }
  1056. paths = addpaths;
  1057. }
  1058. return found.ToArray();
  1059. }
  1060. public static string ServerURI(string uri)
  1061. {
  1062. if (uri == string.Empty)
  1063. return string.Empty;
  1064. // Get rid of eventual slashes at the end
  1065. uri = uri.TrimEnd('/');
  1066. IPAddress ipaddr1 = null;
  1067. string port1 = "";
  1068. try
  1069. {
  1070. ipaddr1 = Util.GetHostFromURL(uri);
  1071. }
  1072. catch { }
  1073. try
  1074. {
  1075. port1 = uri.Split(new char[] { ':' })[2];
  1076. }
  1077. catch { }
  1078. // We tried our best to convert the domain names to IP addresses
  1079. return (ipaddr1 != null) ? "http://" + ipaddr1.ToString() + ":" + port1 : uri;
  1080. }
  1081. public static byte[] StringToBytes256(string str)
  1082. {
  1083. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1084. if (str.Length > 254) str = str.Remove(254);
  1085. if (!str.EndsWith("\0")) { str += "\0"; }
  1086. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1087. // might have gotten an oversized array even after the string trim
  1088. byte[] data = UTF8.GetBytes(str);
  1089. if (data.Length > 256)
  1090. {
  1091. Array.Resize<byte>(ref data, 256);
  1092. data[255] = 0;
  1093. }
  1094. return data;
  1095. }
  1096. public static byte[] StringToBytes1024(string str)
  1097. {
  1098. if (String.IsNullOrEmpty(str)) { return Utils.EmptyBytes; }
  1099. if (str.Length > 1023) str = str.Remove(1023);
  1100. if (!str.EndsWith("\0")) { str += "\0"; }
  1101. // Because this is UTF-8 encoding and not ASCII, it's possible we
  1102. // might have gotten an oversized array even after the string trim
  1103. byte[] data = UTF8.GetBytes(str);
  1104. if (data.Length > 1024)
  1105. {
  1106. Array.Resize<byte>(ref data, 1024);
  1107. data[1023] = 0;
  1108. }
  1109. return data;
  1110. }
  1111. #region FireAndForget Threading Pattern
  1112. /// <summary>
  1113. /// Created to work around a limitation in Mono with nested delegates
  1114. /// </summary>
  1115. private class FireAndForgetWrapper
  1116. {
  1117. public void FireAndForget(System.Threading.WaitCallback callback)
  1118. {
  1119. callback.BeginInvoke(null, EndFireAndForget, callback);
  1120. }
  1121. public void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1122. {
  1123. callback.BeginInvoke(obj, EndFireAndForget, callback);
  1124. }
  1125. private static void EndFireAndForget(IAsyncResult ar)
  1126. {
  1127. System.Threading.WaitCallback callback = (System.Threading.WaitCallback)ar.AsyncState;
  1128. try { callback.EndInvoke(ar); }
  1129. catch (Exception ex) { m_log.Error("[UTIL]: Asynchronous method threw an exception: " + ex.Message, ex); }
  1130. ar.AsyncWaitHandle.Close();
  1131. }
  1132. }
  1133. public static void FireAndForget(System.Threading.WaitCallback callback)
  1134. {
  1135. FireAndForget(callback, null);
  1136. }
  1137. public static void SetMaxThreads(int maxThreads)
  1138. {
  1139. if (m_ThreadPool != null)
  1140. return;
  1141. STPStartInfo startInfo = new STPStartInfo();
  1142. startInfo.IdleTimeout = 2000; // 2 seconds
  1143. startInfo.MaxWorkerThreads = maxThreads;
  1144. startInfo.MinWorkerThreads = 2;
  1145. startInfo.StackSize = 524288;
  1146. startInfo.ThreadPriority = ThreadPriority.Normal;
  1147. startInfo.StartSuspended = false;
  1148. m_ThreadPool = new SmartThreadPool(startInfo);
  1149. }
  1150. public static void FireAndForget(System.Threading.WaitCallback callback, object obj)
  1151. {
  1152. switch (FireAndForgetMethod)
  1153. {
  1154. case FireAndForgetMethod.UnsafeQueueUserWorkItem:
  1155. System.Threading.ThreadPool.UnsafeQueueUserWorkItem(callback, obj);
  1156. break;
  1157. case FireAndForgetMethod.QueueUserWorkItem:
  1158. System.Threading.ThreadPool.QueueUserWorkItem(callback, obj);
  1159. break;
  1160. case FireAndForgetMethod.BeginInvoke:
  1161. FireAndForgetWrapper wrapper = Singleton.GetInstance<FireAndForgetWrapper>();
  1162. wrapper.FireAndForget(callback, obj);
  1163. break;
  1164. case FireAndForgetMethod.SmartThreadPool:
  1165. m_ThreadPool.QueueWorkItem(delegate(object o) { callback(o); return null; }, obj);
  1166. break;
  1167. case FireAndForgetMethod.Thread:
  1168. System.Threading.Thread thread = new System.Threading.Thread(delegate(object o) { callback(o); });
  1169. thread.Start(obj);
  1170. break;
  1171. default:
  1172. throw new NotImplementedException();
  1173. }
  1174. }
  1175. #endregion FireAndForget Threading Pattern
  1176. }
  1177. }