Skip to content

Commit

Permalink
Merge pull request #416 from microsoft/staging
Browse files Browse the repository at this point in the history
Release - 7/16/24
EricJohnson327 authored Jul 15, 2024
2 parents 11fb693 + fa3fbed commit 9b013b6
Showing 66 changed files with 651 additions and 611 deletions.
39 changes: 32 additions & 7 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -46,7 +46,7 @@ csharp_space_between_method_declaration_parameter_list_parentheses = false

#Formatting - wrapping options

#leave code block on separate lines
#allow code blocks on single lines
csharp_preserve_single_line_blocks = true

#Style - Code block preferences
@@ -87,16 +87,13 @@ csharp_style_var_elsewhere = true:suggestion
csharp_style_var_for_built_in_types = true:suggestion
#prefer var when the type is already mentioned on the right-hand side of a declaration expression
csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:warning

#Style - language keyword and framework type options

#prefer the language keyword for local variables, method parameters, and class members, instead of the type name, for types that have a keyword to represent them
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion

#Style - Language rules
csharp_style_implicit_object_creation_when_type_is_apparent = true:warning
csharp_style_var_for_built_in_types = true:warning

#Style - modifier options

#prefer accessibility modifiers to be declared except for public interface members. This will currently not differ from always and will act as future proofing for if C# adds default interface methods.
@@ -146,7 +143,6 @@ dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
[*.{cs,vb}]

#Style - Unnecessary code rules
csharp_style_unused_value_assignment_preference = discard_variable:warning
@@ -203,6 +199,35 @@ dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:warning
dotnet_style_prefer_simplified_interpolation = true:suggestion

# Define what we will treat as private fields.
dotnet_naming_symbols.private_fields.applicable_kinds = field
dotnet_naming_symbols.private_fields.applicable_accessibilities = private

dotnet_naming_symbols.const_private_fields.applicable_kinds = field
dotnet_naming_symbols.const_private_fields.applicable_accessibilities = private
dotnet_naming_symbols.const_private_fields.required_modifiers = const

# Define rule that something must begin with an underscore and be in camel case.
dotnet_naming_style.require_underscore_prefix_and_camel_case.required_prefix = _
dotnet_naming_style.require_underscore_prefix_and_camel_case.capitalization = camel_case

dotnet_naming_style.requre_no_prefix_and_pascal_case.required_prefix =
dotnet_naming_style.requre_no_prefix_and_pascal_case.capitalization = pascal_case

# Appy our rule to private fields.
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.symbols = private_fields
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.style = require_underscore_prefix_and_camel_case
dotnet_naming_rule.private_fields_must_begin_with_underscore_and_be_in_camel_case.severity = warning

dotnet_naming_rule.const_fields_must_begin_with_no_prefix_and_be_in_pascal_case.symbols = const_private_fields
dotnet_naming_rule.const_fields_must_begin_with_no_prefix_and_be_in_pascal_case.style = requre_no_prefix_and_pascal_case
dotnet_naming_rule.const_fields_must_begin_with_no_prefix_and_be_in_pascal_case.severity = warning
# Spelling

spelling_exclusion_path = .\exclusion.dic
spelling_exclusion_path = .\exclusion.dic

# Diagnostic configuration

# CS8305: Type is for evaluation purposes only and is subject to change or removal in future updates.
dotnet_diagnostic.CS8305.severity = suggestion

2 changes: 1 addition & 1 deletion build/azure-pipelines.yml
Original file line number Diff line number Diff line change
@@ -20,7 +20,7 @@ parameters:
- release

variables:
MSIXVersion: '0.1500'
MSIXVersion: '0.1600'
solution: '**/GitHubExtension.sln'
appxPackageDir: 'AppxPackages'
testOutputArtifactDir: 'TestResults'
2 changes: 1 addition & 1 deletion build/scripts/CreateBuildInfo.ps1
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ Param(
)

$Major = "0"
$Minor = "15"
$Minor = "16"
$Patch = "99" # default to 99 for local builds

$versionSplit = $Version.Split(".");
6 changes: 6 additions & 0 deletions exclusion.dic
Original file line number Diff line number Diff line change
@@ -13,3 +13,9 @@ riid
Impl
microsoft
octokit
Octokit
Dependabot
Stringify
riid
impl
dhlog
26 changes: 13 additions & 13 deletions src/GitHubExtension/Client/GithubClientProvider.cs
Original file line number Diff line number Diff line change
@@ -10,13 +10,13 @@ namespace GitHubExtension.Client;

public class GitHubClientProvider
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(GitHubClientProvider)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(GitHubClientProvider)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

private readonly GitHubClient publicRepoClient;
private readonly GitHubClient _publicRepoClient;

private static readonly object InstanceLock = new();
private static readonly object _instanceLock = new();

private static GitHubClientProvider? _instance;

