Ext.cs 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Specialized;
  4. using System.IO;
  5. using System.IO.Compression;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Model.Services;
  10. using SocketHttpListener.Net;
  11. using HttpListenerResponse = SocketHttpListener.Net.HttpListenerResponse;
  12. using HttpStatusCode = SocketHttpListener.Net.HttpStatusCode;
  13. namespace SocketHttpListener
  14. {
  15. /// <summary>
  16. /// Provides a set of static methods for the websocket-sharp.
  17. /// </summary>
  18. public static class Ext
  19. {
  20. #region Private Const Fields
  21. private const string _tspecials = "()<>@,;:\\\"/[]?={} \t";
  22. #endregion
  23. #region Private Methods
  24. private static MemoryStream compress(this Stream stream)
  25. {
  26. var output = new MemoryStream();
  27. if (stream.Length == 0)
  28. return output;
  29. stream.Position = 0;
  30. using (var ds = new DeflateStream(output, CompressionMode.Compress, true))
  31. {
  32. stream.CopyTo(ds);
  33. //ds.Close(); // "BFINAL" set to 1.
  34. output.Position = 0;
  35. return output;
  36. }
  37. }
  38. private static byte[] decompress(this byte[] value)
  39. {
  40. if (value.Length == 0)
  41. return value;
  42. using (var input = new MemoryStream(value))
  43. {
  44. return input.decompressToArray();
  45. }
  46. }
  47. private static MemoryStream decompress(this Stream stream)
  48. {
  49. var output = new MemoryStream();
  50. if (stream.Length == 0)
  51. return output;
  52. stream.Position = 0;
  53. using (var ds = new DeflateStream(stream, CompressionMode.Decompress, true))
  54. {
  55. ds.CopyTo(output, true);
  56. return output;
  57. }
  58. }
  59. private static byte[] decompressToArray(this Stream stream)
  60. {
  61. using (var decomp = stream.decompress())
  62. {
  63. return decomp.ToArray();
  64. }
  65. }
  66. private static byte[] readBytes(this Stream stream, byte[] buffer, int offset, int length)
  67. {
  68. var len = stream.Read(buffer, offset, length);
  69. if (len < 1)
  70. return buffer.SubArray(0, offset);
  71. var tmp = 0;
  72. while (len < length)
  73. {
  74. tmp = stream.Read(buffer, offset + len, length - len);
  75. if (tmp < 1)
  76. break;
  77. len += tmp;
  78. }
  79. return len < length
  80. ? buffer.SubArray(0, offset + len)
  81. : buffer;
  82. }
  83. private static bool readBytes(
  84. this Stream stream, byte[] buffer, int offset, int length, Stream dest)
  85. {
  86. var bytes = stream.readBytes(buffer, offset, length);
  87. var len = bytes.Length;
  88. dest.Write(bytes, 0, len);
  89. return len == offset + length;
  90. }
  91. #endregion
  92. #region Internal Methods
  93. internal static byte[] Append(this ushort code, string reason)
  94. {
  95. using (var buffer = new MemoryStream())
  96. {
  97. var tmp = code.ToByteArrayInternally(ByteOrder.Big);
  98. buffer.Write(tmp, 0, 2);
  99. if (reason != null && reason.Length > 0)
  100. {
  101. tmp = Encoding.UTF8.GetBytes(reason);
  102. buffer.Write(tmp, 0, tmp.Length);
  103. }
  104. return buffer.ToArray();
  105. }
  106. }
  107. internal static string CheckIfClosable(this WebSocketState state)
  108. {
  109. return state == WebSocketState.Closing
  110. ? "While closing the WebSocket connection."
  111. : state == WebSocketState.Closed
  112. ? "The WebSocket connection has already been closed."
  113. : null;
  114. }
  115. internal static string CheckIfOpen(this WebSocketState state)
  116. {
  117. return state == WebSocketState.Connecting
  118. ? "A WebSocket connection isn't established."
  119. : state == WebSocketState.Closing
  120. ? "While closing the WebSocket connection."
  121. : state == WebSocketState.Closed
  122. ? "The WebSocket connection has already been closed."
  123. : null;
  124. }
  125. internal static string CheckIfValidControlData(this byte[] data, string paramName)
  126. {
  127. return data.Length > 125
  128. ? String.Format("'{0}' length must be less.", paramName)
  129. : null;
  130. }
  131. internal static string CheckIfValidSendData(this byte[] data)
  132. {
  133. return data == null
  134. ? "'data' must not be null."
  135. : null;
  136. }
  137. internal static string CheckIfValidSendData(this string data)
  138. {
  139. return data == null
  140. ? "'data' must not be null."
  141. : null;
  142. }
  143. internal static Stream Compress(this Stream stream, CompressionMethod method)
  144. {
  145. return method == CompressionMethod.Deflate
  146. ? stream.compress()
  147. : stream;
  148. }
  149. internal static bool Contains<T>(this IEnumerable<T> source, Func<T, bool> condition)
  150. {
  151. foreach (T elm in source)
  152. if (condition(elm))
  153. return true;
  154. return false;
  155. }
  156. internal static void CopyTo(this Stream src, Stream dest, bool setDefaultPosition)
  157. {
  158. var readLen = 0;
  159. var bufferLen = 256;
  160. var buffer = new byte[bufferLen];
  161. while ((readLen = src.Read(buffer, 0, bufferLen)) > 0)
  162. {
  163. dest.Write(buffer, 0, readLen);
  164. }
  165. if (setDefaultPosition)
  166. dest.Position = 0;
  167. }
  168. internal static byte[] Decompress(this byte[] value, CompressionMethod method)
  169. {
  170. return method == CompressionMethod.Deflate
  171. ? value.decompress()
  172. : value;
  173. }
  174. internal static byte[] DecompressToArray(this Stream stream, CompressionMethod method)
  175. {
  176. return method == CompressionMethod.Deflate
  177. ? stream.decompressToArray()
  178. : stream.ToByteArray();
  179. }
  180. /// <summary>
  181. /// Determines whether the specified <see cref="int"/> equals the specified <see cref="char"/>,
  182. /// and invokes the specified Action&lt;int&gt; delegate at the same time.
  183. /// </summary>
  184. /// <returns>
  185. /// <c>true</c> if <paramref name="value"/> equals <paramref name="c"/>;
  186. /// otherwise, <c>false</c>.
  187. /// </returns>
  188. /// <param name="value">
  189. /// An <see cref="int"/> to compare.
  190. /// </param>
  191. /// <param name="c">
  192. /// A <see cref="char"/> to compare.
  193. /// </param>
  194. /// <param name="action">
  195. /// An Action&lt;int&gt; delegate that references the method(s) called at
  196. /// the same time as comparing. An <see cref="int"/> parameter to pass to
  197. /// the method(s) is <paramref name="value"/>.
  198. /// </param>
  199. /// <exception cref="ArgumentOutOfRangeException">
  200. /// <paramref name="value"/> isn't between 0 and 255.
  201. /// </exception>
  202. internal static bool EqualsWith(this int value, char c, Action<int> action)
  203. {
  204. if (value < 0 || value > 255)
  205. throw new ArgumentOutOfRangeException("value");
  206. action(value);
  207. return value == c - 0;
  208. }
  209. internal static string GetMessage(this CloseStatusCode code)
  210. {
  211. return code == CloseStatusCode.ProtocolError
  212. ? "A WebSocket protocol error has occurred."
  213. : code == CloseStatusCode.IncorrectData
  214. ? "An incorrect data has been received."
  215. : code == CloseStatusCode.Abnormal
  216. ? "An exception has occurred."
  217. : code == CloseStatusCode.InconsistentData
  218. ? "An inconsistent data has been received."
  219. : code == CloseStatusCode.PolicyViolation
  220. ? "A policy violation has occurred."
  221. : code == CloseStatusCode.TooBig
  222. ? "A too big data has been received."
  223. : code == CloseStatusCode.IgnoreExtension
  224. ? "WebSocket client did not receive expected extension(s)."
  225. : code == CloseStatusCode.ServerError
  226. ? "WebSocket server got an internal error."
  227. : code == CloseStatusCode.TlsHandshakeFailure
  228. ? "An error has occurred while handshaking."
  229. : String.Empty;
  230. }
  231. internal static string GetNameInternal(this string nameAndValue, string separator)
  232. {
  233. var i = nameAndValue.IndexOf(separator);
  234. return i > 0
  235. ? nameAndValue.Substring(0, i).Trim()
  236. : null;
  237. }
  238. internal static string GetValueInternal(this string nameAndValue, string separator)
  239. {
  240. var i = nameAndValue.IndexOf(separator);
  241. return i >= 0 && i < nameAndValue.Length - 1
  242. ? nameAndValue.Substring(i + 1).Trim()
  243. : null;
  244. }
  245. internal static bool IsCompressionExtension(this string value, CompressionMethod method)
  246. {
  247. return value.StartsWith(method.ToExtensionString());
  248. }
  249. internal static bool IsPortNumber(this int value)
  250. {
  251. return value > 0 && value < 65536;
  252. }
  253. internal static bool IsReserved(this ushort code)
  254. {
  255. return code == (ushort)CloseStatusCode.Undefined ||
  256. code == (ushort)CloseStatusCode.NoStatusCode ||
  257. code == (ushort)CloseStatusCode.Abnormal ||
  258. code == (ushort)CloseStatusCode.TlsHandshakeFailure;
  259. }
  260. internal static bool IsReserved(this CloseStatusCode code)
  261. {
  262. return code == CloseStatusCode.Undefined ||
  263. code == CloseStatusCode.NoStatusCode ||
  264. code == CloseStatusCode.Abnormal ||
  265. code == CloseStatusCode.TlsHandshakeFailure;
  266. }
  267. internal static bool IsText(this string value)
  268. {
  269. var len = value.Length;
  270. for (var i = 0; i < len; i++)
  271. {
  272. char c = value[i];
  273. if (c < 0x20 && !"\r\n\t".Contains(c))
  274. return false;
  275. if (c == 0x7f)
  276. return false;
  277. if (c == '\n' && ++i < len)
  278. {
  279. c = value[i];
  280. if (!" \t".Contains(c))
  281. return false;
  282. }
  283. }
  284. return true;
  285. }
  286. internal static bool IsToken(this string value)
  287. {
  288. foreach (char c in value)
  289. if (c < 0x20 || c >= 0x7f || _tspecials.Contains(c))
  290. return false;
  291. return true;
  292. }
  293. internal static string Quote(this string value)
  294. {
  295. return value.IsToken()
  296. ? value
  297. : String.Format("\"{0}\"", value.Replace("\"", "\\\""));
  298. }
  299. internal static byte[] ReadBytes(this Stream stream, int length)
  300. {
  301. return stream.readBytes(new byte[length], 0, length);
  302. }
  303. internal static byte[] ReadBytes(this Stream stream, long length, int bufferLength)
  304. {
  305. using (var result = new MemoryStream())
  306. {
  307. var count = length / bufferLength;
  308. var rem = (int)(length % bufferLength);
  309. var buffer = new byte[bufferLength];
  310. var end = false;
  311. for (long i = 0; i < count; i++)
  312. {
  313. if (!stream.readBytes(buffer, 0, bufferLength, result))
  314. {
  315. end = true;
  316. break;
  317. }
  318. }
  319. if (!end && rem > 0)
  320. stream.readBytes(new byte[rem], 0, rem, result);
  321. return result.ToArray();
  322. }
  323. }
  324. internal static async Task<byte[]> ReadBytesAsync(this Stream stream, int length)
  325. {
  326. var buffer = new byte[length];
  327. var len = await stream.ReadAsync(buffer, 0, length).ConfigureAwait(false);
  328. var bytes = len < 1
  329. ? new byte[0]
  330. : len < length
  331. ? stream.readBytes(buffer, len, length - len)
  332. : buffer;
  333. return bytes;
  334. }
  335. internal static string RemovePrefix(this string value, params string[] prefixes)
  336. {
  337. var i = 0;
  338. foreach (var prefix in prefixes)
  339. {
  340. if (value.StartsWith(prefix))
  341. {
  342. i = prefix.Length;
  343. break;
  344. }
  345. }
  346. return i > 0
  347. ? value.Substring(i)
  348. : value;
  349. }
  350. internal static T[] Reverse<T>(this T[] array)
  351. {
  352. var len = array.Length;
  353. T[] reverse = new T[len];
  354. var end = len - 1;
  355. for (var i = 0; i <= end; i++)
  356. reverse[i] = array[end - i];
  357. return reverse;
  358. }
  359. internal static IEnumerable<string> SplitHeaderValue(
  360. this string value, params char[] separator)
  361. {
  362. var len = value.Length;
  363. var separators = new string(separator);
  364. var buffer = new StringBuilder(32);
  365. var quoted = false;
  366. var escaped = false;
  367. char c;
  368. for (var i = 0; i < len; i++)
  369. {
  370. c = value[i];
  371. if (c == '"')
  372. {
  373. if (escaped)
  374. escaped = !escaped;
  375. else
  376. quoted = !quoted;
  377. }
  378. else if (c == '\\')
  379. {
  380. if (i < len - 1 && value[i + 1] == '"')
  381. escaped = true;
  382. }
  383. else if (separators.Contains(c))
  384. {
  385. if (!quoted)
  386. {
  387. yield return buffer.ToString();
  388. buffer.Length = 0;
  389. continue;
  390. }
  391. }
  392. else {
  393. }
  394. buffer.Append(c);
  395. }
  396. if (buffer.Length > 0)
  397. yield return buffer.ToString();
  398. }
  399. internal static byte[] ToByteArray(this Stream stream)
  400. {
  401. using (var output = new MemoryStream())
  402. {
  403. stream.Position = 0;
  404. stream.CopyTo(output);
  405. return output.ToArray();
  406. }
  407. }
  408. internal static byte[] ToByteArrayInternally(this ushort value, ByteOrder order)
  409. {
  410. var bytes = BitConverter.GetBytes(value);
  411. if (!order.IsHostOrder())
  412. Array.Reverse(bytes);
  413. return bytes;
  414. }
  415. internal static byte[] ToByteArrayInternally(this ulong value, ByteOrder order)
  416. {
  417. var bytes = BitConverter.GetBytes(value);
  418. if (!order.IsHostOrder())
  419. Array.Reverse(bytes);
  420. return bytes;
  421. }
  422. internal static string ToExtensionString(
  423. this CompressionMethod method, params string[] parameters)
  424. {
  425. if (method == CompressionMethod.None)
  426. return String.Empty;
  427. var m = String.Format("permessage-{0}", method.ToString().ToLower());
  428. if (parameters == null || parameters.Length == 0)
  429. return m;
  430. return String.Format("{0}; {1}", m, parameters.ToString("; "));
  431. }
  432. internal static List<TSource> ToList<TSource>(this IEnumerable<TSource> source)
  433. {
  434. return new List<TSource>(source);
  435. }
  436. internal static ushort ToUInt16(this byte[] src, ByteOrder srcOrder)
  437. {
  438. return BitConverter.ToUInt16(src.ToHostOrder(srcOrder), 0);
  439. }
  440. internal static ulong ToUInt64(this byte[] src, ByteOrder srcOrder)
  441. {
  442. return BitConverter.ToUInt64(src.ToHostOrder(srcOrder), 0);
  443. }
  444. internal static string TrimEndSlash(this string value)
  445. {
  446. value = value.TrimEnd('/');
  447. return value.Length > 0
  448. ? value
  449. : "/";
  450. }
  451. internal static string Unquote(this string value)
  452. {
  453. var start = value.IndexOf('\"');
  454. var end = value.LastIndexOf('\"');
  455. if (start < end)
  456. value = value.Substring(start + 1, end - start - 1).Replace("\\\"", "\"");
  457. return value.Trim();
  458. }
  459. internal static void WriteBytes(this Stream stream, byte[] value)
  460. {
  461. using (var src = new MemoryStream(value))
  462. {
  463. src.CopyTo(stream);
  464. }
  465. }
  466. #endregion
  467. #region Public Methods
  468. /// <summary>
  469. /// Determines whether the specified <see cref="string"/> contains any of characters
  470. /// in the specified array of <see cref="char"/>.
  471. /// </summary>
  472. /// <returns>
  473. /// <c>true</c> if <paramref name="value"/> contains any of <paramref name="chars"/>;
  474. /// otherwise, <c>false</c>.
  475. /// </returns>
  476. /// <param name="value">
  477. /// A <see cref="string"/> to test.
  478. /// </param>
  479. /// <param name="chars">
  480. /// An array of <see cref="char"/> that contains characters to find.
  481. /// </param>
  482. public static bool Contains(this string value, params char[] chars)
  483. {
  484. return chars == null || chars.Length == 0
  485. ? true
  486. : value == null || value.Length == 0
  487. ? false
  488. : value.IndexOfAny(chars) != -1;
  489. }
  490. /// <summary>
  491. /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
  492. /// with the specified <paramref name="name"/>.
  493. /// </summary>
  494. /// <returns>
  495. /// <c>true</c> if <paramref name="collection"/> contains the entry
  496. /// with <paramref name="name"/>; otherwise, <c>false</c>.
  497. /// </returns>
  498. /// <param name="collection">
  499. /// A <see cref="QueryParamCollection"/> to test.
  500. /// </param>
  501. /// <param name="name">
  502. /// A <see cref="string"/> that represents the key of the entry to find.
  503. /// </param>
  504. public static bool Contains(this QueryParamCollection collection, string name)
  505. {
  506. return collection == null || collection.Count == 0
  507. ? false
  508. : collection[name] != null;
  509. }
  510. /// <summary>
  511. /// Determines whether the specified <see cref="QueryParamCollection"/> contains the entry
  512. /// with the specified both <paramref name="name"/> and <paramref name="value"/>.
  513. /// </summary>
  514. /// <returns>
  515. /// <c>true</c> if <paramref name="collection"/> contains the entry
  516. /// with both <paramref name="name"/> and <paramref name="value"/>;
  517. /// otherwise, <c>false</c>.
  518. /// </returns>
  519. /// <param name="collection">
  520. /// A <see cref="QueryParamCollection"/> to test.
  521. /// </param>
  522. /// <param name="name">
  523. /// A <see cref="string"/> that represents the key of the entry to find.
  524. /// </param>
  525. /// <param name="value">
  526. /// A <see cref="string"/> that represents the value of the entry to find.
  527. /// </param>
  528. public static bool Contains(this QueryParamCollection collection, string name, string value)
  529. {
  530. if (collection == null || collection.Count == 0)
  531. return false;
  532. var values = collection[name];
  533. if (values == null)
  534. return false;
  535. foreach (var v in values.Split(','))
  536. if (v.Trim().Equals(value, StringComparison.OrdinalIgnoreCase))
  537. return true;
  538. return false;
  539. }
  540. /// <summary>
  541. /// Emits the specified <see cref="EventHandler"/> delegate if it isn't <see langword="null"/>.
  542. /// </summary>
  543. /// <param name="eventHandler">
  544. /// A <see cref="EventHandler"/> to emit.
  545. /// </param>
  546. /// <param name="sender">
  547. /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
  548. /// </param>
  549. /// <param name="e">
  550. /// A <see cref="EventArgs"/> that contains no event data.
  551. /// </param>
  552. public static void Emit(this EventHandler eventHandler, object sender, EventArgs e)
  553. {
  554. if (eventHandler != null)
  555. eventHandler(sender, e);
  556. }
  557. /// <summary>
  558. /// Emits the specified <c>EventHandler&lt;TEventArgs&gt;</c> delegate
  559. /// if it isn't <see langword="null"/>.
  560. /// </summary>
  561. /// <param name="eventHandler">
  562. /// An <c>EventHandler&lt;TEventArgs&gt;</c> to emit.
  563. /// </param>
  564. /// <param name="sender">
  565. /// An <see cref="object"/> from which emits this <paramref name="eventHandler"/>.
  566. /// </param>
  567. /// <param name="e">
  568. /// A <c>TEventArgs</c> that represents the event data.
  569. /// </param>
  570. /// <typeparam name="TEventArgs">
  571. /// The type of the event data generated by the event.
  572. /// </typeparam>
  573. public static void Emit<TEventArgs>(
  574. this EventHandler<TEventArgs> eventHandler, object sender, TEventArgs e)
  575. where TEventArgs : EventArgs
  576. {
  577. if (eventHandler != null)
  578. eventHandler(sender, e);
  579. }
  580. /// <summary>
  581. /// Gets the collection of the HTTP cookies from the specified HTTP <paramref name="headers"/>.
  582. /// </summary>
  583. /// <returns>
  584. /// A <see cref="CookieCollection"/> that receives a collection of the HTTP cookies.
  585. /// </returns>
  586. /// <param name="headers">
  587. /// A <see cref="QueryParamCollection"/> that contains a collection of the HTTP headers.
  588. /// </param>
  589. /// <param name="response">
  590. /// <c>true</c> if <paramref name="headers"/> is a collection of the response headers;
  591. /// otherwise, <c>false</c>.
  592. /// </param>
  593. public static CookieCollection GetCookies(this QueryParamCollection headers, bool response)
  594. {
  595. var name = response ? "Set-Cookie" : "Cookie";
  596. return headers == null || !headers.Contains(name)
  597. ? new CookieCollection()
  598. : CookieHelper.Parse(headers[name], response);
  599. }
  600. /// <summary>
  601. /// Gets the description of the specified HTTP status <paramref name="code"/>.
  602. /// </summary>
  603. /// <returns>
  604. /// A <see cref="string"/> that represents the description of the HTTP status code.
  605. /// </returns>
  606. /// <param name="code">
  607. /// One of <see cref="HttpStatusCode"/> enum values, indicates the HTTP status codes.
  608. /// </param>
  609. public static string GetDescription(this HttpStatusCode code)
  610. {
  611. return ((int)code).GetStatusDescription();
  612. }
  613. /// <summary>
  614. /// Gets the name from the specified <see cref="string"/> that contains a pair of name and
  615. /// value separated by a separator string.
  616. /// </summary>
  617. /// <returns>
  618. /// A <see cref="string"/> that represents the name if any; otherwise, <c>null</c>.
  619. /// </returns>
  620. /// <param name="nameAndValue">
  621. /// A <see cref="string"/> that contains a pair of name and value separated by a separator
  622. /// string.
  623. /// </param>
  624. /// <param name="separator">
  625. /// A <see cref="string"/> that represents a separator string.
  626. /// </param>
  627. public static string GetName(this string nameAndValue, string separator)
  628. {
  629. return (nameAndValue != null && nameAndValue.Length > 0) &&
  630. (separator != null && separator.Length > 0)
  631. ? nameAndValue.GetNameInternal(separator)
  632. : null;
  633. }
  634. /// <summary>
  635. /// Gets the name and value from the specified <see cref="string"/> that contains a pair of
  636. /// name and value separated by a separator string.
  637. /// </summary>
  638. /// <returns>
  639. /// A <c>KeyValuePair&lt;string, string&gt;</c> that represents the name and value if any.
  640. /// </returns>
  641. /// <param name="nameAndValue">
  642. /// A <see cref="string"/> that contains a pair of name and value separated by a separator
  643. /// string.
  644. /// </param>
  645. /// <param name="separator">
  646. /// A <see cref="string"/> that represents a separator string.
  647. /// </param>
  648. public static KeyValuePair<string, string> GetNameAndValue(
  649. this string nameAndValue, string separator)
  650. {
  651. var name = nameAndValue.GetName(separator);
  652. var value = nameAndValue.GetValue(separator);
  653. return name != null
  654. ? new KeyValuePair<string, string>(name, value)
  655. : new KeyValuePair<string, string>(null, null);
  656. }
  657. /// <summary>
  658. /// Gets the description of the specified HTTP status <paramref name="code"/>.
  659. /// </summary>
  660. /// <returns>
  661. /// A <see cref="string"/> that represents the description of the HTTP status code.
  662. /// </returns>
  663. /// <param name="code">
  664. /// An <see cref="int"/> that represents the HTTP status code.
  665. /// </param>
  666. public static string GetStatusDescription(this int code)
  667. {
  668. switch (code)
  669. {
  670. case 100: return "Continue";
  671. case 101: return "Switching Protocols";
  672. case 102: return "Processing";
  673. case 200: return "OK";
  674. case 201: return "Created";
  675. case 202: return "Accepted";
  676. case 203: return "Non-Authoritative Information";
  677. case 204: return "No Content";
  678. case 205: return "Reset Content";
  679. case 206: return "Partial Content";
  680. case 207: return "Multi-Status";
  681. case 300: return "Multiple Choices";
  682. case 301: return "Moved Permanently";
  683. case 302: return "Found";
  684. case 303: return "See Other";
  685. case 304: return "Not Modified";
  686. case 305: return "Use Proxy";
  687. case 307: return "Temporary Redirect";
  688. case 400: return "Bad Request";
  689. case 401: return "Unauthorized";
  690. case 402: return "Payment Required";
  691. case 403: return "Forbidden";
  692. case 404: return "Not Found";
  693. case 405: return "Method Not Allowed";
  694. case 406: return "Not Acceptable";
  695. case 407: return "Proxy Authentication Required";
  696. case 408: return "Request Timeout";
  697. case 409: return "Conflict";
  698. case 410: return "Gone";
  699. case 411: return "Length Required";
  700. case 412: return "Precondition Failed";
  701. case 413: return "Request Entity Too Large";
  702. case 414: return "Request-Uri Too Long";
  703. case 415: return "Unsupported Media Type";
  704. case 416: return "Requested Range Not Satisfiable";
  705. case 417: return "Expectation Failed";
  706. case 422: return "Unprocessable Entity";
  707. case 423: return "Locked";
  708. case 424: return "Failed Dependency";
  709. case 500: return "Internal Server Error";
  710. case 501: return "Not Implemented";
  711. case 502: return "Bad Gateway";
  712. case 503: return "Service Unavailable";
  713. case 504: return "Gateway Timeout";
  714. case 505: return "Http Version Not Supported";
  715. case 507: return "Insufficient Storage";
  716. }
  717. return String.Empty;
  718. }
  719. /// <summary>
  720. /// Gets the value from the specified <see cref="string"/> that contains a pair of name and
  721. /// value separated by a separator string.
  722. /// </summary>
  723. /// <returns>
  724. /// A <see cref="string"/> that represents the value if any; otherwise, <c>null</c>.
  725. /// </returns>
  726. /// <param name="nameAndValue">
  727. /// A <see cref="string"/> that contains a pair of name and value separated by a separator
  728. /// string.
  729. /// </param>
  730. /// <param name="separator">
  731. /// A <see cref="string"/> that represents a separator string.
  732. /// </param>
  733. public static string GetValue(this string nameAndValue, string separator)
  734. {
  735. return (nameAndValue != null && nameAndValue.Length > 0) &&
  736. (separator != null && separator.Length > 0)
  737. ? nameAndValue.GetValueInternal(separator)
  738. : null;
  739. }
  740. /// <summary>
  741. /// Determines whether the specified <see cref="ByteOrder"/> is host
  742. /// (this computer architecture) byte order.
  743. /// </summary>
  744. /// <returns>
  745. /// <c>true</c> if <paramref name="order"/> is host byte order;
  746. /// otherwise, <c>false</c>.
  747. /// </returns>
  748. /// <param name="order">
  749. /// One of the <see cref="ByteOrder"/> enum values, to test.
  750. /// </param>
  751. public static bool IsHostOrder(this ByteOrder order)
  752. {
  753. // true : !(true ^ true) or !(false ^ false)
  754. // false: !(true ^ false) or !(false ^ true)
  755. return !(BitConverter.IsLittleEndian ^ (order == ByteOrder.Little));
  756. }
  757. /// <summary>
  758. /// Determines whether the specified <see cref="string"/> is a predefined scheme.
  759. /// </summary>
  760. /// <returns>
  761. /// <c>true</c> if <paramref name="value"/> is a predefined scheme; otherwise, <c>false</c>.
  762. /// </returns>
  763. /// <param name="value">
  764. /// A <see cref="string"/> to test.
  765. /// </param>
  766. public static bool IsPredefinedScheme(this string value)
  767. {
  768. if (value == null || value.Length < 2)
  769. return false;
  770. var c = value[0];
  771. if (c == 'h')
  772. return value == "http" || value == "https";
  773. if (c == 'w')
  774. return value == "ws" || value == "wss";
  775. if (c == 'f')
  776. return value == "file" || value == "ftp";
  777. if (c == 'n')
  778. {
  779. c = value[1];
  780. return c == 'e'
  781. ? value == "news" || value == "net.pipe" || value == "net.tcp"
  782. : value == "nntp";
  783. }
  784. return (c == 'g' && value == "gopher") || (c == 'm' && value == "mailto");
  785. }
  786. /// <summary>
  787. /// Determines whether the specified <see cref="string"/> is a URI string.
  788. /// </summary>
  789. /// <returns>
  790. /// <c>true</c> if <paramref name="value"/> may be a URI string; otherwise, <c>false</c>.
  791. /// </returns>
  792. /// <param name="value">
  793. /// A <see cref="string"/> to test.
  794. /// </param>
  795. public static bool MaybeUri(this string value)
  796. {
  797. if (value == null || value.Length == 0)
  798. return false;
  799. var i = value.IndexOf(':');
  800. if (i == -1)
  801. return false;
  802. if (i >= 10)
  803. return false;
  804. return value.Substring(0, i).IsPredefinedScheme();
  805. }
  806. /// <summary>
  807. /// Retrieves a sub-array from the specified <paramref name="array"/>.
  808. /// A sub-array starts at the specified element position.
  809. /// </summary>
  810. /// <returns>
  811. /// An array of T that receives a sub-array, or an empty array of T if any problems
  812. /// with the parameters.
  813. /// </returns>
  814. /// <param name="array">
  815. /// An array of T that contains the data to retrieve a sub-array.
  816. /// </param>
  817. /// <param name="startIndex">
  818. /// An <see cref="int"/> that contains the zero-based starting position of a sub-array
  819. /// in <paramref name="array"/>.
  820. /// </param>
  821. /// <param name="length">
  822. /// An <see cref="int"/> that contains the number of elements to retrieve a sub-array.
  823. /// </param>
  824. /// <typeparam name="T">
  825. /// The type of elements in the <paramref name="array"/>.
  826. /// </typeparam>
  827. public static T[] SubArray<T>(this T[] array, int startIndex, int length)
  828. {
  829. if (array == null || array.Length == 0)
  830. return new T[0];
  831. if (startIndex < 0 || length <= 0)
  832. return new T[0];
  833. if (startIndex + length > array.Length)
  834. return new T[0];
  835. if (startIndex == 0 && array.Length == length)
  836. return array;
  837. T[] subArray = new T[length];
  838. Array.Copy(array, startIndex, subArray, 0, length);
  839. return subArray;
  840. }
  841. /// <summary>
  842. /// Converts the order of the specified array of <see cref="byte"/> to the host byte order.
  843. /// </summary>
  844. /// <returns>
  845. /// An array of <see cref="byte"/> converted from <paramref name="src"/>.
  846. /// </returns>
  847. /// <param name="src">
  848. /// An array of <see cref="byte"/> to convert.
  849. /// </param>
  850. /// <param name="srcOrder">
  851. /// One of the <see cref="ByteOrder"/> enum values, indicates the byte order of
  852. /// <paramref name="src"/>.
  853. /// </param>
  854. /// <exception cref="ArgumentNullException">
  855. /// <paramref name="src"/> is <see langword="null"/>.
  856. /// </exception>
  857. public static byte[] ToHostOrder(this byte[] src, ByteOrder srcOrder)
  858. {
  859. if (src == null)
  860. throw new ArgumentNullException("src");
  861. return src.Length > 1 && !srcOrder.IsHostOrder()
  862. ? src.Reverse()
  863. : src;
  864. }
  865. /// <summary>
  866. /// Converts the specified <paramref name="array"/> to a <see cref="string"/> that
  867. /// concatenates the each element of <paramref name="array"/> across the specified
  868. /// <paramref name="separator"/>.
  869. /// </summary>
  870. /// <returns>
  871. /// A <see cref="string"/> converted from <paramref name="array"/>,
  872. /// or <see cref="String.Empty"/> if <paramref name="array"/> is empty.
  873. /// </returns>
  874. /// <param name="array">
  875. /// An array of T to convert.
  876. /// </param>
  877. /// <param name="separator">
  878. /// A <see cref="string"/> that represents the separator string.
  879. /// </param>
  880. /// <typeparam name="T">
  881. /// The type of elements in <paramref name="array"/>.
  882. /// </typeparam>
  883. /// <exception cref="ArgumentNullException">
  884. /// <paramref name="array"/> is <see langword="null"/>.
  885. /// </exception>
  886. public static string ToString<T>(this T[] array, string separator)
  887. {
  888. if (array == null)
  889. throw new ArgumentNullException("array");
  890. var len = array.Length;
  891. if (len == 0)
  892. return String.Empty;
  893. if (separator == null)
  894. separator = String.Empty;
  895. var buff = new StringBuilder(64);
  896. (len - 1).Times(i => buff.AppendFormat("{0}{1}", array[i].ToString(), separator));
  897. buff.Append(array[len - 1].ToString());
  898. return buff.ToString();
  899. }
  900. /// <summary>
  901. /// Executes the specified <c>Action&lt;int&gt;</c> delegate <paramref name="n"/> times.
  902. /// </summary>
  903. /// <param name="n">
  904. /// An <see cref="int"/> is the number of times to execute.
  905. /// </param>
  906. /// <param name="action">
  907. /// An <c>Action&lt;int&gt;</c> delegate that references the method(s) to execute.
  908. /// An <see cref="int"/> parameter to pass to the method(s) is the zero-based count of
  909. /// iteration.
  910. /// </param>
  911. public static void Times(this int n, Action<int> action)
  912. {
  913. if (n > 0 && action != null)
  914. for (int i = 0; i < n; i++)
  915. action(i);
  916. }
  917. /// <summary>
  918. /// Converts the specified <see cref="string"/> to a <see cref="Uri"/>.
  919. /// </summary>
  920. /// <returns>
  921. /// A <see cref="Uri"/> converted from <paramref name="uriString"/>, or <see langword="null"/>
  922. /// if <paramref name="uriString"/> isn't successfully converted.
  923. /// </returns>
  924. /// <param name="uriString">
  925. /// A <see cref="string"/> to convert.
  926. /// </param>
  927. public static Uri ToUri(this string uriString)
  928. {
  929. Uri res;
  930. return Uri.TryCreate(
  931. uriString, uriString.MaybeUri() ? UriKind.Absolute : UriKind.Relative, out res)
  932. ? res
  933. : null;
  934. }
  935. /// <summary>
  936. /// URL-decodes the specified <see cref="string"/>.
  937. /// </summary>
  938. /// <returns>
  939. /// A <see cref="string"/> that receives the decoded string, or the <paramref name="value"/>
  940. /// if it's <see langword="null"/> or empty.
  941. /// </returns>
  942. /// <param name="value">
  943. /// A <see cref="string"/> to decode.
  944. /// </param>
  945. public static string UrlDecode(this string value)
  946. {
  947. return value == null || value.Length == 0
  948. ? value
  949. : WebUtility.UrlDecode(value);
  950. }
  951. #endregion
  952. }
  953. }