From e4075617d07035ce9fa308f386ab06dbedda28b8 Mon Sep 17 00:00:00 2001 From: Cinder Date: Sun, 25 Sep 2016 20:36:12 -0500 Subject: [PATCH] More boring modernization --- OpenMetaverse.Utilities/RegistrationApi.cs | 107 +++--- OpenMetaverse.Utilities/Utilities.cs | 93 ++--- OpenMetaverse.Utilities/VoiceManager.cs | 358 +++++++++--------- .../VoiceManagerBlocking.cs | 45 +-- OpenMetaverseTypes/BlockingQueue.cs | 64 ++-- OpenMetaverseTypes/CRC32.cs | 2 +- OpenMetaverseTypes/CircularQueue.cs | 80 ++-- OpenMetaverseTypes/Color4.cs | 133 +++---- OpenMetaverseTypes/DoubleDictionary.cs | 35 +- OpenMetaverseTypes/Enums.cs | 2 +- OpenMetaverseTypes/ExpiringCache.cs | 77 ++-- OpenMetaverseTypes/Lazy.cs | 32 +- 12 files changed, 462 insertions(+), 566 deletions(-) diff --git a/OpenMetaverse.Utilities/RegistrationApi.cs b/OpenMetaverse.Utilities/RegistrationApi.cs index ea8c570d..b890b523 100644 --- a/OpenMetaverse.Utilities/RegistrationApi.cs +++ b/OpenMetaverse.Utilities/RegistrationApi.cs @@ -26,7 +26,7 @@ using System; using System.Collections.Generic; -using System.Threading; + using System.Text; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; @@ -71,17 +71,17 @@ namespace OpenMetaverse public DateTime Birthdate; // optional: - public Nullable LimitedToEstate; + public int? LimitedToEstate; public string StartRegionName; - public Nullable StartLocation; - public Nullable StartLookAt; + public Vector3? StartLocation; + public Vector3? StartLookAt; } private UserInfo _userInfo; private RegistrationCaps _caps; private int _initializing; - private List _lastNames = new List(); - private Dictionary _errors = new Dictionary(); + private readonly List _lastNames = new List(); + private readonly Dictionary _errors = new Dictionary(); public bool Initializing { @@ -110,11 +110,13 @@ namespace OpenMetaverse { _initializing = -2; - _userInfo = new UserInfo(); + _userInfo = new UserInfo + { + FirstName = firstName, + LastName = lastName, + Password = password + }; - _userInfo.FirstName = firstName; - _userInfo.LastName = lastName; - _userInfo.Password = password; GatherCaps(); } @@ -125,42 +127,37 @@ namespace OpenMetaverse System.Threading.Thread.Sleep(10); } - public Uri RegistrationApiCaps - { - get { return new Uri("https://cap.secondlife.com/get_reg_capabilities"); } - } + public Uri RegistrationApiCaps => new Uri("https://cap.secondlife.com/get_reg_capabilities"); private void GatherCaps() { // build post data - byte[] postData = Encoding.ASCII.GetBytes( - String.Format("first_name={0}&last_name={1}&password={2}", _userInfo.FirstName, _userInfo.LastName, - _userInfo.Password)); + var postData = Encoding.ASCII.GetBytes( + $"first_name={_userInfo.FirstName}&last_name={_userInfo.LastName}&password={_userInfo.Password}"); - CapsClient request = new CapsClient(RegistrationApiCaps); - request.OnComplete += new CapsClient.CompleteCallback(GatherCapsResponse); + var request = new CapsClient(RegistrationApiCaps); + request.OnComplete += GatherCapsResponse; request.BeginGetResponse(postData, "application/x-www-form-urlencoded", REQUEST_TIMEOUT); } private void GatherCapsResponse(CapsClient client, OSD response, Exception error) { - if (response is OSDMap) + if (!(response is OSDMap)) return; + var respTable = (OSDMap)response; + + // parse + _caps = new RegistrationCaps { - OSDMap respTable = (OSDMap)response; + CreateUser = respTable["create_user"].AsUri(), + CheckName = respTable["check_name"].AsUri(), + GetLastNames = respTable["get_last_names"].AsUri(), + GetErrorCodes = respTable["get_error_codes"].AsUri() + }; - // parse - _caps = new RegistrationCaps(); + // finalize + _initializing++; - _caps.CreateUser = respTable["create_user"].AsUri(); - _caps.CheckName = respTable["check_name"].AsUri(); - _caps.GetLastNames = respTable["get_last_names"].AsUri(); - _caps.GetErrorCodes = respTable["get_error_codes"].AsUri(); - - // finalize - _initializing++; - - GatherErrorMessages(); - } + GatherErrorMessages(); } private void GatherErrorMessages() @@ -168,8 +165,8 @@ namespace OpenMetaverse if (_caps.GetErrorCodes == null) throw new InvalidOperationException("access denied"); // this should work even for not-approved users - CapsClient request = new CapsClient(_caps.GetErrorCodes); - request.OnComplete += new CapsClient.CompleteCallback(GatherErrorMessagesResponse); + var request = new CapsClient(_caps.GetErrorCodes); + request.OnComplete += GatherErrorMessagesResponse; request.BeginGetResponse(REQUEST_TIMEOUT); } @@ -206,8 +203,8 @@ namespace OpenMetaverse if (_caps.GetLastNames == null) throw new InvalidOperationException("access denied: only approved developers have access to the registration api"); - CapsClient request = new CapsClient(_caps.GetLastNames); - request.OnComplete += new CapsClient.CompleteCallback(GatherLastNamesResponse); + var request = new CapsClient(_caps.GetLastNames); + request.OnComplete += GatherLastNamesResponse; request.BeginGetResponse(REQUEST_TIMEOUT); // FIXME: Block @@ -245,13 +242,15 @@ namespace OpenMetaverse throw new InvalidOperationException("access denied; only approved developers have access to the registration api"); // Create the POST data - OSDMap query = new OSDMap(); - query.Add("username", OSD.FromString(firstName)); - query.Add("last_name_id", OSD.FromInteger(lastName.ID)); + var query = new OSDMap + { + {"username", OSD.FromString(firstName)}, + {"last_name_id", OSD.FromInteger(lastName.ID)} + }; //byte[] postData = OSDParser.SerializeXmlBytes(query); - CapsClient request = new CapsClient(_caps.CheckName); - request.OnComplete += new CapsClient.CompleteCallback(CheckNameResponse); + var request = new CapsClient(_caps.CheckName); + request.OnComplete += CheckNameResponse; request.BeginGetResponse(REQUEST_TIMEOUT); // FIXME: @@ -286,12 +285,14 @@ namespace OpenMetaverse throw new InvalidOperationException("access denied; only approved developers have access to the registration api"); // Create the POST data - OSDMap query = new OSDMap(); - query.Add("username", OSD.FromString(user.FirstName)); - query.Add("last_name_id", OSD.FromInteger(user.LastName.ID)); - query.Add("email", OSD.FromString(user.Email)); - query.Add("password", OSD.FromString(user.Password)); - query.Add("dob", OSD.FromString(user.Birthdate.ToString("yyyy-MM-dd"))); + var query = new OSDMap + { + {"username", OSD.FromString(user.FirstName)}, + {"last_name_id", OSD.FromInteger(user.LastName.ID)}, + {"email", OSD.FromString(user.Email)}, + {"password", OSD.FromString(user.Password)}, + {"dob", OSD.FromString(user.Birthdate.ToString("yyyy-MM-dd"))} + }; if (user.LimitedToEstate != null) query.Add("limited_to_estate", OSD.FromInteger(user.LimitedToEstate.Value)); @@ -316,8 +317,8 @@ namespace OpenMetaverse //byte[] postData = OSDParser.SerializeXmlBytes(query); // Make the request - CapsClient request = new CapsClient(_caps.CreateUser); - request.OnComplete += new CapsClient.CompleteCallback(CreateUserResponse); + var request = new CapsClient(_caps.CreateUser); + request.OnComplete += CreateUserResponse; request.BeginGetResponse(REQUEST_TIMEOUT); // FIXME: Block @@ -335,11 +336,11 @@ namespace OpenMetaverse else { // an error happened - OSDArray al = (OSDArray)response; + var al = (OSDArray)response; - StringBuilder sb = new StringBuilder(); + var sb = new StringBuilder(); - foreach (OSD ec in al) + foreach (var ec in al) { if (sb.Length > 0) sb.Append("; "); diff --git a/OpenMetaverse.Utilities/Utilities.cs b/OpenMetaverse.Utilities/Utilities.cs index 4695655b..c1f55eb6 100644 --- a/OpenMetaverse.Utilities/Utilities.cs +++ b/OpenMetaverse.Utilities/Utilities.cs @@ -25,11 +25,7 @@ */ using System; -using System.Collections; -using System.Collections.Generic; using System.Threading; -using OpenMetaverse; -using OpenMetaverse.Packets; namespace OpenMetaverse.Utilities { @@ -59,10 +55,7 @@ namespace OpenMetaverse.Utilities /// public static bool Shoot(GridClient client, Vector3 target) { - if (client.Self.Movement.TurnToward(target)) - return Shoot(client); - else - return false; + return client.Self.Movement.TurnToward(target) && Shoot(client); } /// @@ -119,12 +112,12 @@ namespace OpenMetaverse.Utilities /// Characters per second rate for chatting public static void Chat(GridClient client, string message, ChatType type, int cps) { - Random rand = new Random(); - int characters = 0; - bool typing = true; + var rand = new Random(); + var characters = 0; + var typing = true; // Start typing - client.Self.Chat(String.Empty, 0, ChatType.StartTyping); + client.Self.Chat(string.Empty, 0, ChatType.StartTyping); client.Self.AnimationStart(Animations.TYPE, false); while (characters < message.Length) @@ -132,7 +125,7 @@ namespace OpenMetaverse.Utilities if (!typing) { // Start typing again - client.Self.Chat(String.Empty, 0, ChatType.StartTyping); + client.Self.Chat(string.Empty, 0, ChatType.StartTyping); client.Self.AnimationStart(Animations.TYPE, false); typing = true; } @@ -141,14 +134,14 @@ namespace OpenMetaverse.Utilities // Randomly pause typing if (rand.Next(10) >= 9) { - client.Self.Chat(String.Empty, 0, ChatType.StopTyping); + client.Self.Chat(string.Empty, 0, ChatType.StopTyping); client.Self.AnimationStop(Animations.TYPE, false); typing = false; } } // Sleep for a second and increase the amount of characters we've typed - System.Threading.Thread.Sleep(1000); + Thread.Sleep(1000); characters += cps; } @@ -156,24 +149,24 @@ namespace OpenMetaverse.Utilities client.Self.Chat(message, 0, type); // Stop typing - client.Self.Chat(String.Empty, 0, ChatType.StopTyping); + client.Self.Chat(string.Empty, 0, ChatType.StopTyping); client.Self.AnimationStop(Animations.TYPE, false); } } public class ConnectionManager { - private GridClient Client; - private ulong SimHandle; - private Vector3 Position = Vector3.Zero; - private System.Timers.Timer CheckTimer; + private readonly GridClient _client; + private ulong _simHandle; + private Vector3 _position = Vector3.Zero; + private readonly System.Timers.Timer _checkTimer; public ConnectionManager(GridClient client, int timerFrequency) { - Client = client; + _client = client; - CheckTimer = new System.Timers.Timer(timerFrequency); - CheckTimer.Elapsed += new System.Timers.ElapsedEventHandler(CheckTimer_Elapsed); + _checkTimer = new System.Timers.Timer(timerFrequency); + _checkTimer.Elapsed += CheckTimer_Elapsed; } public static bool PersistentLogin(GridClient client, string firstName, string lastName, string password, @@ -188,41 +181,32 @@ namespace OpenMetaverse.Utilities Logger.Log("Logged in to " + client.Network.CurrentSim, Helpers.LogLevel.Info, client); return true; } - else + switch (client.Network.LoginErrorKey) { - if (client.Network.LoginErrorKey == "god") - { + case "god": Logger.Log("Grid is down, waiting 10 minutes", Helpers.LogLevel.Warning, client); LoginWait(10); goto Start; - } - else if (client.Network.LoginErrorKey == "key") - { + case "key": Logger.Log("Bad username or password, giving up on login", Helpers.LogLevel.Error, client); return false; - } - else if (client.Network.LoginErrorKey == "presence") - { + case "presence": Logger.Log("Server is still logging us out, waiting 1 minute", Helpers.LogLevel.Warning, client); LoginWait(1); goto Start; - } - else if (client.Network.LoginErrorKey == "disabled") - { + case "disabled": Logger.Log("This account has been banned! Giving up on login", Helpers.LogLevel.Error, client); return false; - } - else if (client.Network.LoginErrorKey == "timed out" ||client.Network.LoginErrorKey == "no connection" ) - { + case "timed out": + case "no connection": Logger.Log("Login request timed out, waiting 1 minute", Helpers.LogLevel.Warning, client); LoginWait(1); goto Start; - } else if (client.Network.LoginErrorKey == "bad response") { + case "bad response": Logger.Log("Login server returned unparsable result", Helpers.LogLevel.Warning, client); LoginWait(1); goto Start; - } else - { + default: ++unknownLogins; if (unknownLogins < 5) @@ -232,20 +216,16 @@ namespace OpenMetaverse.Utilities LoginWait(2); goto Start; } - else - { - Logger.Log("Too many unknown login error codes, giving up", Helpers.LogLevel.Error, client); - return false; - } - } + Logger.Log("Too many unknown login error codes, giving up", Helpers.LogLevel.Error, client); + return false; } } public void StayInSim(ulong handle, Vector3 desiredPosition) { - SimHandle = handle; - Position = desiredPosition; - CheckTimer.Start(); + _simHandle = handle; + _position = desiredPosition; + _checkTimer.Start(); } private static void LoginWait(int minutes) @@ -255,14 +235,13 @@ namespace OpenMetaverse.Utilities private void CheckTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { - if (SimHandle != 0) + if (_simHandle == 0) return; + + if (_client.Network.CurrentSim.Handle != 0 && + _client.Network.CurrentSim.Handle != _simHandle) { - if (Client.Network.CurrentSim.Handle != 0 && - Client.Network.CurrentSim.Handle != SimHandle) - { - // Attempt to move to our target sim - Client.Self.Teleport(SimHandle, Position); - } + // Attempt to move to our target sim + _client.Self.Teleport(_simHandle, _position); } } } diff --git a/OpenMetaverse.Utilities/VoiceManager.cs b/OpenMetaverse.Utilities/VoiceManager.cs index 226fda6e..10e311d2 100644 --- a/OpenMetaverse.Utilities/VoiceManager.cs +++ b/OpenMetaverse.Utilities/VoiceManager.cs @@ -30,8 +30,6 @@ using System.Net.Sockets; using System.Text; using System.IO; using System.Xml; -using System.Threading; -using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenMetaverse.Http; using OpenMetaverse.Interfaces; @@ -115,44 +113,44 @@ namespace OpenMetaverse.Utilities protected Voice.TCPPipe _DaemonPipe; protected VoiceStatus _Status; protected int _CommandCookie = 0; - protected string _TuningSoundFile = String.Empty; + protected string _TuningSoundFile = string.Empty; protected Dictionary _ChannelMap = new Dictionary(); protected List _CaptureDevices = new List(); protected List _RenderDevices = new List(); #region Response Processing Variables - private bool isEvent = false; - private bool isChannel = false; - private bool isLocallyMuted = false; - private bool isModeratorMuted = false; - private bool isSpeaking = false; - private int cookie = 0; - //private int returnCode = 0; - private int statusCode = 0; - private int volume = 0; - private int state = 0; - private int participantType = 0; - private float energy = 0f; - private string statusString = String.Empty; - //private string uuidString = String.Empty; - private string actionString = String.Empty; - private string connectorHandle = String.Empty; - private string accountHandle = String.Empty; - private string sessionHandle = String.Empty; - private string eventSessionHandle = String.Empty; - private string eventTypeString = String.Empty; - private string uriString = String.Empty; - private string nameString = String.Empty; - //private string audioMediaString = String.Empty; - private string displayNameString = String.Empty; + private bool isEvent; + private bool isChannel; + private bool isLocallyMuted; + private bool isModeratorMuted; + private bool isSpeaking; + private int cookie; + //private int returnCode; + private int statusCode; + private int volume; + private int state; + private int participantType; + private float energy; + private string statusString = string.Empty; + //private string uuidString = string.Empty; + private string actionString = string.Empty; + private string connectorHandle = string.Empty; + private string accountHandle = string.Empty; + private string sessionHandle = string.Empty; + private string eventSessionHandle = string.Empty; + private string eventTypeString = string.Empty; + private string uriString = string.Empty; + private string nameString = string.Empty; + //private string audioMediaString = string.Empty; + private string displayNameString = string.Empty; #endregion Response Processing Variables public VoiceManager(GridClient client) { Client = client; - Client.Network.RegisterEventCallback("RequiredVoiceVersion", new Caps.EventQueueCallback(RequiredVoiceVersionEventHandler)); + Client.Network.RegisterEventCallback("RequiredVoiceVersion", RequiredVoiceVersionEventHandler); // Register callback handlers for the blocking functions RegisterCallbacks(); @@ -187,20 +185,17 @@ namespace OpenMetaverse.Utilities if (!Enabled) return false; _DaemonPipe = new Voice.TCPPipe(); - _DaemonPipe.OnDisconnected += new Voice.TCPPipe.OnDisconnectedCallback(_DaemonPipe_OnDisconnected); - _DaemonPipe.OnReceiveLine += new Voice.TCPPipe.OnReceiveLineCallback(_DaemonPipe_OnReceiveLine); + _DaemonPipe.OnDisconnected += _DaemonPipe_OnDisconnected; + _DaemonPipe.OnReceiveLine += _DaemonPipe_OnReceiveLine; - SocketException se = _DaemonPipe.Connect(address, port); + var se = _DaemonPipe.Connect(address, port); if (se == null) { return true; } - else - { - Console.WriteLine("Connection failed: " + se.Message); - return false; - } + Console.WriteLine("Connection failed: " + se.Message); + return false; } public Dictionary GetChannelMap() @@ -220,7 +215,7 @@ namespace OpenMetaverse.Utilities public string VoiceAccountFromUUID(UUID id) { - string result = "x" + Convert.ToBase64String(id.GetBytes()); + var result = "x" + Convert.ToBase64String(id.GetBytes()); return result.Replace('+', '-').Replace('/', '_'); } @@ -229,58 +224,42 @@ namespace OpenMetaverse.Utilities if (accountName.Length == 25 && accountName[0] == 'x' && accountName[23] == '=' && accountName[24] == '=') { accountName = accountName.Replace('/', '_').Replace('+', '-'); - byte[] idBytes = Convert.FromBase64String(accountName); + var idBytes = Convert.FromBase64String(accountName); - if (idBytes.Length == 16) - return new UUID(idBytes, 0); - else - return UUID.Zero; - } - else - { - return UUID.Zero; + return idBytes.Length == 16 ? new UUID(idBytes, 0) : UUID.Zero; } + return UUID.Zero; } public string SIPURIFromVoiceAccount(string account) { - return String.Format("sip:{0}@{1}", account, VoiceServer); + return $"sip:{account}@{VoiceServer}"; } public int RequestCaptureDevices() { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}", - _CommandCookie++, - REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } - else - { - Logger.Log("VoiceManager.RequestCaptureDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client); - return -1; - } + Logger.Log("VoiceManager.RequestCaptureDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client); + return -1; } public int RequestRenderDevices() { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}", - _CommandCookie++, - REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } - else - { - Logger.Log("VoiceManager.RequestRenderDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client); - return -1; - } + Logger.Log("VoiceManager.RequestRenderDevices() called when the daemon pipe is disconnected", Helpers.LogLevel.Error, Client); + return -1; } public int RequestCreateConnector() @@ -294,16 +273,16 @@ namespace OpenMetaverse.Utilities { VoiceServer = voiceServer; - string accountServer = String.Format("https://www.{0}/api2/", VoiceServer); - string logPath = "."; + var accountServer = $"https://www.{VoiceServer}/api2/"; + var logPath = "."; - StringBuilder request = new StringBuilder(); - request.Append(String.Format("", _CommandCookie++)); + var request = new StringBuilder(); + request.Append($""); request.Append("V2 SDK"); - request.Append(String.Format("{0}", accountServer)); + request.Append($"{accountServer}"); request.Append(""); request.Append("false"); - request.Append(String.Format("{0}", logPath)); + request.Append($"{logPath}"); request.Append("vivox-gateway"); request.Append(".log"); request.Append("0"); @@ -328,23 +307,20 @@ namespace OpenMetaverse.Utilities { if (Client.Network.CurrentSim != null && Client.Network.CurrentSim.Caps != null) { - Uri url = Client.Network.CurrentSim.Caps.CapabilityURI(capsName); + var url = Client.Network.CurrentSim.Caps.CapabilityURI(capsName); if (url != null) { - CapsClient request = new CapsClient(url); - OSDMap body = new OSDMap(); - request.OnComplete += new CapsClient.CompleteCallback(callback); + var request = new CapsClient(url); + var body = new OSDMap(); + request.OnComplete += callback; request.BeginGetResponse(body, OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); return true; } - else - { - Logger.Log("VoiceManager." + me + "(): " + capsName + " capability is missing", - Helpers.LogLevel.Info, Client); - return false; - } + Logger.Log("VoiceManager." + me + "(): " + capsName + " capability is missing", + Helpers.LogLevel.Info, Client); + return false; } } @@ -368,11 +344,11 @@ namespace OpenMetaverse.Utilities { if (_DaemonPipe.Connected) { - StringBuilder request = new StringBuilder(); - request.Append(String.Format("", _CommandCookie++)); - request.Append(String.Format("{0}", connectorHandle)); - request.Append(String.Format("{0}", accountName)); - request.Append(String.Format("{0}", password)); + var request = new StringBuilder(); + request.Append($""); + request.Append($"{connectorHandle}"); + request.Append($"{accountName}"); + request.Append($"{password}"); request.Append("VerifyAnswer"); request.Append(""); request.Append("10"); @@ -395,9 +371,8 @@ namespace OpenMetaverse.Utilities { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}", - _CommandCookie, deviceName, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{deviceName}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -412,9 +387,8 @@ namespace OpenMetaverse.Utilities { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}", - _CommandCookie, duration, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{duration}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -429,9 +403,8 @@ namespace OpenMetaverse.Utilities { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}", - _CommandCookie, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -442,16 +415,15 @@ namespace OpenMetaverse.Utilities } } - public int RequestSetSpeakerVolume(int volume) + public int RequestSetSpeakerVolume(int volume_) { - if (volume < 0 || volume > 100) - throw new ArgumentException("volume must be between 0 and 100", "volume"); + if (volume_ < 0 || volume_ > 100) + throw new ArgumentException("volume must be between 0 and 100", nameof(volume_)); if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}", - _CommandCookie, volume, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{volume_}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -462,16 +434,15 @@ namespace OpenMetaverse.Utilities } } - public int RequestSetCaptureVolume(int volume) + public int RequestSetCaptureVolume(int volume_) { - if (volume < 0 || volume > 100) - throw new ArgumentException("volume must be between 0 and 100", "volume"); + if (volume_ < 0 || volume_ > 100) + throw new ArgumentException("volume must be between 0 and 100", nameof(volume_)); if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}", - _CommandCookie, volume, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{volume_}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -493,9 +464,8 @@ namespace OpenMetaverse.Utilities { _TuningSoundFile = fileName; - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}{3}", - _CommandCookie++, _TuningSoundFile, (loop ? "1" : "0"), REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{_TuningSoundFile}{(loop ? "1" : "0")}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -510,9 +480,8 @@ namespace OpenMetaverse.Utilities { if (_DaemonPipe.Connected) { - _DaemonPipe.SendData(Encoding.ASCII.GetBytes(String.Format( - "{1}{2}", - _CommandCookie++, _TuningSoundFile, REQUEST_TERMINATOR))); + _DaemonPipe.SendData(Encoding.ASCII.GetBytes( + $"{_TuningSoundFile}{REQUEST_TERMINATOR}")); return _CommandCookie - 1; } @@ -527,55 +496,49 @@ namespace OpenMetaverse.Utilities private void RequiredVoiceVersionEventHandler(string capsKey, IMessage message, Simulator simulator) { - RequiredVoiceVersionMessage msg = (RequiredVoiceVersionMessage)message; + var msg = (RequiredVoiceVersionMessage)message; - if (VOICE_MAJOR_VERSION != msg.MajorVersion) - { - Logger.Log(String.Format("Voice version mismatch! Got {0}, expecting {1}. Disabling the voice manager", - msg.MajorVersion, VOICE_MAJOR_VERSION), Helpers.LogLevel.Error, Client); - Enabled = false; - } - else - { - Logger.DebugLog("Voice version " + msg.MajorVersion + " verified", Client); - } + if (VOICE_MAJOR_VERSION != msg.MajorVersion) + { + Logger.Log( + $"Voice version mismatch! Got {msg.MajorVersion}, expecting {VOICE_MAJOR_VERSION}. Disabling the voice manager", Helpers.LogLevel.Error, Client); + Enabled = false; + } + else + { + Logger.DebugLog("Voice version " + msg.MajorVersion + " verified", Client); + } } private void ProvisionCapsResponse(CapsClient client, OSD response, Exception error) { - if (response is OSDMap) - { - OSDMap respTable = (OSDMap)response; + if (!(response is OSDMap)) return; + var respTable = (OSDMap)response; - if (OnProvisionAccount != null) - { - try { OnProvisionAccount(respTable["username"].AsString(), respTable["password"].AsString()); } - catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } - } - } + if (OnProvisionAccount == null) return; + try { OnProvisionAccount(respTable["username"].AsString(), respTable["password"].AsString()); } + catch (Exception e) { Logger.Log(e.Message, Helpers.LogLevel.Error, Client, e); } } private void ParcelVoiceInfoResponse(CapsClient client, OSD response, Exception error) { - if (response is OSDMap) + if (!(response is OSDMap)) return; + var respTable = (OSDMap)response; + + var regionName = respTable["region_name"].AsString(); + var localID = respTable["parcel_local_id"].AsInteger(); + + string channelURI = null; + if (respTable["voice_credentials"] is OSDMap) { - OSDMap respTable = (OSDMap)response; - - string regionName = respTable["region_name"].AsString(); - int localID = (int)respTable["parcel_local_id"].AsInteger(); - - string channelURI = null; - if (respTable["voice_credentials"] is OSDMap) - { - OSDMap creds = (OSDMap)respTable["voice_credentials"]; - channelURI = creds["channel_uri"].AsString(); - } - - if (OnParcelVoiceInfo != null) OnParcelVoiceInfo(regionName, localID, channelURI); + var creds = (OSDMap)respTable["voice_credentials"]; + channelURI = creds["channel_uri"].AsString(); } + + OnParcelVoiceInfo?.Invoke(regionName, localID, channelURI); } - private void _DaemonPipe_OnDisconnected(SocketException se) + private static void _DaemonPipe_OnDisconnected(SocketException se) { if (se != null) Console.WriteLine("Disconnected! " + se.Message); else Console.WriteLine("Disconnected!"); @@ -583,7 +546,7 @@ namespace OpenMetaverse.Utilities private void _DaemonPipe_OnReceiveLine(string line) { - XmlTextReader reader = new XmlTextReader(new StringReader(line)); + var reader = new XmlTextReader(new StringReader(line)); while (reader.Read()) { @@ -597,22 +560,14 @@ namespace OpenMetaverse.Utilities if (isEvent || reader.Name == "Response") { - for (int i = 0; i < reader.AttributeCount; i++) + for (var i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); - switch (reader.Name) - { -// case "requestId": -// uuidString = reader.Value; -// break; - case "action": - actionString = reader.Value; - break; - case "type": - eventTypeString = reader.Value; - break; - } + if (reader.Name == "action") + actionString = reader.Value; + else if (reader.Name == "type") + eventTypeString = reader.Value; } } } @@ -627,21 +582,20 @@ namespace OpenMetaverse.Utilities reader.Read(); if (reader.Name == "Request") { - for (int i = 0; i < reader.AttributeCount; i++) + for (var i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); - if (reader.Name == "requestId") - { - Int32.TryParse(reader.Value, out cookie); - break; - } + if (reader.Name != "requestId") continue; + int.TryParse(reader.Value, out cookie); + break; } } if (cookie == -1) { - Logger.Log("VoiceManager._DaemonPipe_OnReceiveLine(): Failed to parse InputXml for the cookie", + Logger.Log( + "VoiceManager._DaemonPipe_OnReceiveLine(): Failed to parse InputXml for the cookie", Helpers.LogLevel.Warning, Client); } break; @@ -748,6 +702,40 @@ namespace OpenMetaverse.Utilities if (reader.Depth == 0) ProcessEvent(); break; + case XmlNodeType.None: + break; + case XmlNodeType.Attribute: + break; + case XmlNodeType.Text: + break; + case XmlNodeType.CDATA: + break; + case XmlNodeType.EntityReference: + break; + case XmlNodeType.Entity: + break; + case XmlNodeType.ProcessingInstruction: + break; + case XmlNodeType.Comment: + break; + case XmlNodeType.Document: + break; + case XmlNodeType.DocumentType: + break; + case XmlNodeType.DocumentFragment: + break; + case XmlNodeType.Notation: + break; + case XmlNodeType.Whitespace: + break; + case XmlNodeType.SignificantWhitespace: + break; + case XmlNodeType.EndEntity: + break; + case XmlNodeType.XmlDeclaration: + break; + default: + throw new ArgumentOutOfRangeException(); } } @@ -765,22 +753,22 @@ namespace OpenMetaverse.Utilities switch (eventTypeString) { case "LoginStateChangeEvent": - if (OnLoginStateChange != null) OnLoginStateChange(cookie, accountHandle, statusCode, statusString, state); + OnLoginStateChange?.Invoke(cookie, accountHandle, statusCode, statusString, state); break; case "SessionNewEvent": - if (OnNewSession != null) OnNewSession(cookie, accountHandle, eventSessionHandle, state, nameString, uriString); + OnNewSession?.Invoke(cookie, accountHandle, eventSessionHandle, state, nameString, uriString); break; case "SessionStateChangeEvent": - if (OnSessionStateChange != null) OnSessionStateChange(cookie, uriString, statusCode, statusString, eventSessionHandle, state, isChannel, nameString); + OnSessionStateChange?.Invoke(cookie, uriString, statusCode, statusString, eventSessionHandle, state, isChannel, nameString); break; case "ParticipantStateChangeEvent": - if (OnParticipantStateChange != null) OnParticipantStateChange(cookie, uriString, statusCode, statusString, state, nameString, displayNameString, participantType); + OnParticipantStateChange?.Invoke(cookie, uriString, statusCode, statusString, state, nameString, displayNameString, participantType); break; case "ParticipantPropertiesEvent": - if (OnParticipantProperties != null) OnParticipantProperties(cookie, uriString, statusCode, statusString, isLocallyMuted, isModeratorMuted, isSpeaking, volume, energy); + OnParticipantProperties?.Invoke(cookie, uriString, statusCode, statusString, isLocallyMuted, isModeratorMuted, isSpeaking, volume, energy); break; case "AuxAudioPropertiesEvent": - if (OnAuxAudioProperties != null) OnAuxAudioProperties(cookie, energy); + OnAuxAudioProperties?.Invoke(cookie, energy); break; } } @@ -789,34 +777,34 @@ namespace OpenMetaverse.Utilities switch (actionString) { case "Connector.Create.1": - if (OnConnectorCreated != null) OnConnectorCreated(cookie, statusCode, statusString, connectorHandle); + OnConnectorCreated?.Invoke(cookie, statusCode, statusString, connectorHandle); break; case "Account.Login.1": - if (OnLogin != null) OnLogin(cookie, statusCode, statusString, accountHandle); + OnLogin?.Invoke(cookie, statusCode, statusString, accountHandle); break; case "Session.Create.1": - if (OnSessionCreated != null) OnSessionCreated(cookie, statusCode, statusString, sessionHandle); + OnSessionCreated?.Invoke(cookie, statusCode, statusString, sessionHandle); break; case "Session.Connect.1": - if (OnSessionConnected != null) OnSessionConnected(cookie, statusCode, statusString); + OnSessionConnected?.Invoke(cookie, statusCode, statusString); break; case "Session.Terminate.1": - if (OnSessionTerminated != null) OnSessionTerminated(cookie, statusCode, statusString); + OnSessionTerminated?.Invoke(cookie, statusCode, statusString); break; case "Account.Logout.1": - if (OnAccountLogout != null) OnAccountLogout(cookie, statusCode, statusString); + OnAccountLogout?.Invoke(cookie, statusCode, statusString); break; case "Connector.InitiateShutdown.1": - if (OnConnectorInitiateShutdown != null) OnConnectorInitiateShutdown(cookie, statusCode, statusString); + OnConnectorInitiateShutdown?.Invoke(cookie, statusCode, statusString); break; case "Account.ChannelGetList.1": - if (OnAccountChannelGetList != null) OnAccountChannelGetList(cookie, statusCode, statusString); + OnAccountChannelGetList?.Invoke(cookie, statusCode, statusString); break; case "Aux.GetCaptureDevices.1": - if (OnCaptureDevices != null) OnCaptureDevices(cookie, statusCode, statusString, nameString); + OnCaptureDevices?.Invoke(cookie, statusCode, statusString, nameString); break; case "Aux.GetRenderDevices.1": - if (OnRenderDevices != null) OnRenderDevices(cookie, statusCode, statusString, nameString); + OnRenderDevices?.Invoke(cookie, statusCode, statusString, nameString); break; } } diff --git a/OpenMetaverse.Utilities/VoiceManagerBlocking.cs b/OpenMetaverse.Utilities/VoiceManagerBlocking.cs index e1a0f988..ae460d82 100644 --- a/OpenMetaverse.Utilities/VoiceManagerBlocking.cs +++ b/OpenMetaverse.Utilities/VoiceManagerBlocking.cs @@ -27,7 +27,6 @@ using System; using System.Collections.Generic; using System.Threading; -using OpenMetaverse; namespace OpenMetaverse.Utilities { @@ -42,7 +41,7 @@ namespace OpenMetaverse.Utilities public List CaptureDevices() { - AutoResetEvent evt = new AutoResetEvent(false); + var evt = new AutoResetEvent(false); Events[_CommandCookie] = evt; if (RequestCaptureDevices() == -1) @@ -51,15 +50,12 @@ namespace OpenMetaverse.Utilities return new List(); } - if (evt.WaitOne(BlockingTimeout, false)) - return CurrentCaptureDevices(); - else - return new List(); + return evt.WaitOne(BlockingTimeout, false) ? CurrentCaptureDevices() : new List(); } public List RenderDevices() { - AutoResetEvent evt = new AutoResetEvent(false); + var evt = new AutoResetEvent(false); Events[_CommandCookie] = evt; if (RequestRenderDevices() == -1) @@ -68,62 +64,53 @@ namespace OpenMetaverse.Utilities return new List(); } - if (evt.WaitOne(BlockingTimeout, false)) - return CurrentRenderDevices(); - else - return new List(); + return evt.WaitOne(BlockingTimeout, false) ? CurrentRenderDevices() : new List(); } public string CreateConnector(out int status) { status = 0; - AutoResetEvent evt = new AutoResetEvent(false); + var evt = new AutoResetEvent(false); Events[_CommandCookie] = evt; if (RequestCreateConnector() == -1) { Events.Remove(_CommandCookie); - return String.Empty; + return string.Empty; } - bool success = evt.WaitOne(BlockingTimeout, false); + var success = evt.WaitOne(BlockingTimeout, false); status = statusCode; - if (success && statusCode == 0) - return connectorHandle; - else - return String.Empty; + return success && statusCode == 0 ? connectorHandle : string.Empty; } public string Login(string accountName, string password, string connectorHandle, out int status) { status = 0; - AutoResetEvent evt = new AutoResetEvent(false); + var evt = new AutoResetEvent(false); Events[_CommandCookie] = evt; if (RequestLogin(accountName, password, connectorHandle) == -1) { Events.Remove(_CommandCookie); - return String.Empty; + return string.Empty; } - bool success = evt.WaitOne(BlockingTimeout, false); + var success = evt.WaitOne(BlockingTimeout, false); status = statusCode; - if (success && statusCode == 0) - return accountHandle; - else - return String.Empty; + return success && statusCode == 0 ? accountHandle : string.Empty; } protected void RegisterCallbacks() { - OnCaptureDevices += new DevicesCallback(VoiceManager_OnCaptureDevices); - OnRenderDevices += new DevicesCallback(VoiceManager_OnRenderDevices); - OnConnectorCreated += new ConnectorCreatedCallback(VoiceManager_OnConnectorCreated); - OnLogin += new LoginCallback(VoiceManager_OnLogin); + OnCaptureDevices += VoiceManager_OnCaptureDevices; + OnRenderDevices += VoiceManager_OnRenderDevices; + OnConnectorCreated += VoiceManager_OnConnectorCreated; + OnLogin += VoiceManager_OnLogin; } #region Callbacks diff --git a/OpenMetaverseTypes/BlockingQueue.cs b/OpenMetaverseTypes/BlockingQueue.cs index 182844ab..b0ef2c4f 100644 --- a/OpenMetaverseTypes/BlockingQueue.cs +++ b/OpenMetaverseTypes/BlockingQueue.cs @@ -27,7 +27,6 @@ using System; using System.Collections.Generic; using System.Threading; -using OpenMetaverse; namespace OpenMetaverse { @@ -37,8 +36,8 @@ namespace OpenMetaverse /// public class BlockingQueue : Queue { - private object SyncRoot; - private bool open; + private readonly object _syncRoot; + private bool _open; /// /// Create new BlockingQueue. @@ -47,8 +46,8 @@ namespace OpenMetaverse public BlockingQueue(IEnumerable col) : base(col) { - SyncRoot = new object(); - open = true; + _syncRoot = new object(); + _open = true; } /// @@ -58,8 +57,8 @@ namespace OpenMetaverse public BlockingQueue(int capacity) : base(capacity) { - SyncRoot = new object(); - open = true; + _syncRoot = new object(); + _open = true; } /// @@ -68,8 +67,8 @@ namespace OpenMetaverse public BlockingQueue() : base() { - SyncRoot = new object(); - open = true; + _syncRoot = new object(); + _open = true; } /// @@ -85,7 +84,7 @@ namespace OpenMetaverse /// public new void Clear() { - lock (SyncRoot) + lock (_syncRoot) { base.Clear(); } @@ -96,11 +95,11 @@ namespace OpenMetaverse /// public void Close() { - lock (SyncRoot) + lock (_syncRoot) { - open = false; + _open = false; base.Clear(); - Monitor.PulseAll(SyncRoot); // resume any waiting threads + Monitor.PulseAll(_syncRoot); // resume any waiting threads } } @@ -130,39 +129,35 @@ namespace OpenMetaverse /// Object in queue. public T Dequeue(int timeout) { - lock (SyncRoot) + lock (_syncRoot) { - while (open && (base.Count == 0)) + while (_open && (Count == 0)) { - if (!Monitor.Wait(SyncRoot, timeout)) + if (!Monitor.Wait(_syncRoot, timeout)) throw new InvalidOperationException("Timeout"); } - if (open) + if (_open) return base.Dequeue(); - else - throw new InvalidOperationException("Queue Closed"); + throw new InvalidOperationException("Queue Closed"); } } public bool Dequeue(int timeout, ref T obj) { - lock (SyncRoot) + lock (_syncRoot) { - while (open && (base.Count == 0)) + while (_open && (base.Count == 0)) { - if (!Monitor.Wait(SyncRoot, timeout)) + if (!Monitor.Wait(_syncRoot, timeout)) return false; } - if (open) + if (_open) { obj = base.Dequeue(); return true; } - else - { - obj = default(T); - return false; - } + obj = default(T); + return false; } } @@ -172,10 +167,10 @@ namespace OpenMetaverse /// Object to put in queue public new void Enqueue(T obj) { - lock (SyncRoot) + lock (_syncRoot) { base.Enqueue(obj); - Monitor.Pulse(SyncRoot); + Monitor.Pulse(_syncRoot); } } @@ -184,18 +179,15 @@ namespace OpenMetaverse /// public void Open() { - lock (SyncRoot) + lock (_syncRoot) { - open = true; + _open = true; } } /// /// Gets flag indicating if queue has been closed. /// - public bool Closed - { - get { return !open; } - } + public bool Closed => !_open; } } diff --git a/OpenMetaverseTypes/CRC32.cs b/OpenMetaverseTypes/CRC32.cs index 773c199d..f2aed82c 100644 --- a/OpenMetaverseTypes/CRC32.cs +++ b/OpenMetaverseTypes/CRC32.cs @@ -94,7 +94,7 @@ namespace OpenMetaverse public void Update(byte[] value, int pos, int length) { - for (int i = pos; i < length; i++) + for (var i = pos; i < length; i++) CRC = crcTable[(CRC ^ value[i]) & 0xff] ^ (CRC >> 8); } } diff --git a/OpenMetaverseTypes/CircularQueue.cs b/OpenMetaverseTypes/CircularQueue.cs index b8954863..de8ad683 100644 --- a/OpenMetaverseTypes/CircularQueue.cs +++ b/OpenMetaverseTypes/CircularQueue.cs @@ -24,27 +24,23 @@ * POSSIBILITY OF SUCH DAMAGE. */ -using System; - namespace OpenMetaverse { public class CircularQueue { public readonly T[] Items; - int first; - int next; - int capacity; - object syncRoot; + private readonly int _capacity; + private readonly object _syncRoot; - public int First { get { return first; } } - public int Next { get { return next; } } + public int First { get; private set; } + public int Next { get; private set; } public CircularQueue(int capacity) { - this.capacity = capacity; + _capacity = capacity; Items = new T[capacity]; - syncRoot = new object(); + _syncRoot = new object(); } /// @@ -53,51 +49,51 @@ namespace OpenMetaverse /// Circular queue to copy public CircularQueue(CircularQueue queue) { - lock (queue.syncRoot) + lock (queue._syncRoot) { - capacity = queue.capacity; - Items = new T[capacity]; - syncRoot = new object(); + _capacity = queue._capacity; + Items = new T[_capacity]; + _syncRoot = new object(); - for (int i = 0; i < capacity; i++) + for (var i = 0; i < _capacity; i++) Items[i] = queue.Items[i]; - first = queue.first; - next = queue.next; + First = queue.First; + Next = queue.Next; } } public void Clear() { - lock (syncRoot) + lock (_syncRoot) { // Explicitly remove references to help garbage collection - for (int i = 0; i < capacity; i++) + for (var i = 0; i < _capacity; i++) Items[i] = default(T); - first = next; + First = Next; } } public void Enqueue(T value) { - lock (syncRoot) + lock (_syncRoot) { - Items[next] = value; - next = (next + 1) % capacity; - if (next == first) first = (first + 1) % capacity; + Items[Next] = value; + Next = (Next + 1) % _capacity; + if (Next == First) First = (First + 1) % _capacity; } } public T Dequeue() { - lock (syncRoot) + lock (_syncRoot) { - T value = Items[first]; - Items[first] = default(T); + var value = Items[First]; + Items[First] = default(T); - if (first != next) - first = (first + 1) % capacity; + if (First != Next) + First = (First + 1) % _capacity; return value; } @@ -105,29 +101,29 @@ namespace OpenMetaverse public T DequeueLast() { - lock (syncRoot) + lock (_syncRoot) { // If the next element is right behind the first element (queue is full), // back up the first element by one - int firstTest = first - 1; - if (firstTest < 0) firstTest = capacity - 1; + var firstTest = First - 1; + if (firstTest < 0) firstTest = _capacity - 1; - if (firstTest == next) + if (firstTest == Next) { - --next; - if (next < 0) next = capacity - 1; + --Next; + if (Next < 0) Next = _capacity - 1; - --first; - if (first < 0) first = capacity - 1; + --First; + if (First < 0) First = _capacity - 1; } - else if (first != next) + else if (First != Next) { - --next; - if (next < 0) next = capacity - 1; + --Next; + if (Next < 0) Next = _capacity - 1; } - T value = Items[next]; - Items[next] = default(T); + var value = Items[Next]; + Items[Next] = default(T); return value; } diff --git a/OpenMetaverseTypes/Color4.cs b/OpenMetaverseTypes/Color4.cs index a4bc542e..213eda60 100644 --- a/OpenMetaverseTypes/Color4.cs +++ b/OpenMetaverseTypes/Color4.cs @@ -58,10 +58,10 @@ namespace OpenMetaverse { const float quanta = 1.0f / 255.0f; - R = (float)r * quanta; - G = (float)g * quanta; - B = (float)b * quanta; - A = (float)a * quanta; + R = r * quanta; + G = g * quanta; + B = b * quanta; + A = a * quanta; } public Color4(float r, float g, float b, float a) @@ -70,8 +70,7 @@ namespace OpenMetaverse // like using float values from 0.0 - 255.0 if (r > 1f || g > 1f || b > 1f || a > 1f) throw new ArgumentException( - String.Format("Attempting to initialize Color4 with out of range values <{0},{1},{2},{3}>", - r, g, b, a)); + $"Attempting to initialize Color4 with out of range values <{r},{g},{b},{a}>"); // Valid range is from 0.0 to 1.0 R = Utils.Clamp(r, 0f, 1f); @@ -136,36 +135,15 @@ namespace OpenMetaverse /// Alpha is only used when the colors are otherwise equivalent public int CompareTo(Color4 color) { - float thisHue = GetHue(); - float thatHue = color.GetHue(); + var thisHue = GetHue(); + var thatHue = color.GetHue(); if (thisHue < 0f && thatHue < 0f) { // Both monochromatic - if (R == color.R) - { - // Monochromatic and equal, compare alpha - return A.CompareTo(color.A); - } - else - { - // Compare lightness - return R.CompareTo(R); - } - } - else - { - if (thisHue == thatHue) - { - // RGB is equal, compare alpha - return A.CompareTo(color.A); - } - else - { - // Compare hues - return thisHue.CompareTo(thatHue); - } + return R == color.R ? A.CompareTo(color.A) : R.CompareTo(R); } + return thisHue == thatHue ? A.CompareTo(color.A) : thisHue.CompareTo(thatHue); } public void FromBytes(byte[] byteArray, int pos, bool inverted) @@ -174,17 +152,17 @@ namespace OpenMetaverse if (inverted) { - R = (float)(255 - byteArray[pos]) * quanta; - G = (float)(255 - byteArray[pos + 1]) * quanta; - B = (float)(255 - byteArray[pos + 2]) * quanta; - A = (float)(255 - byteArray[pos + 3]) * quanta; + R = (255 - byteArray[pos]) * quanta; + G = (255 - byteArray[pos + 1]) * quanta; + B = (255 - byteArray[pos + 2]) * quanta; + A = (255 - byteArray[pos + 3]) * quanta; } else { - R = (float)byteArray[pos] * quanta; - G = (float)byteArray[pos + 1] * quanta; - B = (float)byteArray[pos + 2] * quanta; - A = (float)byteArray[pos + 3] * quanta; + R = byteArray[pos] * quanta; + G = byteArray[pos + 1] * quanta; + B = byteArray[pos + 2] * quanta; + A = byteArray[pos + 3] * quanta; } } @@ -215,14 +193,14 @@ namespace OpenMetaverse public byte[] GetBytes(bool inverted) { - byte[] byteArray = new byte[4]; + var byteArray = new byte[4]; ToBytes(byteArray, 0, inverted); return byteArray; } public byte[] GetFloatBytes() { - byte[] bytes = new byte[16]; + var bytes = new byte[16]; ToFloatBytes(bytes, 0); return bytes; } @@ -253,13 +231,12 @@ namespace OpenMetaverse dest[pos + 2] = Utils.FloatToByte(B, 0f, 1f); dest[pos + 3] = Utils.FloatToByte(A, 0f, 1f); - if (inverted) - { - dest[pos + 0] = (byte)(255 - dest[pos + 0]); - dest[pos + 1] = (byte)(255 - dest[pos + 1]); - dest[pos + 2] = (byte)(255 - dest[pos + 2]); - dest[pos + 3] = (byte)(255 - dest[pos + 3]); - } + if (!inverted) return; + + dest[pos + 0] = (byte)(255 - dest[pos + 0]); + dest[pos + 1] = (byte)(255 - dest[pos + 1]); + dest[pos + 2] = (byte)(255 - dest[pos + 2]); + dest[pos + 3] = (byte)(255 - dest[pos + 3]); } /// @@ -280,30 +257,32 @@ namespace OpenMetaverse { const float HUE_MAX = 360f; - float max = Math.Max(Math.Max(R, G), B); - float min = Math.Min(Math.Min(R, B), B); + var max = Math.Max(Math.Max(R, G), B); + var min = Math.Min(Math.Min(R, B), B); - if (max == min) + double TOLERANCE = Math.Abs(max * .00001); + + if (Math.Abs(max - min) < TOLERANCE) { // Achromatic, hue is undefined return -1f; } - else if (R == max) + if (Math.Abs(R - max) < TOLERANCE) { - float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return bDelta - gDelta; } - else if (G == max) + if (Math.Abs(G - max) < TOLERANCE) { - float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var bDelta = (((max - B) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return (HUE_MAX / 3f) + rDelta - bDelta; } else // B == max { - float gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); - float rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var gDelta = (((max - G) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); + var rDelta = (((max - R) * (HUE_MAX / 6f)) + ((max - min) / 2f)) / (max - min); return ((2f * HUE_MAX) / 3f) + gDelta - rDelta; } } @@ -344,9 +323,9 @@ namespace OpenMetaverse /// An fully opaque RGB color (alpha is 1.0) public static Color4 FromHSV(double hue, double saturation, double value) { - double r = 0d; - double g = 0d; - double b = 0d; + var r = 0d; + var g = 0d; + var b = 0d; if (saturation == 0d) { @@ -358,29 +337,21 @@ namespace OpenMetaverse } else { - double p; - double q; - double t; - - double fractionalSector; - int sectorNumber; - double sectorPos; - // The color wheel consists of 6 sectors. // Figure out which sector you//re in. - sectorPos = hue / 60d; - sectorNumber = (int)(Math.Floor(sectorPos)); + var sectorPos = hue / 60d; + var sectorNumber = (int)(Math.Floor(sectorPos)); // get the fractional part of the sector. // That is, how many degrees into the sector // are you? - fractionalSector = sectorPos - sectorNumber; + var fractionalSector = sectorPos - sectorNumber; // Calculate values for the three axes // of the color. - p = value * (1d - saturation); - q = value * (1d - (saturation * fractionalSector)); - t = value * (1d - (saturation * (1d - fractionalSector))); + var p = value * (1d - saturation); + var q = value * (1d - (saturation * fractionalSector)); + var t = value * (1d - (saturation * (1d - fractionalSector))); // Assign the fractional colors to r, g, and b // based on the sector the angle is in. @@ -444,17 +415,17 @@ namespace OpenMetaverse public override string ToString() { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); + return string.Format(Utils.EnUsCulture, "<{0}, {1}, {2}, {3}>", R, G, B, A); } public string ToRGBString() { - return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); + return string.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", R, G, B); } public override bool Equals(object obj) { - return (obj is Color4) ? this == (Color4)obj : false; + return (obj is Color4) && this == (Color4)obj; } public bool Equals(Color4 other) @@ -517,9 +488,9 @@ namespace OpenMetaverse #endregion Operators /// A Color4 with zero RGB values and fully opaque (alpha 1.0) - public readonly static Color4 Black = new Color4(0f, 0f, 0f, 1f); + public static readonly Color4 Black = new Color4(0f, 0f, 0f, 1f); /// A Color4 with full RGB values (1.0) and fully opaque (alpha 1.0) - public readonly static Color4 White = new Color4(1f, 1f, 1f, 1f); + public static readonly Color4 White = new Color4(1f, 1f, 1f, 1f); } } diff --git a/OpenMetaverseTypes/DoubleDictionary.cs b/OpenMetaverseTypes/DoubleDictionary.cs index b00bf220..21326406 100644 --- a/OpenMetaverseTypes/DoubleDictionary.cs +++ b/OpenMetaverseTypes/DoubleDictionary.cs @@ -38,8 +38,8 @@ namespace OpenMetaverse { public class DoubleDictionary { - Dictionary Dictionary1; - Dictionary Dictionary2; + readonly Dictionary Dictionary1; + readonly Dictionary Dictionary2; ReaderWriterLockImpl rwLock = new ReaderWriterLockImpl(); public DoubleDictionary() @@ -103,7 +103,7 @@ namespace OpenMetaverse TValue value; if (Dictionary1.TryGetValue(key1, out value)) { - foreach (KeyValuePair kvp in Dictionary2) + foreach (var kvp in Dictionary2) { if (kvp.Value.Equals(value)) { @@ -131,7 +131,7 @@ namespace OpenMetaverse TValue value; if (Dictionary2.TryGetValue(key2, out value)) { - foreach (KeyValuePair kvp in Dictionary1) + foreach (var kvp in Dictionary1) { if (kvp.Value.Equals(value)) { @@ -160,10 +160,7 @@ namespace OpenMetaverse finally { rwLock.ExitWriteLock(); } } - public int Count - { - get { return Dictionary1.Count; } - } + public int Count => Dictionary1.Count; public bool ContainsKey(TKey1 key) { @@ -203,7 +200,7 @@ namespace OpenMetaverse try { - foreach (TValue value in Dictionary1.Values) + foreach (var value in Dictionary1.Values) action(value); } finally { rwLock.ExitReadLock(); } @@ -215,7 +212,7 @@ namespace OpenMetaverse try { - foreach (KeyValuePair entry in Dictionary1) + foreach (var entry in Dictionary1) action(entry); } finally { rwLock.ExitReadLock(); } @@ -227,7 +224,7 @@ namespace OpenMetaverse try { - foreach (KeyValuePair entry in Dictionary2) + foreach (var entry in Dictionary2) action(entry); } finally { rwLock.ExitReadLock(); } @@ -238,7 +235,7 @@ namespace OpenMetaverse rwLock.EnterReadLock(); try { - foreach (TValue value in Dictionary1.Values) + foreach (var value in Dictionary1.Values) { if (predicate(value)) return value; @@ -256,7 +253,7 @@ namespace OpenMetaverse try { - foreach (TValue value in Dictionary1.Values) + foreach (var value in Dictionary1.Values) { if (predicate(value)) list.Add(value); @@ -275,14 +272,14 @@ namespace OpenMetaverse try { - foreach (KeyValuePair kvp in Dictionary1) + foreach (var kvp in Dictionary1) { if (predicate(kvp.Value)) list.Add(kvp.Key); } IList list2 = new List(list.Count); - foreach (KeyValuePair kvp in Dictionary2) + foreach (var kvp in Dictionary2) { if (predicate(kvp.Value)) list2.Add(kvp.Key); @@ -292,11 +289,11 @@ namespace OpenMetaverse try { - for (int i = 0; i < list.Count; i++) - Dictionary1.Remove(list[i]); + foreach (var t in list) + Dictionary1.Remove(t); - for (int i = 0; i < list2.Count; i++) - Dictionary2.Remove(list2[i]); + foreach (var t in list2) + Dictionary2.Remove(t); } finally { rwLock.ExitWriteLock(); } } diff --git a/OpenMetaverseTypes/Enums.cs b/OpenMetaverseTypes/Enums.cs index a3359623..ff9ce87e 100644 --- a/OpenMetaverseTypes/Enums.cs +++ b/OpenMetaverseTypes/Enums.cs @@ -42,7 +42,7 @@ namespace OpenMetaverse /// Text used when presenting ENUM to user public EnumInfoAttribute(string text) { - this.Text = text; + Text = text; } } diff --git a/OpenMetaverseTypes/ExpiringCache.cs b/OpenMetaverseTypes/ExpiringCache.cs index 1d4aa25b..7a1ffbd7 100644 --- a/OpenMetaverseTypes/ExpiringCache.cs +++ b/OpenMetaverseTypes/ExpiringCache.cs @@ -32,42 +32,36 @@ namespace OpenMetaverse { #region TimedCacheKey Class - class TimedCacheKey : IComparable + internal class TimedCacheKey : IComparable { - private DateTime expirationDate; - private bool slidingExpiration; - private TimeSpan slidingExpirationWindowSize; - private TKey key; - - public DateTime ExpirationDate { get { return expirationDate; } } - public TKey Key { get { return key; } } - public bool SlidingExpiration { get { return slidingExpiration; } } - public TimeSpan SlidingExpirationWindowSize { get { return slidingExpirationWindowSize; } } - + public DateTime ExpirationDate { get; private set; } + public TKey Key { get; } + public bool SlidingExpiration { get; } + public TimeSpan SlidingExpirationWindowSize { get; } public TimedCacheKey(TKey key, DateTime expirationDate) { - this.key = key; - this.slidingExpiration = false; - this.expirationDate = expirationDate; + Key = key; + SlidingExpiration = false; + ExpirationDate = expirationDate; } public TimedCacheKey(TKey key, TimeSpan slidingExpirationWindowSize) { - this.key = key; - this.slidingExpiration = true; - this.slidingExpirationWindowSize = slidingExpirationWindowSize; + Key = key; + SlidingExpiration = true; + SlidingExpirationWindowSize = slidingExpirationWindowSize; Accessed(); } public void Accessed() { - if (slidingExpiration) - expirationDate = DateTime.Now.Add(slidingExpirationWindowSize); + if (SlidingExpiration) + ExpirationDate = DateTime.Now.Add(SlidingExpirationWindowSize); } public int CompareTo(TKey other) { - return key.GetHashCode().CompareTo(other.GetHashCode()); + return Key.GetHashCode().CompareTo(other.GetHashCode()); } } @@ -85,8 +79,8 @@ namespace OpenMetaverse /// For thread safety object isPurging = new object(); - Dictionary, TValue> timedStorage = new Dictionary, TValue>(); - Dictionary> timedStorageIndex = new Dictionary>(); + readonly Dictionary, TValue> timedStorage = new Dictionary, TValue>(); + readonly Dictionary> timedStorageIndex = new Dictionary>(); private System.Timers.Timer timer = new System.Timers.Timer(TimeSpan.FromSeconds(CACHE_PURGE_HZ).TotalMilliseconds); #endregion @@ -116,7 +110,7 @@ namespace OpenMetaverse } else { - TimedCacheKey internalKey = new TimedCacheKey(key, DateTime.UtcNow + TimeSpan.FromSeconds(expirationSeconds)); + var internalKey = new TimedCacheKey(key, DateTime.UtcNow + TimeSpan.FromSeconds(expirationSeconds)); timedStorage.Add(internalKey, value); timedStorageIndex.Add(key, internalKey); return true; @@ -138,7 +132,7 @@ namespace OpenMetaverse } else { - TimedCacheKey internalKey = new TimedCacheKey(key, slidingExpiration); + var internalKey = new TimedCacheKey(key, slidingExpiration); timedStorage.Add(internalKey, value); timedStorageIndex.Add(key, internalKey); return true; @@ -210,27 +204,20 @@ namespace OpenMetaverse finally { Monitor.Exit(syncRoot); } } - public int Count - { - get - { - return timedStorage.Count; - } - } + public int Count => timedStorage.Count; public object this[TKey key] { get { - TValue o; if (!Monitor.TryEnter(syncRoot, MAX_LOCK_WAIT)) throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { if (timedStorageIndex.ContainsKey(key)) { - TimedCacheKey tkey = timedStorageIndex[key]; - o = timedStorage[tkey]; + var tkey = timedStorageIndex[key]; + var o = timedStorage[tkey]; timedStorage.Remove(tkey); tkey.Accessed(); timedStorage.Add(tkey, o); @@ -275,7 +262,7 @@ namespace OpenMetaverse { if (timedStorageIndex.ContainsKey(key)) { - TimedCacheKey tkey = timedStorageIndex[key]; + var tkey = timedStorageIndex[key]; o = timedStorage[tkey]; timedStorage.Remove(tkey); tkey.Accessed(); @@ -351,7 +338,7 @@ namespace OpenMetaverse return false; } - TimedCacheKey internalKey = new TimedCacheKey(key, slidingExpiration); + var internalKey = new TimedCacheKey(key, slidingExpiration); timedStorage.Add(internalKey, value); timedStorageIndex.Add(key, internalKey); return true; @@ -362,12 +349,12 @@ namespace OpenMetaverse public void CopyTo(Array array, int startIndex) { // Error checking - if (array == null) { throw new ArgumentNullException("array"); } + if (array == null) { throw new ArgumentNullException(nameof(array)); } - if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", "startIndex must be >= 0."); } + if (startIndex < 0) { throw new ArgumentOutOfRangeException(nameof(startIndex), "startIndex must be >= 0."); } - if (array.Rank > 1) { throw new ArgumentException("array must be of Rank 1 (one-dimensional)", "array"); } - if (startIndex >= array.Length) { throw new ArgumentException("startIndex must be less than the length of the array.", "startIndex"); } + if (array.Rank > 1) { throw new ArgumentException("array must be of Rank 1 (one-dimensional)", nameof(array)); } + if (startIndex >= array.Length) { throw new ArgumentException("startIndex must be less than the length of the array.", nameof(startIndex)); } if (Count > array.Length - startIndex) { throw new ArgumentException("There is not enough space from startIndex to the end of the array to accomodate all items in the cache."); } // Copy the data to the array (in a thread-safe manner) @@ -375,7 +362,7 @@ namespace OpenMetaverse throw new ApplicationException("Lock could not be acquired after " + MAX_LOCK_WAIT + "ms"); try { - foreach (object o in timedStorage) + foreach (var o in timedStorage) { array.SetValue(o, startIndex); startIndex++; @@ -399,7 +386,7 @@ namespace OpenMetaverse if (!Monitor.TryEnter(isPurging)) return; - DateTime signalTime = DateTime.UtcNow; + var signalTime = DateTime.UtcNow; try { @@ -408,9 +395,9 @@ namespace OpenMetaverse return; try { - Lazy> expiredItems = new Lazy>(); + var expiredItems = new Lazy>(); - foreach (TimedCacheKey timedKey in timedStorage.Keys) + foreach (var timedKey in timedStorage.Keys) { if (timedKey.ExpirationDate < signalTime) { @@ -427,7 +414,7 @@ namespace OpenMetaverse { foreach (TKey key in expiredItems.Value) { - TimedCacheKey timedKey = timedStorageIndex[key]; + var timedKey = timedStorageIndex[key]; timedStorageIndex.Remove(timedKey.Key); timedStorage.Remove(timedKey); } diff --git a/OpenMetaverseTypes/Lazy.cs b/OpenMetaverseTypes/Lazy.cs index ae07078f..1306515b 100644 --- a/OpenMetaverseTypes/Lazy.cs +++ b/OpenMetaverseTypes/Lazy.cs @@ -25,8 +25,6 @@ */ using System; -using System.Collections.Generic; -using System.Text; using System.Threading; namespace OpenMetaverse @@ -36,17 +34,17 @@ namespace OpenMetaverse private T _value = default(T); private volatile bool _isValueCreated = false; private Func _valueFactory = null; - private object _lock; + private readonly object _lock; - public bool IsValueCreated { get { return _isValueCreated; } } + public bool IsValueCreated => _isValueCreated; public Lazy() - : this(() => Activator.CreateInstance()) + : this(Activator.CreateInstance) { } public Lazy(bool isThreadSafe) - : this(() => Activator.CreateInstance(), isThreadSafe) + : this(Activator.CreateInstance, isThreadSafe) { } @@ -59,10 +57,10 @@ namespace OpenMetaverse { if (isThreadSafe) { - this._lock = new object(); + _lock = new object(); } - this._valueFactory = valueFactory; + _valueFactory = valueFactory; } @@ -70,30 +68,30 @@ namespace OpenMetaverse { get { - if (!this._isValueCreated) + if (!_isValueCreated) { - if (this._lock != null) + if (_lock != null) { Monitor.Enter(this._lock); } try { - T value = this._valueFactory.Invoke(); - this._valueFactory = null; + var value = _valueFactory.Invoke(); + _valueFactory = null; Thread.MemoryBarrier(); - this._value = value; - this._isValueCreated = true; + _value = value; + _isValueCreated = true; } finally { - if (this._lock != null) + if (_lock != null) { - Monitor.Exit(this._lock); + Monitor.Exit(_lock); } } } - return this._value; + return _value; } } }