@@ -26,7 +26,7 @@ public static GitHubClientProvider Instance
{
if (_instance == null)
{
lock (InstanceLock)
lock (_instanceLock)
{
_instance = new GitHubClientProvider();
}
@@ -38,7 +38,7 @@ public static GitHubClientProvider Instance

public GitHubClientProvider()
{
publicRepoClient = new GitHubClient(new ProductHeaderValue(Constants.DEV_HOME_APPLICATION_NAME));
_publicRepoClient = new GitHubClient(new ProductHeaderValue(Constants.DEV_HOME_APPLICATION_NAME));
}

public GitHubClient? GetClient(IDeveloperId devId)
@@ -52,15 +52,15 @@ public GitHubClient GetClient(string url)
var devIdInternal = DeveloperIdProvider.GetInstance().GetLoggedInDeveloperIdsInternal().Where(i => i.Url.Equals(url, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
if (devIdInternal == null)
{
return publicRepoClient;
return _publicRepoClient;
}

return devIdInternal.GitHubClient;
}

public GitHubClient GetClient()
{
return publicRepoClient;
return _publicRepoClient;
}

public async Task<GitHubClient> GetClientForLoggedInDeveloper(bool logRateLimit = false)
@@ -70,18 +70,18 @@ public async Task<GitHubClient> GetClientForLoggedInDeveloper(bool logRateLimit
GitHubClient client;
if (devIds == null || !devIds.Any())
{
Log.Information($"No logged in developer, using public GitHub client.");
_log.Information($"No logged in developer, using public GitHub client.");
client = Instance.GetClient();
}
else
{
Log.Information($"Using authenticated user: {devIds.First().LoginId}");
_log.Information($"Using authenticated user: {devIds.First().LoginId}");
client = devIds.First().GitHubClient;
}

if (client == null)
{
Log.Error($"Failed creating GitHubClient.");
_log.Error($"Failed creating GitHubClient.");
return client!;
}

@@ -90,11 +90,11 @@ public async Task<GitHubClient> GetClientForLoggedInDeveloper(bool logRateLimit
try
{
var miscRateLimit = await client.RateLimit.GetRateLimits();
Log.Information($"Rate Limit: Remaining: {miscRateLimit.Resources.Core.Remaining} Total: {miscRateLimit.Resources.Core.Limit} Resets: {miscRateLimit.Resources.Core.Reset}");
_log.Information($"Rate Limit: Remaining: {miscRateLimit.Resources.Core.Remaining} Total: {miscRateLimit.Resources.Core.Limit} Resets: {miscRateLimit.Resources.Core.Reset}");
}
catch (Exception ex)
{
Log.Error(ex, $"Rate limiting not enabled for server.");
_log.Error(ex, $"Rate limiting not enabled for server.");
}
}

14 changes: 7 additions & 7 deletions src/GitHubExtension/Client/Validation.cs
Original file line number Diff line number Diff line change
@@ -9,9 +9,9 @@ namespace GitHubExtension.Client;
// Validation layer to help parsing GitHub URL.
public static class Validation
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(Validation)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(Validation)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

private static bool IsValidHttpUri(string uriString, out Uri? uri)
{
@@ -29,7 +29,7 @@ public static bool IsValidGitHubComURL(Uri uri)
// Valid GitHub URL has three segments. The first is '/'.
if (uri.Segments.Length < 3 || (!uri.Host.Equals("github.com", StringComparison.OrdinalIgnoreCase) && !uri.Host.Equals("www.github.com", StringComparison.OrdinalIgnoreCase)))
{
Log.Debug($"{uri.OriginalString} is not a valid GitHub uri");
_log.Debug($"{uri.OriginalString} is not a valid GitHub uri");
return false;
}

@@ -43,7 +43,7 @@ public static bool IsValidGitHubEnterpriseServerURL(Uri server)
// https://docs.github.com/en/[email protected]/admin/configuration/configuring-network-settings/configuring-the-hostname-for-your-instance
if (server.Segments.Length < 3)
{
Log.Debug($"{server.OriginalString} is not a valid GHES repo uri");
_log.Debug($"{server.OriginalString} is not a valid GHES repo uri");
return false;
}

@@ -60,7 +60,7 @@ public static bool IsValidGitHubURL(string url)
// Above link shows a work around.
if (!IsValidHttpUri(url, out parsedUri) || url == null || parsedUri == null)
{
Log.Debug($"{url} is not a valid http uri");
_log.Debug($"{url} is not a valid http uri");
return false;
}

@@ -231,13 +231,13 @@ public static async Task<bool> IsReachableGitHubEnterpriseServerURL(Uri server)
var probeResult = await new EnterpriseProbe(new ProductHeaderValue(Constants.DEV_HOME_APPLICATION_NAME)).Probe(server);
if (probeResult != EnterpriseProbeResult.Ok)
{
Log.Error($"EnterpriseServer {server.AbsoluteUri} is not reachable");
_log.Error($"EnterpriseServer {server.AbsoluteUri} is not reachable");
return false;
}
}
catch (Exception ex)
{
Log.Error(ex, $"EnterpriseServer {server.AbsoluteUri} could not be probed.");
_log.Error(ex, $"EnterpriseServer {server.AbsoluteUri} could not be probed.");
return false;
}

10 changes: 5 additions & 5 deletions src/GitHubExtension/DataManager/DataUpdater.cs
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ namespace GitHubExtension.DataManager;
public class DataUpdater : IDisposable
{
// This is the default interval the timer will run. It is not the interval that we necessarily do work.
private static readonly TimeSpan TimerUpdateInterval = TimeSpan.FromSeconds(5);
private static readonly TimeSpan _timerUpdateInterval = TimeSpan.FromSeconds(5);

private readonly ILogger _logger;
private readonly PeriodicTimer _timer;
@@ -28,7 +28,7 @@ public DataUpdater(TimeSpan interval, Func<Task> action)
}

public DataUpdater(Func<Task> action)
: this(TimerUpdateInterval, action)
: this(_timerUpdateInterval, action)
{
}

@@ -62,11 +62,11 @@ public void Stop()

public override string ToString() => "DataUpdater";

private bool disposed; // To detect redundant calls.
private bool _disposed; // To detect redundant calls.

protected virtual void Dispose(bool disposing)
{
if (!disposed)
if (!_disposed)
{
_logger.Debug("Disposing of all updater resources.");

@@ -75,7 +75,7 @@ protected virtual void Dispose(bool disposing)
_timer.Dispose();
}

disposed = true;
_disposed = true;
}
}

120 changes: 60 additions & 60 deletions src/GitHubExtension/DataManager/GitHubDataManager.cs

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions src/GitHubExtension/DataManager/GitHubDataManagerUpdate.cs
Original file line number Diff line number Diff line change
@@ -9,14 +9,14 @@ namespace GitHubExtension;
public partial class GitHubDataManager
{
// This is how frequently the DataStore update occurs.
private static readonly TimeSpan UpdateInterval = TimeSpan.FromMinutes(5);
private static DateTime lastUpdateTime = DateTime.MinValue;
private static readonly TimeSpan _updateInterval = TimeSpan.FromMinutes(5);
private static DateTime _lastUpdateTime = DateTime.MinValue;

public static async Task Update()
{
// Only update per the update interval.
// This is intended to be dynamic in the future.
if (DateTime.Now - lastUpdateTime < UpdateInterval)
if (DateTime.Now - _lastUpdateTime < _updateInterval)
{
return;
}
@@ -27,15 +27,15 @@ public static async Task Update()
}
catch (Exception ex)
{
Log.Error(ex, "Update failed unexpectedly.");
_log.Error(ex, "Update failed unexpectedly.");
}

lastUpdateTime = DateTime.Now;
_lastUpdateTime = DateTime.Now;
}

private static async Task UpdateDeveloperPullRequests()
{
Log.Debug($"Executing UpdateDeveloperPullRequests");
_log.Debug($"Executing UpdateDeveloperPullRequests");
using var dataManager = CreateInstance() ?? throw new DataStoreInaccessibleException("GitHubDataManager is null.");
await dataManager.UpdatePullRequestsForLoggedInDeveloperIdsAsync();

@@ -73,7 +73,7 @@ private static void SendUpdateEvent(object? source, DataManagerUpdateKind kind,
{
info ??= string.Empty;
context ??= Array.Empty<string>();
Log.Information($"Sending Update Event: {kind} Info: {info} Context: {string.Join(",", context)}");
_log.Information($"Sending Update Event: {kind} Info: {info} Context: {string.Join(",", context)}");
OnUpdate.Invoke(source, new DataManagerUpdateEventArgs(kind, info, context));
}
}
16 changes: 8 additions & 8 deletions src/GitHubExtension/DataManager/GitHubSearchManager.cs
Original file line number Diff line number Diff line change
@@ -12,11 +12,11 @@ namespace GitHubExtension;

public partial class GitHubSearchManager : IGitHubSearchManager, IDisposable
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(GitHubSearchManager)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(GitHubSearchManager)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

private static readonly string Name = nameof(GitHubSearchManager);
private static readonly string _name = nameof(GitHubSearchManager);

public static event SearchManagerResultsAvailableEventHandler? OnResultsAvailable;

@@ -32,7 +32,7 @@ public GitHubSearchManager()
}
catch (Exception e)
{
Log.Error(e, "Failed creating GitHubSearchManager");
_log.Error(e, "Failed creating GitHubSearchManager");
Environment.FailFast(e.Message, e);
return null;
}
@@ -54,7 +54,7 @@ public async Task SearchForGitHubIssuesOrPRs(Octokit.SearchIssuesRequest request

private async Task SearchForGitHubIssuesOrPRs(Octokit.SearchIssuesRequest request, string initiator, SearchCategory category, Octokit.GitHubClient client, RequestOptions? options = null)
{
Log.Information(Name, $"Searching for issues or pull requests for widget {initiator}");
_log.Information(_name, $"Searching for issues or pull requests for widget {initiator}");
request.State = Octokit.ItemState.Open;
request.Archived = false;
request.PerPage = 10;
@@ -75,12 +75,12 @@ private async Task SearchForGitHubIssuesOrPRs(Octokit.SearchIssuesRequest reques
var octokitResult = await client.Search.SearchIssues(request);
if (octokitResult == null)
{
Log.Debug($"No issues or PRs found.");
_log.Debug($"No issues or PRs found.");
SendResultsAvailable(new List<Octokit.Issue>(), initiator);
}
else
{
Log.Debug($"Results contain {octokitResult.Items.Count} items.");
_log.Debug($"Results contain {octokitResult.Items.Count} items.");
SendResultsAvailable(octokitResult.Items, initiator);
}
}
@@ -89,7 +89,7 @@ private void SendResultsAvailable(IEnumerable<Octokit.Issue> results, string ini
{
if (OnResultsAvailable != null)
{
Log.Information(Name, $"Sending search results available Event, of type: {initiator}");
_log.Information(_name, $"Sending search results available Event, of type: {initiator}");
OnResultsAvailable.Invoke(results, initiator);
}
}
22 changes: 11 additions & 11 deletions src/GitHubExtension/DataModel/DataObjects/CheckRun.cs
Original file line number Diff line number Diff line change
@@ -12,9 +12,9 @@ namespace GitHubExtension.DataModel;
[Table("CheckRun")]
public class CheckRun
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CheckRun)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CheckRun)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -134,7 +134,7 @@ private static CheckConclusion GetCheckRunConclusion(StringEnum<Octokit.CheckCon
catch (Exception)
{
// This error means a programming error or Octokit added to or changed their enum.
Log.Error($"Found Unknown CheckConclusion value: {octoCheckConclusion.Value.Value}");
_log.Error($"Found Unknown CheckConclusion value: {octoCheckConclusion.Value.Value}");
return CheckConclusion.Unknown;
}

@@ -154,7 +154,7 @@ private static CheckStatus GetCheckRunStatus(StringEnum<Octokit.CheckStatus> oct
catch (Exception)
{
// This error means a programming error or Octokit added to or changed their enum.
Log.Error($"Found Unknown CheckStatus value: {octoCheckStatus.Value}");
_log.Error($"Found Unknown CheckStatus value: {octoCheckStatus.Value}");
return CheckStatus.Unknown;
}

@@ -210,7 +210,7 @@ public static IEnumerable<CheckRun> GetFailedCheckRunsForPullRequest(DataStore d
MaxConclusion = (long)CheckConclusion.ActionRequired,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
return dataStore.Connection!.Query<CheckRun>(sql, param, null) ?? Enumerable.Empty<CheckRun>();
}

@@ -225,7 +225,7 @@ public static CheckStatus GetCheckRunStatusForPullRequest(DataStore datastore, P
pullRequest.HeadSha,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));

// Query results in NULL if there are no entries, and QueryFirstOrDefault will throw trying
// to assign null to an integer. In this instance we catch it and return the None type.
@@ -255,7 +255,7 @@ public static CheckConclusion GetCheckRunConclusionForPullRequest(DataStore data
StatusId = (long)CheckStatus.Completed,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));

// Query results in NULL if there are no entries, and QueryFirstOrDefault will throw trying
// to assign null to an integer. In this instance we catch it and return the None type.
@@ -275,9 +275,9 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM CheckRun WHERE HeadSha NOT IN (SELECT HeadSha FROM PullRequest)";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

public static void DeleteAllForPullRequest(DataStore dataStore, PullRequest pullRequest)
@@ -287,8 +287,8 @@ public static void DeleteAllForPullRequest(DataStore dataStore, PullRequest pull
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$HeadSha", pullRequest.HeadSha);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
18 changes: 9 additions & 9 deletions src/GitHubExtension/DataModel/DataObjects/CheckSuite.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("CheckSuite")]
public class CheckSuite
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CheckSuite)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CheckSuite)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -111,7 +111,7 @@ private static CheckConclusion GetCheckConclusion(StringEnum<Octokit.CheckConclu
catch (Exception)
{
// This error means a programming error or Octokit added to or changed their enum.
Log.Error($"Found Unknown CheckConclusion value: {octoCheckConclusion.Value.Value}");
_log.Error($"Found Unknown CheckConclusion value: {octoCheckConclusion.Value.Value}");
return CheckConclusion.Unknown;
}

@@ -131,7 +131,7 @@ private static CheckStatus GetCheckStatus(StringEnum<Octokit.CheckStatus> octoCh
catch (Exception)
{
// This error means a programming error or Octokit added to or changed their enum.
Log.Error($"Found Unknown CheckStatus value: {octoCheckStatus.Value}");
_log.Error($"Found Unknown CheckStatus value: {octoCheckStatus.Value}");
return CheckStatus.Unknown;
}

@@ -184,7 +184,7 @@ public static CheckStatus GetCheckStatusForPullRequest(DataStore datastore, Pull
pullRequest.HeadSha,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));

// Query results in NULL if there are no entries, and QueryFirstOrDefault will throw trying
// to assign null to an integer. In this instance we catch it and return the None type.
@@ -214,7 +214,7 @@ public static CheckConclusion GetCheckConclusionForPullRequest(DataStore datasto
StatusId = (long)CheckStatus.Completed,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));

// Query results in NULL if there are no entries, and QueryFirstOrDefault will throw trying
// to assign null to an integer. In this instance we catch it and return the None type.
@@ -235,9 +235,9 @@ public static void DeleteAllForPullRequest(DataStore dataStore, PullRequest pull
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$HeadSha", pullRequest.HeadSha);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

public static void DeleteUnreferenced(DataStore dataStore)
@@ -246,7 +246,7 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM CheckSuite WHERE HeadSha NOT IN (SELECT HeadSha FROM PullRequest)";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
command.ExecuteNonQuery();
}
}
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("CommitCombinedStatus")]
public class CommitCombinedStatus
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CommitCombinedStatus)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(CommitCombinedStatus)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -76,7 +76,7 @@ private static CommitState GetCommitState(Octokit.StringEnum<Octokit.CommitState
catch (Exception)
{
// This error means a programming error or Octokit added to or changed their enum.
Log.Error($"Found Unknown CheckStatus value: {octoCommitState.Value}");
_log.Error($"Found Unknown CheckStatus value: {octoCommitState.Value}");
return CommitState.Unknown;
}

@@ -117,9 +117,9 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM CommitCombinedStatus WHERE HeadSha NOT IN (SELECT HeadSha FROM PullRequest)";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

public static void DeleteForPullRequest(DataStore dataStore, PullRequest pullRequest)
@@ -129,8 +129,8 @@ public static void DeleteForPullRequest(DataStore dataStore, PullRequest pullReq
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$HeadSha", pullRequest.HeadSha);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
14 changes: 7 additions & 7 deletions src/GitHubExtension/DataModel/DataObjects/Issue.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("Issue")]
public class Issue
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Issue)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Issue)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -191,7 +191,7 @@ private static Issue CreateFromOctokitIssue(DataStore dataStore, Octokit.Issue o

issue.AssigneeIds = string.Join(",", assignees);

// Owner is a rowid in the User table
// Owner is a row id in the User table
var author = User.GetOrCreateByOctokitUser(dataStore, okitIssue.User);
issue.AuthorId = author.Id;

@@ -291,7 +291,7 @@ public static IEnumerable<Issue> GetAllForRepository(DataStore dataStore, Reposi
RepositoryId = repository.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var issues = dataStore.Connection!.Query<Issue>(sql, param, null) ?? Enumerable.Empty<Issue>();
foreach (var issue in issues)
{
@@ -315,7 +315,7 @@ public static IEnumerable<Issue> GetForSearch(DataStore dataStore, Search search
SearchId = search.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var issues = dataStore.Connection!.Query<Issue>(sql, param, null) ?? Enumerable.Empty<Issue>();
foreach (var issue in issues)
{
@@ -370,8 +370,8 @@ public static void DeleteLastObservedBefore(DataStore dataStore, long repository
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
command.Parameters.AddWithValue("$RepositoryId", repositoryId);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
6 changes: 3 additions & 3 deletions src/GitHubExtension/DataModel/DataObjects/IssueAssign.cs
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("IssueAssign")]
public class IssueAssign
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(IssueAssign)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(IssueAssign)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -60,7 +60,7 @@ public static IEnumerable<User> GetUsersForIssue(DataStore dataStore, Issue issu
IssueId = issue.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
return dataStore.Connection!.Query<User>(sql, param, null) ?? Enumerable.Empty<User>();
}

6 changes: 3 additions & 3 deletions src/GitHubExtension/DataModel/DataObjects/IssueLabel.cs
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("IssueLabel")]
public class IssueLabel
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(IssueLabel)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(IssueLabel)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -60,7 +60,7 @@ public static IEnumerable<Label> GetLabelsForIssue(DataStore dataStore, Issue is
IssueId = issue.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
return dataStore.Connection!.Query<Label>(sql, param, null) ?? Enumerable.Empty<Label>();
}

8 changes: 4 additions & 4 deletions src/GitHubExtension/DataModel/DataObjects/Label.cs
Original file line number Diff line number Diff line change
@@ -11,14 +11,14 @@ namespace GitHubExtension.DataModel;
[Table("Label")]
public class Label
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Label)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Label)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

// This is the time between seeing a potential updated label record and updating it.
// This value / 2 is the average time between label changing on GitHub and having
// it reflected in the datastore.
private static readonly long UpdateThreshold = TimeSpan.FromHours(4).Ticks;
private static readonly long _updateThreshold = TimeSpan.FromHours(4).Ticks;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -60,7 +60,7 @@ private static Label AddOrUpdateLabel(DataStore dataStore, Label label)
// avoid unnecessary updating and database operations for data that
// is extremely unlikely to have changed in any significant way, we
// will only update every UpdateThreshold amount of time.
if ((label.TimeUpdated - existing.TimeUpdated) > UpdateThreshold)
if ((label.TimeUpdated - existing.TimeUpdated) > _updateThreshold)
{
label.Id = existing.Id;
dataStore.Connection!.Update(label);
4 changes: 2 additions & 2 deletions src/GitHubExtension/DataModel/DataObjects/MetaData.cs
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("MetaData")]
public class MetaData
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(MetaData)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(MetaData)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
28 changes: 14 additions & 14 deletions src/GitHubExtension/DataModel/DataObjects/Notification.cs
Original file line number Diff line number Diff line change
@@ -25,9 +25,9 @@ namespace GitHubExtension.DataModel;
[Table("Notification")]
public class Notification
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Notification)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Notification)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -98,7 +98,7 @@ public bool Toasted
// Catch errors so we do not throw for something like this. The local ToastState
// will still be set even if the datastore update fails. This could result in a
// toast later being shown twice, however, so report it as an error.
Log.Error(ex, "Failed setting Notification ToastState for Notification Id = {Id}");
_log.Error(ex, "Failed setting Notification ToastState for Notification Id = {Id}");
}
}
}
@@ -175,7 +175,7 @@ private bool ShowFailedCheckRunToast()
{
try
{
Log.Information($"Showing Notification for {this}");
_log.Information($"Showing Notification for {this}");
var resLoader = new ResourceLoader(ResourceLoader.GetDefaultResourceFilePath(), "GitHubExtension/Resources");
var nb = new AppNotificationBuilder();
nb.SetDuration(AppNotificationDuration.Long);
@@ -194,7 +194,7 @@ private bool ShowFailedCheckRunToast()
}
catch (Exception ex)
{
Log.Error(ex, $"Failed creating the Notification for {this}");
_log.Error(ex, $"Failed creating the Notification for {this}");
return false;
}

@@ -205,7 +205,7 @@ private bool ShowSucceededCheckRunToast()
{
try
{
Log.Information($"Showing Notification for {this}");
_log.Information($"Showing Notification for {this}");
var resLoader = new ResourceLoader(ResourceLoader.GetDefaultResourceFilePath(), "GitHubExtension/Resources");
var nb = new AppNotificationBuilder();
nb.SetDuration(AppNotificationDuration.Long);
@@ -224,7 +224,7 @@ private bool ShowSucceededCheckRunToast()
}
catch (Exception ex)
{
Log.Error(ex, $"Failed creating the Notification for {this}");
_log.Error(ex, $"Failed creating the Notification for {this}");
return false;
}

@@ -235,7 +235,7 @@ private bool ShowNewReviewToast()
{
try
{
Log.Information($"Showing Notification for {this}");
_log.Information($"Showing Notification for {this}");
var resLoader = new ResourceLoader(ResourceLoader.GetDefaultResourceFilePath(), "GitHubExtension/Resources");
var nb = new AppNotificationBuilder();
nb.SetDuration(AppNotificationDuration.Long);
@@ -267,7 +267,7 @@ private bool ShowNewReviewToast()
}
catch (Exception ex)
{
Log.Error(ex, $"Failed creating the Notification for {this}");
_log.Error(ex, $"Failed creating the Notification for {this}");
return false;
}

@@ -338,7 +338,7 @@ public static IEnumerable<Notification> Get(DataStore dataStore, DateTime? since
ToastedCount = includeToasted ? 1 : 0,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var notifications = dataStore.Connection!.Query<Notification>(sql, param, null) ?? Enumerable.Empty<Notification>();
foreach (var notification in notifications)
{
@@ -362,13 +362,13 @@ public static void SetOlderNotificationsToasted(DataStore dataStore, Notificatio
notification.TimeOccurred,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var outDatedNotifications = dataStore.Connection!.Query<Notification>(sql, param, null) ?? Enumerable.Empty<Notification>();
foreach (var olderNotification in outDatedNotifications)
{
olderNotification.DataStore = dataStore;
olderNotification.Toasted = true;
Log.Information($"Found older notification for {olderNotification.Identifier} with result {olderNotification.Result}, marking toasted.");
_log.Information($"Found older notification for {olderNotification.Identifier} with result {olderNotification.Result}, marking toasted.");
}
}

@@ -379,8 +379,8 @@ public static void DeleteBefore(DataStore dataStore, DateTime date)
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
16 changes: 8 additions & 8 deletions src/GitHubExtension/DataModel/DataObjects/PullRequest.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("PullRequest")]
public class PullRequest
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequest)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequest)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -491,7 +491,7 @@ public static IEnumerable<PullRequest> GetAllForRepository(DataStore dataStore,
RepositoryId = repository.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var pulls = dataStore.Connection!.Query<PullRequest>(sql, param, null) ?? Enumerable.Empty<PullRequest>();
foreach (var pull in pulls)
{
@@ -509,7 +509,7 @@ public static IEnumerable<PullRequest> GetAllForUser(DataStore dataStore, User u
AuthorId = user.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var pulls = dataStore.Connection!.Query<PullRequest>(sql, param, null) ?? Enumerable.Empty<PullRequest>();
foreach (var pull in pulls)
{
@@ -564,9 +564,9 @@ public static void DeleteLastObservedBefore(DataStore dataStore, long repository
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
command.Parameters.AddWithValue("$RepositoryId", repositoryId);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

// Delete all records from a particular user before the specified date.
@@ -587,9 +587,9 @@ public static void DeleteAllByDeveloperLoginAndLastObservedBefore(DataStore data
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
command.Parameters.AddWithValue("$UserId", user.Id);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
break;
}
}
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("PullRequestAssign")]
public class PullRequestAssign
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestAssign)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestAssign)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -62,7 +62,7 @@ public static IEnumerable<User> GetUsersForPullRequest(DataStore dataStore, Pull
PullId = pull.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
return dataStore.Connection!.Query<User>(sql, param, null) ?? Enumerable.Empty<User>();
}

6 changes: 3 additions & 3 deletions src/GitHubExtension/DataModel/DataObjects/PullRequestLabel.cs
Original file line number Diff line number Diff line change
@@ -10,9 +10,9 @@ namespace GitHubExtension.DataModel;
[Table("PullRequestLabel")]
public class PullRequestLabel
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestLabel)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestLabel)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -60,7 +60,7 @@ public static IEnumerable<Label> GetLabelsForPullRequest(DataStore dataStore, Pu
PullId = pull.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
return dataStore.Connection!.Query<Label>(sql, param, null) ?? Enumerable.Empty<Label>();
}

18 changes: 9 additions & 9 deletions src/GitHubExtension/DataModel/DataObjects/PullRequestStatus.cs
Original file line number Diff line number Diff line change
@@ -14,9 +14,9 @@ namespace GitHubExtension.DataModel;
[Table("PullRequestStatus")]
public class PullRequestStatus
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestStatus)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(PullRequestStatus)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -164,7 +164,7 @@ public static PullRequestStatus Create(PullRequest pullRequest)
PullRequestId = pullRequest.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var pullRequestStatus = dataStore.Connection!.QueryFirstOrDefault<PullRequestStatus>(sql, param, null);
if (pullRequestStatus is not null)
{
@@ -179,7 +179,7 @@ public static PullRequestStatus Add(DataStore dataStore, PullRequest pullRequest
{
var pullRequestStatus = Create(pullRequest);
pullRequestStatus.Id = dataStore.Connection!.Insert(pullRequestStatus);
Log.Debug($"Inserted PullRequestStatus, Id = {pullRequestStatus.Id}");
_log.Debug($"Inserted PullRequestStatus, Id = {pullRequestStatus.Id}");

// Remove older records we no longer need.
DeleteOutdatedForPullRequest(dataStore, pullRequest);
@@ -195,9 +195,9 @@ public static void DeleteOutdatedForPullRequest(DataStore dataStore, PullRequest
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$Id", pullRequest.Id);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

public static void DeleteUnreferenced(DataStore dataStore)
@@ -208,9 +208,9 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM PullRequestStatus WHERE HeadSha NOT IN (SELECT HeadSha FROM PullRequest)";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

private PullRequestCombinedStatus GetCombinedStatus()
@@ -234,7 +234,7 @@ private PullRequestCombinedStatus GetCombinedStatus()
return PullRequestCombinedStatus.Success;
}

Log.Warning($"Unknown PR Status: State={State} Status={Status} Conclusion={Conclusion}");
_log.Warning($"Unknown PR Status: State={State} Status={Status} Conclusion={Conclusion}");
return PullRequestCombinedStatus.Unknown;
}
}
14 changes: 7 additions & 7 deletions src/GitHubExtension/DataModel/DataObjects/Release.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("Release")]
public class Release
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Release)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Release)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -71,7 +71,7 @@ public static IEnumerable<Release> GetAllForRepository(DataStore dataStore, Repo
RepositoryId = repository.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var releases = dataStore.Connection!.Query<Release>(sql, param, null) ?? Enumerable.Empty<Release>();
foreach (var release in releases)
{
@@ -109,9 +109,9 @@ public static void DeleteLastObservedBefore(DataStore dataStore, long repository
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
command.Parameters.AddWithValue("$RepositoryId", repositoryId);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

private static Release CreateFromOctokitRelease(DataStore dataStore, Octokit.Release okitRelease, Repository repository)
@@ -159,8 +159,8 @@ public static void DeleteBefore(DataStore dataStore, DateTime date)
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
8 changes: 4 additions & 4 deletions src/GitHubExtension/DataModel/DataObjects/Repository.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("Repository")]
public class Repository
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Repository)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Repository)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -262,7 +262,7 @@ public static IEnumerable<Repository> GetAll(DataStore dataStore)
Owner = owner,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var repo = dataStore.Connection!.QueryFirstOrDefault<Repository>(sql, param, null);
if (repo is not null)
{
@@ -277,7 +277,7 @@ public static IEnumerable<Repository> GetAll(DataStore dataStore)
var nameSplit = fullName.Split(new[] { '/' }, 2);
if (nameSplit.Length != 2)
{
Log.Warning($"Invalid fullName input into Repository.Get: {fullName}");
_log.Warning($"Invalid fullName input into Repository.Get: {fullName}");
return null;
}

14 changes: 7 additions & 7 deletions src/GitHubExtension/DataModel/DataObjects/Review.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("Review")]
public class Review
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Review)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Review)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -100,7 +100,7 @@ private static Review CreateFromOctokitReview(DataStore dataStore, Octokit.PullR
TimeLastObserved = DateTime.UtcNow.ToDataStoreInteger(),
};

