[Myoe-cvs] MyOE/Net Connection.cs,1.5,1.6 POPConnection.cs,1.2,1.3
Status: Beta
Brought to you by:
tene_
From: Quentin P. <te...@us...> - 2004-08-17 14:52:26
|
Update of /cvsroot/myoe/MyOE/Net In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv1785/Net Modified Files: Connection.cs POPConnection.cs Log Message: - .NET 2.0 support - thousand of cross-thread bugs fixed (detected by .NET 2.0) - some C# 2.0 code (myoe won't be compatible with VS.NET 2003 anymore... without small code change) - Draft folder Index: POPConnection.cs =================================================================== RCS file: /cvsroot/myoe/MyOE/Net/POPConnection.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** POPConnection.cs 12 Apr 2004 21:03:09 -0000 1.2 --- POPConnection.cs 17 Aug 2004 14:46:00 -0000 1.3 *************** *** 1,265 **** ! // MyOE.NET ! // see www.myoe.org for more info ! // © Quentin Pouplard and MyOE contributors. ! // This application is under the GPL licence. ! // ! // when you modify this file PLEASE add all your modification here ! // format: ! // date hour - name - description ! // ! // 08/02/2003 15:24 - Quentin Pouplard - Start Comments. ! ! using System; ! ! namespace MyOE.Net.POP ! { ! /// <summary> ! /// ! /// </summary> ! public class POPConnection : MyOE.Net.Connection ! { ! string _login=""; ! public string Login ! { ! get ! { ! return _login; ! } ! set ! { ! _login=value; ! } ! } ! ! string _password=""; ! public string Password ! { ! get ! { ! return _password; ! } ! set ! { ! _password=value; ! } ! } ! ! int _messagecount=-1; ! public int MessageCount{ ! get{ ! if(_messagecount==-1){ ! SendCommand("STAT"); ! string response=ReceiveLine(); ! string[] resp=response.Split(' '); ! return int.Parse(resp[1]); ! } ! return _messagecount; ! } ! } ! ! string []_messageidcache=null; ! public string[] RetrieveAllMessageID() ! { ! try ! { ! string []idarray=new string[MessageCount]; ! ! SendCommand("UIDL"); ! string response=ReceiveLine(); ! if(response[0]!='+') throw new ConnectionException("Error while retrieving message ID: " + response); ! ! int i=0; ! ! response=ReceiveLine(); ! while(response!=".") ! { ! idarray[i]=response.Split(' ')[1]; ! // System.Diagnostics.Debug.WriteLine(response); ! i++; ! response=ReceiveLine(); ! } ! ! _messageidcache=idarray; ! ! return idarray; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return RetrieveAllMessageID(); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public int GetIndexFromUIDL(string uidl) ! { ! try ! { ! if(_messageidcache==null) ! { ! RetrieveAllMessageID(); ! } ! for(int i=0; i<_messageidcache.Length; i++) ! { ! if(_messageidcache[i]==uidl) return i; ! } ! return -1; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return GetIndexFromUIDL(uidl); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public string RetrieveMessageID(int number){ ! SendCommand("UIDL " + number); ! ! string line=ReceiveLine(); ! if(line[0]!='+'){ ! throw new ConnectionException("Error in UIDL: " + line); ! } ! string[] part=line.Split(' '); ! return part[2]; ! } ! ! public void RemoveMessageFromServer(string uidl) ! { ! int index=GetIndexFromUIDL(uidl); ! ! if(index>=0) ! { ! RemoveMessageFromServer(index); ! } ! else ! { ! throw new ConnectionException(uidl + " doesn't seem to exist on server? already deleted?"); ! } ! } ! ! public void RemoveMessageFromServer(int index) ! { ! SendCommand("DELE " + index); ! ! string str=ReceiveLine(); ! if(str[0]!='+') ! { ! throw new ConnectionException("Can't delete message " + index +" : " + str); ! } ! } ! /* Examples: C: LIST 2 S: +OK 2 200 ! * */ public int GetMessageSize(int number) ! { try ! { ! SendCommand("LIST " + number); ! ! string line=ReceiveLine(); ! if(line[0]=='+') ! { ! string[] lines=line.Split(new char[]{' '}); ! return int.Parse(lines[2]); } else ! { ! return -1; ! } } catch ! { ! return -1; ! } ! } ! ! ! public string RetrieveMessage(int number,MyOE.Utils.IProgressNotification notification) ! { ! try ! { ! SendCommand("RETR " + number); ! ! string line=ReceiveLine(); ! if(line[0]!='+') ! { ! throw new ConnectionException("Error in RETR: " + line); ! } if(notification!=null) ! { ! notification.CurrentValue+=line.Length+2; ! } ! ! string message=ReceiveLinesUpTo(".", notification); ! return message; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return RetrieveMessage(number, notification); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public POPConnection() ! { ! // ! // TODO: Add constructor logic here ! // ! DefaultTimeOut=30000; // default to 30 seconds timeout.. ! } ! ! public override void Connect() ! { ! // TODO: Add POPConnection.Connect implementation ! base.Connect (); ! string response=ReceiveLine(); ! if(response[0]!='+') ! { ! throw new ConnectionException("Error while connecting: " +response); ! } ! ! System.Diagnostics.Debug.WriteLine(Login); ! SendCommand("USER " + Login); ! response=ReceiveLine(); ! if(response[0]!='+'){ ! throw new ConnectionException("Error while login: " +response); ! } ! ! SendCommand("PASS " + Password); ! response=ReceiveLine(); ! ! ! if(response == null || response[0]!='+') ! { ! throw new ConnectionException("Error while login: " +response); ! } ! } ! ! public override void Disconnect() ! { ! SendCommand("QUIT"); ! // TODO: Add POPConnection.Disconnect implementation ! base.Disconnect (); ! } ! } ! } --- 1,275 ---- ! // MyOE.NET ! // see www.myoe.org for more info ! // © Quentin Pouplard and MyOE contributors. ! // This application is under the GPL licence. ! // ! // when you modify this file PLEASE add all your modification here ! // format: ! // date hour - name - description ! // ! // 08/02/2003 15:24 - Quentin Pouplard - Start Comments. ! ! using System; ! ! namespace MyOE.Net.POP ! { ! /// <summary> ! /// ! /// </summary> ! public class POPConnection : MyOE.Net.Connection ! { ! string _login=""; ! public string Login ! { ! get ! { ! return _login; ! } ! set ! { ! _login=value; ! } ! } ! ! string _password=""; ! public string Password ! { ! get ! { ! return _password; ! } ! set ! { ! _password=value; ! } ! } ! ! int _messagecount=-1; ! public int MessageCount{ ! get{ ! if(_messagecount==-1){ ! SendCommand("STAT"); ! string response=ReceiveLine(); ! ! // sometimes this fucking server imagine that a timeout is ! // really a good thing to do ! if (response[0] == '-') ! { ! throw new ApplicationException(response); ! } ! else ! { ! string[] resp = response.Split(' '); ! return int.Parse(resp[1]); ! } ! } ! return _messagecount; ! } ! } ! ! string []_messageidcache=null; ! public string[] RetrieveAllMessageID() ! { ! try ! { ! string []idarray=new string[MessageCount]; ! ! SendCommand("UIDL"); ! string response=ReceiveLine(); ! if(response[0]!='+') throw new ConnectionException("Error while retrieving message ID: " + response); ! ! int i=0; ! ! response=ReceiveLine(); ! while(response!=".") ! { ! idarray[i]=response.Split(' ')[1]; ! // System.Diagnostics.Debug.WriteLine(response); ! i++; ! response=ReceiveLine(); ! } ! ! _messageidcache=idarray; ! ! return idarray; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return RetrieveAllMessageID(); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public int GetIndexFromUIDL(string uidl) ! { ! try ! { ! if(_messageidcache==null) ! { ! RetrieveAllMessageID(); ! } ! for(int i=0; i<_messageidcache.Length; i++) ! { ! if(_messageidcache[i]==uidl) return i; ! } ! return -1; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return GetIndexFromUIDL(uidl); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public string RetrieveMessageID(int number){ ! SendCommand("UIDL " + number); ! ! string line=ReceiveLine(); ! if(line[0]!='+'){ ! throw new ConnectionException("Error in UIDL: " + line); ! } ! string[] part=line.Split(' '); ! return part[2]; ! } ! ! public void RemoveMessageFromServer(string uidl) ! { ! int index=GetIndexFromUIDL(uidl); ! ! if(index>=0) ! { ! RemoveMessageFromServer(index); ! } ! else ! { ! throw new ConnectionException(uidl + " doesn't seem to exist on server? already deleted?"); ! } ! } ! ! public void RemoveMessageFromServer(int index) ! { ! SendCommand("DELE " + index); ! ! string str=ReceiveLine(); ! if(str[0]!='+') ! { ! throw new ConnectionException("Can't delete message " + index +" : " + str); ! } ! } ! /* Examples: C: LIST 2 S: +OK 2 200 ! * */ public int GetMessageSize(int number) ! { try ! { ! SendCommand("LIST " + number); ! ! string line=ReceiveLine(); ! if(line[0]=='+') ! { ! string[] lines=line.Split(new char[]{' '}); ! return int.Parse(lines[2]); } else ! { ! return -1; ! } } catch ! { ! return -1; ! } ! } ! ! ! public string RetrieveMessage(int number,MyOE.Utils.IProgressNotification notification) ! { ! try ! { ! SendCommand("RETR " + number); ! ! string line=ReceiveLine(); ! if(line[0]!='+') ! { ! throw new ConnectionException("Error in RETR: " + line); ! } if(notification!=null) ! { ! notification.CurrentValue+=line.Length+2; ! } ! ! string message=ReceiveLinesUpTo(".", notification); ! return message; ! } ! catch(System.Net.Sockets.SocketException ex) ! { ! if(RetryConnect()) ! { ! return RetrieveMessage(number, notification); ! } ! else ! { ! throw ex; ! } ! } ! } ! ! public POPConnection() ! { ! // ! // TODO: Add constructor logic here ! // ! DefaultTimeOut=30000; // default to 30 seconds timeout.. ! } ! ! public override void Connect() ! { ! // TODO: Add POPConnection.Connect implementation ! base.Connect (); ! string response=ReceiveLine(); ! if(response[0]!='+') ! { ! throw new ConnectionException("Error while connecting: " +response); ! } ! ! System.Diagnostics.Debug.WriteLine(Login); ! SendCommand("USER " + Login); ! response=ReceiveLine(); ! if(response[0]!='+'){ ! throw new ConnectionException("Error while login: " +response); ! } ! ! SendCommand("PASS " + Password); ! response=ReceiveLine(); ! ! ! if(response == null || response[0]!='+') ! { ! throw new ConnectionException("Error while login: " +response); ! } ! } ! ! public override void Disconnect() ! { ! SendCommand("QUIT"); ! // TODO: Add POPConnection.Disconnect implementation ! base.Disconnect (); ! } ! } ! } Index: Connection.cs =================================================================== RCS file: /cvsroot/myoe/MyOE/Net/Connection.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Connection.cs 27 Apr 2004 13:57:44 -0000 1.5 --- Connection.cs 17 Aug 2004 14:46:00 -0000 1.6 *************** *** 1,411 **** ! // MyOE.NET ! // see www.myoe.org for more info ! // © Quentin Pouplard and MyOE contributors. ! // This application is under the GPL licence. ! // ! // when you modify this file PLEASE add all your modification here ! // format: ! // date hour - name - description ! // ! // 08/02/2003 15:24 - Quentin Pouplard - Start Comments. ! // 08/10/2003 12:08 - QP - Fixed AddCarriageReturn behaviour in SendCommand. ! ! // Inspired from ! // http://www.c2i.fr - rc...@c2... ! ! ! using System; ! using System.Diagnostics; ! using System.IO; ! using System.Net; ! using System.Net.Sockets; ! using System.Text; ! ! using Org.Mentalis.Network.ProxySocket; ! ! namespace MyOE.Net ! { ! public class ProxyServer ! { ! public string ProxyServerName; ! public int ProxyServerPort; ! public ProxyTypes ProxyType; ! public string ProxyUserName; ! public string ProxyUserPassword; ! } ! ! /// <summary> ! /// Summary description for my_protocole_socket. ! /// </summary> ! // public class my_protocole_socket ! ! public delegate void UploadDownloadProgression(int current, int size); ! ! ! public class ConnectionException : System.Exception ! { ! public ConnectionException(string error) : base(error) ! { ! ! } ! } ! ! public class Connection : IDisposable ! { ! protected event UploadDownloadProgression currentProgression; ! ! ProxySocket _ProxySocket; ! ProxyServer _proxy; ! NetworkStream _NetworkStream; ! StreamWriter _NetworkWriter; ! StreamReader _NetworkReader; ! public int DefaultTimeOut=30000; ! ! public ProxyServer Proxy ! { ! get ! { ! return _proxy; ! } ! set ! { ! _proxy=value; ! } ! } ! ! string _server; ! public string Server ! { ! get ! { ! return _server; ! } ! set ! { ! _server=value; ! } ! } ! ! int _port; ! public int Port ! { ! get ! { ! return _port; ! } ! set ! { ! _port=value; ! } ! } ! ! // Etat de la connection TCP ! public bool Connected ! { ! get ! { ! return _ProxySocket.Connected; ! } ! } ! ! ! public enum SocksTypes ! { ! /// <summary>No proxy server; the ProxySocket object behaves exactly like an ordinary Socket object.</summary> ! None, ! /// <summary>A SOCKS4[A] proxy server.</summary> ! Socks4, ! /// <summary>A SOCKS5 proxy server.</summary> ! Socks5 ! } ! ! // Connection ! public void Connect(string sServeur,int iPort) ! { ! Server=sServeur; ! Port=iPort; ! Connect(); ! } ! ! public virtual void Connect() ! { ! _connectionCount++; ! //ouverture du socket ! if(Proxy==null) ! { ! _ProxySocket = new ProxySocket(System.Net.Sockets.AddressFamily.InterNetwork, ! System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); ! _ProxySocket.ProxyEndPoint = null; ! // _ProxySocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1); ! ! } ! else ! { ! _ProxySocket = new ProxySocket(System.Net.Sockets.AddressFamily.InterNetwork, ! System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp, ! Proxy.ProxyUserName,Proxy.ProxyUserPassword); ! _ProxySocket.ProxyEndPoint = new IPEndPoint(Dns.Resolve(Proxy.ProxyServerName).AddressList[0], Proxy.ProxyServerPort); ! _ProxySocket.ProxyType = Proxy.ProxyType; ! } ! ! try ! { ! _ProxySocket.Connect(Server, Port); ! _ProxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DefaultTimeOut); ! _ProxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, DefaultTimeOut); ! _NetworkStream = new NetworkStream(_ProxySocket); ! ! _NetworkWriter = new StreamWriter( _NetworkStream, _Encoding); ! _NetworkWriter.AutoFlush = true; ! _NetworkReader = new StreamReader( _NetworkStream, _Encoding); ! // _NetworkReader=new StreamReader(); ! } ! catch(Exception e) ! { ! Debug.Write(e.ToString()); ! _ProxySocket.Close(); ! throw new Exception("Error during connection", e); ! } ! //obtention de la rponse du serveur ! // getResponse(); ! } ! ! /// <summary> ! /// Disconnect and dispose all disposable object. ! /// </summary> ! public virtual void Disconnect() ! { ! try ! { ! if(_NetworkReader!=null) ! _NetworkReader.Close(); ! ! if(_NetworkReader!=null) ! _NetworkWriter.Close(); ! ! if(_ProxySocket!=null) ! _ProxySocket.Close(); ! ! _ProxySocket=null; ! ! } ! catch ! { ! // Debugger.Break(); ! } ! } ! ! bool _AddCarriageReturn=true; ! /// <summary> ! /// Set to false to avoid the SendCommand to add carriage return at the ! /// end of the command. ! /// </summary> ! bool AddCarriageReturn ! { ! get ! { ! return _AddCarriageReturn; ! } ! set ! { ! _AddCarriageReturn=value; ! } ! } ! ! ! //public string _EncondingType="iso-8859-1"; ! private Encoding _Encoding = new MyOE.Utils.Trivial8BitEncoding(); ! ! /// <summary> ! /// The name of the encoding used for this connection. Default to simple 8bit encoding. ! /// </summary> ! public string EncodingType ! { ! get ! { ! //return _EncondingType; ! return _Encoding.HeaderName; ! }set ! { ! //_EncondingType=value; ! _Encoding = Encoding.GetEncoding(value); ! } ! } ! ! ! public void SendCommand(string sCommand) ! { ! SendCommand(sCommand, null); ! } ! /// <summary> ! /// Send a command to a POP/IMAP/NNTP... ! /// the carriage return is added automatically, you can avoid this by setting AddCarriage to false ! /// </summary> ! /// <param name="sCommand"></param> ! /// <returns></returns> ! public void SendCommand(string sCommand, MyOE.Utils.IProgressNotification notification) ! { ! try ! { ! if(_NetworkReader==null) ! { ! Debug.WriteLine("Not connected!!!"); ! return; ! } ! ! int NetworkStep=512; ! ! for(int i=0; i<sCommand.Length; i+=NetworkStep) ! { if(notification!=null) ! { ! notification.CurrentValue+=Math.Min(sCommand.Length - i, NetworkStep); ! } ! // Debug.WriteLine(sCommand.Substring(i, Math.Min(sCommand.Length - i, 50))); ! ! ! // fix buggy server? if(i+50>=sCommand.Length && AddCarriageReturn) ! { ! _NetworkWriter.Write(sCommand.Substring(i, Math.Min(sCommand.Length - i, NetworkStep)) + "\r\n"); } else ! { ! _NetworkWriter.Write(sCommand.Substring(i, Math.Min(sCommand.Length - i, NetworkStep))); ! } ! ! ! if(currentProgression!=null) ! currentProgression(i, sCommand.Length); ! } ! // if(AddCarriageReturn) ! // _NetworkWriter.Write("\r\n"); ! ! if(currentProgression!=null) ! currentProgression(sCommand.Length, sCommand.Length); ! } ! catch(Exception e) ! { ! Debug.WriteLine(e.ToString()); ! Trace.WriteLine("... error in SendCommand"); ! } ! } ! ! /// <summary> ! /// Receive all the line (delimited with \n) of this connection ! /// until ".\r\n" or ".\n" is reached. ! /// </summary> ! /// <returns></returns> ! public string ReceiveLines() ! { ! return ReceiveLinesUpTo(".", null); ! } ! ! int _maxRetryCount=3; ! /// <summary> ! /// The number of retry allowed by this connection, not all protocol support retry ! /// at worst, no retry will be done, it's always safe to set this parameter (but may ! /// produce no effect) ! /// set it to -1 to perform infinite retry. ! /// </summary> ! public int MaxRetryCount ! { ! get ! { ! return _maxRetryCount; ! }set ! { ! _maxRetryCount=value; ! } ! } ! ! int _retryCount=0; ! /// <summary> ! /// The number of actual retry performed on this connection ! /// See MaxRetryCount and RetryConnect for more informations. ! /// </summary> ! public int RetryCount ! { ! get ! { ! return _retryCount; ! } ! } ! ! /// <summary> ! /// Try to reconnect (if connection was a problem) ! /// Call Disconnect(), Connect() ! /// </summary> ! /// <returns>true if reconnection was succesful, false if not, or if retry count exceed</returns> ! public bool RetryConnect() ! { ! if(RetryCount<MaxRetryCount || MaxRetryCount==-1) ! { ! _retryCount++; ! try ! { ! Disconnect(); ! } ! catch{} ! ! try ! { ! Connect(); ! } ! catch ! { ! return false; ! } ! return true; ! } ! return false; ! } ! ! public string ReceiveLinesUpTo(string upto, MyOE.Utils.IProgressNotification progress) ! { ! string line = _NetworkReader.ReadLine(); ! ! if(progress!=null) ! progress.CurrentValue+=line.Length + 2; ! ! StringBuilder builder=new StringBuilder(); ! ! while(line!=upto) ! { ! // Debug.WriteLine(line); ! builder.Append(line); ! builder.Append("\r\n"); ! line=_NetworkReader.ReadLine(); ! if(progress!=null) ! progress.CurrentValue+=line.Length + 2; ! } ! return builder.ToString(); ! } ! ! public string ReceiveLine() ! { ! string line = _NetworkReader.ReadLine(); ! ! return line; ! } ! ! public static int _connectionCount=0; ! ! ~Connection() ! { ! if(_ProxySocket!=null) ! Disconnect(); ! } ! #region IDisposable Members ! ! public void Dispose() ! { ! _connectionCount--; ! if(_ProxySocket!=null) ! Disconnect(); ! } ! ! #endregion ! } ! } --- 1,411 ---- ! // MyOE.NET ! // see www.myoe.org for more info ! // © Quentin Pouplard and MyOE contributors. ! // This application is under the GPL licence. ! // ! // when you modify this file PLEASE add all your modification here ! // format: ! // date hour - name - description ! // ! // 08/02/2003 15:24 - Quentin Pouplard - Start Comments. ! // 08/10/2003 12:08 - QP - Fixed AddCarriageReturn behaviour in SendCommand. ! ! // Inspired from ! // http://www.c2i.fr - rc...@c2... ! ! ! using System; ! using System.Diagnostics; ! using System.IO; ! using System.Net; ! using System.Net.Sockets; ! using System.Text; ! ! using Org.Mentalis.Network.ProxySocket; ! ! namespace MyOE.Net ! { ! public class ProxyServer ! { ! public string ProxyServerName; ! public int ProxyServerPort; ! public ProxyTypes ProxyType; ! public string ProxyUserName; ! public string ProxyUserPassword; ! } ! ! /// <summary> ! /// Summary description for my_protocole_socket. ! /// </summary> ! // public class my_protocole_socket ! ! public delegate void UploadDownloadProgression(int current, int size); ! ! ! public class ConnectionException : System.Exception ! { ! public ConnectionException(string error) : base(error) ! { ! ! } ! } ! ! public class Connection : IDisposable ! { ! protected event UploadDownloadProgression currentProgression; ! ! ProxySocket _ProxySocket; ! ProxyServer _proxy; ! NetworkStream _NetworkStream; ! StreamWriter _NetworkWriter; ! StreamReader _NetworkReader; ! public int DefaultTimeOut=60000; ! ! public ProxyServer Proxy ! { ! get ! { ! return _proxy; ! } ! set ! { ! _proxy=value; ! } ! } ! ! string _server; ! public string Server ! { ! get ! { ! return _server; ! } ! set ! { ! _server=value; ! } ! } ! ! int _port; ! public int Port ! { ! get ! { ! return _port; ! } ! set ! { ! _port=value; ! } ! } ! ! // Etat de la connection TCP ! public bool Connected ! { ! get ! { ! return _ProxySocket.Connected; ! } ! } ! ! ! public enum SocksTypes ! { ! /// <summary>No proxy server; the ProxySocket object behaves exactly like an ordinary Socket object.</summary> ! None, ! /// <summary>A SOCKS4[A] proxy server.</summary> ! Socks4, ! /// <summary>A SOCKS5 proxy server.</summary> ! Socks5 ! } ! ! // Connection ! public void Connect(string sServeur,int iPort) ! { ! Server=sServeur; ! Port=iPort; ! Connect(); ! } ! ! public virtual void Connect() ! { ! _connectionCount++; ! //ouverture du socket ! if(Proxy==null) ! { ! _ProxySocket = new ProxySocket(System.Net.Sockets.AddressFamily.InterNetwork, ! System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP); ! _ProxySocket.ProxyEndPoint = null; ! // _ProxySocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.NoDelay, 1); ! ! } ! else ! { ! _ProxySocket = new ProxySocket(System.Net.Sockets.AddressFamily.InterNetwork, ! System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp, ! Proxy.ProxyUserName,Proxy.ProxyUserPassword); ! _ProxySocket.ProxyEndPoint = new IPEndPoint(Dns.Resolve(Proxy.ProxyServerName).AddressList[0], Proxy.ProxyServerPort); ! _ProxySocket.ProxyType = Proxy.ProxyType; ! } ! ! try ! { ! _ProxySocket.Connect(Server, Port); ! _ProxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, DefaultTimeOut); ! _ProxySocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, DefaultTimeOut); ! _NetworkStream = new NetworkStream(_ProxySocket); ! ! _NetworkWriter = new StreamWriter( _NetworkStream, _Encoding); ! _NetworkWriter.AutoFlush = true; ! _NetworkReader = new StreamReader( _NetworkStream, _Encoding); ! // _NetworkReader=new StreamReader(); ! } ! catch(Exception e) ! { ! Debug.Write(e.ToString()); ! _ProxySocket.Close(); ! throw new Exception("Error during connection", e); ! } ! //obtention de la rponse du serveur ! // getResponse(); ! } ! ! /// <summary> ! /// Disconnect and dispose all disposable object. ! /// </summary> ! public virtual void Disconnect() ! { ! try ! { ! if(_NetworkReader!=null) ! _NetworkReader.Close(); ! ! if(_NetworkReader!=null) ! _NetworkWriter.Close(); ! ! if(_ProxySocket!=null) ! _ProxySocket.Close(); ! ! _ProxySocket=null; ! ! } ! catch ! { ! // Debugger.Break(); ! } ! } ! ! bool _AddCarriageReturn=true; ! /// <summary> ! /// Set to false to avoid the SendCommand to add carriage return at the ! /// end of the command. ! /// </summary> ! bool AddCarriageReturn ! { ! get ! { ! return _AddCarriageReturn; ! } ! set ! { ! _AddCarriageReturn=value; ! } ! } ! ! ! //public string _EncondingType="iso-8859-1"; ! private Encoding _Encoding = new MyOE.Utils.Trivial8BitEncoding(); ! ! /// <summary> ! /// The name of the encoding used for this connection. Default to simple 8bit encoding. ! /// </summary> ! public string EncodingType ! { ! get ! { ! //return _EncondingType; ! return _Encoding.HeaderName; ! }set ! { ! //_EncondingType=value; ! _Encoding = Encoding.GetEncoding(value); ! } ! } ! ! ! public void SendCommand(string sCommand) ! { ! SendCommand(sCommand, null); ! } ! /// <summary> ! /// Send a command to a POP/IMAP/NNTP... ! /// the carriage return is added automatically, you can avoid this by setting AddCarriage to false ! /// </summary> ! /// <param name="sCommand"></param> ! /// <returns></returns> ! public void SendCommand(string sCommand, MyOE.Utils.IProgressNotification notification) ! { ! try ! { ! if(_NetworkReader==null) ! { ! Debug.WriteLine("Not connected!!!"); ! return; ! } ! ! int NetworkStep=512; ! ! for(int i=0; i<sCommand.Length; i+=NetworkStep) ! { if(notification!=null) ! { ! notification.CurrentValue+=Math.Min(sCommand.Length - i, NetworkStep); ! } ! // Debug.WriteLine(sCommand.Substring(i, Math.Min(sCommand.Length - i, 50))); ! ! ! // fix buggy server? if(i+50>=sCommand.Length && AddCarriageReturn) ! { ! _NetworkWriter.Write(sCommand.Substring(i, Math.Min(sCommand.Length - i, NetworkStep)) + "\r\n"); } else ! { ! _NetworkWriter.Write(sCommand.Substring(i, Math.Min(sCommand.Length - i, NetworkStep))); ! } ! ! ! if(currentProgression!=null) ! currentProgression(i, sCommand.Length); ! } ! // if(AddCarriageReturn) ! // _NetworkWriter.Write("\r\n"); ! ! if(currentProgression!=null) ! currentProgression(sCommand.Length, sCommand.Length); ! } ! catch(Exception e) ! { ! Debug.WriteLine(e.ToString()); ! Trace.WriteLine("... error in SendCommand"); ! } ! } ! ! /// <summary> ! /// Receive all the line (delimited with \n) of this connection ! /// until ".\r\n" or ".\n" is reached. ! /// </summary> ! /// <returns></returns> ! public string ReceiveLines() ! { ! return ReceiveLinesUpTo(".", null); ! } ! ! int _maxRetryCount=3; ! /// <summary> ! /// The number of retry allowed by this connection, not all protocol support retry ! /// at worst, no retry will be done, it's always safe to set this parameter (but may ! /// produce no effect) ! /// set it to -1 to perform infinite retry. ! /// </summary> ! public int MaxRetryCount ! { ! get ! { ! return _maxRetryCount; ! }set ! { ! _maxRetryCount=value; ! } ! } ! ! int _retryCount=0; ! /// <summary> ! /// The number of actual retry performed on this connection ! /// See MaxRetryCount and RetryConnect for more informations. ! /// </summary> ! public int RetryCount ! { ! get ! { ! return _retryCount; ! } ! } ! ! /// <summary> ! /// Try to reconnect (if connection was a problem) ! /// Call Disconnect(), Connect() ! /// </summary> ! /// <returns>true if reconnection was succesful, false if not, or if retry count exceed</returns> ! public bool RetryConnect() ! { ! if(RetryCount<MaxRetryCount || MaxRetryCount==-1) ! { ! _retryCount++; ! try ! { ! Disconnect(); ! } ! catch{} ! ! try ! { ! Connect(); ! } ! catch ! { ! return false; ! } ! return true; ! } ! return false; ! } ! ! public string ReceiveLinesUpTo(string upto, MyOE.Utils.IProgressNotification progress) ! { ! string line = _NetworkReader.ReadLine(); ! ! if(progress!=null) ! progress.CurrentValue+=line.Length + 2; ! ! StringBuilder builder=new StringBuilder(); ! ! while(line!=upto) ! { ! // Debug.WriteLine(line); ! builder.Append(line); ! builder.Append("\r\n"); ! line=_NetworkReader.ReadLine(); ! if(progress!=null) ! progress.CurrentValue+=line.Length + 2; ! } ! return builder.ToString(); ! } ! ! public string ReceiveLine() ! { ! string line = _NetworkReader.ReadLine(); ! ! return line; ! } ! ! public static int _connectionCount=0; ! ! ~Connection() ! { ! if(_ProxySocket!=null) ! Disconnect(); ! } ! #region IDisposable Members ! ! public void Dispose() ! { ! _connectionCount--; ! if(_ProxySocket!=null) ! Disconnect(); ! } ! ! #endregion ! } ! } |