Warning if not using 'simple using'

This commit is contained in:
nicolas.dorier 2022-01-14 17:50:29 +09:00
parent c6a7e90c1a
commit 50d4b55f73
No known key found for this signature in database
GPG Key ID: 6618763EF09186FE
40 changed files with 5355 additions and 5732 deletions

View File

@ -122,6 +122,7 @@ csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
csharp_style_prefer_null_check_over_type_check = true:warning
csharp_prefer_simple_using_statement = true:warning
# C++ Files

View File

@ -21,12 +21,10 @@ namespace BTCPayServer
public static string Unzip(byte[] bytes)
{
MemoryStream ms = new MemoryStream(bytes);
using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress))
{
using GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);
StreamReader reader = new StreamReader(gzip, Encoding.UTF8);
var unzipped = reader.ReadToEnd();
return unzipped;
}
}
}
}

View File

@ -35,8 +35,7 @@ namespace BTCPayServer.Tests
//as a user through your profile
//as an external application requesting an api key from a user
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
var tester = s.Server;
@ -195,7 +194,6 @@ namespace BTCPayServer.Tests
var apikeydata = await TestApiAgainstAccessToken<ApiKeyData>(allAPIKey, $"api/v1/api-keys/current", tester.PayTester.HttpClient);
Assert.Equal(checkedPermissionCount, apikeydata.Permissions.Length);
}
}
async Task TestApiAgainstAccessToken(string accessToken, ServerTester tester, TestAccount testAccount,
params string[] expectedPermissionsArr)

View File

@ -243,11 +243,9 @@ namespace BTCPayServer.Tests
private async Task WaitSiteIsOperational()
{
_ = HttpClient.GetAsync("/").ConfigureAwait(false);
using (var cts = new CancellationTokenSource(20_000))
{
using var cts = new CancellationTokenSource(20_000);
var synching = WaitIsFullySynched(cts.Token);
await Task.WhenAll(synching).ConfigureAwait(false);
}
// Opportunistic call to wake up view compilation in debug mode, we don't need to await.
}

View File

@ -23,8 +23,7 @@ namespace BTCPayServer.Tests
public async Task CanHandleRefundEmailForm()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.GoToRegister();
s.RegisterNewUser();
@ -67,14 +66,12 @@ namespace BTCPayServer.Tests
s.Driver.Navigate().Refresh();
s.Driver.AssertElementNotFound(By.Id("emailAddressFormInput"));
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanHandleRefundEmailForm2()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
// Prepare user account and store
await s.StartAsync();
s.GoToRegister();
@ -129,13 +126,11 @@ namespace BTCPayServer.Tests
s.Driver.Navigate().Refresh();
s.Driver.AssertElementNotFound(By.Id("emailAddressFormInput"));
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseLanguageDropdown()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.GoToRegister();
s.RegisterNewUser();
@ -159,14 +154,12 @@ namespace BTCPayServer.Tests
s.Driver.Quit();
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Lightning", "Lightning")]
public async Task CanSetDefaultPaymentMethod()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
s.Server.ActivateLightning();
await s.StartAsync();
s.GoToRegister();
@ -181,14 +174,12 @@ namespace BTCPayServer.Tests
Assert.Equal("Bitcoin (Lightning) (BTC)", s.Driver.FindElement(By.ClassName("payment__currencies")).Text);
s.Driver.Quit();
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Lightning", "Lightning")]
public async Task CanUseLightningSatsFeature()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
s.Server.ActivateLightning();
await s.StartAsync();
s.GoToRegister();
@ -205,13 +196,11 @@ namespace BTCPayServer.Tests
s.GoToInvoiceCheckout(invoiceId);
Assert.Contains("Sats", s.Driver.FindElement(By.ClassName("payment__currencies_noborder")).Text);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseJSModal()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.GoToRegister();
s.RegisterNewUser();
@ -245,5 +234,4 @@ namespace BTCPayServer.Tests
new Uri(s.ServerUri, $"tests/index.html?invoice={invoiceId}").ToString());
}
}
}
}

View File

@ -26,8 +26,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanCreateAndDeleteCrowdfundApp()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -60,14 +59,12 @@ namespace BTCPayServer.Tests
appList = Assert.IsType<ListAppsViewModel>(Assert.IsType<ViewResult>(apps.ListApps(user.StoreId).Result).Model);
Assert.Empty(appList.Apps);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanContributeOnlyWhenAllowed()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -149,14 +146,12 @@ namespace BTCPayServer.Tests
Amount = new decimal(0.05)
}, default));
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanComputeCrowdfundModel()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -277,5 +272,4 @@ namespace BTCPayServer.Tests
});
}
}
}
}

View File

@ -42,8 +42,7 @@ namespace BTCPayServer.Tests
public async Task<JObject> GetNextRequest()
{
using (CancellationTokenSource cancellation = new CancellationTokenSource(2000000))
{
using CancellationTokenSource cancellation = new CancellationTokenSource(2000000);
try
{
JObject req = null;
@ -59,7 +58,6 @@ namespace BTCPayServer.Tests
throw new Xunit.Sdk.XunitException("Callback to the webserver was expected, check if the callback url is accessible from internet");
}
}
}
public void Dispose()
{

View File

@ -60,8 +60,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task MissingPermissionTest()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -72,14 +71,12 @@ namespace BTCPayServer.Tests
GreenfieldPermissionAPIError permissionError = Assert.IsType<GreenfieldPermissionAPIError>(e.APIError);
Assert.Equal(permissionError.MissingPermission, Policies.CanModifyStoreSettings);
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task ApiKeysControllerTests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -101,7 +98,6 @@ namespace BTCPayServer.Tests
//a client using Basic Auth has no business here
await AssertHttpError(401, async () => await clientBasic.RevokeCurrentAPIKeyInfo());
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
@ -129,8 +125,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task SpecificCanModifyStoreCantCreateNewStore()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
await acc.GrantAccessAsync();
@ -148,14 +143,12 @@ namespace BTCPayServer.Tests
restricted = new BTCPayServerClient(unrestricted.Host, apiKey);
await restricted.CreateStore(new CreateStoreRequest() { Name = "store2" });
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanCreateAndDeleteAPIKeyViaAPI()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
await acc.GrantAccessAsync();
@ -180,7 +173,6 @@ namespace BTCPayServer.Tests
await unrestricted.RevokeAPIKey(apiKey.ApiKey);
await AssertAPIError("apikey-not-found", () => unrestricted.RevokeAPIKey(apiKey.ApiKey));
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
@ -225,8 +217,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanCreateUsersViaAPI()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
tester.PayTester.DisableRegistration = true;
await tester.StartAsync();
var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri);
@ -354,16 +345,13 @@ namespace BTCPayServer.Tests
new CreateApplicationUserRequest() { Email = "test9@gmail.com", Password = "afewfoiewiou" }));
await adminClient.CreateUser(
new CreateApplicationUserRequest() { Email = "test9@gmail.com", Password = "afewfoiewiou" });
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUsePullPaymentViaAPI()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.Register();
@ -595,7 +583,6 @@ namespace BTCPayServer.Tests
Assert.Equal(PayoutState.Completed, payout.State);
await AssertAPIError("invalid-state", async () => await client.MarkPayoutPaid(storeId, payout.Id));
}
}
private DateTimeOffset RoundSeconds(DateTimeOffset dateTimeOffset)
{
@ -620,8 +607,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task StoresControllerTests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -673,7 +659,6 @@ namespace BTCPayServer.Tests
await ctx.SaveChangesAsync();
await AssertHttpError(403, async () => await client.UpdateStore(newStore.Id, new UpdateStoreRequest() { Name = "B" }));
}
}
private async Task<GreenfieldValidationException> AssertValidationError(string[] fields, Func<Task> act)
{
@ -698,8 +683,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task UsersControllerTests()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
tester.PayTester.DisableRegistration = true;
await tester.StartAsync();
var user = tester.NewAccount();
@ -758,7 +742,6 @@ namespace BTCPayServer.Tests
await clientServer.CreateUser(
new CreateApplicationUserRequest() { Password = Guid.NewGuid().ToString() }));
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
@ -865,8 +848,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task HealthControllerTests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri);
@ -874,14 +856,12 @@ namespace BTCPayServer.Tests
Assert.NotNull(apiHealthData);
Assert.True(apiHealthData.Synchronized);
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task ServerInfoControllerTests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var unauthClient = new BTCPayServerClient(tester.PayTester.ServerUri);
await AssertHttpError(401, async () => await unauthClient.GetServerInfo());
@ -899,14 +879,12 @@ namespace BTCPayServer.Tests
Assert.NotNull(serverInfoData.SyncStatus);
Assert.Single(serverInfoData.SyncStatus.Select(s => s.CryptoCode == "BTC"));
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
public async Task PaymentControllerTests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -991,7 +969,6 @@ namespace BTCPayServer.Tests
Assert.Equal(PaymentRequestData.PaymentRequestStatus.Completed, (await client.GetPaymentRequest(user.StoreId, paymentTestPaymentRequest.Id)).Status);
});
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
@ -1065,8 +1042,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanOverpayInvoice()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.RegisterDerivationSchemeAsync("BTC");
@ -1091,7 +1067,6 @@ namespace BTCPayServer.Tests
Assert.Equal(amount + 1.0m, method.TotalPaid);
});
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]
@ -1440,8 +1415,7 @@ namespace BTCPayServer.Tests
[Trait("Lightning", "Lightning")]
public async Task CanUseLightningAPI()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
await tester.EnsureChannelsSetup();
@ -1542,7 +1516,6 @@ namespace BTCPayServer.Tests
// Can use lightning node is only granted to store's owner
await AssertPermissionError("btcpay.store.canuselightningnode", () => client.GetLightningNodeInfo(user.StoreId, "BTC"));
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Integration", "Integration")]