// Author is a rowid in the User table
// Author is a row id in the User table
var author = User.GetOrCreateByOctokitUser(dataStore, okitReview.User);
review.AuthorId = author.Id;

@@ -177,7 +177,7 @@ public static IEnumerable<Review> GetAllForPullRequest(DataStore dataStore, Pull
PullRequestId = pullRequest.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var reviews = dataStore.Connection!.Query<Review>(sql, param, null) ?? Enumerable.Empty<Review>();
foreach (var review in reviews)
{
@@ -195,7 +195,7 @@ public static IEnumerable<Review> GetAllForUser(DataStore dataStore, User user)
AuthorId = user.Id,
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var reviews = dataStore.Connection!.Query<Review>(sql, param, null) ?? Enumerable.Empty<Review>();
foreach (var review in reviews)
{
@@ -211,8 +211,8 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM Review WHERE PullRequestId NOT IN (SELECT Id FROM PullRequest)";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
12 changes: 6 additions & 6 deletions src/GitHubExtension/DataModel/DataObjects/Search.cs
Original file line number Diff line number Diff line change
@@ -11,12 +11,12 @@ namespace GitHubExtension.DataModel;
[Table("Search")]
public class Search
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Search)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(Search)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

// This is the time between seeing a search and updating it's TimeUpdated.
private static readonly long UpdateThreshold = TimeSpan.FromMinutes(2).Ticks;
private static readonly long _updateThreshold = TimeSpan.FromMinutes(2).Ticks;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -50,7 +50,7 @@ private static Search AddOrUpdate(DataStore dataStore, Search search)
{
// The Search time updated is for identifying stale data for deletion later.
// If it's been recently updated, don't repeatedly update it for every item in a search.
if ((search.TimeUpdated - existing.TimeUpdated) > UpdateThreshold)
if ((search.TimeUpdated - existing.TimeUpdated) > _updateThreshold)
{
search.Id = existing.Id;
dataStore.Connection!.Update(search);
@@ -97,8 +97,8 @@ public static void DeleteBefore(DataStore dataStore, DateTime date)
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
12 changes: 6 additions & 6 deletions src/GitHubExtension/DataModel/DataObjects/SearchIssue.cs
Original file line number Diff line number Diff line change
@@ -11,9 +11,9 @@ namespace GitHubExtension.DataModel;
[Table("SearchIssue")]
public class SearchIssue
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(SearchIssue)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(SearchIssue)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -68,9 +68,9 @@ public static void DeleteUnreferenced(DataStore dataStore)
var sql = @"DELETE FROM SearchIssue WHERE (Search NOT IN (SELECT Id FROM Search)) OR (Issue NOT IN (SELECT Id FROM Issue))";
var command = dataStore.Connection!.CreateCommand();
command.CommandText = sql;
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}

public static void DeleteBefore(DataStore dataStore, Search search, DateTime date)
@@ -81,8 +81,8 @@ public static void DeleteBefore(DataStore dataStore, Search search, DateTime dat
command.CommandText = sql;
command.Parameters.AddWithValue("$Time", date.ToDataStoreInteger());
command.Parameters.AddWithValue("$SearchId", search.Id);
Log.Verbose(DataStore.GetCommandLogMessage(sql, command));
_log.Verbose(DataStore.GetCommandLogMessage(sql, command));
var rowsDeleted = command.ExecuteNonQuery();
Log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
_log.Verbose(DataStore.GetDeletedLogMessage(rowsDeleted));
}
}
10 changes: 5 additions & 5 deletions src/GitHubExtension/DataModel/DataObjects/User.cs
Original file line number Diff line number Diff line change
@@ -12,14 +12,14 @@ namespace GitHubExtension.DataModel;
[Table("User")]
public class User
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(User)}"));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", $"DataModel/{nameof(User)}"));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

