using System; using System.Collections.Generic; using System.Text; using System.Net; using System.IO; using System.Web; using System.Xml.Serialization; using System.Xml; using System.Collections.Specialized; namespace Com.Piwigo.Lib.Proxy { static internal class PwgGenericProxy { /// /// Send Get data request to piwigo /// /// /// /// /// internal static T Get(Uri address, String methodName, String methodParameter) { T ReturnValue = default(T); HttpWebRequest Request; HttpWebResponse Response = null; StreamReader Reader; if (address == null) { throw new PwgProxyException("The get address is null."); } try { UriBuilder completeUri = new UriBuilder(address); if (methodParameter == null) { completeUri.Query = String.Format("method={0}", methodName); } else { completeUri.Query = String.Format("method={0}&{1}", methodName, methodParameter); } // Create and initialize the web request Request = WebRequest.Create(completeUri.Uri) as HttpWebRequest; Request.UserAgent = PwgConfigProxy.PwgUserAgent; Request.KeepAlive = PwgConfigProxy.PwgKeepAlive; #if DEBUG Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000; #else Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000; #endif Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie // Get response Response = Request.GetResponse() as HttpWebResponse; if (Request.HaveResponse == true && Response != null) { // Get the response stream Reader = new StreamReader(Response.GetResponseStream()); ReturnValue = DeserializeObject(Reader); } } catch (WebException wex) { // This exception will be raised if the server didn't return 200 - OK // Try to retrieve more information about the network error if (wex.Response != null) { using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response) { throw new PwgProxyException( String.Format( "The server returned '{0}' with the status code {1} ({2:d}).", errorResponse.StatusDescription, errorResponse.StatusCode, errorResponse.StatusCode), wex); } } } finally { if (Response != null) { Response.Close(); } } return ReturnValue; } /// /// Send Post data request to piwigo /// /// /// /// internal static T Post(Uri address, String data) { T ReturnValue = default(T); //System.Net.ServicePointManager.Expect100Continue = false; HttpWebRequest Request; HttpWebResponse Response = null; if (address == null) { throw new PwgProxyException("The get address is null."); } try { // Create the web request Request = WebRequest.Create(address) as HttpWebRequest; Request.UserAgent = PwgConfigProxy.PwgUserAgent; Request.KeepAlive = PwgConfigProxy.PwgKeepAlive; #if DEBUG Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000; #else Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000; #endif Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie // Set type to POST Request.Method = "POST"; Request.ContentType = "application/x-www-form-urlencoded"; // Create a byte array of the data we want to send byte[] byteData = UTF8Encoding.UTF8.GetBytes(data); // Set the content length in the request headers Request.ContentLength = byteData.Length; // Write data using (Stream PostStream = Request.GetRequestStream()) { PostStream.Write(byteData, 0, byteData.Length); } // Get response using (Response = Request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(Response.GetResponseStream()); ReturnValue = DeserializeObject(reader); } } catch (WebException wex) { // This exception will be raised if the server didn't return 200 - OK // Try to retrieve more information about the network error if (wex.Response != null) { using (HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response) { throw new PwgProxyException( String.Format( "The server returned '{0}' with the status code {1} ({2:d}).", ErrorResponse.StatusDescription, ErrorResponse.StatusCode, ErrorResponse.StatusCode), wex); } } } finally { if (Response != null) { Response.Close(); } } return ReturnValue; } private class MimePart { internal NameValueCollection Headers { get; set; } internal byte[] Header { get; set; } internal Stream Data { get; set; } internal MimePart() { Headers = new NameValueCollection(); } } /// /// /// /// URI of server /// Dictionary(String NameOfFileFiel, String FilePath) FilePath must exist on hdd /// Dictionary(String NameOfFormField, String ValueForField) others form filed to submit /// internal static T PostAsMultiPartForm(Uri address, Dictionary dcFiles, Dictionary dcFields) { List lstMimeParts = new List(); T ReturnValue = default(T); HttpWebRequest Request; HttpWebResponse Response = null; if (address == null) { throw new PwgProxyException("The get address is null."); } try { // Create the web request Request = WebRequest.Create(address) as HttpWebRequest; Request.UserAgent = PwgConfigProxy.PwgUserAgent; Request.KeepAlive = PwgConfigProxy.PwgKeepAlive; #if DEBUG Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000 * 1000; #else Request.Timeout = PwgConfigProxy.PwgTimeOutInSecond * 1000; #endif Request.SendChunked = true; Request.ProtocolVersion = System.Net.HttpVersion.Version11; Request.CookieContainer = PwgConfigProxy.cookieContainer; // get session cookie // MultiPart Post Request Request.ContentType = "multipart/form-data;"; Request.Method = "POST"; // Loading Mine Part data from others form fields foreach (string key in dcFields.Keys) { MimePart part = new MimePart(); part.Headers["Content-Disposition"] = "form-data; name=\"" + key + "\""; part.Data = new MemoryStream(Encoding.UTF8.GetBytes(dcFields[key])); lstMimeParts.Add(part); } // Loading MinePart data from form file fields foreach (String strFieldName in dcFiles.Keys) { MimePart part = new MimePart(); part.Headers["Content-Disposition"] = "form-data; name=\"" + strFieldName + "\"; filename=\"" + dcFiles[strFieldName] + "\""; part.Headers["Content-Type"] = "application/octet-stream"; part.Data = File.OpenRead(dcFiles[strFieldName]); // Open file for getting a stream reader on it. lstMimeParts.Add(part); } string strBound = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] strFooter = Encoding.UTF8.GetBytes("--" + strBound + "--\r\n"); Request.ContentType += " boundary=" + strBound; long contentLength = 0; foreach (MimePart part in lstMimeParts) { StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBound); sb.AppendLine(); foreach (string key in part.Headers.AllKeys) { sb.Append(key); sb.Append(": "); sb.AppendLine(part.Headers[key]); } sb.AppendLine(); part.Header = Encoding.UTF8.GetBytes(sb.ToString()); contentLength += part.Header.Length + part.Data.Length + 2; } Request.ContentLength = contentLength + strFooter.Length; byte[] buffer = new byte[8192]; byte[] afterFile = Encoding.UTF8.GetBytes("\r\n"); int read; using (Stream s = Request.GetRequestStream()) { foreach (MimePart part in lstMimeParts) { s.Write(part.Header, 0, part.Header.Length); while ((read = part.Data.Read(buffer, 0, buffer.Length)) > 0) s.Write(buffer, 0, read); part.Data.Close(); part.Data.Dispose(); s.Write(afterFile, 0, afterFile.Length); } s.Write(strFooter, 0, strFooter.Length); } // Get response using (Response = Request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(Response.GetResponseStream()); ReturnValue = DeserializeObject(reader); } } catch (WebException wex) { // This exception will be raised if the server didn't return 200 - OK // Try to retrieve more information about the network error if (wex.Response != null) { using (HttpWebResponse ErrorResponse = (HttpWebResponse)wex.Response) { throw new PwgProxyException( String.Format( "The server returned '{0}' with the status code {1} ({2:d}).", ErrorResponse.StatusDescription, ErrorResponse.StatusCode, ErrorResponse.StatusCode), wex); } } } catch (IOException ioex) { // This exception will be raised if file aren't ok on client if (ioex!= null) { throw new PwgProxyException( String.Format( "A IO file exception stop the request building : {0}.", ioex.Message), ioex); } } finally { if (Response != null) { Response.Close(); } foreach (MimePart part in lstMimeParts) { if (part.Data != null) part.Data.Dispose(); } } return ReturnValue; } /// /// return object from xml retuned by piwigo /// /// /// internal static T DeserializeObject(StreamReader xmlData) { T ReturnValue = default(T); String line = String.Empty; try { #if DEBUG line = xmlData.ReadToEnd(); System.Diagnostics.Debug.WriteLine(line); byte[] hexLine = System.Text.Encoding.UTF8.GetBytes(line); MemoryStream m = new System.IO.MemoryStream(hexLine); StreamReader xmlDat = new StreamReader(m); #else xmlDat = xmlData; #endif System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); ReturnValue = (T)xsSerializer.Deserialize(xmlDat); } catch (Exception ex) { throw new PwgProxyException( String.Format( "The value {0} can't be deserialized in {1}, the error is {2} .", line, typeof(T).Name, ex.Message), ex); } return ReturnValue; } internal static void SerializeToXML(String fileName, T obj) { try { XmlSerializer serializer = new XmlSerializer(typeof(T)); TextWriter textWriter = new StreamWriter(fileName); serializer.Serialize(textWriter, obj); textWriter.Close(); } catch (Exception ex) { throw new PwgProxyException( String.Format( "The value {0} can't be serialized in {1}, the error is {2} .", obj, fileName, ex.Message), ex); } } } }