View File

@ -18,8 +18,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanAutoDetectLanguage()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var languageService = tester.PayTester.GetService<LanguageService>();
@ -47,5 +46,4 @@ namespace BTCPayServer.Tests
Assert.Null(lang4);
}
}
}
}

View File

@ -22,8 +22,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanUsePoSApp1()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -69,5 +68,4 @@ donation:
.ViewPointOfSale(app.Id, PosViewType.Cart, 0, null, null, null, null, "apple").Result);
}
}
}
}

View File

@ -23,8 +23,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanPlayWithPSBT()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -135,7 +134,6 @@ namespace BTCPayServer.Tests
UploadedPSBTFile = TestUtils.GetFormFile("base64", signedPSBT.ToBase64())
})).Model).PSBT));
}
}
private static string AssertRedirectedPSBT(IActionResult view, string actionName)
{

View File

@ -46,8 +46,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanUseTheDelayedBroadcaster()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var network = tester.NetworkProvider.GetNetwork<BTCPayNetwork>("BTC");
var broadcaster = tester.PayTester.GetService<DelayedTransactionBroadcaster>();
@ -62,13 +61,11 @@ namespace BTCPayServer.Tests
Assert.Equal(1, await broadcaster.ProcessAll());
Assert.Equal(0, await broadcaster.ProcessAll());
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUsePayjoinRepository()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var network = tester.NetworkProvider.GetNetwork<BTCPayNetwork>("BTC");
var repo = tester.PayTester.GetService<PayJoinRepository>();
@ -101,14 +98,12 @@ namespace BTCPayServer.Tests
Assert.False(await repo.TryLockInputs(new[] { outpoint2, outpoint1 }));
Assert.True(await repo.TryLockInputs(new[] { outpoint2 }));
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task ChooseBestUTXOsForPayjoin()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var network = tester.NetworkProvider.GetNetwork<BTCPayNetwork>("BTC");
var controller = tester.PayTester.GetService<PayJoinEndpointController>();
@ -138,7 +133,6 @@ namespace BTCPayServer.Tests
result = await controller.SelectUTXO(network, utxos, inputs, paymentAmount, otherOutputs);
Assert.Equal(PayJoinEndpointController.PayjoinUtxoSelectionType.HeuristicBased, result.selectionType);
}
}
@ -168,8 +162,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanOnlyUseCorrectAddressFormatsForPayjoin()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var broadcaster = tester.PayTester.GetService<DelayedTransactionBroadcaster>();
var payjoinRepository = tester.PayTester.GetService<PayJoinRepository>();
@ -222,16 +215,13 @@ namespace BTCPayServer.Tests
var pj = await senderUser.SubmitPayjoin(invoice, psbt, errorCode, false);
}
}
}
}
[Fact]
[Trait("Selenium", "Selenium")]
public async Task CanUsePayjoinForTopUp()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
var receiver = s.CreateNewStore();
@ -275,14 +265,12 @@ namespace BTCPayServer.Tests
Assert.Equal(0.023m, invoice.Price);
});
}
}
[Fact]
[Trait("Selenium", "Selenium")]
public async Task CanUsePayjoinViaUI()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
var invoiceRepository = s.Server.PayTester.GetService<InvoiceRepository>();
s.RegisterNewUser(true);
@ -410,14 +398,12 @@ namespace BTCPayServer.Tests
});
}
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUsePayjoin2()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var pjClient = tester.PayTester.GetService<PayjoinClient>();
var nbx = tester.PayTester.GetService<ExplorerClientProvider>().GetExplorerClient("BTC");
@ -629,7 +615,6 @@ namespace BTCPayServer.Tests
var ex2 = await Assert.ThrowsAsync<PayjoinReceiverException>(async () => await pjClient.RequestPayjoin(endpoint, new PayjoinWallet(derivationSchemeSettings), psbt, default));
Assert.Equal(PayjoinReceiverWellknownErrors.NotEnoughMoney, ex2.WellknownError);
}
}
private static async Task<PSBT> ParsePSBT(Microsoft.AspNetCore.Http.HttpContext request)
{

View File

@ -24,8 +24,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanCreateViewUpdateAndDeletePaymentRequest()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -91,14 +90,12 @@ namespace BTCPayServer.Tests
.IsType<ListPaymentRequestsViewModel>(Assert
.IsType<ViewResult>(await paymentRequestController.GetPaymentRequests(user.StoreId)).Model).Items);
}
}
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
public async Task CanPayPaymentRequestWhenPossible()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -157,14 +154,12 @@ namespace BTCPayServer.Tests
.IsType<BadRequestObjectResult>(
await paymentRequestController.PayPaymentRequest(response.Value.ToString(), false));
}
}
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
public async Task CanCancelPaymentWhenPossible()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -241,5 +236,4 @@ namespace BTCPayServer.Tests
await paymentRequestController.CancelUnpaidPendingInvoice(paymentRequestId);
}
}
}
}

View File

@ -49,8 +49,7 @@ namespace BTCPayServer.Tests
[Fact(Timeout = TestTimeout)]
public async Task CanNavigateServerSettings()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
s.Driver.FindElement(By.Id("Nav-ServerSettings")).Click();
@ -64,14 +63,12 @@ namespace BTCPayServer.Tests
Assert.Contains("Starting listening NBXplorer", s.Driver.PageSource);
s.Driver.Quit();
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Lightning", "Lightning")]
public async Task CanUseLndSeedBackup()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
s.Server.ActivateLightning();
await s.StartAsync();
s.RegisterNewUser(true);
@ -96,14 +93,12 @@ namespace BTCPayServer.Tests
seedEl = s.Driver.FindElement(By.Id("Seed"));
Assert.Contains("Seed removed", seedEl.Text, StringComparison.OrdinalIgnoreCase);
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Selenium", "Selenium")]
public async Task CanChangeUserMail()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
var tester = s.Server;
@ -136,13 +131,11 @@ namespace BTCPayServer.Tests
Assert.NotNull(await manager.FindByNameAsync(changedEmail));
Assert.NotNull(await manager.FindByEmailAsync(changedEmail));
}
}
[Fact(Timeout = TestTimeout)]
public async Task NewUserLogin()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
//Register & Log Out
var email = s.RegisterNewUser();
@ -220,13 +213,11 @@ namespace BTCPayServer.Tests
Assert.Contains("/login", s.Driver.Url);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseSSHService()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
var settings = s.Server.PayTester.GetService<SettingsRepository>();
var policies = await settings.GetSettingAsync<PoliciesSettings>() ?? new PoliciesSettings();
@ -277,13 +268,11 @@ namespace BTCPayServer.Tests
policies.DisableSSHService = false;
await settings.UpdateSetting(policies);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanSetupEmailServer()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(isAdmin: true);
s.Driver.Navigate().GoToUrl(s.Link("/server/emails"));
@ -297,13 +286,11 @@ namespace BTCPayServer.Tests
s.GoToUrl($"stores/{s.StoreId}/emails");
CanSetupEmailCore(s);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseDynamicDns()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(isAdmin: true);
s.Driver.Navigate().GoToUrl(s.Link("/server/services"));
@ -348,7 +335,6 @@ namespace BTCPayServer.Tests
Assert.DoesNotContain("/server/services/dynamic-dns/pouet.hello.com/delete", s.Driver.PageSource);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanCreateInvoiceInUI()
{
@ -384,8 +370,7 @@ namespace BTCPayServer.Tests
[Fact(Timeout = TestTimeout)]
public async Task CanSetupStoreViaGuide()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser();
s.GoToUrl("/");
@ -403,14 +388,12 @@ namespace BTCPayServer.Tests
Assert.True(s.Driver.PageSource.Contains("id=\"StoreSelectorDropdown\""), "Store selector dropdown should be present");
Assert.False(s.Driver.PageSource.Contains("id=\"SetupGuide\""), "Setup guide should not be present");
}
}
[Fact(Timeout = TestTimeout)]
[Trait("Lightning", "Lightning")]
public async Task CanCreateStores()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
s.Server.ActivateLightning();
await s.StartAsync();
var alice = s.RegisterNewUser(true);
@ -542,13 +525,11 @@ namespace BTCPayServer.Tests
s.GoToUrl(storeUrl);
Assert.Contains("ReturnUrl", s.Driver.Url);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUsePairing()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.Driver.Navigate().GoToUrl(s.Link("/api-access-request"));
Assert.Contains("ReturnUrl", s.Driver.Url);
@ -587,13 +568,11 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("ApprovePairing")).Click();
AssertUrlHasPairingCode(s);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanCreateAppPoS()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser();
s.CreateNewStore();
@ -625,13 +604,11 @@ namespace BTCPayServer.Tests
s.Driver.Url = posBaseUrl + "/cart";
Assert.True(s.Driver.PageSource.Contains("Cart"), "Cart PoS not showing correct view");
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanCreateCrowdfundingApp()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser();
s.CreateNewStore();
@ -650,13 +627,11 @@ namespace BTCPayServer.Tests
Assert.Equal("currently active!",
s.Driver.FindElement(By.CssSelector("[data-test='time-state']")).Text);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanCreatePayRequest()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser();
s.CreateNewStore();
@ -694,13 +669,11 @@ namespace BTCPayServer.Tests
Assert.Equal("Pay Invoice",
s.Driver.FindElement(By.CssSelector("[data-test='pay-button']")).Text.Trim());
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseCoinSelection()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
(_, string storeId) = s.CreateNewStore();
@ -756,13 +729,11 @@ namespace BTCPayServer.Tests
Assert.Single(tx.Inputs);
Assert.Equal(spentOutpoint, tx.Inputs[0].PrevOut);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanUseWebhooks()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
s.CreateNewStore();
@ -875,13 +846,11 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("ConfirmContinue")).Click();
s.FindAlertMessage();
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanImportMnemonic()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
foreach (var isHotwallet in new[] { false, true })
@ -896,13 +865,11 @@ namespace BTCPayServer.Tests
Assert.DoesNotContain("View seed", s.Driver.PageSource);
}
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanManageWallet()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
(_, string storeId) = s.CreateNewStore();
@ -1058,13 +1025,11 @@ namespace BTCPayServer.Tests
s.Driver.FindElement(By.Id("proceed")).Click();
Assert.Equal(settingsUrl, s.Driver.Url);
}
}
[Fact(Timeout = TestTimeout)]
public async Task CanImportWallet()
{
using (var s = CreateSeleniumTester())
{
using var s = CreateSeleniumTester();
await s.StartAsync();
s.RegisterNewUser(true);
(_, string storeId) = s.CreateNewStore();
@ -1078,7 +1043,6 @@ namespace BTCPayServer.Tests
Assert.Contains("m/84'/1'/0'",
s.Driver.FindElement(By.Id("AccountKeys_0__AccountKeyPath")).GetAttribute("value"));
}
}
[Fact]
[Trait("Selenium", "Selenium")]

