diff --git a/Core.Test/Helper.cs b/Core.Test/Helper.cs index bc37ac5..471f52f 100644 --- a/Core.Test/Helper.cs +++ b/Core.Test/Helper.cs @@ -21,8 +21,6 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -using System; - using NUnit.Framework; namespace XG.Core.Test @@ -33,8 +31,8 @@ public class Helper [Test] public void ShrinkFileName() { - string fileName = "This_(is).-an_Evil)(File-_-name_[Test].txt"; - Int64 fileSize = 440044; + const string fileName = "This_(is).-an_Evil)(File-_-name_[Test].txt"; + const long fileSize = 440044; string result = Core.Helper.ShrinkFileName(fileName, fileSize); Assert.AreEqual("thisisanevilfilenametesttxt.440044/", result); diff --git a/Core.Test/Object.cs b/Core.Test/Object.cs index dfda5ad..c4f2067 100644 --- a/Core.Test/Object.cs +++ b/Core.Test/Object.cs @@ -35,7 +35,7 @@ public class Object [Test] public void Test() { - Core.Object obj = new Core.Object(); + var obj = new Core.Object(); obj.Changed += delegate { _modified = true; }; AssertModified(obj, false); @@ -48,8 +48,7 @@ public void Test() obj.Connected = true; AssertModified(obj, true); - Core.Object parent = new Core.Object(); - parent.Guid = Guid.NewGuid(); + var parent = new Core.Object {Guid = Guid.NewGuid()}; Assert.AreEqual(Guid.Empty, obj.ParentGuid); obj.Parent = parent; diff --git a/Core.Test/Objects.cs b/Core.Test/Objects.cs index 57b5ccd..e27dfd3 100644 --- a/Core.Test/Objects.cs +++ b/Core.Test/Objects.cs @@ -35,13 +35,13 @@ public class Objects [Test] public void Test() { - Core.Objects parent = new Core.Objects(); + var parent = new Core.Objects(); parent.Added += delegate { _childAdded = true; }; parent.Guid = Guid.NewGuid(); AssertChildAdded(false); - Core.Object obj = new Core.Object(); + var obj = new Core.Object(); Assert.AreEqual(Guid.Empty, obj.ParentGuid); parent.Add(obj); diff --git a/Core/AObject.cs b/Core/AObject.cs index 3d4e5ad..dc97249 100644 --- a/Core/AObject.cs +++ b/Core/AObject.cs @@ -92,14 +92,7 @@ public virtual AObject Parent if (_parent != value) { _parent = value; - if (_parent != null) - { - _parentGuid = _parent.Guid; - } - else - { - _parentGuid = Guid.Empty; - } + _parentGuid = _parent != null ? _parent.Guid : Guid.Empty; } } } @@ -172,7 +165,6 @@ public virtual bool Enabled public DateTime EnabledTime { get { return _enabledTime; } - private set { throw new NotSupportedException("You can not set this Property."); } } #endregion diff --git a/Core/AObjects.cs b/Core/AObjects.cs index 4ae6222..4e5b9af 100644 --- a/Core/AObjects.cs +++ b/Core/AObjects.cs @@ -67,14 +67,7 @@ protected void FireRemoved(AObjects aObjects, AObject aObject) protected object ObjectLock { - get - { - if (_objectLock == null) - { - _objectLock = new object(); - } - return _objectLock; - } + get { return _objectLock ?? (_objectLock = new object()); } } readonly List _children; @@ -105,10 +98,9 @@ protected bool Add(AObject aObject) aObject.EnabledChanged += FireEnabledChanged; aObject.Changed += FireChanged; - if (aObject is AObjects) + var aObjects = aObject as AObjects; + if (aObjects != null) { - AObjects aObjects = (AObjects) aObject; - aObjects.Added += FireAdded; aObjects.Removed += FireRemoved; } @@ -137,10 +129,9 @@ protected bool Remove(AObject aObject) aObject.EnabledChanged -= FireEnabledChanged; aObject.Changed -= FireChanged; - if (aObject is AObjects) + var aObjects = aObject as AObjects; + if (aObjects != null) { - AObjects aObjects = (AObjects) aObject; - aObjects.Added -= FireAdded; aObjects.Removed -= FireRemoved; } @@ -161,10 +152,9 @@ public void AttachChildEvents() tObject.EnabledChanged += FireEnabledChanged; tObject.Changed += FireChanged; - if (tObject is AObjects) + var tObjects = tObject as AObjects; + if (tObjects != null) { - AObjects tObjects = (AObjects) tObject; - tObjects.Added += FireAdded; tObjects.Removed += FireRemoved; @@ -192,10 +182,9 @@ public virtual AObject WithGuid(Guid aGuid) tObjectReturn = tObject; break; } - else if (tObject is AObjects) + var tObjects = tObject as AObjects; + if (tObjects != null) { - AObjects tObjects = (AObjects) tObject; - tObjectReturn = tObjects.WithGuid(aGuid); if (tObjectReturn != null) { @@ -208,13 +197,14 @@ public virtual AObject WithGuid(Guid aGuid) public virtual AObject Named(string aName) { - AObject tObject = null; try { - tObject = All.First(obj => obj.Name.Trim().ToLower() == aName.Trim().ToLower()); + return All.First(obj => obj.Name.Trim().ToLower() == aName.Trim().ToLower()); + } + catch (Exception) + { + return null; } - catch {} - return tObject; } public AObject Next(AObject aObject) diff --git a/Core/Bot.cs b/Core/Bot.cs index 4613877..bcf0f7d 100644 --- a/Core/Bot.cs +++ b/Core/Bot.cs @@ -85,7 +85,7 @@ public States State [NonSerialized] IPAddress _ip = IPAddress.None; - public IPAddress IP + public IPAddress Ip { get { return _ip; } set { SetProperty(ref _ip, value); } @@ -208,7 +208,7 @@ public double Speed public IEnumerable Packets { - get { return base.All.Cast(); } + get { return All.Cast(); } } public Packet Packet(int aId) @@ -217,18 +217,20 @@ public Packet Packet(int aId) { return Packets.First(pack => pack.Id == aId); } - catch {} - return null; + catch (Exception) + { + return null; + } } public void AddPacket(Packet aPacket) { - base.Add(aPacket); + Add(aPacket); } public void RemovePacket(Packet aPacket) { - base.Remove(aPacket); + Remove(aPacket); } public Packet OldestActivePacket() diff --git a/Core/Channel.cs b/Core/Channel.cs index dd49ccf..f72b3fd 100644 --- a/Core/Channel.cs +++ b/Core/Channel.cs @@ -45,7 +45,7 @@ public override bool Connected { foreach (AObject obj in All) { - obj.Connected = value; + obj.Connected = false; } } base.Connected = value; @@ -74,22 +74,22 @@ public int ErrorCode public IEnumerable Bots { - get { return base.All.Cast(); } + get { return All.Cast(); } } public Bot Bot(string aName) { - return (Bot) base.Named(aName); + return base.Named(aName) as Bot; } public void AddBot(Bot aBot) { - base.Add(aBot); + Add(aBot); } public void RemoveBot(Bot aBot) { - base.Remove(aBot); + Remove(aBot); } #endregion diff --git a/Core/Extensions.cs b/Core/Extensions.cs index dc9279b..54c9cd0 100644 --- a/Core/Extensions.cs +++ b/Core/Extensions.cs @@ -30,7 +30,7 @@ public static class Extensions { public static string ToAscii(this string aString) { - StringBuilder output = new StringBuilder(string.Empty); + var output = new StringBuilder(string.Empty); if (!string.IsNullOrEmpty(aString)) { for (int i = 0; i < aString.Length; i++) @@ -43,16 +43,15 @@ public static string ToAscii(this string aString) public static Int64 ToTimestamp(this DateTime aDate) { - DateTime date = new DateTime(1970, 1, 1); - TimeSpan ts = new TimeSpan(aDate.Ticks - date.Ticks); + var date = new DateTime(1970, 1, 1); + var ts = new TimeSpan(aDate.Ticks - date.Ticks); return (Convert.ToInt64(ts.TotalSeconds)); } public static DateTime ToDate(this Int64 aTimestamp) { - DateTime date = new DateTime(1970, 1, 1); - date.AddSeconds(aTimestamp); - return date; + var date = new DateTime(1970, 1, 1); + return date.AddSeconds(aTimestamp); } public static bool IsEqualWith(this byte[] aBytes1, byte[] aBytes2) diff --git a/Core/File.cs b/Core/File.cs index 2a03fa8..936e7f2 100644 --- a/Core/File.cs +++ b/Core/File.cs @@ -72,7 +72,7 @@ public Int64 Size [DataMember] public List Parts { - get { return base.All.Cast().ToList(); } + get { return All.Cast().ToList(); } private set { throw new NotSupportedException("You can not set this Property."); } } diff --git a/Core/Files.cs b/Core/Files.cs index 76dab8f..d101f16 100644 --- a/Core/Files.cs +++ b/Core/Files.cs @@ -41,8 +41,10 @@ public File File(string tmpPath) { return All.First(file => file.TmpPath == tmpPath); } - catch {} - return null; + catch (Exception) + { + return null; + } } public void Add(File aFile) @@ -52,7 +54,7 @@ public void Add(File aFile) public void Add(string aName, Int64 aSize) { - File tFile = new File(aName, aSize); + var tFile = new File(aName, aSize); if (File(tFile.TmpPath) == null) { Add(tFile); diff --git a/Core/Helper.cs b/Core/Helper.cs index 81fdb4d..76b6a93 100644 --- a/Core/Helper.cs +++ b/Core/Helper.cs @@ -149,10 +149,7 @@ public static string ShrinkFileName(string aName, Int64 aSize) { return Regex.Replace(aName, "(\\(|\\)|\\[|\\]|\\{|\\}|-|_|\\.)", "").ToLower() + "." + aSize + "/"; } - else - { - return ""; - } + return ""; } } } diff --git a/Core/Server.cs b/Core/Server.cs index 48c11c2..8454156 100644 --- a/Core/Server.cs +++ b/Core/Server.cs @@ -44,7 +44,7 @@ public override bool Connected { foreach (AObject obj in All) { - obj.Connected = value; + obj.Connected = false; } } base.Connected = value; @@ -83,7 +83,7 @@ public SocketErrorCode ErrorCode public IEnumerable Channels { - get { return base.All.Cast(); } + get { return All.Cast(); } } public Channel Channel(string aName) @@ -111,7 +111,7 @@ public Bot Bot(string aName) public void AddChannel(Channel aChannel) { - base.Add(aChannel); + Add(aChannel); } public void AddChannel(string aChannel) @@ -123,16 +123,14 @@ public void AddChannel(string aChannel) } if (Channel(aChannel) == null) { - Channel tChannel = new Channel(); - tChannel.Name = aChannel; - tChannel.Enabled = Enabled; + var tChannel = new Channel {Name = aChannel, Enabled = Enabled}; AddChannel(tChannel); } } public void RemoveChannel(Channel aChannel) { - base.Remove(aChannel); + Remove(aChannel); } #endregion diff --git a/Core/Servers.cs b/Core/Servers.cs index 182c39e..4e16e00 100644 --- a/Core/Servers.cs +++ b/Core/Servers.cs @@ -50,10 +50,7 @@ public void Add(string aServer) aServer = aServer.Trim().ToLower(); if (Server(aServer) == null) { - Server tServer = new Server(); - tServer.Name = aServer; - tServer.Port = 6667; - tServer.Enabled = true; + var tServer = new Server {Name = aServer, Port = 6667, Enabled = true}; Add(tServer); } } diff --git a/Server.Cmd/Cmd.cs b/Server.Cmd/Cmd.cs index e3fcfe9..e83df31 100644 --- a/Server.Cmd/Cmd.cs +++ b/Server.Cmd/Cmd.cs @@ -55,10 +55,12 @@ public static void Main(string[] args) // build our own, who logs only fatals to console Logger root = ((Hierarchy) LogManager.GetRepository()).Root; - ConsoleAppender lAppender = new ConsoleAppender(); - lAppender.Name = "Console"; - lAppender.Layout = new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %line:%logger.%message%n"); - lAppender.Threshold = Level.Fatal; + var lAppender = new ConsoleAppender + { + Name = "Console", + Layout = new PatternLayout("%date{dd-MM-yyyy HH:mm:ss,fff} %5level [%2thread] %line:%logger.%message%n"), + Threshold = Level.Fatal + }; lAppender.ActivateOptions(); root.AddAppender(lAppender); @@ -75,9 +77,9 @@ public static void Main(string[] args) } #endif - Main instance = new Main(); + var instance = new Main(); - ABackendPlugin backend = null; + ABackendPlugin backend; if (Settings.Instance.UseMySqlBackend) { backend = new BackendPlugin(); @@ -115,10 +117,7 @@ public static void Main(string[] args) instance.Stop(); break; } - else - { - Thread.Sleep(1000); - } + Thread.Sleep(1000); } Environment.Exit(0); diff --git a/Server.Plugin.Backend.File/BackendPlugin.cs b/Server.Plugin.Backend.File/BackendPlugin.cs index e0fe7da..ed2ca3b 100644 --- a/Server.Plugin.Backend.File/BackendPlugin.cs +++ b/Server.Plugin.Backend.File/BackendPlugin.cs @@ -38,7 +38,7 @@ public class BackendPlugin : ABackendPlugin { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly BinaryFormatter _formatter = new BinaryFormatter(); bool _isSaveFile; @@ -47,12 +47,12 @@ public class BackendPlugin : ABackendPlugin readonly object _saveSearchesLock = new object(); readonly object _saveSnapshotsLock = new object(); - string _dataBinary = "xg.bin"; - string _filesBinary = "xgfiles.bin"; - string _searchesBinary = "xgsearches.bin"; - string _snapshotsBinary = "xgsnapshots.bin"; + const string DataBinary = "xg.bin"; + const string FilesBinary = "xgfiles.bin"; + const string SearchesBinary = "xgsearches.bin"; + const string SnapshotsBinary = "xgsnapshots.bin"; - int BackupDataTime = 900000; + const int BackupDataTime = 900000; #endregion @@ -60,65 +60,56 @@ public class BackendPlugin : ABackendPlugin public override Core.Servers LoadServers() { - Core.Servers _servers = null; try { - _servers = (Core.Servers) Load(Settings.Instance.AppDataPath + _dataBinary); - _servers.AttachChildEvents(); + var servers = (Core.Servers) Load(Settings.Instance.AppDataPath + DataBinary); + servers.AttachChildEvents(); + return servers; } - catch {} - if (_servers == null) + catch (Exception) { - _servers = new Core.Servers(); + return new Core.Servers(); } - return _servers; } public override Files LoadFiles() { - Files _files = null; try { - _files = (Files) Load(Settings.Instance.AppDataPath + _filesBinary); - _files.AttachChildEvents(); + var files = (Files) Load(Settings.Instance.AppDataPath + FilesBinary); + files.AttachChildEvents(); + return files; } - catch {} - if (_files == null) + catch (Exception) { - _files = new Files(); + return new Files(); } - return _files; } public override Objects LoadSearches() { - Objects _searches = null; try { - _searches = (Objects) Load(Settings.Instance.AppDataPath + _searchesBinary); - _searches.AttachChildEvents(); + var searches = (Objects) Load(Settings.Instance.AppDataPath + SearchesBinary); + searches.AttachChildEvents(); + return searches; } - catch {} - if (_searches == null) + catch (Exception) { - _searches = new Objects(); + return new Objects(); } - return _searches; } public override Snapshots LoadStatistics() { - Snapshots _snapshots = null; try { - _snapshots = (Snapshots) Load(Settings.Instance.AppDataPath + _snapshotsBinary); + return (Snapshots) Load(Settings.Instance.AppDataPath + SnapshotsBinary); } - catch {} - if (_snapshots == null) + catch (Exception) { - _snapshots = new Snapshots(); + return new Snapshots(); } - return _snapshots; } #endregion @@ -154,6 +145,8 @@ protected override void StartRun() } Thread.Sleep(Settings.Instance.RunLoopTime * 1000); + + // TODO break this! } } @@ -188,7 +181,7 @@ protected override void FileChanged(AObject aObj) } else if (aObj is FilePart) { - FilePart part = aObj as FilePart; + var part = aObj as FilePart; // if this change is lost, the data might be corrupt, so save it now if (part.State != FilePart.States.Open) { @@ -260,11 +253,11 @@ bool Save(object aObj, string aFile) FileSystem.DeleteFile(aFile + ".bak"); FileSystem.MoveFile(aFile, aFile + ".bak"); FileSystem.MoveFile(aFile + ".new", aFile); - _log.Debug("Save(" + aFile + ")"); + Log.Debug("Save(" + aFile + ")"); } catch (Exception ex) { - _log.Fatal("Save(" + aFile + ")", ex); + Log.Fatal("Save(" + aFile + ")", ex); return false; } return true; @@ -285,22 +278,22 @@ object Load(string aFile) Stream streamRead = System.IO.File.OpenRead(aFile); obj = _formatter.Deserialize(streamRead); streamRead.Close(); - _log.Debug("Load(" + aFile + ")"); + Log.Debug("Load(" + aFile + ")"); } catch (Exception ex) { - _log.Fatal("Load(" + aFile + ")", ex); + Log.Fatal("Load(" + aFile + ")", ex); // try to load the backup try { Stream streamRead = System.IO.File.OpenRead(aFile + ".bak"); obj = _formatter.Deserialize(streamRead); streamRead.Close(); - _log.Debug("Load(" + aFile + ".bak)"); + Log.Debug("Load(" + aFile + ".bak)"); } catch (Exception) { - _log.Fatal("Load(" + aFile + ".bak)", ex); + Log.Fatal("Load(" + aFile + ".bak)", ex); } } } @@ -312,7 +305,7 @@ bool SaveFiles() lock (_saveFilesLock) { _isSaveFile = false; - return Save(Files, Settings.Instance.AppDataPath + _filesBinary); + return Save(Files, Settings.Instance.AppDataPath + FilesBinary); } } @@ -320,7 +313,7 @@ bool SaveObjects() { lock (_saveObjectsLock) { - return Save(Servers, Settings.Instance.AppDataPath + _dataBinary); + return Save(Servers, Settings.Instance.AppDataPath + DataBinary); } } @@ -328,7 +321,7 @@ bool SaveSearches() { lock (_saveSearchesLock) { - return Save(Searches, Settings.Instance.AppDataPath + _searchesBinary); + return Save(Searches, Settings.Instance.AppDataPath + SearchesBinary); } } @@ -336,7 +329,7 @@ bool SaveSnapshots() { lock (_saveSnapshotsLock) { - return Save(Snapshots, Settings.Instance.AppDataPath + _snapshotsBinary); + return Save(Snapshots, Settings.Instance.AppDataPath + SnapshotsBinary); } } diff --git a/Server.Plugin.Backend.MySql/BackendPlugin.cs b/Server.Plugin.Backend.MySql/BackendPlugin.cs index 50d6e92..c58f057 100644 --- a/Server.Plugin.Backend.MySql/BackendPlugin.cs +++ b/Server.Plugin.Backend.MySql/BackendPlugin.cs @@ -37,7 +37,7 @@ public class BackendPlugin : ABackendPlugin { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly MySqlConnection _dbConnection; readonly object _locked = new object(); @@ -64,8 +64,8 @@ public BackendPlugin() } catch (Exception ex) { - _log.Fatal("MySqlBackend(" + connectionString + ") ", ex); - throw ex; + Log.Fatal("MySqlBackend(" + connectionString + ") ", ex); + throw; } } @@ -81,7 +81,7 @@ protected override void StopRun() } catch (Exception ex) { - _log.Fatal("CloseClient() ", ex); + Log.Fatal("CloseClient() ", ex); } } @@ -91,14 +91,13 @@ protected override void StopRun() public override Core.Servers LoadServers() { - Core.Servers _servers = new Core.Servers(); + var servers = new Core.Servers(); - Dictionary dic = new Dictionary(); - dic.Add("guid", Guid.Empty); + var dic = new Dictionary {{"guid", Guid.Empty}}; foreach (Core.Server serv in ExecuteQuery("SELECT * FROM servers;", null)) { serv.Connected = false; - _servers.Add(serv); + servers.Add(serv); dic["guid"] = serv.Guid.ToString(); foreach (Channel chan in ExecuteQuery("SELECT * FROM channels WHERE ParentGuid = @guid;", dic)) @@ -123,36 +122,36 @@ public override Core.Servers LoadServers() } } - return _servers; + return servers; } public override Files LoadFiles() { - Files _files = new Files(); + var files = new Files(); /*foreach(File file in ExecuteQuery("SELECT * FROM files;", null)) { - _files.Add(file); + files.Add(file); }*/ - return _files; + return files; } public override Objects LoadSearches() { - Objects _searches = new Objects(); + var searches = new Objects(); /*foreach(Core.Object obj in ExecuteQuery("SELECT * FROM searches;", null)) { - _searches.Add(obj); + searches.Add(obj); }*/ - return _searches; + return searches; } public override Snapshots LoadStatistics() { - Snapshots _snapshots = new Snapshots(); + var snapshots = new Snapshots(); foreach (Snapshot snapshot in ExecuteQuery("SELECT * FROM snapshots;", null)) { @@ -165,10 +164,10 @@ public override Snapshots LoadStatistics() coreSnapshot.Set(type, (Int64) prop.GetValue(snapshot, null)); } - _snapshots.Add(coreSnapshot); + snapshots.Add(coreSnapshot); } - return _snapshots; + return snapshots; } #endregion @@ -223,7 +222,7 @@ protected override void ObjectChanged(AObject aObj) protected override void ObjectRemoved(AObject aParentObj, AObject aObj) { string table = Table4Object(aObj); - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); if (table != "") { @@ -234,7 +233,7 @@ protected override void ObjectRemoved(AObject aParentObj, AObject aObj) protected override void SnapshotAdded(Core.Snapshot aSnap) { - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); for (int a = 0; a <= 26; a++) { @@ -264,7 +263,7 @@ protected override void SnapshotAdded(Core.Snapshot aSnap) Dictionary Object2Dic(object aObj) { - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); var properties = aObj.GetType().GetProperties(); foreach (var prop in properties) @@ -331,7 +330,7 @@ T Dic2Object(Dictionary aDic) { if (ex.InnerException == null || ex.InnerException.GetType() != typeof (NotSupportedException)) { - throw ex; + throw; } } } @@ -343,7 +342,7 @@ void ExecuteNonQuery(string aSql, Dictionary aDic) { lock (_locked) { - MySqlCommand cmd = new MySqlCommand(aSql, _dbConnection); + var cmd = new MySqlCommand(aSql, _dbConnection); using (cmd) { if (aDic != null) @@ -362,17 +361,17 @@ void ExecuteNonQuery(string aSql, Dictionary aDic) } catch (MySqlException ex) { - _log.Fatal("ExecuteQuery(" + ex.Number + ") '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Fatal("ExecuteQuery(" + ex.Number + ") '" + BuildSqlString(aSql, aDic) + "' ", ex); } catch (InvalidOperationException ex) { - _log.Fatal("ExecuteQuery() '" + BuildSqlString(aSql, aDic) + "' ", ex); - _log.Warn("ExecuteQuery() : stopping server plugin!"); + Log.Fatal("ExecuteQuery() '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Warn("ExecuteQuery() : stopping server plugin!"); Stop(); } catch (Exception ex) { - _log.Fatal("ExecuteQuery() '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Fatal("ExecuteQuery() '" + BuildSqlString(aSql, aDic) + "' ", ex); } #endif } @@ -381,11 +380,11 @@ void ExecuteNonQuery(string aSql, Dictionary aDic) List ExecuteQuery(string aSql, Dictionary aDic) { - List list = new List(); + var list = new List(); lock (_locked) { - MySqlCommand cmd = new MySqlCommand(aSql, _dbConnection); + var cmd = new MySqlCommand(aSql, _dbConnection); using (cmd) { if (aDic != null) @@ -402,12 +401,12 @@ List ExecuteQuery(string aSql, Dictionary aDic) MySqlDataReader myReader = cmd.ExecuteReader(); while (myReader.Read()) { - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); for (int col = 0; col < myReader.FieldCount; col++) { dic.Add(myReader.GetName(col), myReader.GetValue(col)); } - T obj = Dic2Object(dic); + var obj = Dic2Object(dic); if (obj != null) { list.Add(obj); @@ -418,17 +417,17 @@ List ExecuteQuery(string aSql, Dictionary aDic) } catch (MySqlException ex) { - _log.Fatal("ExecuteReader(" + ex.Number + ") '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Fatal("ExecuteReader(" + ex.Number + ") '" + BuildSqlString(aSql, aDic) + "' ", ex); } catch (InvalidOperationException ex) { - _log.Fatal("ExecuteReader() '" + BuildSqlString(aSql, aDic) + "' ", ex); - _log.Warn("ExecuteReader() : stopping server plugin!"); + Log.Fatal("ExecuteReader() '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Warn("ExecuteReader() : stopping server plugin!"); Stop(); } catch (Exception ex) { - _log.Fatal("ExecuteReader() '" + BuildSqlString(aSql, aDic) + "' ", ex); + Log.Fatal("ExecuteReader() '" + BuildSqlString(aSql, aDic) + "' ", ex); } #endif } @@ -443,15 +442,15 @@ string Table4Object(AObject aObj) { return "servers"; } - else if (aObj is Channel) + if (aObj is Channel) { return "channels"; } - else if (aObj is Bot) + if (aObj is Bot) { return "bots"; } - else if (aObj is Packet) + if (aObj is Packet) { return "packets"; } diff --git a/Server.Plugin.General.Jabber/Plugin.cs b/Server.Plugin.General.Jabber/Plugin.cs index ab7d148..5d86f3e 100644 --- a/Server.Plugin.General.Jabber/Plugin.cs +++ b/Server.Plugin.General.Jabber/Plugin.cs @@ -27,7 +27,6 @@ using XG.Core; using agsXMPP; -using agsXMPP.Xml.Dom; using agsXMPP.protocol.client; using log4net; @@ -38,7 +37,7 @@ public class Plugin : APlugin { #region VARIABLES - static readonly ILog log = LogManager.GetLogger(typeof (Plugin)); + static readonly ILog Log = LogManager.GetLogger(typeof (Plugin)); XmppClientConnection _client; @@ -51,8 +50,8 @@ protected override void StartRun() _client = new XmppClientConnection(Settings.Instance.JabberServer); _client.Open(Settings.Instance.JabberUser, Settings.Instance.JabberPassword); _client.OnLogin += delegate { UpdateState(0); }; - _client.OnError += delegate(object sender, Exception ex) { log.Fatal("StartRun()", ex); }; - _client.OnAuthError += delegate(object sender, Element e) { log.Fatal("StartRun() " + e); }; + _client.OnError += (sender, ex) => Log.Fatal("StartRun()", ex); + _client.OnAuthError += (sender, e) => Log.Fatal("StartRun() " + e); } protected override void StopRun() @@ -68,12 +67,15 @@ protected new void FileChanged(AObject aObj) { if (aObj is FilePart) { - double speed = 0; + double speed; try { speed = (from file in Files.All from part in file.Parts select part.Speed).Sum(); } - catch {} + catch (Exception) + { + speed = 0; + } UpdateState(speed); } } @@ -89,10 +91,10 @@ void UpdateState(double aSpeed) return; } - Presence p = null; + Presence p; if (aSpeed > 0) { - string str = ""; + string str; if (aSpeed < 1024) { str = aSpeed + " B/s"; @@ -110,13 +112,11 @@ void UpdateState(double aSpeed) str = (aSpeed / (1024 * 1024 * 1024)).ToString("0.00") + " GB/s"; } - p = new Presence(ShowType.chat, str); - p.Type = PresenceType.available; + p = new Presence(ShowType.chat, str) {Type = PresenceType.available}; } else { - p = new Presence(ShowType.away, "Idle"); - p.Type = PresenceType.available; + p = new Presence(ShowType.away, "Idle") {Type = PresenceType.available}; } _client.Send(p); } diff --git a/Server.Plugin.General.Webserver/BrowserConnection.cs b/Server.Plugin.General.Webserver/BrowserConnection.cs index 429198b..bbd4b97 100644 --- a/Server.Plugin.General.Webserver/BrowserConnection.cs +++ b/Server.Plugin.General.Webserver/BrowserConnection.cs @@ -23,6 +23,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; @@ -45,7 +46,7 @@ public class BrowserConnection : APlugin { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public HttpListenerContext Context { get; set; } @@ -58,9 +59,9 @@ public class BrowserConnection : APlugin protected override void StartRun() { - Dictionary tDic = new Dictionary(); + var tDic = new Dictionary(); string str = Context.Request.RawUrl; - _log.Debug("StartRun() " + str); + Log.Debug("StartRun() " + str); #if !UNSAFE try @@ -99,16 +100,14 @@ protected override void StartRun() Context.Response.AppendCookie(new Cookie("xg.password", HttpUtility.UrlDecode(tDic["password"]))); } - ClientRequest tMessage = (ClientRequest) int.Parse(tDic["request"]); + var tMessage = (ClientRequest) int.Parse(tDic["request"]); #region DATA HANDLING string response = ""; Context.Response.AddHeader("Cache-Control", "no-cache"); - bool showOfflineBots = Context.Request.Cookies["xg.show_offline_bots"] == null - ? true - : (Context.Request.Cookies["xg.show_offline_bots"].Value == "1" ? true : false); + bool showOfflineBots = Context.Request.Cookies["xg.show_offline_bots"] == null || (Context.Request.Cookies["xg.show_offline_bots"].Value == "1"); Guid guid = Guid.Empty; try { @@ -183,8 +182,7 @@ protected override void StartRun() Object obj = Searches.Named(name); if (obj == null) { - obj = new Object(); - obj.Name = name; + obj = new Object {Name = name}; Searches.Add(obj); } break; @@ -297,8 +295,7 @@ protected override void StartRun() Bot tBot = chan.Bot(botName); if (tBot == null) { - tBot = new Bot(); - tBot.Name = botName; + tBot = new Bot {Name = botName}; chan.AddBot(tBot); } @@ -306,9 +303,7 @@ protected override void StartRun() Packet pack = tBot.Packet(packetId); if (pack == null) { - pack = new Packet(); - pack.Id = packetId; - pack.Name = link[5]; + pack = new Packet {Id = packetId, Name = link[5]}; tBot.AddPacket(pack); } pack.Enabled = true; @@ -399,8 +394,11 @@ protected override void StartRun() { Context.Response.Close(); } - catch {} - _log.Fatal("StartRun(" + str + ")", ex); + catch (Exception) + { + // just ignore + } + Log.Fatal("StartRun(" + str + ")", ex); } #endif } @@ -418,7 +416,7 @@ void WriteToStream(byte[] aData) { if (Context.Request.Headers["Accept-Encoding"] != null) { - using (MemoryStream ms = new MemoryStream()) + using (var ms = new MemoryStream()) { Stream compress = null; if (Context.Request.Headers["Accept-Encoding"].Contains("gzip")) @@ -654,13 +652,13 @@ IEnumerable SortedObjects(IEnumerable aObjects, string aSortBy string Searches2Json(Objects aObjects) { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("{"); sb.Append("\"Searches\":["); int count = 0; - foreach (AObject obj in aObjects.All) + foreach (var obj in aObjects.All) { count++; sb.Append("{\"Search\": \"" + obj.Name + "\"}"); @@ -678,9 +676,7 @@ string Searches2Json(Objects aObjects) string Objects2Json(IEnumerable aObjects, int aPage, int aRows) { - var tObjects = new JQGrid.Objects(); - tObjects.Page = aPage; - tObjects.Rows = aRows; + var tObjects = new JQGrid.Objects {Page = aPage, Rows = aRows}; tObjects.SetObjects(aObjects); return Json.Serialize(tObjects); } @@ -698,10 +694,10 @@ string Object2Json(AObject aObject) string Statistic2Json() { - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); sb.Append("{"); - List types = new List(); + var types = new List(); // uncool, but works for (int a = (int) StatisticType.BytesLoaded; a <= (int) StatisticType.SpeedMax; a++) { @@ -713,7 +709,7 @@ string Statistic2Json() { count++; double val = Statistic.Instance.Get(type); - sb.Append("\"" + type + "\":" + val.ToString().Replace(",", ".")); + sb.Append("\"" + type + "\":" + val.ToString(CultureInfo.InvariantCulture).Replace(",", ".")); if (count < types.Count) { sb.Append(","); diff --git a/Server.Plugin.General.Webserver/FileLoader.cs b/Server.Plugin.General.Webserver/FileLoader.cs index 0fbbf57..35c4496 100644 --- a/Server.Plugin.General.Webserver/FileLoader.cs +++ b/Server.Plugin.General.Webserver/FileLoader.cs @@ -34,7 +34,7 @@ public class FileLoader { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); readonly Dictionary _dicString; readonly Dictionary _dicByte; @@ -65,77 +65,76 @@ public string LoadFile(string aFile, string[] aLanguages) { return _dicString[aFile]; } - else - { #if !UNSAFE - try - { + try + { #endif - string content = ""; - if (aFile == "/js/all.js") + string content = ""; + if (aFile == "/js/all.js") + { + foreach (string file in _jsFiles) { - foreach (string file in _jsFiles) - { - content += LoadFile("/js/" + PatchLanguage(file, aLanguages) + ".js", aLanguages) + "\n"; - } + content += LoadFile("/js/" + PatchLanguage(file, aLanguages) + ".js", aLanguages) + "\n"; } - else if (aFile == "/css/all.css") + } + else if (aFile == "/css/all.css") + { + foreach (string file in _cssFiles) { - foreach (string file in _cssFiles) - { - content += LoadFile("/css/" + file + ".css", aLanguages) + "\n"; - } + content += LoadFile("/css/" + file + ".css", aLanguages) + "\n"; } - else - { + } + else + { #if DEBUG && !WINDOWS - content = File.OpenText("./Resources" + aFile).ReadToEnd(); + content = File.OpenText("./Resources" + aFile).ReadToEnd(); #else - Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); - string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); - content = new StreamReader(assembly.GetManifestResourceStream(name)).ReadToEnd(); + Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); + string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); + Stream stream = assembly.GetManifestResourceStream(name); + if (stream != null) + { + content = new StreamReader(stream).ReadToEnd(); + } #endif - if (aFile == "/index.html") - { + if (aFile == "/index.html") + { #if DEBUG - string css = ""; - foreach (string cssFile in _cssFiles) - { - css += "\t\t\n"; - } + string css = ""; + foreach (string cssFile in _cssFiles) + { + css += "\t\t\n"; + } #else - string css = "\t\t\n"; + string css = "\t\t\n"; #endif - content = content.Replace("#CSS_FILES#", css); - - //#if DEBUG - string js = ""; - foreach (string jsFile in _jsFiles) - { - js += "\t\t\n"; - } - //#else - // string js = "\t\t\n"; - //#endif - content = content.Replace("#JS_FILES#", js); - - content = content.Replace("#SALT#", Salt); - content = PatchLanguage(content, aLanguages); + content = content.Replace("#CSS_FILES#", css); + + //#if DEBUG + string js = ""; + foreach (string jsFile in _jsFiles) + { + js += "\t\t\n"; } + //#else + // string js = "\t\t\n"; + //#endif + content = content.Replace("#JS_FILES#", js); + + content = content.Replace("#SALT#", Salt); + content = PatchLanguage(content, aLanguages); } + } #if !DEBUG - _dicString.Add(aFile, content); + _dicString.Add(aFile, content); #endif - return content; + return content; #if !UNSAFE - } - catch (Exception ex) - { - _log.Fatal("LoadFile(" + aFile + ")", ex); - } -#endif } -#if !UNSAFE + catch (Exception ex) + { + Log.Fatal("LoadFile(" + aFile + ")", ex); + } return ""; #endif } @@ -146,29 +145,28 @@ public byte[] LoadFile(string aFile) { return _dicByte[aFile]; } - else - { #if !UNSAFE - try - { + try + { #endif #if DEBUG && !WINDOWS - return File.ReadAllBytes("./Resources" + aFile); + return File.ReadAllBytes("./Resources" + aFile); #else - Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); - string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); - _dicByte.Add(aFile, new BinaryReader(assembly.GetManifestResourceStream(name)).ReadAllBytes()); - return _dicByte[aFile]; -#endif -#if !UNSAFE - } - catch (Exception ex) + Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); + string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); + Stream stream = assembly.GetManifestResourceStream(name); + if (stream != null) { - _log.Fatal("LoadFile(" + aFile + ")", ex); + _dicByte.Add(aFile, new BinaryReader(stream).ReadAllBytes()); + return _dicByte[aFile]; } #endif - } #if !UNSAFE + } + catch (Exception ex) + { + Log.Fatal("LoadFile(" + aFile + ")", ex); + } return new byte[0]; #endif } @@ -185,15 +183,15 @@ public byte[] LoadImage(string aFile) { return _dicByte[aFile]; } - else - { #if !UNSAFE - try - { + try + { #endif - Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); - string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); - Stream stream = assembly.GetManifestResourceStream(name); + Assembly assembly = Assembly.GetAssembly(typeof (FileLoader)); + string name = "XG." + assembly.GetName().Name + ".Resources" + aFile.Replace('/', '.'); + Stream stream = assembly.GetManifestResourceStream(name); + if (stream != null) + { byte[] data = new byte[stream.Length]; int offset = 0; int remaining = data.Length; @@ -209,15 +207,13 @@ public byte[] LoadImage(string aFile) } _dicByte.Add(aFile, data); return _dicByte[aFile]; -#if !UNSAFE } - catch (Exception ex) - { - _log.Fatal("LoadImage(" + aFile + ")", ex); - } -#endif - } #if !UNSAFE + } + catch (Exception ex) + { + Log.Fatal("LoadImage(" + aFile + ")", ex); + } return null; #endif } diff --git a/Server.Plugin.General.Webserver/Json.cs b/Server.Plugin.General.Webserver/Json.cs index 871e89a..76f7ec8 100644 --- a/Server.Plugin.General.Webserver/Json.cs +++ b/Server.Plugin.General.Webserver/Json.cs @@ -33,25 +33,24 @@ public class Json { public static string Serialize(T t) { - DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof (T)); - MemoryStream ms = new MemoryStream(); + var ser = new DataContractJsonSerializer(typeof (T)); + var ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); - string p = @"\\/Date\(([0-9-]+)(((\+|-)[0-9]+)|)\)\\/"; + const string p = @"\\/Date\(([0-9-]+)(((\+|-)[0-9]+)|)\)\\/"; MatchEvaluator matchEvaluator = ConvertJsonDateToDateString; - Regex reg = new Regex(p); + var reg = new Regex(p); jsonString = reg.Replace(jsonString, matchEvaluator); return jsonString; } static string ConvertJsonDateToDateString(Match m) { - string result = string.Empty; - DateTime dt = new DateTime(1970, 1, 1); + var dt = new DateTime(1970, 1, 1); dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value)); - result = dt.ToString("HH:mm:ss dd.MM.yyyy"); + string result = dt.ToString("HH:mm:ss dd.MM.yyyy"); return result; } } diff --git a/Server.Plugin.General.Webserver/Plugin.cs b/Server.Plugin.General.Webserver/Plugin.cs index ea22007..b53e127 100644 --- a/Server.Plugin.General.Webserver/Plugin.cs +++ b/Server.Plugin.General.Webserver/Plugin.cs @@ -34,7 +34,7 @@ public class Plugin : APlugin { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); HttpListener _listener; @@ -61,14 +61,13 @@ protected override void StartRun() #if WINDOWS if (ex.NativeErrorCode == 5) { - _log.Fatal(@"TO GET XG UP AND RUNNING YOU MUST RUN 'netsh http add urlacl url=http://*:5556/ user=%USERDOMAIN%\%USERNAME%' AS ADMINISTRATOR"); + Log.Fatal(@"TO GET XG UP AND RUNNING YOU MUST RUN 'netsh http add urlacl url=http://*:5556/ user=%USERDOMAIN%\%USERNAME%' AS ADMINISTRATOR"); } #endif - throw ex; + throw; } - FileLoader fileLoader = new FileLoader(); - fileLoader.Salt = _salt; + var fileLoader = new FileLoader {Salt = _salt}; while (true) { @@ -76,14 +75,16 @@ protected override void StartRun() try { #endif - BrowserConnection connection = new BrowserConnection(); - connection.Context = _listener.GetContext(); - connection.Servers = Servers; - connection.Files = Files; - connection.Searches = Searches; - connection.Snapshots = Snapshots; - connection.FileLoader = fileLoader; - connection.Salt = _salt; + var connection = new BrowserConnection + { + Context = _listener.GetContext(), + Servers = Servers, + Files = Files, + Searches = Searches, + Snapshots = Snapshots, + FileLoader = fileLoader, + Salt = _salt + }; connection.Start(); #if !UNSAFE diff --git a/Server.Test/Helper/Filesystem.cs b/Server.Test/Helper/Filesystem.cs index f8a9399..00a1ca1 100644 --- a/Server.Test/Helper/Filesystem.cs +++ b/Server.Test/Helper/Filesystem.cs @@ -25,7 +25,9 @@ using NUnit.Framework; -namespace XG.Server.Helper.Test +using XG.Server.Helper; + +namespace XG.Server.Test.Helper { [TestFixture] public class Filesystem @@ -33,15 +35,13 @@ public class Filesystem [Test] public void MoveFile() { - string fileNameOld = "test1.txt"; - string fileNameNew = "test2.txt"; - - bool result = false; + const string fileNameOld = "test1.txt"; + const string fileNameNew = "test2.txt"; File.Delete(fileNameOld); File.Delete(fileNameNew); - result = FileSystem.MoveFile(fileNameOld, fileNameNew); + bool result = FileSystem.MoveFile(fileNameOld, fileNameNew); Assert.AreEqual(false, result); File.Create(fileNameOld).Close(); diff --git a/Server.Test/Helper/Process.cs b/Server.Test/Helper/Process.cs index e0f97f6..1d99f0e 100644 --- a/Server.Test/Helper/Process.cs +++ b/Server.Test/Helper/Process.cs @@ -25,7 +25,7 @@ using NUnit.Framework; -namespace XG.Server.Helper.Test +namespace XG.Server.Test.Helper { [TestFixture] public class Process @@ -33,8 +33,8 @@ public class Process [Test] public void Run() { - string file = "test.txt"; - string archive = "test.rar"; + const string file = "test.txt"; + const string archive = "test.rar"; File.Create(file).Close(); Assert.AreEqual(true, Compress(file, archive, "test")); @@ -51,18 +51,15 @@ public void Run() bool Compress(string file, string archive, string password) { - var p = new Helper.Process(); - p.Command = "rar"; - p.Arguments = "a " + (string.IsNullOrEmpty(password) ? "" : "-p" + password + " ") + archive + " " + file; + var p = new Server.Helper.Process + {Command = "rar", Arguments = "a " + (string.IsNullOrEmpty(password) ? "" : "-p" + password + " ") + archive + " " + file}; return p.Run(); } bool DeCompress(string archive) { - var p = new Helper.Process(); - p.Command = "unrar"; - p.Arguments = "e -p- " + archive; + var p = new Server.Helper.Process {Command = "unrar", Arguments = "e -p- " + archive}; return p.Run(); } diff --git a/Server.Test/Irc/AParser.cs b/Server.Test/Irc/AParser.cs index d37a236..8d09810 100644 --- a/Server.Test/Irc/AParser.cs +++ b/Server.Test/Irc/AParser.cs @@ -28,84 +28,81 @@ using XG.Core; -namespace XG.Server.Irc.Test +namespace XG.Server.Test.Irc { public abstract class AParser { - protected Core.Server _server; - protected Channel _channel; - protected Bot _bot; + protected Core.Server Server; + protected Channel Channel; + protected Bot Bot; - protected string _eventParsingError; - protected Channel _eventChannel; - protected Bot _eventBot; - protected Packet _eventPacket; - protected Int64 _eventChunk; - protected IPAddress _eventIp; - protected int _eventPort; - protected string _eventData; - protected AObject _eventObject; - protected Int64 _eventTime; - protected bool _eventOverride; + protected string EventParsingError; + protected Channel EventChannel; + protected Bot EventBot; + protected Packet EventPacket; + protected Int64 EventChunk; + protected IPAddress EventIp; + protected int EventPort; + protected string EventData; + protected AObject EventObject; + protected Int64 EventTime; + protected bool EventOverride; - protected Irc.AParser _ircParser; + protected Server.Irc.AParser IrcParser; - public AParser() + protected AParser() { - _server = new Core.Server(); - _server.Name = "test.bitpir.at"; + Server = new Core.Server {Name = "test.bitpir.at"}; - _channel = new Channel(); - _channel.Name = "#test"; - _server.AddChannel(_channel); + Channel = new Channel {Name = "#test"}; + Server.AddChannel(Channel); - _bot = new Bot(); - _bot.Name = "[XG]TestBot"; - _channel.AddBot(_bot); + Bot = new Bot {Name = "[XG]TestBot"}; + Channel.AddBot(Bot); } - public void RegisterParser(Irc.AParser aParser) + public void RegisterParser(Server.Irc.AParser aParser) { - _ircParser = aParser; + IrcParser = aParser; - _ircParser.ParsingError += delegate(string aData) { _eventParsingError = aData; }; + IrcParser.ParsingError += delegate(string aData) { EventParsingError = aData; }; - _ircParser.AddDownload += delegate(Packet aPack, long aChunk, IPAddress aIp, int aPort) + IrcParser.AddDownload += delegate(Packet aPack, long aChunk, IPAddress aIp, int aPort) { - _eventPacket = aPack; - _eventChunk = aChunk; - _eventIp = aIp; - _eventPort = aPort; + EventPacket = aPack; + EventChunk = aChunk; + EventIp = aIp; + EventPort = aPort; }; - _ircParser.RemoveDownload += delegate(Bot aBot) { _eventBot = aBot; }; + IrcParser.RemoveDownload += delegate(Bot aBot) { EventBot = aBot; }; - _ircParser.SendData += delegate(Core.Server aServer, string aData) + IrcParser.SendData += delegate(Core.Server aServer, string aData) { - Assert.AreEqual(_server, aServer); - _eventData = aData; + Assert.AreEqual(Server, aServer); + EventData = aData; }; - _ircParser.JoinChannel += delegate(Core.Server aServer, Channel aChannel) + IrcParser.JoinChannel += delegate(Core.Server aServer, Channel aChannel) { - Assert.AreEqual(_server, aServer); - _eventChannel = aChannel; + Assert.AreEqual(Server, aServer); + EventChannel = aChannel; }; - _ircParser.CreateTimer += delegate(Core.Server aServer, AObject aObject, int aTime, bool aOverride) + IrcParser.CreateTimer += delegate(Core.Server aServer, AObject aObject, int aTime, bool aOverride) { - Assert.AreEqual(_server, aServer); - _eventObject = aObject; - _eventTime = aTime; - _eventOverride = aOverride; + Assert.AreEqual(Server, aServer); + EventObject = aObject; + EventTime = aTime; + EventOverride = aOverride; }; - _ircParser.RequestFromBot += delegate(Core.Server aServer, Bot aBot) + IrcParser.RequestFromBot += delegate(Core.Server aServer, Bot aBot) { - Assert.AreEqual(_server, aServer); - _eventBot = aBot; + Assert.AreEqual(Server, aServer); + EventBot = aBot; }; - _ircParser.UnRequestFromBot += delegate(Core.Server aServer, Bot aBot) + IrcParser.UnRequestFromBot += delegate(Core.Server aServer, Bot aBot) { - Assert.AreEqual(_server, aServer); - _eventBot = aBot; + Assert.AreEqual(Server, aServer); + EventBot = aBot; }; } } diff --git a/Server.Test/Irc/Notice.cs b/Server.Test/Irc/Notice.cs index 310a6f5..c00e430 100644 --- a/Server.Test/Irc/Notice.cs +++ b/Server.Test/Irc/Notice.cs @@ -23,28 +23,28 @@ using NUnit.Framework; -namespace XG.Server.Irc.Test +namespace XG.Server.Test.Irc { [TestFixture] public class Notice : AParser { public Notice() { - RegisterParser(new Irc.Notice()); + RegisterParser(new Server.Irc.Notice()); } [Test] public void BotMessages() { - _eventParsingError = ""; + EventParsingError = ""; Settings.Instance.AutoJoinOnInvite = true; - _ircParser.ParseData(_server, + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT NOTICE xg1_bitpir_at : ** Closing Connection You Must JOIN MG-CHAT As Well To Download - Your Download Will Be Canceled Now"); - Assert.AreEqual("JOIN #MG-CHAT", _eventData); + Assert.AreEqual("JOIN #MG-CHAT", EventData); - Assert.AreEqual(true, string.IsNullOrEmpty(_eventParsingError)); + Assert.AreEqual(true, string.IsNullOrEmpty(EventParsingError)); } } } diff --git a/Server.Test/Irc/Parser.cs b/Server.Test/Irc/Parser.cs index ad52f4c..baa940e 100644 --- a/Server.Test/Irc/Parser.cs +++ b/Server.Test/Irc/Parser.cs @@ -21,13 +21,13 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -namespace XG.Server.Irc.Test +namespace XG.Server.Test.Irc { public class Parser : AParser { public Parser() { - RegisterParser(new Irc.Parser()); + RegisterParser(new Server.Irc.Parser()); } } } diff --git a/Server.Test/Irc/PrivateMessage.cs b/Server.Test/Irc/PrivateMessage.cs index f946fb8..a56f78d 100644 --- a/Server.Test/Irc/PrivateMessage.cs +++ b/Server.Test/Irc/PrivateMessage.cs @@ -27,86 +27,85 @@ using XG.Core; -namespace XG.Server.Irc.Test +namespace XG.Server.Test.Irc { [TestFixture] public class PrivateMessage : AParser { public PrivateMessage() { - RegisterParser(new Irc.PrivateMessage()); + RegisterParser(new Server.Irc.PrivateMessage()); } [Test] public void ParseBandwidth() { - _eventParsingError = ""; + EventParsingError = ""; - _ircParser.ParseData(_server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :** Bandwidth Usage ** Current: 12.7kB/s, Record: 139.5kB/s"); - Assert.AreEqual((Int64) (12.7 * 1024), _bot.InfoSpeedCurrent); - Assert.AreEqual((Int64) (139.5 * 1024), _bot.InfoSpeedMax); + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :** Bandwidth Usage ** Current: 12.7kB/s, Record: 139.5kB/s"); + Assert.AreEqual((Int64) (12.7 * 1024), Bot.InfoSpeedCurrent); + Assert.AreEqual((Int64) (139.5 * 1024), Bot.InfoSpeedMax); - _ircParser.ParseData(_server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :** Bandwidth Usage ** Current: 0.0KB/s, Record: 231.4KB/s"); - Assert.AreEqual(0, _bot.InfoSpeedCurrent); - Assert.AreEqual((Int64) (231.4 * 1024), _bot.InfoSpeedMax); + IrcParser.ParseData(Server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :** Bandwidth Usage ** Current: 0.0KB/s, Record: 231.4KB/s"); + Assert.AreEqual(0, Bot.InfoSpeedCurrent); + Assert.AreEqual((Int64) (231.4 * 1024), Bot.InfoSpeedMax); - Assert.AreEqual(true, string.IsNullOrEmpty(_eventParsingError)); + Assert.AreEqual(true, string.IsNullOrEmpty(EventParsingError)); } [Test] public void ParsePacketInfo() { - _eventParsingError = ""; + EventParsingError = ""; - _ircParser.ParseData(_server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :** 9 packs ** 1 of 1 slot open, Min: 5.0kB/s, Record: 59.3kB/s"); - Assert.AreEqual(1, _bot.InfoSlotCurrent); - Assert.AreEqual(1, _bot.InfoSlotTotal); + IrcParser.ParseData(Server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :** 9 packs ** 1 of 1 slot open, Min: 5.0kB/s, Record: 59.3kB/s"); + Assert.AreEqual(1, Bot.InfoSlotCurrent); + Assert.AreEqual(1, Bot.InfoSlotTotal); - _ircParser.ParseData(_server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :-> 1 Pack <- 10 Of 10 Slots Open Min: 15.0KB/s Record: 691.8KB/s"); - Assert.AreEqual(10, _bot.InfoSlotCurrent); - Assert.AreEqual(10, _bot.InfoSlotTotal); + IrcParser.ParseData(Server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :-> 1 Pack <- 10 Of 10 Slots Open Min: 15.0KB/s Record: 691.8KB/s"); + Assert.AreEqual(10, Bot.InfoSlotCurrent); + Assert.AreEqual(10, Bot.InfoSlotTotal); - _ircParser.ParseData(_server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :**[EWG]* packs ** 12 of 12 slots open, Record: 1736.8kB/s"); - Assert.AreEqual(12, _bot.InfoSlotCurrent); - Assert.AreEqual(12, _bot.InfoSlotTotal); + IrcParser.ParseData(Server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :**[EWG]* packs ** 12 of 12 slots open, Record: 1736.8kB/s"); + Assert.AreEqual(12, Bot.InfoSlotCurrent); + Assert.AreEqual(12, Bot.InfoSlotTotal); - _ircParser.ParseData(_server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :-> 18 PackS <- 13 Of 15 Slots Open Min: 15.0KB/s Record: 99902.4KB/s"); - Assert.AreEqual(13, _bot.InfoSlotCurrent); - Assert.AreEqual(15, _bot.InfoSlotTotal); + IrcParser.ParseData(Server, ":[XG]TestBot!~ROOT@local.host PRIVMSG #test :-> 18 PackS <- 13 Of 15 Slots Open Min: 15.0KB/s Record: 99902.4KB/s"); + Assert.AreEqual(13, Bot.InfoSlotCurrent); + Assert.AreEqual(15, Bot.InfoSlotTotal); - Assert.AreEqual(true, string.IsNullOrEmpty(_eventParsingError)); + Assert.AreEqual(true, string.IsNullOrEmpty(EventParsingError)); } [Test] public void ParsePackets() { - Packet tPack = null; - _eventParsingError = ""; + EventParsingError = ""; - _ircParser.ParseData(_server, + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :#5  90x [181M] 6,9 Serie 9,6 The.Big.Bang.Theory.S05E05.Ab.nach.Baikonur.GERMAN.DUBBED.HDTVRiP.XviD-SOF.rar "); - tPack = _bot.Packet(5); + Packet tPack = Bot.Packet(5); Assert.AreEqual(181 * 1024 * 1024, tPack.Size); Assert.AreEqual("Serie The.Big.Bang.Theory.S05E05.Ab.nach.Baikonur.GERMAN.DUBBED.HDTVRiP.XviD-SOF.rar", tPack.Name); - _ircParser.ParseData(_server, + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :#3  54x [150M] 2,11 [ABOOK] Fanny_Mueller--Grimms_Maerchen_(Abook)-2CD-DE-2008-OMA.rar "); - tPack = _bot.Packet(3); + tPack = Bot.Packet(3); Assert.AreEqual(150 * 1024 * 1024, tPack.Size); Assert.AreEqual("[ABOOK] Fanny_Mueller--Grimms_Maerchen_(Abook)-2CD-DE-2008-OMA.rar", tPack.Name); - _ircParser.ParseData(_server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :#1� 0x [� 5M] 5meg"); - tPack = _bot.Packet(1); + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :#1� 0x [� 5M] 5meg"); + tPack = Bot.Packet(1); Assert.AreEqual(5 * 1024 * 1024, tPack.Size); Assert.AreEqual("5meg", tPack.Name); - _ircParser.ParseData(_server, + IrcParser.ParseData(Server, ":[XG]TestBot!~SYSTEM@XG.BITPIR.AT PRIVMSG #test :#18 5x [2.2G] Payback.Heute.ist.Zahltag.2011.German.DL.1080p.BluRay.x264-LeechOurStuff.mkv"); - tPack = _bot.Packet(18); + tPack = Bot.Packet(18); Assert.AreEqual((Int64) (2.2 * 1024 * 1024 * 1024), tPack.Size); Assert.AreEqual("Payback.Heute.ist.Zahltag.2011.German.DL.1080p.BluRay.x264-LeechOurStuff.mkv", tPack.Name); - Assert.AreEqual(true, string.IsNullOrEmpty(_eventParsingError)); + Assert.AreEqual(true, string.IsNullOrEmpty(EventParsingError)); } } } diff --git a/Server/BotConnection.cs b/Server/BotConnection.cs index 21d9b14..f701203 100644 --- a/Server/BotConnection.cs +++ b/Server/BotConnection.cs @@ -48,7 +48,7 @@ public class BotConnection : AIrcConnection { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); BinaryWriter _writer; BinaryReader _reader; @@ -96,7 +96,7 @@ Int64 StopSize set { Part.StopSize = value; - _log.Info("StopSize.set(" + value + ")"); + Log.Info("StopSize.set(" + value + ")"); Part.Commit(); } } @@ -116,11 +116,8 @@ string FileName { return Settings.Instance.TempPath + File.TmpPath + Part.StartSize; } - // damn this should not happen - else - { - return ""; - } + // damn this should not happen + return ""; } } @@ -141,21 +138,21 @@ protected override void ConnectionConnected() _speedCalcSize = 0; _receivedBytes = 0; - File File = FileActions.NewFile(Packet.RealName, Packet.RealSize); - if (File == null) + File tFile = FileActions.NewFile(Packet.RealName, Packet.RealSize); + if (tFile == null) { - _log.Fatal("ConnectionConnected() cant find or create a file to download"); + Log.Fatal("ConnectionConnected() cant find or create a file to download"); Connection.Disconnect(); return; } - Part = FileActions.Part(File, StartSize); + Part = FileActions.Part(tFile, StartSize); if (Part != null) { // wtf? if (StartSize == StopSize) { - _log.Error("ConnectionConnected() startSize = stopsize (" + StartSize + ")"); + Log.Error("ConnectionConnected() startSize = stopsize (" + StartSize + ")"); Connection.Disconnect(); return; } @@ -163,13 +160,13 @@ protected override void ConnectionConnected() Part.State = FilePart.States.Open; Part.Packet = Packet; - _log.Info("ConnectionConnected() startet (" + StartSize + " - " + StopSize + ")"); + Log.Info("ConnectionConnected() startet (" + StartSize + " - " + StopSize + ")"); #if !UNSAFE try { #endif - FileInfo info = new FileInfo(FileName); + var info = new FileInfo(FileName); FileStream stream = info.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite); // we are connected @@ -195,7 +192,7 @@ protected override void ConnectionConnected() } catch (Exception ex) { - _log.Fatal("ConnectionConnected() seek", ex); + Log.Fatal("ConnectionConnected() seek", ex); Connection.Disconnect(); return; } @@ -226,7 +223,7 @@ protected override void ConnectionConnected() } catch (Exception ex) { - _log.Fatal("ConnectionConnected()", ex); + Log.Fatal("ConnectionConnected()", ex); Connection.Disconnect(); return; } @@ -237,7 +234,7 @@ protected override void ConnectionConnected() } else { - _log.Error("ConnectionConnected() cant find a part to download"); + Log.Error("ConnectionConnected() cant find a part to download"); Connection.Disconnect(); } } @@ -277,7 +274,7 @@ protected override void ConnectionDisconnected(SocketErrorCode aValue) if (CurrrentSize == StopSize || (!Part.Checked && CurrrentSize == StopSize + Settings.Instance.FileRollbackCheckBytes)) { Part.State = FilePart.States.Ready; - _log.Info("ConnectionDisconnected() ready" + (Part.Checked ? "" : " but unchecked")); + Log.Info("ConnectionDisconnected() ready" + (Part.Checked ? "" : " but unchecked")); // statistics Statistic.Instance.Increase(StatisticType.PacketsCompleted); @@ -286,12 +283,12 @@ protected override void ConnectionDisconnected(SocketErrorCode aValue) else if (CurrrentSize > StopSize) { Part.State = FilePart.States.Broken; - _log.Error("ConnectionDisconnected() size is bigger than excepted: " + CurrrentSize + " > " + StopSize); + Log.Error("ConnectionDisconnected() size is bigger than excepted: " + CurrrentSize + " > " + StopSize); // this mostly happens on the last part of a file - so lets remove the file and load the package again if (File.Parts.Count() == 1 || Part.StopSize == File.Size) { FileActions.RemoveFile(File); - _log.Error("ConnectionDisconnected() removing corupted file " + File.Name); + Log.Error("ConnectionDisconnected() removing corupted file " + File.Name); } // statistics @@ -300,7 +297,7 @@ protected override void ConnectionDisconnected(SocketErrorCode aValue) // it did not start else if (_receivedBytes == 0) { - _log.Error("ConnectionDisconnected() downloading did not start, disabling packet"); + Log.Error("ConnectionDisconnected() downloading did not start, disabling packet"); Packet.Enabled = false; // statistics @@ -309,7 +306,7 @@ protected override void ConnectionDisconnected(SocketErrorCode aValue) // it is incomplete else { - _log.Error("ConnectionDisconnected() incomplete"); + Log.Error("ConnectionDisconnected() incomplete"); // statistics Statistic.Instance.Increase(StatisticType.PacketsIncompleted); @@ -321,7 +318,7 @@ protected override void ConnectionDisconnected(SocketErrorCode aValue) else { // lets disable the packet, because the bot seems to have broken config or is firewalled - _log.Error("ConnectionDisconnected() connection did not work, disabling packet"); + Log.Error("ConnectionDisconnected() connection did not work, disabling packet"); Packet.Enabled = false; // statistics @@ -372,7 +369,7 @@ protected override void ConnectionDataReceived(byte[] aData) // all ok if (_rollbackRefernce.IsEqualWith(_startBuffer)) { - _log.Info("con_DataReceived() rollback check ok"); + Log.Info("con_DataReceived() rollback check ok"); aData = _startBuffer; _startBuffer = null; _streamOk = true; @@ -380,13 +377,12 @@ protected override void ConnectionDataReceived(byte[] aData) // data mismatch else { - _log.Error("con_DataReceived() rollback check failed"); + Log.Error("con_DataReceived() rollback check failed"); // unregister from the event because if this is triggered // it will remove the part Packet.EnabledChanged -= EnabledChanged; Packet.Enabled = false; - aData = new byte[0]; Connection.Disconnect(); return; } @@ -470,15 +466,14 @@ protected override void ConnectionDataReceived(byte[] aData) // all ok if (stopSize == 0) { - _log.Info("con_DataReceived() reference check ok"); - aData = new byte[0]; + Log.Info("con_DataReceived() reference check ok"); Connection.Disconnect(); return; } - // data mismatch + // data mismatch else { - _log.Error("con_DataReceived() reference check failed"); + Log.Error("con_DataReceived() reference check failed"); aData = _stopBuffer; StopSize = stopSize; } @@ -523,7 +518,7 @@ protected override void ConnectionDataReceived(byte[] aData) } catch (Exception ex) { - _log.Fatal("con_DataReceived() write", ex); + Log.Fatal("con_DataReceived() write", ex); _streamOk = false; Connection.Disconnect(); return; diff --git a/Server/Connection/Connection.cs b/Server/Connection/Connection.cs index 4a2519c..8ceb943 100644 --- a/Server/Connection/Connection.cs +++ b/Server/Connection/Connection.cs @@ -84,9 +84,7 @@ public override void Connect() // we just need a writer if reading in text mode if (MaxData == 0) { - _writer = new StreamWriter(stream); - _writer.NewLine = "\r\n"; - _writer.AutoFlush = true; + _writer = new StreamWriter(stream) {NewLine = "\r\n", AutoFlush = true}; } FireConnected(); @@ -97,7 +95,7 @@ public override void Connect() if (MaxData > 0) { - using (BinaryReader reader = new BinaryReader(stream)) + using (var reader = new BinaryReader(stream)) { Int64 missing = MaxData; Int64 max = Settings.Instance.DownloadPerReadBytes; @@ -122,12 +120,11 @@ public override void Connect() } catch (IOException ex) { - if (ex.InnerException != null && ex.InnerException is SocketException) + if (ex.InnerException is SocketException) { - SocketException exi = (SocketException) ex.InnerException; + var exi = (SocketException) ex.InnerException; _errorCode = (SocketErrorCode) exi.ErrorCode; _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + (_errorCode), ex); - break; } else { @@ -151,7 +148,7 @@ public override void Connect() _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received"); break; } - } while (data != null && missing > 0); + } while (missing > 0); } } @@ -161,7 +158,7 @@ public override void Connect() else { - using (StreamReader reader = new StreamReader(stream)) + using (var reader = new StreamReader(stream)) { int failCounter = 0; string data = ""; @@ -185,11 +182,10 @@ public override void Connect() { if (ex.InnerException is SocketException) { - SocketException exi = (SocketException) ex.InnerException; + var exi = (SocketException) ex.InnerException; _errorCode = (SocketErrorCode) exi.ErrorCode; // we dont need to log this kind of exception, because it is just normal //Log("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + ((SocketErrorCode)exi.ErrorCode), LogLevel.Exception); - break; } else { @@ -219,12 +215,9 @@ public override void Connect() _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received"); break; } - else - { - data = ""; - } + data = ""; } - } while (data != null); + } while (true); } } @@ -297,19 +290,25 @@ public override void SendData(string aData) { if (ex.InnerException is SocketException) { - SocketException exi = (SocketException) ex.InnerException; + var exi = (SocketException) ex.InnerException; _errorCode = (SocketErrorCode) exi.ErrorCode; // we dont need to log this kind of exception, because it is just normal //Log("SendData(" + aData + ") : " + ((SocketErrorCode)exi.ErrorCode), LogLevel.Exception); } else { - _log.Fatal("SendData(" + aData + ") ", ex); + if (_log != null) + { + _log.Fatal("SendData(" + aData + ") ", ex); + } } } catch (Exception ex) { - _log.Fatal("SendData(" + aData + ") ", ex); + if (_log != null) + { + _log.Fatal("SendData(" + aData + ") ", ex); + } } } } diff --git a/Server/Helper/FileActions.cs b/Server/Helper/FileActions.cs index 3711ffe..53bfc6c 100644 --- a/Server/Helper/FileActions.cs +++ b/Server/Helper/FileActions.cs @@ -41,7 +41,7 @@ public class FileActions { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Core.Servers _servers; @@ -100,7 +100,7 @@ File File(string aName, Int64 aSize) // lets check if the directory is still on the harddisk if (!Directory.Exists(Settings.Instance.TempPath + file.TmpPath)) { - _log.Warn("File(" + aName + ", " + aSize + ") directory " + file.TmpPath + " is missing "); + Log.Warn("File(" + aName + ", " + aSize + ") directory " + file.TmpPath + " is missing "); RemoveFile(file); break; } @@ -129,7 +129,7 @@ public File NewFile(string aName, Int64 aSize) } catch (Exception ex) { - _log.Fatal("NewFile()", ex); + Log.Fatal("NewFile()", ex); tFile = null; } } @@ -143,7 +143,7 @@ public File NewFile(string aName, Int64 aSize) /// public void RemoveFile(File aFile) { - _log.Info("RemoveFile(" + aFile.Name + ", " + aFile.Size + ")"); + Log.Info("RemoveFile(" + aFile.Name + ", " + aFile.Size + ")"); // check if this file is currently downloaded bool skip = false; @@ -182,13 +182,9 @@ public FilePart Part(File aFile, Int64 aSize) FilePart returnPart = null; IEnumerable parts = aFile.Parts; - if (parts.Count() == 0 && aSize == 0) + if (!parts.Any() && aSize == 0) { - returnPart = new FilePart(); - returnPart.StartSize = aSize; - returnPart.CurrentSize = aSize; - returnPart.StopSize = aFile.Size; - returnPart.Checked = true; + returnPart = new FilePart {StartSize = aSize, CurrentSize = aSize, StopSize = aFile.Size, Checked = true}; aFile.Add(returnPart); } else @@ -214,10 +210,7 @@ public FilePart Part(File aFile, Int64 aSize) // split the part if (part.StartSize < aSize && part.StopSize > aSize) { - returnPart = new FilePart(); - returnPart.StartSize = aSize; - returnPart.CurrentSize = aSize; - returnPart.StopSize = part.StopSize; + returnPart = new FilePart {StartSize = aSize, CurrentSize = aSize, StopSize = part.StopSize}; // update previous part part.StopSize = aSize; @@ -238,7 +231,7 @@ public FilePart Part(File aFile, Int64 aSize) /// public void RemovePart(File aFile, FilePart aPart) { - _log.Info("RemovePart(" + aFile.Name + ", " + aFile.Size + ", " + aPart.StartSize + ")"); + Log.Info("RemovePart(" + aFile.Name + ", " + aFile.Size + ", " + aPart.StartSize + ")"); IEnumerable parts = aFile.Parts; foreach (FilePart part in parts) @@ -248,7 +241,7 @@ public void RemovePart(File aFile, FilePart aPart) part.StopSize = aPart.StopSize; if (part.State == FilePart.States.Ready) { - _log.Info("RemovePart(" + aFile.Name + ", " + aFile.Size + ", " + aPart.StartSize + ") expanding part " + part.StartSize + " to " + + Log.Info("RemovePart(" + aFile.Name + ", " + aFile.Size + ", " + aPart.StartSize + ") expanding part " + part.StartSize + " to " + aPart.StopSize); part.State = FilePart.States.Closed; part.Commit(); @@ -258,7 +251,7 @@ public void RemovePart(File aFile, FilePart aPart) } aFile.Remove(aPart); - if (aFile.Parts.Count() == 0) + if (!aFile.Parts.Any()) { RemoveFile(aFile); } @@ -277,7 +270,7 @@ public void RemovePart(File aFile, FilePart aPart) /// /// /// - /// -1 if there is no part, 0 < = if there is a new part available + /// -1 if there is no part, 0 or greater if there is a new part available public Int64 NextAvailablePartSize(string aName, Int64 aSize) { File tFile = File(aName, aSize); @@ -288,7 +281,7 @@ public Int64 NextAvailablePartSize(string aName, Int64 aSize) Int64 nextSize = -1; IEnumerable parts = tFile.Parts; - if (parts.Count() == 0) + if (!parts.Any()) { nextSize = 0; } @@ -345,8 +338,11 @@ public Int64 NextAvailablePartSize(string aName, Int64 aSize) /// void CheckNextReferenceBytes(object aObj) { - PartBytesObject pbo = aObj as PartBytesObject; - CheckNextReferenceBytes(pbo.Part, pbo.Bytes, true); + var pbo = aObj as PartBytesObject; + if (pbo != null) + { + CheckNextReferenceBytes(pbo.Part, pbo.Bytes, true); + } } /// @@ -369,7 +365,7 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) { File tFile = aPart.Parent; IEnumerable parts = tFile.Parts; - _log.Info("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ", " + aPart.StopSize + ") with " + parts.Count() + + Log.Info("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ", " + aPart.StopSize + ") with " + parts.Count() + " parts called"); foreach (FilePart part in parts) @@ -389,7 +385,7 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) { if (!part.StartReference.IsEqualWith(aBytes)) { - _log.Warn("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") removing next part " + part.StartSize); + Log.Warn("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") removing next part " + part.StartSize); part.Packet.Enabled = false; part.Packet.Commit(); RemovePart(tFile, part); @@ -397,7 +393,7 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) } else { - _log.Info("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") part " + part.StartSize + " is checked"); + Log.Info("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") part " + part.StartSize + " is checked"); part.Checked = true; part.Commit(); return 0; @@ -405,13 +401,13 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) } else { - _log.Error("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") part " + part.StartSize + + Log.Error("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") part " + part.StartSize + " is open, but has no packet"); return 0; } } // it is already ready - else if (part.State == FilePart.States.Closed || part.State == FilePart.States.Ready) + if (part.State == FilePart.States.Closed || part.State == FilePart.States.Ready) { string fileName = CompletePath(part); try @@ -422,7 +418,7 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) if (!bytes.IsEqualWith(aBytes)) { - _log.Warn("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") removing closed part " + part.StartSize); + Log.Warn("CheckNextReferenceBytes(" + tFile.Name + ", " + tFile.Size + ", " + aPart.StartSize + ") removing closed part " + part.StartSize); RemovePart(tFile, part); return part.StopSize; } @@ -437,7 +433,7 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) if (part.StopSize < tFile.Size) { FileStream fileStream = System.IO.File.Open(fileName, FileMode.Open, FileAccess.ReadWrite); - BinaryReader fileReader = new BinaryReader(fileStream); + var fileReader = new BinaryReader(fileStream); // extract the needed refernce bytes fileStream.Seek(-Settings.Instance.FileRollbackCheckBytes, SeekOrigin.End); bytes = fileReader.ReadBytes(Settings.Instance.FileRollbackCheckBytes); @@ -461,14 +457,14 @@ Int64 CheckNextReferenceBytes(FilePart aPart, byte[] aBytes, bool aThreaded) } catch (Exception ex) { - _log.Fatal( + Log.Fatal( "CheckNextReferenceBytes(" + aPart.Parent.Name + ", " + aPart.Parent.Size + ", " + aPart.StartSize + ") handling part " + part.StartSize + "", ex); } } else { - _log.Error("CheckNextReferenceBytes(" + aPart.Parent.Name + ", " + aPart.Parent.Size + ", " + aPart.StartSize + + Log.Error("CheckNextReferenceBytes(" + aPart.Parent.Name + ", " + aPart.Parent.Size + ", " + aPart.StartSize + ") do not know what to do with part " + part.StartSize); } @@ -490,8 +486,8 @@ public void CheckFile(File aFile) { lock (aFile.Lock) { - _log.Info("CheckFile(" + aFile.Name + ")"); - if (aFile.Parts.Count() == 0) + Log.Info("CheckFile(" + aFile.Name + ")"); + if (!aFile.Parts.Any()) { return; } @@ -503,7 +499,7 @@ public void CheckFile(File aFile) if (part.State != FilePart.States.Ready) { complete = false; - _log.Info("CheckFile(" + aFile.Name + ") part " + part.StartSize + " is not complete"); + Log.Info("CheckFile(" + aFile.Name + ") part " + part.StartSize + " is not complete"); break; } } @@ -522,130 +518,133 @@ public void CheckFile(File aFile) /// void JoinCompleteParts(object aObject) { - File tFile = aObject as File; - lock (tFile.Lock) + var tFile = aObject as File; + if (tFile != null) { - _log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") starting"); + lock (tFile.Lock) + { + Log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") starting"); - #region DISABLE ALL MATCHING PACKETS + #region DISABLE ALL MATCHING PACKETS - // TODO remove all CD* packets if a multi packet was downloaded + // TODO remove all CD* packets if a multi packet was downloaded - string fileName = Core.Helper.ShrinkFileName(tFile.Name, 0); + string fileName = Core.Helper.ShrinkFileName(tFile.Name, 0); - foreach (Core.Server tServ in _servers.All) - { - foreach (Channel tChan in tServ.Channels) + foreach (Core.Server tServ in _servers.All) { - if (tChan.Connected) + foreach (Channel tChan in tServ.Channels) { - foreach (Bot tBot in tChan.Bots) + if (tChan.Connected) { - foreach (Packet tPack in tBot.Packets) + foreach (Bot tBot in tChan.Bots) { - if (tPack.Enabled && - (Core.Helper.ShrinkFileName(tPack.RealName, 0).EndsWith(fileName) || Core.Helper.ShrinkFileName(tPack.Name, 0).EndsWith(fileName))) + foreach (Packet tPack in tBot.Packets) { - _log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") disabling packet #" + tPack.Id + " (" + tPack.Name + ") from " + - tPack.Parent.Name); - tPack.Enabled = false; - tPack.Commit(); + if (tPack.Enabled && + (Core.Helper.ShrinkFileName(tPack.RealName, 0).EndsWith(fileName) || Core.Helper.ShrinkFileName(tPack.Name, 0).EndsWith(fileName))) + { + Log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") disabling packet #" + tPack.Id + " (" + tPack.Name + ") from " + + tPack.Parent.Name); + tPack.Enabled = false; + tPack.Commit(); + } } } } } } - } - #endregion + #endregion - if (tFile.Parts.Count() == 0) - { - return; - } + if (!tFile.Parts.Any()) + { + return; + } - bool error = true; - bool deleteOnError = true; - IEnumerable parts = tFile.Parts; - string fileReady = Settings.Instance.ReadyPath + tFile.Name; + bool error = true; + bool deleteOnError = true; + IEnumerable parts = tFile.Parts; + string fileReady = Settings.Instance.ReadyPath + tFile.Name; - try - { - FileStream stream = System.IO.File.Open(fileReady, FileMode.Create, FileAccess.Write); - BinaryWriter writer = new BinaryWriter(stream); - foreach (FilePart part in parts) + try { - try + FileStream stream = System.IO.File.Open(fileReady, FileMode.Create, FileAccess.Write); + var writer = new BinaryWriter(stream); + foreach (FilePart part in parts) { - BinaryReader reader = FileSystem.OpenFileReadable(CompletePath(part)); - byte[] data; - while ((data = reader.ReadBytes(Settings.Instance.DownloadPerReadBytes)).Length > 0) + try { - writer.Write(data); - writer.Flush(); + BinaryReader reader = FileSystem.OpenFileReadable(CompletePath(part)); + byte[] data; + while ((data = reader.ReadBytes(Settings.Instance.DownloadPerReadBytes)).Length > 0) + { + writer.Write(data); + writer.Flush(); + } + reader.Close(); } - reader.Close(); - } - catch (Exception ex) - { - _log.Fatal("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") handling part " + part.StartSize + "", ex); - // dont delete the source if the disk is full! - // taken from http://www.dotnetspider.com/forum/101158-Disk-full-C.aspx - // TODO this doesnt work :( - int hresult = (int) ex.GetType().GetField("_HResult", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex); - if ((hresult & 0xFFFF) == 112L) + catch (Exception ex) { - deleteOnError = false; + Log.Fatal("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") handling part " + part.StartSize + "", ex); + // dont delete the source if the disk is full! + // taken from http://www.dotnetspider.com/forum/101158-Disk-full-C.aspx + // TODO this doesnt work :( + var hresult = (int) ex.GetType().GetField("_HResult", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(ex); + if ((hresult & 0xFFFF) == 112L) + { + deleteOnError = false; + } + break; } - break; } - } - writer.Close(); - stream.Close(); + writer.Close(); + stream.Close(); - Int64 size = new FileInfo(fileReady).Length; - if (size == tFile.Size) - { - FileSystem.DeleteDirectory(Settings.Instance.TempPath + tFile.TmpPath); - _log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") file build"); + Int64 size = new FileInfo(fileReady).Length; + if (size == tFile.Size) + { + FileSystem.DeleteDirectory(Settings.Instance.TempPath + tFile.TmpPath); + Log.Info("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") file build"); - // statistics - Statistic.Instance.Increase(StatisticType.FilesCompleted); + // statistics + Statistic.Instance.Increase(StatisticType.FilesCompleted); - // the file is complete and enabled - tFile.Enabled = true; - error = false; + // the file is complete and enabled + tFile.Enabled = true; + error = false; - // maybee clear it - if (Settings.Instance.ClearReadyDownloads) - { - RemoveFile(tFile); + // maybee clear it + if (Settings.Instance.ClearReadyDownloads) + { + RemoveFile(tFile); + } + + // great, all went right, so lets check what we can do with the file + new Thread(() => HandleFile(fileReady)).Start(); } + else + { + Log.Error("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") filesize is not the same: " + size); - // great, all went right, so lets check what we can do with the file - new Thread(() => HandleFile(fileReady)).Start(); + // statistics + Statistic.Instance.Increase(StatisticType.FilesBroken); + } } - else + catch (Exception ex) { - _log.Error("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") filesize is not the same: " + size); + Log.Fatal("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") make", ex); // statistics Statistic.Instance.Increase(StatisticType.FilesBroken); } - } - catch (Exception ex) - { - _log.Fatal("JoinCompleteParts(" + tFile.Name + ", " + tFile.Size + ") make", ex); - // statistics - Statistic.Instance.Increase(StatisticType.FilesBroken); - } - - if (error && deleteOnError) - { - // the creation was not successfull, so delete the files and parts - FileSystem.DeleteFile(fileReady); - RemoveFile(tFile); + if (error && deleteOnError) + { + // the creation was not successfull, so delete the files and parts + FileSystem.DeleteFile(fileReady); + RemoveFile(tFile); + } } } } @@ -658,11 +657,11 @@ void HandleFile(string aFile) { if (!string.IsNullOrEmpty(aFile)) { - string folder = System.IO.Path.GetDirectoryName(aFile); - string file = System.IO.Path.GetFileName(aFile); - string fileName = System.IO.Path.GetFileNameWithoutExtension(aFile); - string fileExtension = System.IO.Path.GetExtension(aFile); - if (fileExtension.StartsWith(".")) + string folder = Path.GetDirectoryName(aFile); + string file = Path.GetFileName(aFile); + string fileName = Path.GetFileNameWithoutExtension(aFile); + string fileExtension = Path.GetExtension(aFile); + if (fileExtension != null && fileExtension.StartsWith(".")) { fileExtension = fileExtension.Substring(1); } @@ -679,7 +678,7 @@ void HandleFile(string aFile) } catch (Exception ex) { - _log.Fatal("RunFileHandler(" + aFile + ") Regex Error (" + handler.Regex + ")", ex); + Log.Fatal("RunFileHandler(" + aFile + ") Regex Error (" + handler.Regex + ")", ex); } } } @@ -699,9 +698,7 @@ void RunFileHandlerProcess(FileHandlerProcess aHandler, string aPath, string aFo arguments = arguments.Replace("%FILENAME%", aFileName); arguments = arguments.Replace("%EXTENSION%", aFileExtension); - Process p = new Process(); - p.Command = aHandler.Command; - p.Arguments = arguments; + var p = new Process {Command = aHandler.Command, Arguments = arguments}; if (p.Run()) { diff --git a/Server/Helper/FileHandler.cs b/Server/Helper/FileHandler.cs index 6062477..2583f70 100644 --- a/Server/Helper/FileHandler.cs +++ b/Server/Helper/FileHandler.cs @@ -21,7 +21,7 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -namespace XG.Server +namespace XG.Server.Helper { public class FileHandler { diff --git a/Server/Helper/FileHandlerProcess.cs b/Server/Helper/FileHandlerProcess.cs index 8e1847d..e509ba1 100644 --- a/Server/Helper/FileHandlerProcess.cs +++ b/Server/Helper/FileHandlerProcess.cs @@ -21,7 +21,7 @@ // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // -namespace XG.Server +namespace XG.Server.Helper { public class FileHandlerProcess { diff --git a/Server/Helper/FileSystem.cs b/Server/Helper/FileSystem.cs index f23bc90..8848da1 100644 --- a/Server/Helper/FileSystem.cs +++ b/Server/Helper/FileSystem.cs @@ -31,7 +31,7 @@ namespace XG.Server.Helper { public class FileSystem { - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// /// Moves a file @@ -50,7 +50,7 @@ public static bool MoveFile(string aNameOld, string aNameNew) } catch (Exception ex) { - _log.Fatal("MoveFile('" + aNameOld + "', '" + aNameNew + "') ", ex); + Log.Fatal("MoveFile('" + aNameOld + "', '" + aNameNew + "') ", ex); return false; } } @@ -73,7 +73,7 @@ public static bool DeleteFile(string aName) } catch (Exception ex) { - _log.Fatal("DeleteFile(" + aName + ") ", ex); + Log.Fatal("DeleteFile(" + aName + ") ", ex); return false; } } @@ -96,7 +96,7 @@ public static bool DeleteDirectory(string aName) } catch (Exception ex) { - _log.Fatal("DeleteDirectory(" + aName + ") ", ex); + Log.Fatal("DeleteDirectory(" + aName + ") ", ex); return false; } } @@ -121,7 +121,7 @@ public static string[] ListDirectory(string aDir) /// file list public static string[] ListDirectory(string aDir, string aSearch) { - string[] files = new string[] {}; + var files = new string[] {}; try { files = aSearch == null ? Directory.GetFiles(aDir) : Directory.GetFiles(aDir, aSearch); @@ -129,7 +129,7 @@ public static string[] ListDirectory(string aDir, string aSearch) } catch (Exception ex) { - _log.Fatal("ListDirectory('" + aDir + "', '" + aSearch + "') ", ex); + Log.Fatal("ListDirectory('" + aDir + "', '" + aSearch + "') ", ex); } return files; } @@ -148,20 +148,22 @@ public static BinaryReader OpenFileReadable(string aFile) public static string ReadFile(string aFile) { - string str = ""; - if (File.Exists(aFile)) { try { - StreamReader reader = new StreamReader(aFile); - str = reader.ReadToEnd(); + var reader = new StreamReader(aFile); + string str = reader.ReadToEnd(); reader.Close(); + return str; + } + catch (Exception) + { + return ""; } - catch (Exception) {} } - return str; + return ""; } } } diff --git a/Server/Helper/Process.cs b/Server/Helper/Process.cs index db3f79c..cdbde2c 100644 --- a/Server/Helper/Process.cs +++ b/Server/Helper/Process.cs @@ -33,7 +33,7 @@ public class Process { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public string Command { get; set; } public string Arguments { get; set; } @@ -50,14 +50,19 @@ public bool Run() try { - System.Diagnostics.Process p = new System.Diagnostics.Process(); - p.StartInfo.FileName = Command; - p.StartInfo.Arguments = Arguments; - p.StartInfo.CreateNoWindow = true; - p.StartInfo.UseShellExecute = false; - p.StartInfo.RedirectStandardInput = true; - p.StartInfo.RedirectStandardOutput = true; - p.StartInfo.RedirectStandardError = true; + var p = new System.Diagnostics.Process + { + StartInfo = + { + FileName = Command, + Arguments = Arguments, + CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; p.OutputDataReceived += OutputDataReceived; p.ErrorDataReceived += ErrorDataReceived; @@ -77,13 +82,13 @@ public bool Run() } catch (Exception ex) { - _log.Fatal("Run(" + Command + ", " + Arguments + ")", ex); + Log.Fatal("Run(" + Command + ", " + Arguments + ")", ex); result = false; } finally { - _log.Info("Run(" + Command + ", " + Arguments + ") Output: " + Output); - _log.Info("Run(" + Command + ", " + Arguments + ") Error: " + Error); + Log.Info("Run(" + Command + ", " + Arguments + ") Output: " + Output); + Log.Info("Run(" + Command + ", " + Arguments + ") Error: " + Error); if (!string.IsNullOrEmpty(Error)) { diff --git a/Server/Irc/AParser.cs b/Server/Irc/AParser.cs index 3eb9a76..ed83909 100644 --- a/Server/Irc/AParser.cs +++ b/Server/Irc/AParser.cs @@ -38,9 +38,9 @@ public abstract class AParser { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - protected const string MAGICSTRING = @"((\*|:){2,3}|->|<-|)"; + protected const string Magicstring = @"((\*|:){2,3}|->|<-|)"; #endregion @@ -155,7 +155,7 @@ public void ParseData(Core.Server aServer, string aRawData) else if (aRawData.StartsWith("PING")) { - _log.Info("ParseData() PING"); + Log.Info("ParseData() PING"); FireSendData(aServer, "PONG " + aRawData.Split(':')[1]); } @@ -165,7 +165,7 @@ public void ParseData(Core.Server aServer, string aRawData) else if (aRawData.StartsWith("ERROR")) { - _log.Error("ParseData() ERROR: " + aRawData); + Log.Error("ParseData() ERROR: " + aRawData); } #endregion diff --git a/Server/Irc/IntValue.cs b/Server/Irc/IntValue.cs index 1d12c74..2b180e2 100644 --- a/Server/Irc/IntValue.cs +++ b/Server/Irc/IntValue.cs @@ -37,13 +37,13 @@ public class IntValue : AParser protected override void Parse(Core.Server aServer, string aRawData, string aMessage, string[] aCommands) { - ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); + ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); Bot tBot = aServer.Bot(aCommands[0].Split('!')[0]); Channel tChan = aServer.Channel(aCommands[2]); string tComCodeStr = aCommands[1]; - int tComCode = 0; + int tComCode; if (int.TryParse(tComCodeStr, out tComCode)) { switch (tComCode) @@ -78,7 +78,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess } if (addChan) { - _log.Info("Parse() auto adding channel " + chanName); + log.Info("Parse() auto adding channel " + chanName); aServer.AddChannel(chanName); } } @@ -105,7 +105,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess { tBot.State = Bot.States.Idle; } - _log.Info("Parse() bot " + tBot.Name + " is online"); + log.Info("Parse() bot " + tBot.Name + " is online"); tBot.Commit(); FireRequestFromBot(aServer, tBot); } @@ -123,7 +123,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess { tChan.ErrorCode = 0; tChan.Connected = true; - _log.Info("Parse() joined channel " + tChan.Name); + log.Info("Parse() joined channel " + tChan.Name); } // statistics @@ -136,7 +136,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess case 376: // RPL_ENDOFMOTD case 422: // ERR_NOMOTD - _log.Info("Parse() really connected"); + log.Info("Parse() really connected"); aServer.Connected = true; aServer.Commit(); foreach (Channel chan in aServer.Channels) @@ -185,7 +185,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess { tChan.ErrorCode = tComCode; tChan.Connected = false; - _log.Warn("Parse() could not join channel " + tChan.Name + ": " + tComCode); + log.Warn("Parse() could not join channel " + tChan.Name + ": " + tComCode); } // statistics @@ -206,7 +206,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess { tChan.ErrorCode = tComCode; tChan.Connected = false; - _log.Warn("Parse() could not join channel " + tChan.Name + ": " + tComCode); + log.Warn("Parse() could not join channel " + tChan.Name + ": " + tComCode); FireCreateTimer(aServer, tChan, tComCode == 471 || tComCode == 485 ? Settings.Instance.ChannelWaitTime : Settings.Instance.ChannelWaitTimeLong, false); } @@ -229,7 +229,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess } else { - _log.Error("Parse() Irc code " + tComCodeStr + " could not be parsed. (" + aRawData + ")"); + log.Error("Parse() Irc code " + tComCodeStr + " could not be parsed. (" + aRawData + ")"); } } diff --git a/Server/Irc/Nickserv.cs b/Server/Irc/Nickserv.cs index 82f21da..70a36c0 100644 --- a/Server/Irc/Nickserv.cs +++ b/Server/Irc/Nickserv.cs @@ -37,25 +37,25 @@ public class Nickserv : AParser protected override void Parse(Core.Server aServer, string aRawData, string aMessage, string[] aCommands) { - ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); + ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); string tUserName = aCommands[0].Split('!')[0]; if (Matches(aMessage, ".*Password incorrect.*")) { - _log.Error("password wrong"); + log.Error("password wrong"); return; } if (Matches(aMessage, ".*(The given email address has reached it's usage limit of 1 user|This nick is being held for a registered user).*")) { - _log.Error("nick or email already used"); + log.Error("nick or email already used"); return; } if (Matches(aMessage, ".*Your nick isn't registered.*")) { - _log.Info("registering nick"); + log.Info("registering nick"); if (Settings.Instance.AutoRegisterNickserv && Settings.Instance.IrcPasswort != "" && Settings.Instance.IrcRegisterEmail != "") { FireSendData(aServer, tUserName + " register " + Settings.Instance.IrcPasswort + " " + Settings.Instance.IrcRegisterEmail); @@ -89,7 +89,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess } else { - _log.Error("nick is already registered and i got no password"); + log.Error("nick is already registered and i got no password"); } return; } @@ -103,25 +103,25 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (Matches(aMessage, ".*Please try again with a more obscure password.*")) { - _log.Error("password is unsecure"); + log.Error("password is unsecure"); return; } if (Matches(aMessage, ".*(A passcode has been sent to|This nick is awaiting an e-mail verification code).*")) { - _log.Error("confirm email"); + log.Error("confirm email"); return; } if (Matches(aMessage, ".*Nickname .*registered under your account.*")) { - _log.Info("nick registered succesfully"); + log.Info("nick registered succesfully"); return; } if (Matches(aMessage, ".*Password accepted.*")) { - _log.Info("password accepted"); + log.Info("password accepted"); return; } @@ -131,22 +131,22 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (tMatch.Success) { FireSendData(aServer, "/msg NickServ confirm " + tMatch.Groups["code"]); - _log.Info("Parse(" + aRawData + ") - confirming nickserv"); + log.Info("Parse(" + aRawData + ") - confirming nickserv"); } else { - _log.Error("Parse(" + aRawData + ") - cant find nickserv code"); + log.Error("Parse(" + aRawData + ") - cant find nickserv code"); } return; } if (Matches(aMessage, ".*Your password is.*")) { - _log.Info("password accepted"); + log.Info("password accepted"); return; } - _log.Error("unknow command: " + aRawData); + log.Error("unknow command: " + aRawData); } #endregion diff --git a/Server/Irc/Notice.cs b/Server/Irc/Notice.cs index e16a9f7..0c09ecf 100644 --- a/Server/Irc/Notice.cs +++ b/Server/Irc/Notice.cs @@ -37,7 +37,7 @@ public class Notice : AParser protected override void Parse(Core.Server aServer, string aRawData, string aMessage, string[] aCommands) { - ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); + ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + aServer.Name + ")"); string tUserName = aCommands[0].Split('!')[0]; @@ -45,30 +45,29 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (tBot != null) { bool isParsed = false; - Match tMatch = null; - Match tMatch1 = null; - Match tMatch2 = null; - Match tMatch3 = null; - Match tMatch4 = null; - Match tMatch5 = null; - - int valueInt = 0; + Match tMatch; + Match tMatch1; + Match tMatch2 ; + Match tMatch3; + Match tMatch4; + + int valueInt; aMessage = ClearString(aMessage); - //double valueDouble = 0; + //double valueDouble; #region ALL SLOTS FULL / ADDING TO QUEUE - if (!isParsed) + if (true) { tMatch1 = Regex.Match(aMessage, - "(" + MAGICSTRING + + "(" + Magicstring + " All Slots Full, |)Added you to the main queue (for pack ([0-9]+) \\(\".*\"\\) |).*in positi(o|0)n (?[0-9]+)\\. To Remove you(r|)self at a later time .*", RegexOptions.IgnoreCase); tMatch2 = Regex.Match(aMessage, "Queueing you for pack [0-9]+ \\(.*\\) in slot (?[0-9]+)/(?[0-9]+)\\. To remove you(r|)self from the queue, type: .*\\. To check your position in the queue, type: .*\\. Estimated time remaining in queue: (?[0-9]+) days, (?[0-9]+) hours, (?[0-9]+) minutes", RegexOptions.IgnoreCase); tMatch3 = Regex.Match(aMessage, - "(" + MAGICSTRING + + "(" + Magicstring + " |)Es laufen bereits genug .bertragungen, Du bist jetzt in der Warteschlange f.r Datei [0-9]+ \\(.*\\) in Position (?[0-9]+)\\. Wenn Du sp.ter Abbrechen willst schreibe .*", RegexOptions.IgnoreCase); if (tMatch1.Success || tMatch2.Success || tMatch3.Success) @@ -120,7 +119,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (!isParsed) { - tMatch = Regex.Match(aMessage, MAGICSTRING + " Removed From Queue: .*", RegexOptions.IgnoreCase); + tMatch = Regex.Match(aMessage, Magicstring + " Removed From Queue: .*", RegexOptions.IgnoreCase); if (tMatch.Success) { isParsed = true; @@ -138,11 +137,10 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (!isParsed) { - tMatch1 = Regex.Match(aMessage, MAGICSTRING + " Die Nummer der Datei ist ung.ltig", RegexOptions.IgnoreCase); - tMatch2 = Regex.Match(aMessage, MAGICSTRING + " Invalid Pack Number, Try Again", RegexOptions.IgnoreCase); + tMatch1 = Regex.Match(aMessage, Magicstring + " Die Nummer der Datei ist ung.ltig", RegexOptions.IgnoreCase); + tMatch2 = Regex.Match(aMessage, Magicstring + " Invalid Pack Number, Try Again", RegexOptions.IgnoreCase); if (tMatch1.Success || tMatch2.Success) { - tMatch = tMatch1.Success ? tMatch1 : tMatch2; isParsed = true; Packet tPack = tBot.OldestActivePacket(); if (tPack != null) @@ -156,7 +154,7 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess tBot.RemovePacket(pack); } } - _log.Error("Parse() invalid packetnumber from " + tBot.Name); + log.Error("Parse() invalid packetnumber from " + tBot.Name); } } @@ -166,8 +164,8 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (!isParsed) { - tMatch1 = Regex.Match(aMessage, MAGICSTRING + " You already requested that pack(.*|)", RegexOptions.IgnoreCase); - tMatch2 = Regex.Match(aMessage, MAGICSTRING + " Du hast diese Datei bereits angefordert(.*|)", RegexOptions.IgnoreCase); + tMatch1 = Regex.Match(aMessage, Magicstring + " You already requested that pack(.*|)", RegexOptions.IgnoreCase); + tMatch2 = Regex.Match(aMessage, Magicstring + " Du hast diese Datei bereits angefordert(.*|)", RegexOptions.IgnoreCase); if (tMatch1.Success || tMatch2.Success) { isParsed = true; @@ -185,12 +183,12 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (!isParsed) { tMatch1 = Regex.Match(aMessage, "Denied, You already have ([0-9]+) item(s|) queued, Try Again Later", RegexOptions.IgnoreCase); - tMatch2 = Regex.Match(aMessage, MAGICSTRING + " All Slots Full, Denied, You already have that item queued\\.", RegexOptions.IgnoreCase); + tMatch2 = Regex.Match(aMessage, Magicstring + " All Slots Full, Denied, You already have that item queued\\.", RegexOptions.IgnoreCase); tMatch3 = Regex.Match(aMessage, "You are already receiving or are queued for the maximum number of packs .*", RegexOptions.IgnoreCase); tMatch4 = Regex.Match(aMessage, "Du hast max\\. ([0-9]+) transfer auf einmal, Du bist jetzt in der Warteschlange f.r Datei .*", RegexOptions.IgnoreCase); - tMatch5 = Regex.Match(aMessage, "Es laufen bereits genug .bertragungen, abgewiesen, Du hast diese Datei bereits in der Warteschlange\\.", - RegexOptions.IgnoreCase); + Match tMatch5 = Regex.Match(aMessage, "Es laufen bereits genug .bertragungen, abgewiesen, Du hast diese Datei bereits in der Warteschlange\\.", + RegexOptions.IgnoreCase); if (tMatch1.Success || tMatch2.Success || tMatch3.Success || tMatch4.Success || tMatch5.Success) { isParsed = true; @@ -216,11 +214,11 @@ protected override void Parse(Core.Server aServer, string aRawData, string aMess if (!isParsed) { tMatch1 = Regex.Match(aMessage, - MAGICSTRING + + Magicstring + " You have a DCC pending, Set your client to receive the transfer\\. ((Type .*|Send XDCC CANCEL) to abort the transfer\\. |)\\((? public void TriggerTimerRun() { - List remove = new List(); + var remove = new List(); foreach (var kvp in _timedObjects) { DateTime time = kvp.Value; diff --git a/Server/Servers.cs b/Server/Servers.cs index dc1f7a4..7919a57 100644 --- a/Server/Servers.cs +++ b/Server/Servers.cs @@ -51,7 +51,7 @@ public class Servers { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Parser _ircParser; @@ -109,15 +109,13 @@ public void ServerConnect(Core.Server aServer) { if (!_servers.ContainsKey(aServer)) { - ServerConnection con = new ServerConnection(); - con.FileActions = FileActions; - con.Server = aServer; - con.IrcParser = _ircParser; - - con.Connection = new Connection.Connection(); - con.Connection.Hostname = aServer.Name; - con.Connection.Port = aServer.Port; - con.Connection.MaxData = 0; + var con = new ServerConnection + { + FileActions = FileActions, + Server = aServer, + IrcParser = _ircParser, + Connection = new Connection.Connection {Hostname = aServer.Name, Port = aServer.Port, MaxData = 0} + }; _servers.Add(aServer, con); @@ -129,7 +127,7 @@ public void ServerConnect(Core.Server aServer) } else { - _log.Error("ConnectServer(" + aServer.Name + ") server is already in the dictionary"); + Log.Error("ConnectServer(" + aServer.Name + ") server is already in the dictionary"); } } @@ -155,7 +153,7 @@ public void ServerDisconnect(Core.Server aServer) } else { - _log.Error("DisconnectServer(" + aServer.Name + ") server is not in the dictionary"); + Log.Error("DisconnectServer(" + aServer.Name + ") server is not in the dictionary"); } } @@ -208,34 +206,31 @@ void ServerDisconnected(Core.Server aServer, SocketErrorCode aValue) } else { - _log.Error("ServerConnectionDisconnected(" + aServer.Name + ", " + aValue + ") server is not in the dictionary"); + Log.Error("ServerConnectionDisconnected(" + aServer.Name + ", " + aValue + ") server is not in the dictionary"); } } void ServerReconnect(object aServer) { - Core.Server tServer = aServer as Core.Server; + var tServer = aServer as Core.Server; - if (_servers.ContainsKey(tServer)) + if (tServer != null && _servers.ContainsKey(tServer)) { ServerConnection con = _servers[tServer]; if (tServer.Enabled) { - _log.Error("ReconnectServer(" + tServer.Name + ")"); + Log.Error("ReconnectServer(" + tServer.Name + ")"); // TODO do we need a new connection here? - con.Connection = new Connection.Connection(); - con.Connection.Hostname = tServer.Name; - con.Connection.Port = tServer.Port; - con.Connection.MaxData = 0; + con.Connection = new Connection.Connection {Hostname = tServer.Name, Port = tServer.Port, MaxData = 0}; con.Connection.Connect(); } } - else + else if (tServer != null) { - _log.Error("ReconnectServer(" + tServer.Name + ") server is not in the dictionary"); + Log.Error("ReconnectServer(" + tServer.Name + ") server is not in the dictionary"); } } @@ -255,15 +250,13 @@ void BotConnect(Packet aPack, Int64 aChunk, IPAddress aIp, int aPort) { new Thread(() => { - BotConnection con = new BotConnection(); - con.FileActions = FileActions; - con.Packet = aPack; - con.StartSize = aChunk; - - con.Connection = new Connection.Connection(); - con.Connection.Hostname = aIp.ToString(); - con.Connection.Port = aPort; - con.Connection.MaxData = aPack.RealSize - aChunk; + var con = new BotConnection + { + FileActions = FileActions, + Packet = aPack, + StartSize = aChunk, + Connection = new Connection.Connection {Hostname = aIp.ToString(), Port = aPort, MaxData = aPack.RealSize - aChunk} + }; con.Connected += BotConnected; con.Disconnected += BotDisconnected; @@ -275,7 +268,7 @@ void BotConnect(Packet aPack, Int64 aChunk, IPAddress aIp, int aPort) else { // uhh - that should not happen - _log.Error("IrcParserAddDownload(" + aPack.Name + ") is already downloading"); + Log.Error("IrcParserAddDownload(" + aPack.Name + ") is already downloading"); } } @@ -316,7 +309,7 @@ void BotDisconnected(Packet aPacket, BotConnection aCon) } catch (Exception ex) { - _log.Fatal("bot_Disconnected()", ex); + Log.Fatal("bot_Disconnected()", ex); } try @@ -326,7 +319,7 @@ void BotDisconnected(Packet aPacket, BotConnection aCon) } catch (Exception ex) { - _log.Fatal("bot_Disconnected() request", ex); + Log.Fatal("bot_Disconnected() request", ex); } } } @@ -350,6 +343,8 @@ void RunTimer() Thread.Sleep(Settings.Instance.RunLoopTime * 1000); } + + // TODO break this! } #endregion diff --git a/Server/Settings.cs b/Server/Settings.cs index a923302..50d12ef 100644 --- a/Server/Settings.cs +++ b/Server/Settings.cs @@ -26,6 +26,8 @@ using System.Reflection; using System.Xml.Serialization; +using XG.Server.Helper; + using log4net; namespace XG.Server @@ -33,7 +35,7 @@ namespace XG.Server [Serializable] public class Settings { - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); static Settings _instance; @@ -80,20 +82,20 @@ static Settings Deserialize() { try { - XmlSerializer ser = new XmlSerializer(typeof (Settings)); - StreamReader sr = new StreamReader(AppDataPathStatic + "settings.xml"); - Settings settings = (Settings) ser.Deserialize(sr); + var ser = new XmlSerializer(typeof (Settings)); + var sr = new StreamReader(AppDataPathStatic + "settings.xml"); + var settings = (Settings) ser.Deserialize(sr); sr.Close(); return settings; } catch (Exception ex) { - _log.Fatal("Settings.Deserialize", ex); + Log.Fatal("Settings.Deserialize", ex); } } else { - _log.Error("Settings.Deserialize found no settings file"); + Log.Error("Settings.Deserialize found no settings file"); } return null; } @@ -102,14 +104,14 @@ static void Serialize() { try { - XmlSerializer ser = new XmlSerializer(typeof (Settings)); - StreamWriter sw = new StreamWriter(AppDataPathStatic + "settings.xml"); + var ser = new XmlSerializer(typeof (Settings)); + var sw = new StreamWriter(AppDataPathStatic + "settings.xml"); ser.Serialize(sw, _instance); sw.Close(); } catch (Exception ex) { - _log.Fatal("Settings.Serialize", ex); + Log.Fatal("Settings.Serialize", ex); } } diff --git a/Server/Statistic.cs b/Server/Statistic.cs index 46791a9..7bc5e1b 100644 --- a/Server/Statistic.cs +++ b/Server/Statistic.cs @@ -74,8 +74,8 @@ public XmlSchema GetSchema() public void ReadXml(XmlReader reader) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + var keySerializer = new XmlSerializer(typeof (TKey)); + var valueSerializer = new XmlSerializer(typeof (TValue)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); @@ -90,11 +90,11 @@ public void ReadXml(XmlReader reader) reader.ReadStartElement("item"); reader.ReadStartElement("key"); - TKey key = (TKey) keySerializer.Deserialize(reader); + var key = (TKey) keySerializer.Deserialize(reader); reader.ReadEndElement(); reader.ReadStartElement("value"); - TValue value = (TValue) valueSerializer.Deserialize(reader); + var value = (TValue) valueSerializer.Deserialize(reader); reader.ReadEndElement(); Add(key, value); @@ -107,8 +107,8 @@ public void ReadXml(XmlReader reader) public void WriteXml(XmlWriter writer) { - XmlSerializer keySerializer = new XmlSerializer(typeof (TKey)); - XmlSerializer valueSerializer = new XmlSerializer(typeof (TValue)); + var keySerializer = new XmlSerializer(typeof (TKey)); + var valueSerializer = new XmlSerializer(typeof (TValue)); foreach (TKey key in Keys) { @@ -133,43 +133,43 @@ public void WriteXml(XmlWriter writer) [Serializable] public class Statistic { - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - static readonly object locked = new object(); - static readonly XmlSerializer serializer = new XmlSerializer(typeof (Statistic)); + static readonly object Locked = new object(); + static readonly XmlSerializer Serializer = new XmlSerializer(typeof (Statistic)); [NonSerialized] - static Statistic instance; + static Statistic _instance; [NonSerialized] - static readonly object statisticLock = new object(); + static readonly object StatisticLock = new object(); - SerializableDictionary myValuesInt = new SerializableDictionary(); + SerializableDictionary _myValuesInt = new SerializableDictionary(); public SerializableDictionary ValuesInt { - get { return myValuesInt; } - set { myValuesInt = value; } + get { return _myValuesInt; } + set { _myValuesInt = value; } } - SerializableDictionary myValuesDouble = new SerializableDictionary(); + SerializableDictionary _myValuesDouble = new SerializableDictionary(); public SerializableDictionary ValuesDouble { - get { return myValuesDouble; } - set { myValuesDouble = value; } + get { return _myValuesDouble; } + set { _myValuesDouble = value; } } public static Statistic Instance { get { - if (instance == null) + if (_instance == null) { - instance = Deserialize(); + _instance = Deserialize(); Serialize(); } - return instance; + return _instance; } } @@ -177,36 +177,36 @@ static Statistic Deserialize() { if (File.Exists(Settings.Instance.AppDataPath + "statistics.xml")) { - lock (locked) + lock (Locked) { try { Stream streamRead = File.OpenRead(Settings.Instance.AppDataPath + "statistics.xml"); - Statistic statistic = (Statistic) serializer.Deserialize(streamRead); + var statistic = (Statistic) Serializer.Deserialize(streamRead); streamRead.Close(); return statistic; } catch (Exception ex) { - _log.Fatal("Statistic.Deserialize", ex); + Log.Fatal("Statistic.Deserialize", ex); } } } else { - _log.Error("Statistic.Deserialize found no settings file"); + Log.Error("Statistic.Deserialize found no settings file"); } return new Statistic(); } static void Serialize() { - lock (locked) + lock (Locked) { try { Stream streamWrite = File.Create(Settings.Instance.AppDataPath + "statistics.xml"); - serializer.Serialize(streamWrite, instance); + Serializer.Serialize(streamWrite, _instance); streamWrite.Close(); } catch (InvalidOperationException) @@ -219,7 +219,7 @@ static void Serialize() } catch (Exception ex) { - _log.Fatal("Statistic.Serialize", ex); + Log.Fatal("Statistic.Serialize", ex); } } } @@ -238,49 +238,43 @@ public void Increase(StatisticType aType) public void Increase(StatisticType aType, Int64 aValue) { - lock (statisticLock) + lock (StatisticLock) { - if (!myValuesInt.ContainsKey(aType)) + if (!_myValuesInt.ContainsKey(aType)) { - myValuesInt.Add(aType, aValue); + _myValuesInt.Add(aType, aValue); } else { - myValuesInt[aType] += aValue; + _myValuesInt[aType] += aValue; } } } public double Get(StatisticType aType) { - if (!myValuesDouble.ContainsKey(aType)) + if (!_myValuesDouble.ContainsKey(aType)) { - if (!myValuesInt.ContainsKey(aType)) + if (!_myValuesInt.ContainsKey(aType)) { return 0; } - else - { - return myValuesInt[aType]; - } - } - else - { - return myValuesDouble[aType]; + return _myValuesInt[aType]; } + return _myValuesDouble[aType]; } public void Set(StatisticType aType, double aValue) { - lock (statisticLock) + lock (StatisticLock) { - if (!myValuesDouble.ContainsKey(aType)) + if (!_myValuesDouble.ContainsKey(aType)) { - myValuesDouble.Add(aType, aValue); + _myValuesDouble.Add(aType, aValue); } else { - myValuesDouble[aType] = aValue; + _myValuesDouble[aType] = aValue; } } } diff --git a/Server/Worker/ALoopWorker.cs b/Server/Worker/ALoopWorker.cs index ea9970e..a702ce0 100644 --- a/Server/Worker/ALoopWorker.cs +++ b/Server/Worker/ALoopWorker.cs @@ -33,7 +33,7 @@ public abstract class ALoopWorker : AWorker { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public Int64 SecondsToSleep { get; set; } DateTime _last; @@ -43,7 +43,7 @@ public abstract class ALoopWorker : AWorker #region FUNCTIONS - public ALoopWorker() + protected ALoopWorker() { _last = DateTime.MinValue.ToUniversalTime(); _allowRun = true; @@ -63,7 +63,7 @@ protected override void StartRun() } catch (Exception ex) { - _log.Fatal("LoopRun()", ex); + Log.Fatal("LoopRun()", ex); } } diff --git a/Server/Worker/AWorker.cs b/Server/Worker/AWorker.cs index a866340..983a9c4 100644 --- a/Server/Worker/AWorker.cs +++ b/Server/Worker/AWorker.cs @@ -35,7 +35,7 @@ public abstract class AWorker { #region VARIABLES - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Thread _thread; @@ -176,7 +176,7 @@ public void Start() } catch (Exception ex) { - _log.Fatal("Start()", ex); + Log.Fatal("Start()", ex); } } @@ -191,7 +191,7 @@ public void Stop() } catch (Exception ex) { - _log.Fatal("Stop()", ex); + Log.Fatal("Stop()", ex); } } diff --git a/Server/Worker/BotWatchdogWorker.cs b/Server/Worker/BotWatchdogWorker.cs index 0d0101d..997402b 100644 --- a/Server/Worker/BotWatchdogWorker.cs +++ b/Server/Worker/BotWatchdogWorker.cs @@ -22,7 +22,6 @@ // using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; @@ -34,21 +33,21 @@ namespace XG.Server.Worker { public class BotWatchdogWorker : ALoopWorker { - static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); + static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region AWorker protected override void LoopRun() { - IEnumerable tBots = from server in Servers.All - where server.Connected - from channel in server.Channels - where channel.Connected - from bot in channel.Bots - where - !bot.Connected && (DateTime.Now - bot.LastContact).TotalSeconds > Settings.Instance.BotOfflineTime && - bot.OldestActivePacket() == null - select bot; + Bot[] tBots = (from server in Servers.All + where server.Connected + from channel in server.Channels + where channel.Connected + from bot in channel.Bots + where + !bot.Connected && (DateTime.Now - bot.LastContact).TotalSeconds > Settings.Instance.BotOfflineTime && + bot.OldestActivePacket() == null + select bot).ToArray(); int a = tBots.Count(); foreach (Bot tBot in tBots) @@ -57,7 +56,7 @@ where channel.Connected } if (a > 0) { - _log.Info("RunBotWatchdog() removed " + a + " offline bot(s)"); + Log.Info("RunBotWatchdog() removed " + a + " offline bot(s)"); } // TODO scan for empty channels and send a "xdcc list" command to all the people in there diff --git a/Server/Worker/SnapshotWorker.cs b/Server/Worker/SnapshotWorker.cs index b050ead..79f19e7 100644 --- a/Server/Worker/SnapshotWorker.cs +++ b/Server/Worker/SnapshotWorker.cs @@ -22,7 +22,6 @@ // using System; -using System.Collections.Generic; using System.Linq; using XG.Core; @@ -35,12 +34,12 @@ public class SnapshotWorker : ALoopWorker protected override void LoopRun() { - IEnumerable servers = from server in Servers.All select server; - IEnumerable channels = from server in servers from channel in server.Channels select channel; - IEnumerable bots = from channel in channels from bot in channel.Bots select bot; - IEnumerable packets = from bot in bots from packet in bot.Packets select packet; + Core.Server[] servers = (from server in Servers.All select server).ToArray(); + Channel[] channels = (from server in servers from channel in server.Channels select channel).ToArray(); + Bot[] bots = (from channel in channels from bot in channel.Bots select bot).ToArray(); + Packet[] packets = (from bot in bots from packet in bot.Packets select packet).ToArray(); - Snapshot snap = new Snapshot(); + var snap = new Snapshot(); snap.Set(SnapshotValue.Timestamp, DateTime.Now.ToTimestamp()); snap.Set(SnapshotValue.Speed, (from file in Files.All from part in file.Parts select part.Speed).Sum());