// This is the time between seeing a potential updated user record and updating it.
// This value / 2 is the average time between user updating their user data and having
// it reflected in the datastore.
private static readonly long UpdateThreshold = TimeSpan.FromHours(4).Ticks;
private static readonly long _updateThreshold = TimeSpan.FromHours(4).Ticks;

[Key]
public long Id { get; set; } = DataStore.NoForeignKey;
@@ -82,7 +82,7 @@ public static User AddOrUpdateUser(DataStore dataStore, User user)
// avoid unnecessary updating and database operations for data that
// is extremely unlikely to have changed in any significant way, we
// will only update every UpdateThreshold amount of time.
if ((user.TimeUpdated - existingUser.TimeUpdated) > UpdateThreshold)
if ((user.TimeUpdated - existingUser.TimeUpdated) > _updateThreshold)
{
user.Id = existingUser.Id;
dataStore.Connection!.Update(user);
@@ -156,7 +156,7 @@ public static IEnumerable<User> GetDeveloperUsers(DataStore dataStore)
DeveloperIds = GetDeveloperLoginIds(),
};

Log.Verbose(DataStore.GetSqlLogMessage(sql, param));
_log.Verbose(DataStore.GetSqlLogMessage(sql, param));
var users = dataStore.Connection!.Query<User>(sql, param) ?? Enumerable.Empty<User>();
foreach (var user in users)
{
58 changes: 29 additions & 29 deletions src/GitHubExtension/DataModel/DataStore.cs
Original file line number Diff line number Diff line change
@@ -12,9 +12,9 @@ namespace GitHubExtension.DataModel;

public class DataStore : IDisposable
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(DataStore)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(DataStore)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

public string Name { get; private set; }

@@ -24,7 +24,7 @@ public DataStore(string name, string dataStoreFilePath, IDataStoreSchema schema)
{
Name = name;
DataStoreFilePath = dataStoreFilePath;
this.schema = schema;
_schema = schema;
}

public SqliteConnection? Connection { get; private set; }
@@ -37,7 +37,7 @@ public string DataStoreFilePath
private set;
}

