From a3cb5c595cf2e04063848acdf5c541cbf022c024 Mon Sep 17 00:00:00 2001 From: Madpeter Date: Sat, 9 May 2020 20:30:21 +0100 Subject: [PATCH] Sync most changes from May 9, 2020 libremetaverse into -core --- .../JSON/JsonData.cs | 613 ++++++++------- .../JSON/JsonMapper.cs | 729 ++++++++++-------- .../Libremetaverse.types/Color4.cs | 2 +- .../Libremetaverse.types/Matrix4.cs | 2 +- .../Libremetaverse.types/Quaternion.cs | 2 +- .../Libremetaverse.types/Vector2.cs | 2 +- .../Libremetaverse.types/Vector3d.cs | 2 +- .../Libremetaverse.types/Vector4.cs | 2 +- .../Assets/Archiving/OarFile.cs | 8 +- .../Assets/AssetTypes/AssetCallingCard.cs | 2 +- .../Assets/AssetTypes/AssetLandmark.cs | 4 +- .../Assets/AssetTypes/AssetNotecard.cs | 6 +- .../Libremetaverse/GridManager.cs | 7 +- .../Libremetaverse/Messages/Messages.cs | 2 +- .../Libremetaverse/ObjectManager.cs | 125 +-- .../Libremetaverse/PacketDecoder.cs | 235 +++--- .../Libremetaverse/Permissions.cs | 2 +- .../Libremetaverse/Rendering/LindenMesh.cs | 4 +- 18 files changed, 919 insertions(+), 830 deletions(-) diff --git a/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonData.cs b/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonData.cs index 55c6fd6..b2ddedb 100644 --- a/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonData.cs +++ b/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonData.cs @@ -23,15 +23,15 @@ namespace LitJson public class JsonData : IJsonWrapper, IEquatable { #region Fields - private IList inst_array; - private bool inst_boolean; - private double inst_double; - private int inst_int; - private long inst_long; + private IList inst_array; + private bool inst_boolean; + private double inst_double; + private int inst_int; + private long inst_long; private IDictionary inst_object; - private string inst_string; - private string json; - private JsonType type; + private string inst_string; + private string json; + private JsonType type; // Used to implement the IOrderedDictionary interface private IList> object_list; @@ -39,7 +39,7 @@ namespace LitJson #region Properties - public int Count => EnsureCollection ().Count; + public int Count => EnsureCollection().Count; public bool IsArray => type == JsonType.Array; @@ -61,33 +61,37 @@ namespace LitJson #region ICollection Properties int ICollection.Count => Count; - bool ICollection.IsSynchronized => EnsureCollection ().IsSynchronized; + bool ICollection.IsSynchronized => EnsureCollection().IsSynchronized; - object ICollection.SyncRoot => EnsureCollection ().SyncRoot; + object ICollection.SyncRoot => EnsureCollection().SyncRoot; #endregion #region IDictionary Properties - bool IDictionary.IsFixedSize => EnsureDictionary ().IsFixedSize; + bool IDictionary.IsFixedSize => EnsureDictionary().IsFixedSize; - bool IDictionary.IsReadOnly => EnsureDictionary ().IsReadOnly; + bool IDictionary.IsReadOnly => EnsureDictionary().IsReadOnly; - ICollection IDictionary.Keys { - get { - EnsureDictionary (); + ICollection IDictionary.Keys + { + get + { + EnsureDictionary(); IList keys = object_list.Select(entry => entry.Key).ToList(); - return (ICollection) keys; + return (ICollection)keys; } } - ICollection IDictionary.Values { - get { - EnsureDictionary (); + ICollection IDictionary.Values + { + get + { + EnsureDictionary(); IList values = object_list.Select(entry => entry.Value).ToList(); - return (ICollection) values; + return (ICollection)values; } } #endregion @@ -113,45 +117,51 @@ namespace LitJson #region IList Properties - bool IList.IsFixedSize => EnsureList ().IsFixedSize; + bool IList.IsFixedSize => EnsureList().IsFixedSize; - bool IList.IsReadOnly => EnsureList ().IsReadOnly; + bool IList.IsReadOnly => EnsureList().IsReadOnly; #endregion #region IDictionary Indexer - object IDictionary.this[object key] { - get { - return EnsureDictionary ()[key]; + object IDictionary.this[object key] + { + get + { + return EnsureDictionary()[key]; } - set { - if (! (key is String)) - throw new ArgumentException ( + set + { + if (!(key is String)) + throw new ArgumentException( "The key has to be a string"); - JsonData data = ToJsonData (value); + JsonData data = ToJsonData(value); - this[(string) key] = data; + this[(string)key] = data; } } #endregion #region IOrderedDictionary Indexer - object IOrderedDictionary.this[int idx] { - get { - EnsureDictionary (); + object IOrderedDictionary.this[int idx] + { + get + { + EnsureDictionary(); return object_list[idx].Value; } - set { - EnsureDictionary (); - JsonData data = ToJsonData (value); + set + { + EnsureDictionary(); + JsonData data = ToJsonData(value); var old_entry = object_list[idx]; inst_object[old_entry.Key] = data; - var entry = new KeyValuePair (old_entry.Key, data); + var entry = new KeyValuePair(old_entry.Key, data); object_list[idx] = entry; } } @@ -159,14 +169,17 @@ namespace LitJson #region IList Indexer - object IList.this[int index] { - get { - return EnsureList ()[index]; + object IList.this[int index] + { + get + { + return EnsureList()[index]; } - set { - EnsureList (); - JsonData data = ToJsonData (value); + set + { + EnsureList(); + JsonData data = ToJsonData(value); this[index] = data; } @@ -175,15 +188,18 @@ namespace LitJson #region Public Indexers - public JsonData this[string prop_name] { - get { - EnsureDictionary (); + public JsonData this[string prop_name] + { + get + { + EnsureDictionary(); return inst_object[prop_name]; } - set { - EnsureDictionary (); - var entry = new KeyValuePair (prop_name, value); + set + { + EnsureDictionary(); + var entry = new KeyValuePair(prop_name, value); if (inst_object.ContainsKey(prop_name)) { for (int i = 0; i < object_list.Count; i++) @@ -206,20 +222,24 @@ namespace LitJson } } - public JsonData this[int index] { - get { - EnsureCollection (); + public JsonData this[int index] + { + get + { + EnsureCollection(); return type == JsonType.Array ? inst_array[index] : object_list[index].Value; } - set { - EnsureCollection (); + set + { + EnsureCollection(); if (type == JsonType.Array) inst_array[index] = value; - else { + else + { var entry = object_list[index]; - var new_entry = new KeyValuePair (entry.Key, value); + var new_entry = new KeyValuePair(entry.Key, value); object_list[index] = new_entry; inst_object[entry.Key] = value; @@ -232,71 +252,76 @@ namespace LitJson #region Constructors - public JsonData () + public JsonData() { } - public JsonData (bool boolean) + public JsonData(bool boolean) { type = JsonType.Boolean; inst_boolean = boolean; } - public JsonData (double number) + public JsonData(double number) { type = JsonType.Double; inst_double = number; } - public JsonData (int number) + public JsonData(int number) { type = JsonType.Int; inst_int = number; } - public JsonData (long number) + public JsonData(long number) { type = JsonType.Long; inst_long = number; } - public JsonData (object obj) + public JsonData(object obj) { - if (obj is Boolean) { + if (obj is bool b) + { type = JsonType.Boolean; - inst_boolean = (bool) obj; + inst_boolean = b; return; } - if (obj is Double) { + if (obj is double d) + { type = JsonType.Double; - inst_double = (double) obj; + inst_double = d; return; } - if (obj is Int32) { + if (obj is int i) + { type = JsonType.Int; - inst_int = (int) obj; + inst_int = i; return; } - if (obj is Int64) { + if (obj is long l) + { type = JsonType.Long; - inst_long = (long) obj; + inst_long = l; return; } - if (obj is String) { + if (obj is string s) + { type = JsonType.String; - inst_string = (string) obj; + inst_string = s; return; } - throw new ArgumentException ( + throw new ArgumentException( "Unable to wrap the given object with JsonData"); } - public JsonData (string str) + public JsonData(string str) { type = JsonType.String; inst_string = str; @@ -305,74 +330,74 @@ namespace LitJson #region Implicit Conversions - public static implicit operator JsonData (Boolean data) + public static implicit operator JsonData(Boolean data) { - return new JsonData (data); + return new JsonData(data); } - public static implicit operator JsonData (Double data) + public static implicit operator JsonData(Double data) { - return new JsonData (data); + return new JsonData(data); } - public static implicit operator JsonData (Int32 data) + public static implicit operator JsonData(Int32 data) { - return new JsonData (data); + return new JsonData(data); } - public static implicit operator JsonData (Int64 data) + public static implicit operator JsonData(Int64 data) { - return new JsonData (data); + return new JsonData(data); } - public static implicit operator JsonData (String data) + public static implicit operator JsonData(String data) { - return new JsonData (data); + return new JsonData(data); } #endregion #region Explicit Conversions - public static explicit operator Boolean (JsonData data) + public static explicit operator Boolean(JsonData data) { if (data.type != JsonType.Boolean) - throw new InvalidCastException ( + throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_boolean; } - public static explicit operator Double (JsonData data) + public static explicit operator Double(JsonData data) { if (data.type != JsonType.Double) - throw new InvalidCastException ( + throw new InvalidCastException( "Instance of JsonData doesn't hold a double"); return data.inst_double; } - public static explicit operator Int32 (JsonData data) + public static explicit operator Int32(JsonData data) { if (data.type != JsonType.Int) - throw new InvalidCastException ( + throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_int; } - public static explicit operator Int64 (JsonData data) + public static explicit operator Int64(JsonData data) { if (data.type != JsonType.Long) - throw new InvalidCastException ( + throw new InvalidCastException( "Instance of JsonData doesn't hold an int"); return data.inst_long; } - public static explicit operator String (JsonData data) + public static explicit operator String(JsonData data) { if (data.type != JsonType.String) - throw new InvalidCastException ( + throw new InvalidCastException( "Instance of JsonData doesn't hold a string"); return data.inst_string; @@ -381,50 +406,52 @@ namespace LitJson #region ICollection Methods - void ICollection.CopyTo (Array array, int index) + void ICollection.CopyTo(Array array, int index) { - EnsureCollection ().CopyTo (array, index); + EnsureCollection().CopyTo(array, index); } #endregion #region IDictionary Methods - void IDictionary.Add (object key, object value) + void IDictionary.Add(object key, object value) { - JsonData data = ToJsonData (value); + JsonData data = ToJsonData(value); - EnsureDictionary ().Add (key, data); + EnsureDictionary().Add(key, data); - var entry = new KeyValuePair ((string) key, data); - object_list.Add (entry); + var entry = new KeyValuePair((string)key, data); + object_list.Add(entry); json = null; } - void IDictionary.Clear () + void IDictionary.Clear() { - EnsureDictionary ().Clear (); - object_list.Clear (); + EnsureDictionary().Clear(); + object_list.Clear(); json = null; } - bool IDictionary.Contains (object key) + bool IDictionary.Contains(object key) { - return EnsureDictionary ().Contains (key); + return EnsureDictionary().Contains(key); } - IDictionaryEnumerator IDictionary.GetEnumerator () + IDictionaryEnumerator IDictionary.GetEnumerator() { - return ((IOrderedDictionary) this).GetEnumerator (); + return ((IOrderedDictionary)this).GetEnumerator(); } - void IDictionary.Remove (object key) + void IDictionary.Remove(object key) { - EnsureDictionary ().Remove (key); + EnsureDictionary().Remove(key); - for (int i = 0; i < object_list.Count; i++) { - if (object_list[i].Key == (string) key) { - object_list.RemoveAt (i); + for (int i = 0; i < object_list.Count; i++) + { + if (object_list[i].Key == (string)key) + { + object_list.RemoveAt(i); break; } } @@ -435,433 +462,445 @@ namespace LitJson #region IEnumerable Methods - IEnumerator IEnumerable.GetEnumerator () + IEnumerator IEnumerable.GetEnumerator() { - return EnsureCollection ().GetEnumerator (); + return EnsureCollection().GetEnumerator(); } #endregion #region IJsonWrapper Methods - bool IJsonWrapper.GetBoolean () + bool IJsonWrapper.GetBoolean() { if (type != JsonType.Boolean) - throw new InvalidOperationException ( + throw new InvalidOperationException( "JsonData instance doesn't hold a boolean"); return inst_boolean; } - double IJsonWrapper.GetDouble () + double IJsonWrapper.GetDouble() { if (type != JsonType.Double) - throw new InvalidOperationException ( + throw new InvalidOperationException( "JsonData instance doesn't hold a double"); return inst_double; } - int IJsonWrapper.GetInt () + int IJsonWrapper.GetInt() { if (type != JsonType.Int) - throw new InvalidOperationException ( + throw new InvalidOperationException( "JsonData instance doesn't hold an int"); return inst_int; } - long IJsonWrapper.GetLong () + long IJsonWrapper.GetLong() { if (type != JsonType.Long) - throw new InvalidOperationException ( + throw new InvalidOperationException( "JsonData instance doesn't hold a long"); return inst_long; } - string IJsonWrapper.GetString () + string IJsonWrapper.GetString() { if (type != JsonType.String) - throw new InvalidOperationException ( + throw new InvalidOperationException( "JsonData instance doesn't hold a string"); return inst_string; } - void IJsonWrapper.SetBoolean (bool val) + void IJsonWrapper.SetBoolean(bool val) { type = JsonType.Boolean; inst_boolean = val; json = null; } - void IJsonWrapper.SetDouble (double val) + void IJsonWrapper.SetDouble(double val) { type = JsonType.Double; inst_double = val; json = null; } - void IJsonWrapper.SetInt (int val) + void IJsonWrapper.SetInt(int val) { type = JsonType.Int; inst_int = val; json = null; } - void IJsonWrapper.SetLong (long val) + void IJsonWrapper.SetLong(long val) { type = JsonType.Long; inst_long = val; json = null; } - void IJsonWrapper.SetString (string val) + void IJsonWrapper.SetString(string val) { type = JsonType.String; inst_string = val; json = null; } - string IJsonWrapper.ToJson () + string IJsonWrapper.ToJson() { - return ToJson (); + return ToJson(); } - void IJsonWrapper.ToJson (JsonWriter writer) + void IJsonWrapper.ToJson(JsonWriter writer) { - ToJson (writer); + ToJson(writer); } #endregion #region IList Methods - int IList.Add (object value) + int IList.Add(object value) { - return Add (value); + return Add(value); } - void IList.Clear () + void IList.Clear() { - EnsureList ().Clear (); + EnsureList().Clear(); json = null; } - bool IList.Contains (object value) + bool IList.Contains(object value) { - return EnsureList ().Contains (value); + return EnsureList().Contains(value); } - int IList.IndexOf (object value) + int IList.IndexOf(object value) { - return EnsureList ().IndexOf (value); + return EnsureList().IndexOf(value); } - void IList.Insert (int index, object value) + void IList.Insert(int index, object value) { - EnsureList ().Insert (index, value); + EnsureList().Insert(index, value); json = null; } - void IList.Remove (object value) + void IList.Remove(object value) { - EnsureList ().Remove (value); + EnsureList().Remove(value); json = null; } - void IList.RemoveAt (int index) + void IList.RemoveAt(int index) { - EnsureList ().RemoveAt (index); + EnsureList().RemoveAt(index); json = null; } #endregion #region IOrderedDictionary Methods - IDictionaryEnumerator IOrderedDictionary.GetEnumerator () + IDictionaryEnumerator IOrderedDictionary.GetEnumerator() { - EnsureDictionary (); + EnsureDictionary(); - return new OrderedDictionaryEnumerator ( - object_list.GetEnumerator ()); + return new OrderedDictionaryEnumerator( + object_list.GetEnumerator()); } - void IOrderedDictionary.Insert (int idx, object key, object value) + void IOrderedDictionary.Insert(int idx, object key, object value) { - string property = (string) key; - JsonData data = ToJsonData (value); + string property = (string)key; + JsonData data = ToJsonData(value); this[property] = data; KeyValuePair entry = - new KeyValuePair (property, data); + new KeyValuePair(property, data); - object_list.Insert (idx, entry); + object_list.Insert(idx, entry); } - void IOrderedDictionary.RemoveAt (int idx) + void IOrderedDictionary.RemoveAt(int idx) { - EnsureDictionary (); + EnsureDictionary(); - inst_object.Remove (object_list[idx].Key); - object_list.RemoveAt (idx); + inst_object.Remove(object_list[idx].Key); + object_list.RemoveAt(idx); } #endregion #region Private Methods - private ICollection EnsureCollection () + private ICollection EnsureCollection() { if (type == JsonType.Array) - return (ICollection) inst_array; + return (ICollection)inst_array; if (type == JsonType.Object) - return (ICollection) inst_object; + return (ICollection)inst_object; - throw new InvalidOperationException ( + throw new InvalidOperationException( "The JsonData instance has to be initialized first"); } - private IDictionary EnsureDictionary () + private IDictionary EnsureDictionary() { if (type == JsonType.Object) - return (IDictionary) inst_object; + return (IDictionary)inst_object; if (type != JsonType.None) - throw new InvalidOperationException ( + throw new InvalidOperationException( "Instance of JsonData is not a dictionary"); type = JsonType.Object; - inst_object = new Dictionary (); - object_list = new List> (); + inst_object = new Dictionary(); + object_list = new List>(); - return (IDictionary) inst_object; + return (IDictionary)inst_object; } - private IList EnsureList () + private IList EnsureList() { if (type == JsonType.Array) - return (IList) inst_array; + return (IList)inst_array; if (type != JsonType.None) - throw new InvalidOperationException ( + throw new InvalidOperationException( "Instance of JsonData is not a list"); type = JsonType.Array; - inst_array = new List (); + inst_array = new List(); - return (IList) inst_array; + return (IList)inst_array; } - private JsonData ToJsonData (object obj) + private JsonData ToJsonData(object obj) { if (obj == null) return null; - if (obj is JsonData) - return (JsonData) obj; + if (obj is JsonData data) + return data; - return new JsonData (obj); + return new JsonData(obj); } - private static void WriteJson (IJsonWrapper obj, JsonWriter writer) + private static void WriteJson(IJsonWrapper obj, JsonWriter writer) { - if (obj.IsString) { - writer.Write (obj.GetString ()); + if (obj.IsString) + { + writer.Write(obj.GetString()); return; } - if (obj.IsBoolean) { - writer.Write (obj.GetBoolean ()); + if (obj.IsBoolean) + { + writer.Write(obj.GetBoolean()); return; } - if (obj.IsDouble) { - writer.Write (obj.GetDouble ()); + if (obj.IsDouble) + { + writer.Write(obj.GetDouble()); return; } - if (obj.IsInt) { - writer.Write (obj.GetInt ()); + if (obj.IsInt) + { + writer.Write(obj.GetInt()); return; } - if (obj.IsLong) { - writer.Write (obj.GetLong ()); + if (obj.IsLong) + { + writer.Write(obj.GetLong()); return; } - if (obj.IsArray) { - writer.WriteArrayStart (); - foreach (object elem in (IList) obj) - WriteJson ((JsonData) elem, writer); - writer.WriteArrayEnd (); + if (obj.IsArray) + { + writer.WriteArrayStart(); + foreach (object elem in (IList)obj) + WriteJson((JsonData)elem, writer); + writer.WriteArrayEnd(); return; } - if (obj.IsObject) { - writer.WriteObjectStart (); + if (obj.IsObject) + { + writer.WriteObjectStart(); - foreach (DictionaryEntry entry in ((IDictionary) obj)) { - writer.WritePropertyName ((string) entry.Key); - WriteJson ((JsonData) entry.Value, writer); + foreach (DictionaryEntry entry in ((IDictionary)obj)) + { + writer.WritePropertyName((string)entry.Key); + WriteJson((JsonData)entry.Value, writer); } - writer.WriteObjectEnd (); + writer.WriteObjectEnd(); } } #endregion - public int Add (object value) + public int Add(object value) { - JsonData data = ToJsonData (value); + JsonData data = ToJsonData(value); json = null; - return EnsureList ().Add (data); + return EnsureList().Add(data); } - public void Clear () + public void Clear() { - if (IsObject) { - ((IDictionary) this).Clear (); + if (IsObject) + { + ((IDictionary)this).Clear(); } else if (IsArray) { - ((IList) this).Clear (); + ((IList)this).Clear(); } } - public bool Equals (JsonData x) + public bool Equals(JsonData x) { if (x?.type != type) return false; - switch (this.type) { - case JsonType.None: - return true; + switch (this.type) + { + case JsonType.None: + return true; - case JsonType.Object: - return this.inst_object.Equals (x.inst_object); + case JsonType.Object: + return this.inst_object.Equals(x.inst_object); - case JsonType.Array: - return this.inst_array.Equals (x.inst_array); + case JsonType.Array: + return this.inst_array.Equals(x.inst_array); - case JsonType.String: - return this.inst_string.Equals (x.inst_string); + case JsonType.String: + return this.inst_string.Equals(x.inst_string); - case JsonType.Int: - return this.inst_int.Equals (x.inst_int); + case JsonType.Int: + return this.inst_int.Equals(x.inst_int); - case JsonType.Long: - return this.inst_long.Equals (x.inst_long); + case JsonType.Long: + return this.inst_long.Equals(x.inst_long); - case JsonType.Double: - return this.inst_double.Equals (x.inst_double); + case JsonType.Double: + return this.inst_double.Equals(x.inst_double); - case JsonType.Boolean: - return this.inst_boolean.Equals (x.inst_boolean); + case JsonType.Boolean: + return this.inst_boolean.Equals(x.inst_boolean); } return false; } - public JsonType GetJsonType () + public JsonType GetJsonType() { return type; } - public void SetJsonType (JsonType type) + public void SetJsonType(JsonType type) { if (this.type == type) return; - switch (type) { - case JsonType.None: - break; + switch (type) + { + case JsonType.None: + break; - case JsonType.Object: - inst_object = new Dictionary (); - object_list = new List> (); - break; + case JsonType.Object: + inst_object = new Dictionary(); + object_list = new List>(); + break; - case JsonType.Array: - inst_array = new List (); - break; + case JsonType.Array: + inst_array = new List(); + break; - case JsonType.String: - inst_string = default (String); - break; + case JsonType.String: + inst_string = default(String); + break; - case JsonType.Int: - inst_int = default (Int32); - break; + case JsonType.Int: + inst_int = default(Int32); + break; - case JsonType.Long: - inst_long = default (Int64); - break; + case JsonType.Long: + inst_long = default(Int64); + break; - case JsonType.Double: - inst_double = default (Double); - break; + case JsonType.Double: + inst_double = default(Double); + break; - case JsonType.Boolean: - inst_boolean = default (Boolean); - break; + case JsonType.Boolean: + inst_boolean = default(Boolean); + break; } this.type = type; } - public string ToJson () + public string ToJson() { if (json != null) return json; - StringWriter sw = new StringWriter (); - JsonWriter writer = new JsonWriter(sw) {Validate = false}; + StringWriter sw = new StringWriter(); + JsonWriter writer = new JsonWriter(sw) { Validate = false }; - WriteJson (this, writer); - json = sw.ToString (); + WriteJson(this, writer); + json = sw.ToString(); return json; } - public void ToJson (JsonWriter writer) + public void ToJson(JsonWriter writer) { bool old_validate = writer.Validate; writer.Validate = false; - WriteJson (this, writer); + WriteJson(this, writer); writer.Validate = old_validate; } - public override string ToString () + public override string ToString() { - switch (type) { - case JsonType.Array: - return "JsonData array"; + switch (type) + { + case JsonType.Array: + return "JsonData array"; - case JsonType.Boolean: - return inst_boolean.ToString (); + case JsonType.Boolean: + return inst_boolean.ToString(); - case JsonType.Double: - return inst_double.ToString (); + case JsonType.Double: + return inst_double.ToString(); - case JsonType.Int: - return inst_int.ToString (); + case JsonType.Int: + return inst_int.ToString(); - case JsonType.Long: - return inst_long.ToString (); + case JsonType.Long: + return inst_long.ToString(); - case JsonType.Object: - return "JsonData object"; + case JsonType.Object: + return "JsonData object"; - case JsonType.String: - return inst_string; + case JsonType.String: + return inst_string; } return "Uninitialized JsonData"; @@ -876,10 +915,12 @@ namespace LitJson public object Current => Entry; - public DictionaryEntry Entry { - get { + public DictionaryEntry Entry + { + get + { var curr = list_enumerator.Current; - return new DictionaryEntry (curr.Key, curr.Value); + return new DictionaryEntry(curr.Key, curr.Value); } } @@ -888,21 +929,21 @@ namespace LitJson public object Value => list_enumerator.Current.Value; - public OrderedDictionaryEnumerator ( + public OrderedDictionaryEnumerator( IEnumerator> enumerator) { list_enumerator = enumerator; } - public bool MoveNext () + public bool MoveNext() { - return list_enumerator.MoveNext (); + return list_enumerator.MoveNext(); } - public void Reset () + public void Reset() { - list_enumerator.Reset (); + list_enumerator.Reset(); } } } diff --git a/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonMapper.cs b/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonMapper.cs index 79f7fa8..582fe14 100644 --- a/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonMapper.cs +++ b/libremetaverse-core/Libremetaverse.structureddata/JSON/JsonMapper.cs @@ -22,8 +22,8 @@ namespace LitJson internal struct PropertyMetadata { public MemberInfo Info; - public bool IsField; - public Type Type; + public bool IsField; + public Type Type; } @@ -34,10 +34,12 @@ namespace LitJson private bool is_list; - public Type ElementType { - get { + public Type ElementType + { + get + { if (element_type == null) - return typeof (JsonData); + return typeof(JsonData); return element_type; } @@ -45,12 +47,14 @@ namespace LitJson set { element_type = value; } } - public bool IsArray { + public bool IsArray + { get { return is_array; } set { is_array = value; } } - public bool IsList { + public bool IsList + { get { return is_list; } set { is_list = value; } } @@ -65,10 +69,12 @@ namespace LitJson private IDictionary properties; - public Type ElementType { - get { + public Type ElementType + { + get + { if (element_type == null) - return typeof (JsonData); + return typeof(JsonData); return element_type; } @@ -76,25 +82,27 @@ namespace LitJson set { element_type = value; } } - public bool IsDictionary { + public bool IsDictionary + { get { return is_dictionary; } set { is_dictionary = value; } } - public IDictionary Properties { + public IDictionary Properties + { get { return properties; } set { properties = value; } } } - internal delegate void ExporterFunc (object obj, JsonWriter writer); - public delegate void ExporterFunc (T obj, JsonWriter writer); + internal delegate void ExporterFunc(object obj, JsonWriter writer); + public delegate void ExporterFunc(T obj, JsonWriter writer); - internal delegate object ImporterFunc (object input); - public delegate TValue ImporterFunc (TJson input); + internal delegate object ImporterFunc(object input); + public delegate TValue ImporterFunc(TJson input); - public delegate IJsonWrapper WrapperFactory (); + public delegate IJsonWrapper WrapperFactory(); public class JsonMapper @@ -113,189 +121,211 @@ namespace LitJson IDictionary> custom_importers_table; private static IDictionary array_metadata; - private static readonly object array_metadata_lock = new Object (); + private static readonly object array_metadata_lock = new Object(); private static IDictionary> conv_ops; - private static readonly object conv_ops_lock = new Object (); + private static readonly object conv_ops_lock = new Object(); private static IDictionary object_metadata; - private static readonly object object_metadata_lock = new Object (); + private static readonly object object_metadata_lock = new Object(); private static IDictionary> type_properties; - private static readonly object type_properties_lock = new Object (); + private static readonly object type_properties_lock = new Object(); - private static JsonWriter static_writer; - private static readonly object static_writer_lock = new Object (); + private static JsonWriter static_writer; + private static readonly object static_writer_lock = new Object(); #endregion #region Constructors - static JsonMapper () + static JsonMapper() { max_nesting_depth = 100; - array_metadata = new Dictionary (); - conv_ops = new Dictionary> (); - object_metadata = new Dictionary (); + array_metadata = new Dictionary(); + conv_ops = new Dictionary>(); + object_metadata = new Dictionary(); type_properties = new Dictionary> (); + IList>(); - static_writer = new JsonWriter (); + static_writer = new JsonWriter(); datetime_format = DateTimeFormatInfo.InvariantInfo; - base_exporters_table = new Dictionary (); - custom_exporters_table = new Dictionary (); + base_exporters_table = new Dictionary(); + custom_exporters_table = new Dictionary(); base_importers_table = new Dictionary> (); + IDictionary>(); custom_importers_table = new Dictionary> (); + IDictionary>(); - RegisterBaseExporters (); - RegisterBaseImporters (); + RegisterBaseExporters(); + RegisterBaseImporters(); } #endregion #region Private Methods - private static void AddArrayMetadata (Type type) + private static void AddArrayMetadata(Type type) { - if (array_metadata.ContainsKey (type)) + if (array_metadata.ContainsKey(type)) return; - ArrayMetadata data = new ArrayMetadata (); + ArrayMetadata data = new ArrayMetadata(); data.IsArray = type.IsArray; - if (type.GetInterface ("System.Collections.IList") != null) + if (type.GetInterface("System.Collections.IList") != null) data.IsList = true; - foreach (PropertyInfo p_info in type.GetProperties ()) { + foreach (PropertyInfo p_info in type.GetProperties()) + { if (p_info.Name != "Item") continue; - ParameterInfo[] parameters = p_info.GetIndexParameters (); + ParameterInfo[] parameters = p_info.GetIndexParameters(); if (parameters.Length != 1) continue; - if (parameters[0].ParameterType == typeof (int)) + if (parameters[0].ParameterType == typeof(int)) data.ElementType = p_info.PropertyType; } - lock (array_metadata_lock) { - try { - array_metadata.Add (type, data); - } catch (ArgumentException) { + lock (array_metadata_lock) + { + try + { + array_metadata.Add(type, data); + } + catch (ArgumentException) + { return; } } } - private static void AddObjectMetadata (Type type) + private static void AddObjectMetadata(Type type) { - if (object_metadata.ContainsKey (type)) + if (object_metadata.ContainsKey(type)) return; - ObjectMetadata data = new ObjectMetadata (); + ObjectMetadata data = new ObjectMetadata(); - if (type.GetInterface ("System.Collections.IDictionary") != null) + if (type.GetInterface("System.Collections.IDictionary") != null) data.IsDictionary = true; - data.Properties = new Dictionary (); + data.Properties = new Dictionary(); - foreach (PropertyInfo p_info in type.GetProperties ()) { - if (p_info.Name == "Item") { - ParameterInfo[] parameters = p_info.GetIndexParameters (); + foreach (PropertyInfo p_info in type.GetProperties()) + { + if (p_info.Name == "Item") + { + ParameterInfo[] parameters = p_info.GetIndexParameters(); if (parameters.Length != 1) continue; - if (parameters[0].ParameterType == typeof (string)) + if (parameters[0].ParameterType == typeof(string)) data.ElementType = p_info.PropertyType; continue; } - PropertyMetadata p_data = new PropertyMetadata (); + PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = p_info; p_data.Type = p_info.PropertyType; - data.Properties.Add (p_info.Name, p_data); + data.Properties.Add(p_info.Name, p_data); } - foreach (FieldInfo f_info in type.GetFields ()) { - PropertyMetadata p_data = new PropertyMetadata (); + foreach (FieldInfo f_info in type.GetFields()) + { + PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; - data.Properties.Add (f_info.Name, p_data); + data.Properties.Add(f_info.Name, p_data); } - lock (object_metadata_lock) { - try { - object_metadata.Add (type, data); - } catch (ArgumentException) { + lock (object_metadata_lock) + { + try + { + object_metadata.Add(type, data); + } + catch (ArgumentException) + { return; } } } - private static void AddTypeProperties (Type type) + private static void AddTypeProperties(Type type) { - if (type_properties.ContainsKey (type)) + if (type_properties.ContainsKey(type)) return; - IList props = new List (); + IList props = new List(); - foreach (PropertyInfo p_info in type.GetProperties ()) { + foreach (PropertyInfo p_info in type.GetProperties()) + { if (p_info.Name == "Item") continue; - PropertyMetadata p_data = new PropertyMetadata (); + PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = p_info; p_data.IsField = false; - props.Add (p_data); + props.Add(p_data); } - foreach (FieldInfo f_info in type.GetFields ()) { - PropertyMetadata p_data = new PropertyMetadata (); + foreach (FieldInfo f_info in type.GetFields()) + { + PropertyMetadata p_data = new PropertyMetadata(); p_data.Info = f_info; p_data.IsField = true; - props.Add (p_data); + props.Add(p_data); } - lock (type_properties_lock) { - try { - type_properties.Add (type, props); - } catch (ArgumentException) { + lock (type_properties_lock) + { + try + { + type_properties.Add(type, props); + } + catch (ArgumentException) + { return; } } } - private static MethodInfo GetConvOp (Type t1, Type t2) + private static MethodInfo GetConvOp(Type t1, Type t2) { lock (conv_ops_lock) { if (!conv_ops.ContainsKey(t1)) conv_ops.Add(t1, new Dictionary()); - + if (conv_ops[t1].ContainsKey(t2)) return conv_ops[t1][t2]; } var op = t1.GetMethod("op_Implicit", new[] { t2 }); - lock (conv_ops_lock) { - try { - conv_ops[t1].Add (t2, op); - } catch (ArgumentException) { + lock (conv_ops_lock) + { + try + { + conv_ops[t1].Add(t2, op); + } + catch (ArgumentException) + { return conv_ops[t1][t2]; } } @@ -303,17 +333,18 @@ namespace LitJson return op; } - private static object ReadValue (Type inst_type, JsonReader reader) + private static object ReadValue(Type inst_type, JsonReader reader) { - reader.Read (); + reader.Read(); if (reader.Token == JsonToken.ArrayEnd) return null; - if (reader.Token == JsonToken.Null) { + if (reader.Token == JsonToken.Null) + { - if (! inst_type.IsClass) - throw new JsonException (String.Format ( + if (!inst_type.IsClass) + throw new JsonException(String.Format( "Can't assign null to an instance of type {0}", inst_type)); @@ -324,135 +355,154 @@ namespace LitJson reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || - reader.Token == JsonToken.Boolean) { + reader.Token == JsonToken.Boolean) + { - Type json_type = reader.Value.GetType (); + Type json_type = reader.Value.GetType(); - if (inst_type.IsAssignableFrom (json_type)) + if (inst_type.IsAssignableFrom(json_type)) return reader.Value; // If there's a custom importer that fits, use it - if (custom_importers_table.ContainsKey (json_type) && - custom_importers_table[json_type].ContainsKey ( - inst_type)) { + if (custom_importers_table.ContainsKey(json_type) && + custom_importers_table[json_type].ContainsKey( + inst_type)) + { ImporterFunc importer = custom_importers_table[json_type][inst_type]; - return importer (reader.Value); + return importer(reader.Value); } // Maybe there's a base importer that works - if (base_importers_table.ContainsKey (json_type) && - base_importers_table[json_type].ContainsKey ( - inst_type)) { + if (base_importers_table.ContainsKey(json_type) && + base_importers_table[json_type].ContainsKey( + inst_type)) + { ImporterFunc importer = base_importers_table[json_type][inst_type]; - return importer (reader.Value); + return importer(reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) - return Enum.ToObject (inst_type, reader.Value); + return Enum.ToObject(inst_type, reader.Value); // Try using an implicit conversion operator - MethodInfo conv_op = GetConvOp (inst_type, json_type); + MethodInfo conv_op = GetConvOp(inst_type, json_type); if (conv_op != null) - return conv_op.Invoke (null, + return conv_op.Invoke(null, new object[] { reader.Value }); // No luck - throw new JsonException (String.Format ( + throw new JsonException(String.Format( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; - if (reader.Token == JsonToken.ArrayStart) { + if (reader.Token == JsonToken.ArrayStart) + { - AddArrayMetadata (inst_type); + AddArrayMetadata(inst_type); ArrayMetadata t_data = array_metadata[inst_type]; - if (! t_data.IsArray && ! t_data.IsList) - throw new JsonException (String.Format ( + if (!t_data.IsArray && !t_data.IsList) + throw new JsonException(String.Format( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; - if (! t_data.IsArray) { - list = (IList) Activator.CreateInstance (inst_type); + if (!t_data.IsArray) + { + list = (IList)Activator.CreateInstance(inst_type); elem_type = t_data.ElementType; - } else { - list = new ArrayList (); - elem_type = inst_type.GetElementType (); + } + else + { + list = new ArrayList(); + elem_type = inst_type.GetElementType(); } - while (true) { - object item = ReadValue (elem_type, reader); + while (true) + { + object item = ReadValue(elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; - list.Add (item); + list.Add(item); } - if (t_data.IsArray) { + if (t_data.IsArray) + { int n = list.Count; - instance = Array.CreateInstance (elem_type, n); + instance = Array.CreateInstance(elem_type, n); for (int i = 0; i < n; i++) - ((Array) instance).SetValue (list[i], i); - } else + ((Array)instance).SetValue(list[i], i); + } + else instance = list; - } else if (reader.Token == JsonToken.ObjectStart) { + } + else if (reader.Token == JsonToken.ObjectStart) + { - AddObjectMetadata (inst_type); + AddObjectMetadata(inst_type); ObjectMetadata t_data = object_metadata[inst_type]; - instance = Activator.CreateInstance (inst_type); + instance = Activator.CreateInstance(inst_type); - while (true) { - reader.Read (); + while (true) + { + reader.Read(); if (reader.Token == JsonToken.ObjectEnd) break; - string property = (string) reader.Value; + string property = (string)reader.Value; - if (t_data.Properties.ContainsKey (property)) { + if (t_data.Properties.ContainsKey(property)) + { PropertyMetadata prop_data = t_data.Properties[property]; - if (prop_data.IsField) { - ((FieldInfo) prop_data.Info).SetValue ( - instance, ReadValue (prop_data.Type, reader)); - } else { + if (prop_data.IsField) + { + ((FieldInfo)prop_data.Info).SetValue( + instance, ReadValue(prop_data.Type, reader)); + } + else + { PropertyInfo p_info = - (PropertyInfo) prop_data.Info; + (PropertyInfo)prop_data.Info; if (p_info.CanWrite) - p_info.SetValue ( + p_info.SetValue( instance, - ReadValue (prop_data.Type, reader), + ReadValue(prop_data.Type, reader), null); else - ReadValue (prop_data.Type, reader); + ReadValue(prop_data.Type, reader); } - } else { - if (! t_data.IsDictionary) - throw new JsonException (String.Format ( + } + else + { + if (!t_data.IsDictionary) + throw new JsonException(String.Format( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); - ((IDictionary) instance).Add ( - property, ReadValue ( + ((IDictionary)instance).Add( + property, ReadValue( t_data.ElementType, reader)); } @@ -463,55 +513,57 @@ namespace LitJson return instance; } - private static IJsonWrapper ReadValue (WrapperFactory factory, + private static IJsonWrapper ReadValue(WrapperFactory factory, JsonReader reader) { - reader.Read (); + reader.Read(); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; - IJsonWrapper instance = factory (); + IJsonWrapper instance = factory(); switch (reader.Token) { case JsonToken.String: - instance.SetString ((string) reader.Value); + instance.SetString((string)reader.Value); break; case JsonToken.Double: - instance.SetDouble ((double) reader.Value); + instance.SetDouble((double)reader.Value); break; case JsonToken.Int: - instance.SetInt ((int) reader.Value); + instance.SetInt((int)reader.Value); break; case JsonToken.Long: - instance.SetLong ((long) reader.Value); + instance.SetLong((long)reader.Value); break; case JsonToken.Boolean: - instance.SetBoolean ((bool) reader.Value); + instance.SetBoolean((bool)reader.Value); break; case JsonToken.ArrayStart: - instance.SetJsonType (JsonType.Array); + instance.SetJsonType(JsonType.Array); - while (true) { - IJsonWrapper item = ReadValue (factory, reader); + while (true) + { + IJsonWrapper item = ReadValue(factory, reader); if (item == null && reader.Token == JsonToken.ArrayEnd) break; - ((IList) instance).Add (item); + ((IList)instance).Add(item); } break; case JsonToken.ObjectStart: - instance.SetJsonType (JsonType.Object); + instance.SetJsonType(JsonType.Object); - while (true) { - reader.Read (); + while (true) + { + reader.Read(); if (reader.Token == JsonToken.ObjectEnd) break; - string property = (string) reader.Value; - ((IDictionary) instance)[property] = ReadValue ( + string property = (string)reader.Value; + ((IDictionary)instance)[property] = ReadValue( factory, reader); } break; @@ -520,382 +572,373 @@ namespace LitJson return instance; } - private static void RegisterBaseExporters () + private static void RegisterBaseExporters() { - base_exporters_table[typeof (byte)] = + base_exporters_table[typeof(byte)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToInt32 ((byte) obj)); + writer.Write(Convert.ToInt32((byte)obj)); }; - base_exporters_table[typeof (char)] = + base_exporters_table[typeof(char)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToString ((char) obj)); + writer.Write(Convert.ToString((char)obj)); }; - base_exporters_table[typeof (DateTime)] = + base_exporters_table[typeof(DateTime)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToString ((DateTime) obj, + writer.Write(Convert.ToString((DateTime)obj, datetime_format)); }; - base_exporters_table[typeof (decimal)] = + base_exporters_table[typeof(decimal)] = delegate (object obj, JsonWriter writer) { - writer.Write ((decimal) obj); + writer.Write((decimal)obj); }; - base_exporters_table[typeof (sbyte)] = + base_exporters_table[typeof(sbyte)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToInt32 ((sbyte) obj)); + writer.Write(Convert.ToInt32((sbyte)obj)); }; - base_exporters_table[typeof (short)] = + base_exporters_table[typeof(short)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToInt32 ((short) obj)); + writer.Write(Convert.ToInt32((short)obj)); }; - base_exporters_table[typeof (ushort)] = + base_exporters_table[typeof(ushort)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToInt32 ((ushort) obj)); + writer.Write(Convert.ToInt32((ushort)obj)); }; - base_exporters_table[typeof (uint)] = + base_exporters_table[typeof(uint)] = delegate (object obj, JsonWriter writer) { - writer.Write (Convert.ToUInt64 ((uint) obj)); + writer.Write(Convert.ToUInt64((uint)obj)); }; - base_exporters_table[typeof (ulong)] = + base_exporters_table[typeof(ulong)] = delegate (object obj, JsonWriter writer) { - writer.Write ((ulong) obj); + writer.Write((ulong)obj); }; } - private static void RegisterBaseImporters () + private static void RegisterBaseImporters() { - ImporterFunc importer; + ImporterFunc importer = input => Convert.ToByte((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(byte), importer); - importer = delegate (object input) { - return Convert.ToByte ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (byte), importer); + importer = input => Convert.ToUInt64((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(ulong), importer); - importer = delegate (object input) { - return Convert.ToUInt64 ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (ulong), importer); + importer = input => Convert.ToSByte((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(sbyte), importer); - importer = delegate (object input) { - return Convert.ToSByte ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (sbyte), importer); + importer = input => Convert.ToInt16((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(short), importer); - importer = delegate (object input) { - return Convert.ToInt16 ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (short), importer); + importer = input => Convert.ToUInt16((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(ushort), importer); - importer = delegate (object input) { - return Convert.ToUInt16 ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (ushort), importer); + importer = input => Convert.ToUInt32((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(uint), importer); - importer = delegate (object input) { - return Convert.ToUInt32 ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (uint), importer); + importer = input => Convert.ToSingle((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(float), importer); - importer = delegate (object input) { - return Convert.ToSingle ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (float), importer); + importer = input => Convert.ToDouble((int)input); + RegisterImporter(base_importers_table, typeof(int), + typeof(double), importer); - importer = delegate (object input) { - return Convert.ToDouble ((int) input); - }; - RegisterImporter (base_importers_table, typeof (int), - typeof (double), importer); - - importer = delegate (object input) { - return Convert.ToDecimal ((double) input); - }; - RegisterImporter (base_importers_table, typeof (double), - typeof (decimal), importer); + importer = input => Convert.ToDecimal((double)input); + RegisterImporter(base_importers_table, typeof(double), + typeof(decimal), importer); - importer = delegate (object input) { - return Convert.ToUInt32 ((long) input); - }; - RegisterImporter (base_importers_table, typeof (long), - typeof (uint), importer); + importer = input => Convert.ToUInt32((long)input); + RegisterImporter(base_importers_table, typeof(long), + typeof(uint), importer); - importer = delegate (object input) { - return Convert.ToChar ((string) input); - }; - RegisterImporter (base_importers_table, typeof (string), - typeof (char), importer); + importer = input => Convert.ToChar((string)input); + RegisterImporter(base_importers_table, typeof(string), + typeof(char), importer); - importer = delegate (object input) { - return Convert.ToDateTime ((string) input, datetime_format); - }; - RegisterImporter (base_importers_table, typeof (string), - typeof (DateTime), importer); + importer = input => Convert.ToDateTime((string)input, datetime_format); + RegisterImporter(base_importers_table, typeof(string), + typeof(DateTime), importer); } - private static void RegisterImporter ( + private static void RegisterImporter( IDictionary> table, Type json_type, Type value_type, ImporterFunc importer) { - if (! table.ContainsKey (json_type)) - table.Add (json_type, new Dictionary ()); + if (!table.ContainsKey(json_type)) + table.Add(json_type, new Dictionary()); table[json_type][value_type] = importer; } - private static void WriteValue (object obj, JsonWriter writer, + private static void WriteValue(object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) - throw new JsonException ( - String.Format ("Max allowed object depth reached while " + + throw new JsonException( + String.Format("Max allowed object depth reached while " + "trying to export from type {0}", - obj.GetType ())); + obj.GetType())); - if (obj == null) { - writer.Write (null); + if (obj == null) + { + writer.Write(null); return; } - if (obj is IJsonWrapper) { + if (obj is IJsonWrapper wrapper) + { if (writer_is_private) - writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); + writer.TextWriter.Write(wrapper.ToJson()); else - ((IJsonWrapper) obj).ToJson (writer); + wrapper.ToJson(writer); return; } - if (obj is String) { - writer.Write ((string) obj); + if (obj is string s) + { + writer.Write(s); return; } - if (obj is Double) { - writer.Write ((double) obj); + if (obj is double d) + { + writer.Write(d); return; } - if (obj is Int32) { - writer.Write ((int) obj); + if (obj is int i) + { + writer.Write(i); return; } - if (obj is Boolean) { - writer.Write ((bool) obj); + if (obj is bool b) + { + writer.Write(b); return; } - if (obj is Int64) { - writer.Write ((long) obj); + if (obj is long l) + { + writer.Write(l); return; } - if (obj is Array) { - writer.WriteArrayStart (); + if (obj is Array array) + { + writer.WriteArrayStart(); - foreach (object elem in (Array) obj) - WriteValue (elem, writer, writer_is_private, depth + 1); + foreach (object elem in array) + WriteValue(elem, writer, writer_is_private, depth + 1); - writer.WriteArrayEnd (); + writer.WriteArrayEnd(); return; } - if (obj is IList) { - writer.WriteArrayStart (); - foreach (object elem in (IList) obj) - WriteValue (elem, writer, writer_is_private, depth + 1); - writer.WriteArrayEnd (); + if (obj is IList list) + { + writer.WriteArrayStart(); + foreach (object elem in list) + WriteValue(elem, writer, writer_is_private, depth + 1); + writer.WriteArrayEnd(); return; } - if (obj is IDictionary) { - writer.WriteObjectStart (); - foreach (DictionaryEntry entry in (IDictionary) obj) { - writer.WritePropertyName ((string) entry.Key); - WriteValue (entry.Value, writer, writer_is_private, + if (obj is IDictionary dictionary) + { + writer.WriteObjectStart(); + foreach (DictionaryEntry entry in dictionary) + { + writer.WritePropertyName((string)entry.Key); + WriteValue(entry.Value, writer, writer_is_private, depth + 1); } - writer.WriteObjectEnd (); + writer.WriteObjectEnd(); return; } - Type obj_type = obj.GetType (); + Type obj_type = obj.GetType(); // See if there's a custom exporter for the object - if (custom_exporters_table.ContainsKey (obj_type)) { + if (custom_exporters_table.ContainsKey(obj_type)) + { ExporterFunc exporter = custom_exporters_table[obj_type]; - exporter (obj, writer); + exporter(obj, writer); return; } // If not, maybe there's a base exporter - if (base_exporters_table.ContainsKey (obj_type)) { + if (base_exporters_table.ContainsKey(obj_type)) + { ExporterFunc exporter = base_exporters_table[obj_type]; - exporter (obj, writer); + exporter(obj, writer); return; } // Last option, let's see if it's an enum - if (obj is Enum) { - Type e_type = Enum.GetUnderlyingType (obj_type); + if (obj is Enum) + { + Type e_type = Enum.GetUnderlyingType(obj_type); - if (e_type == typeof (long) - || e_type == typeof (uint) - || e_type == typeof (ulong)) - writer.Write ((ulong) obj); + if (e_type == typeof(long) + || e_type == typeof(uint) + || e_type == typeof(ulong)) + writer.Write((ulong)obj); else - writer.Write ((int) obj); + writer.Write((int)obj); return; } // Okay, so it looks like the input should be exported as an // object - AddTypeProperties (obj_type); + AddTypeProperties(obj_type); IList props = type_properties[obj_type]; - writer.WriteObjectStart (); - foreach (PropertyMetadata p_data in props) { - if (p_data.IsField) { - writer.WritePropertyName (p_data.Info.Name); - WriteValue (((FieldInfo) p_data.Info).GetValue (obj), + writer.WriteObjectStart(); + foreach (PropertyMetadata p_data in props) + { + if (p_data.IsField) + { + writer.WritePropertyName(p_data.Info.Name); + WriteValue(((FieldInfo)p_data.Info).GetValue(obj), writer, writer_is_private, depth + 1); } - else { - PropertyInfo p_info = (PropertyInfo) p_data.Info; + else + { + PropertyInfo p_info = (PropertyInfo)p_data.Info; - if (p_info.CanRead) { - writer.WritePropertyName (p_data.Info.Name); - WriteValue (p_info.GetValue (obj, null), + if (p_info.CanRead) + { + writer.WritePropertyName(p_data.Info.Name); + WriteValue(p_info.GetValue(obj, null), writer, writer_is_private, depth + 1); } } } - writer.WriteObjectEnd (); + writer.WriteObjectEnd(); } #endregion - public static string ToJson (object obj) + public static string ToJson(object obj) { - lock (static_writer_lock) { - static_writer.Reset (); + lock (static_writer_lock) + { + static_writer.Reset(); - WriteValue (obj, static_writer, true, 0); + WriteValue(obj, static_writer, true, 0); - return static_writer.ToString (); + return static_writer.ToString(); } } - public static void ToJson (object obj, JsonWriter writer) + public static void ToJson(object obj, JsonWriter writer) { - WriteValue (obj, writer, false, 0); + WriteValue(obj, writer, false, 0); } - public static JsonData ToObject (JsonReader reader) + public static JsonData ToObject(JsonReader reader) { - return (JsonData) ToWrapper ( - delegate { return new JsonData (); }, reader); + return (JsonData)ToWrapper( + () => new JsonData(), reader); } - public static JsonData ToObject (TextReader reader) + public static JsonData ToObject(TextReader reader) { - JsonReader json_reader = new JsonReader (reader); + JsonReader json_reader = new JsonReader(reader); - return (JsonData) ToWrapper ( - delegate { return new JsonData (); }, json_reader); + return (JsonData)ToWrapper( + () => new JsonData(), json_reader); } - public static JsonData ToObject (string json) + public static JsonData ToObject(string json) { - return (JsonData) ToWrapper ( - delegate { return new JsonData (); }, json); + return (JsonData)ToWrapper( + () => new JsonData(), json); } - public static T ToObject (JsonReader reader) + public static T ToObject(JsonReader reader) { - return (T) ReadValue (typeof (T), reader); + return (T)ReadValue(typeof(T), reader); } - public static T ToObject (TextReader reader) + public static T ToObject(TextReader reader) { - JsonReader json_reader = new JsonReader (reader); + JsonReader json_reader = new JsonReader(reader); - return (T) ReadValue (typeof (T), json_reader); + return (T)ReadValue(typeof(T), json_reader); } - public static T ToObject (string json) + public static T ToObject(string json) { - JsonReader reader = new JsonReader (json); + JsonReader reader = new JsonReader(json); - return (T) ReadValue (typeof (T), reader); + return (T)ReadValue(typeof(T), reader); } - public static IJsonWrapper ToWrapper (WrapperFactory factory, + public static IJsonWrapper ToWrapper(WrapperFactory factory, JsonReader reader) { - return ReadValue (factory, reader); + return ReadValue(factory, reader); } - public static IJsonWrapper ToWrapper (WrapperFactory factory, + public static IJsonWrapper ToWrapper(WrapperFactory factory, string json) { - JsonReader reader = new JsonReader (json); + JsonReader reader = new JsonReader(json); - return ReadValue (factory, reader); + return ReadValue(factory, reader); } - public static void RegisterExporter (ExporterFunc exporter) + public static void RegisterExporter(ExporterFunc exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { - exporter ((T) obj, writer); + exporter((T)obj, writer); }; - custom_exporters_table[typeof (T)] = exporter_wrapper; + custom_exporters_table[typeof(T)] = exporter_wrapper; } - public static void RegisterImporter ( + public static void RegisterImporter( ImporterFunc importer) { ImporterFunc importer_wrapper = - delegate (object input) { - return importer ((TJson) input); - }; + input => importer((TJson)input); - RegisterImporter (custom_importers_table, typeof (TJson), - typeof (TValue), importer_wrapper); + RegisterImporter(custom_importers_table, typeof(TJson), + typeof(TValue), importer_wrapper); } - public static void UnregisterExporters () + public static void UnregisterExporters() { - custom_exporters_table.Clear (); + custom_exporters_table.Clear(); } - public static void UnregisterImporters () + public static void UnregisterImporters() { - custom_importers_table.Clear (); + custom_importers_table.Clear(); } } } diff --git a/libremetaverse-core/Libremetaverse.types/Color4.cs b/libremetaverse-core/Libremetaverse.types/Color4.cs index ebde8b2..0b7dd8e 100644 --- a/libremetaverse-core/Libremetaverse.types/Color4.cs +++ b/libremetaverse-core/Libremetaverse.types/Color4.cs @@ -425,7 +425,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Color4) && this == (Color4)obj; + return (obj is Color4 color4) && this == color4; } public bool Equals(Color4 other) diff --git a/libremetaverse-core/Libremetaverse.types/Matrix4.cs b/libremetaverse-core/Libremetaverse.types/Matrix4.cs index 99a759b..f3c9c83 100644 --- a/libremetaverse-core/Libremetaverse.types/Matrix4.cs +++ b/libremetaverse-core/Libremetaverse.types/Matrix4.cs @@ -986,7 +986,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Matrix4) ? this.Equals((Matrix4)obj) : false; + return (obj is Matrix4 matrix4) && this.Equals(matrix4); } public bool Equals(Matrix4 other) diff --git a/libremetaverse-core/Libremetaverse.types/Quaternion.cs b/libremetaverse-core/Libremetaverse.types/Quaternion.cs index 900b003..f4ffdf0 100644 --- a/libremetaverse-core/Libremetaverse.types/Quaternion.cs +++ b/libremetaverse-core/Libremetaverse.types/Quaternion.cs @@ -675,7 +675,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Quaternion) ? this == (Quaternion)obj : false; + return (obj is Quaternion quaternion) && this == quaternion; } public bool Equals(Quaternion other) diff --git a/libremetaverse-core/Libremetaverse.types/Vector2.cs b/libremetaverse-core/Libremetaverse.types/Vector2.cs index 9e3be7e..5de75a7 100644 --- a/libremetaverse-core/Libremetaverse.types/Vector2.cs +++ b/libremetaverse-core/Libremetaverse.types/Vector2.cs @@ -344,7 +344,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Vector2) ? this == ((Vector2)obj) : false; + return (obj is Vector2 vector2) && this == vector2; } public bool Equals(Vector2 other) diff --git a/libremetaverse-core/Libremetaverse.types/Vector3d.cs b/libremetaverse-core/Libremetaverse.types/Vector3d.cs index 84ede5c..5c68536 100644 --- a/libremetaverse-core/Libremetaverse.types/Vector3d.cs +++ b/libremetaverse-core/Libremetaverse.types/Vector3d.cs @@ -381,7 +381,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Vector3d) ? this == (Vector3d)obj : false; + return (obj is Vector3d v3d) && this == v3d; } public bool Equals(Vector3d other) diff --git a/libremetaverse-core/Libremetaverse.types/Vector4.cs b/libremetaverse-core/Libremetaverse.types/Vector4.cs index 06c4915..f4c4e07 100644 --- a/libremetaverse-core/Libremetaverse.types/Vector4.cs +++ b/libremetaverse-core/Libremetaverse.types/Vector4.cs @@ -425,7 +425,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Vector4) ? this == (Vector4)obj : false; + return (obj is Vector4 vector4) && this == vector4; } public bool Equals(Vector4 other) diff --git a/libremetaverse-core/Libremetaverse/Assets/Archiving/OarFile.cs b/libremetaverse-core/Libremetaverse/Assets/Archiving/OarFile.cs index ab56d07..6259161 100644 --- a/libremetaverse-core/Libremetaverse/Assets/Archiving/OarFile.cs +++ b/libremetaverse-core/Libremetaverse/Assets/Archiving/OarFile.cs @@ -110,13 +110,13 @@ namespace OpenMetaverse.Assets { // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); - int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); + int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR, StringComparison.Ordinal); if (i == -1) { - Logger.Log(String.Format( - "[OarFile]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", - assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR), Helpers.LogLevel.Warning); + Logger.Log( + $"[OarFile]: Could not find extension information in asset path {assetPath} since it's missing the separator " + + $"{ArchiveConstants.ASSET_EXTENSION_SEPARATOR}. Skipping", Helpers.LogLevel.Warning); return false; } diff --git a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetCallingCard.cs b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetCallingCard.cs index 2f93f4d..ef1ca4d 100644 --- a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetCallingCard.cs +++ b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetCallingCard.cs @@ -83,7 +83,7 @@ namespace OpenMetaverse.Assets String text = Utils.BytesToString(AssetData); if (text.ToLower().Contains("callingcard version 2")) { - AvatarID = new UUID(text.Substring(text.IndexOf("avatar_id") + 10, 36)); + AvatarID = new UUID(text.Substring(text.IndexOf("avatar_id", StringComparison.Ordinal) + 10, 36)); return true; } return false; diff --git a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetLandmark.cs b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetLandmark.cs index 96feea7..67813af 100644 --- a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetLandmark.cs +++ b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetLandmark.cs @@ -75,9 +75,9 @@ namespace OpenMetaverse.Assets String text = Utils.BytesToString(AssetData); if (text.ToLower().Contains("landmark version 2")) { - RegionID = new UUID(text.Substring(text.IndexOf("region_id") + 10, 36)); + RegionID = new UUID(text.Substring(text.IndexOf("region_id", StringComparison.Ordinal) + 10, 36)); String vecDelim = " "; - String[] vecStrings = text.Substring(text.IndexOf("local_pos") + 10).Split(vecDelim.ToCharArray()); + String[] vecStrings = text.Substring(text.IndexOf("local_pos", StringComparison.Ordinal) + 10).Split(vecDelim.ToCharArray()); if (vecStrings.Length == 3) { Position = new Vector3(float.Parse(vecStrings[0], System.Globalization.CultureInfo.InvariantCulture), float.Parse(vecStrings[1], System.Globalization.CultureInfo.InvariantCulture), float.Parse(vecStrings[2], System.Globalization.CultureInfo.InvariantCulture)); diff --git a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetNotecard.cs b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetNotecard.cs index a6aa8fa..a53e0ee 100644 --- a/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetNotecard.cs +++ b/libremetaverse-core/Libremetaverse/Assets/AssetTypes/AssetNotecard.cs @@ -342,11 +342,11 @@ namespace OpenMetaverse.Assets } else if (key == "name") { - name = val.Remove(val.LastIndexOf("|")); + name = val.Remove(val.LastIndexOf("|", StringComparison.Ordinal)); } else if (key == "desc") { - description = val.Remove(val.LastIndexOf("|")); + description = val.Remove(val.LastIndexOf("|", StringComparison.Ordinal)); } else if (key == "creation_date") { @@ -388,7 +388,7 @@ namespace OpenMetaverse.Assets { BodyText += lines[i++] + "\n"; } - BodyText = BodyText.Remove(BodyText.LastIndexOf("}")); + BodyText = BodyText.Remove(BodyText.LastIndexOf("}", StringComparison.Ordinal)); return true; } catch (Exception ex) diff --git a/libremetaverse-core/Libremetaverse/GridManager.cs b/libremetaverse-core/Libremetaverse/GridManager.cs index ac76f3a..78e313a 100644 --- a/libremetaverse-core/Libremetaverse/GridManager.cs +++ b/libremetaverse-core/Libremetaverse/GridManager.cs @@ -129,8 +129,8 @@ namespace OpenMetaverse /// public override bool Equals(object obj) { - if (obj is GridRegion) - return Equals((GridRegion)obj); + if (obj is GridRegion region) + return Equals(region); else return false; } @@ -811,7 +811,8 @@ namespace OpenMetaverse } // find stale entries (people who left the sim) - List removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return !coarseEntries.ContainsKey(findID); }); + List removedEntries = e.Simulator.avatarPositions.FindAll( + findID => !coarseEntries.ContainsKey(findID)); // anyone who was not listed in the previous update List newEntries = new List(); diff --git a/libremetaverse-core/Libremetaverse/Messages/Messages.cs b/libremetaverse-core/Libremetaverse/Messages/Messages.cs index 9d869a2..b472407 100644 --- a/libremetaverse-core/Libremetaverse/Messages/Messages.cs +++ b/libremetaverse-core/Libremetaverse/Messages/Messages.cs @@ -44,7 +44,7 @@ namespace OpenMetaverse.Messages public static OSD FromIP(IPAddress address) { - if (address != null && address != IPAddress.Any) + if (address != null && !Equals(address, IPAddress.Any)) return OSD.FromBinary(address.GetAddressBytes()); else return new OSD(); diff --git a/libremetaverse-core/Libremetaverse/ObjectManager.cs b/libremetaverse-core/Libremetaverse/ObjectManager.cs index 46bce37..5bc8457 100644 --- a/libremetaverse-core/Libremetaverse/ObjectManager.cs +++ b/libremetaverse-core/Libremetaverse/ObjectManager.cs @@ -284,7 +284,8 @@ namespace OpenMetaverse /// /// A ParticleUpdateEventArgs object containing /// the data sent from the simulator - protected virtual void OnParticleUpdate(ParticleUpdateEventArgs e) { + protected virtual void OnParticleUpdate(ParticleUpdateEventArgs e) + { EventHandler handler = m_ParticleUpdate; if (handler != null) handler(this, e); @@ -305,7 +306,8 @@ namespace OpenMetaverse #endregion AvatarUpdate event #region TerseObjectUpdate event - public event EventHandler ParticleUpdate { + public event EventHandler ParticleUpdate + { add { lock (m_ParticleUpdateLock) { m_ParticleUpdate += value; } } remove { lock (m_ParticleUpdateLock) { m_ParticleUpdate -= value; } } } @@ -1685,16 +1687,18 @@ namespace OpenMetaverse { ObjectMediaNavigateMessage req = new ObjectMediaNavigateMessage { - PrimID = primID, URL = newURL, Face = face + PrimID = primID, + URL = newURL, + Face = face }; request.OnComplete += (client, result, error) => + { + if (error != null) { - if (error != null) - { - Logger.Log("ObjectMediaNavigate: " + error.Message, Helpers.LogLevel.Error, Client); - } - }; + Logger.Log("ObjectMediaNavigate: " + error.Message, Helpers.LogLevel.Error, Client); + } + }; request.BeginGetResponse(req.Serialize(), OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } @@ -1716,15 +1720,15 @@ namespace OpenMetaverse CapsClient request; if (sim.Caps != null && (request = Client.Network.CurrentSim.Caps.CreateCapsClient("ObjectMedia")) != null) { - ObjectMediaUpdate req = new ObjectMediaUpdate {PrimID = primID, FaceMedia = faceMedia, Verb = "UPDATE"}; + ObjectMediaUpdate req = new ObjectMediaUpdate { PrimID = primID, FaceMedia = faceMedia, Verb = "UPDATE" }; request.OnComplete += (client, result, error) => + { + if (error != null) { - if (error != null) - { - Logger.Log("ObjectMediaUpdate: " + error.Message, Helpers.LogLevel.Error, Client); - } - }; + Logger.Log("ObjectMediaUpdate: " + error.Message, Helpers.LogLevel.Error, Client); + } + }; request.BeginGetResponse(req.Serialize(), OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } else @@ -1744,44 +1748,42 @@ namespace OpenMetaverse CapsClient request; if (sim.Caps != null && (request = Client.Network.CurrentSim.Caps.CreateCapsClient("ObjectMedia")) != null) { - ObjectMediaRequest req = new ObjectMediaRequest {PrimID = primID, Verb = "GET"}; + ObjectMediaRequest req = new ObjectMediaRequest { PrimID = primID, Verb = "GET" }; request.OnComplete += (client, result, error) => + { + if (result == null) { - if (result == null) + Logger.Log("Failed retrieving ObjectMedia data", Helpers.LogLevel.Error, Client); + try { callback(false, string.Empty, null); } + catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } + return; + } + + ObjectMediaMessage msg = new ObjectMediaMessage(); + msg.Deserialize((OSDMap)result); + + if (msg.Request is ObjectMediaResponse response) + { + if (Client.Settings.OBJECT_TRACKING) { - Logger.Log("Failed retrieving ObjectMedia data", Helpers.LogLevel.Error, Client); - try { callback(false, string.Empty, null); } - catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } - return; - } - - ObjectMediaMessage msg = new ObjectMediaMessage(); - msg.Deserialize((OSDMap)result); - - if (msg.Request is ObjectMediaResponse) - { - ObjectMediaResponse response = (ObjectMediaResponse)msg.Request; - - if (Client.Settings.OBJECT_TRACKING) + Primitive prim = sim.ObjectsPrimitives.Find((Primitive p) => p.ID == primID); + if (prim != null) { - Primitive prim = sim.ObjectsPrimitives.Find((Primitive p) => { return p.ID == primID; }); - if (prim != null) - { - prim.MediaVersion = response.Version; - prim.FaceMedia = response.FaceMedia; - } + prim.MediaVersion = response.Version; + prim.FaceMedia = response.FaceMedia; } + } - try { callback(true, response.Version, response.FaceMedia); } - catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } - } - else - { - try { callback(false, string.Empty, null); } - catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } - } - }; + try { callback(true, response.Version, response.FaceMedia); } + catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } + } + else + { + try { callback(false, string.Empty, null); } + catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client); } + } + }; request.BeginGetResponse(req.Serialize(), OSDFormat.Xml, Client.Settings.CAPS_TIMEOUT); } @@ -2109,15 +2111,16 @@ namespace OpenMetaverse prim.Rotation = objectupdate.Rotation; prim.AngularVelocity = objectupdate.AngularVelocity; #endregion - + EventHandler handler = m_ObjectUpdate; if (handler != null) { - ThreadPool.QueueUserWorkItem(delegate(object o) + ThreadPool.QueueUserWorkItem(delegate (object o) { handler(this, new PrimEventArgs(simulator, prim, update.RegionData.TimeDilation, isNewObject, attachment)); }); } //OnParticleUpdate handler replacing decode particles, PCode.Particle system appears to be deprecated this is a fix - if (prim.ParticleSys.PartMaxAge != 0) { + if (prim.ParticleSys.PartMaxAge != 0) + { OnParticleUpdate(new ParticleUpdateEventArgs(simulator, prim.ParticleSys, prim)); } @@ -2334,7 +2337,7 @@ namespace OpenMetaverse EventHandler handler = m_TerseObjectUpdate; if (handler != null) { - ThreadPool.QueueUserWorkItem(delegate(object o) + ThreadPool.QueueUserWorkItem(delegate (object o) { handler(this, new TerseObjectUpdateEventArgs(simulator, obj, update, terse.RegionData.TimeDilation)); }); } @@ -2500,7 +2503,7 @@ namespace OpenMetaverse i++; // Text color - prim.TextColor = new Color4(block.Data, i,false,true); + prim.TextColor = new Color4(block.Data, i, false, true); i += 4; } else @@ -2626,7 +2629,7 @@ namespace OpenMetaverse catch (IndexOutOfRangeException ex) { Logger.Log("Error decoding an ObjectUpdateCompressed packet", Helpers.LogLevel.Warning, Client, ex); - Logger.Log(block.ToString(), Helpers.LogLevel.Warning); // ? Might want to look into what .ToString here returns + Logger.Log(block.ToString(), Helpers.LogLevel.Warning); } } } @@ -2656,9 +2659,9 @@ namespace OpenMetaverse { continue; } - } + } ids.Add(localID); - } + } RequestObjects(simulator, ids); } } @@ -2808,7 +2811,7 @@ namespace OpenMetaverse if (Client.Settings.OBJECT_TRACKING) { Primitive findPrim = simulator.ObjectsPrimitives.Find( - delegate(Primitive prim) { return prim.ID == props.ObjectID; }); + prim => prim.ID == props.ObjectID); if (findPrim != null) { @@ -2858,7 +2861,7 @@ namespace OpenMetaverse if (Client.Settings.OBJECT_TRACKING) { Primitive findPrim = simulator.ObjectsPrimitives.Find( - delegate(Primitive prim) { return prim.ID == op.ObjectData.ObjectID; }); + prim => prim.ID == op.ObjectData.ObjectID); if (findPrim != null) { @@ -3132,7 +3135,7 @@ namespace OpenMetaverse #region Object Tracking Link - /// + /// /// /// /// @@ -3254,7 +3257,7 @@ namespace OpenMetaverse // Iterate through all of this sims avatars sim.ObjectsAvatars.ForEach( - delegate(Avatar avatar) + delegate (Avatar avatar) { #region Linear Motion // Only do movement interpolation (extrapolation) when there is a non-zero velocity but @@ -3271,7 +3274,7 @@ namespace OpenMetaverse // Iterate through all of this sims primitives sim.ObjectsPrimitives.ForEach( - delegate(Primitive prim) + delegate (Primitive prim) { if (prim.Joint == JointType.Invalid) { @@ -3472,7 +3475,8 @@ namespace OpenMetaverse } } - public class ParticleUpdateEventArgs : EventArgs { + public class ParticleUpdateEventArgs : EventArgs + { private readonly Simulator m_Simulator; private readonly Primitive.ParticleSystem m_ParticleSystem; private readonly Primitive m_Source; @@ -3490,7 +3494,8 @@ namespace OpenMetaverse /// The simulator the packet originated from /// The ParticleSystem data /// The Primitive source - public ParticleUpdateEventArgs(Simulator simulator, Primitive.ParticleSystem particlesystem, Primitive source) { + public ParticleUpdateEventArgs(Simulator simulator, Primitive.ParticleSystem particlesystem, Primitive source) + { this.m_Simulator = simulator; this.m_ParticleSystem = particlesystem; this.m_Source = source; diff --git a/libremetaverse-core/Libremetaverse/PacketDecoder.cs b/libremetaverse-core/Libremetaverse/PacketDecoder.cs index ddbd7e9..9683ed1 100644 --- a/libremetaverse-core/Libremetaverse/PacketDecoder.cs +++ b/libremetaverse-core/Libremetaverse/PacketDecoder.cs @@ -165,7 +165,7 @@ namespace OpenMetaverse.Packets private static string DecodeTerseUpdate(string fieldName, object fieldData) { - byte[] block = (byte[]) fieldData; + byte[] block = (byte[])fieldData; int i = 4; StringBuilder result = new StringBuilder(); @@ -182,7 +182,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, "State", point, - "(" + (AttachmentPoint) point + ")", + "(" + (AttachmentPoint)point + ")", "AttachmentPoint"); // Avatar boolean @@ -256,7 +256,7 @@ namespace OpenMetaverse.Packets private static string DecodeObjectCompressedData(string fieldName, object fieldData) { StringBuilder result = new StringBuilder(); - byte[] block = (byte[]) fieldData; + byte[] block = (byte[])fieldData; int i = 0; // UUID @@ -267,7 +267,7 @@ namespace OpenMetaverse.Packets i += 16; // Local ID - uint LocalID = (uint) (block[i++] + (block[i++] << 8) + + uint LocalID = (uint)(block[i++] + (block[i++] << 8) + (block[i++] << 16) + (block[i++] << 24)); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, @@ -275,19 +275,19 @@ namespace OpenMetaverse.Packets LocalID, "Uint32"); // PCode - PCode pcode = (PCode) block[i++]; + PCode pcode = (PCode)block[i++]; result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, "PCode", - (int) pcode, + (int)pcode, "(" + pcode + ")", "PCode"); // State - AttachmentPoint point = (AttachmentPoint) block[i++]; + AttachmentPoint point = (AttachmentPoint)block[i++]; result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, "State", - (byte) point, + (byte)point, "(" + point + ")", "AttachmentPoint"); @@ -302,14 +302,14 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, "Material", block[i], - "(" + (Material) block[i++] + ")", + "(" + (Material)block[i++] + ")", "Material"); // Click action result.AppendFormat("{0,30}: {1,-3} {2,-36} [{3}]" + Environment.NewLine, "ClickAction", block[i], - "(" + (ClickAction) block[i++] + ")", + "(" + (ClickAction)block[i++] + ")", "ClickAction"); // Scale @@ -334,11 +334,11 @@ namespace OpenMetaverse.Packets i += 12; // Compressed flags - CompressedFlags flags = (CompressedFlags) Utils.BytesToUInt(block, i); + CompressedFlags flags = (CompressedFlags)Utils.BytesToUInt(block, i); result.AppendFormat("{0,30}: {1,-10} {2,-29} [{3}]" + Environment.NewLine, "CompressedFlags", Utils.BytesToUInt(block, i), - "(" + (CompressedFlags) Utils.BytesToUInt(block, i) + ")", + "(" + (CompressedFlags)Utils.BytesToUInt(block, i) + ")", "UInt"); i += 4; @@ -364,7 +364,7 @@ namespace OpenMetaverse.Packets { result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "ParentID", - (uint) (block[i++] + (block[i++] << 8) + + (uint)(block[i++] + (block[i++] << 8) + (block[i++] << 16) + (block[i++] << 24)), "UInt"); } @@ -375,7 +375,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, "TreeSpecies", block[i++], - "(" + (Tree) block[i] + ")", + "(" + (Tree)block[i] + ")", "Tree"); } @@ -397,7 +397,7 @@ namespace OpenMetaverse.Packets string text = String.Empty; while (block[i] != 0) { - text += (char) block[i]; + text += (char)block[i]; i++; } @@ -423,7 +423,7 @@ namespace OpenMetaverse.Packets string text = String.Empty; while (block[i] != 0) { - text += (char) block[i]; + text += (char)block[i]; i++; } @@ -470,7 +470,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, "SoundFlags", block[i++], - "(" + (SoundFlags) block[i] + ")", + "(" + (SoundFlags)block[i] + ")", "SoundFlags"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, @@ -486,7 +486,7 @@ namespace OpenMetaverse.Packets string text = string.Empty; while (block[i] != 0) { - text += (char) block[i]; + text += (char)block[i]; i++; } @@ -514,7 +514,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-2} {2,-37} [{3}]" + Environment.NewLine, "PathCurve", block[i], - "(" + (PathCurve) block[i++] + ")", + "(" + (PathCurve)block[i++] + ")", "PathCurve"); ushort pathBegin = Utils.BytesToUInt16(block, i); @@ -543,37 +543,37 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathShearX", - Primitive.UnpackPathShear((sbyte) block[i++]), + Primitive.UnpackPathShear((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathShearY", - Primitive.UnpackPathShear((sbyte) block[i++]), + Primitive.UnpackPathShear((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathTwist", - Primitive.UnpackPathTwist((sbyte) block[i++]), + Primitive.UnpackPathTwist((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathTwistBegin", - Primitive.UnpackPathTwist((sbyte) block[i++]), + Primitive.UnpackPathTwist((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathRadiusOffset", - Primitive.UnpackPathTwist((sbyte) block[i++]), + Primitive.UnpackPathTwist((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathTaperX", - Primitive.UnpackPathTaper((sbyte) block[i++]), + Primitive.UnpackPathTaper((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathTaperY", - Primitive.UnpackPathTaper((sbyte) block[i++]), + Primitive.UnpackPathTaper((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, @@ -583,7 +583,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, "PathSkew", - Primitive.UnpackPathTwist((sbyte) block[i++]), + Primitive.UnpackPathTwist((sbyte)block[i++]), "float"); result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, @@ -612,7 +612,7 @@ namespace OpenMetaverse.Packets Primitive.UnpackProfileHollow(profileHollow), "float"); - int textureEntryLength = (int) Utils.BytesToUInt(block, i); + int textureEntryLength = (int)Utils.BytesToUInt(block, i); i += 4; //prim.Textures = new Primitive.TextureEntry(block, i, textureEntryLength); String s = DecodeTextureEntry("TextureEntry", new Primitive.TextureEntry(block, i, textureEntryLength)); @@ -643,11 +643,11 @@ namespace OpenMetaverse.Packets private static string DecodeObjectData(string fieldName, object fieldData) { - byte[] data = (byte[]) fieldData; + byte[] data = (byte[])fieldData; if (data.Length == 1) { return - $"{fieldName + " (Tree Species)",30}: {fieldData,2} {"(" + (Tree) data[0] + ")",-38} [{fieldData.GetType().Name}]"; + $"{fieldName + " (Tree Species)",30}: {fieldData,2} {"(" + (Tree)data[0] + ")",-38} [{fieldData.GetType().Name}]"; } else if (data.Length == 76) { @@ -734,7 +734,7 @@ namespace OpenMetaverse.Packets } else { - return Utils.BytesToHexString((byte[]) fieldData, $"{fieldName,30}"); + return Utils.BytesToHexString((byte[])fieldData, $"{fieldName,30}"); } } @@ -745,7 +745,7 @@ namespace OpenMetaverse.Packets if (fieldData is Primitive.TextureAnimation data) textureAnim = data; else - textureAnim = new Primitive.TextureAnimation((byte[]) fieldData, 0); + textureAnim = new Primitive.TextureAnimation((byte[])fieldData, 0); result.AppendFormat("{0,30}", " " + Environment.NewLine); GenericTypeDecoder(textureAnim, ref result); @@ -756,26 +756,26 @@ namespace OpenMetaverse.Packets private static string DecodeEstateParameter(string fieldName, object fieldData) { - byte[] bytes = (byte[]) fieldData; + byte[] bytes = (byte[])fieldData; if (bytes.Length == 17) { - return $"{fieldName,30}: {new UUID((byte[]) fieldData, 0),-40} [UUID]"; + return $"{fieldName,30}: {new UUID((byte[])fieldData, 0),-40} [UUID]"; } else { - return $"{fieldName,30}: {Utils.BytesToString((byte[]) fieldData),-40} [Byte[]]"; + return $"{fieldName,30}: {Utils.BytesToString((byte[])fieldData),-40} [Byte[]]"; } } private static string DecodeNameValue(string fieldName, object fieldData) { NameValue[] nameValues = null; - if (fieldData is NameValue[]) - nameValues = fieldData as NameValue[]; + if (fieldData is NameValue[] data) + nameValues = data; else { - string nameValue = Utils.BytesToString((byte[]) fieldData); + string nameValue = Utils.BytesToString((byte[])fieldData); if (nameValue.Length > 0) { string[] lines = nameValue.Split('\n'); @@ -811,7 +811,7 @@ namespace OpenMetaverse.Packets private static string DecodeObjectExtraParams(string fieldName, object fieldData) { - byte[] data = (byte[]) fieldData; + byte[] data = (byte[])fieldData; int i = 0; //int totalLength = 1; @@ -827,7 +827,7 @@ namespace OpenMetaverse.Packets for (int k = 0; k < extraParamCount; k++) { - ExtraParamType type = (ExtraParamType) Utils.BytesToUInt16(data, i); + ExtraParamType type = (ExtraParamType)Utils.BytesToUInt16(data, i); i += 2; uint paramLength = Utils.BytesToUInt(data, i); @@ -841,13 +841,13 @@ namespace OpenMetaverse.Packets sculpt = new Primitive.SculptData(data, i); else if (type == ExtraParamType.Mesh) mesh = new Primitive.SculptData(data, i); - else if ((byte) type == 0x70) + else if ((byte)type == 0x70) { hasMeshFlags = true; meshFlags = Utils.BytesToUInt(data, i); } - i += (int) paramLength; + i += (int)paramLength; //totalLength += (int)paramLength + 6; } @@ -899,7 +899,7 @@ namespace OpenMetaverse.Packets if (fieldData is Primitive.ParticleSystem data) particleSys = data; else - particleSys = new Primitive.ParticleSystem((byte[]) fieldData, 0); + particleSys = new Primitive.ParticleSystem((byte[])fieldData, 0); result.AppendFormat("{0,30}", "" + Environment.NewLine); GenericTypeDecoder(particleSys, ref result); @@ -931,67 +931,67 @@ namespace OpenMetaverse.Packets private static string DecodeObjectPCode(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-3} {"(" + (PCode) (byte) fieldData + ")",-36} [PCode]"; + return $"{fieldName,30}: {fieldData,-3} {"(" + (PCode)(byte)fieldData + ")",-36} [PCode]"; } private static string DecodeImageType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-3} {"(" + (ImageType) (byte) fieldData + ")",-36} [ImageType]"; + return $"{fieldName,30}: {fieldData,-3} {"(" + (ImageType)(byte)fieldData + ")",-36} [ImageType]"; } private static string DecodeImageCodec(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-3} {"(" + (ImageCodec) (byte) fieldData + ")",-36} [ImageCodec]"; + return $"{fieldName,30}: {fieldData,-3} {"(" + (ImageCodec)(byte)fieldData + ")",-36} [ImageCodec]"; } private static string DecodeObjectMaterial(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-3} {"(" + (Material) (byte) fieldData + ")",-36} [Material]"; + return $"{fieldName,30}: {fieldData,-3} {"(" + (Material)(byte)fieldData + ")",-36} [Material]"; } private static string DecodeObjectClickAction(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-3} {"(" + (ClickAction) (byte) fieldData + ")",-36} [ClickAction]"; + return $"{fieldName,30}: {fieldData,-3} {"(" + (ClickAction)(byte)fieldData + ")",-36} [ClickAction]"; } private static string DecodeEventFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-3} {"(" + (DirectoryManager.EventFlags) (uint) fieldData + ")",-36} [EventFlags]"; + $"{fieldName,30}: {fieldData,-3} {"(" + (DirectoryManager.EventFlags)(uint)fieldData + ")",-36} [EventFlags]"; } private static string DecodeDirQueryFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.DirFindFlags) (uint) fieldData + ")",-29} [DirectoryManager.DirFindFlags]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.DirFindFlags)(uint)fieldData + ")",-29} [DirectoryManager.DirFindFlags]"; } private static string DecodeDirClassifiedQueryFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.ClassifiedQueryFlags) (uint) fieldData + ")",-29} [ClassifiedQueryFlags]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.ClassifiedQueryFlags)(uint)fieldData + ")",-29} [ClassifiedQueryFlags]"; } private static string DecodeDirClassifiedFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.ClassifiedFlags) (byte) fieldData + ")",-29} [ClassifiedFlags]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.ClassifiedFlags)(byte)fieldData + ")",-29} [ClassifiedFlags]"; } private static string DecodeGroupPowers(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-20} {"(" + (GroupPowers) (ulong) fieldData + ")",-19} [GroupPowers]"; + return $"{fieldName,30}: {fieldData,-20} {"(" + (GroupPowers)(ulong)fieldData + ")",-19} [GroupPowers]"; } private static string DecodeParcelAcl(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-10} {"(" + (AccessList) (uint) fieldData + ")",-29} [AccessList]"; + return $"{fieldName,30}: {fieldData,-10} {"(" + (AccessList)(uint)fieldData + ")",-29} [AccessList]"; } private static string SearchTypeFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.SearchTypeFlags) (uint) fieldData + ")",-29} [DirectoryManager.SearchTypeFlags]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (DirectoryManager.SearchTypeFlags)(uint)fieldData + ")",-29} [DirectoryManager.SearchTypeFlags]"; } private static string DecodeCategory(string fieldName, object fieldData) @@ -1001,42 +1001,42 @@ namespace OpenMetaverse.Packets private static string DecodeObjectUpdateFlags(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-10} {"(" + (PrimFlags) (uint) fieldData + ")",-29} [PrimFlags]"; + return $"{fieldName,30}: {fieldData,-10} {"(" + (PrimFlags)(uint)fieldData + ")",-29} [PrimFlags]"; } private static string DecodeTeleportFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (TeleportFlags) (uint) fieldData + ")",-29} [TeleportFlags]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (TeleportFlags)(uint)fieldData + ")",-29} [TeleportFlags]"; } private static string DecodeScriptControls(string fieldName, object fieldData) { return - $"{fieldName,30}: {(uint) fieldData,-10} {"(" + (AgentManager.ControlFlags) (uint) fieldData + ")",-29} [AgentManager.ControlFlags]"; + $"{fieldName,30}: {(uint)fieldData,-10} {"(" + (AgentManager.ControlFlags)(uint)fieldData + ")",-29} [AgentManager.ControlFlags]"; } private static string DecodeColorField(string fieldName, object fieldData) { return - $"{fieldName,30}: {(fieldData.GetType().Name.Equals("Color4") ? (Color4) fieldData : new Color4((byte[]) fieldData, 0, false)),-40} [Color4]"; + $"{fieldName,30}: {(fieldData.GetType().Name.Equals("Color4") ? (Color4)fieldData : new Color4((byte[])fieldData, 0, false)),-40} [Color4]"; } private static string DecodeTimeStamp(string fieldName, object fieldData) { - if (fieldData is Int32 && (int) fieldData > 0) + if (fieldData is int data && data > 0) return - $"{fieldName,30}: {fieldData,-10} {"(" + Utils.UnixTimeToDateTime((int) fieldData) + ")",-29} [{fieldData.GetType().Name}]"; - else if (fieldData is uint && (uint) fieldData > 0) + $"{fieldName,30}: {data,-10} {"(" + Utils.UnixTimeToDateTime(data) + ")",-29} [{data.GetType().Name}]"; + else if (fieldData is uint u && u > 0) return - $"{fieldName,30}: {fieldData,-10} {"(" + Utils.UnixTimeToDateTime((uint) fieldData) + ")",-29} [{fieldData.GetType().Name}]"; + $"{fieldName,30}: {u,-10} {"(" + Utils.UnixTimeToDateTime(u) + ")",-29} [{u.GetType().Name}]"; else return $"{fieldName,30}: {fieldData,-40} [{fieldData.GetType().Name}]"; } private static string DecodeBinaryBucket(string fieldName, object fieldData) { - byte[] bytes = (byte[]) fieldData; + byte[] bytes = (byte[])fieldData; string bucket; if (bytes.Length == 1) { @@ -1044,7 +1044,7 @@ namespace OpenMetaverse.Packets } else if (bytes.Length == 17) { - bucket = $"{new UUID(bytes, 1),-36} {bytes[0]} ({(AssetType) (sbyte) bytes[0]})"; + bucket = $"{new UUID(bytes, 1),-36} {bytes[0]} ({(AssetType)(sbyte)bytes[0]})"; } else if (bytes.Length == 16 ) // the folder ID for the asset to be stored into if we accept an inventory offer @@ -1061,56 +1061,56 @@ namespace OpenMetaverse.Packets private static string DecodeBinaryToHexString(string fieldName, object fieldData) { - return $"{Utils.BytesToHexString((byte[]) fieldData, $"{fieldName,30}"),30}"; + return $"{Utils.BytesToHexString((byte[])fieldData, $"{fieldName,30}"),30}"; } private static string DecodeWearableType(string fieldName, object fieldData) { - return $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (WearableType) fieldData + ")",-37} [WearableType]"; + return $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (WearableType)fieldData + ")",-37} [WearableType]"; } private static string DecodeInventoryType(string fieldName, object fieldData) { return - $"{fieldName,30}: {(sbyte) fieldData,-2} {"(" + (AssetType) (sbyte) fieldData + ")",-37} [AssetType]"; + $"{fieldName,30}: {(sbyte)fieldData,-2} {"(" + (AssetType)(sbyte)fieldData + ")",-37} [AssetType]"; } private static string DecodeInventorySort(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-2} {"(" + (InventorySortOrder) (int) fieldData + ")",-37} [InventorySortOrder]"; + $"{fieldName,30}: {fieldData,-2} {"(" + (InventorySortOrder)(int)fieldData + ")",-37} [InventorySortOrder]"; } private static string DecodeInventoryInvType(string fieldName, object fieldData) { return - $"{fieldName,30}: {(sbyte) fieldData,-2} {"(" + (InventoryType) fieldData + ")",-37} [InventoryType]"; + $"{fieldName,30}: {(sbyte)fieldData,-2} {"(" + (InventoryType)fieldData + ")",-37} [InventoryType]"; } private static string DecodeFolderType(string fieldName, object fieldData) { - return $"{fieldName,30}: {(sbyte) fieldData,-2} {"(" + (FolderType) fieldData + ")",-37} [Folderype]"; + return $"{fieldName,30}: {(sbyte)fieldData,-2} {"(" + (FolderType)fieldData + ")",-37} [Folderype]"; } private static string DecodeInventoryFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {(uint) fieldData,-2} {"(" + (InventoryItemFlags) (uint) fieldData + ")",-37} [InventoryItemFlags]"; + $"{fieldName,30}: {(uint)fieldData,-2} {"(" + (InventoryItemFlags)(uint)fieldData + ")",-37} [InventoryItemFlags]"; } private static string DecodeObjectSaleType(string fieldName, object fieldData) { - return $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (SaleType) fieldData + ")",-37} [SaleType]"; + return $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (SaleType)fieldData + ")",-37} [SaleType]"; } private static string DecodeRegionFlags(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (RegionFlags) (uint) fieldData + ")",-37} [RegionFlags]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (RegionFlags)(uint)fieldData + ")",-37} [RegionFlags]"; } private static string DecodeTransferParams(string fieldName, object fieldData) { - byte[] paramData = (byte[]) fieldData; + byte[] paramData = (byte[])fieldData; StringBuilder result = new StringBuilder(); result.AppendLine(" "); if (paramData.Length == 20) @@ -1121,8 +1121,8 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, "AssetType", - (sbyte) paramData[16], - "(" + (AssetType) (sbyte) paramData[16] + ")"); + (sbyte)paramData[16], + "(" + (AssetType)(sbyte)paramData[16] + ")"); } else if (paramData.Length == 100) { @@ -1154,8 +1154,8 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0,30}: {1,-2} {2,-37} [AssetType]" + Environment.NewLine, "AssetType", - (sbyte) paramData[96], - "(" + (AssetType) (sbyte) paramData[96] + ")"); + (sbyte)paramData[96], + "(" + (AssetType)(sbyte)paramData[96] + ")"); } else { @@ -1169,75 +1169,75 @@ namespace OpenMetaverse.Packets private static string DecodeTransferChannelType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (ChannelType) (int) fieldData + ")",-37} [ChannelType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (ChannelType)(int)fieldData + ")",-37} [ChannelType]"; } private static string DecodeTransferSourceType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (SourceType) (int) fieldData + ")",-37} [SourceType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (SourceType)(int)fieldData + ")",-37} [SourceType]"; } private static string DecodeTransferTargetType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (TargetType) (int) fieldData + ")",-37} [TargetType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (TargetType)(int)fieldData + ")",-37} [TargetType]"; } private static string DecodeMapRequestFlags(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (GridLayerType) (uint) fieldData + ")",-37} [GridLayerType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (GridLayerType)(uint)fieldData + ")",-37} [GridLayerType]"; } private static string DecodeGridItemType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (GridItemType) (uint) fieldData + ")",-37} [GridItemType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (GridItemType)(uint)fieldData + ")",-37} [GridItemType]"; } private static string DecodeLayerDataType(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-2} {"(" + (TerrainPatch.LayerType) (byte) fieldData + ")",-37} [LayerType]"; + $"{fieldName,30}: {fieldData,-2} {"(" + (TerrainPatch.LayerType)(byte)fieldData + ")",-37} [LayerType]"; } private static string DecodeMapAccess(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (SimAccess) (byte) fieldData + ")",-37} [SimAccess]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (SimAccess)(byte)fieldData + ")",-37} [SimAccess]"; } private static string DecodeSimAccess(string fieldName, object fieldData) { - return $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (SimAccess) fieldData + ")",-37} [SimAccess]"; + return $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (SimAccess)fieldData + ")",-37} [SimAccess]"; } private static string DecodeAttachedSoundFlags(string fieldName, object fieldData) { - return $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (SoundFlags) fieldData + ")",-37} [SoundFlags]"; + return $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (SoundFlags)fieldData + ")",-37} [SoundFlags]"; } private static string DecodeChatSourceType(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (SourceType) (byte) fieldData + ")",-37} [SourceType]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (SourceType)(byte)fieldData + ")",-37} [SourceType]"; } private static string DecodeChatChatType(string fieldName, object fieldData) { - return $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (ChatType) fieldData + ")",-37} [ChatType]"; + return $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (ChatType)fieldData + ")",-37} [ChatType]"; } private static string DecodeChatAudible(string fieldName, object fieldData) { return - $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (ChatAudibleLevel) (byte) fieldData + ")",-37} [ChatAudibleLevel]"; + $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (ChatAudibleLevel)(byte)fieldData + ")",-37} [ChatAudibleLevel]"; } private static string DecodeImageData(string fieldName, object fieldData) { - return $"{Utils.BytesToHexString((byte[]) fieldData, $"{fieldName,30}"),10}"; + return $"{Utils.BytesToHexString((byte[])fieldData, $"{fieldName,30}"),10}"; } private static string DecodeTerseTextureEntry(string fieldName, object fieldData) { - byte[] block = (byte[]) fieldData; + byte[] block = (byte[])fieldData; Primitive.TextureEntry te = new Primitive.TextureEntry(block, 4, block.Length - 4); @@ -1272,11 +1272,11 @@ namespace OpenMetaverse.Packets private static string DecodeTextureEntry(string fieldName, object fieldData) { Primitive.TextureEntry te; - if (fieldData is Primitive.TextureEntry) - te = (Primitive.TextureEntry) fieldData; + if (fieldData is Primitive.TextureEntry data) + te = data; else { - byte[] tebytes = (byte[]) fieldData; + byte[] tebytes = (byte[])fieldData; te = new Primitive.TextureEntry(tebytes, 0, tebytes.Length); } @@ -1355,24 +1355,24 @@ namespace OpenMetaverse.Packets private static string DecodeDialog(string fieldName, object fieldData) { return - $"{fieldName,30}: {(byte) fieldData,-2} {"(" + (InstantMessageDialog) fieldData + ")",-37} [{fieldData.GetType().Name}]"; + $"{fieldName,30}: {(byte)fieldData,-2} {"(" + (InstantMessageDialog)fieldData + ")",-37} [{fieldData.GetType().Name}]"; } private static string DecodeControlFlags(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-10} {"(" + (AgentManager.ControlFlags) (uint) fieldData + ")",-29} [{fieldData.GetType().Name}]"; + $"{fieldName,30}: {fieldData,-10} {"(" + (AgentManager.ControlFlags)(uint)fieldData + ")",-29} [{fieldData.GetType().Name}]"; } private static string DecodePermissionMask(string fieldName, object fieldData) { return - $"{fieldName,30}: {(uint) fieldData,-10} {"(" + (PermissionMask) fieldData + ")",-29} [{fieldData.GetType().Name}]"; + $"{fieldName,30}: {(uint)fieldData,-10} {"(" + (PermissionMask)fieldData + ")",-29} [{fieldData.GetType().Name}]"; } private static string DecodeViewerEffectTypeData(string fieldName, object fieldData) { - byte[] data = (byte[]) fieldData; + byte[] data = (byte[])fieldData; StringBuilder sb = new StringBuilder(); if (data.Length == 56 || data.Length == 57) { @@ -1385,7 +1385,7 @@ namespace OpenMetaverse.Packets "Target ObjectID=" + targetObject); - Helpers.GlobalPosToRegionHandle((float) targetPos.X, (float) targetPos.Y, out _, out _); + Helpers.GlobalPosToRegionHandle((float)targetPos.X, (float)targetPos.Y, out _, out _); sb.AppendFormat("{0,30}: {1,-40} [Vector3d]", fieldName, targetPos); @@ -1393,7 +1393,7 @@ namespace OpenMetaverse.Packets { sb.AppendLine(); sb.AppendFormat("{0,30}: {1,-17} {2,-22} [Byte]", fieldName, "Point At Type=" + data[56], - "(" + (PointAtType) data[56] + ")"); + "(" + (PointAtType)data[56] + ")"); } return sb.ToString(); @@ -1407,32 +1407,32 @@ namespace OpenMetaverse.Packets private static string DecodeAgentState(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (AgentState) (byte) fieldData + ")",-37} [AgentState]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (AgentState)(byte)fieldData + ")",-37} [AgentState]"; } private static string DecodeAgentFlags(string fieldName, object fieldData) { - return $"{fieldName,30}: {fieldData,-2} {"(" + (AgentFlags) (byte) fieldData + ")",-37} [AgentFlags]"; + return $"{fieldName,30}: {fieldData,-2} {"(" + (AgentFlags)(byte)fieldData + ")",-37} [AgentFlags]"; } private static string DecodeObjectState(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-2} {"(" + (AttachmentPoint) (byte) fieldData + ")",-37} [AttachmentPoint]"; + $"{fieldName,30}: {fieldData,-2} {"(" + (AttachmentPoint)(byte)fieldData + ")",-37} [AttachmentPoint]"; } private static string DecodeViewerEffectType(string fieldName, object fieldData) { return - $"{fieldName,30}: {fieldData,-2} {"(" + (EffectType) (byte) fieldData + ")",-37} [{fieldData.GetType().Name}]"; + $"{fieldName,30}: {fieldData,-2} {"(" + (EffectType)(byte)fieldData + ")",-37} [{fieldData.GetType().Name}]"; } private static string DecodeAnimToConst(string fieldName, object fieldData) { string animConst = "UUID"; Dictionary animsDict = Animations.ToDictionary(); - if (animsDict.ContainsKey((UUID) fieldData)) - animConst = animsDict[(UUID) fieldData]; + if (animsDict.ContainsKey((UUID)fieldData)) + animConst = animsDict[(UUID)fieldData]; return $"{fieldName,30}: {fieldData,-40} [{animConst}]"; } @@ -1517,7 +1517,7 @@ namespace OpenMetaverse.Packets { result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, t.Name, - Utils.BytesToString((byte[]) t.GetValue(nestedArrayRecord)), + Utils.BytesToString((byte[])t.GetValue(nestedArrayRecord)), /*fields[i].GetValue(nestedArrayRecord).GetType().Name*/ "String"); } else // default for a field @@ -1547,7 +1547,7 @@ namespace OpenMetaverse.Packets /* Leave the c for now at the end, it signifies something useful that still needs to be done i.e. a decoder written */ result.AppendFormat("{0, 30}: {1,-40} [{2}]c" + Environment.NewLine, propertyInfo.Name, - Utils.BytesToString((byte[]) propertyInfo.GetValue(nestedArrayRecord, null)), + Utils.BytesToString((byte[])propertyInfo.GetValue(nestedArrayRecord, null)), propertyInfo.PropertyType.Name); } } @@ -1574,7 +1574,7 @@ namespace OpenMetaverse.Packets { result.AppendFormat("{0,30}: {1,-40} [{2}]" + Environment.NewLine, packetValueField.Name, - Utils.BytesToString((byte[]) packetValueField.GetValue(packetDataObject)), + Utils.BytesToString((byte[])packetValueField.GetValue(packetDataObject)), /*packetValueField.FieldType.Name*/ "String"); } else @@ -1602,7 +1602,7 @@ namespace OpenMetaverse.Packets { result.AppendFormat("{0, 30}: {1,-40} [{2}]" + Environment.NewLine, propertyInfo.Name, - Utils.BytesToString((byte[]) propertyInfo.GetValue(packetDataObject, null)), + Utils.BytesToString((byte[])propertyInfo.GetValue(packetDataObject, null)), propertyInfo.PropertyType.Name); } else @@ -1618,13 +1618,12 @@ namespace OpenMetaverse.Packets private static bool SpecialDecoder(string decoderKey, object fieldData, out string result) { result = string.Empty; - string[] keys = decoderKey.Split(new[] {'.'}, StringSplitOptions.RemoveEmptyEntries); - string[] keyList = {decoderKey, decoderKey.Replace("Packet", ""), keys[1] + "." + keys[2], keys[2]}; + string[] keys = decoderKey.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); + string[] keyList = { decoderKey, decoderKey.Replace("Packet", ""), keys[1] + "." + keys[2], keys[2] }; foreach (string key in keyList) { - if (fieldData is byte[]) + if (fieldData is byte[] fd) { - byte[] fd = (byte[]) fieldData; if (!(fd.Length > 0)) { // bypass the decoder since we were passed an empty byte array @@ -1683,7 +1682,7 @@ namespace OpenMetaverse.Packets result.AppendFormat("{0, 30}:" + Environment.NewLine, messageField.Name); result.AppendFormat("{0}" + Environment.NewLine, - Utils.BytesToHexString((byte[]) messageField.GetValue(message), + Utils.BytesToHexString((byte[])messageField.GetValue(message), $"{"",30}")); } @@ -1691,7 +1690,7 @@ namespace OpenMetaverse.Packets else if (messageField.FieldType.IsArray) { var messageObjectData = messageField.GetValue(message) as Array; - + if (messageObjectData == null) continue; result.AppendFormat("-- {0} --" + Environment.NewLine, messageField.FieldType.Name); diff --git a/libremetaverse-core/Libremetaverse/Permissions.cs b/libremetaverse-core/Libremetaverse/Permissions.cs index b54f8da..bd21da1 100644 --- a/libremetaverse-core/Libremetaverse/Permissions.cs +++ b/libremetaverse-core/Libremetaverse/Permissions.cs @@ -145,7 +145,7 @@ namespace OpenMetaverse public override bool Equals(object obj) { - return (obj is Permissions) && this == (Permissions)obj; + return (obj is Permissions permissions) && this == permissions; } public bool Equals(Permissions other) diff --git a/libremetaverse-core/Libremetaverse/Rendering/LindenMesh.cs b/libremetaverse-core/Libremetaverse/Rendering/LindenMesh.cs index c199ae1..82abaac 100644 --- a/libremetaverse-core/Libremetaverse/Rendering/LindenMesh.cs +++ b/libremetaverse-core/Libremetaverse/Rendering/LindenMesh.cs @@ -548,12 +548,12 @@ namespace OpenMetaverse.Rendering /// A standard .Net string public static string TrimAt0(string s) { - int pos = s.IndexOf("\0"); + int pos = s.IndexOf("\0", StringComparison.Ordinal); if (pos >= 0) return s.Substring(0, pos); - return s; + return pos >= 0 ? s.Substring(0, pos) : s; } } }