XHRHttpWebRequest.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. //Copyright 2010 Microsoft Corporation
  2. //
  3. //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
  4. //You may obtain a copy of the License at
  5. //
  6. //http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. //Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
  9. //"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. //See the License for the specific language governing permissions and limitations under the License.
  11. namespace System.Data.Services.Http
  12. {
  13. #region Namespaces.
  14. using System;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Windows.Browser;
  20. using System.Diagnostics;
  21. #endregion Namespaces.
  22. internal sealed class XHRHttpWebRequest : System.Data.Services.Http.HttpWebRequest
  23. {
  24. #region Private fields.
  25. private bool aborted;
  26. private HttpWebRequestAsyncResult asyncRequestResult;
  27. private HttpWebRequestAsyncResult asyncResponseResult;
  28. private NonClosingMemoryStream contentStream;
  29. private System.Data.Services.Http.XHRWebHeaderCollection headers;
  30. private bool invoked;
  31. private string method;
  32. private System.Data.Services.Http.HttpWebResponse response;
  33. private ScriptXmlHttpRequest underlyingRequest;
  34. private Uri uri;
  35. #endregion Private fields.
  36. internal XHRHttpWebRequest(Uri uri)
  37. {
  38. Debug.Assert(uri != null, "uri != null");
  39. this.uri = uri;
  40. }
  41. public override string Accept
  42. {
  43. get
  44. {
  45. return this.headers[System.Data.Services.Http.HttpRequestHeader.Accept];
  46. }
  47. set
  48. {
  49. this.headers.SetSpecialHeader("accept", value);
  50. }
  51. }
  52. public override long ContentLength
  53. {
  54. set
  55. {
  56. this.headers[System.Data.Services.Http.HttpRequestHeader.ContentLength] = value.ToString(CultureInfo.InvariantCulture);
  57. }
  58. }
  59. public override bool AllowReadStreamBuffering
  60. {
  61. get { return true; }
  62. set { }
  63. }
  64. public override string ContentType
  65. {
  66. get
  67. {
  68. return this.headers[System.Data.Services.Http.HttpRequestHeader.ContentType];
  69. }
  70. set
  71. {
  72. this.headers.SetSpecialHeader("content-type", value);
  73. }
  74. }
  75. public override System.Data.Services.Http.WebHeaderCollection Headers
  76. {
  77. get
  78. {
  79. if (this.headers == null)
  80. {
  81. this.headers = new System.Data.Services.Http.XHRWebHeaderCollection(System.Data.Services.Http.WebHeaderCollectionType.HttpWebRequest);
  82. }
  83. return this.headers;
  84. }
  85. }
  86. public override string Method
  87. {
  88. get { return this.method; }
  89. set { this.method = value; }
  90. }
  91. public override Uri RequestUri
  92. {
  93. get { return this.uri; }
  94. }
  95. public static bool IsAvailable()
  96. {
  97. try
  98. {
  99. ScriptXmlHttpRequest request = new ScriptXmlHttpRequest();
  100. return (null != request);
  101. }
  102. catch (WebException)
  103. {
  104. return false;
  105. }
  106. }
  107. public override void Abort()
  108. {
  109. this.aborted = true;
  110. if (this.underlyingRequest != null)
  111. {
  112. this.underlyingRequest.Abort();
  113. this.underlyingRequest.Dispose();
  114. this.underlyingRequest = null;
  115. }
  116. if (this.response != null)
  117. {
  118. ((XHRHttpWebResponse)this.response).InternalRequest = null;
  119. this.response = null;
  120. }
  121. this.Close();
  122. }
  123. public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
  124. {
  125. if (this.aborted)
  126. {
  127. throw CreateAbortException();
  128. }
  129. if (this.contentStream == null)
  130. {
  131. this.contentStream = new NonClosingMemoryStream();
  132. }
  133. else
  134. {
  135. this.contentStream.Seek(0L, SeekOrigin.Begin);
  136. }
  137. HttpWebRequestAsyncResult asyncResult = new HttpWebRequestAsyncResult(callback, state);
  138. this.asyncRequestResult = asyncResult;
  139. this.asyncRequestResult.CompletedSynchronously = true;
  140. if (asyncResult != null)
  141. {
  142. asyncResult.SetCompleted();
  143. asyncResult.Callback(asyncResult);
  144. }
  145. return asyncResult;
  146. }
  147. public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
  148. {
  149. HttpWebRequestAsyncResult asyncResult = new HttpWebRequestAsyncResult(callback, state);
  150. try
  151. {
  152. asyncResult.InsideBegin = true;
  153. this.asyncResponseResult = asyncResult;
  154. this.InvokeRequest();
  155. }
  156. finally
  157. {
  158. asyncResult.InsideBegin = false;
  159. }
  160. return asyncResult;
  161. }
  162. public override Stream EndGetRequestStream(IAsyncResult asyncResult)
  163. {
  164. if (asyncResult == null)
  165. {
  166. throw new ArgumentNullException("asyncResult");
  167. }
  168. if (this.asyncRequestResult != asyncResult)
  169. {
  170. throw new InvalidOperationException(
  171. System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetRequestStream"));
  172. }
  173. if (this.asyncRequestResult.EndCalled)
  174. {
  175. throw new InvalidOperationException(
  176. System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetRequestStream.2"));
  177. }
  178. if (this.aborted)
  179. {
  180. throw CreateAbortException();
  181. }
  182. this.asyncRequestResult.EndCalled = true;
  183. this.asyncRequestResult.Dispose();
  184. this.asyncRequestResult = null;
  185. return this.contentStream;
  186. }
  187. public override System.Data.Services.Http.WebResponse EndGetResponse(IAsyncResult asyncResult)
  188. {
  189. if (asyncResult == null)
  190. {
  191. throw new ArgumentNullException("asyncResult");
  192. }
  193. if (this.asyncResponseResult != asyncResult)
  194. {
  195. throw new InvalidOperationException(
  196. System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetResponse"));
  197. }
  198. if (this.asyncResponseResult.EndCalled)
  199. {
  200. throw new InvalidOperationException(
  201. System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.EndGetResponse.2"));
  202. }
  203. if (this.aborted)
  204. {
  205. throw CreateAbortException();
  206. }
  207. this.asyncResponseResult.EndCalled = true;
  208. this.CreateResponse();
  209. this.asyncResponseResult.Dispose();
  210. this.asyncResponseResult = null;
  211. return this.response;
  212. }
  213. public override System.Net.WebHeaderCollection CreateEmptyWebHeaderCollection()
  214. {
  215. return System.Net.WebRequest.Create(this.RequestUri).Headers;
  216. }
  217. internal void Close()
  218. {
  219. this.Dispose(true);
  220. }
  221. internal Stream ReadResponse(IDisposable connection)
  222. {
  223. Debug.Assert(connection != null, "connection != null");
  224. if ((this.response.ContentType == null) ||
  225. this.response.ContentType.Contains("json") ||
  226. this.response.ContentType.Contains("xml") ||
  227. this.response.ContentType.Contains("text") ||
  228. this.response.ContentType.Contains("multipart"))
  229. {
  230. string buffer = this.underlyingRequest.ReadResponseAsString();
  231. return (!string.IsNullOrEmpty(buffer) ? new DisposingMemoryStream(connection, Encoding.UTF8.GetBytes(buffer)) : null);
  232. }
  233. throw WebException.CreateInternal("HttpWebRequest.ReadResponse");
  234. }
  235. protected override void Dispose(bool disposing)
  236. {
  237. if (disposing)
  238. {
  239. if (this.contentStream != null)
  240. {
  241. this.contentStream.InternalDispose();
  242. this.contentStream = null;
  243. }
  244. }
  245. }
  246. private static System.Data.Services.Http.WebException CreateAbortException()
  247. {
  248. return new System.Data.Services.Http.WebException(System.Data.Services.Client.Strings.HttpWebRequest_Aborted);
  249. }
  250. private void CreateResponse()
  251. {
  252. int statusCode;
  253. this.underlyingRequest.GetResponseStatus(out statusCode);
  254. if (statusCode != -1)
  255. {
  256. string responseHeaders = this.underlyingRequest.GetResponseHeaders();
  257. this.response = new System.Data.Services.Http.XHRHttpWebResponse(this, statusCode, responseHeaders);
  258. }
  259. }
  260. private void ReadyStateChanged()
  261. {
  262. if (this.underlyingRequest.IsCompleted && (this.asyncResponseResult != null))
  263. {
  264. try
  265. {
  266. if (this.asyncResponseResult.InsideBegin)
  267. {
  268. this.asyncResponseResult.CompletedSynchronously = true;
  269. }
  270. this.asyncResponseResult.SetCompleted();
  271. this.asyncResponseResult.Callback(this.asyncResponseResult);
  272. }
  273. finally
  274. {
  275. this.underlyingRequest.Dispose();
  276. }
  277. }
  278. }
  279. private void InvokeRequest()
  280. {
  281. if (this.aborted)
  282. {
  283. throw CreateAbortException();
  284. }
  285. if (this.invoked)
  286. {
  287. throw new InvalidOperationException(
  288. System.Data.Services.Client.Strings.HttpWeb_Internal("HttpWebRequest.InvokeRequest"));
  289. }
  290. this.invoked = true;
  291. this.underlyingRequest = new ScriptXmlHttpRequest();
  292. this.underlyingRequest.Open(this.uri.AbsoluteUri, this.Method, (Action)this.ReadyStateChanged);
  293. if ((this.headers != null) && (this.headers.Count != 0))
  294. {
  295. foreach (string header in this.headers.AllKeys)
  296. {
  297. string value = this.headers[header];
  298. this.underlyingRequest.SetRequestHeader(header, value);
  299. }
  300. }
  301. string content = null;
  302. if (this.contentStream != null)
  303. {
  304. byte[] buf = this.contentStream.GetBuffer();
  305. if (buf != null)
  306. {
  307. int bufferSize = checked((int)this.contentStream.Position);
  308. content = Encoding.UTF8.GetString(buf, 0, bufferSize);
  309. this.underlyingRequest.SetRequestHeader("content-length", bufferSize.ToString(CultureInfo.InvariantCulture));
  310. }
  311. }
  312. this.underlyingRequest.Send(content);
  313. }
  314. private sealed class HttpWebRequestAsyncResult : IAsyncResult, IDisposable
  315. {
  316. private AsyncCallback callback;
  317. private bool completed;
  318. private bool completedSynchronously;
  319. private bool endCalled;
  320. private object state;
  321. private ManualResetEvent waitHandle;
  322. public HttpWebRequestAsyncResult(AsyncCallback callback, object state)
  323. {
  324. this.callback = callback;
  325. this.state = state;
  326. }
  327. public object AsyncState
  328. {
  329. get { return this.state; }
  330. }
  331. public WaitHandle AsyncWaitHandle
  332. {
  333. get
  334. {
  335. if (this.waitHandle == null)
  336. {
  337. this.waitHandle = new ManualResetEvent(false);
  338. }
  339. return this.waitHandle;
  340. }
  341. }
  342. public AsyncCallback Callback
  343. {
  344. get { return this.callback; }
  345. }
  346. public bool CompletedSynchronously
  347. {
  348. get
  349. {
  350. return this.completedSynchronously;
  351. }
  352. internal set
  353. {
  354. this.completedSynchronously = value;
  355. }
  356. }
  357. public bool EndCalled
  358. {
  359. get { return this.endCalled; }
  360. set { this.endCalled = value; }
  361. }
  362. public bool IsCompleted
  363. {
  364. get { return this.completed; }
  365. }
  366. public bool InsideBegin
  367. {
  368. get;
  369. set;
  370. }
  371. public void Dispose()
  372. {
  373. if (this.waitHandle != null)
  374. {
  375. ((IDisposable)this.waitHandle).Dispose();
  376. }
  377. }
  378. public void SetCompleted()
  379. {
  380. this.completed = true;
  381. if (this.waitHandle != null)
  382. {
  383. this.waitHandle.Set();
  384. }
  385. }
  386. }
  387. private sealed class DisposingMemoryStream : MemoryStream
  388. {
  389. private readonly IDisposable disposable;
  390. internal DisposingMemoryStream(IDisposable disposable, byte[] buffer) : base(buffer)
  391. {
  392. Debug.Assert(disposable != null, "disposable != null");
  393. this.disposable = disposable;
  394. }
  395. protected override void Dispose(bool disposing)
  396. {
  397. this.disposable.Dispose();
  398. base.Dispose(disposing);
  399. }
  400. }
  401. private sealed class NonClosingMemoryStream : MemoryStream
  402. {
  403. public override void Close()
  404. {
  405. }
  406. internal void InternalDispose()
  407. {
  408. base.Dispose();
  409. }
  410. protected override void Dispose(bool disposing)
  411. {
  412. }
  413. }
  414. }
  415. }