private readonly IDataStoreSchema schema;
private readonly IDataStoreSchema _schema;

public bool Create(bool deleteExistingDatabase = false)
{
@@ -51,22 +51,22 @@ public bool Create(bool deleteExistingDatabase = false)
{
Open();
var currentSchemaVersion = GetPragma<long>("user_version");
if (currentSchemaVersion != schema.SchemaVersion)
if (currentSchemaVersion != _schema.SchemaVersion)
{
// Any mismatch of schema is considered invalid.
// Since the data stored is functionally a cache, the simplest and most reliable.
// migration method is to delete the existing database and create anew.
deleteExistingDatabase = true;
Close();
Log.Information($"Schema mismatch. Expected: {schema.SchemaVersion} Actual: {currentSchemaVersion}");
_log.Information($"Schema mismatch. Expected: {_schema.SchemaVersion} Actual: {currentSchemaVersion}");
}
}
catch (SqliteException e)
{
// if we had a problem opening the DB and fetching the pragma, then
// we surely cannot reuse it.
deleteExistingDatabase = true;
Log.Error(e, $"Unable to open existing database to verify schema. Deleting database.");
_log.Error(e, $"Unable to open existing database to verify schema. Deleting database.");
}
}

@@ -76,7 +76,7 @@ public bool Create(bool deleteExistingDatabase = false)
}
else
{
Log.Warning($"Deleting database: {DataStoreFilePath}");
_log.Warning($"Deleting database: {DataStoreFilePath}");

if (IsConnected)
{
@@ -92,24 +92,24 @@ public bool Create(bool deleteExistingDatabase = false)
{
if ((uint)e.HResult == 0x80070020)
{
Log.Fatal(e, $"Sharing Violation Error; datastore exists and cannot be deleted ({DataStoreFilePath})");
_log.Fatal(e, $"Sharing Violation Error; datastore exists and cannot be deleted ({DataStoreFilePath})");
}
else
{
Log.Fatal(e, $"I/O Error ({DataStoreFilePath})");
_log.Fatal(e, $"I/O Error ({DataStoreFilePath})");
}
}
catch (UnauthorizedAccessException e)
{
Log.Fatal(e, $"Access Denied ({e})");
_log.Fatal(e, $"Access Denied ({e})");
}
}
}

// Report creating new if it didn't exist or it was successfully deleted.
if (!File.Exists(DataStoreFilePath))
{
Log.Information($"Creating new DataStore at {DataStoreFilePath}");
_log.Information($"Creating new DataStore at {DataStoreFilePath}");
}

// Ensure Directory exists. Sqlite open database will create a file
@@ -118,14 +118,14 @@ public bool Create(bool deleteExistingDatabase = false)
if (!Directory.Exists(directory))
{
// Create the directory.
Log.Information($"Creating root directory: {directory}");
_log.Information($"Creating root directory: {directory}");
try
{
Directory.CreateDirectory(directory!);
}
catch (Exception e)
{
Log.Fatal(e, $"Failed creating directory: ({directory})");
_log.Fatal(e, $"Failed creating directory: ({directory})");
}
}

@@ -141,20 +141,20 @@ public void Open()
{
if (Connection is not null)
{
Log.Verbose($"Connection is already open.");
_log.Verbose($"Connection is already open.");
return;
}

Log.Verbose($"Opening datastore {DataStoreFilePath}");
disposed = false;
_log.Verbose($"Opening datastore {DataStoreFilePath}");
_disposed = false;
var builder = new SqliteConnectionStringBuilder
{
DataSource = DataStoreFilePath,
Mode = SqliteOpenMode.ReadWriteCreate,
Cache = SqliteCacheMode.Shared,
};
Connection = new SqliteConnection(builder.ToString());
Log.Verbose($"SL: new SqliteConnection: {Connection.ConnectionString}");
_log.Verbose($"SL: new SqliteConnection: {Connection.ConnectionString}");

try
{
@@ -163,26 +163,26 @@ public void Open()
}
catch (SqliteException e)
{
Log.Fatal(e, $"Failed to open connection: {Connection.ConnectionString}");
_log.Fatal(e, $"Failed to open connection: {Connection.ConnectionString}");
}

Log.Debug($"Opened DataStore at {DataStoreFilePath}");
_log.Debug($"Opened DataStore at {DataStoreFilePath}");
}

private void CreateSchema()
{
Log.Debug("Creating Schema");
_log.Debug("Creating Schema");
SetPragma("encoding", "\"UTF-8\"");

using var tx = BeginTransaction();
var sqls = schema.SchemaSqls;
var sqls = _schema.SchemaSqls;
foreach (var sql in sqls)
{
Execute(sql);
}

Log.Debug($"Created schema ({sqls.Count} entities)");
SetPragma("user_version", schema.SchemaVersion);
_log.Debug($"Created schema ({sqls.Count} entities)");
SetPragma("user_version", _schema.SchemaVersion);
tx.Commit();
}

@@ -259,7 +259,7 @@ private void Execute(string sql)
}
catch (SqliteException e)
{
Log.Error(e, $"Failure executing SQL Command: {command.CommandText}");
_log.Error(e, $"Failure executing SQL Command: {command.CommandText}");
}
}

@@ -285,24 +285,24 @@ public void Close()
if (Connection != null)
{
Connection.Close();
Log.Debug("DataStore closed.");
_log.Debug("DataStore closed.");
Connection = null;
SqliteConnection.ClearAllPools();
}
}

private bool disposed; // To detect redundant calls.
private bool _disposed; // To detect redundant calls.

protected virtual void Dispose(bool disposing)
{
if (!disposed)
if (!_disposed)
{
if (disposing)
{
Close();
}

disposed = true;
_disposed = true;
}
}

8 changes: 4 additions & 4 deletions src/GitHubExtension/DataModel/DataStoreOptions.cs
Original file line number Diff line number Diff line change
@@ -13,15 +13,15 @@ public partial class DataStoreOptions
// If we directly put in the ApplicationData folder, it would fail anytime the program was not packaged.
// For use with packaged application, set in Options to:
// ApplicationData.Current.LocalFolder.Path
private readonly string dataStoreFolderPathDefault = Path.Combine(Path.GetTempPath(), "GitHubExtension");
private readonly string _dataStoreFolderPathDefault = Path.Combine(Path.GetTempPath(), "GitHubExtension");

// ApplicationData is not static, using a static folder for initialization.
private string? dataStoreFolderPath;
private string? _dataStoreFolderPath;

public string DataStoreFolderPath
{
get => dataStoreFolderPath is null ? dataStoreFolderPathDefault : dataStoreFolderPath;
set => dataStoreFolderPath = string.IsNullOrEmpty(value) ? dataStoreFolderPathDefault : value;
get => _dataStoreFolderPath is null ? _dataStoreFolderPathDefault : _dataStoreFolderPath;
set => _dataStoreFolderPath = string.IsNullOrEmpty(value) ? _dataStoreFolderPathDefault : value;
}

public IDataStoreSchema? DataStoreSchema { get; set; }
18 changes: 9 additions & 9 deletions src/GitHubExtension/DataModel/DataStoreTransaction.cs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ namespace GitHubExtension.DataModel;

