Skip to content

Replacing ContainsKey with TryGetValue to avoid duplicate lookups in … #1374

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions src/Hangfire.Core/CaptureCultureAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/Client/CreatingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ public T GetJobParameter<T>(string name)

try
{
return Parameters.ContainsKey(name)
? (T)Parameters[name]
return Parameters.TryGetValue(name, out var parameter)
? (T)parameter
: default(T);
}
catch (Exception ex)
Expand Down
52 changes: 25 additions & 27 deletions src/Hangfire.Core/Dashboard/JobHistoryRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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<HtmlHelper, IDictionary<string, string>, NonEscapedString> renderer)
Expand All @@ -112,8 +112,8 @@ public static NonEscapedString RenderHistory(
this HtmlHelper helper,
string state, IDictionary<string, string> properties)
{
var renderer = Renderers.ContainsKey(state)
? Renderers[state]
var renderer = Renderers.TryGetValue(state, out var stateRenderer)
? stateRenderer
: DefaultRenderer;

return renderer?.Invoke(helper, properties);
Expand Down Expand Up @@ -149,28 +149,27 @@ public static NonEscapedString SucceededRenderer(HtmlHelper html, IDictionary<st

var itemsAdded = false;

if (stateData.ContainsKey("Latency"))
if (stateData.TryGetValue("Latency", out var latencyValue))
{
var latency = TimeSpan.FromMilliseconds(long.Parse(stateData["Latency"]));
var latency = TimeSpan.FromMilliseconds(long.Parse(latencyValue));

builder.Append($"<dt>Latency:</dt><dd>{html.ToHumanDuration(latency, false)}</dd>");

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($"<dt>Duration:</dt><dd>{html.ToHumanDuration(duration, false)}</dd>");

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($"<dt>Result:</dt><dd>{System.Net.WebUtility.HtmlEncode(result)}</dd>");
builder.Append($"<dt>Result:</dt><dd>{System.Net.WebUtility.HtmlEncode(resultValue)}</dd>");

itemsAdded = true;
}
Expand All @@ -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)
Expand All @@ -211,15 +210,15 @@ private static NonEscapedString ProcessingRenderer(HtmlHelper helper, IDictionar
builder.Append($"<dd>{helper.ServerId(serverId)}</dd>");
}

if (stateData.ContainsKey("WorkerId"))
if (stateData.TryGetValue("WorkerId", out var workerId))
{
builder.Append("<dt>Worker:</dt>");
builder.Append($"<dd>{stateData["WorkerId"].Substring(0, 8)}</dd>");
builder.Append($"<dd>{workerId.Substring(0, 8)}</dd>");
}
else if (stateData.ContainsKey("WorkerNumber"))
else if (stateData.TryGetValue("WorkerNumber", out var workerNumber))
{
builder.Append("<dt>Worker:</dt>");
builder.Append($"<dd>#{stateData["WorkerNumber"]}</dd>");
builder.Append($"<dd>#{workerNumber}</dd>");
}

builder.Append("</dl>");
Expand Down Expand Up @@ -247,21 +246,20 @@ private static NonEscapedString AwaitingRenderer(HtmlHelper helper, IDictionary<

builder.Append("<dl class=\"dl-horizontal\">");

if (stateData.ContainsKey("ParentId"))
if (stateData.TryGetValue("ParentId", out var parentId))
{
builder.Append($"<dt>Parent</dt><dd>{helper.JobIdLink(stateData["ParentId"])}</dd>");
builder.Append($"<dt>Parent</dt><dd>{helper.JobIdLink(parentId)}</dd>");
}

if (stateData.ContainsKey("NextState"))
if (stateData.TryGetValue("NextState", out var nextStateValue))
{
var nextState = SerializationHelper.Deserialize<IState>(stateData["NextState"], SerializationOption.TypedInternal);
var nextState = SerializationHelper.Deserialize<IState>(nextStateValue, SerializationOption.TypedInternal);

builder.Append($"<dt>Next State</dt><dd>{helper.StateLabel(nextState.Name)}</dd>");
}

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");
Expand Down
9 changes: 4 additions & 5 deletions src/Hangfire.Core/Dashboard/Owin/OwinDashboardRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,16 @@ public override async Task<IList<string>> GetFormValuesAsync(string key)
{
IList<string> 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
Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,9 @@
@Html.JobNameLink(jobId, jobData.Job)
</td>
<td class="min-width">
@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))
{
<code>@stateData.Data["Options"]</code>
<code>@options</code>
}
else
{
Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/Dashboard/Pages/AwaitingJobsPage.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
{


Expand All @@ -519,7 +519,7 @@ public override void Execute()


#line 131 "..\..\Dashboard\Pages\AwaitingJobsPage.cshtml"
Write(stateData.Data["Options"]);
Write(options);


#line default
Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,9 @@ else
@(stateData?.Reason)
</td>
<td class="align-right">
@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))
}
</td>
<td class="align-right">
Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/Dashboard/Pages/RetriesPage.cshtml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -549,15 +549,15 @@ 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))
{


#line default
#line hidden

#line 137 "..\..\Dashboard\Pages\RetriesPage.cshtml"
Write(Html.RelativeTime(JobHelper.DeserializeDateTime(stateData.Data["EnqueueAt"])));
Write(Html.RelativeTime(JobHelper.DeserializeDateTime(enqueueAt)));


#line default
Expand Down
4 changes: 2 additions & 2 deletions src/Hangfire.Core/DisableConcurrentExecutionAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down
52 changes: 26 additions & 26 deletions src/Hangfire.Core/RecurringJobEntity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down Expand Up @@ -141,38 +141,38 @@ public IReadOnlyDictionary<string, string> GetChangedFields(out DateTime? nextEx
{
var result = new Dictionary<string, string>();

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);
Expand All @@ -181,13 +181,13 @@ public IReadOnlyDictionary<string, string> 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);
}
Expand Down
Loading