View File

@ -37,8 +37,7 @@ namespace BTCPayServer.Tests
[FactWithSecret("AzureBlobStorageConnectionString")]
public async Task CanUseAzureBlobStorage()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -71,7 +70,6 @@ namespace BTCPayServer.Tests
await UnitTest1.CanUploadRemoveFiles(controller);
}
}
[Fact]
public void CanQueryDirectProviders()
@ -338,8 +336,7 @@ namespace BTCPayServer.Tests
[Fact]
public async Task CanUseExchangeSpecificRate()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.PayTester.MockRates = false;
await tester.StartAsync();
var user = tester.NewAccount();
@ -357,7 +354,6 @@ namespace BTCPayServer.Tests
Assert.Single(rates.Where(r => r == rate));
}
}
}
private static async Task<decimal> CreateInvoice(ServerTester tester, TestAccount user, string exchange,
string currency = "USD")

View File

@ -134,8 +134,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CheckSwaggerIsConformToSchema()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
@ -158,14 +157,12 @@ namespace BTCPayServer.Tests
Assert.Empty(errors);
Assert.True(valid);
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task EnsureSwaggerPermissionsDocumented()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
@ -198,7 +195,6 @@ namespace BTCPayServer.Tests
Assert.Equal(description, json["components"]["securitySchemes"]["API Key"]["description"].Value<string>());
}
}
private async Task CheckDeadLinks(Regex regex, HttpClient httpClient, string file)
{
@ -271,8 +267,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanAcceptInvoiceWithTolerance2()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -309,14 +304,12 @@ namespace BTCPayServer.Tests
Assert.Equal("paid", localInvoice.Status);
});
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanThrowBitpay404Error()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -349,7 +342,6 @@ namespace BTCPayServer.Tests
Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
Assert.Equal(0, result.Content.Headers.ContentLength.Value);
}
}
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
@ -418,8 +410,7 @@ namespace BTCPayServer.Tests
[Trait("Lightning", "Lightning")]
public async Task CanSetLightningServer()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
await tester.EnsureChannelsSetup();
@ -456,7 +447,6 @@ namespace BTCPayServer.Tests
.IsType<ViewResult>(storeResponse).Model);
Assert.Single(storeVm.LightningNodes.Where(l => !string.IsNullOrEmpty(l.Address)));
}
}
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
@ -487,8 +477,7 @@ namespace BTCPayServer.Tests
// For easier debugging and testing
// LightningLikePaymentHandler.LIGHTNING_TIMEOUT = int.MaxValue;
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
await tester.EnsureChannelsSetup();
@ -503,7 +492,6 @@ namespace BTCPayServer.Tests
.Select(_ => CanSendLightningPaymentCore(tester, user))
.ToArray());
}
}
async Task CanSendLightningPaymentCore(ServerTester tester, TestAccount user)
{
var invoice = await user.BitPay.CreateInvoiceAsync(new Invoice()
@ -531,8 +519,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanUseServerInitiatedPairingCode()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.Register();
@ -552,16 +539,13 @@ namespace BTCPayServer.Tests
acc.BitPay.AuthorizeClient(new PairingCode(pairingCode)).GetAwaiter().GetResult();
Assert.True(acc.BitPay.TestAccess(Facade.Merchant));
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanSendIPN()
{
using (var callbackServer = new CustomServer())
{
using (var tester = CreateServerTester())
{
using var callbackServer = new CustomServer();
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.GrantAccess();
@ -622,15 +606,12 @@ namespace BTCPayServer.Tests
var invoice2 = acc.BitPay.GetInvoice(invoice.Id);
Assert.NotNull(invoice2);
}
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CantPairTwiceWithSamePubkey()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.Register();
@ -647,14 +628,12 @@ namespace BTCPayServer.Tests
Assert.Contains(nameof(PairingResult.ReusedKey),
(string)store2.TempData[WellKnownTempData.ErrorMessage], StringComparison.CurrentCultureIgnoreCase);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanUseTorClient()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var httpFactory = tester.PayTester.GetService<IHttpClientFactory>();
var client = httpFactory.CreateClient(PayjoinServerCommunicator.PayjoinOnionNamedClient);
@ -689,14 +668,12 @@ namespace BTCPayServer.Tests
TestLogs.LogInformation("Querying valid onion but unreachable");
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync("http://nzwsosflsoquxirwb2zikz6uxr3u5n5u73l33umtdx4hq5mzm5dycuqd.onion/"));
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanRescanWallet()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.GrantAccess();
@ -791,14 +768,12 @@ namespace BTCPayServer.Tests
var walletInfo = await tester.PayTester.GetService<WalletRepository>().GetWalletInfo(walletId);
Assert.Single(walletInfo.LabelColors); // the test2 color should have been removed
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanListInvoices()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
await acc.GrantAccessAsync();
@ -843,14 +818,12 @@ namespace BTCPayServer.Tests
AssertSearchInvoice(acc, false, invoice.Id,
$"enddate:{time.AddSeconds(-1).ToString("yyyy-MM-dd HH:mm:ss")}");
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanListNotifications()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.GrantAccess(true);
@ -876,14 +849,12 @@ namespace BTCPayServer.Tests
Assert.Equal($"https://github.com/btcpayserver/btcpayserver/releases/tag/v{newVersion}", fn.ActionLink);
Assert.False(fn.Seen);
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanGetRates()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var acc = tester.NewAccount();
acc.GrantAccess();
@ -935,7 +906,6 @@ namespace BTCPayServer.Tests
$"http://127.0.0.1:{tester.PayTester.Port}/rates?storeId={acc.StoreId}");
response.EnsureSuccessStatusCode();
}
}
private void AssertSearchInvoice(TestAccount acc, bool expected, string invoiceId, string filter, string storeId = null)
{
@ -950,8 +920,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanRBFPayment()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -1100,7 +1069,6 @@ namespace BTCPayServer.Tests
}
);
}
}
// [Fact(Timeout = TestTimeout)]
[Fact()]
@ -1135,13 +1103,11 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async void CheckCORSSetOnBitpayAPI()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
foreach (var req in new[] { "invoices/", "invoices", "rates", "tokens" }.Select(async path =>
{
using (HttpClient client = new HttpClient())
{
using HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Options,
tester.PayTester.ServerUri.AbsoluteUri + path);
message.Headers.Add("Access-Control-Request-Headers", "test");
@ -1151,7 +1117,6 @@ namespace BTCPayServer.Tests
Assert.Equal("*", val.FirstOrDefault());
Assert.True(response.Headers.TryGetValues("Access-Control-Allow-Headers", out val));
Assert.Equal("test", val.FirstOrDefault());
}
}).ToList())
{
await req;
@ -1164,14 +1129,12 @@ namespace BTCPayServer.Tests
Assert.True(response2.Headers.TryGetValues("Access-Control-Allow-Origin", out var val2));
Assert.Equal("*", val2.FirstOrDefault());
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task TestAccessBitpayAPI()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
Assert.False(user.BitPay.TestAccess(Facade.Merchant));
@ -1241,16 +1204,15 @@ namespace BTCPayServer.Tests
mess.Method = HttpMethod.Get;
result = client.SendAsync(mess).GetAwaiter().GetResult();
Assert.Equal(System.Net.HttpStatusCode.Unauthorized, result.StatusCode);
//
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanUseAnyoneCanCreateInvoice()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -1295,14 +1257,12 @@ namespace BTCPayServer.Tests
});
Assert.Equal(200, (int)response.StatusCode);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanTweakRate()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -1342,15 +1302,13 @@ namespace BTCPayServer.Tests
var expectedCoins = invoice2.Price / expectedRate;
Assert.True(invoice2.BtcPrice.Almost(Money.Coins(expectedCoins), 0.00001m));
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanCreateTopupInvoices()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -1371,7 +1329,6 @@ namespace BTCPayServer.Tests
await AssertTopUpBtcPrice(tester, user, Money.Coins(v), 5000.0m * v, networkFeeMode);
}
}
}
private static async Task AssertTopUpBtcPrice(ServerTester tester, TestAccount user, Money btcSent, decimal expectedPriceWithoutNetworkFee, NetworkFeeMode networkFeeMode)
{
@ -1432,8 +1389,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanModifyRates()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -1493,14 +1449,12 @@ namespace BTCPayServer.Tests
Assert.True(rateVm.ShowScripting);
Assert.Contains("DOGE_X", rateVm.Script, StringComparison.OrdinalIgnoreCase);
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanUseDefaultCurrency()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync(true);
@ -1534,14 +1488,12 @@ namespace BTCPayServer.Tests
var walletSend = await walletController.WalletSend(new WalletId(user.StoreId, "BTC")).AssertViewModelAsync<WalletSendModel>();
Assert.Equal("EUR", walletSend.Fiat);
}
}
[Fact]
[Trait("Lightning", "Lightning")]
public async Task CanSetPaymentMethodLimits()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
var user = tester.NewAccount();
@ -1612,14 +1564,12 @@ namespace BTCPayServer.Tests
checkout = (await user.GetController<UIInvoiceController>().Checkout(invoice.Id)).AssertViewModel<PaymentModel>();
Assert.Equal(btcMethod, checkout.PaymentMethodId);
}
}
[Fact]
[Trait("Integration", "Integration")]
public async Task CanSetUnifiedQrCode()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
await tester.EnsureChannelsSetup();
@ -1673,15 +1623,13 @@ namespace BTCPayServer.Tests
var lightningFallback = paymentMethodSecond.InvoiceBitcoinUrlQR.Split(new[] { "&lightning=" }, StringSplitOptions.None)[1];
Assert.True(lightningFallback.ToUpperInvariant() == lightningFallback);
}
}
[Fact(Timeout = 60 * 2 * 1000)]
[Trait("Integration", "Integration")]
[Trait("Lightning", "Lightning")]
public async Task CanSetPaymentMethodLimitsLightning()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
await tester.EnsureChannelsSetup();
@ -1735,14 +1683,12 @@ namespace BTCPayServer.Tests
Currency = "USD"
}, Facade.Merchant));
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task PosDataParser_ParsesCorrectly_Slower()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -1785,7 +1731,6 @@ namespace BTCPayServer.Tests
await Task.WhenAll(tasks);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
@ -1798,8 +1743,7 @@ namespace BTCPayServer.Tests
return decimal.Parse(match.Groups[1].Value.Trim(), CultureInfo.InvariantCulture);
}
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -1864,14 +1808,12 @@ namespace BTCPayServer.Tests
Assert.Contains("\"InvoiceDue\": 0", pay3str);
});
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanChangeNetworkFeeMode()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
var btc = new PaymentMethodId("BTC", PaymentTypes.BTCLike);
await tester.StartAsync();
var user = tester.NewAccount();
@ -1955,14 +1897,12 @@ namespace BTCPayServer.Tests
});
}
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanExportInvoicesCsv()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -1996,14 +1936,12 @@ namespace BTCPayServer.Tests
paidresult.Content);
});
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanCreateAndDeleteApps()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
await user.GrantAccessAsync();
@ -2036,15 +1974,13 @@ namespace BTCPayServer.Tests
appList = Assert.IsType<ListAppsViewModel>(Assert.IsType<ViewResult>(apps.ListApps(user.StoreId).Result).Model);
Assert.Empty(appList.Apps);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
[Trait("Lightning", "Lightning")]
public async Task CanCreateStrangeInvoice()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
tester.ActivateLightning();
await tester.StartAsync();
var user = tester.NewAccount();
@ -2131,14 +2067,12 @@ namespace BTCPayServer.Tests
var zeroInvoicePM = await greenfield.GetInvoicePaymentMethods(user.StoreId, zeroInvoice.Id);
Assert.Empty(zeroInvoicePM);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task InvoiceFlowThroughDifferentStatesCorrectly()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -2335,14 +2269,12 @@ namespace BTCPayServer.Tests
Assert.StartsWith(txId.ToString(), c.Payment.Id);
});
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CheckLogsRoute()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -2352,14 +2284,12 @@ namespace BTCPayServer.Tests
var vm = Assert.IsType<LogsViewModel>(
Assert.IsType<ViewResult>(await serverController.LogsView()).Model);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanLoginWithNoSecondaryAuthSystemsOrRequestItWhenAdded()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -2427,14 +2357,12 @@ namespace BTCPayServer.Tests
Assert.Null(vm.LoginWith2FaViewModel);
Assert.NotNull(vm.LoginWithFido2ViewModel);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async void CheckOnionlocationForNonOnionHtmlRequests()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var url = tester.PayTester.ServerUri.AbsoluteUri;
@ -2455,7 +2383,6 @@ namespace BTCPayServer.Tests
otherResponse.EnsureSuccessStatusCode();
Assert.False(otherResponse.Headers.Contains("Onion-Location"));
}
}
private static bool IsMapped(Invoice invoice, ApplicationDbContext ctx)
{
@ -2479,8 +2406,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task CanCheckForNewVersion()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
await tester.StartAsync();
var acc = tester.NewAccount();
@ -2519,14 +2445,12 @@ namespace BTCPayServer.Tests
Assert.Equal($"https://github.com/btcpayserver/btcpayserver/releases/tag/v{newVersion}", fn.ActionLink);
Assert.False(fn.Seen);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanDoLightningInternalNodeMigration()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
tester.ActivateLightning(LightningConnectionType.CLightning);
await tester.StartAsync();
var acc = tester.NewAccount();
@ -2597,15 +2521,13 @@ namespace BTCPayServer.Tests
lnMethod = store.GetSupportedPaymentMethods(tester.NetworkProvider).OfType<LightningSupportedPaymentMethod>().First();
Assert.True(lnMethod.IsInternalNode);
}
}
[Fact(Timeout = LongRunningTestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanDoInvoiceMigrations()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
await tester.StartAsync();
var acc = tester.NewAccount();
@ -2668,8 +2590,6 @@ namespace BTCPayServer.Tests
method is DerivationSchemeSettings dss &&
method.PaymentId == new PaymentMethodId("BTC", BitcoinPaymentType.Instance) &&
dss.AccountKeyPath == new KeyPath("44'/0'/0'"));
}
}
private static async Task RestartMigration(ServerTester tester)
@ -2685,8 +2605,7 @@ namespace BTCPayServer.Tests
[Trait("Integration", "Integration")]
public async Task EmailSenderTests()
{
using (var tester = CreateServerTester(newDb: true))
{
using var tester = CreateServerTester(newDb: true);
await tester.StartAsync();
var acc = tester.NewAccount();
@ -2725,16 +2644,13 @@ namespace BTCPayServer.Tests
}), ""));
Assert.Equal("store@store.com", (await Assert.IsType<StoreEmailSender>(await emailSenderFactory.GetEmailSender(acc.StoreId)).GetEmailSettings()).Login);
}
}
[Fact(Timeout = TestUtils.TestTimeout)]
[Trait("Integration", "Integration")]
public async Task CanConfigureStorage()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -2810,14 +2726,12 @@ namespace BTCPayServer.Tests
Assert.True(viewFilesViewModel.StorageConfigured);
Assert.Empty(viewFilesViewModel.Files);
}
}
[Fact]
[Trait("Integration", "Integration")]
public async void CanUseLocalProviderFiles()
{
using (var tester = CreateServerTester())
{
using var tester = CreateServerTester();
await tester.StartAsync();
var user = tester.NewAccount();
user.GrantAccess();
@ -2838,7 +2752,6 @@ namespace BTCPayServer.Tests
await CanUploadRemoveFiles(controller);
}
}
internal static async Task CanUploadRemoveFiles(UIServerController controller)
{

View File

@ -16,8 +16,7 @@ namespace BTCPayServer.Tests
{
lock (_portLock)
{
using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while (true)
{
try
@ -37,7 +36,6 @@ namespace BTCPayServer.Tests
}
}
}
}
// http://stackoverflow.com/a/14933880/2061103
public static void DeleteDirectory(string destinationDir)