public class DataStoreTransaction : IDataStoreTransaction
{
private SqliteTransaction? transaction;
private SqliteTransaction? _transaction;

public static IDataStoreTransaction BeginTransaction(DataStore dataStore)
{
@@ -24,32 +24,32 @@ public static IDataStoreTransaction BeginTransaction(DataStore dataStore)

private DataStoreTransaction(SqliteTransaction? tx)
{
transaction = tx;
_transaction = tx;
}

public void Commit()
{
transaction?.Commit();
_transaction?.Commit();
}

public void Rollback()
{
transaction?.Rollback();
_transaction?.Rollback();
}

private bool disposed; // To detect redundant calls.
private bool _disposed; // To detect redundant calls.

protected virtual void Dispose(bool disposing)
{
if (!disposed)
if (!_disposed)
{
if (disposing)
{
transaction?.Dispose();
transaction = null;
_transaction?.Dispose();
_transaction = null;
}

disposed = true;
_disposed = true;
}
}

42 changes: 21 additions & 21 deletions src/GitHubExtension/DataModel/GitHubDataStoreSchema.cs
Original file line number Diff line number Diff line change
@@ -7,7 +7,7 @@ public class GitHubDataStoreSchema : IDataStoreSchema
{
public long SchemaVersion => SchemaVersionValue;

public List<string> SchemaSqls => SchemaSqlsValue;
public List<string> SchemaSqls => _schemaSqlsValue;

public GitHubDataStoreSchema()
{
@@ -16,15 +16,15 @@ public GitHubDataStoreSchema()
// Update this anytime incompatible changes happen with a released version.
private const long SchemaVersionValue = 0x0008;

private static readonly string MetaData =
private const string MetaData =
@"CREATE TABLE MetaData (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"Key TEXT NOT NULL COLLATE NOCASE," +
"Value TEXT NULL COLLATE NOCASE" +
");" +
"CREATE UNIQUE INDEX IDX_MetaData_Key ON MetaData (Key);";

private static readonly string User =
private const string User =
@"CREATE TABLE User (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"Login TEXT NOT NULL COLLATE NOCASE," +
@@ -35,7 +35,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_User_InternalId ON User (InternalId);";

private static readonly string Repository =
private const string Repository =
@"CREATE TABLE Repository (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"OwnerId INTEGER NOT NULL," +
@@ -55,7 +55,7 @@ public GitHubDataStoreSchema()
"CREATE UNIQUE INDEX IDX_Repository_OwnerIdName ON Repository (OwnerId, Name);" +
"CREATE UNIQUE INDEX IDX_Repository_InternalId ON Repository (InternalId);";

private static readonly string Label =
private const string Label =
@"CREATE TABLE Label (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -67,7 +67,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_Label_InternalId ON Label (InternalId);";

private static readonly string Issue =
private const string Issue =
@"CREATE TABLE Issue (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -88,23 +88,23 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_Issue_InternalId ON Issue (InternalId);";

private static readonly string IssueLabel =
private const string IssueLabel =
@"CREATE TABLE IssueLabel (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"Issue INTEGER NOT NULL," +
"Label INTEGER NOT NULL" +
");" +
"CREATE UNIQUE INDEX IDX_IssueLabel_IssueLabel ON IssueLabel (Issue,Label);";

private static readonly string IssueAssign =
private const string IssueAssign =
@"CREATE TABLE IssueAssign (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"Issue INTEGER NOT NULL," +
"User INTEGER NOT NULL" +
");" +
"CREATE UNIQUE INDEX IDX_IssueAssign_IssueUser ON IssueAssign (Issue,User);";

private static readonly string PullRequest =
private const string PullRequest =
@"CREATE TABLE PullRequest (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -132,23 +132,23 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_PullRequest_InternalId ON PullRequest (InternalId);";

private static readonly string PullRequestAssign =
private const string PullRequestAssign =
@"CREATE TABLE PullRequestAssign (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"PullRequest INTEGER NOT NULL," +
"User INTEGER NOT NULL" +
");" +
"CREATE UNIQUE INDEX IDX_PullRequestAssign_PullRequestUser ON PullRequestAssign (PullRequest,User);";

private static readonly string PullRequestLabel =
private const string PullRequestLabel =
@"CREATE TABLE PullRequestLabel (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"PullRequest INTEGER NOT NULL," +
"Label INTEGER NOT NULL" +
");" +
"CREATE UNIQUE INDEX IDX_PullRequestLabel_PullRequestLabel ON PullRequestLabel (PullRequest,Label);";

private static readonly string CheckRun =
private const string CheckRun =
@"CREATE TABLE CheckRun (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -164,7 +164,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_CheckRun_InternalId ON CheckRun (InternalId);";

private static readonly string CheckSuite =
private const string CheckSuite =
@"CREATE TABLE CheckSuite (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -176,15 +176,15 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_CheckSuite_InternalId ON CheckSuite (InternalId);";

private static readonly string CommitCombinedStatus =
private const string CommitCombinedStatus =
@"CREATE TABLE CommitCombinedStatus (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"StateId INTEGER NOT NULL," +
"HeadSha TEXT NULL COLLATE NOCASE" +
");" +
"CREATE UNIQUE INDEX IDX_CommitCombinedStatus_HeadSha ON CommitCombinedStatus (HeadSha);";

private static readonly string PullRequestStatus =
private const string PullRequestStatus =
@"CREATE TABLE PullRequestStatus (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"PullRequestId INTEGER NOT NULL," +
@@ -199,7 +199,7 @@ public GitHubDataStoreSchema()
"TimeCreated INTEGER NOT NULL" +
");";

private static readonly string Notification =
private const string Notification =
@"CREATE TABLE Notification (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"TypeId INTEGER NOT NULL," +
@@ -216,7 +216,7 @@ public GitHubDataStoreSchema()
"TimeCreated INTEGER NOT NULL" +
");";

private static readonly string Search =
private const string Search =
@"CREATE TABLE Search (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"RepositoryId INTEGER NOT NULL," +
@@ -225,7 +225,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_Search_RepositoryIdQuery ON Search (RepositoryId, Query);";

private static readonly string SearchIssue =
private const string SearchIssue =
@"CREATE TABLE SearchIssue (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"TimeUpdated INTEGER NOT NULL," +
@@ -234,7 +234,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_SearchIssue_SearchIssue ON SearchIssue (Search, Issue);";

private static readonly string Review =
private const string Review =
@"CREATE TABLE Review (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -248,7 +248,7 @@ public GitHubDataStoreSchema()
");" +
"CREATE UNIQUE INDEX IDX_Review_InternalId ON Review (InternalId);";

private static readonly string Release =
private const string Release =
@"CREATE TABLE Release (" +
"Id INTEGER PRIMARY KEY NOT NULL," +
"InternalId INTEGER NOT NULL," +
@@ -264,7 +264,7 @@ public GitHubDataStoreSchema()
"CREATE UNIQUE INDEX IDX_Release_InternalId ON Release (InternalId);";

// All Sqls together.
private static readonly List<string> SchemaSqlsValue = new()
private static readonly List<string> _schemaSqlsValue = new()
{
MetaData,
User,
18 changes: 9 additions & 9 deletions src/GitHubExtension/DeveloperId/CredentialVault.cs
Original file line number Diff line number Diff line change
@@ -12,9 +12,9 @@ namespace GitHubExtension.DeveloperId;

public class CredentialVault : ICredentialVault
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(CredentialVault)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(CredentialVault)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

private readonly string _credentialResourceName;

@@ -56,15 +56,15 @@ public void SaveCredentials(string loginId, SecureString? accessToken)
}
else
{
Log.Information($"The access token is null for the loginId provided");
_log.Information($"The access token is null for the loginId provided");
throw new ArgumentNullException(nameof(accessToken));
}

// Store credential under Windows Credentials inside Credential Manager.
var isCredentialSaved = CredWrite(credential, 0);
if (!isCredentialSaved)
{
Log.Information($"Writing credentials to Credential Manager has failed");
_log.Information($"Writing credentials to Credential Manager has failed");
throw new Win32Exception(Marshal.GetLastWin32Error());
}
}
@@ -88,7 +88,7 @@ public void SaveCredentials(string loginId, SecureString? accessToken)
if (!isCredentialRetrieved)
{
var error = Marshal.GetLastWin32Error();
Log.Error($"Retrieving credentials from Credential Manager has failed for {loginId} with {error}");
_log.Error($"Retrieving credentials from Credential Manager has failed for {loginId} with {error}");

// NotFound is expected and can be ignored.
if (error == Win32ErrorNotFound)
@@ -109,7 +109,7 @@ public void SaveCredentials(string loginId, SecureString? accessToken)
}
else
{
Log.Error($"No credentials found for this DeveloperId : {loginId}");
_log.Error($"No credentials found for this DeveloperId : {loginId}");
return null;
}

@@ -130,7 +130,7 @@ public void SaveCredentials(string loginId, SecureString? accessToken)
}
catch (Exception ex)
{
Log.Error(ex, $"Retrieving credentials from Credential Manager has failed unexpectedly: {loginId} : ");
_log.Error(ex, $"Retrieving credentials from Credential Manager has failed unexpectedly: {loginId} : ");
throw;
}
finally
@@ -148,7 +148,7 @@ public void RemoveCredentials(string loginId)
var isCredentialDeleted = CredDelete(targetCredentialToDelete, CRED_TYPE.GENERIC, 0);
if (!isCredentialDeleted)
{
Log.Error($"Deleting credentials from Credential Manager has failed for {loginId}");
_log.Error($"Deleting credentials from Credential Manager has failed for {loginId}");
}
}

@@ -217,7 +217,7 @@ public void RemoveAllCredentials()
}
catch (Exception ex)
{
Log.Error(ex, $"Deleting credentials from Credential Manager has failed unexpectedly: {credential} : ");
_log.Error(ex, $"Deleting credentials from Credential Manager has failed unexpectedly: {credential} : ");
}
}
}
52 changes: 26 additions & 26 deletions src/GitHubExtension/DeveloperId/DeveloperIdProvider.cs
Original file line number Diff line number Diff line change
@@ -14,9 +14,9 @@ namespace GitHubExtension.DeveloperId;

public class DeveloperIdProvider : IDeveloperIdProviderInternal
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(DeveloperIdProvider)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(DeveloperIdProvider)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

// Locks to control access to Singleton class members.
private static readonly object _developerIdsLock = new();
@@ -39,7 +39,7 @@ private List<OAuthRequest> OAuthRequests

public event TypedEventHandler<IDeveloperIdProvider, IDeveloperId>? Changed;

private readonly AuthenticationExperienceKind authenticationExperienceForGitHubExtension = AuthenticationExperienceKind.CardSession;
private readonly AuthenticationExperienceKind _authenticationExperienceForGitHubExtension = AuthenticationExperienceKind.CardSession;

public string DisplayName => "GitHub";

@@ -54,7 +54,7 @@ public static DeveloperIdProvider GetInstance()
// Private constructor for Singleton class.
private DeveloperIdProvider()
{
Log.Information($"Creating DeveloperIdProvider singleton instance");
_log.Information($"Creating DeveloperIdProvider singleton instance");

_credentialVault = new(() => new CredentialVault());

@@ -75,7 +75,7 @@ private DeveloperIdProvider()
}
catch (Exception ex)
{
Log.Error(ex, $"Error while restoring DeveloperIds: {ex.Message}. Proceeding without restoring.");
_log.Error(ex, $"Error while restoring DeveloperIds: {ex.Message}. Proceeding without restoring.");
}
}

@@ -99,7 +99,7 @@ public IAsyncOperation<IDeveloperId> LoginNewDeveloperIdAsync()
var oauthRequest = LoginNewDeveloperId();
if (oauthRequest is null)
{
Log.Error($"Invalid OAuthRequest");
_log.Error($"Invalid OAuthRequest");
throw new InvalidOperationException();
}

