FileWebRequest.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. //
  2. // System.Net.FileWebRequest
  3. //
  4. // Author:
  5. // Lawrence Pit ([email protected])
  6. //
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining
  9. // a copy of this software and associated documentation files (the
  10. // "Software"), to deal in the Software without restriction, including
  11. // without limitation the rights to use, copy, modify, merge, publish,
  12. // distribute, sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do so, subject to
  14. // the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be
  17. // included in all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. //
  27. using System;
  28. using System.Collections;
  29. using System.IO;
  30. using System.Runtime.Serialization;
  31. using System.Runtime.Remoting.Messaging;
  32. using System.Threading;
  33. namespace System.Net
  34. {
  35. [Serializable]
  36. public class FileWebRequest : WebRequest, ISerializable
  37. {
  38. private Uri uri;
  39. private WebHeaderCollection webHeaders;
  40. private ICredentials credentials;
  41. private string connectionGroup;
  42. private string method = "GET";
  43. private int timeout = 100000;
  44. private Stream requestStream;
  45. private FileWebResponse webResponse;
  46. private AutoResetEvent requestEndEvent;
  47. private bool requesting;
  48. private bool asyncResponding;
  49. // Constructors
  50. internal FileWebRequest (Uri uri)
  51. {
  52. this.uri = uri;
  53. this.webHeaders = new WebHeaderCollection ();
  54. }
  55. protected FileWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
  56. {
  57. SerializationInfo info = serializationInfo;
  58. method = info.GetString ("method");
  59. uri = (Uri) info.GetValue ("uri", typeof (Uri));
  60. timeout = info.GetInt32 ("timeout");
  61. connectionGroup = info.GetString ("connectionGroup");
  62. webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
  63. }
  64. // Properties
  65. // currently not used according to spec
  66. public override string ConnectionGroupName {
  67. get { return connectionGroup; }
  68. set { connectionGroup = value; }
  69. }
  70. public override long ContentLength {
  71. get {
  72. try {
  73. return Int64.Parse (webHeaders ["Content-Length"]);
  74. } catch (Exception) {
  75. return 0;
  76. }
  77. }
  78. set {
  79. if (value < 0)
  80. throw new ArgumentException ("value");
  81. webHeaders ["Content-Length"] = Convert.ToString (value);
  82. }
  83. }
  84. public override string ContentType {
  85. get { return webHeaders ["Content-Type"]; }
  86. set { webHeaders ["Content-Type"] = value; }
  87. }
  88. public override ICredentials Credentials {
  89. get { return credentials; }
  90. set { credentials = value; }
  91. }
  92. public override WebHeaderCollection Headers {
  93. get { return webHeaders; }
  94. }
  95. // currently not used according to spec
  96. public override string Method {
  97. get { return this.method; }
  98. set { this.method = value; }
  99. }
  100. // currently not used according to spec
  101. public override bool PreAuthenticate {
  102. get { throw new NotSupportedException (); }
  103. set { throw new NotSupportedException (); }
  104. }
  105. // currently not used according to spec
  106. public override IWebProxy Proxy {
  107. get { throw new NotSupportedException (); }
  108. set { throw new NotSupportedException (); }
  109. }
  110. public override Uri RequestUri {
  111. get { return this.uri; }
  112. }
  113. public override int Timeout {
  114. get { return timeout; }
  115. set {
  116. if (value < 0)
  117. throw new ArgumentException ("value");
  118. timeout = value;
  119. }
  120. }
  121. // Methods
  122. private delegate Stream GetRequestStreamCallback ();
  123. private delegate WebResponse GetResponseCallback ();
  124. public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
  125. {
  126. if (method == null || (!method.Equals ("PUT") && !method.Equals ("POST")))
  127. throw new ProtocolViolationException ("Cannot send file when method is: " + this.method + ". Method must be PUT.");
  128. // workaround for bug 24943
  129. Exception e = null;
  130. lock (this) {
  131. if (asyncResponding || webResponse != null)
  132. e = new InvalidOperationException ("This operation cannot be performed after the request has been submitted.");
  133. else if (requesting)
  134. e = new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  135. else
  136. requesting = true;
  137. }
  138. if (e != null)
  139. throw e;
  140. /*
  141. lock (this) {
  142. if (asyncResponding || webResponse != null)
  143. throw new InvalidOperationException ("This operation cannot be performed after the request has been submitted.");
  144. if (requesting)
  145. throw new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  146. requesting = true;
  147. }
  148. */
  149. GetRequestStreamCallback c = new GetRequestStreamCallback (this.GetRequestStreamInternal);
  150. return c.BeginInvoke (callback, state);
  151. }
  152. public override Stream EndGetRequestStream (IAsyncResult asyncResult)
  153. {
  154. if (asyncResult == null)
  155. throw new ArgumentNullException ("asyncResult");
  156. if (!asyncResult.IsCompleted)
  157. asyncResult.AsyncWaitHandle.WaitOne ();
  158. AsyncResult async = (AsyncResult) asyncResult;
  159. GetRequestStreamCallback cb = (GetRequestStreamCallback) async.AsyncDelegate;
  160. return cb.EndInvoke (asyncResult);
  161. }
  162. public override Stream GetRequestStream()
  163. {
  164. IAsyncResult asyncResult = BeginGetRequestStream (null, null);
  165. if (!(asyncResult.AsyncWaitHandle.WaitOne (timeout, false))) {
  166. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  167. }
  168. return EndGetRequestStream (asyncResult);
  169. }
  170. internal Stream GetRequestStreamInternal ()
  171. {
  172. this.requestStream = new FileWebStream (
  173. this,
  174. FileMode.CreateNew,
  175. FileAccess.Write,
  176. FileShare.Read);
  177. return this.requestStream;
  178. }
  179. public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
  180. {
  181. // workaround for bug 24943
  182. Exception e = null;
  183. lock (this) {
  184. if (asyncResponding)
  185. e = new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  186. else
  187. asyncResponding = true;
  188. }
  189. if (e != null)
  190. throw e;
  191. /*
  192. lock (this) {
  193. if (asyncResponding)
  194. throw new InvalidOperationException ("Cannot re-call start of asynchronous method while a previous call is still in progress.");
  195. asyncResponding = true;
  196. }
  197. */
  198. GetResponseCallback c = new GetResponseCallback (this.GetResponseInternal);
  199. return c.BeginInvoke (callback, state);
  200. }
  201. public override WebResponse EndGetResponse (IAsyncResult asyncResult)
  202. {
  203. if (asyncResult == null)
  204. throw new ArgumentNullException ("asyncResult");
  205. if (!asyncResult.IsCompleted)
  206. asyncResult.AsyncWaitHandle.WaitOne ();
  207. AsyncResult async = (AsyncResult) asyncResult;
  208. GetResponseCallback cb = (GetResponseCallback) async.AsyncDelegate;
  209. WebResponse webResponse = cb.EndInvoke(asyncResult);
  210. asyncResponding = false;
  211. return webResponse;
  212. }
  213. public override WebResponse GetResponse ()
  214. {
  215. IAsyncResult asyncResult = BeginGetResponse (null, null);
  216. if (!(asyncResult.AsyncWaitHandle.WaitOne (timeout, false))) {
  217. throw new WebException("The request timed out", WebExceptionStatus.Timeout);
  218. }
  219. return EndGetResponse (asyncResult);
  220. }
  221. WebResponse GetResponseInternal ()
  222. {
  223. if (webResponse != null)
  224. return webResponse;
  225. lock (this) {
  226. if (requesting) {
  227. requestEndEvent = new AutoResetEvent (false);
  228. }
  229. }
  230. if (requestEndEvent != null) {
  231. requestEndEvent.WaitOne ();
  232. }
  233. FileStream fileStream = new FileWebStream (
  234. this,
  235. FileMode.Open,
  236. FileAccess.Read,
  237. FileShare.Read);
  238. this.webResponse = new FileWebResponse (this.uri, fileStream);
  239. return (WebResponse) this.webResponse;
  240. }
  241. void ISerializable.GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
  242. {
  243. SerializationInfo info = serializationInfo;
  244. info.AddValue ("method", method);
  245. info.AddValue ("uri", uri, typeof (Uri));
  246. info.AddValue ("timeout", timeout);
  247. info.AddValue ("connectionGroup", connectionGroup);
  248. info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
  249. }
  250. internal void Close ()
  251. {
  252. // already done in class below
  253. // if (requestStream != null) {
  254. // requestStream.Close ();
  255. // }
  256. lock (this) {
  257. requesting = false;
  258. if (requestEndEvent != null)
  259. requestEndEvent.Set ();
  260. // requestEndEvent = null;
  261. }
  262. }
  263. // to catch the Close called on the FileStream
  264. internal class FileWebStream : FileStream
  265. {
  266. FileWebRequest webRequest;
  267. internal FileWebStream (FileWebRequest webRequest,
  268. FileMode mode,
  269. FileAccess access,
  270. FileShare share)
  271. : base (webRequest.RequestUri.LocalPath,
  272. mode, access, share)
  273. {
  274. this.webRequest = webRequest;
  275. }
  276. public override void Close()
  277. {
  278. base.Close ();
  279. FileWebRequest req = webRequest;
  280. webRequest = null;
  281. if (req != null)
  282. req.Close ();
  283. }
  284. }
  285. }
  286. }