View File

@ -871,12 +871,10 @@ namespace BTCPayServer.Controllers
{
try
{
using (var sshClient = await _Options.SSHSettings.ConnectAsync())
{
using var sshClient = await _Options.SSHSettings.ConnectAsync();
var result = await sshClient.RunBash("cat ~/.ssh/authorized_keys", TimeSpan.FromSeconds(10));
vm.SSHKeyFileContent = result.Output;
}
}
catch { }
}
return View(vm);
@ -1106,18 +1104,14 @@ namespace BTCPayServer.Controllers
return NotFound();
try
{
using (var fileStream = new FileStream(
using var fileStream = new FileStream(
fi.FullName,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using (var reader = new StreamReader(fileStream))
{
FileShare.ReadWrite);
using var reader = new StreamReader(fileStream);
vm.Log = await reader.ReadToEndAsync();
}
}
}
catch
{
return NotFound();

View File

@ -810,11 +810,9 @@ namespace BTCPayServer.Controllers
private async Task<string> ReadAllText(IFormFile file)
{
using (var stream = new StreamReader(file.OpenReadStream()))
{
using var stream = new StreamReader(file.OpenReadStream());
return await stream.ReadToEndAsync();
}
}
private string WalletWarning(bool isHotWallet, string info)
{

View File

@ -125,13 +125,11 @@ namespace BTCPayServer
{
if (webSocket.State == WebSocketState.Open)
{
using (CancellationTokenSource cts = new CancellationTokenSource())
{
using CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(5000);
await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", cts.Token);
}
}
}
catch { }
finally { try { webSocket.Dispose(); } catch { } }
}

View File

@ -40,13 +40,11 @@ retry:
Logs.Configuration.LogInformation($"SSH settings detected, testing connection to {_options.SSHSettings.Username}@{_options.SSHSettings.Server} on port {_options.SSHSettings.Port} ...");
try
{
using (var connection = await _options.SSHSettings.ConnectAsync(_cancellationTokenSource.Token))
{
using var connection = await _options.SSHSettings.ConnectAsync(_cancellationTokenSource.Token);
await connection.DisconnectAsync(_cancellationTokenSource.Token);
Logs.Configuration.LogInformation($"SSH connection succeeded");
canUseSSH = true;
}
}
catch (Renci.SshNet.Common.SshAuthenticationException ex)
{
Logs.Configuration.LogWarning($"SSH invalid credentials ({ex.Message})");

View File

@ -59,13 +59,11 @@ namespace BTCPayServer.HostedServices
}
}
}
using (var delayCancel = CancellationTokenSource.CreateLinkedTokenSource(Cancellation))
{
using var delayCancel = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
var delay = Task.Delay(Period, delayCancel.Token);
var changed = SettingsRepository.WaitSettingsChanged<DynamicDnsSettings>(Cancellation);
await Task.WhenAny(delay, changed);
delayCancel.Cancel();
}
}
}
}