@@ -108,7 +108,7 @@ public IAsyncOperation<IDeveloperId> LoginNewDeveloperIdAsync()
var devId = CreateOrUpdateDeveloperIdFromOauthRequest(oauthRequest);
oauthRequest.Dispose();

Log.Information($"New DeveloperId logged in");
_log.Information($"New DeveloperId logged in");

return devId as IDeveloperId;
}).AsAsyncOperation();
@@ -125,13 +125,13 @@ public DeveloperId LoginNewDeveloperIdWithPAT(Uri hostAddress, SecureString pers
DeveloperId developerId = new(newUser.Login, newUser.Name, newUser.Email, newUser.Url, gitHubClient);
SaveOrOverwriteDeveloperId(developerId, personalAccessToken);

Log.Information($"{developerId.LoginId} logged in with PAT flow to {developerId.GetHostAddress()}");
_log.Information($"{developerId.LoginId} logged in with PAT flow to {developerId.GetHostAddress()}");

return developerId;
}
catch (Exception ex)
{
Log.Error(ex, $"Error while logging in with PAT to {hostAddress.AbsoluteUri} : ");
_log.Error(ex, $"Error while logging in with PAT to {hostAddress.AbsoluteUri} : ");
throw;
}
}
@@ -151,7 +151,7 @@ public DeveloperId LoginNewDeveloperIdWithPAT(Uri hostAddress, SecureString pers
catch (Exception ex)
{
OAuthRequests.Remove(oauthRequest);
Log.Error(ex, $"Unable to complete OAuth request: ");
_log.Error(ex, $"Unable to complete OAuth request: ");
}
}

@@ -166,7 +166,7 @@ public ProviderOperationResult LogoutDeveloperId(IDeveloperId developerId)
developerIdToLogout = DeveloperIds?.Find(e => e.LoginId == developerId.LoginId);
if (developerIdToLogout == null)
{
Log.Error($"Unable to find DeveloperId to logout");
_log.Error($"Unable to find DeveloperId to logout");
return new ProviderOperationResult(ProviderOperationStatus.Failure, new ArgumentNullException(nameof(developerId)), "The developer account to log out does not exist", "Unable to find DeveloperId to logout");
}

@@ -180,7 +180,7 @@ public ProviderOperationResult LogoutDeveloperId(IDeveloperId developerId)
}
catch (Exception ex)
{
Log.Error(ex, $"LoggedOut event signaling failed: ");
_log.Error(ex, $"LoggedOut event signaling failed: ");
}

return new ProviderOperationResult(ProviderOperationStatus.Success, null, "The developer account has been logged out successfully", "LogoutDeveloperId succeeded");
@@ -201,7 +201,7 @@ public void HandleOauthRedirection(Uri authorizationResponse)
{
// This could happen if the user refreshes the redirected browser window
// causing the OAuth response to be received again.
Log.Warning($"No saved OAuth requests to match OAuth response");
_log.Warning($"No saved OAuth requests to match OAuth response");
return;
}

@@ -213,7 +213,7 @@ public void HandleOauthRedirection(Uri authorizationResponse)
{
// This could happen if the user refreshes a previously redirected browser window instead of using
// the new browser window for the response. Log the warning and return.
Log.Warning($"Unable to find valid request for received OAuth response");
_log.Warning($"Unable to find valid request for received OAuth response");
return;
}
else
@@ -252,7 +252,7 @@ private void SaveOrOverwriteDeveloperId(DeveloperId newDeveloperId, SecureString

if (duplicateDeveloperIds.Any())
{
Log.Information($"DeveloperID already exists! Updating accessToken");
_log.Information($"DeveloperID already exists! Updating accessToken");
try
{
// Save the credential to Credential Vault.
@@ -264,12 +264,12 @@ private void SaveOrOverwriteDeveloperId(DeveloperId newDeveloperId, SecureString
}
catch (Exception ex)
{
Log.Error(ex, $"Updated event signaling failed: ");
_log.Error(ex, $"Updated event signaling failed: ");
}
}
catch (InvalidOperationException)
{
Log.Warning($"Multiple copies of same DeveloperID already exists");
_log.Warning($"Multiple copies of same DeveloperID already exists");
throw new InvalidOperationException("Multiple copies of same DeveloperID already exists");
}
}
@@ -288,7 +288,7 @@ private void SaveOrOverwriteDeveloperId(DeveloperId newDeveloperId, SecureString
}
catch (Exception ex)
{
Log.Error(ex, $"LoggedIn event signaling failed: ");
_log.Error(ex, $"LoggedIn event signaling failed: ");
}
}
}
@@ -300,13 +300,13 @@ private DeveloperId CreateOrUpdateDeveloperIdFromOauthRequest(OAuthRequest oauth
var accessToken = oauthRequest.AccessToken;
if (accessToken is null)
{
Log.Error($"Invalid AccessToken");
_log.Error($"Invalid AccessToken");
throw new InvalidOperationException();
}

SaveOrOverwriteDeveloperId(newDeveloperId, accessToken);

Log.Information($"{newDeveloperId.LoginId} logged in with OAuth flow to {newDeveloperId.GetHostAddress()}");
_log.Information($"{newDeveloperId.LoginId} logged in with OAuth flow to {newDeveloperId.GetHostAddress()}");

return newDeveloperId;
}
@@ -340,7 +340,7 @@ private void RestoreDeveloperIds(IEnumerable<string> loginIdsAndUrls)
DeveloperIds.Add(developerId);
}

Log.Information($"Restored DeveloperId {user.Url}");
_log.Information($"Restored DeveloperId {user.Url}");

// If loginId is currently used to save credential, remove it, and use URL instead.
if (!isUrl)
@@ -350,7 +350,7 @@ private void RestoreDeveloperIds(IEnumerable<string> loginIdsAndUrls)
}
catch (Exception ex)
{
Log.Error(ex, $"Error while restoring DeveloperId {loginIdOrUrl} : ");
_log.Error(ex, $"Error while restoring DeveloperId {loginIdOrUrl} : ");

// If we are unable to restore a DeveloperId, remove it from CredentialManager to avoid
// the same error next time, and to force the user to login again
@@ -369,11 +369,11 @@ private void ReplaceSavedLoginIdWithUrl(DeveloperId developerId)
developerId.Url,
new NetworkCredential(string.Empty, _credentialVault.Value.GetCredentials(developerId.LoginId)?.Password).SecurePassword);
_credentialVault.Value.RemoveCredentials(developerId.LoginId);
Log.Information($"Replaced {developerId.LoginId} with {developerId.Url} in CredentialManager");
_log.Information($"Replaced {developerId.LoginId} with {developerId.Url} in CredentialManager");
}
catch (Exception ex)
{
Log.Error(ex, $"Error while replacing {developerId.LoginId} with {developerId.Url} in CredentialManager: ");
_log.Error(ex, $"Error while replacing {developerId.LoginId} with {developerId.Url} in CredentialManager: ");
}
}

@@ -384,12 +384,12 @@ internal void RefreshDeveloperId(IDeveloperId developerIdInternal)

public AuthenticationExperienceKind GetAuthenticationExperienceKind()
{
return authenticationExperienceForGitHubExtension;
return _authenticationExperienceForGitHubExtension;
}

public AdaptiveCardSessionResult GetLoginAdaptiveCardSession()
{
Log.Information($"GetAdaptiveCardController");
_log.Information($"GetAdaptiveCardController");
return new AdaptiveCardSessionResult(new LoginUIController(this));
}

Original file line number Diff line number Diff line change
@@ -16,7 +16,8 @@ public EnterpriseServerPATPage(Uri hostAddress, string errorText, SecureString i
EnterpriseServerPATPageInputValue = new System.Net.NetworkCredential(string.Empty, inputPAT).Password ?? string.Empty,
EnterpriseServerPATPageErrorValue = errorText ?? string.Empty,
EnterpriseServerPATPageErrorVisible = !string.IsNullOrEmpty(errorText),
EnterpriseServerPATPageCreatePATUrlValue = hostAddress?.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + $"/settings/tokens/new?scopes=read:user,notifications,repo,read:org&description=DevHomeGitHubExtension",
EnterpriseServerPATPageCreatePATUrlValue = hostAddress?.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped)
+ $"/settings/tokens/new?scopes=read:user,notifications,repo,read:org&description=DevHomeGitHubExtension",
EnterpriseServerPATPageServerUrlValue = hostAddress?.Host ?? string.Empty,
};
}
68 changes: 34 additions & 34 deletions src/GitHubExtension/DeveloperId/LoginUIController.cs

Large diffs are not rendered by default.

44 changes: 22 additions & 22 deletions src/GitHubExtension/DeveloperId/OAuthRequest.cs
Original file line number Diff line number Diff line change
@@ -13,9 +13,9 @@ namespace GitHubExtension.DeveloperId;

internal class OAuthRequest : IDisposable
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(OAuthRequest)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(OAuthRequest)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

internal string State { get; private set; }

@@ -28,16 +28,16 @@ internal DateTime StartTime

internal OAuthRequest()
{
gitHubClient = new(new ProductHeaderValue(Constants.DEV_HOME_APPLICATION_NAME));
oAuthCompleted = new(0);
_gitHubClient = new(new ProductHeaderValue(Constants.DEV_HOME_APPLICATION_NAME));
_oAuthCompleted = new(0);
State = string.Empty;
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
oAuthCompleted.Dispose();
_oAuthCompleted.Dispose();
}
}

@@ -49,7 +49,7 @@ public void Dispose()

public void AwaitCompletion()
{
oAuthCompleted?.Wait();
_oAuthCompleted?.Wait();
}

private Uri CreateOauthRequestUri()
@@ -63,7 +63,7 @@ private Uri CreateOauthRequestUri()
RedirectUri = new Uri(OauthConfiguration.RedirectUri),
};

