<commit_before>/**
 * $Id$
 * $URL$
 * $Rev$
 * $Author$
 * $Date$
 *
 * Copyright (c) 2003-2004 Mirco 'meebey' Bauer <<EMAIL>> <http://www.meebey.net>
 * 
 * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Reflection;

namespace Meebey.SmartIrc4net
{
    /// <summary>
    ///
    /// </summary>
    public class IrcConnection
    {
        private string          _VersionNumber;
        private string          _VersionString;
        private string[]        _AddressList = {"localhost"};
        private int             _CurrentAddress = 0;
        private int             _Port = 6667;
        private StreamReader    _Reader;
        private StreamWriter    _Writer;
        private ReadThread      _ReadThread;
        private WriteThread     _WriteThread;
        private IrcTcpClient    _TcpClient;
        private Hashtable       _SendBuffer = Hashtable.Synchronized(new Hashtable());
        private int             _SendDelay = 200;
        private bool            _IsRegistered = false;
        private bool            _IsConnected  = false;
        private bool            _IsConnectionError = false;
        private int             _ConnectTries = 0;
        private bool            _AutoRetry     = false;
        private bool            _AutoReconnect = false;
        private Encoding        _Encoding = Encoding.GetEncoding("ISO-8859-1");
        //private Encoding        _Encoding = Encoding.ASCII;
        //private Encoding        _Encoding = Encoding.GetEncoding(1252);
        //private Encoding        _Encoding = Encoding.UTF8;

        /// <event cref="OnReadLine">
        /// Raised when a \r\n terminated line is read from the socket
        /// </event>
        public event ReadLineEventHandler   OnReadLine;
        /// <event cref="OnWriteLine">
        /// Raised when a \r\n terminated line is written to the socket
        /// </event>
        public event WriteLineEventHandler  OnWriteLine;
        /// <event cref="OnConnect">
        /// Raised before the connect attempt
        /// </event>
        public event EventHandler           OnConnecting;
        /// <event cref="OnConnect">
        /// Raised on successful connect
        /// </event>
        public event EventHandler           OnConnected;
        /// <event cref="OnConnect">
        /// Raised before the connection is closed
        /// </event>
        public event EventHandler           OnDisconnecting;
        /// <event cref="OnConnect">
        /// Raised when the connection is closed
        /// </event>
        public event EventHandler           OnDisconnected;
        
        /// <summary>
        /// When a connection error is detected this property will return true
        /// </summary>
        /// <remarks>
        /// Thread-safe
        /// </remarks
        protected bool IsConnectionError
        {
            get {
                lock (this) {
                    return _IsConnectionError;
                }
            }
            set {
                lock (this) {
                    _IsConnectionError = value;
                }
            }
        }

        /// <summary>
        /// The current address of the connection
        /// </summary>
        public string Address
        {
            get {
                return _AddressList[_CurrentAddress];
            }
        }

        /// <summary>
        /// The address list of the connection
        /// </summary>
        public string[] AddressList
        {
            get {
                return _AddressList;
            }
        }

        /// <summary>
        /// Which port is used for the connection
        /// </summary>
        public int Port
        {
            get {
                return _Port;
            }
        }

        /// <summary>
        /// By default nothing is done when the library looses the connection
        /// to the server.
        /// Default: false
        /// </summary>
        /// <value>
        /// true, if the library should reconnect on lost connections
        /// false, if the library should not take care of it
        /// </value>
        public bool AutoReconnect
        {
            get {
                return _AutoReconnect;
            }
            set {
#if LOG4NET
                if (value == true) {
                    Logger.Connection.Info("AutoReconnect enabled");
                } else {
                    Logger.Connection.Info("AutoReconnect disabled");
                }
#endif
                _AutoReconnect = value;
            }
        }

        /// <summary>
        /// If the library should retry to connect when the connection fails.
        /// Default: false
        /// </summary>
        /// <value>
        /// true, if the library should retry to connect
        /// false, if the library should not retry
        /// </value>
        public bool AutoRetry
        {
            get {
                return _AutoRetry;
            }
            set {
#if LOG4NET
                if (value == true) {
                    Logger.Connection.Info("AutoRetry enabled");
                } else {
                    Logger.Connection.Info("AutoRetry disabled");
                }
#endif
                _AutoRetry = value;
            }
        }

        /// <summary>
        /// To prevent flooding the IRC server, it's required to delay each
        /// message, given in milliseconds.
        /// Default: 200
        /// </summary>
        public int SendDelay
        {
            get {
                return _SendDelay;
            }
            set {
                _SendDelay = value;
            }
        }

        /// <summary>
        /// On successful registration on the IRC network, this is set to true.
        /// </summary>
        public bool IsRegistered
        {
            get {
                return _IsRegistered;
            }
        }

        /// <summary>
        /// On successful connect to the IRC server, this is set to true.
        /// </summary>
        public bool IsConnected
        {
            get {
                return _IsConnected;
            }
        }

        /// <summary>
        /// The SmartIrc4net version number
        /// </summary>
        public string VersionNumber
        {
            get {
                return _VersionNumber;
            }
        }

        /// <summary>
        /// The full SmartIrc4net version
        /// </summary>
        public string VersionString
        {
            get {
                return _VersionString;
            }
        }

        /// <summary>
        /// Encoding which is used for reading and writing to the socket
        /// </summary>
        public Encoding Encoding
        {
            get {
                return _Encoding;
            }
            set {
                _Encoding = value;
            }
        }

        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
#if LOG4NET        
            Logger.Init();
#endif
            _SendBuffer[Priority.High]        = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Medium]      = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Low]         = Queue.Synchronized(new Queue());

            OnReadLine += new ReadLineEventHandler(_SimpleParser);

            _ReadThread  = new ReadThread(this);
            _WriteThread = new WriteThread(this);

            Assembly assm = Assembly.GetAssembly(this.GetType());
            AssemblyName assm_name = assm.GetName(false);

            AssemblyProductAttribute pr = (AssemblyProductAttribute)assm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            _VersionNumber = assm_name.Version.ToString();
            _VersionString = pr.Product+" "+_VersionNumber;
        }

        /// <overloads>this method has 2 overloads</overloads>
        /// <summary>
        /// Connects to the specified server and port, when the connection fails
        /// the next server in the list will be used.
        /// </summary>
        /// <param name="addresslist">List of servers to connect to</pararm>
        /// <param name="port">Portnumber to connect to</pararm>
        /// <exception cref="CouldNotConnectException">The connection failed</exceptio>
        /// <exception cref="AlreadyConnectedException">If there is already an active connection</exceptio>
        public void Connect(string[] addresslist, int port)
        {
            if (_IsConnected) {
                throw new AlreadyConnectedException("Already connected to: "+Address+":"+Port);
            }

#if LOG4NET
            Logger.Connection.Info("connecting...");
#endif
            _ConnectTries++;
            _AddressList = (string[])addresslist.Clone();
            _Port = port;

            if (OnConnecting != null) {
                OnConnecting(this, EventArgs.Empty);
            }
            try {
                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
                _TcpClient = new IrcTcpClient();
                _TcpClient.NoDelay = true;
                // set timeout to 6 minutes, after this the connection will be aborted
                _TcpClient.ReceiveTimeout = 360000;
                _TcpClient.SendTimeout = 360000;
                _TcpClient.Connect(ip, port);
                if (OnConnected != null) {
                    OnConnected(this, EventArgs.Empty);
                }

                _Reader = new StreamReader(_TcpClient.GetStream(), Encoding);
                _Writer = new StreamWriter(_TcpClient.GetStream(), Encoding);

                // Connection was succeful, reseting the connect counter
                _ConnectTries = 0;

                // updating the connection error state, so connecting is possible again
                IsConnectionError = false;
                _IsConnected = true;
#if LOG4NET
                Logger.Connection.Info("connected");
#endif

                // lets power up our threads
                _ReadThread.Start();
                _WriteThread.Start();
            } catch (Exception e) {
                if (_Reader != null) {
                    _Reader.Close();
                }
                if (_Writer != null) {<commit_msg>- added IrcConnection.SocketSendTimeout and IrcConnection.SocketReceiveTimeout<commit_after>/**
 * $Id$
 * $URL$
 * $Rev$
 * $Author$
 * $Date$
 *
 * Copyright (c) 2003-2004 Mirco 'meebey' Bauer <<EMAIL>> <http://www.meebey.net>
 * 
 * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt>
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Threading;
using System.Reflection;

namespace Meebey.SmartIrc4net
{
    /// <summary>
    ///
    /// </summary>
    public class IrcConnection
    {
        private string          _VersionNumber;
        private string          _VersionString;
        private string[]        _AddressList = {"localhost"};
        private int             _CurrentAddress = 0;
        private int             _Port = 6667;
        private StreamReader    _Reader;
        private StreamWriter    _Writer;
        private ReadThread      _ReadThread;
        private WriteThread     _WriteThread;
        private IrcTcpClient    _TcpClient;
        private Hashtable       _SendBuffer = Hashtable.Synchronized(new Hashtable());
        private int             _SendDelay = 200;
        private bool            _IsRegistered = false;
        private bool            _IsConnected  = false;
        private bool            _IsConnectionError = false;
        private int             _ConnectTries = 0;
        private bool            _AutoRetry     = false;
        private bool            _AutoReconnect = false;
        private Encoding        _Encoding = Encoding.GetEncoding("ISO-8859-1");
        //private Encoding        _Encoding = Encoding.ASCII;
        //private Encoding        _Encoding = Encoding.GetEncoding(1252);
        //private Encoding        _Encoding = Encoding.UTF8;
        private int             _SocketReceiveTimeout  = 600;
        private int             _SocketSendTimeout = 600;

        /// <event cref="OnReadLine">
        /// Raised when a \r\n terminated line is read from the socket
        /// </event>
        public event ReadLineEventHandler   OnReadLine;
        /// <event cref="OnWriteLine">
        /// Raised when a \r\n terminated line is written to the socket
        /// </event>
        public event WriteLineEventHandler  OnWriteLine;
        /// <event cref="OnConnect">
        /// Raised before the connect attempt
        /// </event>
        public event EventHandler           OnConnecting;
        /// <event cref="OnConnect">
        /// Raised on successful connect
        /// </event>
        public event EventHandler           OnConnected;
        /// <event cref="OnConnect">
        /// Raised before the connection is closed
        /// </event>
        public event EventHandler           OnDisconnecting;
        /// <event cref="OnConnect">
        /// Raised when the connection is closed
        /// </event>
        public event EventHandler           OnDisconnected;
        
        /// <summary>
        /// When a connection error is detected this property will return true
        /// </summary>
        /// <remarks>
        /// Thread-safe
        /// </remarks
        protected bool IsConnectionError
        {
            get {
                lock (this) {
                    return _IsConnectionError;
                }
            }
            set {
                lock (this) {
                    _IsConnectionError = value;
                }
            }
        }

        /// <summary>
        /// The current address of the connection
        /// </summary>
        public string Address
        {
            get {
                return _AddressList[_CurrentAddress];
            }
        }

        /// <summary>
        /// The address list of the connection
        /// </summary>
        public string[] AddressList
        {
            get {
                return _AddressList;
            }
        }

        /// <summary>
        /// Which port is used for the connection
        /// </summary>
        public int Port
        {
            get {
                return _Port;
            }
        }

        /// <summary>
        /// By default nothing is done when the library looses the connection
        /// to the server.
        /// Default: false
        /// </summary>
        /// <value>
        /// true, if the library should reconnect on lost connections
        /// false, if the library should not take care of it
        /// </value>
        public bool AutoReconnect
        {
            get {
                return _AutoReconnect;
            }
            set {
#if LOG4NET
                if (value == true) {
                    Logger.Connection.Info("AutoReconnect enabled");
                } else {
                    Logger.Connection.Info("AutoReconnect disabled");
                }
#endif
                _AutoReconnect = value;
            }
        }

        /// <summary>
        /// If the library should retry to connect when the connection fails.
        /// Default: false
        /// </summary>
        /// <value>
        /// true, if the library should retry to connect
        /// false, if the library should not retry
        /// </value>
        public bool AutoRetry
        {
            get {
                return _AutoRetry;
            }
            set {
#if LOG4NET
                if (value == true) {
                    Logger.Connection.Info("AutoRetry enabled");
                } else {
                    Logger.Connection.Info("AutoRetry disabled");
                }
#endif
                _AutoRetry = value;
            }
        }

        /// <summary>
        /// To prevent flooding the IRC server, it's required to delay each
        /// message, given in milliseconds.
        /// Default: 200
        /// </summary>
        public int SendDelay
        {
            get {
                return _SendDelay;
            }
            set {
                _SendDelay = value;
            }
        }

        /// <summary>
        /// On successful registration on the IRC network, this is set to true.
        /// </summary>
        public bool IsRegistered
        {
            get {
                return _IsRegistered;
            }
        }

        /// <summary>
        /// On successful connect to the IRC server, this is set to true.
        /// </summary>
        public bool IsConnected
        {
            get {
                return _IsConnected;
            }
        }

        /// <summary>
        /// The SmartIrc4net version number
        /// </summary>
        public string VersionNumber
        {
            get {
                return _VersionNumber;
            }
        }

        /// <summary>
        /// The full SmartIrc4net version
        /// </summary>
        public string VersionString
        {
            get {
                return _VersionString;
            }
        }

        /// <summary>
        /// Encoding which is used for reading and writing to the socket
        /// Default: ISO-8859-1
        /// </summary>
        public Encoding Encoding
        {
            get {
                return _Encoding;
            }
            set {
                _Encoding = value;
            }
        }

        /// <summary>
        /// Timeout in seconds for receiving data from the socket
        /// Default: 600
        /// </summary>
        public int SocketReceiveTimeout
        {
            get {
                return _SocketReceiveTimeout;
            }
            set {
                _SocketReceiveTimeout = value*1000;
            }
        }
        
        /// <summary>
        /// Timeout in seconds for sending data to the socket
        /// Default: 600
        /// </summary>
        public int SocketSendTimeout
        {
            get {
                return _SocketSendTimeout;
            }
            set {
                _SocketSendTimeout = value*1000;
            }
        }
        
        /// <summary>
        /// Initializes the message queues, read and write thread
        /// </summary>
        public IrcConnection()
        {
#if LOG4NET        
            Logger.Init();
#endif
            _SendBuffer[Priority.High]        = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.AboveMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Medium]      = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.BelowMedium] = Queue.Synchronized(new Queue());
            _SendBuffer[Priority.Low]         = Queue.Synchronized(new Queue());

            OnReadLine += new ReadLineEventHandler(_SimpleParser);

            _ReadThread  = new ReadThread(this);
            _WriteThread = new WriteThread(this);

            Assembly assm = Assembly.GetAssembly(this.GetType());
            AssemblyName assm_name = assm.GetName(false);

            AssemblyProductAttribute pr = (AssemblyProductAttribute)assm.GetCustomAttributes(typeof(AssemblyProductAttribute), false)[0];

            _VersionNumber = assm_name.Version.ToString();
            _VersionString = pr.Product+" "+_VersionNumber;
        }

        /// <overloads>this method has 2 overloads</overloads>
        /// <summary>
        /// Connects to the specified server and port, when the connection fails
        /// the next server in the list will be used.
        /// </summary>
        /// <param name="addresslist">List of servers to connect to</pararm>
        /// <param name="port">Portnumber to connect to</pararm>
        /// <exception cref="CouldNotConnectException">The connection failed</exceptio>
        /// <exception cref="AlreadyConnectedException">If there is already an active connection</exceptio>
        public void Connect(string[] addresslist, int port)
        {
            if (_IsConnected) {
                throw new AlreadyConnectedException("Already connected to: "+Address+":"+Port);
            }

#if LOG4NET
            Logger.Connection.Info("connecting...");
#endif
            _ConnectTries++;
            _AddressList = (string[])addresslist.Clone();
            _Port = port;

            if (OnConnecting != null) {
                OnConnecting(this, EventArgs.Empty);
            }
            try {
                System.Net.IPAddress ip = System.Net.Dns.Resolve(Address).AddressList[0];
                _TcpClient = new IrcTcpClient();
                _TcpClient.NoDelay = true;
                // set timeout to 6 minutes, after this the connection will be aborted
                _TcpClient.ReceiveTimeout = _SocketReceiveTimeout;
                _TcpClient.SendTimeout = _SocketSendTimeout;
                _TcpClient.Connect(ip, port);
                if (OnConnected != null) {
                    OnConnected(this, EventArgs.Empty);
                }

                _Reader = new StreamReader(_TcpClient.GetStream(), Encoding);
                _Writer = new StreamWriter(_TcpClient.GetStream(), Encoding);

                // Connection was succeful, reseting the connect counter
                _ConnectTries = 0;

                // updating the connection error state, so connecting is possible again
                IsConnectionError = false;
                _IsConnected = true;
#if LOG4NET
                Logger.Connection.Info("connected");
#endif

                // lets power up our threads
                _ReadThread.Start();
                _WriteThread.Start();
            } catch (Exception e) {
                if (_Reader != null) {
                    _Reader.Close();
                }
                if (_Writer != null) {
{'fraction_non_alphanumeric': 0.09168533626410788, 'fraction_numerical': 0.006551971932197658, 'mean_word_length': 1.407448865370917, 'pattern_counts': {'":': 2, '<': 131, '<?xml version=': 0, '>': 129, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6627082', 'n_tokens_mistral': 5927, 'n_tokens_neox': 5630, 'n_words': 1728}