View File

@ -463,8 +463,7 @@ retry:
private async Task ConvertConvertWalletKeyPathRoots()
{
bool save = false;
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
#pragma warning disable CS0618 // Type or member is obsolete
@ -496,12 +495,10 @@ retry:
if (save)
await ctx.SaveChangesAsync();
}
}
private async Task ConvertCrowdfundOldSettings()
{
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var app in await ctx.Apps.Where(a => a.AppType == "Crowdfund").ToArrayAsync())
{
var settings = app.GetSettings<Services.Apps.CrowdfundSettings>();
@ -514,12 +511,10 @@ retry:
}
await ctx.SaveChangesAsync();
}
}
private async Task MigratePaymentMethodCriteria()
{
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
@ -570,12 +565,10 @@ retry:
await ctx.SaveChangesAsync();
}
}
private async Task ConvertNetworkFeeProperty()
{
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
@ -593,12 +586,10 @@ retry:
}
await ctx.SaveChangesAsync();
}
}
private async Task ConvertMultiplierToSpread()
{
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
var blob = store.GetStoreBlob();
@ -621,7 +612,6 @@ retry:
}
await ctx.SaveChangesAsync();
}
}
public class RateRule_Obsolete
{
@ -646,8 +636,7 @@ retry:
private async Task DeprecatedLightningConnectionStringCheck()
{
using (var ctx = _DBContextFactory.CreateContext())
{
using var ctx = _DBContextFactory.CreateContext();
foreach (var store in await ctx.Stores.AsQueryable().ToArrayAsync())
{
foreach (var method in store.GetSupportedPaymentMethods(_NetworkProvider).OfType<Payments.Lightning.LightningSupportedPaymentMethod>())
@ -663,5 +652,4 @@ retry:
await ctx.SaveChangesAsync();
}
}
}
}

View File

@ -20,9 +20,8 @@ namespace BTCPayServer.Hosting
{
_BundlesByName = new Lazy<Dictionary<string, Bundle>>(() =>
{
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BTCPayServer.bundleconfig.json"))
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("BTCPayServer.bundleconfig.json");
using var reader = new StreamReader(stream, Encoding.UTF8);
var content = reader.ReadToEnd();
return JArray.Parse(content).OfType<JObject>()
.Select(jobj => new Bundle()
@ -30,7 +29,6 @@ namespace BTCPayServer.Hosting
Name = jobj.Property("name", StringComparison.OrdinalIgnoreCase)?.Value.Value<string>() ?? jobj.Property("outputFileName", StringComparison.OrdinalIgnoreCase).Value.Value<string>(),
OutputFileUrl = Path.Combine(hosting.ContentRootPath, jobj.Property("outputFileName", StringComparison.OrdinalIgnoreCase).Value.Value<string>())
}).ToDictionary(o => o.Name, o => o);
}
}, true);
}
else

View File

@ -43,10 +43,8 @@ namespace BTCPayServer.Models
}
context.HttpContext.Response.Headers.Add("Content-Type", new Microsoft.Extensions.Primitives.StringValues("application/json"));
var str = JsonConvert.SerializeObject(jobj);
await using (var writer = new StreamWriter(context.HttpContext.Response.Body, new UTF8Encoding(false), 1024 * 10, true))
{
await using var writer = new StreamWriter(context.HttpContext.Response.Body, new UTF8Encoding(false), 1024 * 10, true);
await writer.WriteAsync(str);
}
}
}
}

View File

