diff --git a/.gitignore b/.gitignore index 287e1be..03b416e 100644 --- a/.gitignore +++ b/.gitignore @@ -98,6 +98,7 @@ local.properties x64/ build/ [Oo]bj/ +/.vs # MSTest test Results [Tt]est[Rr]esult*/ diff --git a/BunqSdk.Samples/ApiContextSaveSample.cs b/BunqSdk.Samples/ApiContextSaveSample.cs index 215fc2c..f85b4a6 100644 --- a/BunqSdk.Samples/ApiContextSaveSample.cs +++ b/BunqSdk.Samples/ApiContextSaveSample.cs @@ -5,12 +5,12 @@ namespace Bunq.Sdk.Samples { public class ApiContextSaveSample : ISample { - private const string API_KEY = "### YOUR API KEY ###"; // Put your API key here - private const string DEVICE_DESCRIPTION = "Device description."; + private const string ApiKey = "### YOUR API KEY ###"; // Put your API key here + private const string DeviceDescription = "Device description."; public void Run() { - var apiContext = ApiContext.Create(ApiEnvironmentType.SANDBOX, API_KEY, DEVICE_DESCRIPTION); + var apiContext = ApiContext.Create(ApiEnvironmentType.Sandbox, ApiKey, DeviceDescription); apiContext.Save(); } } diff --git a/BunqSdk.Samples/AttachmentPublicSample.cs b/BunqSdk.Samples/AttachmentPublicSample.cs index 9eca1da..0fc80de 100644 --- a/BunqSdk.Samples/AttachmentPublicSample.cs +++ b/BunqSdk.Samples/AttachmentPublicSample.cs @@ -9,10 +9,10 @@ namespace Bunq.Sdk.Samples { public class AttachmentPublicSample : ISample { - private const string CONTENT_TYPE_IMAGE_JPEG = "image/jpeg"; - private const string DESCRIPTION_TEST_JPG_ATTACHMENT = "A test JPG attachment."; - private const string PATH_ATTACHMENT_IN = "Assets/Attachment.jpg"; - private const string PATH_ATTACHMENT_OUT = "Tmp/AttachmentOut.jpg"; + private const string ContentTypeImageJpeg = "image/jpeg"; + private const string DescriptionTestJpgAttachment = "A test JPG attachment."; + private const string PathAttachmentIn = "Assets/Attachment.jpg"; + private const string PathAttachmentOut = "Tmp/AttachmentOut.jpg"; public void Run() { @@ -20,13 +20,13 @@ public void Run() var customHeaders = new Dictionary { - {ApiClient.HEADER_CONTENT_TYPE, CONTENT_TYPE_IMAGE_JPEG}, - {ApiClient.HEADER_ATTACHMENT_DESCRIPTION, DESCRIPTION_TEST_JPG_ATTACHMENT} + {ApiClient.HeaderContentType, ContentTypeImageJpeg}, + {ApiClient.HeaderAttachmentDescription, DescriptionTestJpgAttachment} }; - var requestBytes = File.ReadAllBytes(PATH_ATTACHMENT_IN); + var requestBytes = File.ReadAllBytes(PathAttachmentIn); var uuid = AttachmentPublic.Create(apiContext, requestBytes, customHeaders).Value; var responseBytes = AttachmentPublicContent.List(apiContext, uuid).Value; - var fileOut = new FileInfo(PATH_ATTACHMENT_OUT); + var fileOut = new FileInfo(PathAttachmentOut); fileOut.Directory.Create(); File.WriteAllBytes(fileOut.FullName, responseBytes); } diff --git a/BunqSdk.Samples/CardDebitSample.cs b/BunqSdk.Samples/CardDebitSample.cs index f78d124..7eac2ab 100644 --- a/BunqSdk.Samples/CardDebitSample.cs +++ b/BunqSdk.Samples/CardDebitSample.cs @@ -9,28 +9,28 @@ namespace Bunq.Sdk.Samples { public class CardDebitSample : ISample { - private const string NAME_YOUR_COMPANY = "USER_COMPANY_NAME"; // Put your user name here - private const string PIN_CODE = "0461"; - private const string POINTER_TYPE_EMAIL = "EMAIL"; - private const string EMAIL_YOUR_COMPANY = "at@at.at"; // Put your user email here - private const string POINTER_NAME_TEST = "test pointer"; - private const int USER_ITEM_ID = 0; // Put your user ID here + private const string NameYourCompany = "USER_COMPANY_NAME"; // Put your user name here + private const string PinCode = "0461"; + private const string PointerTypeEmail = "EMAIL"; + private const string EmailYourCompany = "at@at.at"; // Put your user email here + private const string PointerNameTest = "test pointer"; + private const int UserItemId = 0; // Put your user ID here public void Run() { var apiContext = ApiContext.Restore(); var requestMap = new Dictionary { - {CardDebit.FIELD_NAME_ON_CARD, NAME_YOUR_COMPANY}, + {CardDebit.FIELD_NAME_ON_CARD, NameYourCompany}, {CardDebit.FIELD_SECOND_LINE, GenerateRandomSecondLine()}, - {CardDebit.FIELD_PIN_CODE, PIN_CODE}, + {CardDebit.FIELD_PIN_CODE, PinCode}, { CardDebit.FIELD_ALIAS, - new Pointer(POINTER_TYPE_EMAIL, EMAIL_YOUR_COMPANY) {Name = POINTER_NAME_TEST} + new Pointer(PointerTypeEmail, EmailYourCompany) {Name = PointerNameTest} }, }; - Console.WriteLine(CardDebit.Create(apiContext, requestMap, USER_ITEM_ID)); + Console.WriteLine(CardDebit.Create(apiContext, requestMap, UserItemId)); } private static string GenerateRandomSecondLine() diff --git a/BunqSdk.Samples/CustomerStatementExportSample.cs b/BunqSdk.Samples/CustomerStatementExportSample.cs index e15f85f..99d567b 100644 --- a/BunqSdk.Samples/CustomerStatementExportSample.cs +++ b/BunqSdk.Samples/CustomerStatementExportSample.cs @@ -9,55 +9,55 @@ namespace Bunq.Sdk.Samples public class CustomerStatementExportSample : ISample { /// - /// Constant to translate weeks to milliseconds. + /// Constant value zero. /// - private const int INDEX_FIRST = 0; + private const int IndexFirst = 0; /// /// Date format for Customer Statement Export endpoint. /// - private const string FORMAT_DATE_STATEMENT = "yyyy-MM-dd"; + private const string FormatDateStatement = "yyyy-MM-dd"; /// /// Format of the statement file requested. /// - private const string STATEMENT_FORMAT = "PDF"; + private const string StatementFormat = "PDF"; /// /// Measure of any time unit when none of it is needed. /// - private const int TIME_UNIT_COUNT_NONE = 0; + private const int TimeUnitCountNone = 0; /// - /// Measure of any time unit when none of it is needed. + /// Measure of days in week. /// - private const int DAYS_IN_WEEK = 7; + private const int DaysInWeek = 7; public void Run() { var apiContext = ApiContext.Restore(); var timeSpanWeek = new TimeSpan( - DAYS_IN_WEEK, - TIME_UNIT_COUNT_NONE, - TIME_UNIT_COUNT_NONE, - TIME_UNIT_COUNT_NONE + DaysInWeek, + TimeUnitCountNone, + TimeUnitCountNone, + TimeUnitCountNone ); var dateStart = DateTime.Now.Subtract(timeSpanWeek); var dateEnd = DateTime.Now; var customerStatementMap = new Dictionary { - {CustomerStatementExport.FIELD_STATEMENT_FORMAT, STATEMENT_FORMAT}, - {CustomerStatementExport.FIELD_DATE_START, dateStart.ToString(FORMAT_DATE_STATEMENT)}, - {CustomerStatementExport.FIELD_DATE_END, dateEnd.ToString(FORMAT_DATE_STATEMENT)}, + {CustomerStatementExport.FIELD_STATEMENT_FORMAT, StatementFormat}, + {CustomerStatementExport.FIELD_DATE_START, dateStart.ToString(FormatDateStatement)}, + {CustomerStatementExport.FIELD_DATE_END, dateEnd.ToString(FormatDateStatement)}, }; - var userId = User.List(apiContext).Value[INDEX_FIRST].UserCompany.Id; + var userId = User.List(apiContext).Value[IndexFirst].UserCompany.Id; if (userId != null) { var userIdInt = (int) userId; - var monetaryAccountId = MonetaryAccountBank.List(apiContext, userIdInt).Value[INDEX_FIRST].Id; + var monetaryAccountId = MonetaryAccountBank.List(apiContext, userIdInt).Value[IndexFirst].Id; if (monetaryAccountId != null) { diff --git a/BunqSdk.Samples/MonetaryAccountSample.cs b/BunqSdk.Samples/MonetaryAccountSample.cs index 1fa2ba3..8634ae7 100644 --- a/BunqSdk.Samples/MonetaryAccountSample.cs +++ b/BunqSdk.Samples/MonetaryAccountSample.cs @@ -7,13 +7,13 @@ namespace Bunq.Sdk.Samples { public class MonetaryAccountSample : ISample { - private const int USER_ITEM_ID = 0; // Put your user ID here - private const int MONETARY_ACCOUNT_ITEM_ID = 0; // Put your monetary account ID here + private const int UserItemId = 0; // Put your user ID here + private const int MonetaryAccountItemId = 0; // Put your monetary account ID here public void Run() { var apiContext = ApiContext.Restore(); - var monetaryAccount = MonetaryAccount.Get(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID).Value; + var monetaryAccount = MonetaryAccount.Get(apiContext, UserItemId, MonetaryAccountItemId).Value; Console.WriteLine(monetaryAccount.MonetaryAccountBank); } } diff --git a/BunqSdk.Samples/PaymentBatchSample.cs b/BunqSdk.Samples/PaymentBatchSample.cs index e5ece12..6ae62ed 100644 --- a/BunqSdk.Samples/PaymentBatchSample.cs +++ b/BunqSdk.Samples/PaymentBatchSample.cs @@ -9,13 +9,13 @@ namespace Bunq.Sdk.Samples { public class PaymentBatchSample : ISample { - private const string PAYMENT_AMOUNT = "0.01"; - private const string PAYMENT_CURRENCY = "EUR"; - private const string COUNTERPARTY_POINTER_TYPE = "EMAIL"; - private const string COUNTERPARTY_EMAIL = "bravo@bunq.com"; - private const string PAYMENT_DESCRIPTION = "This is a generated payment batch!"; - private const int USER_ITEM_ID = 0; // Put your user ID here - private const int MONETARY_ACCOUNT_ITEM_ID = 0; // Put your monetary account ID here + private const string ValueAmountEur = "0.01"; + private const string ValueCurrencyEur = "EUR"; + private const string CounterPartyPointerType = "EMAIL"; + private const string CounterPartyEmail = "bravo@bunq.com"; + private const string ValueDescription = "This is a generated payment batch!"; + private const int UserItemId = 0; // Put your user ID here + private const int MonetaryAccountItemId = 0; // Put your monetary account ID here public void Run() { @@ -28,21 +28,21 @@ public void Run() { new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(PAYMENT_AMOUNT, PAYMENT_CURRENCY)}, + {Payment.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, { Payment.FIELD_COUNTERPARTY_ALIAS, - new Pointer(COUNTERPARTY_POINTER_TYPE, COUNTERPARTY_EMAIL) + new Pointer(CounterPartyPointerType, CounterPartyEmail) }, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION} + {Payment.FIELD_DESCRIPTION, ValueDescription} } } } }; - var paymentBatchId = PaymentBatch.Create(apiContext, paymentBatchMap, USER_ITEM_ID, - MONETARY_ACCOUNT_ITEM_ID).Value; + var paymentBatchId = PaymentBatch.Create(apiContext, paymentBatchMap, UserItemId, + MonetaryAccountItemId).Value; - Console.WriteLine(PaymentBatch.Get(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID, paymentBatchId)); + Console.WriteLine(PaymentBatch.Get(apiContext, UserItemId, MonetaryAccountItemId, paymentBatchId)); } } } diff --git a/BunqSdk.Samples/PaymentListSample.cs b/BunqSdk.Samples/PaymentListSample.cs index 3757d9c..fcc48bc 100644 --- a/BunqSdk.Samples/PaymentListSample.cs +++ b/BunqSdk.Samples/PaymentListSample.cs @@ -12,44 +12,44 @@ public class PaymentListSample : ISample /// /// Message constants. /// - private const string MESSAGE_LATEST_PAGE_IDS = "Latest page IDs: "; - private const string MESSAGE_SECOND_LATEST_PAGE_IDS = "Second latest page IDs: "; - private const string MESSAGE_NO_PRIOR_PAYMENTS_FOUND = "No prior payments found!"; + private const string MessageLatestPageAllPaymentId = "Latest page IDs: "; + private const string MessageSecondLatestPageAllPaymentId = "Second latest page IDs: "; + private const string MessageNoPriorPaymentFound = "No prior payments found!"; /// /// Size of each page of payment listing. /// - private const int PAGE_SIZE = 3; + private const int PageSize = 3; /// /// Constants to be changed to run the example. /// - private const int USER_ITEM_ID = 0; // Put your user ID here - private const int MONETARY_ACCOUNT_ITEM_ID = 0; // Put your monetary account ID here + private const int UserItemId = 0; // Put your user ID here + private const int MonetaryAccountItemId = 0; // Put your monetary account ID here public void Run() { var apiContext = ApiContext.Restore(); var paginationCountOnly = new Pagination { - Count = PAGE_SIZE, + Count = PageSize, }; - Console.WriteLine(MESSAGE_LATEST_PAGE_IDS); - var paymentResponse = Payment.List(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID, + Console.WriteLine(MessageLatestPageAllPaymentId); + var paymentResponse = Payment.List(apiContext, UserItemId, MonetaryAccountItemId, paginationCountOnly.UrlParamsCountOnly); PrintPayments(paymentResponse.Value); var pagination = paymentResponse.Pagination; if (pagination.HasPreviousPage()) { - Console.WriteLine(MESSAGE_SECOND_LATEST_PAGE_IDS); - var previousPaymentResponse = Payment.List(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID, + Console.WriteLine(MessageSecondLatestPageAllPaymentId); + var previousPaymentResponse = Payment.List(apiContext, UserItemId, MonetaryAccountItemId, pagination.UrlParamsPreviousPage); PrintPayments(previousPaymentResponse.Value); } else { - Console.WriteLine(MESSAGE_NO_PRIOR_PAYMENTS_FOUND); + Console.WriteLine(MessageNoPriorPaymentFound); } } diff --git a/BunqSdk.Samples/PaymentSample.cs b/BunqSdk.Samples/PaymentSample.cs index be0b8cb..d8a020e 100644 --- a/BunqSdk.Samples/PaymentSample.cs +++ b/BunqSdk.Samples/PaymentSample.cs @@ -9,30 +9,30 @@ namespace Bunq.Sdk.Samples { public class PaymentSample : ISample { - private const int USER_ITEM_ID = 0; // Put your user ID here - private const int MONETARY_ACCOUNT_ITEM_ID = 0; // Put your monetary account ID here - private const string PAYMENT_AMOUNT = "0.01"; - private const string PAYMENT_CURRENCY = "EUR"; - private const string COUNTERPARTY_POINTER_TYPE = "EMAIL"; - private const string COUNTERPARTY_EMAIL = "bravo@bunq.com"; - private const string PAYMENT_DESCRIPTION = "This is a generated payment!"; + private const int UserItemId = 0; // Put your user ID here + private const int MonetaryAccountItemId = 0; // Put your monetary account ID here + private const string ValueAmountEur = "0.01"; + private const string ValueCurrencyEur = "EUR"; + private const string CounterPartyPointerType = "EMAIL"; + private const string CounterPartyEmail = "bravo@bunq.com"; + private const string ValueDescription = "This is a generated payment!"; public void Run() { var apiContext = ApiContext.Restore(); var paymentMap = new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(PAYMENT_AMOUNT, PAYMENT_CURRENCY)}, + {Payment.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, { Payment.FIELD_COUNTERPARTY_ALIAS, - new Pointer(COUNTERPARTY_POINTER_TYPE, COUNTERPARTY_EMAIL) + new Pointer(CounterPartyPointerType, CounterPartyEmail) }, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION} + {Payment.FIELD_DESCRIPTION, ValueDescription} }; - var paymentId = Payment.Create(apiContext, paymentMap, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID).Value; + var paymentId = Payment.Create(apiContext, paymentMap, UserItemId, MonetaryAccountItemId).Value; - Console.WriteLine(Payment.Get(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID, paymentId)); + Console.WriteLine(Payment.Get(apiContext, UserItemId, MonetaryAccountItemId, paymentId)); // Save the API context to account for all the changes that might have occurred to it // during the sample execution diff --git a/BunqSdk.Samples/RequestSample.cs b/BunqSdk.Samples/RequestSample.cs index ba40970..0a2dc95 100644 --- a/BunqSdk.Samples/RequestSample.cs +++ b/BunqSdk.Samples/RequestSample.cs @@ -9,31 +9,31 @@ namespace Bunq.Sdk.Samples { public class RequestSample : ISample { - private const string REQUEST_AMOUNT = "12.30"; - private const string REQUEST_CURRENCY = "EUR"; - private const string COUNTERPARTY_POINTER_TYPE = "EMAIL"; - private const string COUNTERPARTY_EMAIL = "bravo@bunq.com"; - private const string REQUEST_DESCRIPTION = "This is a generated request!"; - private const int USER_ITEM_ID = 0; // Put your user ID here - private const int MONETARY_ACCOUNT_ITEM_ID = 0; // Put your monetary account ID here - private const string STATUS_REVOKED = "REVOKED"; + private const string CounterPartyEmail = "bravo@bunq.com"; + private const string CounterPartyPointerType = "EMAIL"; + private const string ValueAmountEur = "12.30"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueDescription = "This is a generated request!"; + private const string ValueStatusRevoked = "REVOKED"; + private const int UserItemId = 0; // Put your user ID here + private const int MonetaryAccountItemId = 0; // Put your monetary account ID here public void Run() { var apiContext = ApiContext.Restore(); var requestMap = new Dictionary { - {RequestInquiry.FIELD_AMOUNT_INQUIRED, new Amount(REQUEST_AMOUNT, REQUEST_CURRENCY)}, - {RequestInquiry.FIELD_COUNTERPARTY_ALIAS, new Pointer(COUNTERPARTY_POINTER_TYPE, COUNTERPARTY_EMAIL)}, - {RequestInquiry.FIELD_DESCRIPTION, REQUEST_DESCRIPTION}, + {RequestInquiry.FIELD_AMOUNT_INQUIRED, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {RequestInquiry.FIELD_COUNTERPARTY_ALIAS, new Pointer(CounterPartyPointerType, CounterPartyEmail)}, + {RequestInquiry.FIELD_DESCRIPTION, ValueDescription}, {RequestInquiry.FIELD_ALLOW_BUNQME, true} }; - var requestId = RequestInquiry.Create(apiContext, requestMap, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID).Value; - Console.WriteLine(RequestInquiry.Get(apiContext, USER_ITEM_ID, MONETARY_ACCOUNT_ITEM_ID, requestId)); + var requestId = RequestInquiry.Create(apiContext, requestMap, UserItemId, MonetaryAccountItemId).Value; + Console.WriteLine(RequestInquiry.Get(apiContext, UserItemId, MonetaryAccountItemId, requestId)); - var requestUpdateMap = new Dictionary {{RequestInquiry.FIELD_STATUS, STATUS_REVOKED}}; - var requestUpdated = RequestInquiry.Update(apiContext, requestUpdateMap, USER_ITEM_ID, - MONETARY_ACCOUNT_ITEM_ID, requestId); + var requestUpdateMap = new Dictionary {{RequestInquiry.FIELD_STATUS, ValueStatusRevoked}}; + var requestUpdated = RequestInquiry.Update(apiContext, requestUpdateMap, UserItemId, + MonetaryAccountItemId, requestId); Console.WriteLine(requestUpdated); } } diff --git a/BunqSdk.Tests/BunqSdkTestBase.cs b/BunqSdk.Tests/BunqSdkTestBase.cs index cacef7e..0033b11 100644 --- a/BunqSdk.Tests/BunqSdkTestBase.cs +++ b/BunqSdk.Tests/BunqSdkTestBase.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Bunq.Sdk.Context; using Bunq.Sdk.Exception; -using Bunq.Sdk.Model.Generated.Endpoint; namespace Bunq.Sdk.Tests { @@ -13,18 +12,18 @@ public class BunqSdkTestBase /// /// Name of the context configuration file. /// - private const string FILENAME_CONTEXT_CONF = "../../../bunq-test.conf"; + private const string FilenameContextConf = "../../../bunq-test.conf"; /// /// Device description used for tests. /// - private const string DEVICE_DESCRIPTION_TEST = "Csharp unit test"; + private const string DeviceDescriptionTest = "Csharp unit test"; /// /// Configuration items. /// - private static readonly string API_KEY = Config.GetApiKey(); - private static readonly string[] FIELD_PERMITTED_IPS = Config.GetPermittedIps(); + private static readonly string ApiKey = Config.GetApiKey(); + private static readonly string[] FieldAllPermittedIp = Config.GetAllPermittedIp(); /// /// Gets an Api Context, re-creates if needed and returns it. @@ -35,7 +34,7 @@ protected static ApiContext GetApiContext() try { - apiContext = ApiContext.Restore(FILENAME_CONTEXT_CONF); + apiContext = ApiContext.Restore(FilenameContextConf); } catch (BunqException) { @@ -43,15 +42,15 @@ protected static ApiContext GetApiContext() } apiContext.EnsureSessionActive(); - apiContext.Save(FILENAME_CONTEXT_CONF); + apiContext.Save(FilenameContextConf); return apiContext; } private static ApiContext CreateApiContext() { - return ApiContext.Create(ApiEnvironmentType.SANDBOX, API_KEY, DEVICE_DESCRIPTION_TEST, - new List(FIELD_PERMITTED_IPS)); + return ApiContext.Create(ApiEnvironmentType.Sandbox, ApiKey, DeviceDescriptionTest, + new List(FieldAllPermittedIp)); } } } diff --git a/BunqSdk.Tests/Config.cs b/BunqSdk.Tests/Config.cs index 16cc9f3..02e0837 100644 --- a/BunqSdk.Tests/Config.cs +++ b/BunqSdk.Tests/Config.cs @@ -9,101 +9,101 @@ public class Config /// /// Delimiter between the IP addresses in the PERMITTED_IPS field. /// - private const char DELIMITER_IPS = ','; + private const char DelimiterIp = ','; /// /// Length of an empty array. /// - private const int LENGTH_NONE = 0; + private const int LengthNone = 0; /// /// Field constants. /// - private const string FIELD_CONFIG_FILE_PATH = "../../../Resources/config.json"; - private const string FIELD_USER_ID = "USER_ID"; - private const string FIELD_API_KEY = "API_KEY"; - private const string FIELD_PERMITTED_IPS = "PERMITTED_IPS"; - private const string FIELD_ATTACHMENT_PUBLIC_TEST = "AttachmentPublicTest"; - private const string FIELD_ATTACHMENT_PATH_IN = "PATH_IN"; - private const string FIELD_ATTACHMENT_DESCRIPTION = "DESCRIPTION"; - private const string FIELD_ATTACHMENT_CONTENT_TYPE = "CONTENT_TYPE"; - private const string FIELD_MONETARY_ACCOUNT_ID = "MONETARY_ACCOUNT_ID"; - private const string FIELD_MONETARY_ACCOUNT_ID2 = "MONETARY_ACCOUNT_ID2"; - private const string FIELD_COUNTER_PARTY_SELF = "CounterPartySelf"; - private const string FIELD_COUNTER_PARTY_OTHER = "CounterPartyOther"; - private const string FIELD_COUNTER_ALIAS = "Alias"; - private const string FIELD_COUNTER_TYPE = "Type"; - private const string FIELD_TAB_USAGE_SINGLE = "TabUsageSingleTest"; - private const string FIELD_CASH_REGISTER_ID = "CASH_REGISTER_ID"; + private const string FieldConfigFilePath = "../../../Resources/config.json"; + private const string FieldUserId = "USER_ID"; + private const string FieldApiKey = "API_KEY"; + private const string FieldAllPermittedIp = "PERMITTED_IP"; + private const string FieldAttachmentPublicTest = "AttachmentPublicTest"; + private const string FieldAttachmentPathIn = "PATH_IN"; + private const string FieldAttachmentDescription = "DESCRIPTION"; + private const string FieldAttachmentContentType = "CONTENT_TYPE"; + private const string FieldMonetaryAccountId = "MONETARY_ACCOUNT_ID"; + private const string FieldMonetaryAccountId2 = "MONETARY_ACCOUNT_ID2"; + private const string FieldCounterPartySelf = "CounterPartySelf"; + private const string FieldCounterPartyOther = "CounterPartyOther"; + private const string FieldCounterAlias = "Alias"; + private const string FieldCounterType = "Type"; + private const string FieldTabUsageSingle = "TabUsageSingleTest"; + private const string FieldCashRegisterId = "CASH_REGISTER_ID"; public static int GetCashRegisterId() { - return GetConfig()[FIELD_TAB_USAGE_SINGLE][FIELD_CASH_REGISTER_ID].ToObject(); + return GetConfig()[FieldTabUsageSingle][FieldCashRegisterId].ToObject(); } public static Pointer GetCounterPartyAliasOther() { - var alias = GetConfig()[FIELD_COUNTER_PARTY_OTHER][FIELD_COUNTER_ALIAS].ToString(); - var type = GetConfig()[FIELD_COUNTER_PARTY_OTHER][FIELD_COUNTER_TYPE].ToString(); + var alias = GetConfig()[FieldCounterPartyOther][FieldCounterAlias].ToString(); + var type = GetConfig()[FieldCounterPartyOther][FieldCounterType].ToString(); return new Pointer(type, alias); } public static Pointer GetCounterPartyAliasSelf() { - var alias = GetConfig()[FIELD_COUNTER_PARTY_SELF][FIELD_COUNTER_ALIAS].ToString(); - var type = GetConfig()[FIELD_COUNTER_PARTY_SELF][FIELD_COUNTER_TYPE].ToString(); + var alias = GetConfig()[FieldCounterPartySelf][FieldCounterAlias].ToString(); + var type = GetConfig()[FieldCounterPartySelf][FieldCounterType].ToString(); return new Pointer(type, alias); } public static int GetSecondMonetaryAccountId() { - return GetConfig()[FIELD_MONETARY_ACCOUNT_ID2].ToObject(); + return GetConfig()[FieldMonetaryAccountId2].ToObject(); } public static int GetMonetarytAccountId() { - return GetConfig()[FIELD_MONETARY_ACCOUNT_ID].ToObject(); + return GetConfig()[FieldMonetaryAccountId].ToObject(); } public static string GetAttachmentPathIn() { - return GetConfig()[FIELD_ATTACHMENT_PUBLIC_TEST][FIELD_ATTACHMENT_PATH_IN].ToString(); + return GetConfig()[FieldAttachmentPublicTest][FieldAttachmentPathIn].ToString(); } - public static string GetAttachmentDescrpition() + public static string GetAttachmentDescription() { - return GetConfig()[FIELD_ATTACHMENT_PUBLIC_TEST][FIELD_ATTACHMENT_DESCRIPTION].ToString(); + return GetConfig()[FieldAttachmentPublicTest][FieldAttachmentDescription].ToString(); } public static string GetAttachmentContentType() { - return GetConfig()[FIELD_ATTACHMENT_PUBLIC_TEST][FIELD_ATTACHMENT_CONTENT_TYPE].ToString(); + return GetConfig()[FieldAttachmentPublicTest][FieldAttachmentContentType].ToString(); } - public static string[] GetPermittedIps() + public static string[] GetAllPermittedIp() { - var permittedIpsString = GetConfig()[FIELD_PERMITTED_IPS].ToString(); + var allPermittedIp = GetConfig()[FieldAllPermittedIp].ToString(); - return permittedIpsString.Length == LENGTH_NONE ? - new string[LENGTH_NONE] : - permittedIpsString.Split(DELIMITER_IPS); + return allPermittedIp.Length == LengthNone + ? new string[LengthNone] + : allPermittedIp.Split(DelimiterIp); } public static string GetApiKey() { - return GetConfig()[FIELD_API_KEY].ToString(); + return GetConfig()[FieldApiKey].ToString(); } public static int GetUserId() { - return GetConfig()[FIELD_USER_ID].ToObject(); + return GetConfig()[FieldUserId].ToObject(); } private static JObject GetConfig() { - var fileContentString = File.ReadAllText(FIELD_CONFIG_FILE_PATH); + var fileContentString = File.ReadAllText(FieldConfigFilePath); return JObject.Parse(fileContentString); } diff --git a/BunqSdk.Tests/Context/ApiContextTest.cs b/BunqSdk.Tests/Context/ApiContextTest.cs index 9ed1318..ad10937 100644 --- a/BunqSdk.Tests/Context/ApiContextTest.cs +++ b/BunqSdk.Tests/Context/ApiContextTest.cs @@ -12,7 +12,7 @@ public class ApiContextTest : BunqSdkTestBase, IClassFixture /// /// Path to a temporary context file. /// - private const string CONTEXT_FILENAME_TEST = "context-save-restore-test.conf"; + private const string ContextFilenameTest = "context-save-restore-test.conf"; private static ApiContext apiContext; @@ -40,8 +40,8 @@ public void TestApiContextSerializeDeserialize() public void TestApiContextSaveRestore() { var apiContextJson = apiContext.ToJson(); - apiContext.Save(CONTEXT_FILENAME_TEST); - var apiContextRestored = ApiContext.Restore(CONTEXT_FILENAME_TEST); + apiContext.Save(ContextFilenameTest); + var apiContextRestored = ApiContext.Restore(ContextFilenameTest); Assert.Equal(apiContextJson, apiContextRestored.ToJson()); } diff --git a/BunqSdk.Tests/Http/PaginationScenarioTest.cs b/BunqSdk.Tests/Http/PaginationScenarioTest.cs index 848bfef..abde27b 100644 --- a/BunqSdk.Tests/Http/PaginationScenarioTest.cs +++ b/BunqSdk.Tests/Http/PaginationScenarioTest.cs @@ -17,28 +17,28 @@ public class PaginationScenarioTest : BunqSdkTestBase /// /// Config values. /// - private static readonly int USER_ID = Config.GetUserId(); - private static readonly int MONETARY_ACCOUNT_ID = Config.GetMonetarytAccountId(); - private static readonly Pointer COUNTER_PARTY_OTHER = Config.GetCounterPartyAliasOther(); + private static readonly int UserId = Config.GetUserId(); + private static readonly int MonetaryAccountId = Config.GetMonetarytAccountId(); + private static readonly Pointer CounterPartyOther = Config.GetCounterPartyAliasOther(); /// /// Constants for scenario testing. /// - private const int PAYMENT_LISTING_PAGE_SIZE = 2; - private const int PAYMENT_REQUIRED_COUNT_MINIMUM = PAYMENT_LISTING_PAGE_SIZE * 2; - private const int NUMBER_ZERO = 0; + private const int PaymentListingPageSize = 2; + private const int PaymentRequiredCountMinimum = PaymentListingPageSize * 2; + private const int NumberZero = 0; /// /// Constants for payment creation. /// - private const string PAYMENT_AMOUNT_EUR = "0.01"; - private const string PAYMENT_CURRENCY = "EUR"; - private const string PAYMENT_DESCRIPTION = "C# test Payment"; + private const string PaymentAmountEur = "0.01"; + private const string PaymentCurrencyEur = "EUR"; + private const string PaymentDescription = "C# test Payment"; /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); [Fact] public void TestApiScenarioPaymentListingWithPagination() @@ -47,7 +47,7 @@ public void TestApiScenarioPaymentListingWithPagination() var paymentsExpected = new List(GetPaymentsRequired()); var paginationCountOnly = new Pagination { - Count = PAYMENT_LISTING_PAGE_SIZE + Count = PaymentListingPageSize }; var responseLatest = ListPayments(paginationCountOnly.UrlParamsCountOnly); @@ -67,7 +67,7 @@ public void TestApiScenarioPaymentListingWithPagination() private static void EnsureEnoughPayments() { - for (var i = NUMBER_ZERO; i < GetPaymentsMissingCount(); ++i) + for (var i = NumberZero; i < GetPaymentsMissingCount(); ++i) { CreatePayment(); } @@ -75,14 +75,14 @@ private static void EnsureEnoughPayments() private static int GetPaymentsMissingCount() { - return PAYMENT_REQUIRED_COUNT_MINIMUM - GetPaymentsRequired().Count; + return PaymentRequiredCountMinimum - GetPaymentsRequired().Count; } private static IList GetPaymentsRequired() { var pagination = new Pagination { - Count = PAYMENT_REQUIRED_COUNT_MINIMUM + Count = PaymentRequiredCountMinimum }; return ListPayments(pagination.UrlParamsCountOnly).Value; @@ -90,19 +90,19 @@ private static IList GetPaymentsRequired() private static BunqResponse> ListPayments(IDictionary urlParams) { - return Payment.List(API_CONTEXT, USER_ID, MONETARY_ACCOUNT_ID, urlParams); + return Payment.List(ApiContext, UserId, MonetaryAccountId, urlParams); } private static void CreatePayment() { var requestMap = new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(PAYMENT_AMOUNT_EUR, PAYMENT_CURRENCY)}, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION}, - {Payment.FIELD_COUNTERPARTY_ALIAS, COUNTER_PARTY_OTHER} + {Payment.FIELD_AMOUNT, new Amount(PaymentAmountEur, PaymentCurrencyEur)}, + {Payment.FIELD_DESCRIPTION, PaymentDescription}, + {Payment.FIELD_COUNTERPARTY_ALIAS, CounterPartyOther} }; - Payment.Create(API_CONTEXT, requestMap, USER_ID, MONETARY_ACCOUNT_ID); + Payment.Create(ApiContext, requestMap, UserId, MonetaryAccountId); } } } diff --git a/BunqSdk.Tests/Http/PaginationTest.cs b/BunqSdk.Tests/Http/PaginationTest.cs index e59a137..0bac280 100644 --- a/BunqSdk.Tests/Http/PaginationTest.cs +++ b/BunqSdk.Tests/Http/PaginationTest.cs @@ -14,10 +14,10 @@ public class PaginationTest /// /// Values of pagination properties for testing. /// - private const int PAGINATION_OLDER_ID_CUSTOM = 1; - private const int PAGINATION_NEWER_ID_CUSTOM = 2; - private const int PAGINATION_FUTURE_ID_CUSTOM = 3; - private const int PAGINATION_COUNT_CUSTOM = 5; + private const int PaginationOlderIdCustom = 1; + private const int PaginationNewerIdCustom = 2; + private const int PaginationFutureIdCustom = 3; + private const int PaginationCountCustom = 5; [Fact] public void TestGetUrlParamsCountOnly() @@ -25,7 +25,7 @@ public void TestGetUrlParamsCountOnly() var pagination = CreatePaginationWithAllPropertiesSet(); var urlParamsCountOnlyExpected = new Dictionary { - {Pagination.PARAM_COUNT, PAGINATION_COUNT_CUSTOM.ToString()} + {Pagination.ParamCount, PaginationCountCustom.ToString()} }; Assert.Equal(urlParamsCountOnlyExpected, pagination.UrlParamsCountOnly); @@ -35,10 +35,10 @@ private static Pagination CreatePaginationWithAllPropertiesSet() { return new Pagination { - OlderId = PAGINATION_OLDER_ID_CUSTOM, - NewerId = PAGINATION_NEWER_ID_CUSTOM, - FutureId = PAGINATION_FUTURE_ID_CUSTOM, - Count = PAGINATION_COUNT_CUSTOM + OlderId = PaginationOlderIdCustom, + NewerId = PaginationNewerIdCustom, + FutureId = PaginationFutureIdCustom, + Count = PaginationCountCustom }; } @@ -48,8 +48,8 @@ public void TestGetUrlParamsPreviousPage() var pagination = CreatePaginationWithAllPropertiesSet(); var urlParamsPreviousPageExpected = new Dictionary { - {Pagination.PARAM_COUNT, PAGINATION_COUNT_CUSTOM.ToString()}, - {Pagination.PARAM_OLDER_ID, PAGINATION_OLDER_ID_CUSTOM.ToString()} + {Pagination.ParamCount, PaginationCountCustom.ToString()}, + {Pagination.ParamOlderId, PaginationOlderIdCustom.ToString()} }; Assert.True(pagination.HasPreviousPage()); @@ -63,7 +63,7 @@ public void TestGetUrlParamsPreviousPageNoCount() pagination.Count = null; var urlParamsPreviousPageExpected = new Dictionary { - {Pagination.PARAM_OLDER_ID, PAGINATION_OLDER_ID_CUSTOM.ToString()} + {Pagination.ParamOlderId, PaginationOlderIdCustom.ToString()} }; Assert.True(pagination.HasPreviousPage()); @@ -76,8 +76,8 @@ public void TestGetUrlParamsNextPageNewer() var pagination = CreatePaginationWithAllPropertiesSet(); var urlParamsNextPageExpected = new Dictionary { - {Pagination.PARAM_COUNT, PAGINATION_COUNT_CUSTOM.ToString()}, - {Pagination.PARAM_NEWER_ID, PAGINATION_NEWER_ID_CUSTOM.ToString()} + {Pagination.ParamCount, PaginationCountCustom.ToString()}, + {Pagination.ParamNewerId, PaginationNewerIdCustom.ToString()} }; Assert.True(pagination.HasNextPageAssured()); @@ -91,7 +91,7 @@ public void TestGetUrlParamsNextPageNewerNoCount() pagination.Count = null; var urlParamsNextPageExpected = new Dictionary { - {Pagination.PARAM_NEWER_ID, PAGINATION_NEWER_ID_CUSTOM.ToString()} + {Pagination.ParamNewerId, PaginationNewerIdCustom.ToString()} }; Assert.True(pagination.HasNextPageAssured()); @@ -105,8 +105,8 @@ public void TestGetUrlParamsNextPageFuture() pagination.NewerId = null; var urlParamsNextPageExpected = new Dictionary { - {Pagination.PARAM_COUNT, PAGINATION_COUNT_CUSTOM.ToString()}, - {Pagination.PARAM_NEWER_ID, PAGINATION_FUTURE_ID_CUSTOM.ToString()} + {Pagination.ParamCount, PaginationCountCustom.ToString()}, + {Pagination.ParamNewerId, PaginationFutureIdCustom.ToString()} }; Assert.False(pagination.HasNextPageAssured()); @@ -120,8 +120,8 @@ public void TestGetUrlParamsNextPageFutureNoCount() pagination.NewerId = null; var urlParamsNextPageExpected = new Dictionary { - {Pagination.PARAM_COUNT, PAGINATION_COUNT_CUSTOM.ToString()}, - {Pagination.PARAM_NEWER_ID, PAGINATION_FUTURE_ID_CUSTOM.ToString()} + {Pagination.ParamCount, PaginationCountCustom.ToString()}, + {Pagination.ParamNewerId, PaginationFutureIdCustom.ToString()} }; Assert.False(pagination.HasNextPageAssured()); diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/AttachmentPublicTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/AttachmentPublicTest.cs index fbc5135..82f765b 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/AttachmentPublicTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/AttachmentPublicTest.cs @@ -17,16 +17,19 @@ public class AttachmentPublicTest : BunqSdkTestBase /// /// Config values. /// - private const string PATH_ATTACHMENT = "../../../Resources"; - - private static readonly string CONTENT_TYPE = Config.GetAttachmentContentType(); - private static readonly string ATTACHMENT_DESCRIPTION = Config.GetAttachmentDescrpition(); - private static readonly string ATTACHMENT_PATH_IN = Config.GetAttachmentPathIn(); - + private static readonly string ContentType = Config.GetAttachmentContentType(); + private static readonly string AttachmentDescription = Config.GetAttachmentDescription(); + private static readonly string AttachmentPathIn = Config.GetAttachmentPathIn(); + + /// + /// File path constatns. + /// + private const string PathAttachment = "../../../Resources"; + /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests if the file we upload is the file we are getting back once successfully uploaded does. @@ -35,15 +38,15 @@ public class AttachmentPublicTest : BunqSdkTestBase [Fact] public void TestAttachmentUploadAndRetrieval() { - var fileContentBytes = File.ReadAllBytes(PATH_ATTACHMENT + ATTACHMENT_PATH_IN); + var fileContentBytes = File.ReadAllBytes(PathAttachment + AttachmentPathIn); var customHeaders = new Dictionary { - {ApiClient.HEADER_CONTENT_TYPE, CONTENT_TYPE}, - {ApiClient.HEADER_ATTACHMENT_DESCRIPTION, ATTACHMENT_DESCRIPTION} + {ApiClient.HeaderContentType, ContentType}, + {ApiClient.HeaderAttachmentDescription, AttachmentDescription} }; - var attachmentUuid = AttachmentPublic.Create(API_CONTEXT, fileContentBytes, customHeaders).Value; - var responseBytes = AttachmentPublicContent.List(API_CONTEXT, attachmentUuid).Value; + var attachmentUuid = AttachmentPublic.Create(ApiContext, fileContentBytes, customHeaders).Value; + var responseBytes = AttachmentPublicContent.List(ApiContext, attachmentUuid).Value; Assert.Equal(fileContentBytes, responseBytes); } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/AvatarTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/AvatarTest.cs index 0023cb1..e2abdcf 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/AvatarTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/AvatarTest.cs @@ -18,17 +18,24 @@ public class AvatarTest : BunqSdkTestBase /// /// Config values. /// - private const string PATH_TO_ATTACHMENT = "../../../Resources"; - private const int INDEX_FIRST = 0; + private static readonly string AttachmentContentType = Config.GetAttachmentContentType(); + private static readonly string AttachmentDescription = Config.GetAttachmentDescription(); + private static readonly string AttachmentPathIn = Config.GetAttachmentPathIn(); - private static readonly string CONTEN_TYPE = Config.GetAttachmentContentType(); - private static readonly string ATTACHMENT_DECSRIPTION = Config.GetAttachmentDescrpition(); - private static readonly string ATTACHMENT_PATH_IN = Config.GetAttachmentPathIn(); + /// + /// File path constatns. + /// + private const string PathAttachment = "../../../Resources"; + + /// + /// The index of the first item in an array. + /// + private const int IndexFirst = 0; /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests the creation of an avatar by uploading a picture via AttachmentPublic and setting it as avatar @@ -37,18 +44,18 @@ public class AvatarTest : BunqSdkTestBase [Fact] public void TestCreateAvatarAndRetrieval() { - var fileContentByte = File.ReadAllBytes(PATH_TO_ATTACHMENT + ATTACHMENT_PATH_IN); + var fileContentByte = File.ReadAllBytes(PathAttachment + AttachmentPathIn); var attachmentUuid = UploadAvatarAndGetUuid(fileContentByte); var avatarMap = new Dictionary { {Avatar.FIELD_ATTACHMENT_PUBLIC_UUID, attachmentUuid} }; - var avatarUuid = Avatar.Create(API_CONTEXT, avatarMap).Value; + var avatarUuid = Avatar.Create(ApiContext, avatarMap).Value; - var attachmentUuidFromAvatar = Avatar.Get(API_CONTEXT, avatarUuid).Value - .Image[INDEX_FIRST].AttachmentPublicUuid; - var revievedFileContentByte = AttachmentPublicContent.List(API_CONTEXT, attachmentUuidFromAvatar).Value; + var attachmentUuidFromAvatar = Avatar.Get(ApiContext, avatarUuid).Value + .Image[IndexFirst].AttachmentPublicUuid; + var revievedFileContentByte = AttachmentPublicContent.List(ApiContext, attachmentUuidFromAvatar).Value; Assert.Equal(attachmentUuid, attachmentUuidFromAvatar); Assert.Equal(fileContentByte, revievedFileContentByte); @@ -58,11 +65,11 @@ private static string UploadAvatarAndGetUuid(byte[] fileContentByte) { var customHeaders = new Dictionary { - {ApiClient.HEADER_ATTACHMENT_DESCRIPTION, ATTACHMENT_DECSRIPTION}, - {ApiClient.HEADER_CONTENT_TYPE, CONTEN_TYPE}, + {ApiClient.HeaderAttachmentDescription, AttachmentDescription}, + {ApiClient.HeaderContentType, AttachmentContentType}, }; - return AttachmentPublic.Create(API_CONTEXT, fileContentByte, customHeaders).Value; + return AttachmentPublic.Create(ApiContext, fileContentByte, customHeaders).Value; } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/CardDebitTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/CardDebitTest.cs index a2c432b..03269a0 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/CardDebitTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/CardDebitTest.cs @@ -17,19 +17,30 @@ public class CardDebitTest : BunqSdkTestBase /// /// Config values. /// - private const string PIN_CODE = "4045"; - private const int INDEX_FIRST = 0; - private const int NONNEGATIVE_INTEGER_MINIMUM = 0; - private const int BASE_DECIMAL = 10; - private const int CARD_SECOND_LINE_LENGTH_MAXIMUM = 20; - private const int NUMBER_ONE = 1; - - private static readonly int USER_ID = Config.GetUserId(); + private static readonly int UserId = Config.GetUserId(); + + /// + /// CardeDebit field value constatns. + /// + private const string CardDebitPinCode = "4045"; + private const int CardDebitSecondLineLengthMaximum = 20; + + /// + /// The index of the first item in an array. + /// + private const int IndexFirst = 0; + /// + /// Number constatns. + /// + private const int NumberOne = 1; + private const int NonNegativeIntegerMinimum = 0; + private const int BaseDecimal = 10; + /// /// API context used to for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests ordering a new card and checks if the fields we have entered are indeed correct by. @@ -41,12 +52,12 @@ public void TestOrderNewMaestroCard() { {CardDebit.FIELD_ALIAS, GetAlias()}, {CardDebit.FIELD_NAME_ON_CARD, GetAnAllowedName()}, - {CardDebit.FIELD_PIN_CODE, PIN_CODE}, + {CardDebit.FIELD_PIN_CODE, CardDebitPinCode}, {CardDebit.FIELD_SECOND_LINE, GenerateRandomSecondLine()} }; - var cardDebit = CardDebit.Create(API_CONTEXT, cardDebitMap, USER_ID).Value; + var cardDebit = CardDebit.Create(ApiContext, cardDebitMap, UserId).Value; - var cardFromCardEndpoint = Card.Get(API_CONTEXT, USER_ID, cardDebit.Id.Value).Value; + var cardFromCardEndpoint = Card.Get(ApiContext, UserId, cardDebit.Id.Value).Value; Assert.Equal(cardDebit.SecondLine, cardFromCardEndpoint.SecondLine); Assert.Equal(cardDebit.Created, cardFromCardEndpoint.Created); @@ -55,7 +66,7 @@ public void TestOrderNewMaestroCard() private static string GetAnAllowedName() { - return CardName.List(API_CONTEXT, USER_ID).Value[INDEX_FIRST].PossibleCardNameArray[INDEX_FIRST]; + return CardName.List(ApiContext, UserId).Value[IndexFirst].PossibleCardNameArray[IndexFirst]; } private static string GenerateRandomSecondLine() @@ -63,14 +74,14 @@ private static string GenerateRandomSecondLine() var random = new Random(); return random.Next( - NONNEGATIVE_INTEGER_MINIMUM, - (int) Math.Pow(BASE_DECIMAL, CARD_SECOND_LINE_LENGTH_MAXIMUM + NUMBER_ONE) - NUMBER_ONE + NonNegativeIntegerMinimum, + (int) Math.Pow(BaseDecimal, CardDebitSecondLineLengthMaximum + NumberOne) - NumberOne ).ToString(); } private static Pointer GetAlias() { - return User.Get(API_CONTEXT, USER_ID).Value.UserCompany.Alias[INDEX_FIRST]; + return User.Get(ApiContext, UserId).Value.UserCompany.Alias[IndexFirst]; } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/DraftShareInviteBankQrCodeContentTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/DraftShareInviteBankQrCodeContentTest.cs index a5a9b22..f390947 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/DraftShareInviteBankQrCodeContentTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/DraftShareInviteBankQrCodeContentTest.cs @@ -18,17 +18,24 @@ public class DraftShareInviteBankQrCodeContentTest : BunqSdkTestBase /// /// Config values. /// - private const string FILENAME_QR_CODE_IMAGE = "tmp/qrcode.png"; - private const int TIME_UNIT_AMOUNT_ZERO = 0; - private const int TIME_UNIT_AMOUNT_ONE = 1; - private const string FORMAT_DATE = "yyyy-MM-dd HH:mm:ss"; - - private static readonly int USER_ID = Config.GetUserId(); + private static readonly int UserId = Config.GetUserId(); + /// + /// File name constants + /// + private const string FileNameQrCodeImage = "tmp/qrcode.png"; + + /// + /// Date and time constatns. + /// + private const int TimeUnitAmountZero = 0; + private const int TimeUnitAmountOne = 1; + private const string FormatDate = "yyyy-MM-dd HH:mm:ss"; + /// /// API context to use for the test API calls /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests the creation of a connect and getting the qr code related to this connect. @@ -40,9 +47,9 @@ public void TestCreateInviteBankAndGetQrCode() { var draftId = GetShareInviteId(); - var qrContent = DraftShareInviteBankQrCodeContent.List(API_CONTEXT, USER_ID, draftId).Value; + var qrContent = DraftShareInviteBankQrCodeContent.List(ApiContext, UserId, draftId).Value; - var fileOut = new FileInfo(FILENAME_QR_CODE_IMAGE); + var fileOut = new FileInfo(FileNameQrCodeImage); fileOut.Directory.Create(); File.WriteAllBytes(fileOut.FullName, qrContent); } @@ -50,8 +57,8 @@ public void TestCreateInviteBankAndGetQrCode() private static int GetShareInviteId() { var currentDate = DateTime.UtcNow.Date; - var addTime = new TimeSpan(TIME_UNIT_AMOUNT_ZERO, TIME_UNIT_AMOUNT_ONE, TIME_UNIT_AMOUNT_ZERO); - var expirationTime = currentDate.Add(addTime).ToString(FORMAT_DATE); + var addTime = new TimeSpan(TimeUnitAmountZero, TimeUnitAmountOne, TimeUnitAmountZero); + var expirationTime = currentDate.Add(addTime).ToString(FormatDate); var draftShareInviteBankEntry = new DraftShareInviteBankEntry(new ShareDetail {Payment = new ShareDetailPayment(true, true, true, true)}); @@ -62,7 +69,7 @@ private static int GetShareInviteId() {DraftShareInviteBank.FIELD_EXPIRATION, expirationTime} }; - return DraftShareInviteBank.Create(API_CONTEXT, requestMap, USER_ID).Value; + return DraftShareInviteBank.Create(ApiContext, requestMap, UserId).Value; } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/MonetaryAccountBankTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/MonetaryAccountBankTest.cs index 6de7ebb..7b8c2b7 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/MonetaryAccountBankTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/MonetaryAccountBankTest.cs @@ -14,19 +14,22 @@ public class MonetaryAccountBankTest : BunqSdkTestBase /// /// Config values /// - private const string STATUS = "CANCELLED"; - private const string SUBS_STATUS = "REDEMPTION_VOLUNTARY"; - private const string REASON = "OTHER"; - private const string REASON_DESCRIPTION = "Because this is a test"; - private const string CURRENCY = "EUR"; - private const string MONETARY_ACCOUNT_DESCRIPTION = "Test C# monetary account"; - - private static readonly int USER_ID = Config.GetUserId(); + private static readonly int UserId = Config.GetUserId(); + /// + /// MonetaryAccount field value constatns. + /// + private const string ValueStatus = "CANCELLED"; + private const string ValueSubStatus = "REDEMPTION_VOLUNTARY"; + private const string ValueReason = "OTHER"; + private const string ValueReasonDescription = "Because this is a test"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueDescription = "Test C# monetary account"; + /// /// API context used for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests the creation of a new monetary account. This accoult will then be removed afterwards. @@ -36,10 +39,10 @@ public void TestCreationNewMonetaryAccount() { var requestMap = new Dictionary { - {MonetaryAccountBank.FIELD_CURRENCY, CURRENCY}, - {MonetaryAccountBank.FIELD_DESCRIPTION, MONETARY_ACCOUNT_DESCRIPTION} + {MonetaryAccountBank.FIELD_CURRENCY, ValueCurrencyEur}, + {MonetaryAccountBank.FIELD_DESCRIPTION, ValueDescription} }; - var monetaryAccountToCloseId = MonetaryAccountBank.Create(API_CONTEXT, requestMap, USER_ID).Value; + var monetaryAccountToCloseId = MonetaryAccountBank.Create(ApiContext, requestMap, UserId).Value; DeleteMonetaryAccount(monetaryAccountToCloseId); } @@ -48,12 +51,12 @@ private static void DeleteMonetaryAccount(int idToClose) { var requestMap = new Dictionary { - {MonetaryAccountBank.FIELD_STATUS, STATUS}, - {MonetaryAccountBank.FIELD_SUB_STATUS, SUBS_STATUS}, - {MonetaryAccountBank.FIELD_REASON, REASON}, - {MonetaryAccountBank.FIELD_REASON_DESCRIPTION, REASON_DESCRIPTION} + {MonetaryAccountBank.FIELD_STATUS, ValueStatus}, + {MonetaryAccountBank.FIELD_SUB_STATUS, ValueSubStatus}, + {MonetaryAccountBank.FIELD_REASON, ValueReason}, + {MonetaryAccountBank.FIELD_REASON_DESCRIPTION, ValueReasonDescription} }; - MonetaryAccountBank.Update(API_CONTEXT, requestMap, USER_ID, idToClose); + MonetaryAccountBank.Update(ApiContext, requestMap, UserId, idToClose); } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/PaymentChatTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/PaymentChatTest.cs index a288e97..92c5685 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/PaymentChatTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/PaymentChatTest.cs @@ -17,19 +17,22 @@ public class PaymentChatTest : BunqSdkTestBase /// /// Config values. /// - private const string AMOUNT_EUR = "0.01"; - private const string CURRENCY = "EUR"; - private const string PAYMENT_DESCRIPTION = "Payment From C# Test"; - private const string MESSAGE_TEXT = "test msg send from C# test"; - - private static readonly int USER_ID = Config.GetUserId(); - private static readonly int MONETARTY_ACCOUNT_ID = Config.GetMonetarytAccountId(); - private static readonly Pointer COUNTER_PARTY_ALIAS = Config.GetCounterPartyAliasSelf(); + private static readonly int UserId = Config.GetUserId(); + private static readonly int MonetaryAccountId = Config.GetMonetarytAccountId(); + private static readonly Pointer CounterPartyAliasSelf = Config.GetCounterPartyAliasSelf(); + /// + /// Payment and PaymentChat field value constatns. + /// + private const string ValueAmountEur = "0.01"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueDescription = "Payment from C# test"; + private const string ValueText = "Test message sent from C# test"; + /// /// API context used for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests sending a chat message in a newly created payment. @@ -38,26 +41,26 @@ public class PaymentChatTest : BunqSdkTestBase public void TestSendPaymentChat() { var paymentChatMap = new Dictionary(); - var chatId = PaymentChat.Create(API_CONTEXT, paymentChatMap, USER_ID, MONETARTY_ACCOUNT_ID, + var chatId = PaymentChat.Create(ApiContext, paymentChatMap, UserId, MonetaryAccountId, CreatePaymentAndGetId()).Value; var chatMessageMap = new Dictionary { - {ChatMessageText.FIELD_TEXT, MESSAGE_TEXT} + {ChatMessageText.FIELD_TEXT, ValueText} }; - ChatMessageText.Create(API_CONTEXT, chatMessageMap, USER_ID, chatId); + ChatMessageText.Create(ApiContext, chatMessageMap, UserId, chatId); } private static int CreatePaymentAndGetId() { var requestMap = new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(AMOUNT_EUR, CURRENCY)}, - {Payment.FIELD_COUNTERPARTY_ALIAS, COUNTER_PARTY_ALIAS}, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION}, + {Payment.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {Payment.FIELD_COUNTERPARTY_ALIAS, CounterPartyAliasSelf}, + {Payment.FIELD_DESCRIPTION, ValueDescription}, }; - return Payment.Create(API_CONTEXT, requestMap, USER_ID, MONETARTY_ACCOUNT_ID).Value; + return Payment.Create(ApiContext, requestMap, UserId, MonetaryAccountId).Value; } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/PaymentTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/PaymentTest.cs index 83795c5..950cbc7 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/PaymentTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/PaymentTest.cs @@ -15,19 +15,22 @@ public class PaymentTest : BunqSdkTestBase /// /// Config values. /// - private const string PAYMENT_AMOUNT_EUR = "0.01"; - private const string PAYMENT_CURRENCY = "EUR"; - private const string PAYMENT_DESCRIPTION = "C# test Payment"; - - private static readonly int USER_ID = Config.GetUserId(); - private static readonly int MONETARY_ACCOUNT_ID = Config.GetMonetarytAccountId(); - private static readonly Pointer COUNTER_PARTY_SELF = Config.GetCounterPartyAliasSelf(); - private static readonly Pointer COUNTER_PARTY_OTHER = Config.GetCounterPartyAliasOther(); + private static readonly int UserId = Config.GetUserId(); + private static readonly int MonetaryAccountId = Config.GetMonetarytAccountId(); + private static readonly Pointer CounterPartyAliasSelf = Config.GetCounterPartyAliasSelf(); + private static readonly Pointer CounterPartyAliasOther = Config.GetCounterPartyAliasOther(); + /// + /// Payment field value constants. + /// + private const string ValueAmountEur = "0.01"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueDescription = "C# test payment"; + /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests making a payment to another sanndbox user. @@ -39,12 +42,12 @@ public void TestMakePaymentToOtherUser() { var requestMap = new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(PAYMENT_AMOUNT_EUR, PAYMENT_CURRENCY)}, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION}, - {Payment.FIELD_COUNTERPARTY_ALIAS, COUNTER_PARTY_OTHER} + {Payment.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {Payment.FIELD_DESCRIPTION, ValueDescription}, + {Payment.FIELD_COUNTERPARTY_ALIAS, CounterPartyAliasOther} }; - Payment.Create(API_CONTEXT, requestMap, USER_ID, MONETARY_ACCOUNT_ID); + Payment.Create(ApiContext, requestMap, UserId, MonetaryAccountId); } /// @@ -57,12 +60,12 @@ public void TestMakePaymentToOtherAccount() { var requestMap = new Dictionary { - {Payment.FIELD_AMOUNT, new Amount(PAYMENT_AMOUNT_EUR, PAYMENT_CURRENCY)}, - {Payment.FIELD_DESCRIPTION, PAYMENT_DESCRIPTION}, - {Payment.FIELD_COUNTERPARTY_ALIAS, COUNTER_PARTY_SELF} + {Payment.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {Payment.FIELD_DESCRIPTION, ValueDescription}, + {Payment.FIELD_COUNTERPARTY_ALIAS, CounterPartyAliasSelf} }; - Payment.Create(API_CONTEXT, requestMap, USER_ID, MONETARY_ACCOUNT_ID); + Payment.Create(ApiContext, requestMap, UserId, MonetaryAccountId); } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/RequestInquiryTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/RequestInquiryTest.cs index 9b97575..7c92643 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/RequestInquiryTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/RequestInquiryTest.cs @@ -16,21 +16,28 @@ public class RequestInquiryTest : BunqSdkTestBase /// /// Config values. /// - private const string AMOUNT_EUR = "0.01"; - private const string FIELD_CURRENCY = "EUR"; - private const string FIELD_PAYMENT_DESCRIPTION = "C# test Payment"; - private const string FIELD_STATUS = "ACCEPTED"; - private const int INDEX_FIRST = 0; - - private static readonly int USER_ID = Config.GetUserId(); - private static readonly int MONETARY_ACCOUNT_ID = Config.GetMonetarytAccountId(); - private static readonly int SECOND_MONETARY_ACCOUNT_ID = Config.GetSecondMonetaryAccountId(); - private static readonly Pointer COUNTER_PARTY_SELF = Config.GetCounterPartyAliasSelf(); + private static readonly Pointer CounterPartyAliasSelf = Config.GetCounterPartyAliasSelf(); + private static readonly int UserId = Config.GetUserId(); + private static readonly int MonetaryAccountId = Config.GetMonetarytAccountId(); + private static readonly int SecondMonetaryAccountId = Config.GetSecondMonetaryAccountId(); + /// + /// RequestInquiry field value constatns. + /// + private const string ValueAmountEur = "0.01"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueDescription = "C# test payment"; + private const string ValueStatus = "ACCEPTED"; + + /// + /// The index of the first item in an array. + /// + private const int IndexFirst = 0; + /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests sending a request from monetary account 1 to monetary account 2 and accepting this request. @@ -40,28 +47,27 @@ public void TestRequestInquiry() { var requestMap = new Dictionary { - {RequestInquiry.FIELD_AMOUNT_INQUIRED, new Amount(AMOUNT_EUR, FIELD_CURRENCY)}, - {RequestInquiry.FIELD_COUNTERPARTY_ALIAS, COUNTER_PARTY_SELF}, - {RequestInquiry.FIELD_DESCRIPTION, FIELD_PAYMENT_DESCRIPTION}, + {RequestInquiry.FIELD_AMOUNT_INQUIRED, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {RequestInquiry.FIELD_COUNTERPARTY_ALIAS, CounterPartyAliasSelf}, + {RequestInquiry.FIELD_DESCRIPTION, ValueDescription}, {RequestInquiry.FIELD_ALLOW_BUNQME, false} }; - RequestInquiry.Create(API_CONTEXT, requestMap, USER_ID, MONETARY_ACCOUNT_ID); + RequestInquiry.Create(ApiContext, requestMap, UserId, MonetaryAccountId); - Assert.Equal(FIELD_STATUS, AcceptRequest()); + Assert.Equal(ValueStatus, AcceptRequest()); } private static string AcceptRequest() { - var requestResponseId = RequestResponse - .List(API_CONTEXT, USER_ID, SECOND_MONETARY_ACCOUNT_ID).Value[INDEX_FIRST].Id.Value; + var requestResponseId = RequestResponse.List(ApiContext, UserId, SecondMonetaryAccountId).Value[IndexFirst].Id.Value; var requestMap = new Dictionary { - {RequestResponse.FIELD_STATUS, FIELD_STATUS} + {RequestResponse.FIELD_STATUS, ValueStatus} }; - return RequestResponse.Update(API_CONTEXT, requestMap, USER_ID, SECOND_MONETARY_ACCOUNT_ID, + return RequestResponse.Update(ApiContext, requestMap, UserId, SecondMonetaryAccountId, requestResponseId).Value.Status; } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/SessionTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/SessionTest.cs index 350725f..9338921 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/SessionTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/SessionTest.cs @@ -1,9 +1,7 @@ -using System; -using System.IO; +using System.IO; using Bunq.Sdk.Context; using Bunq.Sdk.Model.Generated.Endpoint; using Xunit; -using Xunit.Sdk; namespace Bunq.Sdk.Tests.Model.Generated.Endpoint { @@ -16,17 +14,17 @@ public class SessionTest : BunqSdkTestBase /// /// Name of the context configuration file. /// - private const string FILENAME_CONTEXT_CONF = "../../../bunq-test.conf"; + private const string FilenameContextConf = "../../../bunq-test.conf"; /// - /// Config values. + /// A dummy id for the session, can be an arbitrary number /// - private const int SESSION_ID_DUMMY = 0; + private const int SessionIdDummy = 0; /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests the deleteion of the current session. @@ -36,9 +34,9 @@ public class SessionTest : BunqSdkTestBase [Fact] public void TestSessionDeletion() { - Session.Delete(API_CONTEXT, SESSION_ID_DUMMY); + Session.Delete(ApiContext, SessionIdDummy); - File.Delete(FILENAME_CONTEXT_CONF); + File.Delete(FilenameContextConf); } } } diff --git a/BunqSdk.Tests/Model/Generated/Endpoint/TabUsageSingleTest.cs b/BunqSdk.Tests/Model/Generated/Endpoint/TabUsageSingleTest.cs index c8d9d60..f6596bc 100644 --- a/BunqSdk.Tests/Model/Generated/Endpoint/TabUsageSingleTest.cs +++ b/BunqSdk.Tests/Model/Generated/Endpoint/TabUsageSingleTest.cs @@ -16,21 +16,24 @@ public class TabUsageSingleTest : BunqSdkTestBase /// /// Config values /// - private const string TAB_FIELD_DESCRIPTION = "Pay the tab for Java test please."; - private const string FIELD_STATUS_OPEN = "OPEN"; - private const string AMOUNT_EUR = "10.00"; - private const string FIELD_CURRENCY = "EUR"; - private const string TAB_ITEM_FIELD_DESCRIPTION = "Super expensive java tea"; - private const string FIELD_STATUS_WAITING = "WAITING_FOR_PAYMENT"; - - private static readonly int USER_ID = Config.GetUserId(); - private static readonly int MONETARY_ACCOUNT_ID = Config.GetMonetarytAccountId(); - private static readonly int CASH_REGISTER_ID = Config.GetCashRegisterId(); + private static readonly int UserId = Config.GetUserId(); + private static readonly int MonetaryAccountId = Config.GetMonetarytAccountId(); + private static readonly int CashRegisterId = Config.GetCashRegisterId(); + /// + /// Mixed value constants. + /// + private const string ValueDescription = "Pay the tab for Java test please."; + private const string ValueStatusOpen = "OPEN"; + private const string ValueAmountEur = "10.00"; + private const string ValueCurrencyEur = "EUR"; + private const string ValueOtherDescription = "Super expensive java tea"; + private const string ValueStatusWaiting = "WAITING_FOR_PAYMENT"; + /// /// API context to use for the test API calls. /// - private static readonly ApiContext API_CONTEXT = GetApiContext(); + private static readonly ApiContext ApiContext = GetApiContext(); /// /// Tests opening a new tab, adding a tab item to it and update this tab to awaiting payment. @@ -46,39 +49,39 @@ public void TestCreateTabAndUpdate() var updateTabMap = new Dictionary { - {TabUsageSingle.FIELD_STATUS, FIELD_STATUS_WAITING} + {TabUsageSingle.FIELD_STATUS, ValueStatusWaiting} }; - TabUsageSingle.Update(API_CONTEXT, updateTabMap, USER_ID, MONETARY_ACCOUNT_ID, CASH_REGISTER_ID, tabUuid); + TabUsageSingle.Update(ApiContext, updateTabMap, UserId, MonetaryAccountId, CashRegisterId, tabUuid); DeleteTab(tabUuid); } private static void DeleteTab(string tabId) { - TabUsageSingle.Delete(API_CONTEXT, USER_ID, MONETARY_ACCOUNT_ID, CASH_REGISTER_ID, tabId); + TabUsageSingle.Delete(ApiContext, UserId, MonetaryAccountId, CashRegisterId, tabId); } private static string CreateTabAndGetUuid() { var createTabMap = new Dictionary { - {TabUsageSingle.FIELD_DESCRIPTION, TAB_FIELD_DESCRIPTION}, - {TabUsageSingle.FIELD_STATUS, FIELD_STATUS_OPEN}, - {TabUsageSingle.FIELD_AMOUNT_TOTAL, new Amount(AMOUNT_EUR, FIELD_CURRENCY)} + {TabUsageSingle.FIELD_DESCRIPTION, ValueDescription}, + {TabUsageSingle.FIELD_STATUS, ValueStatusOpen}, + {TabUsageSingle.FIELD_AMOUNT_TOTAL, new Amount(ValueAmountEur, ValueCurrencyEur)} }; - return TabUsageSingle.Create(API_CONTEXT, createTabMap, USER_ID, MONETARY_ACCOUNT_ID, - CASH_REGISTER_ID).Value; + return TabUsageSingle.Create(ApiContext, createTabMap, UserId, MonetaryAccountId, + CashRegisterId).Value; } private static void AddTabItem(string tabUuid) { var tabItemMap = new Dictionary { - {TabItemShop.FIELD_AMOUNT, new Amount(AMOUNT_EUR, FIELD_CURRENCY)}, - {TabItemShop.FIELD_DESCRIPTION, TAB_ITEM_FIELD_DESCRIPTION} + {TabItemShop.FIELD_AMOUNT, new Amount(ValueAmountEur, ValueCurrencyEur)}, + {TabItemShop.FIELD_DESCRIPTION, ValueOtherDescription} }; - TabItemShop.Create(API_CONTEXT, tabItemMap, USER_ID, MONETARY_ACCOUNT_ID, CASH_REGISTER_ID, tabUuid); + TabItemShop.Create(ApiContext, tabItemMap, UserId, MonetaryAccountId, CashRegisterId, tabUuid); } } } diff --git a/BunqSdk.Tests/Model/Generated/Object/NotificationUrlTest.cs b/BunqSdk.Tests/Model/Generated/Object/NotificationUrlTest.cs index 54bcc69..1c3905a 100644 --- a/BunqSdk.Tests/Model/Generated/Object/NotificationUrlTest.cs +++ b/BunqSdk.Tests/Model/Generated/Object/NotificationUrlTest.cs @@ -1,8 +1,6 @@ using System; using System.IO; using System.Reflection; -using System.Runtime.InteropServices.ComTypes; -using Bunq.Sdk.Model.Core; using Bunq.Sdk.Model.Generated.Endpoint; using Bunq.Sdk.Model.Generated.Object; using Newtonsoft.Json.Linq; @@ -10,53 +8,55 @@ namespace Bunq.Sdk.Tests.Model.Generated.Object { + /// + /// Tests: + /// NotificationUrl + /// public class NotificationUrlTest : BunqSdkTestBase { /// /// Getter constans. /// - private const string GET_PAYMENT = "Payment"; - private const string GET_BUNQ_ME_TAB = "BunqMeTab"; - private const string GET_CHAT_MESSAGE_ANNOUNCEMENT = "ChatMessageAnnouncement"; - private const string GET_CHAT_MESSAGE = "ChatMessage"; - private const string GET_DRAFT_PAYMENT = "DraftPayment"; - private const string GET_MASTER_CARD_ACTION = "MasterCardAction"; - private const string GET_MONETARY_ACCOUNT_BANK = "MonetaryAccountBank"; - private const string GET_MONETARY_ACCOUNT = "MonetaryAccount"; - private const string GET_PAYMENT_BATCH = "PaymentBatch"; - private const string GET_REQUEST_INQUIRY = "RequestInquiry"; - private const string GET_REQUEST_RESPONSE = "RequestResponse"; - private const string GET_SCHEDULE_PAYMENT = "ScheduledPayment"; - private const string GET_SCHEDULE_INSTANCE = "ScheduledInstance"; - private const string GET_SHARE_INVITE_BANK_INQUIRY = "ShareInviteBankInquiry"; - private const string GET_SHARE_INVITE_BANK_RESPONSE = "ShareInviteBankResponse"; + private const string GetPayment = "Payment"; + private const string GetBunqMeTab = "BunqMeTab"; + private const string GetChatMessageAnnouncement = "ChatMessageAnnouncement"; + private const string GetChatMessage = "ChatMessage"; + private const string GetDraftPayment = "DraftPayment"; + private const string GetMasterCardAction = "MasterCardAction"; + private const string GetMonetaryAccountBank = "MonetaryAccountBank"; + private const string GetMonetaryAccount = "MonetaryAccount"; + private const string GetPaymentBatch = "PaymentBatch"; + private const string GetRequestInquiry = "RequestInquiry"; + private const string GetRequestResponse = "RequestResponse"; + private const string GetSchedulePayment = "ScheduledPayment"; + private const string GetScheduleInstance = "ScheduledInstance"; + private const string GetShareInviteBankInquiry = "ShareInviteBankInquiry"; + private const string GetShareInviteBankResponse = "ShareInviteBankResponse"; /// /// Model json paths constants. /// - private const string BASE_PATH_JSON_MODEL = "../../../Resources/NotificationUrlJsons"; - private const string JSON_PATH_MUTATION_MODEL = BASE_PATH_JSON_MODEL + "/Mutation.json"; - private const string JSON_PATH_BUNQ_ME_TAB_MODEL = BASE_PATH_JSON_MODEL + "/BunqMeTab.json"; - private const string JSON_PATH_CHAT_MESSAGE_ANNOUNCEMENT_MODEL = BASE_PATH_JSON_MODEL + - "/ChatMessageAnnouncement.json"; - private const string JSON_PATH_DRAFT_PAYMENT_MODEL = BASE_PATH_JSON_MODEL + "/DraftPayment.json"; - private const string JSON_PATH_MASTER_CARD_ACTION_MODEL = BASE_PATH_JSON_MODEL + "/MasterCardAction.json"; - private const string JSON_PATH_MONETARY_ACCOUNT_BANK_MODEL = BASE_PATH_JSON_MODEL + "/MonetaryAccountBank.json"; - private const string JSON_PATH_PAYMENT_BATCH_MODEL = BASE_PATH_JSON_MODEL + "/PaymentBatch.json"; - private const string JSON_PATH_REQUEST_INQUIRY_MODEL = BASE_PATH_JSON_MODEL + "/RequestInquiry.json"; - private const string JSON_PATH_REQUEST_RESPONSE_MODEL = BASE_PATH_JSON_MODEL + "/RequestResponse.json"; - private const string JSON_PATH_SCHEDULE_PAYMENT_MODEL = BASE_PATH_JSON_MODEL + "/ScheduledPayment.json"; - private const string JSON_PATH_SCHEDULE_INSTANCE_MODEL = BASE_PATH_JSON_MODEL + "/ScheduledInstance.json"; - private const string JSON_PATH_SHARE_INVITE_BANK_INQUIRY_MODEL = BASE_PATH_JSON_MODEL + + private const string BasePathJsonModel = "../../../Resources/NotificationUrlJsons"; + private const string JsonPathMutationModel = BasePathJsonModel + "/Mutation.json"; + private const string JsonPathBunqMeTabModel = BasePathJsonModel + "/BunqMeTab.json"; + private const string JsonPathChatMessageAnnouncementModel = BasePathJsonModel + "/ChatMessageAnnouncement.json"; + private const string JsonPathDraftPaymentModel = BasePathJsonModel + "/DraftPayment.json"; + private const string JsonPathMasterCardActionModel = BasePathJsonModel + "/MasterCardAction.json"; + private const string JsonPathMonetaryAccountBankModel = BasePathJsonModel + "/MonetaryAccountBank.json"; + private const string JsonPathPaymentBatchModel = BasePathJsonModel + "/PaymentBatch.json"; + private const string JsonPathRequestInquiryModel = BasePathJsonModel + "/RequestInquiry.json"; + private const string JsonPathRequestResponseModel = BasePathJsonModel + "/RequestResponse.json"; + private const string JsonPathSchedulePaymentModel = BasePathJsonModel + "/ScheduledPayment.json"; + private const string JsonPathScheduleInstanceModel = BasePathJsonModel + "/ScheduledInstance.json"; + private const string JsonPathShareInviteBankInquiryModel = BasePathJsonModel + "/ShareInviteBankInquiry.json"; - - private const string JSON_PATH_SHARE_INVITE_BANK_RESPONSE_MODEL = BASE_PATH_JSON_MODEL + + private const string JsonPathShareInviteBankResponseModel = BasePathJsonModel + "/ShareInviteBankResponse.json"; /// /// Model root key. /// - private const string KEY_NOTIFICATION_URL_MODEL = "NotificationUrl"; + private const string KeyNotificationUrlModel = "NotificationUrl"; private void ExecuteNotificationUrlTest( string expectedJsonFileName, @@ -93,7 +93,7 @@ private static string ReadJsonFromFile(string fileName) { var fileContentString = File.ReadAllText(fileName); var jsonObj = JObject.Parse(fileContentString); - var notificationUrlObject = jsonObj[KEY_NOTIFICATION_URL_MODEL]; + var notificationUrlObject = jsonObj[KeyNotificationUrlModel]; Assert.NotNull(notificationUrlObject); @@ -104,9 +104,9 @@ private static string ReadJsonFromFile(string fileName) public void TestMutationModel() { ExecuteNotificationUrlTest( - JSON_PATH_MUTATION_MODEL, + JsonPathMutationModel, typeof(Payment), - GET_PAYMENT + GetPayment ); } @@ -114,9 +114,9 @@ public void TestMutationModel() public void TestBunqMeTabModel() { ExecuteNotificationUrlTest( - JSON_PATH_BUNQ_ME_TAB_MODEL, + JsonPathBunqMeTabModel, typeof(BunqMeTab), - GET_BUNQ_ME_TAB + GetBunqMeTab ); } @@ -124,10 +124,10 @@ public void TestBunqMeTabModel() public void TestChatMessageAnnouncementModel() { ExecuteNotificationUrlTest( - JSON_PATH_CHAT_MESSAGE_ANNOUNCEMENT_MODEL, + JsonPathChatMessageAnnouncementModel, typeof(ChatMessage), - GET_CHAT_MESSAGE, - GET_CHAT_MESSAGE_ANNOUNCEMENT, + GetChatMessage, + GetChatMessageAnnouncement, typeof(ChatMessageAnnouncement) ); } @@ -136,9 +136,9 @@ public void TestChatMessageAnnouncementModel() public void TestDraftPaymentModel() { ExecuteNotificationUrlTest( - JSON_PATH_DRAFT_PAYMENT_MODEL, + JsonPathDraftPaymentModel, typeof(DraftPayment), - GET_DRAFT_PAYMENT + GetDraftPayment ); } @@ -146,9 +146,9 @@ public void TestDraftPaymentModel() public void TestMasterCardActionModel() { ExecuteNotificationUrlTest( - JSON_PATH_MASTER_CARD_ACTION_MODEL, + JsonPathMasterCardActionModel, typeof(MasterCardAction), - GET_MASTER_CARD_ACTION + GetMasterCardAction ); } @@ -156,10 +156,10 @@ public void TestMasterCardActionModel() public void TestMonetaryAccountBankModel() { ExecuteNotificationUrlTest( - JSON_PATH_MONETARY_ACCOUNT_BANK_MODEL, + JsonPathMonetaryAccountBankModel, typeof(MonetaryAccount), - GET_MONETARY_ACCOUNT, - GET_MONETARY_ACCOUNT_BANK, + GetMonetaryAccount, + GetMonetaryAccountBank, typeof(MonetaryAccountBank) ); } @@ -168,9 +168,9 @@ public void TestMonetaryAccountBankModel() public void TestPaymentBatchModel() { ExecuteNotificationUrlTest( - JSON_PATH_PAYMENT_BATCH_MODEL, + JsonPathPaymentBatchModel, typeof(PaymentBatch), - GET_PAYMENT_BATCH + GetPaymentBatch ); } @@ -178,9 +178,9 @@ public void TestPaymentBatchModel() public void TestRequestInquiryModel() { ExecuteNotificationUrlTest( - JSON_PATH_REQUEST_INQUIRY_MODEL, + JsonPathRequestInquiryModel, typeof(RequestInquiry), - GET_REQUEST_INQUIRY + GetRequestInquiry ); } @@ -188,9 +188,9 @@ public void TestRequestInquiryModel() public void TestRequestResponseModel() { ExecuteNotificationUrlTest( - JSON_PATH_REQUEST_RESPONSE_MODEL, + JsonPathRequestResponseModel, typeof(RequestResponse), - GET_REQUEST_RESPONSE + GetRequestResponse ); } @@ -198,9 +198,9 @@ public void TestRequestResponseModel() public void TestScheduledInstanceModel() { ExecuteNotificationUrlTest( - JSON_PATH_SCHEDULE_INSTANCE_MODEL, + JsonPathScheduleInstanceModel, typeof(ScheduleInstance), - GET_SCHEDULE_INSTANCE + GetScheduleInstance ); } @@ -208,9 +208,9 @@ public void TestScheduledInstanceModel() public void TestScheduledPaymentModel() { ExecuteNotificationUrlTest( - JSON_PATH_SCHEDULE_PAYMENT_MODEL, + JsonPathSchedulePaymentModel, typeof(SchedulePayment), - GET_SCHEDULE_PAYMENT + GetSchedulePayment ); } @@ -218,9 +218,9 @@ public void TestScheduledPaymentModel() public void TestShareInviteBankModel() { ExecuteNotificationUrlTest( - JSON_PATH_SHARE_INVITE_BANK_INQUIRY_MODEL, + JsonPathShareInviteBankInquiryModel, typeof(ShareInviteBankInquiry), - GET_SHARE_INVITE_BANK_INQUIRY + GetShareInviteBankInquiry ); } @@ -228,9 +228,9 @@ public void TestShareInviteBankModel() public void TestShareInviteBankResponse() { ExecuteNotificationUrlTest( - JSON_PATH_SHARE_INVITE_BANK_RESPONSE_MODEL, + JsonPathShareInviteBankResponseModel, typeof(ShareInviteBankResponse), - GET_SHARE_INVITE_BANK_RESPONSE + GetShareInviteBankResponse ); } } diff --git a/BunqSdk.Tests/README.md b/BunqSdk.Tests/README.md index ab15f3b..6ad7f22 100644 --- a/BunqSdk.Tests/README.md +++ b/BunqSdk.Tests/README.md @@ -3,7 +3,7 @@ ## Introduction Hi developers! -Welcome to the bunq Java SDK integration tests. Currently we are not +Welcome to the bunq C# SDK integration tests. Currently we are not targeting the 100% test coverage, but rather want to be certain that the most common scenarios can run without any errors. @@ -34,4 +34,9 @@ same directory, fill in your sandbox user data and rename the copy to `config.js ## Execution To run tests via Rider, you can right click on the `BunqSdk.Tests` solution and should be able to run -the tests cases form the IDE. +the tests cases from the IDE. +To run the tests via Visual Studio, you can use the Test Explorer window. Use default shortcut Ctrl+R, A +for test execution. +To run the tests via Visual Studio Code, you can use this [extension](https://github.com/formulahendry/vscode-dotnet-test-explorer) +for test execution. +To run tests in the command line, you can use the command `dotnet xunit`. More information about xunit [here](https://xunit.github.io/docs/getting-started-dotnet-core.html). \ No newline at end of file diff --git a/BunqSdk.Tests/Resources/config.example.json b/BunqSdk.Tests/Resources/config.example.json index f549508..115703d 100644 --- a/BunqSdk.Tests/Resources/config.example.json +++ b/BunqSdk.Tests/Resources/config.example.json @@ -3,7 +3,7 @@ "USER_ID": "XXXX", "MONETARY_ACCOUNT_ID": "XXXX", "MONETARY_ACCOUNT_ID2": "XXXX", - "PERMITTED_IPS": ",", + "PERMITTED_IP": ",", "AttachmentPublicTest": { "CONTENT_TYPE": "image/png", "DESCRIPTION": "TEST PNG PHP", diff --git a/BunqSdk/Context/ApiContext.cs b/BunqSdk/Context/ApiContext.cs index 2edda96..97c255a 100644 --- a/BunqSdk/Context/ApiContext.cs +++ b/BunqSdk/Context/ApiContext.cs @@ -23,33 +23,33 @@ public class ApiContext /// /// Error constants. /// - private const string ERROR_COULD_NOT_SAVE_API_CONTEXT = "Could not save the API context."; - private const string ERROR_COULD_NOT_RESTORE_API_CONTEXT = "Could not restore the API context."; + private const string ErrorCouldNotSaveApiContext = "Could not save the API context."; + private const string ErrorCouldNotRestoreApiContext = "Could not restore the API context."; /// /// Measure of any time unit when none of it is needed. /// - private const int TIME_UNIT_COUNT_NONE = 0; + private const int TimeUnitCountNone = 0; /// /// Minimum time to session expiry not requiring session reset. /// - private const int TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS = 30; + private const int TimeToSessionExpiryAllMinimumSecond = 30; /// /// Default path to store the serialized context. /// - private const string PATH_API_CONTEXT_DEFAULT = "bunq.conf"; + private const string PathApiContextDefault = "bunq.conf"; /// /// Dummy ID to pass to Session endpoint. /// - private const int SESSION_ID_DUMMY = 0; + private const int SessionIdDummy = 0; /// /// Encoding of the serialized context. /// - private static readonly Encoding ENCODING_BUNQ_CONF = Encoding.UTF8; + private static readonly Encoding EncodingBunqConf = Encoding.UTF8; [JsonProperty(PropertyName = "environment_type")] public ApiEnvironmentType EnvironmentType { get; private set; } @@ -168,7 +168,7 @@ public void CloseSession() private void DeleteSession() { - Session.Delete(this, SESSION_ID_DUMMY); + Session.Delete(this, SessionIdDummy); } /// @@ -191,9 +191,9 @@ public bool IsSessionActive() var timeToExpiry = SessionContext.ExpiryTime.Subtract(DateTime.Now); var timeToExpiryMinimum = new TimeSpan( - TIME_UNIT_COUNT_NONE, - TIME_UNIT_COUNT_NONE, - TIME_TO_SESSION_EXPIRY_MINIMUM_SECONDS + TimeUnitCountNone, + TimeUnitCountNone, + TimeToSessionExpiryAllMinimumSecond ); return timeToExpiry > timeToExpiryMinimum; @@ -204,7 +204,7 @@ public bool IsSessionActive() /// public void Save() { - Save(PATH_API_CONTEXT_DEFAULT); + Save(PathApiContextDefault); } /// @@ -214,11 +214,11 @@ public void Save(string fileName) { try { - File.WriteAllText(fileName, ToJson(), ENCODING_BUNQ_CONF); + File.WriteAllText(fileName, ToJson(), EncodingBunqConf); } catch (IOException exception) { - throw new BunqException(ERROR_COULD_NOT_SAVE_API_CONTEXT, exception); + throw new BunqException(ErrorCouldNotSaveApiContext, exception); } } @@ -235,7 +235,7 @@ public string ToJson() /// public static ApiContext Restore() { - return Restore(PATH_API_CONTEXT_DEFAULT); + return Restore(PathApiContextDefault); } /// @@ -245,11 +245,11 @@ public static ApiContext Restore(string fileName) { try { - return FromJson(File.ReadAllText(fileName, ENCODING_BUNQ_CONF)); + return FromJson(File.ReadAllText(fileName, EncodingBunqConf)); } catch (IOException exception) { - throw new BunqException(ERROR_COULD_NOT_RESTORE_API_CONTEXT, exception); + throw new BunqException(ErrorCouldNotRestoreApiContext, exception); } } @@ -273,9 +273,7 @@ public string GetBaseUri() /// is created either. public string GetSessionToken() { - if (SessionContext != null) return SessionContext.Token; - - return InstallationContext == null ? null : InstallationContext.Token; + return SessionContext != null ? SessionContext.Token : InstallationContext?.Token; } } } diff --git a/BunqSdk/Context/ApiEnvironmentType.cs b/BunqSdk/Context/ApiEnvironmentType.cs index 96a713e..29dce63 100644 --- a/BunqSdk/Context/ApiEnvironmentType.cs +++ b/BunqSdk/Context/ApiEnvironmentType.cs @@ -10,25 +10,25 @@ public sealed class ApiEnvironmentType /// /// Mapping of environment type to the base URI. /// - private static readonly IDictionary NAME_TO_BASE_URI_MAP = new Dictionary + private static readonly IDictionary NameToBaseUriMap = new Dictionary { - {ENVIRONMENT_TYPE_PRODUCTION, BASE_URI_PRODUCTION}, - {ENVIRONMENT_TYPE_SANDBOX, BASE_URI_SANDBOX} + {EnvironmentTypeProduction, BaseUriProduction}, + {EnvironmentTypeSandbox, BaseUriSandbox} }; /// /// Production environment constants. /// - public static readonly ApiEnvironmentType PRODUCTION = new ApiEnvironmentType(ENVIRONMENT_TYPE_PRODUCTION); - private const string ENVIRONMENT_TYPE_PRODUCTION = "PRODUCTION"; - private const string BASE_URI_PRODUCTION = "https://api.bunq.com/v1/"; + public static readonly ApiEnvironmentType Production = new ApiEnvironmentType(EnvironmentTypeProduction); + private const string EnvironmentTypeProduction = "PRODUCTION"; + private const string BaseUriProduction = "https://api.bunq.com/v1/"; /// /// Sandbox environment constants. /// - public static readonly ApiEnvironmentType SANDBOX = new ApiEnvironmentType(ENVIRONMENT_TYPE_SANDBOX); - private const string ENVIRONMENT_TYPE_SANDBOX = "SANDBOX"; - private const string BASE_URI_SANDBOX = "https://sandbox.public.api.bunq.com/v1/"; + public static readonly ApiEnvironmentType Sandbox = new ApiEnvironmentType(EnvironmentTypeSandbox); + private const string EnvironmentTypeSandbox = "SANDBOX"; + private const string BaseUriSandbox = "https://sandbox.public.api.bunq.com/v1/"; public string TypeString { get; private set; } public string BaseUri { get; private set; } @@ -36,7 +36,7 @@ public sealed class ApiEnvironmentType public ApiEnvironmentType(string typeString) { TypeString = typeString; - BaseUri = NAME_TO_BASE_URI_MAP[typeString]; + BaseUri = NameToBaseUriMap[typeString]; } } } diff --git a/BunqSdk/Context/SessionContext.cs b/BunqSdk/Context/SessionContext.cs index 9335d34..6eac6e9 100644 --- a/BunqSdk/Context/SessionContext.cs +++ b/BunqSdk/Context/SessionContext.cs @@ -12,7 +12,7 @@ public class SessionContext /// /// Default assumed value for session timeout. /// - private const double SESSION_TIMEOUT_DEFAULT = 0.0; + private const double SessionTimeoutDefault = 0.0; /// /// Session token returned as a response to POST /session-server. @@ -49,7 +49,7 @@ private static double GetSessionTimeout(SessionServer sessionServer) return (double) sessionServer.UserPerson.SessionTimeout; } - return SESSION_TIMEOUT_DEFAULT; + return SessionTimeoutDefault; } } } diff --git a/BunqSdk/Exception/EXCEPTIONS.md b/BunqSdk/Exception/EXCEPTIONS.md index 4ad60a6..b91e3e5 100644 --- a/BunqSdk/Exception/EXCEPTIONS.md +++ b/BunqSdk/Exception/EXCEPTIONS.md @@ -50,14 +50,14 @@ using Bunq.Sdk.Exception; public class BadRequest { - private const string API_KEY = "Some invalid API key" - private const string DESCRIPTION = "This will throw BadRequestException." + private const string Key = "Some invalid API key" + private const string Description = "This will throw BadRequestException." public void Run() { try { - ApiContext.Create(ApiEnvironmentType.SANDBOX, API_KEY, DEVICE_DESCRIPTION); + ApiContext.Create(ApiEnvironmentType.SandBox, Key, Description); } catch(BadRequestException error) { diff --git a/BunqSdk/Exception/ExceptionFactory.cs b/BunqSdk/Exception/ExceptionFactory.cs index ec31486..84b4665 100644 --- a/BunqSdk/Exception/ExceptionFactory.cs +++ b/BunqSdk/Exception/ExceptionFactory.cs @@ -7,18 +7,18 @@ public class ExceptionFactory /// /// HTTP error response codes constants. /// - private const int HTTP_RESPONSE_CODE_BAD_REQUEST = 400; - private const int HTTP_RESPONSE_CODE_UNAUTHORIZED = 401; - private const int HTTP_RESPONSE_CODE_FORBIDDEN = 403; - private const int HTTP_RESPONSE_CODE_NOT_FOUND = 404; - private const int HTTP_RESPONSE_CODE_METHOD_NOT_ALLOWED = 405; - private const int HTTP_RESPONSE_CODE_TOO_MANY_REQUESTS = 429; - private const int HTTP_RESPONSE_CODE_INTERNAL_SERVER_ERROR = 500; + private const int HttpResponseCodeBadRequest = 400; + private const int HttpResponseCodeUnauthorized = 401; + private const int HttpResponseCodeForbidden = 403; + private const int HttpResponseCodeNotFound = 404; + private const int HttpResponseCodeMethodNotAllowed = 405; + private const int HttpResponseCodeTooManyRequests = 429; + private const int HttpResponseCodeInternalServerError = 500; /// /// Glue to concatenate the error messages. /// - private const string GLUE_ERROR_MESSAGES = "\n"; + private const string SeparatorAllMessage = "\n"; /// The exception that belongs to this status code. public static ApiException CreateExceptionForResponse(int responseCode, IList messages) @@ -27,19 +27,19 @@ public static ApiException CreateExceptionForResponse(int responseCode, IList messages) { - return string.Join(GLUE_ERROR_MESSAGES, messages); + return string.Join(SeparatorAllMessage, messages); } } } diff --git a/BunqSdk/Http/ApiClient.cs b/BunqSdk/Http/ApiClient.cs index 837470e..a8e9a40 100644 --- a/BunqSdk/Http/ApiClient.cs +++ b/BunqSdk/Http/ApiClient.cs @@ -20,64 +20,64 @@ public class ApiClient /// /// Endpoints not requiring active session for the request to succeed. /// - private const string DEVICE_SERVER_URL = "device-server"; - private const string INSTALLATION_URL = "installation"; - private const string SESSION_SERVER_URL = "session-server"; - private static readonly string[] URIS_NOT_REQUIRING_ACTIVE_SESSION = new string[] + private const string DeviceServerUrl = "device-server"; + private const string InstallationUrl = "installation"; + private const string SessionServerUrl = "session-server"; + private static readonly string[] AllUriNotRequiringActiveSession = { - DEVICE_SERVER_URL, - INSTALLATION_URL, - SESSION_SERVER_URL + DeviceServerUrl, + InstallationUrl, + SessionServerUrl }; /// /// Header constants. /// - public const string HEADER_ATTACHMENT_DESCRIPTION = "X-Bunq-Attachment-Description"; - public const string HEADER_CONTENT_TYPE = "Content-Type"; - public const string HEADER_CACHE_CONTROL = "Cache-Control"; - public const string HEADER_USER_AGENT = "User-Agent"; - private const string HEADER_LANGUAGE = "X-Bunq-Language"; - private const string HEADER_REGION = "X-Bunq-Region"; - private const string HEADER_REQUEST_ID = "X-Bunq-Client-Request-Id"; - private const string HEADER_GEOLOCATION = "X-Bunq-Geolocation"; - private const string HEADER_SIGNATURE = "X-Bunq-Client-Signature"; - private const string HEADER_AUTHENTICATION = "X-Bunq-Client-Authentication"; + public const string HeaderAttachmentDescription = "X-Bunq-Attachment-Description"; + public const string HeaderContentType = "Content-Type"; + public const string HeaderCacheControl = "Cache-Control"; + public const string HeaderUserAgent = "User-Agent"; + private const string HeaderLanguage = "X-Bunq-Language"; + private const string HeaderRegion = "X-Bunq-Region"; + private const string HeaderRequestId = "X-Bunq-Client-Request-Id"; + private const string HeaderGeolocation = "X-Bunq-Geolocation"; + private const string HeaderSignature = "X-Bunq-Client-Signature"; + private const string HeaderAuthentication = "X-Bunq-Client-Authentication"; /// /// Field constants. /// - private const string FIELD_ERROR = "Error"; - private const string FIELD_ERROR_DESCRIPTION = "error_description"; + private const string FieldError = "Error"; + private const string FieldErrorDescription = "error_description"; /// /// Values for the default headers /// - private const string CACHE_CONTROL_NONE = "no-cache"; - private const string USER_AGENT_BUNQ = "bunq-sdk-csharp/0.12.4.0-beta"; - private const string LANGUAGE_EN_US = "en_US"; - private const string REGION_NL_NL = "nl_NL"; - private const string GEOLOCATION_ZERO = "0 0 0 0 NL"; + private const string HeaderValueCacheControlNone = "no-cache"; + private const string HeaderValueUserAgentBunq = "bunq-sdk-csharp/0.12.4.0-beta"; + private const string HeaderValueLanguageEnUs = "en_US"; + private const string HeaderValueRegionNlNl = "nl_NL"; + private const string HeaderValueGeolocationZero = "0 0 0 0 NL"; /// /// Delimiter between multiple header values. /// - private const string DELIMITER_HEADER_VALUE = ","; + private const string DelimiterHeaderValue = ","; /// /// Delimiter between path and params in URI. /// - public const char DELIMITER_URI_QUERY = '?'; + public const char DelimiterUriQuery = '?'; /// /// Delimiter between key and value of a URI param. /// - public const char DELIMITER_URI_PARAM_KEY_VALUE = '='; + public const char DelimiterUriParamKeyValue = '='; /// /// Delimiter between URI params. /// - public const char DELIMITER_URI_PARAMS = '&'; + public const char DelimiterAllUriParameter = '&'; private readonly HttpClient client; @@ -143,7 +143,7 @@ private BunqResponseRaw SendRequest(HttpMethod method, string uriRelative, private BunqResponseRaw SendRequest(HttpRequestMessage requestMessage, IDictionary customHeaders, string uriRelative) { - if (!URIS_NOT_REQUIRING_ACTIVE_SESSION.Contains(uriRelative)) + if (!AllUriNotRequiringActiveSession.Contains(uriRelative)) { apiContext.EnsureSessionActive(); } @@ -169,7 +169,7 @@ private static BunqResponseRaw CreateBunqResponseRaw(HttpResponseMessage respons private static IDictionary GetHeaders(HttpResponseMessage responseMessage) { return responseMessage.Headers - .Select(x => new KeyValuePair(x.Key, string.Join(DELIMITER_HEADER_VALUE, x.Value))) + .Select(x => new KeyValuePair(x.Key, string.Join(DelimiterHeaderValue, x.Value))) .ToImmutableDictionary(); } @@ -205,7 +205,7 @@ private static string GetUriWithParams(string uri, IDictionary u if (uriParams.Count <= 0) return uri; var uriWithParamsBuilder = new StringBuilder(uri); - uriWithParamsBuilder.Append(DELIMITER_URI_QUERY); + uriWithParamsBuilder.Append(DelimiterUriQuery); uriWithParamsBuilder.Append(GenerateUriParamsString(uriParams)); return uriWithParamsBuilder.ToString(); @@ -214,8 +214,8 @@ private static string GetUriWithParams(string uri, IDictionary u private static string GenerateUriParamsString(IDictionary uriParams) { return uriParams - .Select(entry => entry.Key + DELIMITER_URI_PARAM_KEY_VALUE + entry.Value) - .Aggregate((current, next) => current + DELIMITER_URI_PARAMS + next); + .Select(entry => entry.Key + DelimiterUriParamKeyValue + entry.Value) + .Aggregate((current, next) => current + DelimiterAllUriParameter + next); } private static void SetDefaultHeaders(HttpRequestMessage requestMessage) @@ -246,12 +246,12 @@ private static IDictionary GetDefaultHeaders() { return new SortedDictionary { - {HEADER_USER_AGENT, USER_AGENT_BUNQ}, - {HEADER_REQUEST_ID, GenerateRandomRequestId()}, - {HEADER_GEOLOCATION, GEOLOCATION_ZERO}, - {HEADER_LANGUAGE, LANGUAGE_EN_US}, - {HEADER_REGION, REGION_NL_NL}, - {HEADER_CACHE_CONTROL, CACHE_CONTROL_NONE} + {HeaderUserAgent, HeaderValueUserAgentBunq}, + {HeaderRequestId, GenerateRandomRequestId()}, + {HeaderGeolocation, HeaderValueGeolocationZero}, + {HeaderLanguage, HeaderValueLanguageEnUs}, + {HeaderRegion, HeaderValueRegionNlNl}, + {HeaderCacheControl, HeaderValueCacheControlNone} }; } @@ -266,8 +266,8 @@ private void SetSessionHeaders(HttpRequestMessage requestMessage) if (sessionToken == null) return; - requestMessage.Headers.Add(HEADER_AUTHENTICATION, sessionToken); - requestMessage.Headers.Add(HEADER_SIGNATURE, GenerateSignature(requestMessage)); + requestMessage.Headers.Add(HeaderAuthentication, sessionToken); + requestMessage.Headers.Add(HeaderSignature, GenerateSignature(requestMessage)); } private string GenerateSignature(HttpRequestMessage requestMessage) @@ -301,7 +301,7 @@ private static IList FetchErrorDescriptions(string responseBody) { var responseBodyObject = BunqJsonConvert.DeserializeObject(responseBody); - return responseBodyObject[FIELD_ERROR] == null + return responseBodyObject[FieldError] == null ? new List {responseBody} : FetchErrorDescriptions(responseBodyObject); } @@ -309,9 +309,9 @@ private static IList FetchErrorDescriptions(string responseBody) private static IList FetchErrorDescriptions(JObject responseBodyObject) { return responseBodyObject - .GetValue(FIELD_ERROR).ToObject() + .GetValue(FieldError).ToObject() .Select(exceptionBody => exceptionBody.ToObject()) - .Select(exceptionBodyJson => exceptionBodyJson.GetValue(FIELD_ERROR_DESCRIPTION).ToString()) + .Select(exceptionBodyJson => exceptionBodyJson.GetValue(FieldErrorDescription).ToString()) .ToList(); } diff --git a/BunqSdk/Http/Pagination.cs b/BunqSdk/Http/Pagination.cs index 0361f23..0401501 100644 --- a/BunqSdk/Http/Pagination.cs +++ b/BunqSdk/Http/Pagination.cs @@ -8,17 +8,17 @@ public class Pagination /// /// Error constants. /// - private const string ERROR_NO_PREVIOUS_PAGE = + private const string ErrorNoPreviousPage = "Could not generate previous page URL params: previous page not found."; - private const string ERROR_NO_NEXT_PAGE = "Could not generate next page URL params: next page not found."; + private const string ErrorNoNextPage = "Could not generate next page URL params: next page not found."; /// /// URL param constants. /// - public const string PARAM_OLDER_ID = "older_id"; - public const string PARAM_NEWER_ID = "newer_id"; - public const string PARAM_FUTURE_ID = "future_id"; - public const string PARAM_COUNT = "count"; + public const string ParamOlderId = "older_id"; + public const string ParamNewerId = "newer_id"; + public const string ParamFutureId = "future_id"; + public const string ParamCount = "count"; public int? OlderId { get; set; } public int? NewerId { get; set; } @@ -35,7 +35,7 @@ public IDictionary UrlParamsNextPage AssertHasNextPage(); var urlParams = new Dictionary(); - urlParams[PARAM_NEWER_ID] = NextId.ToString(); + urlParams[ParamNewerId] = NextId.ToString(); AddCountToParamsIfNeeded(urlParams); return urlParams; @@ -46,7 +46,7 @@ private void AssertHasNextPage() { if (NextId == null) { - throw new BunqException(ERROR_NO_NEXT_PAGE); + throw new BunqException(ErrorNoNextPage); } } @@ -54,7 +54,7 @@ private void AddCountToParamsIfNeeded(IDictionary urlParams) { if (Count != null) { - urlParams[PARAM_COUNT] = Count.ToString(); + urlParams[ParamCount] = Count.ToString(); } } @@ -92,7 +92,7 @@ public IDictionary UrlParamsPreviousPage AssertHasPreviousPage(); var urlParams = new Dictionary(); - urlParams[PARAM_OLDER_ID] = OlderId.ToString(); + urlParams[ParamOlderId] = OlderId.ToString(); AddCountToParamsIfNeeded(urlParams); return urlParams; @@ -103,7 +103,7 @@ private void AssertHasPreviousPage() { if (!HasPreviousPage()) { - throw new BunqException(ERROR_NO_PREVIOUS_PAGE); + throw new BunqException(ErrorNoPreviousPage); } } diff --git a/BunqSdk/Json/AnchorObjectConverter.cs b/BunqSdk/Json/AnchorObjectConverter.cs index b8b1c9e..90cc74c 100644 --- a/BunqSdk/Json/AnchorObjectConverter.cs +++ b/BunqSdk/Json/AnchorObjectConverter.cs @@ -9,7 +9,7 @@ namespace Bunq.Sdk.Json { public class AnchorObjectConverter: JsonConverter { - private const string FORMAT_DATE = "yyyy-MM-dd HH:mm:ss.ffffff"; + private const string FormatDate = "yyyy-MM-dd HH:mm:ss.ffffff"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -22,7 +22,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist new JsonSerializerSettings { ContractResolver = new BunqContractResolver(new List {typeof(IAnchorObjectInterface)}), - DateFormatString = FORMAT_DATE, + DateFormatString = FormatDate, FloatParseHandling = FloatParseHandling.Decimal, Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, diff --git a/BunqSdk/Json/ApiEnvironmentTypeConverter.cs b/BunqSdk/Json/ApiEnvironmentTypeConverter.cs index c817ccc..0306fa2 100644 --- a/BunqSdk/Json/ApiEnvironmentTypeConverter.cs +++ b/BunqSdk/Json/ApiEnvironmentTypeConverter.cs @@ -5,6 +5,7 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of ApiEnvironmentType required due to the hakish nature of C# "Enum with string /// property" pattern. diff --git a/BunqSdk/Json/BunqContractResolver.cs b/BunqSdk/Json/BunqContractResolver.cs index 43ff726..8341745 100644 --- a/BunqSdk/Json/BunqContractResolver.cs +++ b/BunqSdk/Json/BunqContractResolver.cs @@ -12,12 +12,13 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom mapping of types to JSON converters. /// public class BunqContractResolver : DefaultContractResolver { - protected readonly Dictionary converterRegistry = new Dictionary(); + private readonly Dictionary converterRegistry = new Dictionary(); public BunqContractResolver(IReadOnlyCollection typesToExclude=null) { diff --git a/BunqSdk/Json/BunqJsonConvert.cs b/BunqSdk/Json/BunqJsonConvert.cs index f514c69..96bb204 100644 --- a/BunqSdk/Json/BunqJsonConvert.cs +++ b/BunqSdk/Json/BunqJsonConvert.cs @@ -7,7 +7,7 @@ namespace Bunq.Sdk.Json /// public static class BunqJsonConvert { - private const string FORMAT_DATE = "yyyy-MM-dd HH:mm:ss.ffffff"; + private const string FormatDate = "yyyy-MM-dd HH:mm:ss.ffffff"; private static bool isInitialized; @@ -16,12 +16,15 @@ public static class BunqJsonConvert /// private static void Initialize() { - if (isInitialized) return; + if (isInitialized) + { + return; + } JsonConvert.DefaultSettings = () => new JsonSerializerSettings { ContractResolver = new BunqContractResolver(), - DateFormatString = FORMAT_DATE, + DateFormatString = FormatDate, FloatParseHandling = FloatParseHandling.Decimal, Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, diff --git a/BunqSdk/Json/GeolocationConverter.cs b/BunqSdk/Json/GeolocationConverter.cs index 5b9f46f..77ba5db 100644 --- a/BunqSdk/Json/GeolocationConverter.cs +++ b/BunqSdk/Json/GeolocationConverter.cs @@ -10,10 +10,13 @@ namespace Bunq.Sdk.Json /// public class GeolocationConverter : JsonConverter { - private const string FIELD_LATITUDE = "latitude"; - private const string FIELD_LONGITUDE = "longitude"; - private const string FIELD_ALTITUDE = "altitude"; - private const string FIELD_RADIUS = "radius"; + /// + /// Field constants. + /// + private const string FieldLatitude = "latitude"; + private const string FieldLongitude = "longitude"; + private const string FieldAltitude = "altitude"; + private const string FieldRadius = "radius"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -21,16 +24,16 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteStartObject(); - writer.WritePropertyName(FIELD_LATITUDE); + writer.WritePropertyName(FieldLatitude); writer.WriteValue(geolocation.Latitude.ToString()); - writer.WritePropertyName(FIELD_LONGITUDE); + writer.WritePropertyName(FieldLongitude); writer.WriteValue(geolocation.Longitude.ToString()); - writer.WritePropertyName(FIELD_ALTITUDE); + writer.WritePropertyName(FieldAltitude); writer.WriteValue(geolocation.Altitude.ToString()); - writer.WritePropertyName(FIELD_RADIUS); + writer.WritePropertyName(FieldRadius); writer.WriteValue(geolocation.Radius.ToString()); writer.WriteEndObject(); diff --git a/BunqSdk/Json/InstallationContextConverter.cs b/BunqSdk/Json/InstallationContextConverter.cs index bf7bf65..2363869 100644 --- a/BunqSdk/Json/InstallationContextConverter.cs +++ b/BunqSdk/Json/InstallationContextConverter.cs @@ -6,16 +6,20 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of InstallationContext required due to presence in it of the encryption /// keys which should be formatted when serialized in a special way. /// public class InstallationContextConverter : JsonConverter { - private const string FIELD_TOKEN = "token"; - private const string FIELD_PRIVATE_KEY_CLIENT = "private_key_client"; - private const string FIELD_PUBLIC_KEY_CLIENT = "public_key_client"; - private const string FIELD_PUBLIC_KEY_SERVER = "public_key_server"; + /// + /// Field coonstatns. + /// + private const string FieldToken = "token"; + private const string FieldPrivateKeyClient = "private_key_client"; + private const string FieldPublicKeyClient = "public_key_client"; + private const string FieldPublicKeyServer = "public_key_server"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -23,18 +27,18 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s writer.WriteStartObject(); - writer.WritePropertyName(FIELD_TOKEN); + writer.WritePropertyName(FieldToken); serializer.Serialize(writer, installationContext.Token); - writer.WritePropertyName(FIELD_PUBLIC_KEY_CLIENT); + writer.WritePropertyName(FieldPublicKeyClient); var clientPublicKeyString = SecurityUtils.GetPublicKeyFormattedString(installationContext.KeyPairClient); serializer.Serialize(writer, clientPublicKeyString); - writer.WritePropertyName(FIELD_PRIVATE_KEY_CLIENT); + writer.WritePropertyName(FieldPrivateKeyClient); var clientPrivateKeyString = SecurityUtils.GetPrivateKeyFormattedString(installationContext.KeyPairClient); serializer.Serialize(writer, clientPrivateKeyString); - writer.WritePropertyName(FIELD_PUBLIC_KEY_SERVER); + writer.WritePropertyName(FieldPublicKeyServer); var serverPublicKeyString = SecurityUtils.GetPublicKeyFormattedString(installationContext.PublicKeyServer); serializer.Serialize(writer, serverPublicKeyString); @@ -45,10 +49,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist JsonSerializer serializer) { var jObject = JObject.Load(reader); - var installationToken = jObject.GetValue(FIELD_TOKEN).ToString(); - var privateKeyClientString = jObject.GetValue(FIELD_PRIVATE_KEY_CLIENT).ToString(); + var installationToken = jObject.GetValue(FieldToken).ToString(); + var privateKeyClientString = jObject.GetValue(FieldPrivateKeyClient).ToString(); var keyPairClient = SecurityUtils.CreateKeyPairFromPrivateKeyFormattedString(privateKeyClientString); - var publicKeyServerString = jObject.GetValue(FIELD_PUBLIC_KEY_SERVER).ToString(); + var publicKeyServerString = jObject.GetValue(FieldPublicKeyServer).ToString(); var publicKeyServer = SecurityUtils.CreatePublicKeyFromPublicKeyFormattedString(publicKeyServerString); return new InstallationContext(installationToken, keyPairClient, publicKeyServer); diff --git a/BunqSdk/Json/InstallationConverter.cs b/BunqSdk/Json/InstallationConverter.cs index 7ce2154..0a44e26 100644 --- a/BunqSdk/Json/InstallationConverter.cs +++ b/BunqSdk/Json/InstallationConverter.cs @@ -6,29 +6,35 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of Installation required due to the unconventional structure of the /// Installation POST response. /// public class InstallationConverter : JsonConverter { - private const int INDEX_ID = 0; - private const string FIELD_ID = "Id"; - - private const int INDEX_TOKEN = 1; - private const string FIELD_TOKEN = "Token"; - - private const int INDEX_SERVER_PUBLIC_KEY = 2; - private const string FIELD_SERVER_PUBLIC_KEY = "ServerPublicKey"; + /// + /// The indices of the attributes inside the json object. + /// + private const int IndexId = 0; + private const int IndexToken = 1; + private const int IndexServerPublicKey = 2; + + /// + /// Field constatns. + /// + private const string FieldId = "Id"; + private const string FieldToken = "Token"; + private const string FieldServerPublicKey = "ServerPublicKey"; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObjects = JArray.Load(reader).ToObject>(); - var id = FetchObject(jObjects[INDEX_ID], FIELD_ID); - var token = FetchObject(jObjects[INDEX_TOKEN], FIELD_TOKEN); + var id = FetchObject(jObjects[IndexId], FieldId); + var token = FetchObject(jObjects[IndexToken], FieldToken); var publicKeyServer = - FetchObject(jObjects[INDEX_SERVER_PUBLIC_KEY], FIELD_SERVER_PUBLIC_KEY); + FetchObject(jObjects[IndexServerPublicKey], FieldServerPublicKey); return new Installation(id, token, publicKeyServer); } diff --git a/BunqSdk/Json/MonetaryAccountReferenceConverter.cs b/BunqSdk/Json/MonetaryAccountReferenceConverter.cs index cf8681d..e979803 100644 --- a/BunqSdk/Json/MonetaryAccountReferenceConverter.cs +++ b/BunqSdk/Json/MonetaryAccountReferenceConverter.cs @@ -6,6 +6,7 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of MonetaryAccountReference required to provide compatibility between the two types /// used to refer to Monetary Accounts: Pointers in requests and Monetary Account Labels in responses. diff --git a/BunqSdk/Json/NonIntegerNumberConverter.cs b/BunqSdk/Json/NonIntegerNumberConverter.cs index 7b28b0d..c7070bb 100644 --- a/BunqSdk/Json/NonIntegerNumberConverter.cs +++ b/BunqSdk/Json/NonIntegerNumberConverter.cs @@ -4,13 +4,17 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of InstallationContext required due to presence in it of the encryption /// keys which should be formatted when serialized in a special way. /// public class NonIntegerNumberConverter : JsonConverter { - private const string FORMAT_DECIMAL = "0.##"; + /// + /// Format constatns. + /// + private const string FormatDecimal = "0.##"; public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { @@ -20,7 +24,7 @@ public override void WriteJson(JsonWriter writer, object value, JsonSerializer s } else { - writer.WriteValue(((decimal) value).ToString(FORMAT_DECIMAL)); + writer.WriteValue(((decimal) value).ToString(FormatDecimal)); } } diff --git a/BunqSdk/Json/PaginationConverter.cs b/BunqSdk/Json/PaginationConverter.cs index 2231d87..214529c 100644 --- a/BunqSdk/Json/PaginationConverter.cs +++ b/BunqSdk/Json/PaginationConverter.cs @@ -7,6 +7,7 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of SessionServer required due to the unconventional structure of the /// SessionServer POST response. @@ -16,20 +17,20 @@ public class PaginationConverter : JsonConverter /// /// Field constants. /// - private const string FIELD_OLDER_URL = "older_url"; - private const string FIELD_NEWER_URL = "newer_url"; - private const string FIELD_FUTURE_URL = "future_url"; + private const string FieldOlderUrl = "older_url"; + private const string FieldNewerUrl = "newer_url"; + private const string FieldFutureUrl = "future_url"; /// /// Indices of param key and value after parsing. /// - private const int INDEX_PARAM_KEY = 0; - private const int INDEX_PARAM_VALUE = 1; + private const int IndexParamKey = 0; + private const int IndexParamValue = 1; /// /// Base dummy URL to hack through the incomplete relative URI functionality of dotnetcore. /// - private const string URI_BASE_DUMMY = "https://example.com"; + private const string UriBaseDummy = "https://example.com"; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) @@ -39,10 +40,10 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist return new Pagination { - OlderId = GetValueOrNull(paginationBody, Pagination.PARAM_OLDER_ID), - NewerId = GetValueOrNull(paginationBody, Pagination.PARAM_NEWER_ID), - FutureId = GetValueOrNull(paginationBody, Pagination.PARAM_FUTURE_ID), - Count = GetValueOrNull(paginationBody, Pagination.PARAM_COUNT), + OlderId = GetValueOrNull(paginationBody, Pagination.ParamOlderId), + NewerId = GetValueOrNull(paginationBody, Pagination.ParamNewerId), + FutureId = GetValueOrNull(paginationBody, Pagination.ParamFutureId), + Count = GetValueOrNull(paginationBody, Pagination.ParamCount), }; } @@ -56,24 +57,24 @@ private static T GetValueOrNull(IDictionary dictionary, string key var paginationBody = new Dictionary(); UpdatePaginationBodyFromResponseField( paginationBody, - Pagination.PARAM_OLDER_ID, + Pagination.ParamOlderId, responseJson, - FIELD_OLDER_URL, - Pagination.PARAM_OLDER_ID + FieldOlderUrl, + Pagination.ParamOlderId ); UpdatePaginationBodyFromResponseField( paginationBody, - Pagination.PARAM_NEWER_ID, + Pagination.ParamNewerId, responseJson, - FIELD_NEWER_URL, - Pagination.PARAM_NEWER_ID + FieldNewerUrl, + Pagination.ParamNewerId ); UpdatePaginationBodyFromResponseField( paginationBody, - Pagination.PARAM_FUTURE_ID, + Pagination.ParamFutureId, responseJson, - FIELD_FUTURE_URL, - Pagination.PARAM_NEWER_ID + FieldFutureUrl, + Pagination.ParamNewerId ); return paginationBody; @@ -92,10 +93,10 @@ private static void UpdatePaginationBodyFromResponseField(IDictionary ParseUriParams(JToken uriToken) { if (uriToken == null) return new Dictionary(); - return new Uri(URI_BASE_DUMMY + uriToken).Query - .TrimStart(ApiClient.DELIMITER_URI_QUERY) - .Split(ApiClient.DELIMITER_URI_PARAMS) - .Select(param => param.Split(ApiClient.DELIMITER_URI_PARAM_KEY_VALUE)) - .ToDictionary(pair => pair[INDEX_PARAM_KEY], pair => pair[INDEX_PARAM_VALUE]); + return new Uri(UriBaseDummy + uriToken).Query + .TrimStart(ApiClient.DelimiterUriQuery) + .Split(ApiClient.DelimiterAllUriParameter) + .Select(param => param.Split(ApiClient.DelimiterUriParamKeyValue)) + .ToDictionary(pair => pair[IndexParamKey], pair => pair[IndexParamValue]); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) diff --git a/BunqSdk/Json/SessionServerConverter.cs b/BunqSdk/Json/SessionServerConverter.cs index 5a614b8..67de4e6 100644 --- a/BunqSdk/Json/SessionServerConverter.cs +++ b/BunqSdk/Json/SessionServerConverter.cs @@ -6,33 +6,39 @@ namespace Bunq.Sdk.Json { + /// /// /// Custom (de)serialization of SessionServer required due to the unconventional structure of the /// SessionServer POST response. /// public class SessionServerConverter : JsonConverter { - private const int INDEX_ID = 0; - private const string FIELD_ID = "Id"; + /// + /// The indices of the attributes inside the json object. + /// + private const int IndexId = 0; + private const int IndexUser = 2; + private const int IndexToken = 1; - private const int INDEX_TOKEN = 1; - private const string FIELD_TOKEN = "Token"; - - private const int INDEX_USER = 2; - private const string FIELD_USER_COMPANY = "UserCompany"; - private const string FIELD_USER_PERSON = "UserPerson"; + /// + /// Field constantss. + /// + private const string FieldId = "Id"; + private const string FieldToken = "Token"; + private const string FieldUserCompany = "UserCompany"; + private const string FieldUserPerson = "UserPerson"; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObjects = JArray.Load(reader); - var id = FetchObject(jObjects[INDEX_ID], FIELD_ID); - var token = FetchObject(jObjects[INDEX_TOKEN], FIELD_TOKEN); - var userBody = jObjects[INDEX_USER]; + var id = FetchObject(jObjects[IndexId], FieldId); + var token = FetchObject(jObjects[IndexToken], FieldToken); + var userBody = jObjects[IndexUser]; - return userBody[FIELD_USER_COMPANY] == null - ? new SessionServer(id, token, FetchObject(userBody, FIELD_USER_PERSON)) - : new SessionServer(id, token, FetchObject(userBody, FIELD_USER_COMPANY)); + return userBody[FieldUserCompany] == null + ? new SessionServer(id, token, FetchObject(userBody, FieldUserPerson)) + : new SessionServer(id, token, FetchObject(userBody, FieldUserCompany)); } private static T FetchObject(JToken jToken, string fieldName) diff --git a/BunqSdk/Model/Core/BunqModel.cs b/BunqSdk/Model/Core/BunqModel.cs index 790109c..bf5f91b 100644 --- a/BunqSdk/Model/Core/BunqModel.cs +++ b/BunqSdk/Model/Core/BunqModel.cs @@ -12,15 +12,15 @@ public abstract class BunqModel /// /// Field constants. /// - private const string FIELD_RESPONSE = "Response"; - private const string FIELD_ID = "Id"; - private const string FIELD_UUID = "Uuid"; - private const string FIELD_PAGINATION = "Pagination"; + private const string FieldResponse = "Response"; + private const string FieldId = "Id"; + private const string FieldUuid = "Uuid"; + private const string FieldPagination = "Pagination"; /// /// Index of the very first item in an array. /// - private const int INDEX_FIRST = 0; + private const int IndexFirst = 0; /// /// De-serializes an object from a JSON format specific to Installation and SessionServer. @@ -29,7 +29,7 @@ protected static BunqResponse FromJsonArrayNested(BunqResponseRaw response { var json = Encoding.UTF8.GetString(responseRaw.BodyBytes); var jObject = BunqJsonConvert.DeserializeObject(json); - var jsonArrayString = jObject.GetValue(FIELD_RESPONSE).ToString(); + var jsonArrayString = jObject.GetValue(FieldResponse).ToString(); var responseValue = BunqJsonConvert.DeserializeObject(jsonArrayString); return new BunqResponse(responseValue, responseRaw.Headers); @@ -41,7 +41,7 @@ protected static BunqResponse FromJsonArrayNested(BunqResponseRaw response protected static BunqResponse ProcessForId(BunqResponseRaw responseRaw) { var responseItemObject = GetResponseItemObject(responseRaw); - var unwrappedItemJsonString = GetUnwrappedItemJsonString(responseItemObject, FIELD_ID); + var unwrappedItemJsonString = GetUnwrappedItemJsonString(responseItemObject, FieldId); var responseValue = BunqJsonConvert.DeserializeObject(unwrappedItemJsonString).IdInt; return new BunqResponse(responseValue, responseRaw.Headers); @@ -52,7 +52,7 @@ private static JObject GetResponseItemObject(BunqResponseRaw responseRaw) var json = Encoding.UTF8.GetString(responseRaw.BodyBytes); var responseWithWrapper = BunqJsonConvert.DeserializeObject(json); - return responseWithWrapper.GetValue(FIELD_RESPONSE).ToObject().Value(INDEX_FIRST); + return responseWithWrapper.GetValue(FieldResponse).ToObject().Value(IndexFirst); } private static string GetUnwrappedItemJsonString(JObject json, string wrapper) @@ -66,7 +66,7 @@ private static string GetUnwrappedItemJsonString(JObject json, string wrapper) protected static BunqResponse ProcessForUuid(BunqResponseRaw responseRaw) { var responseItemObject = GetResponseItemObject(responseRaw); - var unwrappedItemJsonString = GetUnwrappedItemJsonString(responseItemObject, FIELD_UUID); + var unwrappedItemJsonString = GetUnwrappedItemJsonString(responseItemObject, FieldUuid); var responseValue = BunqJsonConvert.DeserializeObject(unwrappedItemJsonString).UuidString; return new BunqResponse(responseValue, responseRaw.Headers); @@ -106,7 +106,7 @@ protected static BunqResponse> FromJsonList(BunqResponseRaw responseR { var responseObject = DeserializeResponseObject(responseRaw); var responseValue = responseObject - .GetValue(FIELD_RESPONSE).ToObject() + .GetValue(FieldResponse).ToObject() .Select(unwrappedItemObject => GetUnwrappedItemJsonString(unwrappedItemObject.ToObject(), wrapper)) .Select(BunqJsonConvert.DeserializeObject) @@ -120,7 +120,7 @@ protected static BunqResponse> FromJsonList(BunqResponseRaw responseR { var responseObject = DeserializeResponseObject(responseRaw); var responseValue = responseObject - .GetValue(FIELD_RESPONSE).ToObject() + .GetValue(FieldResponse).ToObject() .Select(itemObject => BunqJsonConvert.DeserializeObject(itemObject.ToString())) .ToList(); var pagination = DeserializePagination(responseObject); @@ -130,7 +130,7 @@ protected static BunqResponse> FromJsonList(BunqResponseRaw responseR private static Pagination DeserializePagination(JObject responseObject) { - var paginationBody = responseObject.GetValue(FIELD_PAGINATION).ToString(); + var paginationBody = responseObject.GetValue(FieldPagination).ToString(); return BunqJsonConvert.DeserializeObject(paginationBody); } diff --git a/BunqSdk/Model/Core/Installation.cs b/BunqSdk/Model/Core/Installation.cs index 72ed018..6103ea4 100644 --- a/BunqSdk/Model/Core/Installation.cs +++ b/BunqSdk/Model/Core/Installation.cs @@ -11,16 +11,16 @@ public class Installation : BunqModel /// /// Endpoint name. /// - private const string ENDPOINT_URL_POST = "installation"; + private const string EndpointUrlPost = "installation"; /// /// Field constants. /// - private const string FIELD_CLIENT_PUBLIC_KEY = "client_public_key"; + private const string FieldClientPublicKey = "client_public_key"; - public SessionToken SessionToken { get; private set; } private readonly Id id; private readonly PublicKeyServer publicKeyServer; + public SessionToken SessionToken { get; private set; } public Installation(Id id, SessionToken sessionToken, PublicKeyServer publicKeyServer) { @@ -43,7 +43,7 @@ public static BunqResponse Create(ApiContext apiContext, string pu { var requestBytes = GenerateRequestBodyBytes(publicKeyClientString); var apiClient = new ApiClient(apiContext); - var responseRaw = apiClient.Post(ENDPOINT_URL_POST, requestBytes, new Dictionary()); + var responseRaw = apiClient.Post(EndpointUrlPost, requestBytes, new Dictionary()); return FromJsonArrayNested(responseRaw); } @@ -51,7 +51,7 @@ public static BunqResponse Create(ApiContext apiContext, string pu private static byte[] GenerateRequestBodyBytes(string publicKeyClientString) { var installationRequestBody = - new Dictionary {{FIELD_CLIENT_PUBLIC_KEY, publicKeyClientString}}; + new Dictionary {{FieldClientPublicKey, publicKeyClientString}}; return Encoding.UTF8.GetBytes(BunqJsonConvert.SerializeObject(installationRequestBody)); } diff --git a/BunqSdk/Model/Core/SessionServer.cs b/BunqSdk/Model/Core/SessionServer.cs index 7029832..ae248eb 100644 --- a/BunqSdk/Model/Core/SessionServer.cs +++ b/BunqSdk/Model/Core/SessionServer.cs @@ -12,12 +12,12 @@ public class SessionServer : BunqModel /// /// Endpoint name. /// - private const string ENDPOINT_URL_POST = "session-server"; + private const string EndpointUrlPost = "session-server"; /// /// Field constants. /// - private const string FIELD_SECRET = "secret"; + private const string FieldSecret = "secret"; public Id Id { get; private set; } public SessionToken SessionToken { get; private set; } @@ -50,14 +50,14 @@ public static BunqResponse Create(ApiContext apiContext) { var apiClient = new ApiClient(apiContext); var requestBytes = GenerateRequestBodyBytes(apiContext.ApiKey); - var responseRaw = apiClient.Post(ENDPOINT_URL_POST, requestBytes, new Dictionary()); + var responseRaw = apiClient.Post(EndpointUrlPost, requestBytes, new Dictionary()); return FromJsonArrayNested(responseRaw); } private static byte[] GenerateRequestBodyBytes(string apiKey) { - var sessionServerRequestBody = new Dictionary {{FIELD_SECRET, apiKey}}; + var sessionServerRequestBody = new Dictionary {{FieldSecret, apiKey}}; return Encoding.UTF8.GetBytes(BunqJsonConvert.SerializeObject(sessionServerRequestBody)); } diff --git a/BunqSdk/Security/RsaParameterTraits.cs b/BunqSdk/Security/RsaParameterTraits.cs index e3098d1..612faa5 100644 --- a/BunqSdk/Security/RsaParameterTraits.cs +++ b/BunqSdk/Security/RsaParameterTraits.cs @@ -27,7 +27,7 @@ namespace Bunq.Sdk.Security { internal class RsaParameterTraits { - private const double TOLERANCE = 0.000001; + private const double Tolerance = 0.000001; internal int SizeMod { get; private set; } internal int SizeExp { get; private set; } internal int SizeD { get; private set; } @@ -51,7 +51,7 @@ internal RsaParameterTraits(int modulusLengthInBits) int assumedLength; var logbase = Math.Log(modulusLengthInBits, 2); - if (Math.Abs(logbase - (int) logbase) < TOLERANCE) + if (Math.Abs(logbase - (int) logbase) < Tolerance) { assumedLength = modulusLengthInBits; } diff --git a/BunqSdk/Security/SecurityUtils.cs b/BunqSdk/Security/SecurityUtils.cs index c08004e..ad0c36c 100644 --- a/BunqSdk/Security/SecurityUtils.cs +++ b/BunqSdk/Security/SecurityUtils.cs @@ -18,76 +18,76 @@ public class SecurityUtils /// /// Error constants. /// - private const string ERROR_COULD_NOT_VERIFY_RESPONSE = "Could not verify server response."; + private const string ErrorCouldNotVerifyResponse = "Could not verify server response."; /// /// Constants for formatting the request textual representation for signing. /// - private const string NEWLINE = "\n"; - private const string FORMAT_METHOD_AND_ENDPOINT_STRING = "{0} /v1/{1}"; - private const string HEADER_NAME_PREFIX_X_BUNQ = "X-Bunq-"; - private const string DELIMITER_HEADER_VALUE = ","; - private const string FORMAT_HEADER_STRING = "{0}: {1}"; + private const string FormatNewline = "\n"; + private const string FormatMethodAndEndpointString = "{0} /v1/{1}"; + private const string FormatHeaderNamePrefixXBunq = "X-Bunq-"; + private const string FormatDelimiterHeaderValue = ","; + private const string FormatHeaderString = "{0}: {1}"; /// /// Length of an empty array. /// - private const int ARRAY_LENGTH_EMPTY = 0; + private const int ArrayLengthEmpty = 0; /// /// Constants for formatting RSA keys. /// - private const string PUBLIC_KEY_START = "-----BEGIN PUBLIC KEY-----\n"; - private const string PUBLIC_KEY_END = "\n-----END PUBLIC KEY-----\n"; - private const string FORMAT_PUBLIC_KEY = PUBLIC_KEY_START + "{0}" + PUBLIC_KEY_END; - private const string PRIVATE_KEY_START = "-----BEGIN PRIVATE KEY-----\n"; - private const string PRIVATE_KEY_END = "\n-----END PRIVATE KEY-----\n"; - private const string FORMAT_PRIVATE_KEY = PRIVATE_KEY_START + "{0}" + PRIVATE_KEY_END; + private const string FormatPublicKeyStart = "-----BEGIN PUBLIC KEY-----\n"; + private const string FormatPublicKeyEnd = "\n-----END PUBLIC KEY-----\n"; + private const string FormatPublicKey = FormatPublicKeyStart + "{0}" + FormatPublicKeyEnd; + private const string FormatPrivateKeyStart = "-----BEGIN PRIVATE KEY-----\n"; + private const string FormatPrivateKeyEnd = "\n-----END PRIVATE KEY-----\n"; + private const string FormatPrivateKey = FormatPrivateKeyStart + "{0}" + FormatPrivateKeyEnd; /// /// Size of the encryption key. /// - private const int RSA_KEY_SIZE = 2048; + private const int RsaKeySize = 2048; /// /// Encryption-specific headers. /// - private const string HEADER_CLIENT_ENCRYPTION_HMAC = "X-Bunq-Client-Encryption-Hmac"; - private const string HEADER_CLIENT_ENCRYPTION_IV = "X-Bunq-Client-Encryption-Iv"; - private const string HEADER_CLIENT_ENCRYPTION_KEY = "X-Bunq-Client-Encryption-Key"; - private const string HEADER_SERVER_SIGNATURE = "X-Bunq-Server-Signature"; + private const string HeaderClientEncryptionHmac = "X-Bunq-Client-Encryption-Hmac"; + private const string HeaderClientEncryptionIv = "X-Bunq-Client-Encryption-Iv"; + private const string HeaderClientEncryptionKey = "X-Bunq-Client-Encryption-Key"; + private const string HeaderServerSignature = "X-Bunq-Server-Signature"; /// /// Padding modes for the encrypted key and body. /// - private static readonly RSAEncryptionPadding BUNQ_PADDING_MODE_KEY = RSAEncryptionPadding.Pkcs1; - private const PaddingMode BUNQ_PADDING_MODE_BODY = PaddingMode.PKCS7; + private static readonly RSAEncryptionPadding BunqPaddingModeKey = RSAEncryptionPadding.Pkcs1; + private const PaddingMode BunqPaddingModeBody = PaddingMode.PKCS7; /// /// Sizes of key and IV/block to be used for encrypting bodies of encrypted requests. /// - private const int BUNQ_KEY_SIZE_BITS = 256; - private const int BUNQ_BLOCK_SIZE_BITS = 128; + private const int BunqKeySizeBits = 256; + private const int BunqBlockSizeBits = 128; /// /// Cipher mode for encrypting bodies of encrypted requests. /// - private const CipherMode BUNQ_CIPHER_MODE = CipherMode.CBC; + private const CipherMode BunqCipherMode = CipherMode.CBC; /// /// Number of the very first index in an array or a string. /// - private const int INDEX_FIRST = 0; + private const int IndexFirst = 0; /// /// The index after the firts character in a string. /// - private const int INDEX_LAST_FIRST_CHAR = 1; + private const int IndexLastFirstChar = 1; /// /// Regex constants. /// - private const string REGEX_FOR_LOWERCASE_HEADERS = "(-[a-z])"; + private const string RegexForLowercaseHeaders = "(-[a-z])"; /// /// Generates a base64-representation of RSA/SHA256/PKCS1 signature for a given RequestMessage. @@ -107,14 +107,14 @@ private static byte[] GetRequestBodyBytes(HttpRequestMessage requestMessage) { var requestContent = requestMessage.Content; - return requestContent == null ? new byte[ARRAY_LENGTH_EMPTY] : requestContent.ReadAsByteArrayAsync().Result; + return requestContent == null ? new byte[ArrayLengthEmpty] : requestContent.ReadAsByteArrayAsync().Result; } private static byte[] GenerateRequestHeadBytes(HttpRequestMessage requestMessage) { - var requestHeadString = GenerateMethodAndEndpointString(requestMessage) + NEWLINE + - GenerateRequestHeadersSortedString(requestMessage) + NEWLINE + - NEWLINE; + var requestHeadString = GenerateMethodAndEndpointString(requestMessage) + FormatNewline + + GenerateRequestHeadersSortedString(requestMessage) + FormatNewline + + FormatNewline; return Encoding.UTF8.GetBytes(requestHeadString); } @@ -124,16 +124,16 @@ private static string GenerateMethodAndEndpointString(HttpRequestMessage request var method = requestMessage.Method.ToString(); var endpoint = requestMessage.RequestUri.ToString(); - return string.Format(FORMAT_METHOD_AND_ENDPOINT_STRING, method, endpoint); + return string.Format(FormatMethodAndEndpointString, method, endpoint); } private static string GenerateRequestHeadersSortedString(HttpRequestMessage requestMessage) { return GenerateHeadersSortedString( requestMessage.Headers.Where(x => - x.Key.StartsWith(HEADER_NAME_PREFIX_X_BUNQ) || - x.Key.Equals(ApiClient.HEADER_CACHE_CONTROL) || - x.Key.Equals(ApiClient.HEADER_USER_AGENT) + x.Key.StartsWith(FormatHeaderNamePrefixXBunq) || + x.Key.Equals(ApiClient.HeaderCacheControl) || + x.Key.Equals(ApiClient.HeaderUserAgent) ) ); } @@ -141,13 +141,13 @@ private static string GenerateRequestHeadersSortedString(HttpRequestMessage requ private static string GetHeaderNameCorrectlyCased(string headerName) { headerName = headerName.ToLower(); - headerName = headerName.First().ToString().ToUpper() + headerName.Substring(INDEX_LAST_FIRST_CHAR); - var matches = Regex.Matches(headerName, REGEX_FOR_LOWERCASE_HEADERS); + headerName = headerName.First().ToString().ToUpper() + headerName.Substring(IndexLastFirstChar); + var matches = Regex.Matches(headerName, RegexForLowercaseHeaders); return matches.Cast().Aggregate( headerName, (current, match) => current.Replace( - match.Groups[INDEX_FIRST].Value, match.Groups[INDEX_FIRST].Value.ToUpper() + match.Groups[IndexFirst].Value, match.Groups[IndexFirst].Value.ToUpper() ) ); } @@ -156,10 +156,10 @@ private static string GenerateHeadersSortedString( IEnumerable>> headers) { return headers - .Select(x => new KeyValuePair(x.Key, string.Join(DELIMITER_HEADER_VALUE, x.Value))) + .Select(x => new KeyValuePair(x.Key, string.Join(FormatDelimiterHeaderValue, x.Value))) .ToImmutableSortedDictionary() - .Select(x => string.Format(FORMAT_HEADER_STRING, x.Key, x.Value)) - .Aggregate((a, b) => a + NEWLINE + b); + .Select(x => string.Format(FormatHeaderString, x.Key, x.Value)) + .Aggregate((a, b) => a + FormatNewline + b); } private static byte[] ConcatenateByteArrays(byte[] byteArray1, byte[] byteArray2) @@ -179,7 +179,7 @@ public static string GetPublicKeyFormattedString(RSA keyPair) var publicKey = keyPair.ExportParameters(false); var publicKeyBytes = RsaKeyUtils.PublicKeyToX509(publicKey); - return string.Format(FORMAT_PUBLIC_KEY, Convert.ToBase64String(publicKeyBytes)); + return string.Format(FormatPublicKey, Convert.ToBase64String(publicKeyBytes)); } /// @@ -193,7 +193,7 @@ public static string GetPrivateKeyFormattedString(RSA keyPair) var privateKey = keyPair.ExportParameters(true); var privateKeyBytes = RsaKeyUtils.PrivateKeyToPkcs8(privateKey); - return string.Format(FORMAT_PRIVATE_KEY, Convert.ToBase64String(privateKeyBytes)); + return string.Format(FormatPrivateKey, Convert.ToBase64String(privateKeyBytes)); } catch (SecurityException) { @@ -207,8 +207,8 @@ public static string GetPrivateKeyFormattedString(RSA keyPair) public static RSA CreateKeyPairFromPrivateKeyFormattedString(string privateKeyString) { var privateKeyStringTrimmed = privateKeyString - .Replace(PRIVATE_KEY_START, string.Empty) - .Replace(PRIVATE_KEY_END, string.Empty); + .Replace(FormatPrivateKeyStart, string.Empty) + .Replace(FormatPrivateKeyEnd, string.Empty); return RsaKeyUtils.DecodePrivateKeyInfo(Convert.FromBase64String(privateKeyStringTrimmed)); } @@ -219,8 +219,8 @@ public static RSA CreateKeyPairFromPrivateKeyFormattedString(string privateKeySt public static RSA CreatePublicKeyFromPublicKeyFormattedString(string publicKeyString) { var publicKeyStringTrimmed = publicKeyString - .Replace(PUBLIC_KEY_START, string.Empty) - .Replace(PUBLIC_KEY_END, string.Empty); + .Replace(FormatPublicKeyStart, string.Empty) + .Replace(FormatPublicKeyEnd, string.Empty); return RsaKeyUtils.DecodePublicKey(Convert.FromBase64String(publicKeyStringTrimmed)); } @@ -231,7 +231,7 @@ public static RSA CreatePublicKeyFromPublicKeyFormattedString(string publicKeySt public static RSA GenerateKeyPair() { var rsa = RSA.Create(); - rsa.KeySize = RSA_KEY_SIZE; + rsa.KeySize = RsaKeySize; return rsa; } @@ -255,10 +255,10 @@ public static byte[] Encrypt(ApiContext apiContext, byte[] requestBytes, IDictio private static Aes CreateBunqAes() { var aes = Aes.Create(); - aes.KeySize = BUNQ_KEY_SIZE_BITS; - aes.BlockSize = BUNQ_BLOCK_SIZE_BITS; - aes.Padding = BUNQ_PADDING_MODE_BODY; - aes.Mode = BUNQ_CIPHER_MODE; + aes.KeySize = BunqKeySizeBits; + aes.BlockSize = BunqBlockSizeBits; + aes.Padding = BunqPaddingModeBody; + aes.Mode = BunqCipherMode; aes.GenerateKey(); aes.GenerateIV(); @@ -268,20 +268,20 @@ private static Aes CreateBunqAes() private static void AddHeaderEncryptionKey(ApiContext apiContext, IDictionary headers, SymmetricAlgorithm aes) { - var keyEncrypted = apiContext.InstallationContext.PublicKeyServer.Encrypt(aes.Key, BUNQ_PADDING_MODE_KEY); - headers.Add(HEADER_CLIENT_ENCRYPTION_KEY, Convert.ToBase64String(keyEncrypted)); + var keyEncrypted = apiContext.InstallationContext.PublicKeyServer.Encrypt(aes.Key, BunqPaddingModeKey); + headers.Add(HeaderClientEncryptionKey, Convert.ToBase64String(keyEncrypted)); } private static void AddHeaderEncryptionIv(IDictionary headers, SymmetricAlgorithm aes) { - headers.Add(HEADER_CLIENT_ENCRYPTION_IV, Convert.ToBase64String(aes.IV)); + headers.Add(HeaderClientEncryptionIv, Convert.ToBase64String(aes.IV)); } private static byte[] EncryptBytes(SymmetricAlgorithm aes, byte[] bytesToEncrypt) { using (var encrypt = aes.CreateEncryptor()) { - return encrypt.TransformFinalBlock(bytesToEncrypt, INDEX_FIRST, bytesToEncrypt.Length); + return encrypt.TransformFinalBlock(bytesToEncrypt, IndexFirst, bytesToEncrypt.Length); } } @@ -289,7 +289,7 @@ private static void AddHeaderEncryptionHmac(IDictionary headers, byte[] requestBytesEncrypted) { var hash = HashHmac(aes.IV, requestBytesEncrypted, aes.Key); - headers.Add(HEADER_CLIENT_ENCRYPTION_HMAC, Convert.ToBase64String(hash)); + headers.Add(HeaderClientEncryptionHmac, Convert.ToBase64String(hash)); } private static byte[] HashHmac(byte[] iv, byte[] bytes, byte[] key) @@ -298,7 +298,7 @@ private static byte[] HashHmac(byte[] iv, byte[] bytes, byte[] key) { var buffer = new byte[iv.Length + bytes.Length]; Array.Copy(iv, buffer, iv.Length); - Array.Copy(bytes, INDEX_FIRST, buffer, iv.Length, bytes.Length); + Array.Copy(bytes, IndexFirst, buffer, iv.Length, bytes.Length); return hmacSha1.ComputeHash(buffer); } @@ -309,21 +309,21 @@ public static void ValidateResponse(HttpResponseMessage responseMessage, RSA ser var headBytes = GenerateResponseHeadBytes(responseMessage); var bodyBytes = responseMessage.Content.ReadAsByteArrayAsync().Result; var responseBytes = ConcatenateByteArrays(headBytes, bodyBytes); - var serverSignatureHeader = string.Join(",", responseMessage.Headers.GetValues(HEADER_SERVER_SIGNATURE)); + var serverSignatureHeader = string.Join(",", responseMessage.Headers.GetValues(HeaderServerSignature)); var serverSignature = Convert.FromBase64String(serverSignatureHeader); if (!serverPublicKey.VerifyData(responseBytes, serverSignature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) { - throw new BunqException(ERROR_COULD_NOT_VERIFY_RESPONSE); + throw new BunqException(ErrorCouldNotVerifyResponse); } } private static byte[] GenerateResponseHeadBytes(HttpResponseMessage responseMessage) { - var requestHeadString = (int) responseMessage.StatusCode + NEWLINE + - GenerateResponseHeadersSortedString(responseMessage) + NEWLINE + - NEWLINE; + var requestHeadString = (int) responseMessage.StatusCode + FormatNewline + + GenerateResponseHeadersSortedString(responseMessage) + FormatNewline + + FormatNewline; return Encoding.UTF8.GetBytes(requestHeadString); } @@ -332,8 +332,8 @@ private static string GenerateResponseHeadersSortedString(HttpResponseMessage re { return GenerateHeadersSortedString( responseMessage.Headers.Where(x => - GetHeaderNameCorrectlyCased(x.Key).StartsWith(HEADER_NAME_PREFIX_X_BUNQ) && - !GetHeaderNameCorrectlyCased(x.Key).Equals(HEADER_SERVER_SIGNATURE) + GetHeaderNameCorrectlyCased(x.Key).StartsWith(FormatHeaderNamePrefixXBunq) && + !GetHeaderNameCorrectlyCased(x.Key).Equals(HeaderServerSignature) ) ); }