Ignore:
Timestamp:
Jul 29, 2011, 6:05:05 PM (13 years ago)
Author:
bayral
Message:

MAj des truc existant et debut du upload de fichier

File:
1 edited

Legend:

Unmodified
Added
Removed
  • extensions/PiwigoLib/PiwigoLib/Proxy/PwgGenericProxy.cs

    r7149 r11850  
    88using System.Xml.Serialization;
    99using System.Xml;
     10using System.Collections.Specialized;
    1011
    1112namespace Com.Piwigo.Lib.Proxy
     
    1415    static internal class PwgGenericProxy<T>
    1516    {
    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>
    1724        internal static T Get(Uri address, String methodName, String methodParameter)
    1825        {
     
    7784        }
    7885
     86        /// <summary>
     87        /// Send Post data request to piwigo
     88        /// </summary>
     89        /// <param name="address"></param>
     90        /// <param name="data"></param>
     91        /// <returns></returns>
    7992        internal static T Post(Uri address, String data)
    8093        {
     
    144157        }
    145158
     159        private class MimePart
     160        {
     161            internal NameValueCollection Headers { get; set; }
     162            internal byte[] Header { get; set; }
     163            internal Stream Data { get; set; }
     164
     165            internal MimePart()
     166            {
     167                Headers = new NameValueCollection();
     168            }
     169        }
     170        /// <summary>
     171        ///
     172        /// </summary>
     173        /// <param name="address">URI of server</param>
     174        /// <param name="dcFiles">Dictionary(String NameOfFileFiel, String FilePath) FilePath must exist on hdd</param>
     175        /// <param name="dcFields">Dictionary(String NameOfFormField, String ValueForField) others form filed to submit</param>
     176        /// <returns></returns>
     177        internal static T PostAsMultiPartForm(Uri address, Dictionary<String, String> dcFiles, Dictionary<String, String> dcFields)
     178        {           
     179            List<MimePart> lstMimeParts = new List<MimePart>();
     180            T ReturnValue = default(T);
     181
     182            HttpWebRequest Request;
     183            HttpWebResponse Response = null;
     184           
     185            if (address == null) { throw new PwgProxyException("The get address is null."); }
     186
     187            try
     188            {
     189                // Create the web request 
     190                Request = WebRequest.Create(address) as HttpWebRequest;
     191                Request.UserAgent = PwgConfigProxy.PwgUserAgent;
     192                Request.KeepAlive = PwgConfigProxy.PwgKeepAlive;
     193                Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000;
     194                Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie       
     195
     196                // MultiPart Post Request
     197                Request.ContentType = "multipart/form-data;";
     198                Request.Method = "POST";
     199
     200                // Loading Mine Part data from others form fields
     201                foreach (string key in dcFields.Keys)
     202                {
     203                    MimePart part = new MimePart();
     204                    part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\"";
     205                    part.Data = new MemoryStream(Encoding.UTF8.GetBytes(dcFields[key]));
     206                    lstMimeParts.Add(part);
     207                }
     208
     209                // Loading MinePart data from form file fields
     210                foreach (String strFieldName in dcFiles.Keys)
     211                {
     212                    MimePart part = new MimePart();
     213                    part.Headers["Content-Disposition"] = "form-data; name=\"" + strFieldName + "\"; filename=\"" + dcFiles[strFieldName] + "\"";
     214                    part.Headers["Content-Type"] = "application/octet-stream";
     215                    part.Data = File.OpenRead(dcFiles[strFieldName]); // Open file for getting a stream reader on it.
     216                    lstMimeParts.Add(part);
     217                }
     218
     219                string strBound = "----------" + DateTime.Now.Ticks.ToString("x");
     220                byte[] strFooter = Encoding.UTF8.GetBytes("--" + strBound + "--\r\n");
     221                Request.ContentType += " boundary=" + strBound;
     222
     223                long contentLength = 0;
     224                foreach (MimePart part in lstMimeParts)
     225                {                   
     226                    StringBuilder sb = new StringBuilder();
     227
     228                    sb.Append("--");
     229                    sb.Append(strBound);
     230                    sb.AppendLine();
     231                    foreach (string key in part.Headers.AllKeys)
     232                    {
     233                        sb.Append(key);
     234                        sb.Append(": ");
     235                        sb.AppendLine(part.Headers[key]);
     236                    }
     237                    sb.AppendLine();
     238
     239                    part.Header = Encoding.UTF8.GetBytes(sb.ToString());
     240
     241                    contentLength += part.Header.Length + part.Data.Length + 2;
     242
     243                }
     244
     245                Request.ContentLength = contentLength + strFooter.Length;
     246
     247                byte[] buffer = new byte[8192];
     248                byte[] afterFile = Encoding.UTF8.GetBytes("\r\n");
     249                int read;
     250
     251                using (Stream s = Request.GetRequestStream())
     252                {
     253                    foreach (MimePart part in lstMimeParts)
     254                    {
     255                        s.Write(part.Header, 0, part.Header.Length);
     256
     257                        while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0)
     258                            s.Write(buffer, 0, read);
     259
     260                        part.Data.Close();
     261                        part.Data.Dispose();
     262
     263                        s.Write(afterFile, 0, afterFile.Length);
     264                    }
     265
     266                    s.Write(strFooter, 0, strFooter.Length);
     267                }
     268
     269                // Get response 
     270                using (Response = Request.GetResponse() as HttpWebResponse)
     271                {
     272                    // Get the response stream 
     273                    StreamReader reader = new StreamReader(Response.GetResponseStream());
     274
     275                    ReturnValue = DeserializeObject(reader);
     276                }
     277            }
     278            catch (WebException wex)
     279            {
     280                // This exception will be raised if the server didn't return 200 - OK 
     281                // Try to retrieve more information about the network error 
     282                if (wex.Response != null)
     283                {
     284                    using (HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response)
     285                    {
     286                        throw new PwgProxyException(
     287                            String.Format(
     288                                "The server returned '{0}' with the status code {1} ({2:d}).",
     289                                ErrorResponse.StatusDescription, ErrorResponse.StatusCode,
     290                                ErrorResponse.StatusCode),
     291                            wex);
     292                    }
     293                }
     294            }
     295            catch (IOException ioex)
     296            {
     297                // This exception will be raised if file aren't ok on client
     298                if (ioex!= null)
     299                {
     300                        throw new PwgProxyException(
     301                            String.Format(
     302                                "A IO file exception stop the request building : {0}.", ioex.Message),
     303                            ioex);
     304                }
     305            }
     306            finally
     307            {
     308                if (Response != null) { Response.Close(); }
     309                foreach (MimePart part in lstMimeParts)
     310                {
     311                    if (part.Data != null)
     312                        part.Data.Dispose();
     313                }
     314            }
     315            return ReturnValue;
     316        }
     317   
     318        /// <summary>
     319        ///  return object from xml retuned by piwigo
     320        /// </summary>
     321        /// <param name="xmlData"></param>
     322        /// <returns></returns>
    146323        internal static T DeserializeObject(StreamReader xmlData)
    147324        {
    148325            T ReturnValue = default(T);
    149 
    150             try
    151             {
    152                 //Console.WriteLine(xmlData.ReadToEnd());
    153 
     326            String line = String.Empty;
     327            try
     328            {
     329#if DEBUG
     330                line = xmlData.ReadToEnd();
     331                System.Diagnostics.Debug.WriteLine(line);
     332
     333                byte[] hexLine = System.Text.Encoding.UTF8.GetBytes(line);
     334                MemoryStream m = new System.IO.MemoryStream(hexLine);
     335                StreamReader xmlDat = new StreamReader(m);
     336#else
     337                xmlDat = xmlData;
     338#endif
    154339                System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
    155                 ReturnValue = (T)xsSerializer.Deserialize(xmlData);
     340                ReturnValue = (T)xsSerializer.Deserialize(xmlDat);
    156341            }
    157342            catch (Exception ex)
     
    160345                            String.Format(
    161346                                "The value {0} can't be deserialized in {1}, the error is {2} .",
    162                                 xmlData, typeof(T).Name, ex.Message),
     347                                line, typeof(T).Name, ex.Message),
    163348                            ex);
    164349            }
Note: See TracChangeset for help on using the changeset viewer.