diff --git a/src/Hangfire.Core/CaptureCultureAttribute.cs b/src/Hangfire.Core/CaptureCultureAttribute.cs index b54f2557c..59090f6a7 100644 --- a/src/Hangfire.Core/CaptureCultureAttribute.cs +++ b/src/Hangfire.Core/CaptureCultureAttribute.cs @@ -60,13 +60,13 @@ public void OnPerformed(PerformedContext filterContext) { if (filterContext == null) throw new ArgumentNullException(nameof(filterContext)); - if (filterContext.Items.ContainsKey("PreviousCulture")) + if (filterContext.Items.TryGetValue("PreviousCulture", out var previousCulture)) { - SetCurrentCulture((CultureInfo) filterContext.Items["PreviousCulture"]); + SetCurrentCulture((CultureInfo) previousCulture); } - if (filterContext.Items.ContainsKey("PreviousUICulture")) + if (filterContext.Items.TryGetValue("PreviousUICulture", out var previousUICulture)) { - SetCurrentUICulture((CultureInfo)filterContext.Items["PreviousUICulture"]); + SetCurrentUICulture((CultureInfo) previousUICulture); } } diff --git a/src/Hangfire.Core/Client/CreatingContext.cs b/src/Hangfire.Core/Client/CreatingContext.cs index c6f96c101..7fcb8134c 100644 --- a/src/Hangfire.Core/Client/CreatingContext.cs +++ b/src/Hangfire.Core/Client/CreatingContext.cs @@ -69,8 +69,8 @@ public T GetJobParameter(string name) try { - return Parameters.ContainsKey(name) - ? (T)Parameters[name] + return Parameters.TryGetValue(name, out var parameter) + ? (T)parameter : default(T); } catch (Exception ex) diff --git a/src/Hangfire.Core/Dashboard/JobHistoryRenderer.cs b/src/Hangfire.Core/Dashboard/JobHistoryRenderer.cs index 78be55d24..ce631777d 100644 --- a/src/Hangfire.Core/Dashboard/JobHistoryRenderer.cs +++ b/src/Hangfire.Core/Dashboard/JobHistoryRenderer.cs @@ -68,12 +68,12 @@ public static void AddBackgroundStateColor(string stateName, string color) public static string GetBackgroundStateColor(string stateName) { - if (stateName == null || !BackgroundStateColors.ContainsKey(stateName)) + if (stateName == null || !BackgroundStateColors.TryGetValue(stateName, out var backgroundColor)) { return "inherit"; } - return BackgroundStateColors[stateName]; + return backgroundColor; } public static void AddForegroundStateColor(string stateName, string color) @@ -83,12 +83,12 @@ public static void AddForegroundStateColor(string stateName, string color) public static string GetForegroundStateColor(string stateName) { - if (stateName == null || !ForegroundStateColors.ContainsKey(stateName)) + if (stateName == null || !ForegroundStateColors.TryGetValue(stateName, out var foregroundColor)) { return "inherit"; } - return ForegroundStateColors[stateName]; + return foregroundColor; } public static void Register(string state, Func, NonEscapedString> renderer) @@ -112,8 +112,8 @@ public static NonEscapedString RenderHistory( this HtmlHelper helper, string state, IDictionary properties) { - var renderer = Renderers.ContainsKey(state) - ? Renderers[state] + var renderer = Renderers.TryGetValue(state, out var stateRenderer) + ? stateRenderer : DefaultRenderer; return renderer?.Invoke(helper, properties); @@ -149,28 +149,27 @@ public static NonEscapedString SucceededRenderer(HtmlHelper html, IDictionaryLatency:
{html.ToHumanDuration(latency, false)}
"); itemsAdded = true; } - if (stateData.ContainsKey("PerformanceDuration")) + if (stateData.TryGetValue("PerformanceDuration", out var performanceDurationValue)) { - var duration = TimeSpan.FromMilliseconds(long.Parse(stateData["PerformanceDuration"])); + var duration = TimeSpan.FromMilliseconds(long.Parse(performanceDurationValue)); builder.Append($"
Duration:
{html.ToHumanDuration(duration, false)}
"); itemsAdded = true; } - if (stateData.ContainsKey("Result") && !String.IsNullOrWhiteSpace(stateData["Result"])) + if (stateData.TryGetValue("Result", out var resultValue) && !String.IsNullOrWhiteSpace(resultValue)) { - var result = stateData["Result"]; - builder.Append($"
Result:
{System.Net.WebUtility.HtmlEncode(result)}
"); + builder.Append($"
Result:
{System.Net.WebUtility.HtmlEncode(resultValue)}
"); itemsAdded = true; } @@ -196,13 +195,13 @@ private static NonEscapedString ProcessingRenderer(HtmlHelper helper, IDictionar string serverId = null; - if (stateData.ContainsKey("ServerId")) + if (stateData.TryGetValue("ServerId", out var serverIdValue)) { - serverId = stateData["ServerId"]; + serverId = serverIdValue; } - else if (stateData.ContainsKey("ServerName")) + else if (stateData.TryGetValue("ServerName", out var serverName)) { - serverId = stateData["ServerName"]; + serverId = serverName; } if (serverId != null) @@ -211,15 +210,15 @@ private static NonEscapedString ProcessingRenderer(HtmlHelper helper, IDictionar builder.Append($"
{helper.ServerId(serverId)}
"); } - if (stateData.ContainsKey("WorkerId")) + if (stateData.TryGetValue("WorkerId", out var workerId)) { builder.Append("
Worker:
"); - builder.Append($"
{stateData["WorkerId"].Substring(0, 8)}
"); + builder.Append($"
{workerId.Substring(0, 8)}
"); } - else if (stateData.ContainsKey("WorkerNumber")) + else if (stateData.TryGetValue("WorkerNumber", out var workerNumber)) { builder.Append("
Worker:
"); - builder.Append($"
#{stateData["WorkerNumber"]}
"); + builder.Append($"
#{workerNumber}
"); } builder.Append(""); @@ -247,21 +246,20 @@ private static NonEscapedString AwaitingRenderer(HtmlHelper helper, IDictionary< builder.Append("
"); - if (stateData.ContainsKey("ParentId")) + if (stateData.TryGetValue("ParentId", out var parentId)) { - builder.Append($"
Parent
{helper.JobIdLink(stateData["ParentId"])}
"); + builder.Append($"
Parent
{helper.JobIdLink(parentId)}
"); } - if (stateData.ContainsKey("NextState")) + if (stateData.TryGetValue("NextState", out var nextStateValue)) { - var nextState = SerializationHelper.Deserialize(stateData["NextState"], SerializationOption.TypedInternal); + var nextState = SerializationHelper.Deserialize(nextStateValue, SerializationOption.TypedInternal); builder.Append($"
Next State
{helper.StateLabel(nextState.Name)}
"); } - if (stateData.ContainsKey("Options")) + if (stateData.TryGetValue("Options", out var optionsDescription)) { - var optionsDescription = stateData["Options"]; if (Enum.TryParse(optionsDescription, out JobContinuationOptions options)) { optionsDescription = options.ToString("G"); diff --git a/src/Hangfire.Core/Dashboard/Owin/OwinDashboardRequest.cs b/src/Hangfire.Core/Dashboard/Owin/OwinDashboardRequest.cs index f039edda0..aeb813f03 100644 --- a/src/Hangfire.Core/Dashboard/Owin/OwinDashboardRequest.cs +++ b/src/Hangfire.Core/Dashboard/Owin/OwinDashboardRequest.cs @@ -45,17 +45,16 @@ public override async Task> GetFormValuesAsync(string key) { IList values; - if(_context.Environment.ContainsKey(FormCollectionKey)) + if(_context.Environment.TryGetValue(FormCollectionKey, out var formCollection)) { - if(_context.Environment[FormCollectionKey] is IFormCollection) + if(formCollection is IFormCollection form) { - var form = (IFormCollection)_context.Request.Environment[FormCollectionKey]; values = form.GetValues(key); } else { - dynamic form = _context.Request.Environment[FormCollectionKey]; - values = form.GetValues(key); + dynamic dynamicForm = formCollection; + values = dynamicForm.GetValues(key); } } else diff --git a/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml b/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml index fb0a3b36b..7fae68f9d 100644 --- a/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml +++ b/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml @@ -126,9 +126,9 @@ @Html.JobNameLink(jobId, jobData.Job) - @if (stateData != null && stateData.Data.ContainsKey("Options") && !String.IsNullOrWhiteSpace(stateData.Data["Options"])) + @if (stateData != null && stateData.Data.TryGetValue("Options", out var options) && !String.IsNullOrWhiteSpace(options)) { - @stateData.Data["Options"] + @options } else { diff --git a/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs b/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs index 0cd5d3c57..217046702 100644 --- a/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs +++ b/src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs @@ -508,7 +508,7 @@ public override void Execute() #line 129 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml" - if (stateData != null && stateData.Data.ContainsKey("Options") && !String.IsNullOrWhiteSpace(stateData.Data["Options"])) + if (stateData != null && stateData.Data.TryGetValue("Options", out var options) && !String.IsNullOrWhiteSpace(options)) { @@ -519,7 +519,7 @@ public override void Execute() #line 131 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml" - Write(stateData.Data["Options"]); + Write(options); #line default diff --git a/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml b/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml index c2958fd13..b0f091e98 100644 --- a/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml +++ b/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml @@ -132,9 +132,9 @@ else @(stateData?.Reason) - @if (stateData != null && stateData.Data.ContainsKey("EnqueueAt")) + @if (stateData != null && stateData.Data.TryGetValue("EnqueueAt", out var enqueueAt)) { - @Html.RelativeTime(JobHelper.DeserializeDateTime(stateData.Data["EnqueueAt"])) + @Html.RelativeTime(JobHelper.DeserializeDateTime(enqueueAt)) } diff --git a/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml.cs b/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml.cs index ea80e691e..bc5280127 100644 --- a/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml.cs +++ b/src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml.cs @@ -549,7 +549,7 @@ public override void Execute() #line 135 "..\..\Dashboard\Pages\RetriesPage.cshtml" - if (stateData != null && stateData.Data.ContainsKey("EnqueueAt")) + if (stateData != null && stateData.Data.TryGetValue("EnqueueAt", out var enqueueAt)) { @@ -557,7 +557,7 @@ public override void Execute() #line hidden #line 137 "..\..\Dashboard\Pages\RetriesPage.cshtml" - Write(Html.RelativeTime(JobHelper.DeserializeDateTime(stateData.Data["EnqueueAt"]))); + Write(Html.RelativeTime(JobHelper.DeserializeDateTime(enqueueAt))); #line default diff --git a/src/Hangfire.Core/DisableConcurrentExecutionAttribute.cs b/src/Hangfire.Core/DisableConcurrentExecutionAttribute.cs index 7d0dde0d6..cea410ecc 100644 --- a/src/Hangfire.Core/DisableConcurrentExecutionAttribute.cs +++ b/src/Hangfire.Core/DisableConcurrentExecutionAttribute.cs @@ -43,12 +43,12 @@ public void OnPerforming(PerformingContext filterContext) public void OnPerformed(PerformedContext filterContext) { - if (!filterContext.Items.ContainsKey("DistributedLock")) + if (!filterContext.Items.TryGetValue("DistributedLock", out var distributedLockValue)) { throw new InvalidOperationException("Can not release a distributed lock: it was not acquired."); } - var distributedLock = (IDisposable)filterContext.Items["DistributedLock"]; + var distributedLock = (IDisposable)distributedLockValue; distributedLock.Dispose(); } diff --git a/src/Hangfire.Core/RecurringJobEntity.cs b/src/Hangfire.Core/RecurringJobEntity.cs index 1b303ccd7..82f0da63f 100644 --- a/src/Hangfire.Core/RecurringJobEntity.cs +++ b/src/Hangfire.Core/RecurringJobEntity.cs @@ -40,52 +40,52 @@ public RecurringJobEntity( RecurringJobId = recurringJobId ?? throw new ArgumentNullException(nameof(recurringJobId)); - if (recurringJob.ContainsKey("Queue") && !String.IsNullOrWhiteSpace(recurringJob["Queue"])) + if (recurringJob.TryGetValue("Queue", out var queue) && !String.IsNullOrWhiteSpace(queue)) { - Queue = recurringJob["Queue"]; + Queue = queue; } - TimeZone = recurringJob.ContainsKey("TimeZoneId") && !String.IsNullOrWhiteSpace("TimeZoneId") - ? timeZoneResolver.GetTimeZoneById(recurringJob["TimeZoneId"]) + TimeZone = recurringJob.TryGetValue("TimeZoneId", out var timeZoneId) && !String.IsNullOrWhiteSpace(timeZoneId) + ? timeZoneResolver.GetTimeZoneById(timeZoneId) : TimeZoneInfo.Utc; - if (recurringJob.ContainsKey("Cron") && !String.IsNullOrWhiteSpace(recurringJob["Cron"])) + if (recurringJob.TryGetValue("Cron", out var cron) && !String.IsNullOrWhiteSpace(cron)) { - Cron = recurringJob["Cron"]; + Cron = cron; } - if (recurringJob.ContainsKey("Job") && !String.IsNullOrWhiteSpace(recurringJob["Job"])) + if (recurringJob.TryGetValue("Job", out var job) && !String.IsNullOrWhiteSpace(job)) { - Job = InvocationData.DeserializePayload(recurringJob["Job"]).DeserializeJob(); + Job = InvocationData.DeserializePayload(job).DeserializeJob(); } - if (recurringJob.ContainsKey("LastJobId") && !String.IsNullOrWhiteSpace(recurringJob["LastJobId"])) + if (recurringJob.TryGetValue("LastJobId", out var lastJobId) && !String.IsNullOrWhiteSpace(lastJobId)) { - LastJobId = recurringJob["LastJobId"]; + LastJobId = lastJobId; } - if (recurringJob.ContainsKey("LastExecution") && !String.IsNullOrWhiteSpace(recurringJob["LastExecution"])) + if (recurringJob.TryGetValue("LastExecution", out var lastExecution) && !String.IsNullOrWhiteSpace(lastExecution)) { - LastExecution = JobHelper.DeserializeDateTime(recurringJob["LastExecution"]); + LastExecution = JobHelper.DeserializeDateTime(lastExecution); } - if (recurringJob.ContainsKey("NextExecution") && !String.IsNullOrWhiteSpace(recurringJob["NextExecution"])) + if (recurringJob.TryGetValue("NextExecution", out var nextExecution) && !String.IsNullOrWhiteSpace(nextExecution)) { - NextExecution = JobHelper.DeserializeDateTime(recurringJob["NextExecution"]); + NextExecution = JobHelper.DeserializeDateTime(nextExecution); } - if (recurringJob.ContainsKey("CreatedAt") && !String.IsNullOrWhiteSpace(recurringJob["CreatedAt"])) + if (recurringJob.TryGetValue("CreatedAt", out var createdAt) && !String.IsNullOrWhiteSpace(createdAt)) { - CreatedAt = JobHelper.DeserializeDateTime(recurringJob["CreatedAt"]); + CreatedAt = JobHelper.DeserializeDateTime(createdAt); } else { CreatedAt = now; } - if (recurringJob.ContainsKey("V") && !String.IsNullOrWhiteSpace(recurringJob["V"])) + if (recurringJob.TryGetValue("V", out var v) && !String.IsNullOrWhiteSpace(v)) { - Version = int.Parse(recurringJob["V"], CultureInfo.InvariantCulture); + Version = int.Parse(v, CultureInfo.InvariantCulture); } } @@ -141,38 +141,38 @@ public IReadOnlyDictionary GetChangedFields(out DateTime? nextEx { var result = new Dictionary(); - if ((_recurringJob.ContainsKey("Queue") ? _recurringJob["Queue"] : null) != Queue) + if ((_recurringJob.TryGetValue("Queue", out var queue) ? queue : null) != Queue) { result.Add("Queue", Queue); } - if ((_recurringJob.ContainsKey("Cron") ? _recurringJob["Cron"] : null) != Cron) + if ((_recurringJob.TryGetValue("Cron", out var cron) ? cron : null) != Cron) { result.Add("Cron", Cron); } - if ((_recurringJob.ContainsKey("TimeZoneId") ? _recurringJob["TimeZoneId"] : null) != TimeZone.Id) + if ((_recurringJob.TryGetValue("TimeZoneId", out var timeZoneId) ? timeZoneId : null) != TimeZone.Id) { result.Add("TimeZoneId", TimeZone.Id); } var serializedJob = InvocationData.SerializeJob(Job).SerializePayload(); - if ((_recurringJob.ContainsKey("Job") ? _recurringJob["Job"] : null) != serializedJob) + if ((_recurringJob.TryGetValue("Job", out var job) ? job : null) != serializedJob) { result.Add("Job", serializedJob); } var serializedCreatedAt = JobHelper.SerializeDateTime(CreatedAt); - if ((_recurringJob.ContainsKey("CreatedAt") ? _recurringJob["CreatedAt"] : null) != serializedCreatedAt) + if ((_recurringJob.TryGetValue("CreatedAt", out var createdAt) ? createdAt : null) != serializedCreatedAt) { result.Add("CreatedAt", serializedCreatedAt); } var serializedLastExecution = LastExecution.HasValue ? JobHelper.SerializeDateTime(LastExecution.Value) : null; - if ((_recurringJob.ContainsKey("LastExecution") ? _recurringJob["LastExecution"] : null) != + if ((_recurringJob.TryGetValue("LastExecution", out var lastExecution) ? lastExecution : null) != serializedLastExecution) { result.Add("LastExecution", serializedLastExecution ?? String.Empty); @@ -181,13 +181,13 @@ public IReadOnlyDictionary GetChangedFields(out DateTime? nextEx nextExecution = GetNextExecution(); var serializedNextExecution = nextExecution.HasValue ? JobHelper.SerializeDateTime(nextExecution.Value) : null; - if ((_recurringJob.ContainsKey("NextExecution") ? _recurringJob["NextExecution"] : null) != + if ((_recurringJob.TryGetValue("NextExecution", out var nextExecutionValue) ? nextExecutionValue : null) != serializedNextExecution) { result.Add("NextExecution", serializedNextExecution ?? String.Empty); } - if ((_recurringJob.ContainsKey("LastJobId") ? _recurringJob["LastJobId"] : null) != LastJobId) + if ((_recurringJob.TryGetValue("LastJobId", out var lastJobId) ? lastJobId : null) != LastJobId) { result.Add("LastJobId", LastJobId ?? String.Empty); } diff --git a/src/Hangfire.Core/Server/BackgroundServerProcess.cs b/src/Hangfire.Core/Server/BackgroundServerProcess.cs index 57d503c8c..8cb9e5d6c 100644 --- a/src/Hangfire.Core/Server/BackgroundServerProcess.cs +++ b/src/Hangfire.Core/Server/BackgroundServerProcess.cs @@ -260,14 +260,14 @@ private static ServerContext GetServerContext(IDictionary proper { var serverContext = new ServerContext(); - if (properties.ContainsKey("Queues") && properties["Queues"] is string[] array) + if (properties.TryGetValue("Queues", out var queues) && queues is string[] array) { serverContext.Queues = array; } - if (properties.ContainsKey("WorkerCount")) + if (properties.TryGetValue("WorkerCount", out var workerCount)) { - serverContext.WorkerCount = (int)properties["WorkerCount"]; + serverContext.WorkerCount = (int)workerCount; } return serverContext; diff --git a/src/Hangfire.Core/Server/CoreBackgroundJobPerformer.cs b/src/Hangfire.Core/Server/CoreBackgroundJobPerformer.cs index ee34f63b3..bcfc316f1 100644 --- a/src/Hangfire.Core/Server/CoreBackgroundJobPerformer.cs +++ b/src/Hangfire.Core/Server/CoreBackgroundJobPerformer.cs @@ -224,8 +224,8 @@ private static object[] SubstituteArguments(PerformContext context) var parameter = parameters[i]; var argument = context.BackgroundJob.Job.Args[i]; - var value = Substitutions.ContainsKey(parameter.ParameterType) - ? Substitutions[parameter.ParameterType](context) + var value = Substitutions.TryGetValue(parameter.ParameterType, out var parameterType) + ? parameterType(context) : argument; result.Add(value); diff --git a/src/Hangfire.Core/Server/ServerJobCancellationToken.cs b/src/Hangfire.Core/Server/ServerJobCancellationToken.cs index d83726a11..ebcadbff1 100644 --- a/src/Hangfire.Core/Server/ServerJobCancellationToken.cs +++ b/src/Hangfire.Core/Server/ServerJobCancellationToken.cs @@ -173,22 +173,22 @@ private bool IsJobAborted(IStorageConnection connection) return true; } - if (!state.Data.ContainsKey("ServerId")) + if (!state.Data.TryGetValue("ServerId", out var serverId)) { return true; } - if (!state.Data["ServerId"].Equals(_serverId, StringComparison.OrdinalIgnoreCase)) + if (!serverId.Equals(_serverId, StringComparison.OrdinalIgnoreCase)) { return true; } - if (!state.Data.ContainsKey("WorkerId")) + if (!state.Data.TryGetValue("WorkerId", out var workerId)) { return true; } - if (!state.Data["WorkerId"].Equals(_workerId, StringComparison.OrdinalIgnoreCase)) + if (!workerId.Equals(_workerId, StringComparison.OrdinalIgnoreCase)) { return true; } diff --git a/src/Hangfire.Core/States/StateHandlerCollection.cs b/src/Hangfire.Core/States/StateHandlerCollection.cs index 285eae5be..089b50470 100644 --- a/src/Hangfire.Core/States/StateHandlerCollection.cs +++ b/src/Hangfire.Core/States/StateHandlerCollection.cs @@ -40,22 +40,23 @@ public void AddHandler(IStateHandler handler) if (handler == null) throw new ArgumentNullException(nameof(handler)); if (handler.StateName == null) throw new ArgumentException("The StateName property of the given state handler must be non null.", nameof(handler)); - if (!_handlers.ContainsKey(handler.StateName)) + if (!_handlers.TryGetValue(handler.StateName, out var stateHandlers)) { - _handlers.Add(handler.StateName, new List()); + stateHandlers = new List(); + _handlers.Add(handler.StateName, stateHandlers); } - _handlers[handler.StateName].Add(handler); + stateHandlers.Add(handler); } public IEnumerable GetHandlers(string stateName) { - if (stateName == null || !_handlers.ContainsKey(stateName)) + if (stateName == null || !_handlers.TryGetValue(stateName, out var stateHandlers)) { return Enumerable.Empty(); } - return _handlers[stateName].ToArray(); + return stateHandlers.ToArray(); } } } diff --git a/src/Hangfire.Core/Storage/StorageConnectionExtensions.cs b/src/Hangfire.Core/Storage/StorageConnectionExtensions.cs index 61bf592d2..bc3314cb0 100644 --- a/src/Hangfire.Core/Storage/StorageConnectionExtensions.cs +++ b/src/Hangfire.Core/Storage/StorageConnectionExtensions.cs @@ -90,14 +90,14 @@ private static List GetRecurringJobDtos(IStorageConnection conn dto.LoadException = ex; } - if (hash.ContainsKey("NextExecution")) + if (hash.TryGetValue("NextExecution", out var nextExecution)) { - dto.NextExecution = JobHelper.DeserializeNullableDateTime(hash["NextExecution"]); + dto.NextExecution = JobHelper.DeserializeNullableDateTime(nextExecution); } - if (hash.ContainsKey("LastJobId") && !string.IsNullOrWhiteSpace(hash["LastJobId"])) + if (hash.TryGetValue("LastJobId", out var lastJobId) && !string.IsNullOrWhiteSpace(lastJobId)) { - dto.LastJobId = hash["LastJobId"]; + dto.LastJobId = lastJobId; var stateData = connection.GetStateData(dto.LastJobId); if (stateData != null) @@ -106,24 +106,24 @@ private static List GetRecurringJobDtos(IStorageConnection conn } } - if (hash.ContainsKey("Queue")) + if (hash.TryGetValue("Queue", out var queue)) { - dto.Queue = hash["Queue"]; + dto.Queue = queue; } - if (hash.ContainsKey("LastExecution")) + if (hash.TryGetValue("LastExecution", out var lastExecution)) { - dto.LastExecution = JobHelper.DeserializeNullableDateTime(hash["LastExecution"]); + dto.LastExecution = JobHelper.DeserializeNullableDateTime(lastExecution); } - if (hash.ContainsKey("TimeZoneId")) + if (hash.TryGetValue("TimeZoneId", out var timeZoneId)) { - dto.TimeZoneId = hash["TimeZoneId"]; + dto.TimeZoneId = timeZoneId; } - if (hash.ContainsKey("CreatedAt")) + if (hash.TryGetValue("CreatedAt", out var createdAt)) { - dto.CreatedAt = JobHelper.DeserializeNullableDateTime(hash["CreatedAt"]); + dto.CreatedAt = JobHelper.DeserializeNullableDateTime(createdAt); } result.Add(dto); diff --git a/src/Hangfire.SqlServer/PersistentJobQueueProviderCollection.cs b/src/Hangfire.SqlServer/PersistentJobQueueProviderCollection.cs index 9d60c1118..39f2008a2 100644 --- a/src/Hangfire.SqlServer/PersistentJobQueueProviderCollection.cs +++ b/src/Hangfire.SqlServer/PersistentJobQueueProviderCollection.cs @@ -53,8 +53,8 @@ public void Add(IPersistentJobQueueProvider provider, IEnumerable queues public IPersistentJobQueueProvider GetProvider(string queue) { - return _providersByQueue.ContainsKey(queue) - ? _providersByQueue[queue] + return _providersByQueue.TryGetValue(queue, out var providers) + ? providers : _defaultProvider; } diff --git a/src/Hangfire.SqlServer/SqlServerConnection.cs b/src/Hangfire.SqlServer/SqlServerConnection.cs index 6bac29c9e..7c5ac6110 100644 --- a/src/Hangfire.SqlServer/SqlServerConnection.cs +++ b/src/Hangfire.SqlServer/SqlServerConnection.cs @@ -612,7 +612,7 @@ private IDisposable AcquireLock(string resource, TimeSpan timeout) var lockId = Guid.NewGuid(); - if (!_lockedResources.ContainsKey(resource)) + if (!_lockedResources.TryGetValue(resource, out var lockedResource)) { try { @@ -624,10 +624,11 @@ private IDisposable AcquireLock(string resource, TimeSpan timeout) throw; } - _lockedResources.Add(resource, new HashSet()); + lockedResource = new HashSet(); + _lockedResources.Add(resource, lockedResource); } - _lockedResources[resource].Add(lockId); + lockedResource.Add(lockId); return new DisposableLock(this, resource, lockId); } @@ -635,12 +636,12 @@ private void ReleaseLock(string resource, Guid lockId, bool onDisposing) { try { - if (_lockedResources.ContainsKey(resource)) + if (_lockedResources.TryGetValue(resource, out var lockedResource)) { - if (_lockedResources[resource].Contains(lockId)) + if (lockedResource.Contains(lockId)) { - if (_lockedResources[resource].Remove(lockId) && - _lockedResources[resource].Count == 0 && + if (lockedResource.Remove(lockId) && + lockedResource.Count == 0 && _lockedResources.Remove(resource) && _dedicatedConnection.State == ConnectionState.Open) { diff --git a/src/Hangfire.SqlServer/SqlServerDistributedLock.cs b/src/Hangfire.SqlServer/SqlServerDistributedLock.cs index c5208ce8f..f354b2967 100644 --- a/src/Hangfire.SqlServer/SqlServerDistributedLock.cs +++ b/src/Hangfire.SqlServer/SqlServerDistributedLock.cs @@ -67,7 +67,7 @@ public SqlServerDistributedLock([NotNull] SqlServerStorage storage, [NotNull] st _storage = storage; _resource = resource; - if (!AcquiredLocks.Value.ContainsKey(_resource) || AcquiredLocks.Value[_resource] == 0) + if (!AcquiredLocks.Value.TryGetValue(_resource, out var locks) || locks == 0) { _connection = storage.CreateAndOpenConnection(); diff --git a/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs b/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs index ed9ac6cb5..e6ec03eb8 100644 --- a/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs +++ b/src/Hangfire.SqlServer/SqlServerMonitoringApi.cs @@ -87,7 +87,7 @@ public JobList ProcessingJobs(int @from, int count) { Job = job, InProcessingState = ProcessingState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase), - ServerId = stateData.ContainsKey("ServerId") ? stateData["ServerId"] : stateData["ServerName"], + ServerId = stateData.TryGetValue("ServerId", out var serverId) ? serverId : stateData["ServerName"], StartedAt = sqlJob.StateChanged, })); } @@ -178,8 +178,8 @@ public JobList SucceededJobs(int @from, int count) Job = job, InSucceededState = SucceededState.StateName.Equals(sqlJob.StateName, StringComparison.OrdinalIgnoreCase), Result = stateData["Result"], - TotalDuration = stateData.ContainsKey("PerformanceDuration") && stateData.ContainsKey("Latency") - ? (long?)long.Parse(stateData["PerformanceDuration"]) + (long?)long.Parse(stateData["Latency"]) + TotalDuration = stateData.TryGetValue("PerformanceDuration", out var performanceDuration) && stateData.TryGetValue("Latency", out var latency) + ? (long?)long.Parse(performanceDuration) + (long?)long.Parse(latency) : null, SucceededAt = sqlJob.StateChanged })); @@ -449,7 +449,7 @@ private JobList EnqueuedJobs(DbConnection connection, long[] job .ToDictionary(x => x.Id, x => x); var sortedSqlJobs = jobIds - .Select(jobId => jobs.ContainsKey(jobId) ? jobs[jobId] : new SqlJob { Id = jobId }) + .Select(jobId => jobs.TryGetValue(jobId, out var job) ? job : new SqlJob { Id = jobId }) .ToList(); return DeserializeJobs( diff --git a/src/Hangfire.SqlServer/SqlServerStorage.cs b/src/Hangfire.SqlServer/SqlServerStorage.cs index 06ba46543..20322ef34 100644 --- a/src/Hangfire.SqlServer/SqlServerStorage.cs +++ b/src/Hangfire.SqlServer/SqlServerStorage.cs @@ -173,9 +173,9 @@ public override string ToString() foreach (var alias in new[] { "Data Source", "Server", "Address", "Addr", "Network Address" }) { - if (parts.ContainsKey(alias)) + if (parts.TryGetValue(alias, out var partAlias)) { - builder.Append(parts[alias]); + builder.Append(partAlias); break; } } @@ -184,9 +184,9 @@ public override string ToString() foreach (var alias in new[] { "Database", "Initial Catalog" }) { - if (parts.ContainsKey(alias)) + if (parts.TryGetValue(alias, out var partAlias)) { - builder.Append(parts[alias]); + builder.Append(partAlias); break; } }