Skip to content

Commit 2b9d073

Browse files
committed
Code Review
1 parent c245db4 commit 2b9d073

File tree

7 files changed

+54
-62
lines changed

7 files changed

+54
-62
lines changed

Unosquare.Labs.EmbedIO/Log/SimpleConsoleLog.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ private static void WriteLine(ConsoleColor color, string format, params object[]
2323

2424
format = dateTimeString + "\t" + format;
2525

26-
ThreadPool.QueueUserWorkItem((context) =>
26+
ThreadPool.QueueUserWorkItem(context =>
2727
{
2828
var current = Console.ForegroundColor;
2929
Console.ForegroundColor = color;

Unosquare.Labs.EmbedIO/Modules/CorsModule.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ public CorsModule(string origins = Constants.CorsWildcard, string headers = Cons
3131
if (methods == null) throw new ArgumentException(Constants.ArgumentNullExceptionMessage, nameof(methods));
3232

3333
var validOrigins = origins.ToLower().Split(Constants.CommaSplitChar, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
34-
var validHeaders = headers.ToLower().Split(Constants.CommaSplitChar, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
3534
var validMethods = methods.ToLower().Split(Constants.CommaSplitChar, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim());
3635

3736
AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (server, context) =>
@@ -47,7 +46,7 @@ public CorsModule(string origins = Constants.CorsWildcard, string headers = Cons
4746
var currentHeader = context.RequestHeader(Constants.HeaderAccessControlRequestHeaders);
4847
var currentMethod = context.RequestHeader(Constants.HeaderAccessControlRequestMethod);
4948

50-
if (String.IsNullOrWhiteSpace(currentOrigin) && context.Request.IsLocal) return false;
49+
if (string.IsNullOrWhiteSpace(currentOrigin) && context.Request.IsLocal) return false;
5150

5251
if (origins != Constants.CorsWildcard)
5352
{

Unosquare.Labs.EmbedIO/Modules/LocalSessionModule.cs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ private void FixupSessionCookie(HttpListenerContext context)
6161
if (nameValue.Length == 2 && nameValue[0].Equals(SessionCookieName))
6262
{
6363
var sessionIdValue = nameValue[1].Trim();
64+
6465
if (this.Sessions.ContainsKey(sessionIdValue))
6566
{
6667
context.Request.Cookies[SessionCookieName].Value = sessionIdValue;
@@ -94,7 +95,7 @@ public LocalSessionModule()
9495

9596
if (requestCookie == null)
9697
{
97-
// create the session if sesison not available on the request
98+
// create the session if session not available on the request
9899
var sessionCookie = CreateSession();
99100
context.Response.SetCookie(sessionCookie);
100101
context.Request.Cookies.Add(sessionCookie);
@@ -108,15 +109,15 @@ public LocalSessionModule()
108109
context.Request.Cookies[SessionCookieName].Value = sessionCookie.Value;
109110
server.Log.DebugFormat("Updated session identifier to '{0}'", sessionCookie.Value);
110111
}
111-
else if (this.Sessions.ContainsKey(context.Request.Cookies[SessionCookieName].Value) == true)
112+
else if (this.Sessions.ContainsKey(context.Request.Cookies[SessionCookieName].Value))
112113
{
113114
// If it does exist in the request, check if we're tracking it
114115
var requestSessionId = context.Request.Cookies[SessionCookieName].Value;
115116
this.Sessions[requestSessionId].LastActivity = DateTime.Now;
116117
server.Log.DebugFormat("Session Identified '{0}'", requestSessionId);
117118
}
118119

119-
// Always returns false because we need it to handle the rest fo the modules
120+
// Always returns false because we need it to handle the rest for the modules
120121
return false;
121122
});
122123

@@ -128,10 +129,7 @@ public LocalSessionModule()
128129
/// <value>
129130
/// The sessions.
130131
/// </value>
131-
public ConcurrentDictionary<string, SessionInfo> Sessions
132-
{
133-
get { return this.m_Sessions; }
134-
}
132+
public ConcurrentDictionary<string, SessionInfo> Sessions => this.m_Sessions;
135133

136134
/// <summary>
137135
/// Gets a session object for the given server context.
@@ -177,9 +175,6 @@ public SessionInfo GetSession(WebSocketContext context)
177175
/// <value>
178176
/// The name.
179177
/// </value>
180-
public override string Name
181-
{
182-
get { return "Local Session Module"; }
183-
}
178+
public override string Name => "Local Session Module";
184179
}
185180
}

Unosquare.Labs.EmbedIO/Modules/StaticFilesModule.cs

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,10 @@
1414
/// </summary>
1515
public class StaticFilesModule : WebModuleBase
1616
{
17-
private const int chuckSize = 256*1024;
17+
/// <summary>
18+
/// The chuck size for sending files
19+
/// </summary>
20+
private const int ChuckSize = 256*1024;
1821

1922
private readonly Dictionary<string, string> m_VirtualPaths =
2023
new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
@@ -91,8 +94,7 @@ public class StaticFilesModule : WebModuleBase
9194
/// <value>
9295
/// The virtual paths.
9396
/// </value>
94-
public ReadOnlyDictionary<string, string> VirtualPaths => new ReadOnlyDictionary<string, string>(m_VirtualPaths)
95-
;
97+
public ReadOnlyDictionary<string, string> VirtualPaths => new ReadOnlyDictionary<string, string>(m_VirtualPaths);
9698

9799
/// <summary>
98100
/// Gets the name of this module.
@@ -116,7 +118,7 @@ public void ClearRamCache()
116118
/// <value>
117119
/// The ram cache.
118120
/// </value>
119-
private ConcurrentDictionary<string, RamCacheEntry> RamCache { get; set; }
121+
private ConcurrentDictionary<string, RamCacheEntry> RamCache { get; }
120122

121123
/// <summary>
122124
/// Represents a RAM Cache dictionary entry
@@ -259,7 +261,7 @@ private bool HandleGet(HttpListenerContext context, WebServer server, bool sendB
259261

260262
var lowerByteIndex = 0;
261263
var upperByteIndex = 0;
262-
var byteLength = (long) 0;
264+
long byteLength;
263265
var isPartial = usingPartial &&
264266
CalculateRange(partialHeader, fileSize, out lowerByteIndex, out upperByteIndex);
265267

@@ -320,13 +322,13 @@ private bool HandleGet(HttpListenerContext context, WebServer server, bool sendB
320322
private static void WriteToOutputStream(HttpListenerContext context, long byteLength, Stream buffer,
321323
int lowerByteIndex)
322324
{
323-
var streamBuffer = new byte[chuckSize];
325+
var streamBuffer = new byte[ChuckSize];
324326
var sendData = 0;
325-
var readBufferSize = chuckSize;
327+
var readBufferSize = ChuckSize;
326328

327329
while (true)
328330
{
329-
if (sendData + chuckSize > byteLength) readBufferSize = (int) (byteLength - sendData);
331+
if (sendData + ChuckSize > byteLength) readBufferSize = (int) (byteLength - sendData);
330332

331333
buffer.Seek(lowerByteIndex + sendData, SeekOrigin.Begin);
332334
var read = buffer.Read(streamBuffer, 0, readBufferSize);
@@ -432,12 +434,7 @@ private bool ExistsLocalPath(string urlPath, ref string localPath)
432434
if (string.IsNullOrWhiteSpace(DefaultExtension) == false && DefaultExtension.StartsWith(".") &&
433435
File.Exists(localPath) == false)
434436
{
435-
var newPath = localPath + DefaultExtension;
436-
437-
if (File.Exists(newPath))
438-
{
439-
localPath = newPath;
440-
}
437+
localPath += DefaultExtension;
441438
}
442439

443440
if (File.Exists(localPath)) return true;

Unosquare.Labs.EmbedIO/Modules/WebApiModule.cs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -231,17 +231,17 @@ private string NormalizeWildcardPath(HttpVerbs verb, HttpListenerContext context
231231
if (_delegateMap.ContainsKey(path) == false)
232232
return null;
233233

234-
if (_delegateMap[path].ContainsKey(verb) == false) // TODO: Fix Any Verb
234+
if (_delegateMap[path].ContainsKey(verb)) return path;
235+
236+
var originalPath = context.RequestPath();
237+
238+
if (_delegateMap.ContainsKey(originalPath) &&
239+
_delegateMap[originalPath].ContainsKey(verb))
235240
{
236-
var originalPath = context.RequestPath();
237-
if (_delegateMap.ContainsKey(originalPath) &&
238-
_delegateMap[originalPath].ContainsKey(verb))
239-
{
240-
path = originalPath;
241-
}
242-
else
243-
return null;
241+
path = originalPath;
244242
}
243+
else
244+
return null;
245245

246246
return path;
247247
}
@@ -328,14 +328,13 @@ public void RegisterController(Type controllerType, Func<object> controllerFacto
328328

329329
foreach (var path in attribute.Paths)
330330
{
331-
var delegatePath = new Dictionary<HttpVerbs, Tuple<Func<object>, MethodInfo>>();
332-
333-
if (_delegateMap.ContainsKey(path))
334-
delegatePath = _delegateMap[path]; // update
335-
else
336-
_delegateMap.Add(path, delegatePath); // add
331+
if (_delegateMap.ContainsKey(path) == false)
332+
{
333+
_delegateMap.Add(path, new Dictionary<HttpVerbs, Tuple<Func<object>, MethodInfo>>()); // add
334+
}
337335

338336
var delegatePair = new Tuple<Func<object>, MethodInfo>(controllerFactory, method);
337+
339338
if (_delegateMap[path].ContainsKey(attribute.Verb))
340339
_delegateMap[path][attribute.Verb] = delegatePair; // update
341340
else
@@ -410,7 +409,7 @@ public abstract class WebApiController
410409
/// <summary>
411410
/// Initializes a new instance of the <see cref="WebApiController"/> class.
412411
/// </summary>
413-
public WebApiController()
412+
protected WebApiController()
414413
{
415414
// placeholder
416415
}

Unosquare.Labs.EmbedIO/Modules/WebSocketsModule.cs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,9 @@ public class WebSocketsModule : WebModuleBase
2626
/// Initialize WebSocket module
2727
/// </summary>
2828
public WebSocketsModule()
29-
: base()
3029
{
3130
this.AddHandler(ModuleMap.AnyPath, HttpVerbs.Any, (server, context) =>
3231
{
33-
3432
// check if it is a WebSocket request (this only works with Win8 and Windows 2012)
3533
if (context.Request.IsWebSocketRequest == false)
3634
return false;
@@ -63,7 +61,7 @@ public WebSocketsModule()
6361
public void RegisterWebSocketsServer<T>()
6462
where T : WebSocketsServer, new()
6563
{
66-
RegisterWebSocketsServer(typeof(T));
64+
RegisterWebSocketsServer(typeof (T));
6765
}
6866

6967
/// <summary>
@@ -77,13 +75,14 @@ public void RegisterWebSocketsServer(Type socketType)
7775
throw new ArgumentException("Argument 'socketType' cannot be null", nameof(socketType));
7876

7977
var attribute =
80-
socketType.GetCustomAttributes(typeof(WebSocketHandlerAttribute), true).FirstOrDefault() as
78+
socketType.GetCustomAttributes(typeof (WebSocketHandlerAttribute), true).FirstOrDefault() as
8179
WebSocketHandlerAttribute;
8280

8381
if (attribute == null)
84-
throw new ArgumentException("Argument 'socketType' needs a WebSocketHandlerAttribute", nameof(socketType));
82+
throw new ArgumentException("Argument 'socketType' needs a WebSocketHandlerAttribute",
83+
nameof(socketType));
8584

86-
this._serverMap[attribute.Path] = (WebSocketsServer)Activator.CreateInstance(socketType);
85+
this._serverMap[attribute.Path] = (WebSocketsServer) Activator.CreateInstance(socketType);
8786
}
8887

8988
/// <summary>
@@ -124,7 +123,7 @@ public void RegisterWebSocketsServer<T>(string path, T server)
124123
/// Decorate methods within controllers with this attribute in order to make them callable from the Web API Module
125124
/// Method Must match the WebServerModule.
126125
/// </summary>
127-
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
126+
[AttributeUsage(AttributeTargets.Class)]
128127
public sealed class WebSocketHandlerAttribute : Attribute
129128
{
130129
/// <summary>
@@ -146,7 +145,7 @@ public WebSocketHandlerAttribute(string path)
146145
/// <value>
147146
/// The paths.
148147
/// </value>
149-
public string Path { get; private set; }
148+
public string Path { get; }
150149
}
151150

152151
/// <summary>
@@ -193,7 +192,7 @@ protected WebSocketsServer(bool enableConnectionWatchdog, int maxMessageSize)
193192
{
194193
this._enableDisconnectedSocketColletion = enableConnectionWatchdog;
195194
this._maximumMessageSize = maxMessageSize;
196-
195+
197196
RunConnectionWatchdog();
198197
}
199198

@@ -268,7 +267,7 @@ public void AcceptWebSocket(WebServer server, HttpListenerContext context)
268267
// define a receive buffer
269268
var receiveBuffer = new byte[receiveBufferSize];
270269
// define a dynamic buffer that holds multi-part receptions
271-
var receivedMessage = new List<byte>(receiveBuffer.Length * 2);
270+
var receivedMessage = new List<byte>(receiveBuffer.Length*2);
272271

273272
// poll the WebSockets connections for reception
274273
while (webSocketContext.WebSocket.State == WebSocketState.Open)

Unosquare.Labs.EmbedIO/WebServer.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,8 @@ public WebServer(string[] urlPrefixes, ILog log, RoutingStrategy routingStrategy
181181
foreach (var prefix in urlPrefixes)
182182
{
183183
var urlPrefix = prefix.Clone() as string;
184+
if (urlPrefix == null) continue;
185+
184186
if (urlPrefix.EndsWith("/") == false) urlPrefix = urlPrefix + "/";
185187
urlPrefix = urlPrefix.ToLowerInvariant();
186188

@@ -190,7 +192,7 @@ public WebServer(string[] urlPrefixes, ILog log, RoutingStrategy routingStrategy
190192

191193
this.Log.Info("Finished Loading Web Server.");
192194
}
193-
195+
194196
/// <summary>
195197
/// Gets the module registered for the given type.
196198
/// Returns null if no module matches the given type.
@@ -228,8 +230,10 @@ public void RegisterModule(IWebModule module)
228230
module.Server = this;
229231
this._modules.Add(module);
230232

231-
if (module is ISessionWebModule)
232-
this.SessionModule = module as ISessionWebModule;
233+
var webModule = module as ISessionWebModule;
234+
235+
if (webModule != null)
236+
this.SessionModule = webModule;
233237
}
234238
else
235239
{
@@ -412,9 +416,8 @@ public bool ProcessRequest(HttpListenerContext context)
412416
clientSocketTask.Wait(ct);
413417
var clientSocket = clientSocketTask.Result;
414418

415-
var clientTask =
416-
Task.Factory.StartNew((context) => HandleClientRequest(context as HttpListenerContext, app),
417-
clientSocket, ct);
419+
Task.Factory.StartNew(context => HandleClientRequest(context as HttpListenerContext, app),
420+
clientSocket, ct);
418421
}
419422
catch (OperationCanceledException)
420423
{
@@ -441,14 +444,14 @@ public void Run()
441444

442445
this.Log.Info("Started HTTP Listener");
443446

444-
ThreadPool.QueueUserWorkItem((o) =>
447+
ThreadPool.QueueUserWorkItem(o =>
445448
{
446449
while (this.Listener != null && this.Listener.IsListening)
447450
{
448451
try
449452
{
450453
// Asynchronously queue a response by using a thread from the thread pool
451-
ThreadPool.QueueUserWorkItem((contextState) =>
454+
ThreadPool.QueueUserWorkItem(contextState =>
452455
{
453456
// get a reference to the HTTP Listener Context
454457
var context = contextState as HttpListenerContext;

0 commit comments

Comments
 (0)