@ -130,8 +130,7 @@ namespace BTCPayServer.Payments.Lightning
try
{
using (var cts = new CancellationTokenSource(LIGHTNING_TIMEOUT))
{
using var cts = new CancellationTokenSource(LIGHTNING_TIMEOUT);
var client = CreateLightningClient(supportedPaymentMethod, network);
LightningNodeInformation info;
try
@ -166,7 +165,6 @@ namespace BTCPayServer.Payments.Lightning
return nodeInfo;
}
}
catch (Exception e) when (!throws)
{
invoiceLogs.Write($"NodeInfo failed to be fetched: {e.Message}", InvoiceEventData.EventSeverity.Error);
@ -197,9 +195,7 @@ namespace BTCPayServer.Payments.Lightning
if (!Utils.TryParseEndpoint(nodeInfo.Host, nodeInfo.Port, out var endpoint))
throw new PaymentMethodUnavailableException($"Could not parse the endpoint {nodeInfo.Host}");
using (var tcp = await _socketFactory.ConnectAsync(endpoint, cancellation))
{
}
using var tcp = await _socketFactory.ConnectAsync(endpoint, cancellation);
}
catch (Exception ex)
{

View File

@ -458,8 +458,7 @@ namespace BTCPayServer.Payments.Lightning
try
{
var lightningClient = _lightningClientFactory.Create(ConnectionString, _network);
using (var session = await lightningClient.Listen(cancellation))
{
using var session = await lightningClient.Listen(cancellation);
// Just in case the payment arrived after our last poll but before we listened.
await PollAllListenedInvoices(cancellation);
if (_ErrorAlreadyLogged)
@ -493,7 +492,6 @@ namespace BTCPayServer.Payments.Lightning
}
}
}
}
catch (Exception ex) when (!cancellation.IsCancellationRequested && !_ErrorAlreadyLogged)
{
_ErrorAlreadyLogged = true;

View File

@ -29,22 +29,18 @@ namespace BTCPayServer.Security.Bitpay
{
if (sin == null)
return Array.Empty<BitTokenEntity>();
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
return (await ctx.PairedSINData.Where(p => p.SIN == sin)
.ToArrayAsync())
.Select(p => CreateTokenEntity(p))
.ToArray();
}
}
public async Task<String> GetStoreIdFromAPIKey(string apiKey)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
return await ctx.ApiKeys.Where(o => o.Id == apiKey).Select(o => o.StoreId).FirstOrDefaultAsync();
}
}
public async Task GenerateLegacyAPIKey(string storeId)
{
@ -57,8 +53,7 @@ namespace BTCPayServer.Security.Bitpay
generated[i] = chars[(int)(RandomUtils.GetUInt32() % generated.Length)];
}
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var existing = await ctx.ApiKeys.Where(o => o.StoreId == storeId && o.Type == APIKeyType.Legacy).ToListAsync();
if (existing.Any())
{
@ -67,7 +62,6 @@ namespace BTCPayServer.Security.Bitpay
ctx.ApiKeys.Add(new APIKeyData() { Id = new string(generated), StoreId = storeId });
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task RevokeLegacyAPIKeys(string storeId)
{
@ -77,20 +71,16 @@ namespace BTCPayServer.Security.Bitpay
return;
}
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
ctx.ApiKeys.RemoveRange(keys.Select(s => new APIKeyData() { Id = s }));
await ctx.SaveChangesAsync();
}
}
public async Task<string[]> GetLegacyAPIKeys(string storeId)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
return await ctx.ApiKeys.Where(o => o.StoreId == storeId && o.Type == APIKeyType.Legacy).Select(c => c.Id).ToArrayAsync();
}
}
private BitTokenEntity CreateTokenEntity(PairedSINData data)
{
@ -131,19 +121,16 @@ namespace BTCPayServer.Security.Bitpay
public async Task<PairingCodeEntity> UpdatePairingCode(PairingCodeEntity pairingCodeEntity)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeEntity.Id);
pairingCode.Label = pairingCodeEntity.Label;
await ctx.SaveChangesAsync();
return CreatePairingCodeEntity(pairingCode);
}
}
public async Task<PairingResult> PairWithStoreAsync(string pairingCodeId, string storeId)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeId);
if (pairingCode == null || pairingCode.Expiration < DateTimeOffset.UtcNow)
return PairingResult.Expired;
@ -152,12 +139,10 @@ namespace BTCPayServer.Security.Bitpay
await ctx.SaveChangesAsync();
return result;
}
}
public async Task<PairingResult> PairWithSINAsync(string pairingCodeId, string sin)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var pairingCode = await ctx.PairingCodes.FindAsync(pairingCodeId);
if (pairingCode == null || pairingCode.Expiration < DateTimeOffset.UtcNow)
return PairingResult.Expired;
@ -166,7 +151,6 @@ namespace BTCPayServer.Security.Bitpay
await ctx.SaveChangesAsync();
return result;
}
}
private async Task<PairingResult> ActivateIfComplete(ApplicationDbContext ctx, PairingCodeData pairingCode)
@ -195,21 +179,17 @@ namespace BTCPayServer.Security.Bitpay
public async Task<BitTokenEntity[]> GetTokensByStoreIdAsync(string storeId)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
return (await ctx.PairedSINData.Where(p => p.StoreDataId == storeId).ToListAsync())
.Select(c => CreateTokenEntity(c))
.ToArray();
}
}
public async Task<PairingCodeEntity> GetPairingAsync(string pairingCode)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
return CreatePairingCodeEntity(await ctx.PairingCodes.FindAsync(pairingCode));
}
}
private PairingCodeEntity CreatePairingCodeEntity(PairingCodeData data)
{
@ -229,8 +209,7 @@ namespace BTCPayServer.Security.Bitpay
public async Task<bool> DeleteToken(string tokenId)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var token = await ctx.PairedSINData.FindAsync(tokenId);
if (token == null)
return false;
@ -238,18 +217,15 @@ namespace BTCPayServer.Security.Bitpay
await ctx.SaveChangesAsync();
return true;
}
}
public async Task<BitTokenEntity> GetToken(string tokenId)
{
using (var ctx = _Factory.CreateContext())
{
using var ctx = _Factory.CreateContext();
var token = await ctx.PairedSINData.FindAsync(tokenId);
if (token == null)
return null;
return CreateTokenEntity(token);
}
}
}
}

View File

