From 5bafbc7aeae05847dbdc2bc173f62039310c80f9 Mon Sep 17 00:00:00 2001 From: Damir Ainullin Date: Sat, 24 Feb 2018 23:07:30 +0300 Subject: [PATCH] Use TryGetValue instead of ContainsKey and Getter for Dictionary to prevent double calculation of HashCode --- .../FormsAuthentication.cs | 5 ++--- src/Nancy.Hosting.Aspnet/NancyHandler.cs | 8 ++++---- src/Nancy.Hosting.Self/NancyHost.cs | 12 ++++++------ src/Nancy.Metadata.Modules/MetadataModule.cs | 5 +++-- src/Nancy.Owin/AppBuilderExtensions.cs | 5 +++-- src/Nancy.Testing/ConfigurableBootstrapper.cs | 3 ++- src/Nancy.Testing/NancyContextExtensions.cs | 7 ++++--- .../TestingViewBrowserResponseExtensions.cs | 5 +++-- .../CSharp/CSharpClrTypeResolver.cs | 7 +++---- src/Nancy/Diagnostics/DiagnosticsHook.cs | 4 ++-- .../Extensions/ModelValidationErrorExtensions.cs | 10 ++++++---- src/Nancy/Helpers/HttpEncoder.cs | 5 +++-- src/Nancy/Json/Simple/SimpleJson.cs | 3 ++- src/Nancy/Json/SimpleJson.cs | 3 ++- src/Nancy/ModelBinding/DefaultBinder.cs | 10 ++++++---- src/Nancy/Owin/NancyMiddleware.cs | 5 +++-- src/Nancy/RequestHeaders.cs | 6 +++--- src/Nancy/Response.cs | 7 +++++-- .../Negotiation/DefaultResponseNegotiator.cs | 6 +++--- .../Responses/Negotiation/MediaRangeParameters.cs | 5 +++-- src/Nancy/Routing/DefaultRouteCacheProvider.cs | 10 ++++++---- src/Nancy/Routing/RouteCache.cs | 10 ++++++---- src/Nancy/Routing/RouteMetadata.cs | 11 +++++------ src/Nancy/Security/Csrf.cs | 10 +++++----- src/Nancy/Session/CookieBasedSessions.cs | 8 ++++---- src/Nancy/Session/Session.cs | 8 ++++++-- src/Nancy/TinyIoc/TinyIoC.cs | 5 +++-- src/Nancy/Validation/ModelValidationDescriptor.cs | 10 ++++++---- src/Nancy/Validation/ModelValidationResult.cs | 15 +++++++++------ .../SuperSimpleViewEngine.cs | 4 ++-- 30 files changed, 120 insertions(+), 92 deletions(-) diff --git a/src/Nancy.Authentication.Forms/FormsAuthentication.cs b/src/Nancy.Authentication.Forms/FormsAuthentication.cs index 9347eda36e..536241f50d 100644 --- a/src/Nancy.Authentication.Forms/FormsAuthentication.cs +++ b/src/Nancy.Authentication.Forms/FormsAuthentication.cs @@ -243,13 +243,12 @@ private static Action GetRedirectToLoginHook(FormsAuthenticationCo /// Returns user guid, or Guid.Empty if not present or invalid private static Guid GetAuthenticatedUserFromCookie(NancyContext context, FormsAuthenticationConfiguration configuration) { - if (!context.Request.Cookies.ContainsKey(formsAuthenticationCookieName)) + string cookieValueEncrypted; + if (!context.Request.Cookies.TryGetValue(formsAuthenticationCookieName, out cookieValueEncrypted)) { return Guid.Empty; } - var cookieValueEncrypted = context.Request.Cookies[formsAuthenticationCookieName]; - if (string.IsNullOrEmpty(cookieValueEncrypted)) { return Guid.Empty; diff --git a/src/Nancy.Hosting.Aspnet/NancyHandler.cs b/src/Nancy.Hosting.Aspnet/NancyHandler.cs index cc0c7e4615..70d9375ba2 100644 --- a/src/Nancy.Hosting.Aspnet/NancyHandler.cs +++ b/src/Nancy.Hosting.Aspnet/NancyHandler.cs @@ -97,13 +97,13 @@ private static long GetExpectedRequestLength(IDictionary values; + if (!incomingHeaders.TryGetValue("Content-Length", out values)) { return 0; } - var headerValue = - incomingHeaders["Content-Length"].SingleOrDefault(); + var headerValue = values.SingleOrDefault(); if (headerValue == null) { @@ -180,4 +180,4 @@ private static void SetHttpResponseHeaders(HttpContextBase context, Response res } } } -} \ No newline at end of file +} diff --git a/src/Nancy.Hosting.Self/NancyHost.cs b/src/Nancy.Hosting.Self/NancyHost.cs index e85545367a..abbccece7b 100644 --- a/src/Nancy.Hosting.Self/NancyHost.cs +++ b/src/Nancy.Hosting.Self/NancyHost.cs @@ -11,7 +11,6 @@ using System.Threading.Tasks; using Nancy.Bootstrapper; using Nancy.Extensions; - using Nancy.Helpers; using Nancy.IO; using System.Threading; @@ -371,8 +370,9 @@ private static void OutputWithContentLength(Response nancyResponse, HttpListener buffer = memoryStream.ToArray(); } - var contentLength = (nancyResponse.Headers.ContainsKey("Content-Length")) ? - Convert.ToInt64(nancyResponse.Headers["Content-Length"]) : + string value; + var contentLength = nancyResponse.Headers.TryGetValue("Content-Length", out value) ? + Convert.ToInt64(value) : buffer.Length; response.SendChunked = false; @@ -395,13 +395,13 @@ private static long GetExpectedRequestLength(IDictionary values; + if (!incomingHeaders.TryGetValue("Content-Length", out values)) { return 0; } - var headerValue = - incomingHeaders["Content-Length"].SingleOrDefault(); + var headerValue = values.SingleOrDefault(); if (headerValue == null) { diff --git a/src/Nancy.Metadata.Modules/MetadataModule.cs b/src/Nancy.Metadata.Modules/MetadataModule.cs index 77911c58eb..ee04fda612 100644 --- a/src/Nancy.Metadata.Modules/MetadataModule.cs +++ b/src/Nancy.Metadata.Modules/MetadataModule.cs @@ -44,9 +44,10 @@ public Type MetadataType /// An instance of if one exists, otherwise null. public object GetMetadata(RouteDescription description) { - if (this.metadata.ContainsKey(description.Name)) + Func func; + if (this.metadata.TryGetValue(description.Name, out func)) { - return this.metadata[description.Name].Invoke(description); + return func.Invoke(description); } return null; diff --git a/src/Nancy.Owin/AppBuilderExtensions.cs b/src/Nancy.Owin/AppBuilderExtensions.cs index 38dfc51d75..eab03a3636 100644 --- a/src/Nancy.Owin/AppBuilderExtensions.cs +++ b/src/Nancy.Owin/AppBuilderExtensions.cs @@ -44,12 +44,13 @@ public static IAppBuilder UseNancy(this IAppBuilder builder, Action GetAllModules(NancyContext context) /// The instance public INancyModule GetModule(Type moduleType, NancyContext context) { - return this.moduleInstances.ContainsKey(moduleType.FullName) ? this.moduleInstances[moduleType.FullName] : null; + INancyModule module; + return this.moduleInstances.TryGetValue(moduleType.FullName, out module) ? module : null; } /// diff --git a/src/Nancy.Testing/NancyContextExtensions.cs b/src/Nancy.Testing/NancyContextExtensions.cs index a0007730b1..86863754d0 100644 --- a/src/Nancy.Testing/NancyContextExtensions.cs +++ b/src/Nancy.Testing/NancyContextExtensions.cs @@ -20,9 +20,10 @@ private static T Cache(NancyContext context, string key, Func getData) // We only really want to generate this once, so we'll stick it in the context // This isn't ideal, but we don't want to hide the guts of the context from the // tests this will have to do. - if (context.Items.ContainsKey(key)) + object value; + if (context.Items.TryGetValue(key, out value)) { - return (T)context.Items[key]; + return (T)value; } T data = getData.Invoke(); @@ -85,4 +86,4 @@ public static TModel XmlBody(this NancyContext context) }); } } -} \ No newline at end of file +} diff --git a/src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs b/src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs index 98052a0b50..3a9b30348a 100644 --- a/src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs +++ b/src/Nancy.Testing/TestingViewBrowserResponseExtensions.cs @@ -53,12 +53,13 @@ public static string GetModulePath(this BrowserResponse response) private static string GetContextValue(BrowserResponse response, string key) { - if (!response.Context.Items.ContainsKey(key)) + object val; + if (!response.Context.Items.TryGetValue(key, out val)) { return string.Empty; } - var value = (string)response.Context.Items[key]; + var value = (string)val; return string.IsNullOrEmpty(value) ? string.Empty : value; } } diff --git a/src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs b/src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs index 856bddd35d..088996e767 100644 --- a/src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs +++ b/src/Nancy.ViewEngines.Razor/CSharp/CSharpClrTypeResolver.cs @@ -2,7 +2,6 @@ namespace Nancy.ViewEngines.Razor.CSharp { using System; using System.Collections.Generic; - using System.Linq; using System.Web.Razor.Tokenizer.Symbols; /// @@ -83,8 +82,8 @@ protected override Type ResolvePrimitiveType(string typeName) {"bool", typeof (bool)}, {"object", typeof (object)}, }; - - return (primitives.ContainsKey(typeName) ? primitives[typeName] : null); + Type type; + return primitives.TryGetValue(typeName, out type) ? type : null; } } -} \ No newline at end of file +} diff --git a/src/Nancy/Diagnostics/DiagnosticsHook.cs b/src/Nancy/Diagnostics/DiagnosticsHook.cs index 63ca52c4f0..d5eae40dde 100644 --- a/src/Nancy/Diagnostics/DiagnosticsHook.cs +++ b/src/Nancy/Diagnostics/DiagnosticsHook.cs @@ -228,12 +228,12 @@ private static DiagnosticsSession GetSession(NancyContext context, DiagnosticsCo return ProcessLogin(context, diagnosticsConfiguration, serializer); } - if (!context.Request.Cookies.ContainsKey(diagnosticsConfiguration.CookieName)) + string encryptedValue; + if (!context.Request.Cookies.TryGetValue(diagnosticsConfiguration.CookieName, out encryptedValue)) { return null; } - var encryptedValue = context.Request.Cookies[diagnosticsConfiguration.CookieName]; var hmacStringLength = Base64Helpers.GetBase64Length(diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.HmacLength); var encryptedSession = encryptedValue.Substring(hmacStringLength); var hmacString = encryptedValue.Substring(0, hmacStringLength); diff --git a/src/Nancy/Extensions/ModelValidationErrorExtensions.cs b/src/Nancy/Extensions/ModelValidationErrorExtensions.cs index c021d202b9..07ee5fa73d 100644 --- a/src/Nancy/Extensions/ModelValidationErrorExtensions.cs +++ b/src/Nancy/Extensions/ModelValidationErrorExtensions.cs @@ -18,14 +18,16 @@ public static class ModelValidationResultExtensions /// A reference to the property. public static IDictionary> Add(this IDictionary> errors, string name, string errorMessage) { - if (!errors.ContainsKey(name)) + IList value; + if (!errors.TryGetValue(name, out value)) { - errors[name] = new List(); + value = new List(); + errors[name] = value; } - errors[name].Add(new ModelValidationError(name, errorMessage)); + value.Add(new ModelValidationError(name, errorMessage)); return errors; } } -} \ No newline at end of file +} diff --git a/src/Nancy/Helpers/HttpEncoder.cs b/src/Nancy/Helpers/HttpEncoder.cs index af966df152..6bfa8a2c86 100644 --- a/src/Nancy/Helpers/HttpEncoder.cs +++ b/src/Nancy/Helpers/HttpEncoder.cs @@ -479,8 +479,9 @@ internal static string HtmlDecode(string s) if (c == ';') { string key = entity.ToString(); - if (key.Length > 1 && Entities.ContainsKey(key.Substring(1, key.Length - 2))) - key = Entities[key.Substring(1, key.Length - 2)].ToString(); + char value; + if (key.Length > 1 && Entities.TryGetValue(key.Substring(1, key.Length - 2), out value)) + key = value.ToString(); output.Append(key); state = 0; diff --git a/src/Nancy/Json/Simple/SimpleJson.cs b/src/Nancy/Json/Simple/SimpleJson.cs index 6589c6c64e..40a967d0d3 100644 --- a/src/Nancy/Json/Simple/SimpleJson.cs +++ b/src/Nancy/Json/Simple/SimpleJson.cs @@ -259,7 +259,8 @@ public void Clear() /// public bool Contains(KeyValuePair item) { - return this._members.ContainsKey(item.Key) && this._members[item.Key] == item.Value; + object value; + return this._members.TryGetValue(item.Key, out value) && value == item.Value; } /// diff --git a/src/Nancy/Json/SimpleJson.cs b/src/Nancy/Json/SimpleJson.cs index eb1f255a65..db08010ac7 100644 --- a/src/Nancy/Json/SimpleJson.cs +++ b/src/Nancy/Json/SimpleJson.cs @@ -264,7 +264,8 @@ public void Clear() /// public bool Contains(KeyValuePair item) { - return _members.ContainsKey(item.Key) && _members[item.Key] == item.Value; + object value; + return _members.TryGetValue(item.Key, out value) && value == item.Value; } /// diff --git a/src/Nancy/ModelBinding/DefaultBinder.cs b/src/Nancy/ModelBinding/DefaultBinder.cs index 4515d35a1b..25fa8d1b97 100644 --- a/src/Nancy/ModelBinding/DefaultBinder.cs +++ b/src/Nancy/ModelBinding/DefaultBinder.cs @@ -475,14 +475,14 @@ private static string GetValue(string propertyName, BindingContext context, int .Distinct() .Select((k, i) => new KeyValuePair(i, k)) .ToDictionary(k => k.Key, v => v.Value); - - if (indexindexes.ContainsKey(index)) + int indexValue; + if (indexindexes.TryGetValue(index, out indexValue)) { var propertyValue = context.RequestData.Where(c => { var indexId = IsMatch(c.Key); - return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexindexes[index]; + return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexValue; }) .Select(k => k.Value) .FirstOrDefault(); @@ -492,7 +492,9 @@ private static string GetValue(string propertyName, BindingContext context, int return string.Empty; } - return context.RequestData.ContainsKey(propertyName) ? context.RequestData[propertyName] : string.Empty; + + string value; + return context.RequestData.TryGetValue(propertyName, out value) ? value : string.Empty; } private object DeserializeRequestBody(BindingContext context) diff --git a/src/Nancy/Owin/NancyMiddleware.cs b/src/Nancy/Owin/NancyMiddleware.cs index d4ff381fce..5076a4a81e 100644 --- a/src/Nancy/Owin/NancyMiddleware.cs +++ b/src/Nancy/Owin/NancyMiddleware.cs @@ -143,8 +143,9 @@ private static Task RequestComplete( if (nancyResponse.Cookies != null && nancyResponse.Cookies.Count != 0) { const string setCookieHeaderKey = "Set-Cookie"; - string[] setCookieHeader = owinResponseHeaders.ContainsKey(setCookieHeaderKey) - ? owinResponseHeaders[setCookieHeaderKey] + string[] cookieHeader; + string[] setCookieHeader = owinResponseHeaders.TryGetValue(setCookieHeaderKey, out cookieHeader) + ? cookieHeader : ArrayCache.Empty(); owinResponseHeaders[setCookieHeaderKey] = setCookieHeader .Concat(nancyResponse.Cookies.Select(cookie => cookie.ToString())) diff --git a/src/Nancy/RequestHeaders.cs b/src/Nancy/RequestHeaders.cs index c05e474c5b..53ce771211 100644 --- a/src/Nancy/RequestHeaders.cs +++ b/src/Nancy/RequestHeaders.cs @@ -6,7 +6,6 @@ namespace Nancy using System.Collections.Generic; using System.Globalization; using System.Linq; - using System.Reflection; using Nancy.Cookies; using Nancy.Responses.Negotiation; @@ -274,8 +273,9 @@ public IEnumerable this[string name] { get { - return (this.headers.ContainsKey(name)) ? - this.headers[name] : + IEnumerable value; + return this.headers.TryGetValue(name, out value) ? + value : Enumerable.Empty(); } } diff --git a/src/Nancy/Response.cs b/src/Nancy/Response.cs index c29da68a3c..6d6fe28e99 100644 --- a/src/Nancy/Response.cs +++ b/src/Nancy/Response.cs @@ -5,7 +5,6 @@ namespace Nancy using System.Diagnostics; using System.IO; using System.Linq; - using System.Runtime.CompilerServices; using System.Threading.Tasks; using Nancy.Cookies; using Nancy.Helpers; @@ -43,7 +42,11 @@ public Response() /// The default value is text/html. public string ContentType { - get { return Headers.ContainsKey("content-type") ? Headers["content-type"] : this.contentType; } + get + { + string value; + return Headers.TryGetValue("content-type", out value) ? value : this.contentType; + } set { this.contentType = value; } } diff --git a/src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs b/src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs index cb217662d6..5e26b64f0c 100644 --- a/src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs +++ b/src/Nancy/Responses/Negotiation/DefaultResponseNegotiator.cs @@ -1,7 +1,6 @@ namespace Nancy.Responses.Negotiation { using System; - using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Linq; @@ -390,9 +389,10 @@ protected virtual string CreateLinkHeader(Url requestUrl, IEnumerableThe response. private static void AddContentTypeHeader(NegotiationContext negotiationContext, Response response) { - if (negotiationContext.Headers.ContainsKey("Content-Type")) + string contentType; + if (negotiationContext.Headers.TryGetValue("Content-Type", out contentType)) { - response.ContentType = negotiationContext.Headers["Content-Type"]; + response.ContentType = contentType; negotiationContext.Headers.Remove("Content-Type"); } } diff --git a/src/Nancy/Responses/Negotiation/MediaRangeParameters.cs b/src/Nancy/Responses/Negotiation/MediaRangeParameters.cs index 2bbcf53da1..21cf6c5393 100644 --- a/src/Nancy/Responses/Negotiation/MediaRangeParameters.cs +++ b/src/Nancy/Responses/Negotiation/MediaRangeParameters.cs @@ -85,7 +85,8 @@ public string this[string name] { get { - return (this.parameters.ContainsKey(name)) ? this.parameters[name] : null; + string value; + return this.parameters.TryGetValue(name, out value) ? value : null; } } @@ -126,4 +127,4 @@ public override string ToString() return this; } } -} \ No newline at end of file +} diff --git a/src/Nancy/Routing/DefaultRouteCacheProvider.cs b/src/Nancy/Routing/DefaultRouteCacheProvider.cs index 3ff6f29a1a..9e7c927366 100755 --- a/src/Nancy/Routing/DefaultRouteCacheProvider.cs +++ b/src/Nancy/Routing/DefaultRouteCacheProvider.cs @@ -79,16 +79,18 @@ public IDictionary> GetAllRoutes() foreach (var entry in this.cacheProvider.GetCache().Values.SelectMany(t => t.Select(t1 => t1.Item2))) { - if (!result.ContainsKey(entry.Method)) + IList value; + if (!result.TryGetValue(entry.Method, out value)) { - result[entry.Method] = new List(); + value = new List(); + result[entry.Method] = value; } - result[entry.Method].Add(new { Name = entry.Name, Path = entry.Path }); + value.Add(new { Name = entry.Name, Path = entry.Path }); } return result; } } } -} \ No newline at end of file +} diff --git a/src/Nancy/Routing/RouteCache.cs b/src/Nancy/Routing/RouteCache.cs index 16c24d4688..b40c72ee8b 100644 --- a/src/Nancy/Routing/RouteCache.cs +++ b/src/Nancy/Routing/RouteCache.cs @@ -93,12 +93,14 @@ private RouteMetadata GetRouteMetadata(INancyModule module, RouteDescription rou private void AddRoutesToCache(IEnumerable routes, Type moduleType) { - if (!this.ContainsKey(moduleType)) + List> routeDescriptions; + if (!this.TryGetValue(moduleType, out routeDescriptions)) { - this[moduleType] = new List>(); + routeDescriptions = new List>(); + this[moduleType] = routeDescriptions; } - this[moduleType].AddRange(routes.Select((r, i) => new Tuple(i, r))); + routeDescriptions.AddRange(routes.Select((r, i) => new Tuple(i, r))); } } -} \ No newline at end of file +} diff --git a/src/Nancy/Routing/RouteMetadata.cs b/src/Nancy/Routing/RouteMetadata.cs index 5f5af7e1c0..20d9519f82 100644 --- a/src/Nancy/Routing/RouteMetadata.cs +++ b/src/Nancy/Routing/RouteMetadata.cs @@ -40,12 +40,11 @@ public bool Has() /// The metadata instance if available, otherwise . public TMetadata Retrieve() { - var key = - typeof(TMetadata); - - return (this.Raw.ContainsKey(key)) ? - (TMetadata)this.Raw[key] : + var key = typeof(TMetadata); + object value; + return this.Raw.TryGetValue(key, out value) ? + (TMetadata)value : default(TMetadata); } } -} \ No newline at end of file +} diff --git a/src/Nancy/Security/Csrf.cs b/src/Nancy/Security/Csrf.cs index ed25265ef2..0abbbcf81d 100644 --- a/src/Nancy/Security/Csrf.cs +++ b/src/Nancy/Security/Csrf.cs @@ -9,7 +9,6 @@ using Nancy.Bootstrapper; using Nancy.Cookies; using Nancy.Cryptography; - using Nancy.Helpers; /// /// Csrf protection methods @@ -40,19 +39,20 @@ public static void Enable(IPipelines pipelines, CryptographyConfiguration crypto return; } - if (context.Items.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY)) + object value; + if (context.Items.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out value)) { context.Response.Cookies.Add(new NancyCookie( CsrfToken.DEFAULT_CSRF_KEY, - (string)context.Items[CsrfToken.DEFAULT_CSRF_KEY], + (string)value, true, useSecureCookie)); return; } - if (context.Request.Cookies.ContainsKey(CsrfToken.DEFAULT_CSRF_KEY)) + string cookieValue; + if (context.Request.Cookies.TryGetValue(CsrfToken.DEFAULT_CSRF_KEY, out cookieValue)) { - var cookieValue = context.Request.Cookies[CsrfToken.DEFAULT_CSRF_KEY]; var cookieToken = ParseToCsrfToken(cookieValue); if (CsrfApplicationStartup.TokenValidator.CookieTokenStillValid(cookieToken)) diff --git a/src/Nancy/Session/CookieBasedSessions.cs b/src/Nancy/Session/CookieBasedSessions.cs index 46be9ffda1..48a8384818 100644 --- a/src/Nancy/Session/CookieBasedSessions.cs +++ b/src/Nancy/Session/CookieBasedSessions.cs @@ -166,10 +166,10 @@ public ISession Load(Request request) var cookieName = this.currentConfiguration.CookieName; var hmacProvider = this.currentConfiguration.CryptographyConfiguration.HmacProvider; var encryptionProvider = this.currentConfiguration.CryptographyConfiguration.EncryptionProvider; - - if (request.Cookies.ContainsKey(cookieName)) + string cookieValue; + if (request.Cookies.TryGetValue(cookieName, out cookieValue)) { - var cookieData = HttpUtility.UrlDecode(request.Cookies[cookieName]); + var cookieData = HttpUtility.UrlDecode(cookieValue); var hmacLength = Base64Helpers.GetBase64Length(hmacProvider.HmacLength); if (cookieData.Length < hmacLength) { @@ -229,4 +229,4 @@ private static Response LoadSession(NancyContext context, CookieBasedSessions se return null; } } -} \ No newline at end of file +} diff --git a/src/Nancy/Session/Session.cs b/src/Nancy/Session/Session.cs index fbc1cd282a..1287ea1dd5 100644 --- a/src/Nancy/Session/Session.cs +++ b/src/Nancy/Session/Session.cs @@ -64,7 +64,11 @@ public void Delete(string key) /// The value, or null or the key didn't exist public object this[string key] { - get { return dictionary.ContainsKey(key) ? dictionary[key] : null; } + get + { + object value; + return dictionary.TryGetValue(key, out value) ? value : null; + } set { var existingValue = this[key] ?? new Object(); @@ -116,4 +120,4 @@ private void MarkAsChanged() hasChanged = true; } } -} \ No newline at end of file +} diff --git a/src/Nancy/TinyIoc/TinyIoC.cs b/src/Nancy/TinyIoc/TinyIoC.cs index 90fd8078a0..24c35f8ba9 100755 --- a/src/Nancy/TinyIoc/TinyIoC.cs +++ b/src/Nancy/TinyIoc/TinyIoC.cs @@ -3889,8 +3889,9 @@ private object ConstructType(Type requestedType, Type implementationType, Constr try { - args[parameterIndex] = parameters.ContainsKey(currentParam.Name) ? - parameters[currentParam.Name] : + object value; + args[parameterIndex] = parameters.TryGetValue(currentParam.Name, out value) ? + value : ResolveInternal( new TypeRegistration(currentParam.ParameterType), NamedParameterOverloads.Default, diff --git a/src/Nancy/Validation/ModelValidationDescriptor.cs b/src/Nancy/Validation/ModelValidationDescriptor.cs index 7b0e8b1e91..16d3d76941 100644 --- a/src/Nancy/Validation/ModelValidationDescriptor.cs +++ b/src/Nancy/Validation/ModelValidationDescriptor.cs @@ -54,16 +54,18 @@ private static IDictionary> GetModelValidatio { foreach (var name in rule.MemberNames) { - if (!results.ContainsKey(name)) + IList list; + if (!results.TryGetValue(name, out list)) { - results.Add(name, new List()); + list = new List(); + results.Add(name, list); } - results[name].Add(rule); + list.Add(rule); } } return results; } } -} \ No newline at end of file +} diff --git a/src/Nancy/Validation/ModelValidationResult.cs b/src/Nancy/Validation/ModelValidationResult.cs index 6a6ea9afa6..a83ba2ab0f 100644 --- a/src/Nancy/Validation/ModelValidationResult.cs +++ b/src/Nancy/Validation/ModelValidationResult.cs @@ -77,24 +77,27 @@ private static IDictionary> GetModelValidati foreach (var result in results) { + IList value; foreach (var name in result.MemberNames) { - if (!output.ContainsKey(name)) + if (!output.TryGetValue(name, out value)) { - output.Add(name, new List()); + value = new List(); + output.Add(name, value); } - output[name].Add(result); + value.Add(result); } if (!result.MemberNames.Any() && !string.IsNullOrEmpty(result.ErrorMessage)) { - if (!output.ContainsKey(string.Empty)) + if (!output.TryGetValue(string.Empty, out value)) { - output.Add(string.Empty, new List()); + value = new List(); + output.Add(string.Empty, value); } - output[string.Empty].Add(result); + value.Add(result); } } diff --git a/src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngine.cs b/src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngine.cs index 3b4502a497..77c5545548 100644 --- a/src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngine.cs +++ b/src/Nancy/ViewEngines/SuperSimpleViewEngine/SuperSimpleViewEngine.cs @@ -714,8 +714,8 @@ private string RenderMasterPage(string masterTemplate, IDictionary { var sectionName = m.Groups["SectionName"].Value; - - return sections.ContainsKey(sectionName) ? sections[sectionName] : string.Empty; + string sectionValue; + return sections.TryGetValue(sectionName, out sectionValue) ? sectionValue : string.Empty; }); return result;