WebUtil.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  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.Collections.Specialized;
  31. using System.Globalization;
  32. using System.IO;
  33. using System.IO.Compression;
  34. using System.Net;
  35. using System.Net.Security;
  36. using System.Reflection;
  37. using System.Text;
  38. using System.Web;
  39. using System.Xml;
  40. using System.Xml.Serialization;
  41. using log4net;
  42. using OpenMetaverse.StructuredData;
  43. namespace OpenSim.Framework
  44. {
  45. /// <summary>
  46. /// Miscellaneous static methods and extension methods related to the web
  47. /// </summary>
  48. public static class WebUtil
  49. {
  50. private static readonly ILog m_log =
  51. LogManager.GetLogger(
  52. MethodBase.GetCurrentMethod().DeclaringType);
  53. /// <summary>
  54. /// Control the printing of certain debug messages.
  55. /// </summary>
  56. /// <remarks>
  57. /// If DebugLevel >= 3 then short notices about outgoing HTTP requests are logged.
  58. /// </remarks>
  59. public static int DebugLevel { get; set; }
  60. /// <summary>
  61. /// Request number for diagnostic purposes.
  62. /// </summary>
  63. public static int RequestNumber { get; internal set; }
  64. /// <summary>
  65. /// Control where OSD requests should be serialized per endpoint.
  66. /// </summary>
  67. public static bool SerializeOSDRequestsPerEndpoint { get; set; }
  68. /// <summary>
  69. /// this is the header field used to communicate the local request id
  70. /// used for performance and debugging
  71. /// </summary>
  72. public const string OSHeaderRequestID = "opensim-request-id";
  73. /// <summary>
  74. /// Number of milliseconds a call can take before it is considered
  75. /// a "long" call for warning & debugging purposes
  76. /// </summary>
  77. public const int LongCallTime = 3000;
  78. /// <summary>
  79. /// The maximum length of any data logged because of a long request time.
  80. /// </summary>
  81. /// <remarks>
  82. /// This is to truncate any really large post data, such as an asset. In theory, the first section should
  83. /// give us useful information about the call (which agent it relates to if applicable, etc.).
  84. /// This is also used to truncate messages when using DebugLevel 5.
  85. /// </remarks>
  86. public const int MaxRequestDiagLength = 200;
  87. /// <summary>
  88. /// Dictionary of end points
  89. /// </summary>
  90. private static Dictionary<string,object> m_endpointSerializer = new Dictionary<string,object>();
  91. private static object EndPointLock(string url)
  92. {
  93. System.Uri uri = new System.Uri(url);
  94. string endpoint = string.Format("{0}:{1}",uri.Host,uri.Port);
  95. lock (m_endpointSerializer)
  96. {
  97. object eplock = null;
  98. if (! m_endpointSerializer.TryGetValue(endpoint,out eplock))
  99. {
  100. eplock = new object();
  101. m_endpointSerializer.Add(endpoint,eplock);
  102. // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint);
  103. }
  104. return eplock;
  105. }
  106. }
  107. #region JSONRequest
  108. /// <summary>
  109. /// PUT JSON-encoded data to a web service that returns LLSD or
  110. /// JSON data
  111. /// </summary>
  112. public static OSDMap PutToServiceCompressed(string url, OSDMap data, int timeout)
  113. {
  114. return ServiceOSDRequest(url,data, "PUT", timeout, true);
  115. }
  116. public static OSDMap PutToService(string url, OSDMap data, int timeout)
  117. {
  118. return ServiceOSDRequest(url,data, "PUT", timeout, false);
  119. }
  120. public static OSDMap PostToService(string url, OSDMap data, int timeout)
  121. {
  122. return ServiceOSDRequest(url, data, "POST", timeout, false);
  123. }
  124. public static OSDMap PostToServiceCompressed(string url, OSDMap data, int timeout)
  125. {
  126. return ServiceOSDRequest(url, data, "POST", timeout, true);
  127. }
  128. public static OSDMap GetFromService(string url, int timeout)
  129. {
  130. return ServiceOSDRequest(url, null, "GET", timeout, false);
  131. }
  132. public static OSDMap ServiceOSDRequest(string url, OSDMap data, string method, int timeout, bool compressed)
  133. {
  134. if (SerializeOSDRequestsPerEndpoint)
  135. {
  136. lock (EndPointLock(url))
  137. {
  138. return ServiceOSDRequestWorker(url, data, method, timeout, compressed);
  139. }
  140. }
  141. else
  142. {
  143. return ServiceOSDRequestWorker(url, data, method, timeout, compressed);
  144. }
  145. }
  146. public static void LogOutgoingDetail(Stream outputStream)
  147. {
  148. LogOutgoingDetail("", outputStream);
  149. }
  150. public static void LogOutgoingDetail(string context, Stream outputStream)
  151. {
  152. using (StreamReader reader = new StreamReader(Util.Copy(outputStream), Encoding.UTF8))
  153. {
  154. string output;
  155. if (DebugLevel == 5)
  156. {
  157. char[] chars = new char[WebUtil.MaxRequestDiagLength + 1]; // +1 so we know to add "..." only if needed
  158. int len = reader.Read(chars, 0, WebUtil.MaxRequestDiagLength + 1);
  159. output = new string(chars, 0, len);
  160. }
  161. else
  162. {
  163. output = reader.ReadToEnd();
  164. }
  165. LogOutgoingDetail(context, output);
  166. }
  167. }
  168. public static void LogOutgoingDetail(string output)
  169. {
  170. LogOutgoingDetail("", output);
  171. }
  172. public static void LogOutgoingDetail(string context, string output)
  173. {
  174. if (DebugLevel == 5)
  175. {
  176. if (output.Length > MaxRequestDiagLength)
  177. output = output.Substring(0, MaxRequestDiagLength) + "...";
  178. }
  179. m_log.DebugFormat("[LOGHTTP]: {0}{1}", context, Util.BinaryToASCII(output));
  180. }
  181. public static void LogResponseDetail(Stream inputStream)
  182. {
  183. LogOutgoingDetail("RESPONSE: ", inputStream);
  184. }
  185. public static void LogResponseDetail(string input)
  186. {
  187. LogOutgoingDetail("RESPONSE: ", input);
  188. }
  189. private static OSDMap ServiceOSDRequestWorker(string url, OSDMap data, string method, int timeout, bool compressed)
  190. {
  191. int reqnum = RequestNumber++;
  192. if (DebugLevel >= 3)
  193. m_log.DebugFormat(
  194. "[LOGHTTP]: HTTP OUT {0} ServiceOSD {1} {2} (timeout {3}, compressed {4})",
  195. reqnum, method, url, timeout, compressed);
  196. string errorMessage = "unknown error";
  197. int tickstart = Util.EnvironmentTickCount();
  198. int tickdata = 0;
  199. string strBuffer = null;
  200. try
  201. {
  202. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  203. request.Method = method;
  204. request.Timeout = timeout;
  205. request.KeepAlive = false;
  206. request.MaximumAutomaticRedirections = 10;
  207. request.ReadWriteTimeout = timeout / 4;
  208. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  209. // If there is some input, write it into the request
  210. if (data != null)
  211. {
  212. strBuffer = OSDParser.SerializeJsonString(data);
  213. if (DebugLevel >= 5)
  214. LogOutgoingDetail(strBuffer);
  215. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strBuffer);
  216. request.ContentType = "application/json";
  217. if (compressed)
  218. {
  219. request.Headers["X-Content-Encoding"] = "gzip"; // can't set "Content-Encoding" because old OpenSims fail if they get an unrecognized Content-Encoding
  220. using (MemoryStream ms = new MemoryStream())
  221. {
  222. using (GZipStream comp = new GZipStream(ms, CompressionMode.Compress))
  223. {
  224. comp.Write(buffer, 0, buffer.Length);
  225. // We need to close the gzip stream before we write it anywhere
  226. // because apparently something important related to gzip compression
  227. // gets written on the strteam upon Dispose()
  228. }
  229. byte[] buf = ms.ToArray();
  230. request.ContentLength = buf.Length; //Count bytes to send
  231. using (Stream requestStream = request.GetRequestStream())
  232. requestStream.Write(buf, 0, (int)buf.Length);
  233. }
  234. }
  235. else
  236. {
  237. request.ContentLength = buffer.Length; //Count bytes to send
  238. using (Stream requestStream = request.GetRequestStream())
  239. requestStream.Write(buffer, 0, buffer.Length); //Send it
  240. }
  241. }
  242. // capture how much time was spent writing, this may seem silly
  243. // but with the number concurrent requests, this often blocks
  244. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  245. using (WebResponse response = request.GetResponse())
  246. {
  247. using (Stream responseStream = response.GetResponseStream())
  248. {
  249. using (StreamReader reader = new StreamReader(responseStream))
  250. {
  251. string responseStr = reader.ReadToEnd();
  252. // m_log.DebugFormat("[LOGHTTP]: <{0}> response is <{1}>",reqnum,responseStr);
  253. if (WebUtil.DebugLevel >= 5)
  254. WebUtil.LogResponseDetail(responseStr);
  255. return CanonicalizeResults(responseStr);
  256. }
  257. }
  258. }
  259. }
  260. catch (WebException we)
  261. {
  262. errorMessage = we.Message;
  263. if (we.Status == WebExceptionStatus.ProtocolError)
  264. {
  265. using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
  266. errorMessage = String.Format("[{0}] {1}", webResponse.StatusCode, webResponse.StatusDescription);
  267. }
  268. }
  269. catch (Exception ex)
  270. {
  271. errorMessage = ex.Message;
  272. }
  273. finally
  274. {
  275. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  276. if (tickdiff > LongCallTime)
  277. m_log.InfoFormat(
  278. "[LOGHTTP]: Slow ServiceOSD request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  279. reqnum,
  280. method,
  281. url,
  282. tickdiff,
  283. tickdata,
  284. strBuffer != null
  285. ? (strBuffer.Length > MaxRequestDiagLength ? strBuffer.Remove(MaxRequestDiagLength) : strBuffer)
  286. : "");
  287. else if (DebugLevel >= 4)
  288. m_log.DebugFormat(
  289. "[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  290. reqnum, tickdiff, tickdata);
  291. }
  292. m_log.DebugFormat(
  293. "[LOGHTTP]: ServiceOSD request {0} {1} {2} FAILED: {3}", reqnum, url, method, errorMessage);
  294. return ErrorResponseMap(errorMessage);
  295. }
  296. /// <summary>
  297. /// Since there are no consistencies in the way web requests are
  298. /// formed, we need to do a little guessing about the result format.
  299. /// Keys:
  300. /// Success|success == the success fail of the request
  301. /// _RawResult == the raw string that came back
  302. /// _Result == the OSD unpacked string
  303. /// </summary>
  304. private static OSDMap CanonicalizeResults(string response)
  305. {
  306. OSDMap result = new OSDMap();
  307. // Default values
  308. result["Success"] = OSD.FromBoolean(true);
  309. result["success"] = OSD.FromBoolean(true);
  310. result["_RawResult"] = OSD.FromString(response);
  311. result["_Result"] = new OSDMap();
  312. if (response.Equals("true",System.StringComparison.OrdinalIgnoreCase))
  313. return result;
  314. if (response.Equals("false",System.StringComparison.OrdinalIgnoreCase))
  315. {
  316. result["Success"] = OSD.FromBoolean(false);
  317. result["success"] = OSD.FromBoolean(false);
  318. return result;
  319. }
  320. try
  321. {
  322. OSD responseOSD = OSDParser.Deserialize(response);
  323. if (responseOSD.Type == OSDType.Map)
  324. {
  325. result["_Result"] = (OSDMap)responseOSD;
  326. return result;
  327. }
  328. }
  329. catch
  330. {
  331. // don't need to treat this as an error... we're just guessing anyway
  332. // m_log.DebugFormat("[WEB UTIL] couldn't decode <{0}>: {1}",response,e.Message);
  333. }
  334. return result;
  335. }
  336. #endregion JSONRequest
  337. #region FormRequest
  338. /// <summary>
  339. /// POST URL-encoded form data to a web service that returns LLSD or
  340. /// JSON data
  341. /// </summary>
  342. public static OSDMap PostToService(string url, NameValueCollection data)
  343. {
  344. return ServiceFormRequest(url,data,10000);
  345. }
  346. public static OSDMap ServiceFormRequest(string url, NameValueCollection data, int timeout)
  347. {
  348. lock (EndPointLock(url))
  349. {
  350. return ServiceFormRequestWorker(url,data,timeout);
  351. }
  352. }
  353. private static OSDMap ServiceFormRequestWorker(string url, NameValueCollection data, int timeout)
  354. {
  355. int reqnum = RequestNumber++;
  356. string method = (data != null && data["RequestMethod"] != null) ? data["RequestMethod"] : "unknown";
  357. if (DebugLevel >= 3)
  358. m_log.DebugFormat(
  359. "[LOGHTTP]: HTTP OUT {0} ServiceForm {1} {2} (timeout {3})",
  360. reqnum, method, url, timeout);
  361. string errorMessage = "unknown error";
  362. int tickstart = Util.EnvironmentTickCount();
  363. int tickdata = 0;
  364. string queryString = null;
  365. try
  366. {
  367. HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
  368. request.Method = "POST";
  369. request.Timeout = timeout;
  370. request.KeepAlive = false;
  371. request.MaximumAutomaticRedirections = 10;
  372. request.ReadWriteTimeout = timeout / 4;
  373. request.Headers[OSHeaderRequestID] = reqnum.ToString();
  374. if (data != null)
  375. {
  376. queryString = BuildQueryString(data);
  377. if (DebugLevel >= 5)
  378. LogOutgoingDetail(queryString);
  379. byte[] buffer = System.Text.Encoding.UTF8.GetBytes(queryString);
  380. request.ContentLength = buffer.Length;
  381. request.ContentType = "application/x-www-form-urlencoded";
  382. using (Stream requestStream = request.GetRequestStream())
  383. requestStream.Write(buffer, 0, buffer.Length);
  384. }
  385. // capture how much time was spent writing, this may seem silly
  386. // but with the number concurrent requests, this often blocks
  387. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  388. using (WebResponse response = request.GetResponse())
  389. {
  390. using (Stream responseStream = response.GetResponseStream())
  391. {
  392. using (StreamReader reader = new StreamReader(responseStream))
  393. {
  394. string responseStr = reader.ReadToEnd();
  395. if (WebUtil.DebugLevel >= 5)
  396. WebUtil.LogResponseDetail(responseStr);
  397. OSD responseOSD = OSDParser.Deserialize(responseStr);
  398. if (responseOSD.Type == OSDType.Map)
  399. return (OSDMap)responseOSD;
  400. }
  401. }
  402. }
  403. }
  404. catch (WebException we)
  405. {
  406. errorMessage = we.Message;
  407. if (we.Status == WebExceptionStatus.ProtocolError)
  408. {
  409. using (HttpWebResponse webResponse = (HttpWebResponse)we.Response)
  410. errorMessage = String.Format("[{0}] {1}",webResponse.StatusCode,webResponse.StatusDescription);
  411. }
  412. }
  413. catch (Exception ex)
  414. {
  415. errorMessage = ex.Message;
  416. }
  417. finally
  418. {
  419. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  420. if (tickdiff > LongCallTime)
  421. m_log.InfoFormat(
  422. "[LOGHTTP]: Slow ServiceForm request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  423. reqnum,
  424. method,
  425. url,
  426. tickdiff,
  427. tickdata,
  428. queryString != null
  429. ? (queryString.Length > MaxRequestDiagLength) ? queryString.Remove(MaxRequestDiagLength) : queryString
  430. : "");
  431. else if (DebugLevel >= 4)
  432. m_log.DebugFormat(
  433. "[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  434. reqnum, tickdiff, tickdata);
  435. }
  436. m_log.WarnFormat("[LOGHTTP]: ServiceForm request {0} {1} {2} failed: {2}", reqnum, method, url, errorMessage);
  437. return ErrorResponseMap(errorMessage);
  438. }
  439. /// <summary>
  440. /// Create a response map for an error, trying to keep
  441. /// the result formats consistent
  442. /// </summary>
  443. private static OSDMap ErrorResponseMap(string msg)
  444. {
  445. OSDMap result = new OSDMap();
  446. result["Success"] = "False";
  447. result["Message"] = OSD.FromString("Service request failed: " + msg);
  448. return result;
  449. }
  450. #endregion FormRequest
  451. #region Uri
  452. /// <summary>
  453. /// Combines a Uri that can contain both a base Uri and relative path
  454. /// with a second relative path fragment
  455. /// </summary>
  456. /// <param name="uri">Starting (base) Uri</param>
  457. /// <param name="fragment">Relative path fragment to append to the end
  458. /// of the Uri</param>
  459. /// <returns>The combined Uri</returns>
  460. /// <remarks>This is similar to the Uri constructor that takes a base
  461. /// Uri and the relative path, except this method can append a relative
  462. /// path fragment on to an existing relative path</remarks>
  463. public static Uri Combine(this Uri uri, string fragment)
  464. {
  465. string fragment1 = uri.Fragment;
  466. string fragment2 = fragment;
  467. if (!fragment1.EndsWith("/"))
  468. fragment1 = fragment1 + '/';
  469. if (fragment2.StartsWith("/"))
  470. fragment2 = fragment2.Substring(1);
  471. return new Uri(uri, fragment1 + fragment2);
  472. }
  473. /// <summary>
  474. /// Combines a Uri that can contain both a base Uri and relative path
  475. /// with a second relative path fragment. If the fragment is absolute,
  476. /// it will be returned without modification
  477. /// </summary>
  478. /// <param name="uri">Starting (base) Uri</param>
  479. /// <param name="fragment">Relative path fragment to append to the end
  480. /// of the Uri, or an absolute Uri to return unmodified</param>
  481. /// <returns>The combined Uri</returns>
  482. public static Uri Combine(this Uri uri, Uri fragment)
  483. {
  484. if (fragment.IsAbsoluteUri)
  485. return fragment;
  486. string fragment1 = uri.Fragment;
  487. string fragment2 = fragment.ToString();
  488. if (!fragment1.EndsWith("/"))
  489. fragment1 = fragment1 + '/';
  490. if (fragment2.StartsWith("/"))
  491. fragment2 = fragment2.Substring(1);
  492. return new Uri(uri, fragment1 + fragment2);
  493. }
  494. /// <summary>
  495. /// Appends a query string to a Uri that may or may not have existing
  496. /// query parameters
  497. /// </summary>
  498. /// <param name="uri">Uri to append the query to</param>
  499. /// <param name="query">Query string to append. Can either start with ?
  500. /// or just containg key/value pairs</param>
  501. /// <returns>String representation of the Uri with the query string
  502. /// appended</returns>
  503. public static string AppendQuery(this Uri uri, string query)
  504. {
  505. if (String.IsNullOrEmpty(query))
  506. return uri.ToString();
  507. if (query[0] == '?' || query[0] == '&')
  508. query = query.Substring(1);
  509. string uriStr = uri.ToString();
  510. if (uriStr.Contains("?"))
  511. return uriStr + '&' + query;
  512. else
  513. return uriStr + '?' + query;
  514. }
  515. #endregion Uri
  516. #region NameValueCollection
  517. /// <summary>
  518. /// Convert a NameValueCollection into a query string. This is the
  519. /// inverse of HttpUtility.ParseQueryString()
  520. /// </summary>
  521. /// <param name="parameters">Collection of key/value pairs to convert</param>
  522. /// <returns>A query string with URL-escaped values</returns>
  523. public static string BuildQueryString(NameValueCollection parameters)
  524. {
  525. List<string> items = new List<string>(parameters.Count);
  526. foreach (string key in parameters.Keys)
  527. {
  528. string[] values = parameters.GetValues(key);
  529. if (values != null)
  530. {
  531. foreach (string value in values)
  532. items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty)));
  533. }
  534. }
  535. return String.Join("&", items.ToArray());
  536. }
  537. /// <summary>
  538. ///
  539. /// </summary>
  540. /// <param name="collection"></param>
  541. /// <param name="key"></param>
  542. /// <returns></returns>
  543. public static string GetOne(this NameValueCollection collection, string key)
  544. {
  545. string[] values = collection.GetValues(key);
  546. if (values != null && values.Length > 0)
  547. return values[0];
  548. return null;
  549. }
  550. #endregion NameValueCollection
  551. #region Stream
  552. /// <summary>
  553. /// Copies the contents of one stream to another, starting at the
  554. /// current position of each stream
  555. /// </summary>
  556. /// <param name="copyFrom">The stream to copy from, at the position
  557. /// where copying should begin</param>
  558. /// <param name="copyTo">The stream to copy to, at the position where
  559. /// bytes should be written</param>
  560. /// <param name="maximumBytesToCopy">The maximum bytes to copy</param>
  561. /// <returns>The total number of bytes copied</returns>
  562. /// <remarks>
  563. /// Copying begins at the streams' current positions. The positions are
  564. /// NOT reset after copying is complete.
  565. /// NOTE!! .NET 4.0 adds the method 'Stream.CopyTo(stream, bufferSize)'.
  566. /// This function could be replaced with that method once we move
  567. /// totally to .NET 4.0. For versions before, this routine exists.
  568. /// This routine used to be named 'CopyTo' but the int parameter has
  569. /// a different meaning so this method was renamed to avoid any confusion.
  570. /// </remarks>
  571. public static int CopyStream(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
  572. {
  573. byte[] buffer = new byte[4096];
  574. int readBytes;
  575. int totalCopiedBytes = 0;
  576. while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
  577. {
  578. int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
  579. copyTo.Write(buffer, 0, writeBytes);
  580. totalCopiedBytes += writeBytes;
  581. maximumBytesToCopy -= writeBytes;
  582. }
  583. return totalCopiedBytes;
  584. }
  585. #endregion Stream
  586. public class QBasedComparer : IComparer
  587. {
  588. public int Compare(Object x, Object y)
  589. {
  590. float qx = GetQ(x);
  591. float qy = GetQ(y);
  592. return qy.CompareTo(qx); // descending order
  593. }
  594. private float GetQ(Object o)
  595. {
  596. // Example: image/png;q=0.9
  597. float qvalue = 1F;
  598. if (o is String)
  599. {
  600. string mime = (string)o;
  601. string[] parts = mime.Split(';');
  602. if (parts.Length > 1)
  603. {
  604. string[] kvp = parts[1].Split('=');
  605. if (kvp.Length == 2 && kvp[0] == "q")
  606. float.TryParse(kvp[1], NumberStyles.Number, CultureInfo.InvariantCulture, out qvalue);
  607. }
  608. }
  609. return qvalue;
  610. }
  611. }
  612. /// <summary>
  613. /// Takes the value of an Accept header and returns the preferred types
  614. /// ordered by q value (if it exists).
  615. /// Example input: image/jpg;q=0.7, image/png;q=0.8, image/jp2
  616. /// Exmaple output: ["jp2", "png", "jpg"]
  617. /// NOTE: This doesn't handle the semantics of *'s...
  618. /// </summary>
  619. /// <param name="accept"></param>
  620. /// <returns></returns>
  621. public static string[] GetPreferredImageTypes(string accept)
  622. {
  623. if (string.IsNullOrEmpty(accept))
  624. return new string[0];
  625. string[] types = accept.Split(new char[] { ',' });
  626. if (types.Length > 0)
  627. {
  628. List<string> list = new List<string>(types);
  629. list.RemoveAll(delegate(string s) { return !s.ToLower().StartsWith("image"); });
  630. ArrayList tlist = new ArrayList(list);
  631. tlist.Sort(new QBasedComparer());
  632. string[] result = new string[tlist.Count];
  633. for (int i = 0; i < tlist.Count; i++)
  634. {
  635. string mime = (string)tlist[i];
  636. string[] parts = mime.Split(new char[] { ';' });
  637. string[] pair = parts[0].Split(new char[] { '/' });
  638. if (pair.Length == 2)
  639. result[i] = pair[1].ToLower();
  640. else // oops, we don't know what this is...
  641. result[i] = pair[0];
  642. }
  643. return result;
  644. }
  645. return new string[0];
  646. }
  647. }
  648. public static class AsynchronousRestObjectRequester
  649. {
  650. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  651. /// <summary>
  652. /// Perform an asynchronous REST request.
  653. /// </summary>
  654. /// <param name="verb">GET or POST</param>
  655. /// <param name="requestUrl"></param>
  656. /// <param name="obj"></param>
  657. /// <param name="action"></param>
  658. /// <returns></returns>
  659. ///
  660. /// <exception cref="System.Net.WebException">Thrown if we encounter a
  661. /// network issue while posting the request. You'll want to make
  662. /// sure you deal with this as they're not uncommon</exception>
  663. //
  664. public static void MakeRequest<TRequest, TResponse>(string verb,
  665. string requestUrl, TRequest obj, Action<TResponse> action)
  666. {
  667. MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, action, 0);
  668. }
  669. public static void MakeRequest<TRequest, TResponse>(string verb,
  670. string requestUrl, TRequest obj, Action<TResponse> action,
  671. int maxConnections)
  672. {
  673. int reqnum = WebUtil.RequestNumber++;
  674. if (WebUtil.DebugLevel >= 3)
  675. m_log.DebugFormat(
  676. "[LOGHTTP]: HTTP OUT {0} AsynchronousRequestObject {1} {2}",
  677. reqnum, verb, requestUrl);
  678. int tickstart = Util.EnvironmentTickCount();
  679. int tickdata = 0;
  680. Type type = typeof(TRequest);
  681. WebRequest request = WebRequest.Create(requestUrl);
  682. HttpWebRequest ht = (HttpWebRequest)request;
  683. if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
  684. ht.ServicePoint.ConnectionLimit = maxConnections;
  685. TResponse deserial = default(TResponse);
  686. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  687. request.Method = verb;
  688. MemoryStream buffer = null;
  689. try
  690. {
  691. if (verb == "POST")
  692. {
  693. request.ContentType = "text/xml";
  694. buffer = new MemoryStream();
  695. XmlWriterSettings settings = new XmlWriterSettings();
  696. settings.Encoding = Encoding.UTF8;
  697. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  698. {
  699. XmlSerializer serializer = new XmlSerializer(type);
  700. serializer.Serialize(writer, obj);
  701. writer.Flush();
  702. }
  703. int length = (int)buffer.Length;
  704. request.ContentLength = length;
  705. byte[] data = buffer.ToArray();
  706. if (WebUtil.DebugLevel >= 5)
  707. WebUtil.LogOutgoingDetail(System.Text.Encoding.UTF8.GetString(data));
  708. request.BeginGetRequestStream(delegate(IAsyncResult res)
  709. {
  710. using (Stream requestStream = request.EndGetRequestStream(res))
  711. requestStream.Write(data, 0, length);
  712. // capture how much time was spent writing
  713. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  714. request.BeginGetResponse(delegate(IAsyncResult ar)
  715. {
  716. using (WebResponse response = request.EndGetResponse(ar))
  717. {
  718. try
  719. {
  720. using (Stream respStream = response.GetResponseStream())
  721. {
  722. if (WebUtil.DebugLevel >= 5)
  723. WebUtil.LogResponseDetail(respStream);
  724. deserial = (TResponse)deserializer.Deserialize(respStream);
  725. }
  726. }
  727. catch (System.InvalidOperationException)
  728. {
  729. }
  730. }
  731. action(deserial);
  732. }, null);
  733. }, null);
  734. }
  735. else
  736. {
  737. request.BeginGetResponse(delegate(IAsyncResult res2)
  738. {
  739. try
  740. {
  741. // If the server returns a 404, this appears to trigger a System.Net.WebException even though that isn't
  742. // documented in MSDN
  743. using (WebResponse response = request.EndGetResponse(res2))
  744. {
  745. try
  746. {
  747. using (Stream respStream = response.GetResponseStream())
  748. {
  749. if (WebUtil.DebugLevel >= 5)
  750. WebUtil.LogResponseDetail(respStream);
  751. deserial = (TResponse)deserializer.Deserialize(respStream);
  752. }
  753. }
  754. catch (System.InvalidOperationException)
  755. {
  756. }
  757. }
  758. }
  759. catch (WebException e)
  760. {
  761. if (e.Status == WebExceptionStatus.ProtocolError)
  762. {
  763. if (e.Response is HttpWebResponse)
  764. {
  765. using (HttpWebResponse httpResponse = (HttpWebResponse)e.Response)
  766. {
  767. if (httpResponse.StatusCode != HttpStatusCode.NotFound)
  768. {
  769. // We don't appear to be handling any other status codes, so log these feailures to that
  770. // people don't spend unnecessary hours hunting phantom bugs.
  771. m_log.DebugFormat(
  772. "[ASYNC REQUEST]: Request {0} {1} failed with unexpected status code {2}",
  773. verb, requestUrl, httpResponse.StatusCode);
  774. }
  775. }
  776. }
  777. }
  778. else
  779. {
  780. m_log.ErrorFormat(
  781. "[ASYNC REQUEST]: Request {0} {1} failed with status {2} and message {3}",
  782. verb, requestUrl, e.Status, e.Message);
  783. }
  784. }
  785. catch (Exception e)
  786. {
  787. m_log.ErrorFormat(
  788. "[ASYNC REQUEST]: Request {0} {1} failed with exception {2}{3}",
  789. verb, requestUrl, e.Message, e.StackTrace);
  790. }
  791. // m_log.DebugFormat("[ASYNC REQUEST]: Received {0}", deserial.ToString());
  792. try
  793. {
  794. action(deserial);
  795. }
  796. catch (Exception e)
  797. {
  798. m_log.ErrorFormat(
  799. "[ASYNC REQUEST]: Request {0} {1} callback failed with exception {2}{3}",
  800. verb, requestUrl, e.Message, e.StackTrace);
  801. }
  802. }, null);
  803. }
  804. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  805. if (tickdiff > WebUtil.LongCallTime)
  806. {
  807. string originalRequest = null;
  808. if (buffer != null)
  809. {
  810. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  811. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  812. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  813. }
  814. m_log.InfoFormat(
  815. "[LOGHTTP]: [ASYNC REQUEST]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  816. reqnum,
  817. verb,
  818. requestUrl,
  819. tickdiff,
  820. tickdata,
  821. originalRequest);
  822. }
  823. else if (WebUtil.DebugLevel >= 4)
  824. {
  825. m_log.DebugFormat(
  826. "[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  827. reqnum, tickdiff, tickdata);
  828. }
  829. }
  830. finally
  831. {
  832. if (buffer != null)
  833. buffer.Dispose();
  834. }
  835. }
  836. }
  837. public static class SynchronousRestFormsRequester
  838. {
  839. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  840. /// <summary>
  841. /// Perform a synchronous REST request.
  842. /// </summary>
  843. /// <param name="verb"></param>
  844. /// <param name="requestUrl"></param>
  845. /// <param name="obj"> </param>
  846. /// <param name="timeoutsecs"> </param>
  847. /// <returns></returns>
  848. ///
  849. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  850. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  851. public static string MakeRequest(string verb, string requestUrl, string obj, int timeoutsecs)
  852. {
  853. int reqnum = WebUtil.RequestNumber++;
  854. if (WebUtil.DebugLevel >= 3)
  855. m_log.DebugFormat(
  856. "[LOGHTTP]: HTTP OUT {0} SynchronousRestForms {1} {2}",
  857. reqnum, verb, requestUrl);
  858. int tickstart = Util.EnvironmentTickCount();
  859. int tickdata = 0;
  860. WebRequest request = WebRequest.Create(requestUrl);
  861. request.Method = verb;
  862. if (timeoutsecs > 0)
  863. request.Timeout = timeoutsecs * 1000;
  864. string respstring = String.Empty;
  865. using (MemoryStream buffer = new MemoryStream())
  866. {
  867. if ((verb == "POST") || (verb == "PUT"))
  868. {
  869. request.ContentType = "application/x-www-form-urlencoded";
  870. int length = 0;
  871. using (StreamWriter writer = new StreamWriter(buffer))
  872. {
  873. writer.Write(obj);
  874. writer.Flush();
  875. }
  876. length = (int)obj.Length;
  877. request.ContentLength = length;
  878. byte[] data = buffer.ToArray();
  879. if (WebUtil.DebugLevel >= 5)
  880. WebUtil.LogOutgoingDetail(System.Text.Encoding.UTF8.GetString(data));
  881. Stream requestStream = null;
  882. try
  883. {
  884. requestStream = request.GetRequestStream();
  885. requestStream.Write(data, 0, length);
  886. }
  887. catch (Exception e)
  888. {
  889. m_log.ErrorFormat("[FORMS]: Error sending request to {0}: {1}. Request: {2}", requestUrl, e.Message,
  890. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  891. throw e;
  892. }
  893. finally
  894. {
  895. if (requestStream != null)
  896. requestStream.Dispose();
  897. // capture how much time was spent writing
  898. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  899. }
  900. }
  901. try
  902. {
  903. using (WebResponse resp = request.GetResponse())
  904. {
  905. if (resp.ContentLength != 0)
  906. {
  907. using (Stream respStream = resp.GetResponseStream())
  908. using (StreamReader reader = new StreamReader(respStream))
  909. respstring = reader.ReadToEnd();
  910. }
  911. }
  912. }
  913. catch (Exception e)
  914. {
  915. m_log.ErrorFormat("[FORMS]: Error receiving response from {0}: {1}. Request: {2}", requestUrl, e.Message,
  916. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  917. throw e;
  918. }
  919. }
  920. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  921. if (tickdiff > WebUtil.LongCallTime)
  922. m_log.InfoFormat(
  923. "[LOGHTTP]: [FORMS]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  924. reqnum,
  925. verb,
  926. requestUrl,
  927. tickdiff,
  928. tickdata,
  929. obj.Length > WebUtil.MaxRequestDiagLength ? obj.Remove(WebUtil.MaxRequestDiagLength) : obj);
  930. else if (WebUtil.DebugLevel >= 4)
  931. m_log.DebugFormat(
  932. "[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  933. reqnum, tickdiff, tickdata);
  934. if (WebUtil.DebugLevel >= 5)
  935. WebUtil.LogResponseDetail(respstring);
  936. return respstring;
  937. }
  938. public static string MakeRequest(string verb, string requestUrl, string obj)
  939. {
  940. return MakeRequest(verb, requestUrl, obj, -1);
  941. }
  942. }
  943. public class SynchronousRestObjectRequester
  944. {
  945. private static readonly ILog m_log =
  946. LogManager.GetLogger(
  947. MethodBase.GetCurrentMethod().DeclaringType);
  948. /// <summary>
  949. /// Perform a synchronous REST request.
  950. /// </summary>
  951. /// <param name="verb"></param>
  952. /// <param name="requestUrl"></param>
  953. /// <param name="obj"> </param>
  954. /// <returns></returns>
  955. ///
  956. /// <exception cref="System.Net.WebException">Thrown if we encounter a network issue while posting
  957. /// the request. You'll want to make sure you deal with this as they're not uncommon</exception>
  958. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj)
  959. {
  960. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, 0);
  961. }
  962. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout)
  963. {
  964. return MakeRequest<TRequest, TResponse>(verb, requestUrl, obj, pTimeout, 0);
  965. }
  966. public static TResponse MakeRequest<TRequest, TResponse>(string verb, string requestUrl, TRequest obj, int pTimeout, int maxConnections)
  967. {
  968. int reqnum = WebUtil.RequestNumber++;
  969. if (WebUtil.DebugLevel >= 3)
  970. m_log.DebugFormat(
  971. "[LOGHTTP]: HTTP OUT {0} SynchronousRestObject {1} {2}",
  972. reqnum, verb, requestUrl);
  973. int tickstart = Util.EnvironmentTickCount();
  974. int tickdata = 0;
  975. Type type = typeof(TRequest);
  976. TResponse deserial = default(TResponse);
  977. WebRequest request = WebRequest.Create(requestUrl);
  978. HttpWebRequest ht = (HttpWebRequest)request;
  979. if (maxConnections > 0 && ht.ServicePoint.ConnectionLimit < maxConnections)
  980. ht.ServicePoint.ConnectionLimit = maxConnections;
  981. request.Method = verb;
  982. MemoryStream buffer = null;
  983. try
  984. {
  985. if ((verb == "POST") || (verb == "PUT"))
  986. {
  987. request.ContentType = "text/xml";
  988. buffer = new MemoryStream();
  989. XmlWriterSettings settings = new XmlWriterSettings();
  990. settings.Encoding = Encoding.UTF8;
  991. using (XmlWriter writer = XmlWriter.Create(buffer, settings))
  992. {
  993. XmlSerializer serializer = new XmlSerializer(type);
  994. serializer.Serialize(writer, obj);
  995. writer.Flush();
  996. }
  997. int length = (int)buffer.Length;
  998. request.ContentLength = length;
  999. byte[] data = buffer.ToArray();
  1000. if (WebUtil.DebugLevel >= 5)
  1001. WebUtil.LogOutgoingDetail(System.Text.Encoding.UTF8.GetString(data));
  1002. try
  1003. {
  1004. using (Stream requestStream = request.GetRequestStream())
  1005. requestStream.Write(data, 0, length);
  1006. }
  1007. catch (Exception e)
  1008. {
  1009. m_log.DebugFormat(
  1010. "[SynchronousRestObjectRequester]: Exception in making request {0} {1}: {2}{3}",
  1011. verb, requestUrl, e.Message, e.StackTrace);
  1012. return deserial;
  1013. }
  1014. finally
  1015. {
  1016. // capture how much time was spent writing
  1017. tickdata = Util.EnvironmentTickCountSubtract(tickstart);
  1018. }
  1019. }
  1020. try
  1021. {
  1022. using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
  1023. {
  1024. if (resp.ContentLength != 0)
  1025. {
  1026. using (Stream respStream = resp.GetResponseStream())
  1027. {
  1028. XmlSerializer deserializer = new XmlSerializer(typeof(TResponse));
  1029. if (WebUtil.DebugLevel >= 5)
  1030. {
  1031. byte[] data = new byte[resp.ContentLength];
  1032. Util.ReadStream(respStream, data);
  1033. WebUtil.LogResponseDetail(System.Text.Encoding.UTF8.GetString(data));
  1034. using (MemoryStream temp = new MemoryStream(data))
  1035. deserial = (TResponse)deserializer.Deserialize(temp);
  1036. }
  1037. else
  1038. {
  1039. deserial = (TResponse)deserializer.Deserialize(respStream);
  1040. }
  1041. }
  1042. }
  1043. else
  1044. {
  1045. m_log.DebugFormat(
  1046. "[SynchronousRestObjectRequester]: Oops! no content found in response stream from {0} {1}",
  1047. verb, requestUrl);
  1048. }
  1049. }
  1050. }
  1051. catch (WebException e)
  1052. {
  1053. using (HttpWebResponse hwr = (HttpWebResponse)e.Response)
  1054. {
  1055. if (hwr != null && hwr.StatusCode == HttpStatusCode.NotFound)
  1056. return deserial;
  1057. else
  1058. m_log.ErrorFormat(
  1059. "[SynchronousRestObjectRequester]: WebException for {0} {1} {2}: {3} {4}",
  1060. verb, requestUrl, typeof(TResponse).ToString(), e.Message, e.StackTrace);
  1061. }
  1062. }
  1063. catch (System.InvalidOperationException)
  1064. {
  1065. // This is what happens when there is invalid XML
  1066. m_log.DebugFormat(
  1067. "[SynchronousRestObjectRequester]: Invalid XML from {0} {1} {2}",
  1068. verb, requestUrl, typeof(TResponse).ToString());
  1069. }
  1070. catch (Exception e)
  1071. {
  1072. m_log.DebugFormat(
  1073. "[SynchronousRestObjectRequester]: Exception on response from {0} {1}: {2}{3}",
  1074. verb, requestUrl, e.Message, e.StackTrace);
  1075. }
  1076. int tickdiff = Util.EnvironmentTickCountSubtract(tickstart);
  1077. if (tickdiff > WebUtil.LongCallTime)
  1078. {
  1079. string originalRequest = null;
  1080. if (buffer != null)
  1081. {
  1082. originalRequest = Encoding.UTF8.GetString(buffer.ToArray());
  1083. if (originalRequest.Length > WebUtil.MaxRequestDiagLength)
  1084. originalRequest = originalRequest.Remove(WebUtil.MaxRequestDiagLength);
  1085. }
  1086. m_log.InfoFormat(
  1087. "[LOGHTTP]: [SynchronousRestObjectRequester]: Slow request {0} {1} {2} took {3}ms, {4}ms writing, {5}",
  1088. reqnum,
  1089. verb,
  1090. requestUrl,
  1091. tickdiff,
  1092. tickdata,
  1093. originalRequest);
  1094. }
  1095. else if (WebUtil.DebugLevel >= 4)
  1096. {
  1097. m_log.DebugFormat(
  1098. "[LOGHTTP]: HTTP OUT {0} took {1}ms, {2}ms writing",
  1099. reqnum, tickdiff, tickdata);
  1100. }
  1101. }
  1102. finally
  1103. {
  1104. if (buffer != null)
  1105. buffer.Dispose();
  1106. }
  1107. return deserial;
  1108. }
  1109. }
  1110. }