source: extensions/PiwigoLib/PiwigoLib/Proxy/PwgGenericProxy.cs @ 11872

Last change on this file since 11872 was 11872, checked in by bayral, 13 years ago
File size: 15.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Net;
5using System.IO;
6
7using System.Web;
8using System.Xml.Serialization;
9using System.Xml;
10using System.Collections.Specialized;
11
12namespace Com.Piwigo.Lib.Proxy
13{
14
15    static internal class PwgGenericProxy<T>
16    {
17        /// <summary>
18        /// Send Get data request to piwigo
19        /// </summary>
20        /// <param name="address"></param>
21        /// <param name="methodName"></param>
22        /// <param name="methodParameter"></param>
23        /// <returns></returns>
24        internal static T Get(Uri address, String methodName, String methodParameter)
25        {
26            T ReturnValue = default(T);
27            HttpWebRequest Request;
28            HttpWebResponse Response = null;
29            StreamReader Reader;
30
31            if (address == null) { throw new PwgProxyException("The get address is null."); }
32
33            try
34            {
35                UriBuilder completeUri = new UriBuilder(address);
36                if (methodParameter == null)
37                {
38                    completeUri.Query = String.Format("method={0}", methodName);
39                }
40                else
41                {
42                    completeUri.Query = String.Format("method={0}&{1}", methodName, methodParameter);
43                }
44                // Create and initialize the web request 
45                Request = WebRequest.Create(completeUri.Uri) as HttpWebRequest;
46                Request.UserAgent = PwgConfigProxy.PwgUserAgent;
47                Request.KeepAlive = PwgConfigProxy.PwgKeepAlive;
48#if DEBUG
49                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000;
50#else
51                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000;
52#endif
53
54                Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie
55
56                // Get response 
57                Response = Request.GetResponse() as HttpWebResponse;
58
59                if (Request.HaveResponse == true && Response != null)
60                {
61                    // Get the response stream 
62                    Reader = new StreamReader(Response.GetResponseStream());
63
64                    ReturnValue = DeserializeObject(Reader);
65                }
66            }
67            catch (WebException wex)
68            {
69                // This exception will be raised if the server didn't return 200 - OK 
70                // Try to retrieve more information about the network error 
71                if (wex.Response != null)
72                {
73                    using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
74                    {
75                        throw new PwgProxyException(
76                            String.Format(
77                                "The server returned '{0}' with the status code {1} ({2:d}).",
78                                errorResponse.StatusDescription, errorResponse.StatusCode,
79                                errorResponse.StatusCode),
80                                wex);
81                    }
82                }
83            }
84            finally
85            {
86                if (Response != null) { Response.Close(); }
87            }
88            return ReturnValue;
89        }
90
91        /// <summary>
92        /// Send Post data request to piwigo
93        /// </summary>
94        /// <param name="address"></param>
95        /// <param name="data"></param>
96        /// <returns></returns>
97        internal static T Post(Uri address, String data)
98        {
99            T ReturnValue = default(T);
100
101            HttpWebRequest Request;
102            HttpWebResponse Response = null;
103
104            if (address == null) { throw new PwgProxyException("The get address is null."); }
105
106            try
107            {
108                // Create the web request 
109                Request = WebRequest.Create(address) as HttpWebRequest;
110                Request.UserAgent = PwgConfigProxy.PwgUserAgent;
111                Request.KeepAlive = PwgConfigProxy.PwgKeepAlive;
112#if DEBUG
113                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000;
114#else
115                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000;
116#endif
117
118                Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie
119
120                // Set type to POST 
121                Request.Method = "POST";
122                Request.ContentType = "application/x-www-form-urlencoded";
123
124                // Create a byte array of the data we want to send 
125                byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);
126
127                // Set the content length in the request headers 
128                Request.ContentLength = byteData.Length;
129
130                // Write data 
131                using (Stream PostStream = Request.GetRequestStream())
132                {
133                    PostStream.Write(byteData, 0, byteData.Length);
134                }
135
136                // Get response 
137                using (Response = Request.GetResponse() as HttpWebResponse)
138                {
139                    // Get the response stream 
140                    StreamReader reader = new StreamReader(Response.GetResponseStream());
141
142                    ReturnValue = DeserializeObject(reader);
143                }
144            }
145            catch (WebException wex)
146            {
147                // This exception will be raised if the server didn't return 200 - OK 
148                // Try to retrieve more information about the network error 
149                if (wex.Response != null)
150                {
151                    using (HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response)
152                    {
153                        throw new PwgProxyException(
154                            String.Format(
155                                "The server returned '{0}' with the status code {1} ({2:d}).",
156                                ErrorResponse.StatusDescription, ErrorResponse.StatusCode,
157                                ErrorResponse.StatusCode),
158                            wex);
159                    }
160                }
161            }
162            finally
163            {
164                if (Response != null) { Response.Close(); }
165            }
166            return ReturnValue;
167        }
168
169        private class MimePart
170        {
171            internal NameValueCollection Headers { get; set; }
172            internal byte[] Header { get; set; }
173            internal Stream Data { get; set; }
174
175            internal MimePart()
176            {
177                Headers = new NameValueCollection();
178            }
179        }
180        /// <summary>
181        ///
182        /// </summary>
183        /// <param name="address">URI of server</param>
184        /// <param name="dcFiles">Dictionary(String NameOfFileFiel, String FilePath) FilePath must exist on hdd</param>
185        /// <param name="dcFields">Dictionary(String NameOfFormField, String ValueForField) others form filed to submit</param>
186        /// <returns></returns>
187        internal static T PostAsMultiPartForm(Uri address, Dictionary<String, String> dcFiles, Dictionary<String, String> dcFields)
188        {           
189            List<MimePart> lstMimeParts = new List<MimePart>();
190            T ReturnValue = default(T);
191
192            HttpWebRequest Request;
193            HttpWebResponse Response = null;
194           
195            if (address == null) { throw new PwgProxyException("The get address is null."); }
196
197            try
198            {
199                // Create the web request 
200                Request = WebRequest.Create(address) as HttpWebRequest;
201                Request.UserAgent = PwgConfigProxy.PwgUserAgent;
202                Request.KeepAlive = PwgConfigProxy.PwgKeepAlive;
203#if DEBUG
204                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000;
205#else
206                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000;
207#endif
208                Request.SendChunked = true;
209                Request.ProtocolVersion = System.Net.HttpVersion.Version11;
210                Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie       
211
212                // MultiPart Post Request
213                Request.ContentType = "multipart/form-data;";
214                Request.Method = "POST";
215
216                // Loading Mine Part data from others form fields
217                foreach (string key in dcFields.Keys)
218                {
219                    MimePart part = new MimePart();
220                    part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";
221                    part.Data = new MemoryStream(Encoding.UTF8.GetBytes(dcFields[key]));
222                    lstMimeParts.Add(part);
223                }
224
225                // Loading MinePart data from form file fields
226                foreach (String strFieldName in dcFiles.Keys)
227                {
228                    MimePart part = new MimePart();
229                    part.Headers["Content-Disposition"] = "form-data; name=\"" + strFieldName + "\"; filename=\"" + dcFiles[strFieldName] + "\"";
230                    part.Headers["Content-Type"] = "application/octet-stream";
231                    part.Data = File.OpenRead(dcFiles[strFieldName]); // Open file for getting a stream reader on it.
232                    lstMimeParts.Add(part);
233                }
234
235                string strBound = "----------" + DateTime.Now.Ticks.ToString("x");
236                byte[] strFooter = Encoding.UTF8.GetBytes("--" + strBound + "--\r\n");
237                Request.ContentType += " boundary=" + strBound;
238
239                long contentLength = 0;
240                foreach (MimePart part in lstMimeParts)
241                {                   
242                    StringBuilder sb = new StringBuilder();
243
244                    sb.Append("--");
245                    sb.Append(strBound);
246                    sb.AppendLine();
247                    foreach (string key in part.Headers.AllKeys)
248                    {
249                        sb.Append(key);
250                        sb.Append(": ");
251                        sb.AppendLine(part.Headers[key]);
252                    }
253                    sb.AppendLine();
254
255                    part.Header = Encoding.UTF8.GetBytes(sb.ToString());
256
257                    contentLength += part.Header.Length + part.Data.Length + 2;
258
259                }
260
261                Request.ContentLength = contentLength + strFooter.Length;
262
263                byte[] buffer = new byte[8192];
264                byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
265                int read;
266
267                using (Stream s = Request.GetRequestStream())
268                {
269                    foreach (MimePart part in lstMimeParts)
270                    {
271                        s.Write(part.Header, 0, part.Header.Length);
272
273                        while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
274                            s.Write(buffer, 0, read);
275
276                        part.Data.Close();
277                        part.Data.Dispose();
278
279                        s.Write(afterFile, 0, afterFile.Length);
280                    }
281
282                    s.Write(strFooter, 0, strFooter.Length);
283                }
284
285                // Get response 
286                using (Response = Request.GetResponse() as HttpWebResponse)
287                {
288                    // Get the response stream 
289                    StreamReader reader = new StreamReader(Response.GetResponseStream());
290
291                    ReturnValue = DeserializeObject(reader);
292                }
293            }
294            catch (WebException wex)
295            {
296                // This exception will be raised if the server didn't return 200 - OK 
297                // Try to retrieve more information about the network error 
298                if (wex.Response != null)
299                {
300                    using (HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response)
301                    {
302                        throw new PwgProxyException(
303                            String.Format(
304                                "The server returned '{0}' with the status code {1} ({2:d}).",
305                                ErrorResponse.StatusDescription, ErrorResponse.StatusCode,
306                                ErrorResponse.StatusCode),
307                            wex);
308                    }
309                }
310            }
311            catch (IOException ioex)
312            {
313                // This exception will be raised if file aren't ok on client
314                if (ioex!= null)
315                {
316                        throw new PwgProxyException(
317                            String.Format(
318                                "A IO file exception stop the request building : {0}.", ioex.Message),
319                            ioex);
320                }
321            }
322            finally
323            {
324                if (Response != null) { Response.Close(); }
325                foreach (MimePart part in lstMimeParts)
326                {
327                    if (part.Data != null)
328                        part.Data.Dispose();
329                }
330            }
331            return ReturnValue;
332        }
333   
334        /// <summary>
335        ///  return object from xml retuned by piwigo
336        /// </summary>
337        /// <param name="xmlData"></param>
338        /// <returns></returns>
339        internal static T DeserializeObject(StreamReader xmlData)
340        {
341            T ReturnValue = default(T);
342            String line = String.Empty;
343            try
344            {
345#if DEBUG
346                line = xmlData.ReadToEnd();
347                System.Diagnostics.Debug.WriteLine(line);
348
349                byte[] hexLine = System.Text.Encoding.UTF8.GetBytes(line);
350                MemoryStream m = new System.IO.MemoryStream(hexLine);
351                StreamReader xmlDat = new StreamReader(m);
352#else
353                xmlDat = xmlData;
354#endif
355                System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
356                ReturnValue = (T)xsSerializer.Deserialize(xmlDat);
357            }
358            catch (Exception ex)
359            {
360                throw new PwgProxyException(
361                            String.Format(
362                                "The value {0} can't be deserialized in {1}, the error is {2} .",
363                                line, typeof(T).Name, ex.Message),
364                            ex);
365            }
366
367            return ReturnValue;
368        }
369
370        internal static void SerializeToXML(String fileName, T obj)
371        {
372            try
373            {
374                XmlSerializer serializer = new XmlSerializer(typeof(T));
375                TextWriter textWriter = new StreamWriter(fileName);
376                serializer.Serialize(textWriter, obj);
377                textWriter.Close();
378            }
379            catch (Exception ex)
380            {
381                throw new PwgProxyException(
382                            String.Format(
383                                "The value {0} can't be serialized in {1}, the error is {2} .",
384                                obj, fileName, ex.Message),
385                            ex);
386            }
387        }
388    }
389}
Note: See TracBrowser for help on using the repository browser.