@ -28,8 +28,7 @@ namespace BTCPayServer.Security.Greenfield
public async Task<List<APIKeyData>> GetKeys(APIKeyQuery query)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var queryable = context.ApiKeys.AsQueryable();
if (query != null)
{
@ -41,7 +40,6 @@ namespace BTCPayServer.Security.Greenfield
return await queryable.ToListAsync();
}
}
public async Task CreateKey(APIKeyData key)
{
@ -50,12 +48,10 @@ namespace BTCPayServer.Security.Greenfield
throw new InvalidOperationException("cannot save a bitpay legacy api key with this repository");
}
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
await context.ApiKeys.AddAsync(key);
await context.SaveChangesAsync();
}
}
public async Task<bool> Remove(string id, string getUserId)
{

View File

@ -209,29 +209,24 @@ namespace BTCPayServer.Services.Apps
public async Task<StoreData[]> GetOwnedStores(string userId)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
return await ctx.UserStore
.Where(us => us.ApplicationUserId == userId && us.Role == StoreRoles.Owner)
.Select(u => u.StoreData)
.ToArrayAsync();
}
}
public async Task<bool> DeleteApp(AppData appData)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
ctx.Apps.Add(appData);
ctx.Entry(appData).State = EntityState.Deleted;
return await ctx.SaveChangesAsync() == 1;
}
}
public async Task<ListAppsViewModel.ListAppViewModel[]> GetAllApps(string userId, bool allowNoUser = false, string storeId = null)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var listApps = await ctx.UserStore
.Where(us =>
(allowNoUser && string.IsNullOrEmpty(userId) || us.ApplicationUserId == userId) &&
@ -256,7 +251,6 @@ namespace BTCPayServer.Services.Apps
return listApps;
}
}
public async Task<string> GetAppViewStyleAsync(string appId, string appType)
{
@ -284,8 +278,7 @@ namespace BTCPayServer.Services.Apps
public async Task<List<AppData>> GetApps(string[] appIds, bool includeStore = false)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var query = ctx.Apps
.Where(us => appIds.Contains(us.Id));
@ -295,12 +288,10 @@ namespace BTCPayServer.Services.Apps
}
return await query.ToListAsync();
}
}
public async Task<AppData> GetApp(string appId, AppType? appType, bool includeStore = false)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var query = ctx.Apps
.Where(us => us.Id == appId &&
(appType == null || us.AppType == appType.ToString()));
@ -311,7 +302,6 @@ namespace BTCPayServer.Services.Apps
}
return await query.FirstOrDefaultAsync();
}
}
public Task<StoreData> GetStore(AppData app)
{
@ -525,8 +515,7 @@ namespace BTCPayServer.Services.Apps
{
if (userId == null || appId == null)
return null;
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var app = await ctx.UserStore
.Where(us => us.ApplicationUserId == userId && us.Role == StoreRoles.Owner)
.SelectMany(us => us.StoreData.Apps.Where(a => a.Id == appId))
@ -537,12 +526,10 @@ namespace BTCPayServer.Services.Apps
return null;
return app;
}
}
public async Task UpdateOrCreateApp(AppData app)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
if (string.IsNullOrEmpty(app.Id))
{
app.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(20));
@ -558,7 +545,6 @@ namespace BTCPayServer.Services.Apps
}
await ctx.SaveChangesAsync();
}
}
private static bool TryParseJson(string json, out JObject result)
{

View File

@ -28,15 +28,13 @@ namespace BTCPayServer.Services
public async Task UpdateInvoiceExpiry(string invoiceId, DateTimeOffset dateTimeOffset)
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
var invoiceData = await ctx.Invoices.FindAsync(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
// TODO change the expiry time. But how?
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
Task IHostedService.StartAsync(CancellationToken cancellationToken)
{

View File

@ -44,8 +44,7 @@ namespace BTCPayServer.Services
{
ArgumentNullException.ThrowIfNull(transaction);
ArgumentNullException.ThrowIfNull(network);
using (var db = _dbContextFactory.CreateContext())
{
using var db = _dbContextFactory.CreateContext();
db.PlannedTransactions.Add(new PlannedTransaction()
{
Id = $"{network.CryptoCode}-{transaction.GetHash()}",
@ -60,7 +59,6 @@ namespace BTCPayServer.Services
{
}
}
}
public async Task<int> ProcessAll(CancellationToken cancellationToken = default)
{

View File

@ -67,8 +67,7 @@ namespace BTCPayServer.Services.Invoices
public async Task<bool> RemovePendingInvoice(string invoiceId)
{
Logs.PayServer.LogInformation($"Remove pending invoice {invoiceId}");
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
ctx.PendingInvoices.Remove(new PendingInvoiceData() { Id = invoiceId });
try
{
@ -77,12 +76,10 @@ namespace BTCPayServer.Services.Invoices
}
catch (DbUpdateException) { return false; }
}
}
public async Task<IEnumerable<InvoiceEntity>> GetInvoicesFromAddresses(string[] addresses)
{
using (var db = _applicationDbContextFactory.CreateContext())
{
using var db = _applicationDbContextFactory.CreateContext();
return (await db.AddressInvoices
.Include(a => a.InvoiceData.Payments)
#pragma warning disable CS0618
@ -91,15 +88,12 @@ namespace BTCPayServer.Services.Invoices
.Select(a => a.InvoiceData)
.ToListAsync()).Select(ToEntity);
}
}
public async Task<string[]> GetPendingInvoices()
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
return await ctx.PendingInvoices.AsQueryable().Select(data => data.Id).ToArrayAsync();
}
}
public async Task<List<Data.WebhookDeliveryData>> GetWebhookDeliveries(string invoiceId)
{
@ -115,16 +109,13 @@ namespace BTCPayServer.Services.Invoices
public async Task<AppData[]> GetAppsTaggingStore(string storeId)
{
ArgumentNullException.ThrowIfNull(storeId);
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
return await ctx.Apps.Where(a => a.StoreDataId == storeId && a.TagAllInvoices).ToArrayAsync();
}
}
public async Task UpdateInvoice(string invoiceId, UpdateCustomerModel data)
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
var invoiceData = await ctx.Invoices.FindAsync(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
@ -135,12 +126,10 @@ namespace BTCPayServer.Services.Invoices
}
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task ExtendInvoiceMonitor(string invoiceId)
{
using (var ctx = _applicationDbContextFactory.CreateContext())
{
using var ctx = _applicationDbContextFactory.CreateContext();
var invoiceData = await ctx.Invoices.FindAsync(invoiceId);
var invoice = invoiceData.GetBlob(_btcPayNetworkProvider);
@ -149,7 +138,6 @@ namespace BTCPayServer.Services.Invoices
await ctx.SaveChangesAsync();
}
}
public async Task<InvoiceEntity> CreateInvoiceAsync(string storeId, InvoiceEntity invoice, string[] additionalSearchTerms = null)
{
@ -316,8 +304,7 @@ namespace BTCPayServer.Services.Invoices
public async Task UpdateInvoicePaymentMethod(string invoiceId, PaymentMethod paymentMethod)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var invoice = await context.Invoices.FindAsync(invoiceId);
if (invoice == null)
return;
@ -343,14 +330,11 @@ namespace BTCPayServer.Services.Invoices
invoice.Blob = ToBytes(invoiceEntity, network);
AddToTextSearch(context, invoice, paymentMethod.GetPaymentMethodDetails().GetPaymentDestination());
await context.SaveChangesAsync();
}
}
public async Task AddPendingInvoiceIfNotPresent(string invoiceId)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
if (!context.PendingInvoices.Any(a => a.Id == invoiceId))
{
context.PendingInvoices.Add(new PendingInvoiceData() { Id = invoiceId });
@ -361,7 +345,6 @@ namespace BTCPayServer.Services.Invoices
catch (DbUpdateException) { } // Already exists
}
}
}
public async Task AddInvoiceEvent(string invoiceId, object evt, InvoiceEventData.EventSeverity severity)
{
@ -419,8 +402,7 @@ namespace BTCPayServer.Services.Invoices
public async Task UpdateInvoiceStatus(string invoiceId, InvoiceState invoiceState)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var invoiceData = await context.FindAsync<Data.InvoiceData>(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
@ -428,13 +410,11 @@ namespace BTCPayServer.Services.Invoices
invoiceData.ExceptionStatus = InvoiceState.ToString(invoiceState.ExceptionStatus);
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
internal async Task UpdateInvoicePrice(string invoiceId, InvoiceEntity invoice)
{
if (invoice.Type != InvoiceType.TopUp)
throw new ArgumentException("The invoice type should be TopUp to be able to update invoice price", nameof(invoice));
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var invoiceData = await context.FindAsync<Data.InvoiceData>(invoiceId).ConfigureAwait(false);
if (invoiceData == null)
return;
@ -444,12 +424,10 @@ namespace BTCPayServer.Services.Invoices
invoiceData.Blob = ToBytes(blob, null);
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task MassArchive(string[] invoiceIds, bool archive = true)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var items = context.Invoices.Where(a => invoiceIds.Contains(a.Id));
if (items == null)
{
@ -463,12 +441,10 @@ namespace BTCPayServer.Services.Invoices
await context.SaveChangesAsync();
}
}
public async Task ToggleInvoiceArchival(string invoiceId, bool archived, string storeId = null)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var invoiceData = await context.FindAsync<InvoiceData>(invoiceId).ConfigureAwait(false);
if (invoiceData == null || invoiceData.Archived == archived ||
(storeId != null &&
@ -477,11 +453,9 @@ namespace BTCPayServer.Services.Invoices
invoiceData.Archived = archived;
await context.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task<InvoiceEntity> UpdateInvoiceMetadata(string invoiceId, string storeId, JObject metadata)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var invoiceData = await GetInvoiceRaw(invoiceId, context);
if (invoiceData == null || (storeId != null &&
!invoiceData.StoreDataId.Equals(storeId,
@ -493,7 +467,6 @@ namespace BTCPayServer.Services.Invoices
await context.SaveChangesAsync().ConfigureAwait(false);
return ToEntity(invoiceData);
}
}
public async Task<bool> MarkInvoiceStatus(string invoiceId, InvoiceStatus status)
{
using (var context = _applicationDbContextFactory.CreateContext())
@ -541,17 +514,14 @@ namespace BTCPayServer.Services.Invoices
public async Task<InvoiceEntity> GetInvoice(string id, bool includeAddressData = false)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var res = await GetInvoiceRaw(id, context, includeAddressData);
return res == null ? null : ToEntity(res);
}
}
public async Task<InvoiceEntity[]> GetInvoices(string[] invoiceIds)
{
var invoiceIdSet = invoiceIds.ToHashSet();
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
IQueryable<Data.InvoiceData> query =
context
.Invoices
@ -560,7 +530,6 @@ namespace BTCPayServer.Services.Invoices
return (await query.ToListAsync()).Select(o => ToEntity(o)).ToArray();
}
}
private async Task<InvoiceData> GetInvoiceRaw(string id, ApplicationDbContext dbContext, bool includeAddressData = false)
{
@ -710,17 +679,14 @@ namespace BTCPayServer.Services.Invoices
public async Task<int> GetInvoicesTotal(InvoiceQuery queryObject)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var query = GetInvoiceQuery(context, queryObject);
return await query.CountAsync();
}
}
public async Task<InvoiceEntity[]> GetInvoices(InvoiceQuery queryObject)
{
using (var context = _applicationDbContextFactory.CreateContext())
{
using var context = _applicationDbContextFactory.CreateContext();
var query = GetInvoiceQuery(context, queryObject);
query = query.Include(o => o.Payments);
if (queryObject.IncludeAddresses)
@ -730,7 +696,6 @@ namespace BTCPayServer.Services.Invoices
var data = await query.ToArrayAsync().ConfigureAwait(false);
return data.Select(ToEntity).ToArray();
}
}
private string NormalizeExceptionStatus(string status)
{

View File

@ -37,12 +37,10 @@ namespace BTCPayServer.Services
var result = new List<Language>();
foreach (var file in files)
{
using (var stream = new StreamReader(file))
{
using var stream = new StreamReader(file);
var json = stream.ReadToEnd();
result.Add(JObject.Parse(json).ToObject<Language>());
}
}
_languages = result.ToArray();
}

View File

@ -30,12 +30,10 @@ namespace BTCPayServer.Services.Mails
Logs.Configuration.LogWarning("Should have sent email, but email settings are not configured");
return;
}
using (var smtp = await emailSettings.CreateSmtpClient())
{
using var smtp = await emailSettings.CreateSmtpClient();
var mail = emailSettings.CreateMailMessage(new MailboxAddress(email, email), subject, message, true);
await smtp.SendAsync(mail, cancellationToken);
await smtp.DisconnectAsync(true, cancellationToken);
}
}, TimeSpan.Zero);
}

View File

@ -22,8 +22,7 @@ namespace BTCPayServer.Services.PaymentRequests
public async Task<PaymentRequestData> CreateOrUpdatePaymentRequest(PaymentRequestData entity)
{
using (var context = _ContextFactory.CreateContext())
{
using var context = _ContextFactory.CreateContext();
if (string.IsNullOrEmpty(entity.Id))
{
entity.Id = Guid.NewGuid().ToString();
@ -37,7 +36,6 @@ namespace BTCPayServer.Services.PaymentRequests
await context.SaveChangesAsync();
return entity;
}
}
public async Task<PaymentRequestData> FindPaymentRequest(string id, string userId, CancellationToken cancellationToken = default)
{
@ -46,8 +44,7 @@ namespace BTCPayServer.Services.PaymentRequests
return null;
}
using (var context = _ContextFactory.CreateContext())
{
using var context = _ContextFactory.CreateContext();
var result = await context.PaymentRequests.Include(x => x.StoreData)
.Where(data =>
string.IsNullOrEmpty(userId) ||
@ -55,7 +52,6 @@ namespace BTCPayServer.Services.PaymentRequests
.SingleOrDefaultAsync(x => x.Id == id, cancellationToken);
return result;
}
}
public async Task<bool> IsPaymentRequestAdmin(string paymentRequestId, string userId)
{
@ -63,31 +59,26 @@ namespace BTCPayServer.Services.PaymentRequests
{
return false;
}
using (var context = _ContextFactory.CreateContext())
{
using var context = _ContextFactory.CreateContext();
return await context.PaymentRequests.Include(x => x.StoreData)
.AnyAsync(data =>
data.Id == paymentRequestId &&
(data.StoreData != null && data.StoreData.UserStores.Any(u => u.ApplicationUserId == userId)));
}
}
public async Task UpdatePaymentRequestStatus(string paymentRequestId, Client.Models.PaymentRequestData.PaymentRequestStatus status, CancellationToken cancellationToken = default)
{
using (var context = _ContextFactory.CreateContext())
{
using var context = _ContextFactory.CreateContext();
var invoiceData = await context.FindAsync<PaymentRequestData>(paymentRequestId);
if (invoiceData == null)
return;
invoiceData.Status = status;
await context.SaveChangesAsync(cancellationToken);
}
}
public async Task<(int Total, PaymentRequestData[] Items)> FindPaymentRequests(PaymentRequestQuery query, CancellationToken cancellationToken = default)
{
using (var context = _ContextFactory.CreateContext())
{
using var context = _ContextFactory.CreateContext();
var queryable = context.PaymentRequests.Include(data => data.StoreData).AsQueryable();
if (!query.IncludeArchived)
@ -133,7 +124,6 @@ namespace BTCPayServer.Services.PaymentRequests
}
return (total, await queryable.ToArrayAsync(cancellationToken));
}
}
public async Task<InvoiceEntity[]> GetInvoicesForPaymentRequest(string paymentRequestId,
InvoiceQuery invoiceQuery = null)