return gitHubClient.Oauth.GetGitHubLoginUrl(request);
return _gitHubClient.Oauth.GetGitHubLoginUrl(request);
}

internal void BeginOAuthRequest()
@@ -80,11 +80,11 @@ internal void BeginOAuthRequest()

if (browserLaunch)
{
Log.Information($"Uri Launched - Check browser");
_log.Information($"Uri Launched - Check browser");
}
else
{
Log.Error($"Uri Launch failed");
_log.Error($"Uri Launch failed");
}
});
}
@@ -99,13 +99,13 @@ internal async Task CompleteOAuthAsync(Uri authorizationResponse)

if (!string.IsNullOrEmpty(queryStringCollection.Get("error")))
{
Log.Error($"OAuth authorization error: {queryStringCollection.Get("error")}");
_log.Error($"OAuth authorization error: {queryStringCollection.Get("error")}");
throw new UriFormatException();
}

if (string.IsNullOrEmpty(queryStringCollection.Get("code")))
{
Log.Error($"Malformed authorization response: {queryString}");
_log.Error($"Malformed authorization response: {queryString}");
throw new UriFormatException();
}

@@ -115,30 +115,30 @@ internal async Task CompleteOAuthAsync(Uri authorizationResponse)
try
{
var request = new OauthTokenRequest(OauthConfiguration.GetClientId(), OauthConfiguration.GetClientSecret(), code);
var token = await gitHubClient.Oauth.CreateAccessToken(request);
var token = await _gitHubClient.Oauth.CreateAccessToken(request);
AccessToken = new NetworkCredential(string.Empty, token.AccessToken).SecurePassword;
gitHubClient.Credentials = new Credentials(token.AccessToken);
_gitHubClient.Credentials = new Credentials(token.AccessToken);
}
catch (Exception ex)
{
Log.Error($"Authorization code exchange failed: {ex}");
_log.Error($"Authorization code exchange failed: {ex}");
throw;
}

Log.Information($"Authorization code exchange completed");
oAuthCompleted.Release();
_log.Information($"Authorization code exchange completed");
_oAuthCompleted.Release();
}

internal DeveloperId RetrieveDeveloperId()
{
if (AccessToken is null)
{
Log.Error($"RetrieveDeveloperIdData called before AccessToken is set");
_log.Error($"RetrieveDeveloperIdData called before AccessToken is set");
throw new InvalidOperationException("RetrieveDeveloperIdData called before AccessToken is set");
}

var newUser = gitHubClient.User.Current().Result;
DeveloperId developerId = new(newUser.Login, newUser.Name, newUser.Email, newUser.Url, gitHubClient);
var newUser = _gitHubClient.User.Current().Result;
DeveloperId developerId = new(newUser.Login, newUser.Name, newUser.Email, newUser.Url, _gitHubClient);

return developerId;
}
@@ -155,7 +155,7 @@ internal static string RetrieveState(Uri authorizationResponse)

if (string.IsNullOrEmpty(state))
{
Log.Error($"Authorization code exchange failed: ResponseString:{queryString}");
_log.Error($"Authorization code exchange failed: ResponseString:{queryString}");
throw new UriFormatException();
}

@@ -168,6 +168,6 @@ private static string GetRandomNumber()
return randomNumber.ToStringInvariant();
}

private readonly SemaphoreSlim oAuthCompleted;
private readonly GitHubClient gitHubClient;
private readonly SemaphoreSlim _oAuthCompleted;
private readonly GitHubClient _gitHubClient;
}
84 changes: 84 additions & 0 deletions src/GitHubExtension/Helpers/IconData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

namespace GitHubExtension.Helpers;

internal class IconData
{
public const string AssignedWidgetTitleIconData =
"iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABGdBTUEAALG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uMcKEj4/n6a3OQfYQS7BpyWWmdiIDH" +
"W2+XsCNN5MdnNZw38ksp1Odyag9m4AD1g0f1QBnmA2WUN5HPim5V7jiPIsneZsCMdjHvmn" +
"ZBE9QJ5KFrH0dFXqxnYisOz0HtBybqufmgwMDAwMDFWCmpq/ANfVYnfzsINAAAAAAElFTkSuQmCC";
}
8 changes: 4 additions & 4 deletions src/GitHubExtension/Helpers/IconLoader.cs
Original file line number Diff line number Diff line change
@@ -7,19 +7,19 @@ namespace GitHubExtension.Helpers;

public class IconLoader
{
private static readonly Dictionary<string, string> Base64ImageRegistry = new();
private static readonly Dictionary<string, string> _base64ImageRegistry = new();

public static string GetIconAsBase64(string filename)
{
var log = Log.ForContext("SourceContext", nameof(IconLoader));
log.Verbose($"Asking for icon: {filename}");
if (!Base64ImageRegistry.ContainsKey(filename))
if (!_base64ImageRegistry.ContainsKey(filename))
{
Base64ImageRegistry.Add(filename, ConvertIconToDataString(filename));
_base64ImageRegistry.Add(filename, ConvertIconToDataString(filename));
log.Verbose($"The icon {filename} was converted and is now stored.");
}

return Base64ImageRegistry[filename];
return _base64ImageRegistry[filename];
}

private static string ConvertIconToDataString(string fileName)
10 changes: 5 additions & 5 deletions src/GitHubExtension/Notifications/NotificationHandler.cs
Original file line number Diff line number Diff line change
@@ -12,17 +12,17 @@ namespace GitHubExtension.Notifications;

public class NotificationHandler
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(NotificationHandler)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(NotificationHandler)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

#pragma warning disable IDE0060 // Remove unused parameter
public static void OnNotificationInvoked(object sender, AppNotificationActivatedEventArgs args) => NotificationActivation(args);
#pragma warning restore IDE0060 // Remove unused parameter

public static void NotificationActivation(AppNotificationActivatedEventArgs args)
{
Log.Information($"Notification Activated with args: {NotificationArgsToString(args)}");
_log.Information($"Notification Activated with args: {NotificationArgsToString(args)}");

if (args.Arguments.ContainsKey("htmlurl"))
{
@@ -36,7 +36,7 @@ public static void NotificationActivation(AppNotificationActivatedEventArgs args
throw new InvalidGitHubUrlException($"{urlString} is invalid.");
}

Log.Information($"Launching Uri: {urlString}");
_log.Information($"Launching Uri: {urlString}");
var processStartInfo = new ProcessStartInfo
{
UseShellExecute = true,
@@ -47,7 +47,7 @@ public static void NotificationActivation(AppNotificationActivatedEventArgs args
}
catch (Exception ex)
{
Log.Error(ex, $"Failed launching Uri for {args.Arguments["htmlurl"]}");
_log.Error(ex, $"Failed launching Uri for {args.Arguments["htmlurl"]}");
}

return;
16 changes: 8 additions & 8 deletions src/GitHubExtension/Notifications/NotificationManager.cs
Original file line number Diff line number Diff line change
@@ -8,18 +8,18 @@ namespace GitHubExtension.Notifications;

public class NotificationManager
{
private static readonly Lazy<ILogger> _log = new(() => Serilog.Log.ForContext("SourceContext", nameof(NotificationManager)));
private static readonly Lazy<ILogger> _logger = new(() => Serilog.Log.ForContext("SourceContext", nameof(NotificationManager)));

private static readonly ILogger Log = _log.Value;
private static readonly ILogger _log = _logger.Value;

private bool isRegistered;
private bool _isRegistered;

public NotificationManager(Windows.Foundation.TypedEventHandler<AppNotificationManager, AppNotificationActivatedEventArgs> handler)
{
AppNotificationManager.Default.NotificationInvoked += handler;
AppNotificationManager.Default.Register();
isRegistered = true;
Log.Information($"NotificationManager created and registered.");
_isRegistered = true;
_log.Information($"NotificationManager created and registered.");
}

~NotificationManager()
@@ -29,11 +29,11 @@ public NotificationManager(Windows.Foundation.TypedEventHandler<AppNotificationM

public void Unregister()
{
if (isRegistered)
if (_isRegistered)
{
AppNotificationManager.Default.Unregister();
isRegistered = false;
Log.Information($"NotificationManager unregistered.");
_isRegistered = false;
_log.Information($"NotificationManager unregistered.");
}
}
}
14 changes: 7 additions & 7 deletions src/GitHubExtension/Providers/DevHomeRepository.cs
Original file line number Diff line number Diff line change
@@ -8,32 +8,32 @@ namespace GitHubExtension.Providers;
// Microsoft.Windows.DevHome.SDK.IRepository Implementation
public class DevHomeRepository : Microsoft.Windows.DevHome.SDK.IRepository
{
private readonly string name;
private readonly string _name;

private readonly Uri cloneUrl;
private readonly Uri _cloneUrl;

private readonly bool _isPrivate;

private readonly DateTimeOffset _lastUpdated;

string Microsoft.Windows.DevHome.SDK.IRepository.DisplayName => name;
string Microsoft.Windows.DevHome.SDK.IRepository.DisplayName => _name;

public string OwningAccountName => Validation.ParseOwnerFromGitHubURL(this.cloneUrl);
public string OwningAccountName => Validation.ParseOwnerFromGitHubURL(_cloneUrl);

public bool IsPrivate => _isPrivate;

public DateTimeOffset LastUpdated => _lastUpdated;

public Uri RepoUri => cloneUrl;
public Uri RepoUri => _cloneUrl;

/// <summary>
/// Initializes a new instance of the <see cref="DevHomeRepository"/> class.
/// </summary>
/// <param name="octokitRepository">The repository received from octokit</param>
public DevHomeRepository(Octokit.Repository octokitRepository)
{
this.name = octokitRepository.Name;
this.cloneUrl = new Uri(octokitRepository.CloneUrl);
_name = octokitRepository.Name;
_cloneUrl = new Uri(octokitRepository.CloneUrl);

_lastUpdated = octokitRepository.UpdatedAt;
_isPrivate = octokitRepository.Private;
Loading

0 comments on commit 9b013b6

Please sign in to comment.