Changeset 351
- Timestamp:
- Jan 19, 2019, 6:12:21 PM (6 years ago)
- Location:
- binary-improvements
- Files:
-
- 48 edited
Legend:
- Unmodified
- Added
- Removed
-
binary-improvements/7dtd-server-fixes/src/BlockingQueue.cs
r325 r351 7 7 private bool closing; 8 8 9 public void Enqueue (T item) {9 public void Enqueue (T _item) { 10 10 lock (queue) { 11 queue.Enqueue ( item);11 queue.Enqueue (_item); 12 12 Monitor.PulseAll (queue); 13 13 } -
binary-improvements/7dtd-server-fixes/src/FileCache/AbstractCache.cs
r325 r351 1 1 namespace AllocsFixes.FileCache { 2 2 public abstract class AbstractCache { 3 public abstract byte[] GetFileContent (string filename);3 public abstract byte[] GetFileContent (string _filename); 4 4 } 5 5 } -
binary-improvements/7dtd-server-fixes/src/FileCache/DirectAccess.cs
r325 r351 5 5 // Not caching at all, simply reading from disk on each request 6 6 public class DirectAccess : AbstractCache { 7 public override byte[] GetFileContent (string filename) {7 public override byte[] GetFileContent (string _filename) { 8 8 try { 9 if (!File.Exists ( filename)) {9 if (!File.Exists (_filename)) { 10 10 return null; 11 11 } 12 12 13 return File.ReadAllBytes ( filename);13 return File.ReadAllBytes (_filename); 14 14 } catch (Exception e) { 15 15 Log.Out ("Error in DirectAccess.GetFileContent: " + e); -
binary-improvements/7dtd-server-fixes/src/FileCache/MapTileCache.cs
r346 r351 25 25 } 26 26 27 public void SetZoomCount (int count) {28 cache = new CurrentZoomFile[ count];27 public void SetZoomCount (int _count) { 28 cache = new CurrentZoomFile[_count]; 29 29 for (int i = 0; i < cache.Length; i++) { 30 30 cache [i] = new CurrentZoomFile (); … … 32 32 } 33 33 34 public byte[] LoadTile (int zoomlevel, stringfilename) {34 public byte[] LoadTile (int _zoomlevel, string _filename) { 35 35 try { 36 36 lock (cache) { 37 CurrentZoomFile cacheEntry = cache [ zoomlevel];37 CurrentZoomFile cacheEntry = cache [_zoomlevel]; 38 38 39 if (cacheEntry.filename == null || !cacheEntry.filename.Equals ( filename)) {40 cacheEntry.filename = filename;39 if (cacheEntry.filename == null || !cacheEntry.filename.Equals (_filename)) { 40 cacheEntry.filename = _filename; 41 41 42 if (!File.Exists ( filename)) {42 if (!File.Exists (_filename)) { 43 43 cacheEntry.pngData = null; 44 44 return null; … … 46 46 47 47 Profiler.BeginSample ("ReadPng"); 48 cacheEntry.pngData = ReadAllBytes ( filename);48 cacheEntry.pngData = ReadAllBytes (_filename); 49 49 Profiler.EndSample (); 50 50 } … … 59 59 } 60 60 61 public void SaveTile (int zoomlevel, byte[]contentPng) {61 public void SaveTile (int _zoomlevel, byte[] _contentPng) { 62 62 try { 63 63 lock (cache) { 64 CurrentZoomFile cacheEntry = cache [ zoomlevel];64 CurrentZoomFile cacheEntry = cache [_zoomlevel]; 65 65 66 66 string file = cacheEntry.filename; … … 69 69 } 70 70 71 cacheEntry.pngData = contentPng;71 cacheEntry.pngData = _contentPng; 72 72 73 73 Profiler.BeginSample ("WritePng"); 74 74 using (Stream stream = new FileStream (file, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 75 75 4096)) { 76 stream.Write ( contentPng, 0,contentPng.Length);76 stream.Write (_contentPng, 0, _contentPng.Length); 77 77 } 78 78 Profiler.EndSample (); … … 83 83 } 84 84 85 public void ResetTile (int zoomlevel) {85 public void ResetTile (int _zoomlevel) { 86 86 try { 87 87 lock (cache) { 88 cache [ zoomlevel].filename = null;89 cache [ zoomlevel].pngData = null;88 cache [_zoomlevel].filename = null; 89 cache [_zoomlevel].pngData = null; 90 90 } 91 91 } catch (Exception e) { … … 94 94 } 95 95 96 public override byte[] GetFileContent (string filename) {96 public override byte[] GetFileContent (string _filename) { 97 97 try { 98 98 lock (cache) { 99 99 foreach (CurrentZoomFile czf in cache) { 100 if (czf.filename != null && czf.filename.Equals ( filename)) {100 if (czf.filename != null && czf.filename.Equals (_filename)) { 101 101 return czf.pngData; 102 102 } 103 103 } 104 104 105 if (!File.Exists ( filename)) {105 if (!File.Exists (_filename)) { 106 106 return transparentTile; 107 107 } 108 108 109 return ReadAllBytes ( filename);109 return ReadAllBytes (_filename); 110 110 } 111 111 } catch (Exception e) { -
binary-improvements/7dtd-server-fixes/src/FileCache/SimpleCache.cs
r325 r351 8 8 private readonly Dictionary<string, byte[]> fileCache = new Dictionary<string, byte[]> (); 9 9 10 public override byte[] GetFileContent (string filename) {10 public override byte[] GetFileContent (string _filename) { 11 11 try { 12 12 lock (fileCache) { 13 if (!fileCache.ContainsKey ( filename)) {14 if (!File.Exists ( filename)) {13 if (!fileCache.ContainsKey (_filename)) { 14 if (!File.Exists (_filename)) { 15 15 return null; 16 16 } 17 17 18 fileCache.Add ( filename, File.ReadAllBytes (filename));18 fileCache.Add (_filename, File.ReadAllBytes (_filename)); 19 19 } 20 20 21 return fileCache [ filename];21 return fileCache [_filename]; 22 22 } 23 23 } catch (Exception e) { -
binary-improvements/7dtd-server-fixes/src/JSON/JSONArray.cs
r325 r351 6 6 private readonly List<JSONNode> nodes = new List<JSONNode> (); 7 7 8 public JSONNode this [int index] {9 get { return nodes [ index]; }10 set { nodes [ index] = value; }8 public JSONNode this [int _index] { 9 get { return nodes [_index]; } 10 set { nodes [_index] = value; } 11 11 } 12 12 … … 15 15 } 16 16 17 public void Add (JSONNode node) {18 nodes.Add ( node);17 public void Add (JSONNode _node) { 18 nodes.Add (_node); 19 19 } 20 20 21 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {22 stringBuilder.Append ("[");23 if ( prettyPrint) {24 stringBuilder.Append ('\n');21 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 22 _stringBuilder.Append ("["); 23 if (_prettyPrint) { 24 _stringBuilder.Append ('\n'); 25 25 } 26 26 27 27 foreach (JSONNode n in nodes) { 28 if ( prettyPrint) {29 stringBuilder.Append (new string ('\t',currentLevel + 1));28 if (_prettyPrint) { 29 _stringBuilder.Append (new string ('\t', _currentLevel + 1)); 30 30 } 31 31 32 n.ToString ( stringBuilder, prettyPrint,currentLevel + 1);33 stringBuilder.Append (",");34 if ( prettyPrint) {35 stringBuilder.Append ('\n');32 n.ToString (_stringBuilder, _prettyPrint, _currentLevel + 1); 33 _stringBuilder.Append (","); 34 if (_prettyPrint) { 35 _stringBuilder.Append ('\n'); 36 36 } 37 37 } 38 38 39 39 if (nodes.Count > 0) { 40 stringBuilder.Remove (stringBuilder.Length - (prettyPrint ? 2 : 1), 1);40 _stringBuilder.Remove (_stringBuilder.Length - (_prettyPrint ? 2 : 1), 1); 41 41 } 42 42 43 if ( prettyPrint) {44 stringBuilder.Append (new string ('\t',currentLevel));43 if (_prettyPrint) { 44 _stringBuilder.Append (new string ('\t', _currentLevel)); 45 45 } 46 46 47 stringBuilder.Append ("]");47 _stringBuilder.Append ("]"); 48 48 } 49 49 50 public static JSONArray Parse (string json, ref intoffset) {50 public static JSONArray Parse (string _json, ref int _offset) { 51 51 //Log.Out ("ParseArray enter (" + offset + ")"); 52 52 JSONArray arr = new JSONArray (); 53 53 54 54 bool nextElemAllowed = true; 55 offset++;55 _offset++; 56 56 while (true) { 57 Parser.SkipWhitespace ( json, refoffset);57 Parser.SkipWhitespace (_json, ref _offset); 58 58 59 switch ( json [offset]) {59 switch (_json [_offset]) { 60 60 case ',': 61 61 if (!nextElemAllowed) { 62 62 nextElemAllowed = true; 63 offset++;63 _offset++; 64 64 } else { 65 65 throw new MalformedJSONException ( … … 69 69 break; 70 70 case ']': 71 offset++;71 _offset++; 72 72 73 73 //Log.Out ("JSON:Parsed Array: " + arr.ToString ()); 74 74 return arr; 75 75 default: 76 arr.Add (Parser.ParseInternal ( json, refoffset));76 arr.Add (Parser.ParseInternal (_json, ref _offset)); 77 77 nextElemAllowed = false; 78 78 break; -
binary-improvements/7dtd-server-fixes/src/JSON/JSONBoolean.cs
r325 r351 5 5 private readonly bool value; 6 6 7 public JSONBoolean (bool value) {8 this.value =value;7 public JSONBoolean (bool _value) { 8 value = _value; 9 9 } 10 10 … … 13 13 } 14 14 15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {16 stringBuilder.Append (value ? "true" : "false");15 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 16 _stringBuilder.Append (value ? "true" : "false"); 17 17 } 18 18 19 public static JSONBoolean Parse (string json, ref intoffset) {19 public static JSONBoolean Parse (string _json, ref int _offset) { 20 20 //Log.Out ("ParseBool enter (" + offset + ")"); 21 21 22 if ( json.Substring (offset, 4).Equals ("true")) {22 if (_json.Substring (_offset, 4).Equals ("true")) { 23 23 //Log.Out ("JSON:Parsed Bool: true"); 24 offset += 4;24 _offset += 4; 25 25 return new JSONBoolean (true); 26 26 } 27 27 28 if ( json.Substring (offset, 5).Equals ("false")) {28 if (_json.Substring (_offset, 5).Equals ("false")) { 29 29 //Log.Out ("JSON:Parsed Bool: false"); 30 offset += 5;30 _offset += 5; 31 31 return new JSONBoolean (false); 32 32 } -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNode.cs
r325 r351 3 3 namespace AllocsFixes.JSON { 4 4 public abstract class JSONNode { 5 public abstract void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0);5 public abstract void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0); 6 6 7 7 public override string ToString () { -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNull.cs
r326 r351 3 3 namespace AllocsFixes.JSON { 4 4 public class JSONNull : JSONValue { 5 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {6 stringBuilder.Append ("null");5 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 6 _stringBuilder.Append ("null"); 7 7 } 8 8 9 public static JSONNull Parse (string json, ref intoffset) {9 public static JSONNull Parse (string _json, ref int _offset) { 10 10 //Log.Out ("ParseNull enter (" + offset + ")"); 11 11 12 if (! json.Substring (offset, 4).Equals ("null")) {12 if (!_json.Substring (_offset, 4).Equals ("null")) { 13 13 throw new MalformedJSONException ("No valid null value found"); 14 14 } 15 15 16 16 //Log.Out ("JSON:Parsed Null"); 17 offset += 4;17 _offset += 4; 18 18 return new JSONNull (); 19 19 } -
binary-improvements/7dtd-server-fixes/src/JSON/JSONNumber.cs
r325 r351 6 6 private readonly double value; 7 7 8 public JSONNumber (double value) {9 this.value =value;8 public JSONNumber (double _value) { 9 value = _value; 10 10 } 11 11 … … 18 18 } 19 19 20 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {21 stringBuilder.Append (value.ToCultureInvariantString ());20 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 21 _stringBuilder.Append (value.ToCultureInvariantString ()); 22 22 } 23 23 24 public static JSONNumber Parse (string json, ref intoffset) {24 public static JSONNumber Parse (string _json, ref int _offset) { 25 25 //Log.Out ("ParseNumber enter (" + offset + ")"); 26 26 StringBuilder sbNum = new StringBuilder (); … … 28 28 bool hasDec = false; 29 29 bool hasExp = false; 30 while ( offset <json.Length) {31 if ( json [offset] >= '0' && json [offset] <= '9') {30 while (_offset < _json.Length) { 31 if (_json [_offset] >= '0' && _json [_offset] <= '9') { 32 32 if (hasExp) { 33 sbExp.Append ( json [offset]);33 sbExp.Append (_json [_offset]); 34 34 } else { 35 sbNum.Append ( json [offset]);35 sbNum.Append (_json [_offset]); 36 36 } 37 } else if ( json [offset] == '.') {37 } else if (_json [_offset] == '.') { 38 38 if (hasExp) { 39 39 throw new MalformedJSONException ("Decimal separator in exponent"); … … 50 50 sbNum.Append ('.'); 51 51 hasDec = true; 52 } else if ( json [offset] == '-') {52 } else if (_json [_offset] == '-') { 53 53 if (hasExp) { 54 54 if (sbExp.Length > 0) { … … 56 56 } 57 57 58 sbExp.Append ( json [offset]);58 sbExp.Append (_json [_offset]); 59 59 } else { 60 60 if (sbNum.Length > 0) { … … 62 62 } 63 63 64 sbNum.Append ( json [offset]);64 sbNum.Append (_json [_offset]); 65 65 } 66 } else if ( json [offset] == 'e' || json [offset] == 'E') {66 } else if (_json [_offset] == 'e' || _json [_offset] == 'E') { 67 67 if (hasExp) { 68 68 throw new MalformedJSONException ("Multiple exponential markers in number found"); … … 75 75 sbExp = new StringBuilder (); 76 76 hasExp = true; 77 } else if ( json [offset] == '+') {77 } else if (_json [_offset] == '+') { 78 78 if (hasExp) { 79 79 if (sbExp.Length > 0) { … … 81 81 } 82 82 83 sbExp.Append ( json [offset]);83 sbExp.Append (_json [_offset]); 84 84 } else { 85 85 throw new MalformedJSONException ("Positive sign in mantissa found"); … … 104 104 } 105 105 106 offset++;106 _offset++; 107 107 } 108 108 -
binary-improvements/7dtd-server-fixes/src/JSON/JSONObject.cs
r326 r351 6 6 private readonly Dictionary<string, JSONNode> nodes = new Dictionary<string, JSONNode> (); 7 7 8 public JSONNode this [string name] {9 get { return nodes [ name]; }10 set { nodes [ name] = value; }8 public JSONNode this [string _name] { 9 get { return nodes [_name]; } 10 set { nodes [_name] = value; } 11 11 } 12 12 … … 19 19 } 20 20 21 public bool ContainsKey (string name) {22 return nodes.ContainsKey ( name);21 public bool ContainsKey (string _name) { 22 return nodes.ContainsKey (_name); 23 23 } 24 24 25 public void Add (string name, JSONNodenode) {26 nodes.Add ( name,node);25 public void Add (string _name, JSONNode _node) { 26 nodes.Add (_name, _node); 27 27 } 28 28 29 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {30 stringBuilder.Append ("{");31 if ( prettyPrint) {32 stringBuilder.Append ('\n');29 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 30 _stringBuilder.Append ("{"); 31 if (_prettyPrint) { 32 _stringBuilder.Append ('\n'); 33 33 } 34 34 35 35 foreach (KeyValuePair<string, JSONNode> kvp in nodes) { 36 if ( prettyPrint) {37 stringBuilder.Append (new string ('\t',currentLevel + 1));36 if (_prettyPrint) { 37 _stringBuilder.Append (new string ('\t', _currentLevel + 1)); 38 38 } 39 39 40 stringBuilder.Append (string.Format ("\"{0}\":", kvp.Key));41 if ( prettyPrint) {42 stringBuilder.Append (" ");40 _stringBuilder.Append (string.Format ("\"{0}\":", kvp.Key)); 41 if (_prettyPrint) { 42 _stringBuilder.Append (" "); 43 43 } 44 44 45 kvp.Value.ToString ( stringBuilder, prettyPrint,currentLevel + 1);46 stringBuilder.Append (",");47 if ( prettyPrint) {48 stringBuilder.Append ('\n');45 kvp.Value.ToString (_stringBuilder, _prettyPrint, _currentLevel + 1); 46 _stringBuilder.Append (","); 47 if (_prettyPrint) { 48 _stringBuilder.Append ('\n'); 49 49 } 50 50 } 51 51 52 52 if (nodes.Count > 0) { 53 stringBuilder.Remove (stringBuilder.Length - (prettyPrint ? 2 : 1), 1);53 _stringBuilder.Remove (_stringBuilder.Length - (_prettyPrint ? 2 : 1), 1); 54 54 } 55 55 56 if ( prettyPrint) {57 stringBuilder.Append (new string ('\t',currentLevel));56 if (_prettyPrint) { 57 _stringBuilder.Append (new string ('\t', _currentLevel)); 58 58 } 59 59 60 stringBuilder.Append ("}");60 _stringBuilder.Append ("}"); 61 61 } 62 62 63 public static JSONObject Parse (string json, ref intoffset) {63 public static JSONObject Parse (string _json, ref int _offset) { 64 64 //Log.Out ("ParseObject enter (" + offset + ")"); 65 65 JSONObject obj = new JSONObject (); 66 66 67 67 bool nextElemAllowed = true; 68 offset++;68 _offset++; 69 69 while (true) { 70 Parser.SkipWhitespace ( json, refoffset);71 switch ( json [offset]) {70 Parser.SkipWhitespace (_json, ref _offset); 71 switch (_json [_offset]) { 72 72 case '"': 73 73 if (nextElemAllowed) { 74 JSONString key = JSONString.Parse ( json, refoffset);75 Parser.SkipWhitespace ( json, refoffset);76 if ( json [offset] != ':') {74 JSONString key = JSONString.Parse (_json, ref _offset); 75 Parser.SkipWhitespace (_json, ref _offset); 76 if (_json [_offset] != ':') { 77 77 throw new MalformedJSONException ( 78 78 "Could not parse object, missing colon (\":\") after key"); 79 79 } 80 80 81 offset++;82 JSONNode val = Parser.ParseInternal ( json, refoffset);81 _offset++; 82 JSONNode val = Parser.ParseInternal (_json, ref _offset); 83 83 obj.Add (key.GetString (), val); 84 84 nextElemAllowed = false; … … 92 92 if (!nextElemAllowed) { 93 93 nextElemAllowed = true; 94 offset++;94 _offset++; 95 95 } else { 96 96 throw new MalformedJSONException ( … … 100 100 break; 101 101 case '}': 102 offset++;102 _offset++; 103 103 104 104 //Log.Out ("JSON:Parsed Object: " + obj.ToString ()); -
binary-improvements/7dtd-server-fixes/src/JSON/JSONString.cs
r325 r351 5 5 private readonly string value; 6 6 7 public JSONString (string value) {8 this.value =value;7 public JSONString (string _value) { 8 value = _value; 9 9 } 10 10 … … 13 13 } 14 14 15 public override void ToString (StringBuilder stringBuilder, bool prettyPrint = false, intcurrentLevel = 0) {15 public override void ToString (StringBuilder _stringBuilder, bool _prettyPrint = false, int _currentLevel = 0) { 16 16 if (value == null || value.Length == 0) { 17 stringBuilder.Append ("\"\"");17 _stringBuilder.Append ("\"\""); 18 18 return; 19 19 } … … 21 21 int len = value.Length; 22 22 23 stringBuilder.EnsureCapacity (stringBuilder.Length + 2 * len);23 _stringBuilder.EnsureCapacity (_stringBuilder.Length + 2 * len); 24 24 25 stringBuilder.Append ('"');25 _stringBuilder.Append ('"'); 26 26 27 27 foreach (char c in value) { … … 31 31 32 32 // case '/': 33 stringBuilder.Append ('\\');34 stringBuilder.Append (c);33 _stringBuilder.Append ('\\'); 34 _stringBuilder.Append (c); 35 35 break; 36 36 case '\b': 37 stringBuilder.Append ("\\b");37 _stringBuilder.Append ("\\b"); 38 38 break; 39 39 case '\t': 40 stringBuilder.Append ("\\t");40 _stringBuilder.Append ("\\t"); 41 41 break; 42 42 case '\n': 43 stringBuilder.Append ("\\n");43 _stringBuilder.Append ("\\n"); 44 44 break; 45 45 case '\f': 46 stringBuilder.Append ("\\f");46 _stringBuilder.Append ("\\f"); 47 47 break; 48 48 case '\r': 49 stringBuilder.Append ("\\r");49 _stringBuilder.Append ("\\r"); 50 50 break; 51 51 default: 52 52 if (c < ' ') { 53 stringBuilder.Append ("\\u");54 stringBuilder.Append (((int) c).ToString ("X4"));53 _stringBuilder.Append ("\\u"); 54 _stringBuilder.Append (((int) c).ToString ("X4")); 55 55 } else { 56 stringBuilder.Append (c);56 _stringBuilder.Append (c); 57 57 } 58 58 … … 61 61 } 62 62 63 stringBuilder.Append ('"');63 _stringBuilder.Append ('"'); 64 64 } 65 65 66 public static JSONString Parse (string json, ref intoffset) {66 public static JSONString Parse (string _json, ref int _offset) { 67 67 //Log.Out ("ParseString enter (" + offset + ")"); 68 68 StringBuilder sb = new StringBuilder (); 69 offset++;70 while ( offset <json.Length) {71 switch ( json [offset]) {69 _offset++; 70 while (_offset < _json.Length) { 71 switch (_json [_offset]) { 72 72 case '\\': 73 offset++;74 switch ( json [offset]) {73 _offset++; 74 switch (_json [_offset]) { 75 75 case '\\': 76 76 case '"': 77 77 case '/': 78 sb.Append ( json [offset]);78 sb.Append (_json [_offset]); 79 79 break; 80 80 case 'b': … … 94 94 break; 95 95 default: 96 sb.Append ( json [offset]);96 sb.Append (_json [_offset]); 97 97 break; 98 98 } 99 99 100 offset++;100 _offset++; 101 101 break; 102 102 case '"': 103 offset++;103 _offset++; 104 104 105 105 //Log.Out ("JSON:Parsed String: " + sb.ToString ()); 106 106 return new JSONString (sb.ToString ()); 107 107 default: 108 sb.Append ( json [offset]);109 offset++;108 sb.Append (_json [_offset]); 109 _offset++; 110 110 break; 111 111 } -
binary-improvements/7dtd-server-fixes/src/JSON/MalformedJSONException.cs
r325 r351 7 7 } 8 8 9 public MalformedJSONException (string message) : base (message) {9 public MalformedJSONException (string _message) : base (_message) { 10 10 } 11 11 12 public MalformedJSONException (string message, Exception inner) : base (message,inner) {12 public MalformedJSONException (string _message, Exception _inner) : base (_message, _inner) { 13 13 } 14 14 15 protected MalformedJSONException (SerializationInfo info, StreamingContext context) : base (info,context) {15 protected MalformedJSONException (SerializationInfo _info, StreamingContext _context) : base (_info, _context) { 16 16 } 17 17 } -
binary-improvements/7dtd-server-fixes/src/JSON/Parser.cs
r325 r351 1 1 namespace AllocsFixes.JSON { 2 2 public class Parser { 3 public static JSONNode Parse (string json) {3 public static JSONNode Parse (string _json) { 4 4 int offset = 0; 5 return ParseInternal ( json, ref offset);5 return ParseInternal (_json, ref offset); 6 6 } 7 7 8 public static JSONNode ParseInternal (string json, ref intoffset) {9 SkipWhitespace ( json, refoffset);8 public static JSONNode ParseInternal (string _json, ref int _offset) { 9 SkipWhitespace (_json, ref _offset); 10 10 11 11 //Log.Out ("ParseInternal (" + offset + "): Decide on: '" + json [offset] + "'"); 12 switch ( json [offset]) {12 switch (_json [_offset]) { 13 13 case '[': 14 return JSONArray.Parse ( json, refoffset);14 return JSONArray.Parse (_json, ref _offset); 15 15 case '{': 16 return JSONObject.Parse ( json, refoffset);16 return JSONObject.Parse (_json, ref _offset); 17 17 case '"': 18 return JSONString.Parse ( json, refoffset);18 return JSONString.Parse (_json, ref _offset); 19 19 case 't': 20 20 case 'f': 21 return JSONBoolean.Parse ( json, refoffset);21 return JSONBoolean.Parse (_json, ref _offset); 22 22 case 'n': 23 return JSONNull.Parse ( json, refoffset);23 return JSONNull.Parse (_json, ref _offset); 24 24 default: 25 return JSONNumber.Parse ( json, refoffset);25 return JSONNumber.Parse (_json, ref _offset); 26 26 } 27 27 } 28 28 29 public static void SkipWhitespace (string json, ref intoffset) {29 public static void SkipWhitespace (string _json, ref int _offset) { 30 30 //Log.Out ("SkipWhitespace (" + offset + "): '" + json [offset] + "'"); 31 while ( offset <json.Length) {32 switch ( json [offset]) {31 while (_offset < _json.Length) { 32 switch (_json [_offset]) { 33 33 case ' ': 34 34 case '\t': 35 35 case '\r': 36 36 case '\n': 37 offset++;37 _offset++; 38 38 break; 39 39 default: -
binary-improvements/7dtd-server-fixes/src/LandClaimList.cs
r326 r351 5 5 namespace AllocsFixes { 6 6 public class LandClaimList { 7 public delegate bool OwnerFilter (Player owner);7 public delegate bool OwnerFilter (Player _owner); 8 8 9 public delegate bool PositionFilter (Vector3i position);9 public delegate bool PositionFilter (Vector3i _position); 10 10 11 11 public static Dictionary<Player, List<Vector3i>> GetLandClaims (OwnerFilter[] _ownerFilters, … … 68 68 69 69 public static OwnerFilter SteamIdFilter (string _steamId) { 70 return p =>p.SteamID.Equals (_steamId);70 return _p => _p.SteamID.Equals (_steamId); 71 71 } 72 72 73 73 public static PositionFilter CloseToFilter2dRect (Vector3i _position, int _maxDistance) { 74 return v => Math.Abs (v.x - _position.x) <= _maxDistance && Math.Abs (v.z - _position.z) <= _maxDistance;74 return _v => Math.Abs (_v.x - _position.x) <= _maxDistance && Math.Abs (_v.z - _position.z) <= _maxDistance; 75 75 } 76 76 77 77 public static OwnerFilter OrOwnerFilter (OwnerFilter _f1, OwnerFilter _f2) { 78 return p => _f1 (p) || _f2 (p);78 return _p => _f1 (_p) || _f2 (_p); 79 79 } 80 80 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/InvItem.cs
r325 r351 16 16 public int useTimes; 17 17 18 public InvItem (string itemName, int count, int quality, int maxUseTimes, intmaxUse) {19 this.itemName =itemName;20 this.count =count;21 this.quality =quality;22 this.maxUseTimes =maxUseTimes;23 this.useTimes =maxUse;18 public InvItem (string _itemName, int _count, int _quality, int _maxUseTimes, int _maxUse) { 19 itemName = _itemName; 20 count = _count; 21 quality = _quality; 22 maxUseTimes = _maxUseTimes; 23 useTimes = _maxUse; 24 24 } 25 25 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/Inventory.cs
r326 r351 15 15 } 16 16 17 public void Update (PlayerDataFile pdf) {17 public void Update (PlayerDataFile _pdf) { 18 18 lock (this) { 19 19 //Log.Out ("Updating player inventory - player id: " + pdf.id); 20 ProcessInv (bag, pdf.bag,pdf.id);21 ProcessInv (belt, pdf.inventory,pdf.id);22 ProcessEqu ( pdf.equipment,pdf.id);20 ProcessInv (bag, _pdf.bag, _pdf.id); 21 ProcessInv (belt, _pdf.inventory, _pdf.id); 22 ProcessEqu (_pdf.equipment, _pdf.id); 23 23 } 24 24 } 25 25 26 private void ProcessInv (List<InvItem> target, ItemStack[] sourceFields, intid) {27 target.Clear ();28 for (int i = 0; i < sourceFields.Length; i++) {29 InvItem item = CreateInvItem ( sourceFields [i].itemValue, sourceFields [i].count,id);30 if (item != null && sourceFields [i].itemValue.Modifications != null) {31 ProcessParts ( sourceFields [i].itemValue.Modifications, item,id);26 private void ProcessInv (List<InvItem> _target, ItemStack[] _sourceFields, int _id) { 27 _target.Clear (); 28 for (int i = 0; i < _sourceFields.Length; i++) { 29 InvItem item = CreateInvItem (_sourceFields [i].itemValue, _sourceFields [i].count, _id); 30 if (item != null && _sourceFields [i].itemValue.Modifications != null) { 31 ProcessParts (_sourceFields [i].itemValue.Modifications, item, _id); 32 32 } 33 33 34 target.Add (item);34 _target.Add (item); 35 35 } 36 36 } 37 37 38 private void ProcessEqu (Equipment sourceEquipment, int _playerId) {39 equipment = new InvItem[ sourceEquipment.GetSlotCount ()];40 for (int i = 0; i < sourceEquipment.GetSlotCount (); i++) {41 equipment [i] = CreateInvItem ( sourceEquipment.GetSlotItem (i), 1, _playerId);38 private void ProcessEqu (Equipment _sourceEquipment, int _playerId) { 39 equipment = new InvItem[_sourceEquipment.GetSlotCount ()]; 40 for (int i = 0; i < _sourceEquipment.GetSlotCount (); i++) { 41 equipment [i] = CreateInvItem (_sourceEquipment.GetSlotItem (i), 1, _playerId); 42 42 } 43 43 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/Player.cs
r333 r351 168 168 } 169 169 170 public Player (string steamId) {171 this.steamId =steamId;170 public Player (string _steamId) { 171 steamId = _steamId; 172 172 inventory = new Inventory (); 173 173 } … … 193 193 } 194 194 195 public void SetOnline (ClientInfo ci) {195 public void SetOnline (ClientInfo _ci) { 196 196 Log.Out ("Player set to online: " + steamId); 197 clientInfo = ci;198 entityId = ci.entityId;199 name = ci.playerName;200 ip = ci.ip;197 clientInfo = _ci; 198 entityId = _ci.entityId; 199 name = _ci.playerName; 200 ip = _ci.ip; 201 201 lastOnline = DateTime.Now; 202 202 } -
binary-improvements/7dtd-server-fixes/src/PersistentData/Players.cs
r332 r351 8 8 public readonly Dictionary<string, Player> Dict = new Dictionary<string, Player> (StringComparer.OrdinalIgnoreCase); 9 9 10 public Player this [string steamId, boolcreate] {10 public Player this [string _steamId, bool _create] { 11 11 get { 12 if (string.IsNullOrEmpty ( steamId)) {12 if (string.IsNullOrEmpty (_steamId)) { 13 13 return null; 14 14 } 15 15 16 if (Dict.ContainsKey ( steamId)) {17 return Dict [ steamId];16 if (Dict.ContainsKey (_steamId)) { 17 return Dict [_steamId]; 18 18 } 19 19 20 if (! create ||steamId.Length != 17) {20 if (!_create || _steamId.Length != 17) { 21 21 return null; 22 22 } 23 23 24 Log.Out ("Created new player entry for ID: " + steamId);25 Player p = new Player ( steamId);26 Dict.Add ( steamId, p);24 Log.Out ("Created new player entry for ID: " + _steamId); 25 Player p = new Player (_steamId); 26 Dict.Add (_steamId, p); 27 27 return p; 28 28 } -
binary-improvements/MapRendering/API.cs
r337 r351 21 21 22 22 private void GameShutdown () { 23 AllocsFixes.MapRendering.MapRendering.Shutdown ();23 MapRendering.MapRendering.Shutdown (); 24 24 } 25 25 26 26 private void CalcChunkColorsDone (Chunk _chunk) { 27 AllocsFixes.MapRendering.MapRendering.RenderSingleChunk (_chunk);27 MapRendering.MapRendering.RenderSingleChunk (_chunk); 28 28 } 29 29 } -
binary-improvements/MapRendering/MapRendering/Constants.cs
r331 r351 3 3 namespace AllocsFixes.MapRendering { 4 4 public class Constants { 5 public static TextureFormat DEFAULT_TEX_FORMAT = TextureFormat.ARGB32;5 public static readonly TextureFormat DEFAULT_TEX_FORMAT = TextureFormat.ARGB32; 6 6 public static int MAP_BLOCK_SIZE = 128; 7 public staticint MAP_CHUNK_SIZE = 16;8 public staticint MAP_REGION_SIZE = 512;7 public const int MAP_CHUNK_SIZE = 16; 8 public const int MAP_REGION_SIZE = 512; 9 9 public static int ZOOMLEVELS = 5; 10 10 public static string MAP_DIRECTORY = string.Empty; -
binary-improvements/MapRendering/MapRendering/MapRenderBlockBuffer.cs
r346 r351 18 18 private string currentBlockMapFolder = string.Empty; 19 19 20 public MapRenderBlockBuffer (int level, MapTileCachecache) {21 zoomLevel = level;22 this.cache =cache;20 public MapRenderBlockBuffer (int _level, MapTileCache _cache) { 21 zoomLevel = _level; 22 cache = _cache; 23 23 folderBase = Constants.MAP_DIRECTORY + "/" + zoomLevel + "/"; 24 24 … … 59 59 } 60 60 61 public bool LoadBlock (Vector2i block) {61 public bool LoadBlock (Vector2i _block) { 62 62 Profiler.BeginSample ("LoadBlock"); 63 63 lock (blockMap) { 64 if (currentBlockMapPos != block) {64 if (currentBlockMapPos != _block) { 65 65 Profiler.BeginSample ("LoadBlock.Strings"); 66 66 string folder; 67 if (currentBlockMapPos.x != block.x) {68 folder = folderBase + block.x + '/';67 if (currentBlockMapPos.x != _block.x) { 68 folder = folderBase + _block.x + '/'; 69 69 70 70 Profiler.BeginSample ("LoadBlock.Directory"); … … 75 75 } 76 76 77 string fileName = folder + block.y + ".png";77 string fileName = folder + _block.y + ".png"; 78 78 Profiler.EndSample (); 79 79 … … 82 82 83 83 currentBlockMapFolder = folder; 84 currentBlockMapPos = block;84 currentBlockMapPos = _block; 85 85 86 86 Profiler.EndSample (); … … 93 93 } 94 94 95 public void SetPart (Vector2i offset, int partSize, Color32[]pixels) {96 if ( offset.x + partSize > Constants.MAP_BLOCK_SIZE || offset.y +partSize > Constants.MAP_BLOCK_SIZE) {95 public void SetPart (Vector2i _offset, int _partSize, Color32[] _pixels) { 96 if (_offset.x + _partSize > Constants.MAP_BLOCK_SIZE || _offset.y + _partSize > Constants.MAP_BLOCK_SIZE) { 97 97 Log.Error (string.Format ("MapBlockBuffer[{0}].SetPart ({1}, {2}, {3}) has blockMap.size ({4}/{5})", 98 zoomLevel, offset, partSize,pixels.Length, Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE));98 zoomLevel, _offset, _partSize, _pixels.Length, Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE)); 99 99 return; 100 100 } 101 101 102 102 Profiler.BeginSample ("SetPart"); 103 blockMap.SetPixels32 ( offset.x, offset.y, partSize, partSize,pixels);103 blockMap.SetPixels32 (_offset.x, _offset.y, _partSize, _partSize, _pixels); 104 104 Profiler.EndSample (); 105 105 } … … 135 135 } 136 136 137 public void SetPartNative (Vector2i offset, int partSize, NativeArray<int>pixels) {138 if ( offset.x + partSize > Constants.MAP_BLOCK_SIZE || offset.y +partSize > Constants.MAP_BLOCK_SIZE) {137 public void SetPartNative (Vector2i _offset, int _partSize, NativeArray<int> _pixels) { 138 if (_offset.x + _partSize > Constants.MAP_BLOCK_SIZE || _offset.y + _partSize > Constants.MAP_BLOCK_SIZE) { 139 139 Log.Error (string.Format ("MapBlockBuffer[{0}].SetPart ({1}, {2}, {3}) has blockMap.size ({4}/{5})", 140 zoomLevel, offset, partSize,pixels.Length, Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE));140 zoomLevel, _offset, _partSize, _pixels.Length, Constants.MAP_BLOCK_SIZE, Constants.MAP_BLOCK_SIZE)); 141 141 return; 142 142 } … … 145 145 NativeArray<int> destData = blockMap.GetRawTextureData<int> (); 146 146 147 for (int y = 0; y < partSize; y++) {148 int srcLineStartIdx = partSize * y;149 int destLineStartIdx = blockMap.width * ( offset.y + y) +offset.x;150 for (int x = 0; x < partSize; x++) {151 destData [destLineStartIdx + x] = pixels [srcLineStartIdx + x];147 for (int y = 0; y < _partSize; y++) { 148 int srcLineStartIdx = _partSize * y; 149 int destLineStartIdx = blockMap.width * (_offset.y + y) + _offset.x; 150 for (int x = 0; x < _partSize; x++) { 151 destData [destLineStartIdx + x] = _pixels [srcLineStartIdx + x]; 152 152 } 153 153 } -
binary-improvements/MapRendering/MapRendering/MapRendering.cs
r346 r351 5 5 using System.Text; 6 6 using System.Threading; 7 using System.Timers;8 7 using AllocsFixes.FileCache; 9 8 using AllocsFixes.JSON; … … 66 65 } 67 66 68 public static void RenderSingleChunk (Chunk chunk) {67 public static void RenderSingleChunk (Chunk _chunk) { 69 68 if (renderingEnabled) { 70 69 // TODO: Replace with regular thread and a blocking queue / set 71 ThreadPool.UnsafeQueueUserWorkItem ( o => {70 ThreadPool.UnsafeQueueUserWorkItem (_o => { 72 71 try { 73 72 if (!Instance.renderingFullMap) { 74 73 lock (lockObject) { 75 Chunk c = (Chunk) o;74 Chunk c = (Chunk) _o; 76 75 Vector3i cPos = c.GetWorldPos (); 77 76 Vector2i cPos2 = new Vector2i (cPos.x / Constants.MAP_CHUNK_SIZE, … … 95 94 Log.Out ("Exception in MapRendering.RenderSingleChunk(): " + e); 96 95 } 97 }, chunk);96 }, _chunk); 98 97 } 99 98 } … … 279 278 } 280 279 281 private void RenderZoomLevel (Vector2i innerBlock) {280 private void RenderZoomLevel (Vector2i _innerBlock) { 282 281 Profiler.BeginSample ("RenderZoomLevel"); 283 282 int level = Constants.ZOOMLEVELS - 1; 284 283 while (level > 0) { 285 284 Vector2i block, blockOffset; 286 getBlockNumber ( innerBlock, out block, out blockOffset, 2, Constants.MAP_BLOCK_SIZE / 2);285 getBlockNumber (_innerBlock, out block, out blockOffset, 2, Constants.MAP_BLOCK_SIZE / 2); 287 286 288 287 zoomLevelBuffers [level - 1].LoadBlock (block); … … 299 298 300 299 level--; 301 innerBlock = block;300 _innerBlock = block; 302 301 } 303 302 Profiler.EndSample (); 304 303 } 305 304 306 private void getBlockNumber (Vector2i innerPos, out Vector2i block, out Vector2i blockOffset, intscaleFactor,307 int offsetSize) {308 block = default (Vector2i);309 blockOffset = default (Vector2i);310 block.x = (innerPos.x + 16777216) / scaleFactor - 16777216 /scaleFactor;311 block.y = (innerPos.y + 16777216) / scaleFactor - 16777216 /scaleFactor;312 blockOffset.x = (innerPos.x + 16777216) % scaleFactor *offsetSize;313 blockOffset.y = (innerPos.y + 16777216) % scaleFactor *offsetSize;305 private void getBlockNumber (Vector2i _innerPos, out Vector2i _block, out Vector2i _blockOffset, int _scaleFactor, 306 int _offsetSize) { 307 _block = default (Vector2i); 308 _blockOffset = default (Vector2i); 309 _block.x = (_innerPos.x + 16777216) / _scaleFactor - 16777216 / _scaleFactor; 310 _block.y = (_innerPos.y + 16777216) / _scaleFactor - 16777216 / _scaleFactor; 311 _blockOffset.x = (_innerPos.x + 16777216) % _scaleFactor * _offsetSize; 312 _blockOffset.y = (_innerPos.y + 16777216) % _scaleFactor * _offsetSize; 314 313 } 315 314 … … 352 351 } 353 352 354 private void getWorldExtent (RegionFileManager rfm, out Vector2i minChunk, out Vector2imaxChunk,355 out Vector2i minPos, out Vector2imaxPos,356 out int widthChunks, out intheightChunks,357 out int widthPix, out intheightPix) {358 minChunk = default (Vector2i);359 maxChunk = default (Vector2i);360 minPos = default (Vector2i);361 maxPos = default (Vector2i);362 363 long[] keys = rfm.GetAllChunkKeys ();353 private void getWorldExtent (RegionFileManager _rfm, out Vector2i _minChunk, out Vector2i _maxChunk, 354 out Vector2i _minPos, out Vector2i _maxPos, 355 out int _widthChunks, out int _heightChunks, 356 out int _widthPix, out int _heightPix) { 357 _minChunk = default (Vector2i); 358 _maxChunk = default (Vector2i); 359 _minPos = default (Vector2i); 360 _maxPos = default (Vector2i); 361 362 long[] keys = _rfm.GetAllChunkKeys (); 364 363 int minX = int.MaxValue; 365 364 int minY = int.MaxValue; … … 387 386 } 388 387 389 minChunk.x = minX;390 minChunk.y = minY;391 392 maxChunk.x = maxX;393 maxChunk.y = maxY;394 395 minPos.x = minX * Constants.MAP_CHUNK_SIZE;396 minPos.y = minY * Constants.MAP_CHUNK_SIZE;397 398 maxPos.x = maxX * Constants.MAP_CHUNK_SIZE;399 maxPos.y = maxY * Constants.MAP_CHUNK_SIZE;400 401 widthChunks = maxX - minX + 1;402 heightChunks = maxY - minY + 1;403 404 widthPix =widthChunks * Constants.MAP_CHUNK_SIZE;405 heightPix =heightChunks * Constants.MAP_CHUNK_SIZE;406 } 407 408 private static Color32 shortColorToColor32 (ushort col) {409 byte r = (byte) (256 * (( col >> 10) & 31) / 32);410 byte g = (byte) (256 * (( col >> 5) & 31) / 32);411 byte b = (byte) (256 * ( col & 31) / 32);412 byte a = 255;388 _minChunk.x = minX; 389 _minChunk.y = minY; 390 391 _maxChunk.x = maxX; 392 _maxChunk.y = maxY; 393 394 _minPos.x = minX * Constants.MAP_CHUNK_SIZE; 395 _minPos.y = minY * Constants.MAP_CHUNK_SIZE; 396 397 _maxPos.x = maxX * Constants.MAP_CHUNK_SIZE; 398 _maxPos.y = maxY * Constants.MAP_CHUNK_SIZE; 399 400 _widthChunks = maxX - minX + 1; 401 _heightChunks = maxY - minY + 1; 402 403 _widthPix = _widthChunks * Constants.MAP_CHUNK_SIZE; 404 _heightPix = _heightChunks * Constants.MAP_CHUNK_SIZE; 405 } 406 407 private static Color32 shortColorToColor32 (ushort _col) { 408 byte r = (byte) (256 * ((_col >> 10) & 31) / 32); 409 byte g = (byte) (256 * ((_col >> 5) & 31) / 32); 410 byte b = (byte) (256 * (_col & 31) / 32); 411 const byte a = 255; 413 412 return new Color32 (r, g, b, a); 414 413 } -
binary-improvements/MapRendering/Web/API/ExecuteConsoleCommand.cs
r347 r351 4 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 5 5 public class ExecuteConsoleCommand : WebAPI { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,7 int permissionLevel) {8 if (string.IsNullOrEmpty ( req.QueryString ["command"])) {9 resp.StatusCode = (int) HttpStatusCode.BadRequest;10 Web.SetResponseTextContent ( resp, "No command given");6 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 7 int _permissionLevel) { 8 if (string.IsNullOrEmpty (_req.QueryString ["command"])) { 9 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 10 Web.SetResponseTextContent (_resp, "No command given"); 11 11 return; 12 12 } 13 13 14 14 WebCommandResult.ResultType responseType = 15 req.QueryString ["raw"] != null15 _req.QueryString ["raw"] != null 16 16 ? WebCommandResult.ResultType.Raw 17 : ( req.QueryString ["simple"] != null17 : (_req.QueryString ["simple"] != null 18 18 ? WebCommandResult.ResultType.ResultOnly 19 19 : WebCommandResult.ResultType.Full); 20 20 21 string commandline = req.QueryString ["command"];21 string commandline = _req.QueryString ["command"]; 22 22 string commandPart = commandline.Split (' ') [0]; 23 23 string argumentsPart = commandline.Substring (Math.Min (commandline.Length, commandPart.Length + 1)); … … 26 26 27 27 if (command == null) { 28 resp.StatusCode = (int) HttpStatusCode.NotFound;29 Web.SetResponseTextContent ( resp, "Unknown command");28 _resp.StatusCode = (int) HttpStatusCode.NotFound; 29 Web.SetResponseTextContent (_resp, "Unknown command"); 30 30 return; 31 31 } … … 34 34 GameManager.Instance.adminTools.GetAdminToolsCommandPermission (command.GetCommands ()); 35 35 36 if ( permissionLevel > atcp.PermissionLevel) {37 resp.StatusCode = (int) HttpStatusCode.Forbidden;38 Web.SetResponseTextContent ( resp, "You are not allowed to execute this command");36 if (_permissionLevel > atcp.PermissionLevel) { 37 _resp.StatusCode = (int) HttpStatusCode.Forbidden; 38 Web.SetResponseTextContent (_resp, "You are not allowed to execute this command"); 39 39 return; 40 40 } 41 41 42 resp.SendChunked = true;43 WebCommandResult wcr = new WebCommandResult (commandPart, argumentsPart, responseType, resp);42 _resp.SendChunked = true; 43 WebCommandResult wcr = new WebCommandResult (commandPart, argumentsPart, responseType, _resp); 44 44 SdtdConsole.Instance.ExecuteAsync (commandline, wcr); 45 45 } -
binary-improvements/MapRendering/Web/API/GetAllowedCommands.cs
r325 r351 4 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 5 5 public class GetAllowedCommands : WebAPI { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,7 int permissionLevel) {6 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 7 int _permissionLevel) { 8 8 JSONObject result = new JSONObject (); 9 9 JSONArray entries = new JSONArray (); … … 11 11 AdminToolsCommandPermissions atcp = 12 12 GameManager.Instance.adminTools.GetAdminToolsCommandPermission (cc.GetCommands ()); 13 if ( permissionLevel <= atcp.PermissionLevel) {13 if (_permissionLevel <= atcp.PermissionLevel) { 14 14 string cmd = string.Empty; 15 15 foreach (string s in cc.GetCommands ()) { … … 29 29 result.Add ("commands", entries); 30 30 31 WriteJSON ( resp, result);31 WriteJSON (_resp, result); 32 32 } 33 33 -
binary-improvements/MapRendering/Web/API/GetAnimalsLocation.cs
r325 r351 8 8 private readonly List<EntityAnimal> animals = new List<EntityAnimal> (); 9 9 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,11 int permissionLevel) {10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 12 12 JSONArray animalsJsResult = new JSONArray (); 13 13 … … 36 36 } 37 37 38 WriteJSON ( resp, animalsJsResult);38 WriteJSON (_resp, animalsJsResult); 39 39 } 40 40 } -
binary-improvements/MapRendering/Web/API/GetHostileLocation.cs
r325 r351 8 8 private readonly List<EntityEnemy> enemies = new List<EntityEnemy> (); 9 9 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,11 int permissionLevel) {10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 12 12 JSONArray hostilesJsResult = new JSONArray (); 13 13 … … 36 36 } 37 37 38 WriteJSON ( resp, hostilesJsResult);38 WriteJSON (_resp, hostilesJsResult); 39 39 } 40 40 } -
binary-improvements/MapRendering/Web/API/GetLandClaims.cs
r332 r351 6 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 7 public class GetLandClaims : WebAPI { 8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,9 int permissionLevel) {8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 10 10 string requestedSteamID = string.Empty; 11 11 12 if ( req.QueryString ["steamid"] != null) {12 if (_req.QueryString ["steamid"] != null) { 13 13 ulong lViewersSteamID; 14 requestedSteamID = req.QueryString ["steamid"];14 requestedSteamID = _req.QueryString ["steamid"]; 15 15 if (requestedSteamID.Length != 17 || !ulong.TryParse (requestedSteamID, out lViewersSteamID)) { 16 resp.StatusCode = (int) HttpStatusCode.BadRequest;17 Web.SetResponseTextContent ( resp, "Invalid SteamID given");16 _resp.StatusCode = (int) HttpStatusCode.BadRequest; 17 Web.SetResponseTextContent (_resp, "Invalid SteamID given"); 18 18 return; 19 19 } … … 21 21 22 22 // default user, cheap way to avoid 'null reference exception' 23 user =user ?? new WebConnection ("", IPAddress.None, 0L);23 _user = _user ?? new WebConnection ("", IPAddress.None, 0L); 24 24 25 bool bViewAll = WebConnection.CanViewAllClaims ( permissionLevel);25 bool bViewAll = WebConnection.CanViewAllClaims (_permissionLevel); 26 26 27 27 JSONObject result = new JSONObject (); 28 result.Add ("claimsize", new JSONNumber (GamePrefs.GetInt (Enum GamePrefs.LandClaimSize)));28 result.Add ("claimsize", new JSONNumber (GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> ("LandClaimSize")))); 29 29 30 30 JSONArray claimOwners = new JSONArray (); … … 35 35 if (!string.IsNullOrEmpty (requestedSteamID) && !bViewAll) { 36 36 ownerFilters = new[] { 37 LandClaimList.SteamIdFilter ( user.SteamID.ToString ()),37 LandClaimList.SteamIdFilter (_user.SteamID.ToString ()), 38 38 LandClaimList.SteamIdFilter (requestedSteamID) 39 39 }; 40 40 } else if (!bViewAll) { 41 ownerFilters = new[] {LandClaimList.SteamIdFilter ( user.SteamID.ToString ())};41 ownerFilters = new[] {LandClaimList.SteamIdFilter (_user.SteamID.ToString ())}; 42 42 } else { 43 43 ownerFilters = new[] {LandClaimList.SteamIdFilter (requestedSteamID)}; … … 78 78 } 79 79 80 WriteJSON ( resp, result);80 WriteJSON (_resp, result); 81 81 } 82 82 } -
binary-improvements/MapRendering/Web/API/GetPlayerList.cs
r332 r351 17 17 #endif 18 18 19 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,20 int permissionLevel) {19 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 20 int _permissionLevel) { 21 21 AdminTools admTools = GameManager.Instance.adminTools; 22 user =user ?? new WebConnection ("", IPAddress.None, 0L);23 24 bool bViewAll = WebConnection.CanViewAllPlayers ( permissionLevel);22 _user = _user ?? new WebConnection ("", IPAddress.None, 0L); 23 24 bool bViewAll = WebConnection.CanViewAllPlayers (_permissionLevel); 25 25 26 26 // TODO: Sort (and filter?) prior to converting to JSON ... hard as how to get the correct column's data? (i.e. column name matches JSON object field names, not source data) 27 27 28 28 int rowsPerPage = 25; 29 if ( req.QueryString ["rowsperpage"] != null) {30 int.TryParse ( req.QueryString ["rowsperpage"], out rowsPerPage);29 if (_req.QueryString ["rowsperpage"] != null) { 30 int.TryParse (_req.QueryString ["rowsperpage"], out rowsPerPage); 31 31 } 32 32 33 33 int page = 0; 34 if ( req.QueryString ["page"] != null) {35 int.TryParse ( req.QueryString ["page"], out page);34 if (_req.QueryString ["page"] != null) { 35 int.TryParse (_req.QueryString ["page"], out page); 36 36 } 37 37 … … 55 55 } 56 56 57 if (player_steam_ID == user.SteamID || bViewAll) {57 if (player_steam_ID == _user.SteamID || bViewAll) { 58 58 JSONObject pos = new JSONObject (); 59 59 pos.Add ("x", new JSONNumber (p.LastPosition.x)); … … 93 93 IEnumerable<JSONObject> list = playerList; 94 94 95 foreach (string key in req.QueryString.AllKeys) {95 foreach (string key in _req.QueryString.AllKeys) { 96 96 if (!string.IsNullOrEmpty (key) && key.StartsWith ("filter[")) { 97 97 string filterCol = key.Substring (key.IndexOf ('[') + 1); 98 98 filterCol = filterCol.Substring (0, filterCol.Length - 1); 99 string filterVal = req.QueryString.Get (key).Trim ();99 string filterVal = _req.QueryString.Get (key).Trim (); 100 100 101 101 list = ExecuteFilter (list, filterCol, filterVal); … … 105 105 int totalAfterFilter = list.Count (); 106 106 107 foreach (string key in req.QueryString.AllKeys) {107 foreach (string key in _req.QueryString.AllKeys) { 108 108 if (!string.IsNullOrEmpty (key) && key.StartsWith ("sort[")) { 109 109 string sortCol = key.Substring (key.IndexOf ('[') + 1); 110 110 sortCol = sortCol.Substring (0, sortCol.Length - 1); 111 string sortVal = req.QueryString.Get (key);111 string sortVal = _req.QueryString.Get (key); 112 112 113 113 list = ExecuteSort (list, sortCol, sortVal == "0"); … … 130 130 result.Add ("players", playersJsResult); 131 131 132 WriteJSON ( resp, result);132 WriteJSON (_resp, result); 133 133 } 134 134 135 135 private IEnumerable<JSONObject> ExecuteFilter (IEnumerable<JSONObject> _list, string _filterCol, 136 136 string _filterVal) { 137 if ( _list.Count () == 0) {137 if (!_list.Any()) { 138 138 return _list; 139 139 } … … 147 147 if (colType == typeof (JSONBoolean)) { 148 148 bool value = StringParsers.ParseBool (_filterVal); 149 return _list.Where ( line => ((JSONBoolean)line [_filterCol]).GetBool () == value);149 return _list.Where (_line => ((JSONBoolean) _line [_filterCol]).GetBool () == value); 150 150 } 151 151 … … 157 157 //Log.Out ("GetPlayerList: Filter on String with Regex '" + _filterVal + "'"); 158 158 Regex matcher = new Regex (_filterVal, RegexOptions.IgnoreCase); 159 return _list.Where ( line => matcher.IsMatch (((JSONString)line [_filterCol]).GetString ()));159 return _list.Where (_line => matcher.IsMatch (((JSONString) _line [_filterCol]).GetString ())); 160 160 } 161 161 } … … 198 198 } 199 199 200 return _list.Where (delegate (JSONObject line) {201 double objVal = ((JSONNumber) line [_filterCol]).GetDouble ();200 return _list.Where (delegate (JSONObject _line) { 201 double objVal = ((JSONNumber) _line [_filterCol]).GetDouble (); 202 202 switch (matchType) { 203 203 case NumberMatchType.Greater: … … 230 230 if (colType == typeof (JSONNumber)) { 231 231 if (_ascending) { 232 return _list.OrderBy ( line => ((JSONNumber)line [_sortCol]).GetDouble ());233 } 234 235 return _list.OrderByDescending ( line => ((JSONNumber)line [_sortCol]).GetDouble ());232 return _list.OrderBy (_line => ((JSONNumber) _line [_sortCol]).GetDouble ()); 233 } 234 235 return _list.OrderByDescending (_line => ((JSONNumber) _line [_sortCol]).GetDouble ()); 236 236 } 237 237 238 238 if (colType == typeof (JSONBoolean)) { 239 239 if (_ascending) { 240 return _list.OrderBy ( line => ((JSONBoolean)line [_sortCol]).GetBool ());241 } 242 243 return _list.OrderByDescending ( line => ((JSONBoolean)line [_sortCol]).GetBool ());240 return _list.OrderBy (_line => ((JSONBoolean) _line [_sortCol]).GetBool ()); 241 } 242 243 return _list.OrderByDescending (_line => ((JSONBoolean) _line [_sortCol]).GetBool ()); 244 244 } 245 245 246 246 if (_ascending) { 247 return _list.OrderBy ( line =>line [_sortCol].ToString ());248 } 249 250 return _list.OrderByDescending ( line =>line [_sortCol].ToString ());247 return _list.OrderBy (_line => _line [_sortCol].ToString ()); 248 } 249 250 return _list.OrderByDescending (_line => _line [_sortCol].ToString ()); 251 251 } 252 252 … … 255 255 256 256 257 private bool NearlyEqual (double a, double b, doubleepsilon) {258 double absA = Math.Abs ( a);259 double absB = Math.Abs ( b);260 double diff = Math.Abs ( a -b);261 262 if ( a ==b) {257 private bool NearlyEqual (double _a, double _b, double _epsilon) { 258 double absA = Math.Abs (_a); 259 double absB = Math.Abs (_b); 260 double diff = Math.Abs (_a - _b); 261 262 if (_a == _b) { 263 263 return true; 264 264 } 265 265 266 if ( a == 0 ||b == 0 || diff < double.Epsilon) {267 return diff < epsilon;268 } 269 270 return diff / (absA + absB) < epsilon;266 if (_a == 0 || _b == 0 || diff < double.Epsilon) { 267 return diff < _epsilon; 268 } 269 270 return diff / (absA + absB) < _epsilon; 271 271 } 272 272 -
binary-improvements/MapRendering/Web/API/GetPlayersLocation.cs
r332 r351 6 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 7 public class GetPlayersLocation : WebAPI { 8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,9 int permissionLevel) {8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 10 10 AdminTools admTools = GameManager.Instance.adminTools; 11 user =user ?? new WebConnection ("", IPAddress.None, 0L);11 _user = _user ?? new WebConnection ("", IPAddress.None, 0L); 12 12 13 13 bool listOffline = false; 14 if ( req.QueryString ["offline"] != null) {15 bool.TryParse ( req.QueryString ["offline"], out listOffline);14 if (_req.QueryString ["offline"] != null) { 15 bool.TryParse (_req.QueryString ["offline"], out listOffline); 16 16 } 17 17 18 bool bViewAll = WebConnection.CanViewAllPlayers ( permissionLevel);18 bool bViewAll = WebConnection.CanViewAllPlayers (_permissionLevel); 19 19 20 20 JSONArray playersJsResult = new JSONArray (); … … 37 37 } 38 38 39 if (player_steam_ID == user.SteamID || bViewAll) {39 if (player_steam_ID == _user.SteamID || bViewAll) { 40 40 JSONObject pos = new JSONObject (); 41 41 pos.Add ("x", new JSONNumber (p.LastPosition.x)); … … 61 61 } 62 62 63 WriteJSON ( resp, playersJsResult);63 WriteJSON (_resp, playersJsResult); 64 64 } 65 65 } -
binary-improvements/MapRendering/Web/API/GetPlayersOnline.cs
r326 r351 6 6 namespace AllocsFixes.NetConnections.Servers.Web.API { 7 7 public class GetPlayersOnline : WebAPI { 8 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,9 int permissionLevel) {8 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 9 int _permissionLevel) { 10 10 JSONArray players = new JSONArray (); 11 11 … … 46 46 } 47 47 48 WriteJSON ( resp, players);48 WriteJSON (_resp, players); 49 49 } 50 50 } -
binary-improvements/MapRendering/Web/API/GetServerInfo.cs
r325 r351 5 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 6 public class GetServerInfo : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,8 int permissionLevel) {7 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 8 int _permissionLevel) { 9 9 JSONObject serverInfo = new JSONObject (); 10 10 … … 42 42 43 43 44 WriteJSON ( resp, serverInfo);44 WriteJSON (_resp, serverInfo); 45 45 } 46 46 } -
binary-improvements/MapRendering/Web/API/GetStats.cs
r325 r351 5 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 6 public class GetStats : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,8 int permissionLevel) {7 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 8 int _permissionLevel) { 9 9 JSONObject result = new JSONObject (); 10 10 … … 19 19 result.Add ("animals", new JSONNumber (Animals.Instance.GetCount ())); 20 20 21 WriteJSON ( resp, result);21 WriteJSON (_resp, result); 22 22 } 23 23 -
binary-improvements/MapRendering/Web/API/GetWebUIUpdates.cs
r325 r351 5 5 namespace AllocsFixes.NetConnections.Servers.Web.API { 6 6 public class GetWebUIUpdates : WebAPI { 7 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,8 int permissionLevel) {7 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 8 int _permissionLevel) { 9 9 int latestLine; 10 if ( req.QueryString ["latestLine"] == null ||11 !int.TryParse ( req.QueryString ["latestLine"], out latestLine)) {10 if (_req.QueryString ["latestLine"] == null || 11 !int.TryParse (_req.QueryString ["latestLine"], out latestLine)) { 12 12 latestLine = 0; 13 13 } … … 27 27 result.Add ("newlogs", new JSONNumber (LogBuffer.Instance.LatestLine - latestLine)); 28 28 29 WriteJSON ( resp, result);29 WriteJSON (_resp, result); 30 30 } 31 31 -
binary-improvements/MapRendering/Web/API/Null.cs
r325 r351 4 4 namespace AllocsFixes.NetConnections.Servers.Web.API { 5 5 public class Null : WebAPI { 6 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,7 int permissionLevel) {8 resp.ContentLength64 = 0;9 resp.ContentType = "text/plain";10 resp.ContentEncoding = Encoding.ASCII;11 resp.OutputStream.Write (new byte[] { }, 0, 0);6 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 7 int _permissionLevel) { 8 _resp.ContentLength64 = 0; 9 _resp.ContentType = "text/plain"; 10 _resp.ContentEncoding = Encoding.ASCII; 11 _resp.OutputStream.Write (new byte[] { }, 0, 0); 12 12 } 13 13 } -
binary-improvements/MapRendering/Web/API/WebAPI.cs
r332 r351 17 17 #endif 18 18 19 public static void WriteJSON (HttpListenerResponse resp, JSONNoderoot) {19 public static void WriteJSON (HttpListenerResponse _resp, JSONNode _root) { 20 20 #if ENABLE_PROFILER 21 21 jsonSerializeSampler.Begin (); 22 22 #endif 23 23 StringBuilder sb = new StringBuilder (); 24 root.ToString (sb);24 _root.ToString (sb); 25 25 #if ENABLE_PROFILER 26 26 jsonSerializeSampler.End (); … … 28 28 #endif 29 29 byte[] buf = Encoding.UTF8.GetBytes (sb.ToString ()); 30 resp.ContentLength64 = buf.Length;31 resp.ContentType = "application/json";32 resp.ContentEncoding = Encoding.UTF8;33 resp.OutputStream.Write (buf, 0, buf.Length);30 _resp.ContentLength64 = buf.Length; 31 _resp.ContentType = "application/json"; 32 _resp.ContentEncoding = Encoding.UTF8; 33 _resp.OutputStream.Write (buf, 0, buf.Length); 34 34 #if ENABLE_PROFILER 35 35 netWriteSampler.End (); … … 45 45 } 46 46 47 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,48 int permissionLevel);47 public abstract void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 48 int _permissionLevel); 49 49 50 50 public virtual int DefaultPermissionLevel () { -
binary-improvements/MapRendering/Web/ConnectionHandler.cs
r332 r351 41 41 } 42 42 43 public void SendLine (string line) {43 public void SendLine (string _line) { 44 44 foreach (KeyValuePair<string, WebConnection> kvp in connections) { 45 kvp.Value.SendLine ( line);45 kvp.Value.SendLine (_line); 46 46 } 47 47 } -
binary-improvements/MapRendering/Web/Handlers/ApiHandler.cs
r332 r351 11 11 private readonly string staticPart; 12 12 13 public ApiHandler (string staticPart, string moduleName = null) : base (moduleName) {14 this.staticPart =staticPart;13 public ApiHandler (string _staticPart, string _moduleName = null) : base (_moduleName) { 14 staticPart = _staticPart; 15 15 16 16 foreach (Type t in Assembly.GetExecutingAssembly ().GetTypes ()) { … … 45 45 #endif 46 46 47 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnection user, 48 int permissionLevel) { 49 string apiName = req.Url.AbsolutePath.Remove (0, staticPart.Length); 50 if (!AuthorizeForCommand (apiName, user, permissionLevel)) { 51 resp.StatusCode = (int) HttpStatusCode.Forbidden; 52 if (user != null) { 47 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 48 int _permissionLevel) { 49 string apiName = _req.Url.AbsolutePath.Remove (0, staticPart.Length); 50 51 WebAPI api; 52 if (!apis.TryGetValue (apiName, out api)) { 53 Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\""); 54 _resp.StatusCode = (int) HttpStatusCode.NotFound; 55 return; 56 } 57 58 if (!AuthorizeForCommand (apiName, _user, _permissionLevel)) { 59 _resp.StatusCode = (int) HttpStatusCode.Forbidden; 60 if (_user != null) { 53 61 //Log.Out ("ApiHandler: user '{0}' not allowed to execute '{1}'", user.SteamID, apiName); 54 62 } … … 57 65 } 58 66 59 WebAPI api; 60 if (apis.TryGetValue (apiName, out api)) { 61 try { 67 try { 62 68 #if ENABLE_PROFILER 63 69 apiHandlerSampler.Begin (); 64 70 #endif 65 api.HandleRequest (req, resp, user,permissionLevel);71 api.HandleRequest (_req, _resp, _user, _permissionLevel); 66 72 #if ENABLE_PROFILER 67 73 apiHandlerSampler.End (); 68 74 #endif 69 return; 70 } catch (Exception e) { 71 Log.Error ("Error in ApiHandler.HandleRequest(): Handler {0} threw an exception:", api.Name); 72 Log.Exception (e); 73 resp.StatusCode = (int) HttpStatusCode.InternalServerError; 74 return; 75 } 75 } catch (Exception e) { 76 Log.Error ("Error in ApiHandler.HandleRequest(): Handler {0} threw an exception:", api.Name); 77 Log.Exception (e); 78 _resp.StatusCode = (int) HttpStatusCode.InternalServerError; 76 79 } 77 78 Log.Out ("Error in ApiHandler.HandleRequest(): No handler found for API \"" + apiName + "\"");79 resp.StatusCode = (int) HttpStatusCode.NotFound;80 80 } 81 81 82 private bool AuthorizeForCommand (string apiName, WebConnection user, intpermissionLevel) {83 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + apiName,permissionLevel);82 private bool AuthorizeForCommand (string _apiName, WebConnection _user, int _permissionLevel) { 83 return WebPermissions.Instance.ModuleAllowedWithLevel ("webapi." + _apiName, _permissionLevel); 84 84 } 85 85 } -
binary-improvements/MapRendering/Web/Handlers/ItemIconHandler.cs
r326 r351 18 18 } 19 19 20 public ItemIconHandler (string staticPart, bool logMissingFiles, string moduleName = null) : base (moduleName) {21 this.staticPart =staticPart;22 this.logMissingFiles =logMissingFiles;20 public ItemIconHandler (string _staticPart, bool _logMissingFiles, string _moduleName = null) : base (_moduleName) { 21 staticPart = _staticPart; 22 logMissingFiles = _logMissingFiles; 23 23 Instance = this; 24 24 } … … 26 26 public static ItemIconHandler Instance { get; private set; } 27 27 28 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,29 int permissionLevel) {28 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 29 int _permissionLevel) { 30 30 if (!loaded) { 31 resp.StatusCode = (int) HttpStatusCode.InternalServerError;31 _resp.StatusCode = (int) HttpStatusCode.InternalServerError; 32 32 Log.Out ("Web:IconHandler: Icons not loaded"); 33 33 return; 34 34 } 35 35 36 string requestFileName = req.Url.AbsolutePath.Remove (0, staticPart.Length);36 string requestFileName = _req.Url.AbsolutePath.Remove (0, staticPart.Length); 37 37 requestFileName = requestFileName.Remove (requestFileName.LastIndexOf ('.')); 38 38 39 if (icons.ContainsKey (requestFileName) && req.Url.AbsolutePath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {40 resp.ContentType = MimeType.GetMimeType (".png");39 if (icons.ContainsKey (requestFileName) && _req.Url.AbsolutePath.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) { 40 _resp.ContentType = MimeType.GetMimeType (".png"); 41 41 42 42 byte[] itemIconData = icons [requestFileName]; 43 43 44 resp.ContentLength64 = itemIconData.Length;45 resp.OutputStream.Write (itemIconData, 0, itemIconData.Length);44 _resp.ContentLength64 = itemIconData.Length; 45 _resp.OutputStream.Write (itemIconData, 0, itemIconData.Length); 46 46 } else { 47 resp.StatusCode = (int) HttpStatusCode.NotFound;47 _resp.StatusCode = (int) HttpStatusCode.NotFound; 48 48 if (logMissingFiles) { 49 Log.Out ("Web:IconHandler:FileNotFound: \"" + req.Url.AbsolutePath + "\" ");49 Log.Out ("Web:IconHandler:FileNotFound: \"" + _req.Url.AbsolutePath + "\" "); 50 50 } 51 51 } -
binary-improvements/MapRendering/Web/Handlers/PathHandler.cs
r325 r351 14 14 } 15 15 16 public abstract void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,17 int permissionLevel);16 public abstract void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 17 int _permissionLevel); 18 18 19 public bool IsAuthorizedForHandler (WebConnection user, intpermissionLevel) {19 public bool IsAuthorizedForHandler (WebConnection _user, int _permissionLevel) { 20 20 if (moduleName != null) { 21 return WebPermissions.Instance.ModuleAllowedWithLevel (moduleName, permissionLevel);21 return WebPermissions.Instance.ModuleAllowedWithLevel (moduleName, _permissionLevel); 22 22 } 23 23 -
binary-improvements/MapRendering/Web/Handlers/SessionHandler.cs
r325 r351 10 10 private readonly string staticPart; 11 11 12 public SessionHandler (string _staticPart, string _dataFolder, Web _parent, string moduleName = null) :13 base ( moduleName) {12 public SessionHandler (string _staticPart, string _dataFolder, Web _parent, string _moduleName = null) : 13 base (_moduleName) { 14 14 staticPart = _staticPart; 15 15 parent = _parent; … … 24 24 } 25 25 26 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,27 int permissionLevel) {28 string subpath = req.Url.AbsolutePath.Remove (0, staticPart.Length);26 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 27 int _permissionLevel) { 28 string subpath = _req.Url.AbsolutePath.Remove (0, staticPart.Length); 29 29 30 30 StringBuilder result = new StringBuilder (); … … 32 32 33 33 if (subpath.StartsWith ("verify")) { 34 if ( user != null) {35 resp.Redirect ("/static/index.html");34 if (_user != null) { 35 _resp.Redirect ("/static/index.html"); 36 36 return; 37 37 } … … 40 40 "<h1>Login failed, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 41 41 } else if (subpath.StartsWith ("logout")) { 42 if ( user != null) {43 parent.connectionHandler.LogOut ( user.SessionID);42 if (_user != null) { 43 parent.connectionHandler.LogOut (_user.SessionID); 44 44 Cookie cookie = new Cookie ("sid", "", "/"); 45 45 cookie.Expired = true; 46 resp.AppendCookie (cookie);47 resp.Redirect ("/static/index.html");46 _resp.AppendCookie (cookie); 47 _resp.Redirect ("/static/index.html"); 48 48 return; 49 49 } … … 52 52 "<h1>Not logged in, <a href=\"/static/index.html\">click to return to main page</a>.</h1>"); 53 53 } else if (subpath.StartsWith ("login")) { 54 string host = (Web.isSslRedirected ( req) ? "https://" : "http://") +req.UserHostName;54 string host = (Web.isSslRedirected (_req) ? "https://" : "http://") + _req.UserHostName; 55 55 string url = OpenID.GetOpenIdLoginUrl (host, host + "/session/verify"); 56 resp.Redirect (url);56 _resp.Redirect (url); 57 57 return; 58 58 } else { … … 63 63 result.Append (footer); 64 64 65 resp.ContentType = MimeType.GetMimeType (".html");66 resp.ContentEncoding = Encoding.UTF8;65 _resp.ContentType = MimeType.GetMimeType (".html"); 66 _resp.ContentEncoding = Encoding.UTF8; 67 67 byte[] buf = Encoding.UTF8.GetBytes (result.ToString ()); 68 resp.ContentLength64 = buf.Length;69 resp.OutputStream.Write (buf, 0, buf.Length);68 _resp.ContentLength64 = buf.Length; 69 _resp.OutputStream.Write (buf, 0, buf.Length); 70 70 } 71 71 } -
binary-improvements/MapRendering/Web/Handlers/SimpleRedirectHandler.cs
r325 r351 5 5 private readonly string target; 6 6 7 public SimpleRedirectHandler (string target, string moduleName = null) : base (moduleName) {8 t his.target =target;7 public SimpleRedirectHandler (string _target, string _moduleName = null) : base (_moduleName) { 8 target = _target; 9 9 } 10 10 11 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,12 int permissionLevel) {13 resp.Redirect (target);11 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 12 int _permissionLevel) { 13 _resp.Redirect (target); 14 14 } 15 15 } -
binary-improvements/MapRendering/Web/Handlers/StaticHandler.cs
r332 r351 10 10 private readonly string staticPart; 11 11 12 public StaticHandler (string staticPart, string filePath, AbstractCache cache, boollogMissingFiles,13 string moduleName = null) : base (moduleName) {14 this.staticPart =staticPart;15 datapath = filePath + (filePath [filePath.Length - 1] == '/' ? "" : "/");16 this.cache =cache;17 this.logMissingFiles =logMissingFiles;12 public StaticHandler (string _staticPart, string _filePath, AbstractCache _cache, bool _logMissingFiles, 13 string _moduleName = null) : base (_moduleName) { 14 staticPart = _staticPart; 15 datapath = _filePath + (_filePath [_filePath.Length - 1] == '/' ? "" : "/"); 16 cache = _cache; 17 logMissingFiles = _logMissingFiles; 18 18 } 19 19 20 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,21 int permissionLevel) {22 string fn = req.Url.AbsolutePath.Remove (0, staticPart.Length);20 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 21 int _permissionLevel) { 22 string fn = _req.Url.AbsolutePath.Remove (0, staticPart.Length); 23 23 24 24 byte[] content = cache.GetFileContent (datapath + fn); 25 25 26 26 if (content != null) { 27 resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn));28 resp.ContentLength64 = content.Length;29 resp.OutputStream.Write (content, 0, content.Length);27 _resp.ContentType = MimeType.GetMimeType (Path.GetExtension (fn)); 28 _resp.ContentLength64 = content.Length; 29 _resp.OutputStream.Write (content, 0, content.Length); 30 30 } else { 31 resp.StatusCode = (int) HttpStatusCode.NotFound;31 _resp.StatusCode = (int) HttpStatusCode.NotFound; 32 32 if (logMissingFiles) { 33 Log.Out ("Web:Static:FileNotFound: \"" + req.Url.AbsolutePath + "\" @ \"" + datapath + fn + "\"");33 Log.Out ("Web:Static:FileNotFound: \"" + _req.Url.AbsolutePath + "\" @ \"" + datapath + fn + "\""); 34 34 } 35 35 } -
binary-improvements/MapRendering/Web/Handlers/UserStatusHandler.cs
r332 r351 5 5 namespace AllocsFixes.NetConnections.Servers.Web.Handlers { 6 6 public class UserStatusHandler : PathHandler { 7 public UserStatusHandler (string moduleName = null) : base (moduleName) {7 public UserStatusHandler (string _moduleName = null) : base (_moduleName) { 8 8 } 9 9 10 public override void HandleRequest (HttpListenerRequest req, HttpListenerResponse resp, WebConnectionuser,11 int permissionLevel) {10 public override void HandleRequest (HttpListenerRequest _req, HttpListenerResponse _resp, WebConnection _user, 11 int _permissionLevel) { 12 12 JSONObject result = new JSONObject (); 13 13 14 result.Add ("loggedin", new JSONBoolean ( user != null));15 result.Add ("username", new JSONString ( user != null ?user.SteamID.ToString () : string.Empty));14 result.Add ("loggedin", new JSONBoolean (_user != null)); 15 result.Add ("username", new JSONString (_user != null ? _user.SteamID.ToString () : string.Empty)); 16 16 17 17 JSONArray perms = new JSONArray (); … … 19 19 JSONObject permObj = new JSONObject (); 20 20 permObj.Add ("module", new JSONString (perm.module)); 21 permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= permissionLevel));21 permObj.Add ("allowed", new JSONBoolean (perm.permissionLevel >= _permissionLevel)); 22 22 perms.Add (permObj); 23 23 } … … 25 25 result.Add ("permissions", perms); 26 26 27 WebAPI.WriteJSON ( resp, result);27 WebAPI.WriteJSON (_resp, result); 28 28 } 29 29 } -
binary-improvements/MapRendering/Web/MimeType.cs
r332 r351 568 568 }; 569 569 570 public static string GetMimeType (string extension) {571 if ( extension == null) {572 throw new ArgumentNullException (" extension");570 public static string GetMimeType (string _extension) { 571 if (_extension == null) { 572 throw new ArgumentNullException ("_extension"); 573 573 } 574 574 575 if (! extension.StartsWith (".")) {576 extension = "." +extension;575 if (!_extension.StartsWith (".")) { 576 _extension = "." + _extension; 577 577 } 578 578 579 579 string mime; 580 580 581 return _mappings.TryGetValue ( extension, out mime) ? mime : "application/octet-stream";581 return _mappings.TryGetValue (_extension, out mime) ? mime : "application/octet-stream"; 582 582 } 583 583 } -
binary-improvements/MapRendering/Web/OpenID.cs
r326 r351 25 25 "/steam-intermediate.cer"); 26 26 27 private static readonlybool verboseSsl = false;27 private const bool verboseSsl = false; 28 28 public static bool debugOpenId; 29 29 … … 35 35 } 36 36 37 ServicePointManager.ServerCertificateValidationCallback = ( srvPoint, certificate, chain,errors) => {38 if ( errors == SslPolicyErrors.None) {37 ServicePointManager.ServerCertificateValidationCallback = (_srvPoint, _certificate, _chain, _errors) => { 38 if (_errors == SslPolicyErrors.None) { 39 39 if (verboseSsl) { 40 40 Log.Out ("Steam certificate: No error (1)"); … … 50 50 privateChain.ChainPolicy.ExtraStore.Add (caIntermediateCert); 51 51 52 if (privateChain.Build (new X509Certificate2 ( certificate))) {52 if (privateChain.Build (new X509Certificate2 (_certificate))) { 53 53 // No errors, immediately return 54 54 privateChain.Reset (); -
binary-improvements/MapRendering/Web/Web.cs
r332 r351 27 27 public Web () { 28 28 try { 29 int webPort = GamePrefs.GetInt (Enum GamePrefs.ControlPanelPort);29 int webPort = GamePrefs.GetInt (EnumUtils.Parse<EnumGamePrefs> ("ControlPanelPort")); 30 30 if (webPort < 1 || webPort > 65533) { 31 31 Log.Out ("Webserver not started (ControlPanelPort not within 1-65533)"); … … 132 132 } 133 133 134 public void SendLine (string line) {135 connectionHandler.SendLine ( line);136 } 137 138 public void SendLog (string text, string trace, LogTypetype) {134 public void SendLine (string _line) { 135 connectionHandler.SendLine (_line); 136 } 137 138 public void SendLog (string _text, string _trace, LogType _type) { 139 139 // Do nothing, handled by LogBuffer internally 140 140 } 141 141 142 public static bool isSslRedirected (HttpListenerRequest req) {143 string proto = req.Headers ["X-Forwarded-Proto"];142 public static bool isSslRedirected (HttpListenerRequest _req) { 143 string proto = _req.Headers ["X-Forwarded-Proto"]; 144 144 if (!string.IsNullOrEmpty (proto)) { 145 145 return proto.Equals ("https", StringComparison.OrdinalIgnoreCase); … … 156 156 #endif 157 157 158 private void HandleRequest (IAsyncResult result) {158 private void HandleRequest (IAsyncResult _result) { 159 159 if (!_listener.IsListening) { 160 160 return; … … 167 167 #if ENABLE_PROFILER 168 168 Profiler.BeginThreadProfiling ("AllocsMods", "WebRequest"); 169 HttpListenerContext ctx = _listener.EndGetContext ( result);169 HttpListenerContext ctx = _listener.EndGetContext (_result); 170 170 try { 171 171 #else … … 314 314 } 315 315 316 public static void SetResponseTextContent (HttpListenerResponse resp, stringtext) {317 byte[] buf = Encoding.UTF8.GetBytes ( text);318 resp.ContentLength64 = buf.Length;319 resp.ContentType = "text/html";320 resp.ContentEncoding = Encoding.UTF8;321 resp.OutputStream.Write (buf, 0, buf.Length);316 public static void SetResponseTextContent (HttpListenerResponse _resp, string _text) { 317 byte[] buf = Encoding.UTF8.GetBytes (_text); 318 _resp.ContentLength64 = buf.Length; 319 _resp.ContentType = "text/html"; 320 _resp.ContentEncoding = Encoding.UTF8; 321 _resp.OutputStream.Write (buf, 0, buf.Length); 322 322 } 323 323 } -
binary-improvements/MapRendering/Web/WebPermissions.cs
r332 r351 3 3 using System.IO; 4 4 using System.Xml; 5 using UniLinq;6 5 7 6 namespace AllocsFixes.NetConnections.Servers.Web { … … 171 170 } 172 171 173 private void OnFileChanged (object source, FileSystemEventArgse) {172 private void OnFileChanged (object _source, FileSystemEventArgs _e) { 174 173 Log.Out ("Reloading " + PERMISSIONS_FILE); 175 174 Load (); … … 177 176 178 177 private string GetFilePath () { 179 return GamePrefs.GetString (Enum GamePrefs.SaveGameFolder);178 return GamePrefs.GetString (EnumUtils.Parse<EnumGamePrefs> ("SaveGameFolder")); 180 179 } 181 180
Note:
See TracChangeset
for help on using the changeset viewer.