View File

@ -26,12 +26,10 @@ namespace BTCPayServer.Services.Stores
{
if (storeId == null)
return null;
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var result = await ctx.FindAsync<StoreData>(storeId).ConfigureAwait(false);
return result;
}
}
public async Task<StoreData> FindStore(string storeId, string userId)
{
@ -62,8 +60,7 @@ namespace BTCPayServer.Services.Stores
public async Task<StoreUser[]> GetStoreUsers(string storeId)
{
ArgumentNullException.ThrowIfNull(storeId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
return await ctx
.UserStore
.Where(u => u.StoreDataId == storeId)
@ -74,12 +71,10 @@ namespace BTCPayServer.Services.Stores
Role = u.Role
}).ToArrayAsync();
}
}
public async Task<StoreData[]> GetStoresByUserId(string userId, IEnumerable<string> storeIds = null)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
return (await ctx.UserStore
.Where(u => u.ApplicationUserId == userId && (storeIds == null || storeIds.Contains(u.StoreDataId)))
.Select(u => new { u.StoreData, u.Role })
@ -90,7 +85,6 @@ namespace BTCPayServer.Services.Stores
return u.StoreData;
}).ToArray();
}
}
public async Task<StoreData> GetStoreByInvoiceId(string invoiceId)
{
@ -102,8 +96,7 @@ namespace BTCPayServer.Services.Stores
public async Task<bool> AddStoreUser(string storeId, string userId, string role)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var userStore = new UserStore() { StoreDataId = storeId, ApplicationUserId = userId, Role = role };
ctx.UserStore.Add(userStore);
try
@ -116,12 +109,10 @@ namespace BTCPayServer.Services.Stores
return false;
}
}
}
public async Task CleanUnreachableStores()
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
if (!ctx.Database.SupportDropForeignKey())
return;
foreach (var store in await ctx.Stores.Where(s => !s.UserStores.Where(u => u.Role == StoreRoles.Owner).Any()).ToArrayAsync())
@ -130,7 +121,6 @@ namespace BTCPayServer.Services.Stores
}
await ctx.SaveChangesAsync();
}
}
public async Task RemoveStoreUser(string storeId, string userId)
{
@ -147,8 +137,7 @@ namespace BTCPayServer.Services.Stores
private async Task DeleteStoreIfOrphan(string storeId)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
if (ctx.Database.SupportDropForeignKey())
{
if (!await ctx.UserStore.Where(u => u.StoreDataId == storeId && u.Role == StoreRoles.Owner).AnyAsync())
@ -162,7 +151,6 @@ namespace BTCPayServer.Services.Stores
}
}
}
}
private void SetNewStoreHints(ref StoreData storeData)
{
@ -182,8 +170,7 @@ namespace BTCPayServer.Services.Stores
if (string.IsNullOrEmpty(storeData.StoreName))
throw new ArgumentException("name should not be empty", nameof(storeData.StoreName));
ArgumentNullException.ThrowIfNull(ownerId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
storeData.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(32));
var userStore = new UserStore
{
@ -198,7 +185,6 @@ namespace BTCPayServer.Services.Stores
ctx.Add(userStore);
await ctx.SaveChangesAsync();
}
}
public async Task<StoreData> CreateStore(string ownerId, string name)
{
@ -343,18 +329,15 @@ namespace BTCPayServer.Services.Stores
public async Task UpdateStore(StoreData store)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var existing = await ctx.FindAsync<StoreData>(store.Id);
ctx.Entry(existing).CurrentValues.SetValues(store);
await ctx.SaveChangesAsync().ConfigureAwait(false);
}
}
public async Task<bool> DeleteStore(string storeId)
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
if (!ctx.Database.SupportDropForeignKey())
return false;
var store = await ctx.Stores.FindAsync(storeId);
@ -370,14 +353,11 @@ namespace BTCPayServer.Services.Stores
await ctx.SaveChangesAsync();
return true;
}
}
public bool CanDeleteStores()
{
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
return ctx.Database.SupportDropForeignKey();
}
}
}
}

View File

@ -19,8 +19,7 @@ namespace BTCPayServer.Services
public async Task SetWalletInfo(WalletId walletId, WalletBlobInfo blob)
{
ArgumentNullException.ThrowIfNull(walletId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var walletData = new WalletData() { Id = walletId.ToString() };
walletData.SetBlobInfo(blob);
var entity = await ctx.Wallets.AddAsync(walletData);
@ -35,13 +34,11 @@ namespace BTCPayServer.Services
await ctx.SaveChangesAsync();
}
}
}
public async Task<Dictionary<string, WalletTransactionInfo>> GetWalletTransactionsInfo(WalletId walletId, string[] transactionIds = null)
{
ArgumentNullException.ThrowIfNull(walletId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
return (await ctx.WalletTransactions
.Where(w => w.WalletDataId == walletId.ToString())
.Where(data => transactionIds == null || transactionIds.Contains(data.TransactionId))
@ -49,27 +46,23 @@ namespace BTCPayServer.Services
.ToArrayAsync())
.ToDictionary(w => w.TransactionId, w => w.GetBlobInfo());
}
}
public async Task<WalletBlobInfo> GetWalletInfo(WalletId walletId)
{
ArgumentNullException.ThrowIfNull(walletId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var data = await ctx.Wallets
.Where(w => w.Id == walletId.ToString())
.Select(w => w)
.FirstOrDefaultAsync();
return data?.GetBlobInfo() ?? new WalletBlobInfo();
}
}
public async Task SetWalletTransactionInfo(WalletId walletId, string transactionId, WalletTransactionInfo walletTransactionInfo)
{
ArgumentNullException.ThrowIfNull(walletId);
ArgumentNullException.ThrowIfNull(transactionId);
using (var ctx = _ContextFactory.CreateContext())
{
using var ctx = _ContextFactory.CreateContext();
var walletData = new WalletTransactionData() { WalletDataId = walletId.ToString(), TransactionId = transactionId };
walletData.SetBlobInfo(walletTransactionInfo);
var entity = await ctx.WalletTransactions.AddAsync(walletData);
@ -93,5 +86,4 @@ namespace BTCPayServer.Services
}
}
}
}
}

View File

@ -29,8 +29,7 @@ namespace BTCPayServer.Storage.Services
filesQuery = new FilesQuery();
}
using (var context = _ApplicationDbContextFactory.CreateContext())
{
using var context = _ApplicationDbContextFactory.CreateContext();
return await context.Files
.Include(file => file.ApplicationUser)
.Where(file =>
@ -39,26 +38,21 @@ namespace BTCPayServer.Storage.Services
.OrderByDescending(file => file.Timestamp)
.ToListAsync();
}
}
public async Task RemoveFile(StoredFile file)
{
using (var context = _ApplicationDbContextFactory.CreateContext())
{
using var context = _ApplicationDbContextFactory.CreateContext();
context.Attach(file);
context.Files.Remove(file);
await context.SaveChangesAsync();
}
}
public async Task AddFile(StoredFile storedFile)
{
using (var context = _ApplicationDbContextFactory.CreateContext())
{
using var context = _ApplicationDbContextFactory.CreateContext();
await context.AddAsync(storedFile);
await context.SaveChangesAsync();
}
}
public class FilesQuery
{

View File

@ -94,14 +94,10 @@ namespace BTCPayServer
public async Task Send(string evt, CancellationToken cancellation = default)
{
var bytes = UTF8.GetBytes(evt);
using (var cts = new CancellationTokenSource(5000))
{
using (var cts2 = CancellationTokenSource.CreateLinkedTokenSource(cancellation))
{
using var cts = new CancellationTokenSource(5000);
using var cts2 = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
await Socket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, cts2.Token);
}
}
}
public async Task DisposeAsync(CancellationToken cancellation)
{