(SINGLE_BOUNCE_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/CampaignsTests.cs b/Source/StrongGrid.UnitTests/Resources/CampaignsTests.cs
index 2ed38246..a0414f95 100644
--- a/Source/StrongGrid.UnitTests/Resources/CampaignsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/CampaignsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models.Legacy;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,75 +16,75 @@ public class CampaignsTests
{
#region FIELDS
- private const string ENDPOINT = "campaigns";
+ internal const string ENDPOINT = "campaigns";
- private const string SINGLE_CAMPAIGN_JSON = @"{
- 'id': 986724,
- 'title': 'March Newsletter',
- 'subject': 'New Products for Spring!',
- 'sender_id': 124451,
- 'list_ids': [
+ internal const string SINGLE_CAMPAIGN_JSON = @"{
+ ""id"": 986724,
+ ""title"": ""March Newsletter"",
+ ""subject"": ""New Products for Spring!"",
+ ""sender_id"": 124451,
+ ""list_ids"": [
110,
124
],
- 'segment_ids': [
+ ""segment_ids"": [
110
],
- 'categories': [
- 'spring line'
+ ""categories"": [
+ ""spring line""
],
- 'suppression_group_id': 42,
- 'custom_unsubscribe_url': '',
- 'ip_pool': 'marketing',
- 'html_content': 'Check out our spring line!
',
- 'plain_content': 'Check out our spring line!',
- 'status': 'Draft'
+ ""suppression_group_id"": 42,
+ ""custom_unsubscribe_url"": """",
+ ""ip_pool"": ""marketing"",
+ ""html_content"": ""Check out our spring line!
"",
+ ""plain_content"": ""Check out our spring line!"",
+ ""status"": ""Draft""
}";
- private const string MULTIPLE_CAMPAIGNS_JSON = @"{
- 'result': [
+ internal const string MULTIPLE_CAMPAIGNS_JSON = @"{
+ ""result"": [
{
- 'id': 986724,
- 'title': 'March Newsletter',
- 'subject': 'New Products for Spring!',
- 'sender_id': 124451,
- 'list_ids': [
+ ""id"": 986724,
+ ""title"": ""March Newsletter"",
+ ""subject"": ""New Products for Spring!"",
+ ""sender_id"": 124451,
+ ""list_ids"": [
110,
124
],
- 'segment_ids': [
+ ""segment_ids"": [
110
],
- 'categories': [
- 'spring line'
+ ""categories"": [
+ ""spring line""
],
- 'suppression_group_id': 42,
- 'custom_unsubscribe_url': '',
- 'ip_pool': 'marketing',
- 'html_content': 'Check out our spring line!
',
- 'plain_content': 'Check out our spring line!',
- 'status': 'Draft'
+ ""suppression_group_id"": 42,
+ ""custom_unsubscribe_url"": """",
+ ""ip_pool"": ""marketing"",
+ ""html_content"": ""Check out our spring line!
"",
+ ""plain_content"": ""Check out our spring line!"",
+ ""status"": ""Draft""
},
{
- 'id': 986723,
- 'title': 'February Newsletter',
- 'subject': 'Final Winter Product Sale!',
- 'sender_id': 124451,
- 'list_ids': [
+ ""id"": 986723,
+ ""title"": ""February Newsletter"",
+ ""subject"": ""Final Winter Product Sale!"",
+ ""sender_id"": 124451,
+ ""list_ids"": [
110,
124
],
- 'segment_ids': [
+ ""segment_ids"": [
110
],
- 'categories': [
- 'winter line'
+ ""categories"": [
+ ""winter line""
],
- 'suppression_group_id': 42,
- 'custom_unsubscribe_url': '',
- 'ip_pool': 'marketing',
- 'html_content': 'Last call for winter clothes!
',
- 'plain_content': 'Last call for winter clothes!',
- 'status': 'Sent'
+ ""suppression_group_id"": 42,
+ ""custom_unsubscribe_url"": """",
+ ""ip_pool"": ""marketing"",
+ ""html_content"": ""Last call for winter clothes!
"",
+ ""plain_content"": ""Last call for winter clothes!"",
+ ""status"": ""Sent""
}
]
}";
@@ -97,7 +97,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_CAMPAIGN_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_CAMPAIGN_JSON);
// Assert
result.ShouldNotBeNull();
@@ -236,8 +236,8 @@ public async Task SendNowAsync()
var campaignId = 986724;
var apiResponse = @"{
- 'id': 986724,
- 'status': 'Scheduled'
+ ""id"": 986724,
+ ""status"": ""Scheduled""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -262,9 +262,9 @@ public async Task ScheduleAsync()
var sendOn = DateTime.UtcNow.AddHours(5);
var apiResponse = @"{
- 'id': 986724,
- 'send_at': 1489771528,
- 'status': 'Scheduled'
+ ""id"": 986724,
+ ""send_at"": 1489771528,
+ ""status"": ""Scheduled""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -289,9 +289,9 @@ public async Task RescheduleAsync()
var sendOn = DateTime.UtcNow.AddHours(15);
var apiResponse = @"{
- 'id': 986724,
- 'send_at': 1489451436,
- 'status': 'Scheduled'
+ ""id"": 986724,
+ ""send_at"": 1489451436,
+ ""status"": ""Scheduled""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -314,7 +314,7 @@ public async Task GetScheduledDateAsync()
// Arrange
var campaignId = 986724;
var apiResponse = @"{
- 'send_at': 1489771528
+ ""send_at"": 1489771528
}";
var mockHttp = new MockHttpMessageHandler();
diff --git a/Source/StrongGrid.UnitTests/Resources/DesignsTests.cs b/Source/StrongGrid.UnitTests/Resources/DesignsTests.cs
index 13be6b02..5933397c 100644
--- a/Source/StrongGrid.UnitTests/Resources/DesignsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/DesignsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,55 +16,55 @@ public class DesignsTests
{
#region FIELDS
- private const string ENDPOINT = "designs";
-
- private const string SINGLE_DESIGN_JSON = @"{
- 'id':'4fa4db1f-219e-4599-8239-05dde4404611',
- 'name':'This is my name',
- 'html_content':'This is a test',
- 'plain_content':'This is a test',
- 'generate_plain_content':true,
- 'thumbnail_url':'//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png',
- 'subject':'This is the subject',
- 'created_at':'2019-12-24T20:14:41Z',
- 'updated_at':'2019-12-24T20:15:22Z',
- 'editor':'code',
- 'categories':['one','two','three']
+ internal const string ENDPOINT = "designs";
+
+ internal const string SINGLE_DESIGN_JSON = @"{
+ ""id"":""4fa4db1f-219e-4599-8239-05dde4404611"",
+ ""name"":""This is my name"",
+ ""html_content"":""This is a test"",
+ ""plain_content"":""This is a test"",
+ ""generate_plain_content"":true,
+ ""thumbnail_url"":""//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png"",
+ ""subject"":""This is the subject"",
+ ""created_at"":""2019-12-24T20:14:41Z"",
+ ""updated_at"":""2019-12-24T20:15:22Z"",
+ ""editor"":""code"",
+ ""categories"":[""one"",""two"",""three""]
}";
- private const string MULTIPLE_DESIGNS_JSON = @"{
- 'result': [
+ internal const string MULTIPLE_DESIGNS_JSON = @"{
+ ""result"": [
{
- 'id':'4fa4db1f-219e-4599-8239-05dde4404611',
- 'name':'This is my name',
- 'html_content':'This is a test',
- 'plain_content':'This is a test',
- 'generate_plain_content':true,
- 'thumbnail_url':'//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png',
- 'subject':'This is the subject',
- 'created_at':'2019-12-24T20:14:41Z',
- 'updated_at':'2019-12-24T20:15:22Z',
- 'editor':'code',
- 'categories':['one','two','three']
+ ""id"":""4fa4db1f-219e-4599-8239-05dde4404611"",
+ ""name"":""This is my name"",
+ ""html_content"":""This is a test"",
+ ""plain_content"":""This is a test"",
+ ""generate_plain_content"":true,
+ ""thumbnail_url"":""//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png"",
+ ""subject"":""This is the subject"",
+ ""created_at"":""2019-12-24T20:14:41Z"",
+ ""updated_at"":""2019-12-24T20:15:22Z"",
+ ""editor"":""code"",
+ ""categories"":[""one"",""two"",""three""]
},
{
- 'id':'another_key',
- 'name':'Another name',
- 'html_content':'This is another test',
- 'plain_content':'This is another test',
- 'generate_plain_content':true,
- 'thumbnail_url':'//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png',
- 'subject':'This is the other subject',
- 'created_at':'2019-12-24T20:14:41Z',
- 'updated_at':'2019-12-24T20:15:22Z',
- 'editor':'code',
- 'categories':['four','five']
+ ""id"":""another_key"",
+ ""name"":""Another name"",
+ ""html_content"":""This is another test"",
+ ""plain_content"":""This is another test"",
+ ""generate_plain_content"":true,
+ ""thumbnail_url"":""//us-east-2-production-thumbnail-bucket.s3.amazonaws.com/a6d262cec2588fe05c894ea162f8a1f26d91f37fe7fa412f2c3ecf091d14d60b.png"",
+ ""subject"":""This is the other subject"",
+ ""created_at"":""2019-12-24T20:14:41Z"",
+ ""updated_at"":""2019-12-24T20:15:22Z"",
+ ""editor"":""code"",
+ ""categories"":[""four"",""five""]
}
],
- '_metadata':{
- 'prev':'https://api.sendgrid.com/v3/designs?page_token=prev_token',
- 'self':'https://api.sendgrid.com/v3/designs?page_token=self_token',
- 'next':'https://api.sendgrid.com/v3/designs?page_token=next_token',
- 'count':5
+ ""_metadata"":{
+ ""prev"":""https://api.sendgrid.com/v3/designs?page_token=prev_token"",
+ ""self"":""https://api.sendgrid.com/v3/designs?page_token=self_token"",
+ ""next"":""https://api.sendgrid.com/v3/designs?page_token=next_token"",
+ ""count"":5
}
}";
@@ -76,7 +76,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_DESIGN_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_DESIGN_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/EmailActivitiesTests.cs b/Source/StrongGrid.UnitTests/Resources/EmailActivitiesTests.cs
index ef4c0c1c..6845d26a 100644
--- a/Source/StrongGrid.UnitTests/Resources/EmailActivitiesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/EmailActivitiesTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -8,6 +7,7 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -18,22 +18,22 @@ public class EmailActivitiesTests
{
#region FIELDS
- private const string ENDPOINT = "messages";
-
- private const string SINGLE_MESSAGE = @"{
- 'from_email': 'test@example.com',
- 'msg_id': 'thtIPCIcR_iFZDws2JCrwA.filter0004p3las1-2776-5ACA5525-31.1',
- 'subject': 'Dear customer',
- 'to_email': 'bob@example.com',
- 'status': 'delivered',
- 'opens_count': 2,
- 'clicks_count': 1,
- 'last_event_time': '2018-04-08T17:47:18Z'
+ internal const string ENDPOINT = "messages";
+
+ internal const string SINGLE_MESSAGE = @"{
+ ""from_email"": ""test@example.com"",
+ ""msg_id"": ""thtIPCIcR_iFZDws2JCrwA.filter0004p3las1-2776-5ACA5525-31.1"",
+ ""subject"": ""Dear customer"",
+ ""to_email"": ""bob@example.com"",
+ ""status"": ""delivered"",
+ ""opens_count"": 2,
+ ""clicks_count"": 1,
+ ""last_event_time"": ""2018-04-08T17:47:18Z""
}";
- private const string NO_MESSAGES_FOUND = "{'messages':[]}";
- private const string ONE_MESSAGE_FOUND = "{'messages':[" + SINGLE_MESSAGE + "]}";
- private const string MULTIPLE_MESSAGES_FOUND = "{'messages':[" +
+ internal const string NO_MESSAGES_FOUND = "{\"messages\":[]}";
+ internal const string ONE_MESSAGE_FOUND = "{\"messages\":[" + SINGLE_MESSAGE + "]}";
+ internal const string MULTIPLE_MESSAGES_FOUND = "{\"messages\":[" +
SINGLE_MESSAGE + "," +
SINGLE_MESSAGE + "," +
SINGLE_MESSAGE +
@@ -47,7 +47,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_MESSAGE);
+ var result = JsonSerializer.Deserialize(SINGLE_MESSAGE);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/EmailValidationTests.cs b/Source/StrongGrid.UnitTests/Resources/EmailValidationTests.cs
index 878d6682..53d37c88 100644
--- a/Source/StrongGrid.UnitTests/Resources/EmailValidationTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/EmailValidationTests.cs
@@ -1,9 +1,9 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -14,55 +14,55 @@ public class EmailValidationTests
{
#region FIELDS
- private const string ENDPOINT = "validations/email";
-
- private const string INVALID_EMAIL_RESPONSE = @"{
- 'email': 'john.doe@gmial.com',
- 'verdict': 'Invalid',
- 'score': 0.00089,
- 'local': 'john.doe',
- 'host': 'gmial.com',
- 'suggestion': 'gmail.com',
- 'checks': {
- 'domain': {
- 'has_valid_address_syntax': true,
- 'has_mx_or_a_record': true,
- 'is_suspected_disposable_address': false
+ internal const string ENDPOINT = "validations/email";
+
+ internal const string INVALID_EMAIL_JSON = @"{
+ ""email"": ""john.doe@gmial.com"",
+ ""verdict"": ""Invalid"",
+ ""score"": 0.00089,
+ ""local"": ""john.doe"",
+ ""host"": ""gmial.com"",
+ ""suggestion"": ""gmail.com"",
+ ""checks"": {
+ ""domain"": {
+ ""has_valid_address_syntax"": true,
+ ""has_mx_or_a_record"": true,
+ ""is_suspected_disposable_address"": false
},
- 'local_part': {
- 'is_suspected_role_address': false
+ ""local_part"": {
+ ""is_suspected_role_address"": false
},
- 'additional': {
- 'has_known_bounces': false,
- 'has_suspected_bounces': true
+ ""additional"": {
+ ""has_known_bounces"": false,
+ ""has_suspected_bounces"": true
}
},
- 'ip_address': '123.45.67.89'
+ ""ip_address"": ""123.45.67.89""
}";
- private const string VALID_EMAIL_RESPONSE = @"{
- 'email': 'valid_email_address@mtsg.me',
- 'verdict': 'Valid',
- 'score': 0.93357,
- 'local': 'valid_email_address',
- 'host': 'mtsg.me',
- 'checks': {
- 'domain': {
- 'has_valid_address_syntax': true,
- 'has_mx_or_a_record': true,
- 'is_suspected_disposable_address': false
+ internal const string VALID_EMAIL_JSON = @"{
+ ""email"": ""valid_email_address@mtsg.me"",
+ ""verdict"": ""Valid"",
+ ""score"": 0.93357,
+ ""local"": ""valid_email_address"",
+ ""host"": ""mtsg.me"",
+ ""checks"": {
+ ""domain"": {
+ ""has_valid_address_syntax"": true,
+ ""has_mx_or_a_record"": true,
+ ""is_suspected_disposable_address"": false
},
- 'local_part': {
- 'is_suspected_role_address': false
+ ""local_part"": {
+ ""is_suspected_role_address"": false
},
- 'additional': {
- 'has_known_bounces': false,
- 'has_suspected_bounces': false
+ ""additional"": {
+ ""has_known_bounces"": false,
+ ""has_suspected_bounces"": false
}
},
- 'source': 'TEST',
- 'ip_address': '123.123.123.123'
+ ""source"": ""TEST"",
+ ""ip_address"": ""123.123.123.123""
}";
#endregion
@@ -73,7 +73,7 @@ public void Parse_invalid_email_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(INVALID_EMAIL_RESPONSE);
+ var result = JsonSerializer.Deserialize(INVALID_EMAIL_JSON);
// Assert
result.ShouldNotBeNull();
@@ -104,7 +104,7 @@ public void Parse_valid_email_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(VALID_EMAIL_RESPONSE);
+ var result = JsonSerializer.Deserialize(VALID_EMAIL_JSON);
// Assert
result.ShouldNotBeNull();
@@ -132,7 +132,7 @@ public void Parse_valid_email_json()
public async Task ValidateAsync()
{
// Arrange
- var apiResponse = "{'result':" + VALID_EMAIL_RESPONSE + "}";
+ var apiResponse = "{\"result\":" + VALID_EMAIL_JSON + "}";
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT)).Respond("application/json", apiResponse);
diff --git a/Source/StrongGrid.UnitTests/Resources/GlobalSuppressionTests.cs b/Source/StrongGrid.UnitTests/Resources/GlobalSuppressionTests.cs
index c94ad2b8..14f9b161 100644
--- a/Source/StrongGrid.UnitTests/Resources/GlobalSuppressionTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/GlobalSuppressionTests.cs
@@ -13,19 +13,19 @@ public class GlobalSuppressionTests
{
#region FIELDS
- private const string ENDPOINT = "asm/suppressions/global";
- private const string GLOBALLY_UNSUBSCRIBED = @"[
+ internal const string ENDPOINT = "asm/suppressions/global";
+ internal const string GLOBALLY_UNSUBSCRIBED = @"[
{
- 'email': 'example@bogus.com',
- 'created': 1422313607
+ ""email"": ""example@bogus.com"",
+ ""created"": 1422313607
},
{
- 'email': 'bogus@example.com',
- 'created': 1422313607
+ ""email"": ""bogus@example.com"",
+ ""created"": 1422313607
},
{
- 'email': 'invalid@somewhere.com',
- 'created': 1422313607
+ ""email"": ""invalid@somewhere.com"",
+ ""created"": 1422313607
}
]";
@@ -57,9 +57,9 @@ public async Task AddAsync()
// Arrange
var emails = new[] { "test1@example.com", "test2@example.com" };
var apiResponse = @"{
- 'recipient_emails': [
- 'test1@example.com',
- 'test2@example.com'
+ ""recipient_emails"": [
+ ""test1@example.com"",
+ ""test2@example.com""
]
}";
@@ -104,7 +104,7 @@ public async Task IsUnsubscribedAsync_true()
var email = "test1@example.com";
var apiResponse = @"{
- 'recipient_email': 'test1@example.com'
+ ""recipient_email"": ""test1@example.com""
}";
var mockHttp = new MockHttpMessageHandler();
diff --git a/Source/StrongGrid.UnitTests/Resources/InvalidEmailsTests.cs b/Source/StrongGrid.UnitTests/Resources/InvalidEmailsTests.cs
index 11057953..2d797fcb 100644
--- a/Source/StrongGrid.UnitTests/Resources/InvalidEmailsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/InvalidEmailsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,23 +16,23 @@ public class InvalidEmailsTests
{
#region FIELDS
- private const string ENDPOINT = "suppression/invalid_emails";
+ internal const string ENDPOINT = "suppression/invalid_emails";
- private const string SINGLE_INVALID_EMAIL_JSON = @"{
- 'created': 1454433146,
- 'email': 'test1@example.com',
- 'reason': 'Mail domain mentioned in email address is unknown'
+ internal const string SINGLE_INVALID_EMAIL_JSON = @"{
+ ""created"": 1454433146,
+ ""email"": ""test1@example.com"",
+ ""reason"": ""Mail domain mentioned in email address is unknown""
}";
- private const string MULTIPLE_INVALID_EMAILS_JSON = @"[
+ internal const string MULTIPLE_INVALID_EMAILS_JSON = @"[
{
- 'created': 1449953655,
- 'email': 'user1@example.com',
- 'reason': 'Mail domain mentioned in email address is unknown'
+ ""created"": 1449953655,
+ ""email"": ""user1@example.com"",
+ ""reason"": ""Mail domain mentioned in email address is unknown""
},
{
- 'created': 1449939373,
- 'email': 'user1@example.com',
- 'reason': 'Mail domain mentioned in email address is unknown'
+ ""created"": 1449939373,
+ ""email"": ""user1@example.com"",
+ ""reason"": ""Mail domain mentioned in email address is unknown""
}
]";
@@ -44,7 +44,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_INVALID_EMAIL_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_INVALID_EMAIL_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/IpAddressesTests.cs b/Source/StrongGrid.UnitTests/Resources/IpAddressesTests.cs
index e0dcc2dc..456884bd 100644
--- a/Source/StrongGrid.UnitTests/Resources/IpAddressesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/IpAddressesTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,35 +16,35 @@ public class IpAddressesTests
{
#region FIELDS
- private const string ENDPOINT = "ips";
+ internal const string ENDPOINT = "ips";
- private const string SINGLE_ASSIGNED_IPADDRESS_JSON = @"{
- 'ip': '192.168.1.1',
- 'pools': [
- 'pool1',
- 'pool2'
+ internal const string SINGLE_ASSIGNED_IPADDRESS_JSON = @"{
+ ""ip"": ""192.168.1.1"",
+ ""pools"": [
+ ""pool1"",
+ ""pool2""
],
- 'whitelabeled': false,
- 'start_date': 1409616000,
- 'subusers': [
- 'tim@sendgrid.net'
+ ""whitelabeled"": false,
+ ""start_date"": 1409616000,
+ ""subusers"": [
+ ""tim@sendgrid.net""
],
- 'warmup': false,
- 'assigned_at': 1482883200
+ ""warmup"": false,
+ ""assigned_at"": 1482883200
}";
- private const string SINGLE_UNASSIGNED_IPADDRESS_JSON = @"{
- 'ip': '208.115.214.22',
- 'pools': [],
- 'whitelabeled': true,
- 'rdns': 'o1.email.burgermail.com',
- 'start_date': 1409616000,
- 'subusers': [],
- 'warmup': false,
- 'assigned_at': 1482883200
+ internal const string SINGLE_UNASSIGNED_IPADDRESS_JSON = @"{
+ ""ip"": ""208.115.214.22"",
+ ""pools"": [],
+ ""whitelabeled"": true,
+ ""rdns"": ""o1.email.burgermail.com"",
+ ""start_date"": 1409616000,
+ ""subusers"": [],
+ ""warmup"": false,
+ ""assigned_at"": 1482883200
}";
- private const string MULTIPLE_IPADDRESSES_JSON = "[" +
+ internal const string MULTIPLE_IPADDRESSES_JSON = "[" +
SINGLE_ASSIGNED_IPADDRESS_JSON + "," +
SINGLE_UNASSIGNED_IPADDRESS_JSON +
"]";
@@ -57,7 +57,7 @@ public void Parse_single_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_ASSIGNED_IPADDRESS_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_ASSIGNED_IPADDRESS_JSON);
// Assert
result.ShouldNotBeNull();
@@ -80,7 +80,7 @@ public void Parse_multiple_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(MULTIPLE_IPADDRESSES_JSON);
+ var result = JsonSerializer.Deserialize(MULTIPLE_IPADDRESSES_JSON);
// Assert
result.ShouldNotBeNull();
@@ -101,14 +101,14 @@ public async Task AddAsync()
{
// Arrange
var apiResponse = @"{
- 'ips': [
+ ""ips"": [
{
- 'ip': '1.2.3.4',
- 'subusers': [ 'jdesautels' ]
+ ""ip"": ""1.2.3.4"",
+ ""subusers"": [ ""jdesautels"" ]
}
],
- 'remaining_ips':2,
- 'warmup': false
+ ""remaining_ips"":2,
+ ""warmup"": false
}";
var mockHttp = new MockHttpMessageHandler();
@@ -136,11 +136,11 @@ public async Task GetRemainingCountAsync()
{
// Arrange
var apiResponse = @"{
- 'results': [
+ ""results"": [
{
- 'remaining': 2,
- 'period': 'month',
- 'price_per_ip': 20
+ ""remaining"": 2,
+ ""period"": ""month"",
+ ""price_per_ip"": 20
}
]
}";
diff --git a/Source/StrongGrid.UnitTests/Resources/IpPoolsTests.cs b/Source/StrongGrid.UnitTests/Resources/IpPoolsTests.cs
index 49d8740a..32628d75 100644
--- a/Source/StrongGrid.UnitTests/Resources/IpPoolsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/IpPoolsTests.cs
@@ -1,10 +1,10 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -15,15 +15,15 @@ public class IpPoolsTests
{
#region FIELDS
- private const string ENDPOINT = "ips/pools";
+ internal const string ENDPOINT = "ips/pools";
- private const string SINGLE_IPPOOL_JSON = @"{
- 'pool_name': 'marketing',
- 'ips':
+ internal const string SINGLE_IPPOOL_JSON = @"{
+ ""pool_name"": ""marketing"",
+ ""ips"":
[
- { 'ip': '1.1.1.1', 'start_date': null, 'warmup': false },
- { 'ip': '2.2.2.2', 'start_date': null, 'warmup': false },
- { 'ip': '3.3.3.3', 'start_date': null, 'warmup': false }
+ { ""ip"": ""1.1.1.1"", ""start_date"": null, ""warmup"": false },
+ { ""ip"": ""2.2.2.2"", ""start_date"": null, ""warmup"": false },
+ { ""ip"": ""3.3.3.3"", ""start_date"": null, ""warmup"": false }
]
}";
@@ -35,7 +35,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_IPPOOL_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_IPPOOL_JSON);
// Assert
result.ShouldNotBeNull();
@@ -53,7 +53,7 @@ public async Task CreateAsync()
var name = "marketing";
var apiResponse = @"{
- 'name': 'marketing'
+ ""name"": ""marketing""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -78,10 +78,10 @@ public async Task GetAllNamesAsync()
// Arrange
var apiResponse = @"[
{
- 'name': 'marketing'
+ ""name"": ""marketing""
},
{
- 'name': 'transactional'
+ ""name"": ""transactional""
}
]";
@@ -132,7 +132,7 @@ public async Task UpdateAsync()
var newName = "New Name";
var apiResponse = @"{
- 'name': 'New Name'
+ ""name"": ""New Name""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -179,12 +179,12 @@ public async Task AddAdressAsync()
var address = "0.0.0.0";
var apiResponse = @"{
- 'ip': '000.00.00.0',
- 'pools': [
- 'test1'
+ ""ip"": ""000.00.00.0"",
+ ""pools"": [
+ ""test1""
],
- 'start_date': 1409616000,
- 'warmup': true
+ ""start_date"": 1409616000,
+ ""warmup"": true
}";
var mockHttp = new MockHttpMessageHandler();
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacyCategoriesTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacyCategoriesTests.cs
index b2a0af72..4ad5fb45 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacyCategoriesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacyCategoriesTests.cs
@@ -12,14 +12,14 @@ public class LegacyCategoriesTests
{
#region FIELDS
- private const string ENDPOINT = "categories";
-
- private const string MULTIPLE_CATEGORIES_JSON = @"[
- { 'category': 'cat1' },
- { 'category': 'cat2' },
- { 'category': 'cat3' },
- { 'category': 'cat4' },
- { 'category': 'cat5' }
+ internal const string ENDPOINT = "categories";
+
+ internal const string MULTIPLE_CATEGORIES_JSON = @"[
+ { ""category"": ""cat1"" },
+ { ""category"": ""cat2"" },
+ { ""category"": ""cat3"" },
+ { ""category"": ""cat4"" },
+ { ""category"": ""cat5"" }
]";
#endregion
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacyContactsTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacyContactsTests.cs
index 198ace2d..89b53583 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacyContactsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacyContactsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -7,6 +6,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -17,51 +17,51 @@ public class LegacyContactsTests
{
#region FIELDS
- private const string ENDPOINT = "contactdb/recipients";
-
- private const string SINGLE_RECIPIENT_JSON = @"{
- 'created_at': 1422313607,
- 'email': 'jones@example.com',
- 'first_name': null,
- 'id': 'YUBh',
- 'last_clicked': null,
- 'last_emailed': null,
- 'last_name': 'Jones',
- 'last_opened': null,
- 'updated_at': 1422313790,
- 'custom_fields': [
+ internal const string ENDPOINT = "contactdb/recipients";
+
+ internal const string SINGLE_RECIPIENT_JSON = @"{
+ ""created_at"": 1422313607,
+ ""email"": ""jones@example.com"",
+ ""first_name"": null,
+ ""id"": ""YUBh"",
+ ""last_clicked"": null,
+ ""last_emailed"": null,
+ ""last_name"": ""Jones"",
+ ""last_opened"": null,
+ ""updated_at"": 1422313790,
+ ""custom_fields"": [
{
- 'id': 23,
- 'name': 'pet',
- 'value': 'Indiana',
- 'type': 'text'
+ ""id"": 23,
+ ""name"": ""pet"",
+ ""value"": ""Indiana"",
+ ""type"": ""text""
}
]
}";
- private const string MULTIPLE_RECIPIENTS_JSON = @"{
- 'recipients': [
+ internal const string MULTIPLE_RECIPIENTS_JSON = @"{
+ ""recipients"": [
{
- 'created_at': 1422313607,
- 'email': 'jones@example.com',
- 'first_name': null,
- 'id': 'YUBh',
- 'last_clicked': null,
- 'last_emailed': null,
- 'last_name': 'Jones',
- 'last_opened': null,
- 'updated_at': 1422313790,
- 'custom_fields': [
+ ""created_at"": 1422313607,
+ ""email"": ""jones@example.com"",
+ ""first_name"": null,
+ ""id"": ""YUBh"",
+ ""last_clicked"": null,
+ ""last_emailed"": null,
+ ""last_name"": ""Jones"",
+ ""last_opened"": null,
+ ""updated_at"": 1422313790,
+ ""custom_fields"": [
{
- 'id': 23,
- 'name': 'pet',
- 'value': 'Indiana',
- 'type': 'text'
+ ""id"": 23,
+ ""name"": ""pet"",
+ ""value"": ""Indiana"",
+ ""type"": ""text""
},
{
- 'id': 24,
- 'name': 'age',
- 'value': '43',
- 'type': 'number'
+ ""id"": 24,
+ ""name"": ""age"",
+ ""value"": ""43"",
+ ""type"": ""number""
}
]
}
@@ -76,7 +76,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_RECIPIENT_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_RECIPIENT_JSON);
// Assert
result.ShouldNotBeNull();
@@ -107,16 +107,16 @@ public async Task CreateAsync_success()
var lastName = "Doe";
var apiResponse = @"{
- 'error_count': 0,
- 'error_indices': [
+ ""error_count"": 0,
+ ""error_indices"": [
],
- 'unmodified_indices': [
+ ""unmodified_indices"": [
],
- 'new_count': 1,
- 'persisted_recipients': [
- 'am9uZXNAZXhhbXBsZS5jb20='
+ ""new_count"": 1,
+ ""persisted_recipients"": [
+ ""am9uZXNAZXhhbXBsZS5jb20=""
],
- 'updated_count': 0
+ ""updated_count"": 0
}";
var mockHttp = new MockHttpMessageHandler();
@@ -143,16 +143,16 @@ public async Task CreateAsync_failure()
var lastName = "Doe";
var apiResponse = @"{
- 'error_count': 1,
- 'error_indices': [0],
- 'unmodified_indices': [],
- 'new_count': 0,
- 'persisted_recipients': [],
- 'updated_count': 0,
- 'errors': [
+ ""error_count"": 1,
+ ""error_indices"": [0],
+ ""unmodified_indices"": [],
+ ""new_count"": 0,
+ ""persisted_recipients"": [],
+ ""updated_count"": 0,
+ ""errors"": [
{
- 'message': 'Invalid email.',
- 'error_indices': [0]
+ ""message"": ""Invalid email."",
+ ""error_indices"": [0]
}
]
}";
@@ -185,23 +185,23 @@ public async Task ImportAsync()
};
var apiResponse = @"{
- 'error_count': 1,
- 'error_indices': [
+ ""error_count"": 1,
+ ""error_indices"": [
2
],
- 'unmodified_indices': [
+ ""unmodified_indices"": [
3
],
- 'new_count': 2,
- 'persisted_recipients': [
- 'YUBh',
- 'bWlsbGVyQG1pbGxlci50ZXN0'
+ ""new_count"": 2,
+ ""persisted_recipients"": [
+ ""YUBh"",
+ ""bWlsbGVyQG1pbGxlci50ZXN0""
],
- 'updated_count': 0,
- 'errors': [
+ ""updated_count"": 0,
+ ""errors"": [
{
- 'message': 'Invalid email.',
- 'error_indices': [
+ ""message"": ""Invalid email."",
+ ""error_indices"": [
2
]
}
@@ -239,17 +239,17 @@ public async Task UpdateAsync_success()
var lastName = "Jones";
var apiResponse = @"{
- 'error_count': 0,
- 'error_indices': [
+ ""error_count"": 0,
+ ""error_indices"": [
],
- 'unmodified_indices': [
+ ""unmodified_indices"": [
1
],
- 'new_count': 0,
- 'persisted_recipients': [
- 'am9uZXNAZXhhbXBsZS5jb20='
+ ""new_count"": 0,
+ ""persisted_recipients"": [
+ ""am9uZXNAZXhhbXBsZS5jb20=""
],
- 'updated_count': 1
+ ""updated_count"": 1
}";
var mockHttp = new MockHttpMessageHandler();
@@ -283,16 +283,16 @@ public async Task UpdateAsync_failure()
var lastName = "Jones";
var apiResponse = @"{
- 'error_count': 1,
- 'error_indices': [0],
- 'unmodified_indices': [],
- 'new_count': 0,
- 'persisted_recipients': [],
- 'updated_count': 0,
- 'errors': [
+ ""error_count"": 1,
+ ""error_indices"": [0],
+ ""unmodified_indices"": [],
+ ""new_count"": 0,
+ ""persisted_recipients"": [],
+ ""updated_count"": 0,
+ ""errors"": [
{
- 'message': 'Invalid email.',
- 'error_indices': [0]
+ ""message"": ""Invalid email."",
+ ""error_indices"": [0]
}
]
}";
@@ -413,7 +413,7 @@ public async Task GetBillableCountAsync()
{
// Arrange
var apiResponse = @"{
- 'recipient_count': 2
+ ""recipient_count"": 2
}";
var mockHttp = new MockHttpMessageHandler();
@@ -436,7 +436,7 @@ public async Task GetTotalCountAsync()
{
// Arrange
var apiResponse = @"{
- 'recipient_count': 3
+ ""recipient_count"": 3
}";
var mockHttp = new MockHttpMessageHandler();
@@ -484,29 +484,29 @@ public async Task SearchAsync()
}
};
var apiResponse = @"{
- 'recipients': [
+ ""recipients"": [
{
- 'created_at': 1422313607,
- 'email': 'jones@example.com',
- 'first_name': null,
- 'id': 'YUBh',
- 'last_clicked': 12345,
- 'last_emailed': null,
- 'last_name': 'Miller',
- 'last_opened': null,
- 'updated_at': 1422313790,
- 'custom_fields': [
+ ""created_at"": 1422313607,
+ ""email"": ""jones@example.com"",
+ ""first_name"": null,
+ ""id"": ""YUBh"",
+ ""last_clicked"": 12345,
+ ""last_emailed"": null,
+ ""last_name"": ""Miller"",
+ ""last_opened"": null,
+ ""updated_at"": 1422313790,
+ ""custom_fields"": [
{
- 'id': 23,
- 'name': 'pet',
- 'value': 'Indiana',
- 'type': 'text'
+ ""id"": 23,
+ ""name"": ""pet"",
+ ""value"": ""Indiana"",
+ ""type"": ""text""
},
{
- 'id': 24,
- 'name': 'age',
- 'value': '43',
- 'type': 'number'
+ ""id"": 24,
+ ""name"": ""age"",
+ ""value"": ""43"",
+ ""type"": ""number""
}
]
}
@@ -542,29 +542,29 @@ public async Task SearchAsync_without_conditions()
var listId = (int?)null;
var conditions = (SearchCondition[])null;
var apiResponse = @"{
- 'recipients': [
+ ""recipients"": [
{
- 'created_at': 1422313607,
- 'email': 'jones@example.com',
- 'first_name': null,
- 'id': 'YUBh',
- 'last_clicked': 12345,
- 'last_emailed': null,
- 'last_name': 'Miller',
- 'last_opened': null,
- 'updated_at': 1422313790,
- 'custom_fields': [
+ ""created_at"": 1422313607,
+ ""email"": ""jones@example.com"",
+ ""first_name"": null,
+ ""id"": ""YUBh"",
+ ""last_clicked"": 12345,
+ ""last_emailed"": null,
+ ""last_name"": ""Miller"",
+ ""last_opened"": null,
+ ""updated_at"": 1422313790,
+ ""custom_fields"": [
{
- 'id': 23,
- 'name': 'pet',
- 'value': 'Indiana',
- 'type': 'text'
+ ""id"": 23,
+ ""name"": ""pet"",
+ ""value"": ""Indiana"",
+ ""type"": ""text""
},
{
- 'id': 24,
- 'name': 'age',
- 'value': '43',
- 'type': 'number'
+ ""id"": 24,
+ ""name"": ""age"",
+ ""value"": ""43"",
+ ""type"": ""number""
}
]
}
@@ -599,16 +599,16 @@ public async Task GetListsAsync()
// Arrange
var contactId = "YUBh";
var listsJson = @"{
- 'lists': [
+ ""lists"": [
{
- 'id': 1,
- 'name': 'prospects',
- 'recipient_count': 1
+ ""id"": 1,
+ ""name"": ""prospects"",
+ ""recipient_count"": 1
},
{
- 'id': 2,
- 'name': 'customers',
- 'recipient_count': 1
+ ""id"": 2,
+ ""name"": ""customers"",
+ ""recipient_count"": 1
}
]
}";
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacyCustomFieldsTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacyCustomFieldsTests.cs
index 3fe25bc0..dfce7301 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacyCustomFieldsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacyCustomFieldsTests.cs
@@ -1,10 +1,10 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources.Legacy;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -15,29 +15,29 @@ public class LegacyCustomFieldsTests
{
#region FIELDS
- private const string ENDPOINT = "contactdb/custom_fields";
+ internal const string ENDPOINT = "contactdb/custom_fields";
- private const string SINGLE_CUSTOM_FIELD_JSON = @"{
- 'id': 1,
- 'name': 'customfield1',
- 'type': 'text'
+ internal const string SINGLE_CUSTOM_FIELD_JSON = @"{
+ ""id"": 1,
+ ""name"": ""customfield1"",
+ ""type"": ""text""
}";
- private const string MULTIPLE_CUSTOM_FIELDS_JSON = @"{
- 'custom_fields': [
+ internal const string MULTIPLE_CUSTOM_FIELDS_JSON = @"{
+ ""custom_fields"": [
{
- 'id': 1,
- 'name': 'birthday',
- 'type': 'date'
+ ""id"": 1,
+ ""name"": ""birthday"",
+ ""type"": ""date""
},
{
- 'id': 2,
- 'name': 'middle_name',
- 'type': 'text'
+ ""id"": 2,
+ ""name"": ""middle_name"",
+ ""type"": ""text""
},
{
- 'id': 3,
- 'name': 'favorite_number',
- 'type': 'number'
+ ""id"": 3,
+ ""name"": ""favorite_number"",
+ ""type"": ""number""
}
]
}";
@@ -50,7 +50,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_CUSTOM_FIELD_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_CUSTOM_FIELD_JSON);
// Assert
result.ShouldNotBeNull();
@@ -147,42 +147,42 @@ public async Task GetReservedFieldsAsync()
{
// Arrange
var apiResponse = @"{
- 'reserved_fields': [
+ ""reserved_fields"": [
{
- 'name': 'first_name',
- 'type': 'text'
+ ""name"": ""first_name"",
+ ""type"": ""text""
},
{
- 'name': 'last_name',
- 'type': 'text'
+ ""name"": ""last_name"",
+ ""type"": ""text""
},
{
- 'name': 'email',
- 'type': 'text'
+ ""name"": ""email"",
+ ""type"": ""text""
},
{
- 'name': 'created_at',
- 'type': 'date'
+ ""name"": ""created_at"",
+ ""type"": ""date""
},
{
- 'name': 'updated_at',
- 'type': 'date'
+ ""name"": ""updated_at"",
+ ""type"": ""date""
},
{
- 'name': 'last_emailed',
- 'type': 'date'
+ ""name"": ""last_emailed"",
+ ""type"": ""date""
},
{
- 'name': 'last_clicked',
- 'type': 'date'
+ ""name"": ""last_clicked"",
+ ""type"": ""date""
},
{
- 'name': 'last_opened',
- 'type': 'date'
+ ""name"": ""last_opened"",
+ ""type"": ""date""
},
{
- 'name': 'my_custom_field',
- 'type': 'text'
+ ""name"": ""my_custom_field"",
+ ""type"": ""text""
}
]
}";
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacyListsTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacyListsTests.cs
index 2c6abb60..043f9fd4 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacyListsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacyListsTests.cs
@@ -1,9 +1,9 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Resources.Legacy;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -14,19 +14,19 @@ public class LegacyListsTests
{
#region FIELDS
- private const string ENDPOINT = "contactdb/lists";
+ internal const string ENDPOINT = "contactdb/lists";
- private const string SINGLE_LIST_JSON = @"{
- 'id': 1,
- 'name': 'listname',
- 'recipient_count': 0
+ internal const string SINGLE_LIST_JSON = @"{
+ ""id"": 1,
+ ""name"": ""listname"",
+ ""recipient_count"": 0
}";
- private const string MULTIPLE_LISTS_JSON = @"{
- 'lists': [
+ internal const string MULTIPLE_LISTS_JSON = @"{
+ ""lists"": [
{
- 'id': 1,
- 'name': 'the jones',
- 'recipient_count': 1
+ ""id"": 1,
+ ""name"": ""the jones"",
+ ""recipient_count"": 1
}
]
}";
@@ -39,7 +39,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_LIST_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_LIST_JSON);
// Assert
result.ShouldNotBeNull();
@@ -180,17 +180,17 @@ public async Task GetRecipientsAsync()
var page = 1;
var apiResponse = @"{
- 'recipients': [
+ ""recipients"": [
{
- 'created_at': 1422395108,
- 'email': 'e@example.com',
- 'first_name': 'Ed',
- 'id': 'YUBh',
- 'last_clicked': null,
- 'last_emailed': null,
- 'last_name': null,
- 'last_opened': null,
- 'updated_at': 1422395108
+ ""created_at"": 1422395108,
+ ""email"": ""e@example.com"",
+ ""first_name"": ""Ed"",
+ ""id"": ""YUBh"",
+ ""last_clicked"": null,
+ ""last_emailed"": null,
+ ""last_name"": null,
+ ""last_opened"": null,
+ ""updated_at"": 1422395108
}
]
}";
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacySegmentsTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacySegmentsTests.cs
index a0ea0bae..5e25b140 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacySegmentsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacySegmentsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using StrongGrid.Resources.Legacy;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,48 +16,48 @@ public class LegacySegmentsTests
{
#region FIELDS
- private const string ENDPOINT = "contactdb/segments";
+ internal const string ENDPOINT = "contactdb/segments";
- private const string SINGLE_SEGMENT_JSON = @"{
- 'id': 1,
- 'name': 'Last Name Miller',
- 'list_id': 4,
- 'conditions': [
+ internal const string SINGLE_SEGMENT_JSON = @"{
+ ""id"": 1,
+ ""name"": ""Last Name Miller"",
+ ""list_id"": 4,
+ ""conditions"": [
{
- 'field': 'last_name',
- 'value': 'Miller',
- 'operator': 'eq',
- 'and_or': ''
+ ""field"": ""last_name"",
+ ""value"": ""Miller"",
+ ""operator"": ""eq"",
+ ""and_or"": """"
},
{
- 'field': 'last_clicked',
- 'value': '01/02/2015',
- 'operator': 'gt',
- 'and_or': 'and'
+ ""field"": ""last_clicked"",
+ ""value"": ""01/02/2015"",
+ ""operator"": ""gt"",
+ ""and_or"": ""and""
},
{
- 'field': 'clicks.campaign_identifier',
- 'value': '513',
- 'operator': 'eq',
- 'and_or': 'or'
+ ""field"": ""clicks.campaign_identifier"",
+ ""value"": ""513"",
+ ""operator"": ""eq"",
+ ""and_or"": ""or""
}
]
}";
- private const string MULTIPLE_SEGMENTS_JSON = @"{
- 'segments': [
+ internal const string MULTIPLE_SEGMENTS_JSON = @"{
+ ""segments"": [
{
- 'id': 1,
- 'name': 'Last Name Miller',
- 'list_id': 4,
- 'conditions': [
+ ""id"": 1,
+ ""name"": ""Last Name Miller"",
+ ""list_id"": 4,
+ ""conditions"": [
{
- 'field': 'last_name',
- 'value': 'Miller',
- 'operator': 'eq',
- 'and_or': ''
+ ""field"": ""last_name"",
+ ""value"": ""Miller"",
+ ""operator"": ""eq"",
+ ""and_or"": """"
}
],
- 'recipient_count': 1
+ ""recipient_count"": 1
}
]
}";
@@ -70,7 +70,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SEGMENT_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SEGMENT_JSON);
// Assert
result.ShouldNotBeNull();
@@ -268,23 +268,23 @@ public async Task GetRecipientsAsync()
var page = 1;
var apiResponse = @"{
- 'recipients': [
+ ""recipients"": [
{
- 'created_at': 1422313607,
- 'email': 'jones@example.com',
- 'first_name': null,
- 'id': 'YUBh',
- 'last_clicked': null,
- 'last_emailed': null,
- 'last_name': 'Jones',
- 'last_opened': null,
- 'updated_at': 1422313790,
- 'custom_fields': [
+ ""created_at"": 1422313607,
+ ""email"": ""jones@example.com"",
+ ""first_name"": null,
+ ""id"": ""YUBh"",
+ ""last_clicked"": null,
+ ""last_emailed"": null,
+ ""last_name"": ""Jones"",
+ ""last_opened"": null,
+ ""updated_at"": 1422313790,
+ ""custom_fields"": [
{
- 'id': 23,
- 'name': 'pet',
- 'value': 'Indiana',
- 'type': 'text'
+ ""id"": 23,
+ ""name"": ""pet"",
+ ""value"": ""Indiana"",
+ ""type"": ""text""
}
]
}
diff --git a/Source/StrongGrid.UnitTests/Resources/LegacySenderIdentitiesTests.cs b/Source/StrongGrid.UnitTests/Resources/LegacySenderIdentitiesTests.cs
index 529a18dc..6b64336c 100644
--- a/Source/StrongGrid.UnitTests/Resources/LegacySenderIdentitiesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/LegacySenderIdentitiesTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,52 +16,52 @@ public class LegacySenderIdentitiesTests
{
#region FIELDS
- private const string ENDPOINT = "senders";
+ internal const string ENDPOINT = "senders";
- private const string SINGLE_SENDER_IDENTITY_JSON = @"{
- 'id': 1,
- 'nickname': 'My Sender ID',
- 'from': {
- 'email': 'from@example.com',
- 'name': 'Example INC'
+ internal const string SINGLE_SENDER_IDENTITY_JSON = @"{
+ ""id"": 1,
+ ""nickname"": ""My Sender ID"",
+ ""from"": {
+ ""email"": ""from@example.com"",
+ ""name"": ""Example INC""
},
- 'reply_to': {
- 'email': 'replyto@example.com',
- 'name': 'Example INC'
+ ""reply_to"": {
+ ""email"": ""replyto@example.com"",
+ ""name"": ""Example INC""
},
- 'address': '123 Elm St.',
- 'address_2': 'Apt. 456',
- 'city': 'Denver',
- 'state': 'Colorado',
- 'zip': '80202',
- 'country': 'United States',
- 'verified': { 'status': true, 'reason': '' },
- 'updated_at': 1449872165,
- 'created_at': 1449872165,
- 'locked': false
+ ""address"": ""123 Elm St."",
+ ""address_2"": ""Apt. 456"",
+ ""city"": ""Denver"",
+ ""state"": ""Colorado"",
+ ""zip"": ""80202"",
+ ""country"": ""United States"",
+ ""verified"": { ""status"": true, ""reason"": """" },
+ ""updated_at"": 1449872165,
+ ""created_at"": 1449872165,
+ ""locked"": false
}";
- private const string MULTIPLE_SENDER_IDENTITIES_JSON = @"[
+ internal const string MULTIPLE_SENDER_IDENTITIES_JSON = @"[
{
- 'id': 1,
- 'nickname': 'My Sender ID',
- 'from': {
- 'email': 'from@example.com',
- 'name': 'Example INC'
+ ""id"": 1,
+ ""nickname"": ""My Sender ID"",
+ ""from"": {
+ ""email"": ""from@example.com"",
+ ""name"": ""Example INC""
},
- 'reply_to': {
- 'email': 'replyto@example.com',
- 'name': 'Example INC'
+ ""reply_to"": {
+ ""email"": ""replyto@example.com"",
+ ""name"": ""Example INC""
},
- 'address': '123 Elm St.',
- 'address_2': 'Apt. 456',
- 'city': 'Denver',
- 'state': 'Colorado',
- 'zip': '80202',
- 'country': 'United States',
- 'verified': { 'status': true, 'reason': '' },
- 'updated_at': 1449872165,
- 'created_at': 1449872165,
- 'locked': false
+ ""address"": ""123 Elm St."",
+ ""address_2"": ""Apt. 456"",
+ ""city"": ""Denver"",
+ ""state"": ""Colorado"",
+ ""zip"": ""80202"",
+ ""country"": ""United States"",
+ ""verified"": { ""status"": true, ""reason"": """" },
+ ""updated_at"": 1449872165,
+ ""created_at"": 1449872165,
+ ""locked"": false
}
]";
@@ -73,7 +73,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SENDER_IDENTITY_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SENDER_IDENTITY_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/MailTests.cs b/Source/StrongGrid.UnitTests/Resources/MailTests.cs
index 616a4e09..ca082255 100644
--- a/Source/StrongGrid.UnitTests/Resources/MailTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/MailTests.cs
@@ -19,7 +19,7 @@ public class MailTests
{
#region FIELDS
- private const string ENDPOINT = "mail";
+ internal const string ENDPOINT = "mail";
#endregion
diff --git a/Source/StrongGrid.UnitTests/Resources/SenderAuthenticationTests.cs b/Source/StrongGrid.UnitTests/Resources/SenderAuthenticationTests.cs
index 6e7377d6..979f17d1 100644
--- a/Source/StrongGrid.UnitTests/Resources/SenderAuthenticationTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/SenderAuthenticationTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,281 +16,281 @@ public class SenderAuthenticationTests
{
#region FIELDS
- private const string ENDPOINT = "whitelabel";
-
- private const string SINGLE_DOMAIN_JSON = @"{
- 'id': 1,
- 'domain': 'example.com',
- 'subdomain': 'mail',
- 'username': 'john@example.com',
- 'user_id': 7,
- 'ips': [
- '192.168.1.1',
- '192.168.1.2'
+ internal const string ENDPOINT = "whitelabel";
+
+ internal const string SINGLE_DOMAIN_JSON = @"{
+ ""id"": 1,
+ ""domain"": ""example.com"",
+ ""subdomain"": ""mail"",
+ ""username"": ""john@example.com"",
+ ""user_id"": 7,
+ ""ips"": [
+ ""192.168.1.1"",
+ ""192.168.1.2""
],
- 'custom_spf': true,
- 'default': true,
- 'legacy': false,
- 'automatic_security': true,
- 'valid': true,
- 'dns': {
- 'mail_cname': {
- 'host': 'mail.example.com',
- 'type': 'cname',
- 'data': 'u7.wl.sendgrid.net',
- 'valid': true
+ ""custom_spf"": true,
+ ""default"": true,
+ ""legacy"": false,
+ ""automatic_security"": true,
+ ""valid"": true,
+ ""dns"": {
+ ""mail_cname"": {
+ ""host"": ""mail.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""u7.wl.sendgrid.net"",
+ ""valid"": true
},
- 'spf': {
- 'host': 'example.com',
- 'type': 'txt',
- 'data': 'v=spf1 include:u7.wl.sendgrid.net -all',
- 'valid': true
+ ""spf"": {
+ ""host"": ""example.com"",
+ ""type"": ""txt"",
+ ""data"": ""v=spf1 include:u7.wl.sendgrid.net -all"",
+ ""valid"": true
},
- 'dkim1': {
- 'host': 's1._domainkey.example.com',
- 'type': 'cname',
- 'data': 's1._domainkey.u7.wl.sendgrid.net',
- 'valid': true
+ ""dkim1"": {
+ ""host"": ""s1._domainkey.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""s1._domainkey.u7.wl.sendgrid.net"",
+ ""valid"": true
},
- 'dkim2': {
- 'host': 's2._domainkey.example.com',
- 'type': 'cname',
- 'data': 's2._domainkey.u7.wl.sendgrid.net',
- 'valid': true
+ ""dkim2"": {
+ ""host"": ""s2._domainkey.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""s2._domainkey.u7.wl.sendgrid.net"",
+ ""valid"": true
}
}
}";
- private const string MULTIPLE_DOMAINS_JSON = @"[
+ internal const string MULTIPLE_DOMAINS_JSON = @"[
{
- 'id': 1,
- 'domain': 'example.com',
- 'subdomain': 'mail',
- 'username': 'john@example.com',
- 'user_id': 7,
- 'ips': [
- '192.168.1.1',
- '192.168.1.2'
+ ""id"": 1,
+ ""domain"": ""example.com"",
+ ""subdomain"": ""mail"",
+ ""username"": ""john@example.com"",
+ ""user_id"": 7,
+ ""ips"": [
+ ""192.168.1.1"",
+ ""192.168.1.2""
],
- 'custom_spf': true,
- 'default': true,
- 'legacy': false,
- 'automatic_security': true,
- 'valid': true,
- 'dns': {
- 'mail_cname': {
- 'host': 'mail.example.com',
- 'type': 'cname',
- 'data': 'u7.wl.sendgrid.net',
- 'valid': true
+ ""custom_spf"": true,
+ ""default"": true,
+ ""legacy"": false,
+ ""automatic_security"": true,
+ ""valid"": true,
+ ""dns"": {
+ ""mail_cname"": {
+ ""host"": ""mail.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""u7.wl.sendgrid.net"",
+ ""valid"": true
},
- 'spf': {
- 'host': 'example.com',
- 'type': 'txt',
- 'data': 'v=spf1 include:u7.wl.sendgrid.net -all',
- 'valid': true
+ ""spf"": {
+ ""host"": ""example.com"",
+ ""type"": ""txt"",
+ ""data"": ""v=spf1 include:u7.wl.sendgrid.net -all"",
+ ""valid"": true
},
- 'dkim1': {
- 'host': 's1._domainkey.example.com',
- 'type': 'cname',
- 'data': 's1._domainkey.u7.wl.sendgrid.net',
- 'valid': true
+ ""dkim1"": {
+ ""host"": ""s1._domainkey.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""s1._domainkey.u7.wl.sendgrid.net"",
+ ""valid"": true
},
- 'dkim2': {
- 'host': 's2._domainkey.example.com',
- 'type': 'cname',
- 'data': 's2._domainkey.u7.wl.sendgrid.net',
- 'valid': true
+ ""dkim2"": {
+ ""host"": ""s2._domainkey.example.com"",
+ ""type"": ""cname"",
+ ""data"": ""s2._domainkey.u7.wl.sendgrid.net"",
+ ""valid"": true
}
}
},
{
- 'id': 2,
- 'domain': 'example2.com',
- 'subdomain': 'news',
- 'username': 'jane@example2.com',
- 'user_id': 8,
- 'ips': [
+ ""id"": 2,
+ ""domain"": ""example2.com"",
+ ""subdomain"": ""news"",
+ ""username"": ""jane@example2.com"",
+ ""user_id"": 8,
+ ""ips"": [
],
- 'custom_spf': false,
- 'default': true,
- 'legacy': false,
- 'automatic_security': true,
- 'valid': false,
- 'dns': {
- 'mail_server': {
- 'host': 'news.example2.com',
- 'type': 'mx',
- 'data': 'sendgrid.net',
- 'valid': false
+ ""custom_spf"": false,
+ ""default"": true,
+ ""legacy"": false,
+ ""automatic_security"": true,
+ ""valid"": false,
+ ""dns"": {
+ ""mail_server"": {
+ ""host"": ""news.example2.com"",
+ ""type"": ""mx"",
+ ""data"": ""sendgrid.net"",
+ ""valid"": false
},
- 'subdomain_spf': {
- 'host': 'news.example2.com',
- 'type': 'txt',
- 'data': 'v=spf1 include:sendgrid.net ~all',
- 'valid': false
+ ""subdomain_spf"": {
+ ""host"": ""news.example2.com"",
+ ""type"": ""txt"",
+ ""data"": ""v=spf1 include:sendgrid.net ~all"",
+ ""valid"": false
},
- 'domain_spf': {
- 'host': 'example2.com',
- 'type': 'txt',
- 'data': 'v=spf1 include:news.example2.com -all',
- 'valid': false
+ ""domain_spf"": {
+ ""host"": ""example2.com"",
+ ""type"": ""txt"",
+ ""data"": ""v=spf1 include:news.example2.com -all"",
+ ""valid"": false
},
- 'dkim': {
- 'host': 's1._domainkey.example2.com',
- 'type': 'txt',
- 'data': 'k=rsa; t=s; p=publicKey',
- 'valid': false
+ ""dkim"": {
+ ""host"": ""s1._domainkey.example2.com"",
+ ""type"": ""txt"",
+ ""data"": ""k=rsa; t=s; p=publicKey"",
+ ""valid"": false
}
}
}
]";
- private const string SINGLE_IP_JSON = @"{
- 'id': 1,
- 'ip': '192.168.1.1',
- 'rdns': 'o1.email.example.com',
- 'users': [
+ internal const string SINGLE_IP_JSON = @"{
+ ""id"": 1,
+ ""ip"": ""192.168.1.1"",
+ ""rdns"": ""o1.email.example.com"",
+ ""users"": [
{
- 'username': 'john@example.com',
- 'user_id': 7
+ ""username"": ""john@example.com"",
+ ""user_id"": 7
},
{
- 'username': 'jane@example.com',
- 'user_id': 8
+ ""username"": ""jane@example.com"",
+ ""user_id"": 8
}
],
- 'subdomain': 'email',
- 'domain': 'example.com',
- 'valid': true,
- 'legacy': false,
- 'a_record': {
- 'valid': true,
- 'type': 'a',
- 'host': 'o1.email.example.com',
- 'data': '192.168.1.1'
+ ""subdomain"": ""email"",
+ ""domain"": ""example.com"",
+ ""valid"": true,
+ ""legacy"": false,
+ ""a_record"": {
+ ""valid"": true,
+ ""type"": ""a"",
+ ""host"": ""o1.email.example.com"",
+ ""data"": ""192.168.1.1""
}
}";
- private const string MULTIPLE_IPS_JSON = @"[
+ internal const string MULTIPLE_IPS_JSON = @"[
{
- 'id': 1,
- 'ip': '192.168.1.1',
- 'rdns': 'o1.email.example.com',
- 'users': [
+ ""id"": 1,
+ ""ip"": ""192.168.1.1"",
+ ""rdns"": ""o1.email.example.com"",
+ ""users"": [
{
- 'username': 'john@example.com',
- 'user_id': 7
+ ""username"": ""john@example.com"",
+ ""user_id"": 7
},
{
- 'username': 'jane@example.com',
- 'user_id': 8
+ ""username"": ""jane@example.com"",
+ ""user_id"": 8
}
],
- 'subdomain': 'email',
- 'domain': 'example.com',
- 'valid': true,
- 'legacy': false,
- 'a_record': {
- 'valid': true,
- 'type': 'a',
- 'host': 'o1.email.example.com',
- 'data': '192.168.1.1'
+ ""subdomain"": ""email"",
+ ""domain"": ""example.com"",
+ ""valid"": true,
+ ""legacy"": false,
+ ""a_record"": {
+ ""valid"": true,
+ ""type"": ""a"",
+ ""host"": ""o1.email.example.com"",
+ ""data"": ""192.168.1.1""
}
},
{
- 'id': 2,
- 'ip': '192.168.1.2',
- 'rdns': 'o2.email.example.com',
- 'users': [
+ ""id"": 2,
+ ""ip"": ""192.168.1.2"",
+ ""rdns"": ""o2.email.example.com"",
+ ""users"": [
{
- 'username': 'john@example.com',
- 'user_id': 7
+ ""username"": ""john@example.com"",
+ ""user_id"": 7
},
{
- 'username': 'jane@example2.com',
- 'user_id': 9
+ ""username"": ""jane@example2.com"",
+ ""user_id"": 9
}
],
- 'subdomain': 'email',
- 'domain': 'example.com',
- 'valid': true,
- 'legacy': false,
- 'a_record': {
- 'valid': true,
- 'type': 'a',
- 'host': 'o2.email.example.com',
- 'data': '192.168.1.2'
+ ""subdomain"": ""email"",
+ ""domain"": ""example.com"",
+ ""valid"": true,
+ ""legacy"": false,
+ ""a_record"": {
+ ""valid"": true,
+ ""type"": ""a"",
+ ""host"": ""o2.email.example.com"",
+ ""data"": ""192.168.1.2""
}
}
]";
- private const string SINGLE_LINK_JSON = @"{
- 'id': 1,
- 'domain': 'example.com',
- 'subdomain': 'mail',
- 'username': 'john@example.com',
- 'user_id': 7,
- 'default': true,
- 'valid': true,
- 'legacy': false,
- 'dns': {
- 'domain_cname': {
- 'valid': true,
- 'type': 'cname',
- 'host': 'mail.example.com',
- 'data': 'sendgrid.net'
+ internal const string SINGLE_LINK_JSON = @"{
+ ""id"": 1,
+ ""domain"": ""example.com"",
+ ""subdomain"": ""mail"",
+ ""username"": ""john@example.com"",
+ ""user_id"": 7,
+ ""default"": true,
+ ""valid"": true,
+ ""legacy"": false,
+ ""dns"": {
+ ""domain_cname"": {
+ ""valid"": true,
+ ""type"": ""cname"",
+ ""host"": ""mail.example.com"",
+ ""data"": ""sendgrid.net""
},
- 'owner_cname': {
- 'valid': true,
- 'type': 'cname',
- 'host': '7.example.com',
- 'data': 'sendgrid.net'
+ ""owner_cname"": {
+ ""valid"": true,
+ ""type"": ""cname"",
+ ""host"": ""7.example.com"",
+ ""data"": ""sendgrid.net""
}
}
}";
- private const string MULTIPLE_LINKS_JSON = @"[
+ internal const string MULTIPLE_LINKS_JSON = @"[
{
- 'id': 1,
- 'domain': 'example.com',
- 'subdomain': 'mail',
- 'username': 'john@example.com',
- 'user_id': 7,
- 'default': true,
- 'valid': true,
- 'legacy': false,
- 'dns': {
- 'domain_cname': {
- 'valid': true,
- 'type': 'cname',
- 'host': 'mail.example.com',
- 'data': 'sendgrid.net'
+ ""id"": 1,
+ ""domain"": ""example.com"",
+ ""subdomain"": ""mail"",
+ ""username"": ""john@example.com"",
+ ""user_id"": 7,
+ ""default"": true,
+ ""valid"": true,
+ ""legacy"": false,
+ ""dns"": {
+ ""domain_cname"": {
+ ""valid"": true,
+ ""type"": ""cname"",
+ ""host"": ""mail.example.com"",
+ ""data"": ""sendgrid.net""
},
- 'owner_cname': {
- 'valid': true,
- 'type': 'cname',
- 'host': '7.example.com',
- 'data': 'sendgrid.net'
+ ""owner_cname"": {
+ ""valid"": true,
+ ""type"": ""cname"",
+ ""host"": ""7.example.com"",
+ ""data"": ""sendgrid.net""
}
}
},
{
- 'id': 2,
- 'domain': 'example2.com',
- 'subdomain': 'news',
- 'username': 'john@example.com',
- 'user_id': 8,
- 'default': false,
- 'valid': false,
- 'legacy': false,
- 'dns': {
- 'domain_cname': {
- 'valid': true,
- 'type': 'cname',
- 'host': 'news.example2.com',
- 'data': 'sendgrid.net'
+ ""id"": 2,
+ ""domain"": ""example2.com"",
+ ""subdomain"": ""news"",
+ ""username"": ""john@example.com"",
+ ""user_id"": 8,
+ ""default"": false,
+ ""valid"": false,
+ ""legacy"": false,
+ ""dns"": {
+ ""domain_cname"": {
+ ""valid"": true,
+ ""type"": ""cname"",
+ ""host"": ""news.example2.com"",
+ ""data"": ""sendgrid.net""
},
- 'owner_cname': {
- 'valid': false,
- 'type': 'cname',
- 'host': '8.example2.com',
- 'data': 'sendgrid.net'
+ ""owner_cname"": {
+ ""valid"": false,
+ ""type"": ""cname"",
+ ""host"": ""8.example2.com"",
+ ""data"": ""sendgrid.net""
}
}
}
@@ -304,7 +304,7 @@ public void Parse_AuthenticatedDomain_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_DOMAIN_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_DOMAIN_JSON);
// Assert
result.ShouldNotBeNull();
@@ -521,24 +521,24 @@ public async Task ValidateDomainAsync()
var domainId = 1L;
var apiResponse = @"{
- 'id': 1,
- 'valid': true,
- 'validation_results': {
- 'mail_cname': {
- 'valid': false,
- 'reason': 'Expected your MX record to be \'mx.sendgrid.net\' but found \'example.com\'.'
+ ""id"": 1,
+ ""valid"": true,
+ ""validation_results"": {
+ ""mail_cname"": {
+ ""valid"": false,
+ ""reason"": ""Expected your MX record to be \""mx.sendgrid.net\"" but found \""example.com\"".""
},
- 'dkim1': {
- 'valid': true,
- 'reason': null
+ ""dkim1"": {
+ ""valid"": true,
+ ""reason"": null
},
- 'dkim2': {
- 'valid': true,
- 'reason': null
+ ""dkim2"": {
+ ""valid"": true,
+ ""reason"": null
},
- 'spf': {
- 'valid': true,
- 'reason': null
+ ""spf"": {
+ ""valid"": true,
+ ""reason"": null
}
}
}";
@@ -563,7 +563,7 @@ public async Task ValidateDomainAsync()
result.ValidationResults.Dkim2.IsValid.ShouldBe(true);
result.ValidationResults.Dkim2.Reason.ShouldBeNull();
result.ValidationResults.Mail.IsValid.ShouldBe(false);
- result.ValidationResults.Mail.Reason.ShouldBe("Expected your MX record to be \'mx.sendgrid.net\' but found \'example.com\'.");
+ result.ValidationResults.Mail.Reason.ShouldBe("Expected your MX record to be \"mx.sendgrid.net\" but found \"example.com\".");
result.ValidationResults.Spf.IsValid.ShouldBe(true);
result.ValidationResults.Spf.Reason.ShouldBeNull();
}
@@ -722,12 +722,12 @@ public async Task ValidateReverseDnsAsync()
var id = 1L;
var apiResponse = @"{
- 'id': 1,
- 'valid': true,
- 'validation_results': {
- 'a_record': {
- 'valid': true,
- 'reason': null
+ ""id"": 1,
+ ""valid"": true,
+ ""validation_results"": {
+ ""a_record"": {
+ ""valid"": true,
+ ""reason"": null
}
}
}";
@@ -865,16 +865,16 @@ public async Task ValidateLinkAsync()
var linkId = 1L;
var apiResponse = @"{
- 'id': 1,
- 'valid': true,
- 'validation_results': {
- 'domain_cname': {
- 'valid': false,
- 'reason': 'Expected CNAME to match \'sendgrid.net.\' but found \'example.com.\'.'
+ ""id"": 1,
+ ""valid"": true,
+ ""validation_results"": {
+ ""domain_cname"": {
+ ""valid"": false,
+ ""reason"": ""Expected CNAME to match \""sendgrid.net.\"" but found \""example.com.\"".""
},
- 'owner_cname': {
- 'valid': true,
- 'reason': null
+ ""owner_cname"": {
+ ""valid"": true,
+ ""reason"": null
}
}
}";
@@ -895,7 +895,7 @@ public async Task ValidateLinkAsync()
result.LinkId.ShouldBe(1);
result.IsValid.ShouldBe(true);
result.ValidationResults.Domain.IsValid.ShouldBe(false);
- result.ValidationResults.Domain.Reason.ShouldBe("Expected CNAME to match \'sendgrid.net.\' but found \'example.com.\'.");
+ result.ValidationResults.Domain.Reason.ShouldBe("Expected CNAME to match \"sendgrid.net.\" but found \"example.com.\".");
result.ValidationResults.Owner.IsValid.ShouldBe(true);
result.ValidationResults.Owner.Reason.ShouldBeNull();
}
diff --git a/Source/StrongGrid.UnitTests/Resources/SettingsTests.cs b/Source/StrongGrid.UnitTests/Resources/SettingsTests.cs
index 003aa6f5..2091c1f8 100644
--- a/Source/StrongGrid.UnitTests/Resources/SettingsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/SettingsTests.cs
@@ -1,9 +1,9 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -14,11 +14,11 @@ public class SettingsTests
{
#region FIELDS
- private const string SINGLE_GLOBAL_SETTING_JSON = @"{
- 'name': 'bcc',
- 'title': 'BCC',
- 'description': 'lorem ipsum... .',
- 'enabled': true
+ internal const string SINGLE_GLOBAL_SETTING_JSON = @"{
+ ""name"": ""bcc"",
+ ""title"": ""BCC"",
+ ""description"": ""lorem ipsum... ."",
+ ""enabled"": true
}";
#endregion
@@ -29,7 +29,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_GLOBAL_SETTING_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_GLOBAL_SETTING_JSON);
// Assert
result.ShouldNotBeNull();
@@ -44,8 +44,8 @@ public async Task GetEnforcedTlsSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'require_tls': true,
- 'require_valid_cert': false
+ ""require_tls"": true,
+ ""require_valid_cert"": false
}";
var mockHttp = new MockHttpMessageHandler();
@@ -73,8 +73,8 @@ public async Task UpdateEnforcedTlsSettingsAsync()
var requireValidCert = true;
var apiResponse = @"{
- 'require_tls': true,
- 'require_valid_cert': true
+ ""require_tls"": true,
+ ""require_valid_cert"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -102,12 +102,12 @@ public async Task GetAllMailSettingsAsync()
var offset = 3;
var apiResponse = @"{
- 'result': [
+ ""result"": [
{
- 'name': 'bcc',
- 'title': 'BCC',
- 'description': 'lorem ipsum... .',
- 'enabled': true
+ ""name"": ""bcc"",
+ ""title"": ""BCC"",
+ ""description"": ""lorem ipsum... ."",
+ ""enabled"": true
}
]
}";
@@ -137,12 +137,12 @@ public async Task GetAllPartnerSettingsAsync()
var offset = 3;
var apiResponse = @"{
- 'result': [
+ ""result"": [
{
- 'name': 'new_relic',
- 'title': 'New Relic',
- 'description': 'lorem ipsum... .',
- 'enabled': true
+ ""name"": ""new_relic"",
+ ""title"": ""New Relic"",
+ ""description"": ""lorem ipsum... ."",
+ ""enabled"": true
}
]
}";
@@ -169,8 +169,8 @@ public async Task GetNewRelicSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'license_key': 'key'
+ ""enabled"": true,
+ ""license_key"": ""key""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -198,8 +198,8 @@ public async Task UpdateNewRelicSettings()
var licenseKey = "abc123";
var apiResponse = @"{
- 'enabled': true,
- 'license_key': 'abc123'
+ ""enabled"": true,
+ ""license_key"": ""abc123""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -227,12 +227,12 @@ public async Task GetAllTrackingSettingsAsync()
var offset = 3;
var apiResponse = @"{
- 'result': [
+ ""result"": [
{
- 'name': 'open',
- 'title': 'Open Tracking',
- 'description': 'lorem ipsum... .',
- 'enabled': true
+ ""name"": ""open"",
+ ""title"": ""Open Tracking"",
+ ""description"": ""lorem ipsum... ."",
+ ""enabled"": true
}
]
}";
@@ -259,8 +259,8 @@ public async Task GetClickTrackingSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enable_text': true,
- 'enabled': false,
+ ""enable_text"": true,
+ ""enabled"": false
}";
var mockHttp = new MockHttpMessageHandler();
@@ -287,8 +287,8 @@ public async Task UpdateClickTrackingSettingsAsync()
var enabledInHtml = true;
var apiResponse = @"{
- 'enable_text': false,
- 'enabled': true,
+ ""enable_text"": false,
+ ""enabled"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -312,12 +312,12 @@ public async Task GetGoogleAnalyticsGlobalSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'utm_source': 'sendgrid.com',
- 'utm_medium': 'email',
- 'utm_term': '',
- 'utm_content': '',
- 'utm_campaign': 'website'
+ ""enabled"": true,
+ ""utm_source"": ""sendgrid.com"",
+ ""utm_medium"": ""email"",
+ ""utm_term"": """",
+ ""utm_content"": """",
+ ""utm_campaign"": ""website""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -353,12 +353,12 @@ public async Task UpdateGoogleAnalyticsGlobalAsync()
var utmCampaign = "website";
var apiResponse = @"{
- 'enabled': true,
- 'utm_source': 'sendgrid.com',
- 'utm_medium': 'email',
- 'utm_term': '',
- 'utm_content': '',
- 'utm_campaign': 'website'
+ ""enabled"": true,
+ ""utm_source"": ""sendgrid.com"",
+ ""utm_medium"": ""email"",
+ ""utm_term"": """",
+ ""utm_content"": """",
+ ""utm_campaign"": ""website""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -381,7 +381,7 @@ public async Task GetOpenTrackingSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
+ ""enabled"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -406,7 +406,7 @@ public async Task UpdateOpenTrackingSettingsAsync()
var enabled = true;
var apiResponse = @"{
- 'enabled': true,
+ ""enabled"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -429,12 +429,12 @@ public async Task GetSubscriptionTrackingSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'landing': 'landing page html',
- 'url': 'url',
- 'replace': 'replacement tag',
- 'html_content': 'html content',
- 'plain_content': 'text content'
+ ""enabled"": true,
+ ""landing"": ""landing page html"",
+ ""url"": ""url"",
+ ""replace"": ""replacement tag"",
+ ""html_content"": ""html content"",
+ ""plain_content"": ""text content""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -470,12 +470,12 @@ public async Task UpdateSubscriptionTrackingSettingsAsync()
var textContent = "text content";
var apiResponse = @"{
- 'enabled': true,
- 'landing': 'landing page html',
- 'url': 'url',
- 'replace': 'replacement tag',
- 'html_content': 'html content',
- 'plain_content': 'text content'
+ ""enabled"": true,
+ ""landing"": ""landing page html"",
+ ""url"": ""url"",
+ ""replace"": ""replacement tag"",
+ ""html_content"": ""html content"",
+ ""plain_content"": ""text content""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -493,68 +493,15 @@ public async Task UpdateSubscriptionTrackingSettingsAsync()
result.ShouldNotBeNull();
}
- [Fact]
- public async Task GetBccMailSettingsAsync()
- {
- // Arrange
- var apiResponse = @"{
- 'enabled': true,
- 'email': 'email@example.com'
- }";
-
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri("mail_settings/bcc")).Respond("application/json", apiResponse);
-
- var client = Utils.GetFluentClient(mockHttp);
- var settings = new Settings(client);
-
- // Act
- var result = await settings.GetBccMailSettingsAsync(null, CancellationToken.None).ConfigureAwait(false);
-
- // Assert
- mockHttp.VerifyNoOutstandingExpectation();
- mockHttp.VerifyNoOutstandingRequest();
- result.ShouldNotBeNull();
- result.Enabled.ShouldBe(true);
- result.EmailAddress.ShouldBe("email@example.com");
- }
-
- [Fact]
- public async Task UpdateBccMailSettingsAsync()
- {
- // Arrange
- var enabled = true;
- var email = "email@example.com";
-
- var apiResponse = @"{
- 'enabled': true,
- 'email': 'email@example.com'
- }";
-
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.Expect(new HttpMethod("PATCH"), Utils.GetSendGridApiUri("mail_settings/bcc")).Respond("application/json", apiResponse);
-
- var client = Utils.GetFluentClient(mockHttp);
- var settings = new Settings(client);
-
- // Act
- var result = await settings.UpdateBccMailSettingsAsync(enabled, email, null, CancellationToken.None).ConfigureAwait(false);
-
- // Assert
- mockHttp.VerifyNoOutstandingExpectation();
- mockHttp.VerifyNoOutstandingRequest();
- result.ShouldNotBeNull();
- }
-
[Fact]
public async Task GetAddressWhitelistMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'list': [
- 'email1@example.com',
- 'example.com'
+ ""enabled"": true,
+ ""list"": [
+ ""email1@example.com"",
+ ""example.com""
]
}";
@@ -586,10 +533,10 @@ public async Task UpdateAddressWhitelistMailSettingsAsync()
var emailAddresses = new[] { "email@example.com", "example.com" };
var apiResponse = @"{
- 'enabled': true,
- 'list': [
- 'email1@example.com',
- 'example.com'
+ ""enabled"": true,
+ ""list"": [
+ ""email1@example.com"",
+ ""example.com""
]
}";
@@ -613,9 +560,9 @@ public async Task GetFooterMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'html_content': '... 123 ...',
- 'plain_content': '... abc ...'
+ ""enabled"": true,
+ ""html_content"": ""... 123 ..."",
+ ""plain_content"": ""... abc ...""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -645,9 +592,9 @@ public async Task UpdateFooterMailSettingsAsync()
var textContent = "text content";
var apiResponse = @"{
- 'enabled': true,
- 'html_content': 'html content',
- 'plain_content': 'text content'
+ ""enabled"": true,
+ ""html_content"": ""html content"",
+ ""plain_content"": ""text content""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -670,8 +617,8 @@ public async Task GetForwardSpamMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'email': 'email address'
+ ""enabled"": true,
+ ""email"": ""email address""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -699,8 +646,8 @@ public async Task UpdateForwardSpamMailSettingsAsync()
var email = "email address";
var apiResponse = @"{
- 'enabled': true,
- 'email': 'email address'
+ ""enabled"": true,
+ ""email"": ""email address""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -723,7 +670,7 @@ public async Task GetPlainContentMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
+ ""enabled"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -748,7 +695,7 @@ public async Task UpdatPlainContentMailSettingsAsync()
var enabled = true;
var apiResponse = @"{
- 'enabled': true,
+ ""enabled"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -766,70 +713,13 @@ public async Task UpdatPlainContentMailSettingsAsync()
result.ShouldBeTrue();
}
- [Fact]
- public async Task GetSpamCheckMailSettingsAsync()
- {
- // Arrange
- var apiResponse = @"{
- 'enabled': true,
- 'url': 'url',
- 'max_score': 5
- }";
-
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.Expect(HttpMethod.Get, Utils.GetSendGridApiUri("mail_settings/spam_check")).Respond("application/json", apiResponse);
-
- var client = Utils.GetFluentClient(mockHttp);
- var settings = new Settings(client);
-
- // Act
- var result = await settings.GetSpamCheckMailSettingsAsync(null, CancellationToken.None).ConfigureAwait(false);
-
- // Assert
- mockHttp.VerifyNoOutstandingExpectation();
- mockHttp.VerifyNoOutstandingRequest();
- result.ShouldNotBeNull();
- result.Enabled.ShouldBe(true);
- result.Url.ShouldBe("url");
- result.Threshold.ShouldBe(5);
- }
-
- [Fact]
- public async Task UpdateSpamCheckMailSettingsAsync()
- {
- // Arrange
- var enabled = true;
- var postToUrl = "url";
- var threshold = 5;
-
- var apiResponse = @"{
- 'enabled': true,
- 'url': 'url',
- 'max_score': 5
- }";
-
- var mockHttp = new MockHttpMessageHandler();
- mockHttp.Expect(new HttpMethod("PATCH"), Utils.GetSendGridApiUri("mail_settings/spam_check")).Respond("application/json", apiResponse);
-
- var client = Utils.GetFluentClient(mockHttp);
- var settings = new Settings(client);
-
- // Act
- var result = await settings.UpdateSpamCheckMailSettingsAsync(enabled, postToUrl, threshold, null, CancellationToken.None).ConfigureAwait(false);
-
- // Assert
- mockHttp.VerifyNoOutstandingExpectation();
- mockHttp.VerifyNoOutstandingRequest();
- result.ShouldNotBeNull();
- }
-
[Fact]
public async Task GetTemplateMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'html_content': ' <% body %> '
+ ""enabled"": true,
+ ""html_content"": "" <% body %> ""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -854,11 +744,11 @@ public async Task UpdateTemplateMailSettingsAsync()
{
// Arrange
var enabled = true;
- var htmlContent = "' <% body %> ";
+ var htmlContent = " <% body %> ";
var apiResponse = @"{
- 'enabled': true,
- 'html_content': ' <% body %> '
+ ""enabled"": true,
+ ""html_content"": "" <% body %> ""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -881,9 +771,9 @@ public async Task GetBouncePurgeMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'hard_bounces': 5,
- 'soft_bounces': 5
+ ""enabled"": true,
+ ""hard_bounces"": 5,
+ ""soft_bounces"": 5
}";
var mockHttp = new MockHttpMessageHandler();
@@ -913,9 +803,9 @@ public async Task UpdateBouncePurgeMailSettingsAsync()
var softBounces = 5;
var apiResponse = @"{
- 'enabled': true,
- 'hard_bounces': 5,
- 'soft_bounces': 5
+ ""enabled"": true,
+ ""hard_bounces"": 5,
+ ""soft_bounces"": 5
}";
var mockHttp = new MockHttpMessageHandler();
@@ -938,8 +828,8 @@ public async Task GetForwardBounceMailSettingsAsync()
{
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'email': 'email address'
+ ""enabled"": true,
+ ""email"": ""email address""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -967,8 +857,8 @@ public async Task UpdatForwardBounceMailSettingsAsync()
var email = "email address";
var apiResponse = @"{
- 'enabled': true,
- 'email': 'email address'
+ ""enabled"": true,
+ ""email"": ""email address""
}";
var mockHttp = new MockHttpMessageHandler();
diff --git a/Source/StrongGrid.UnitTests/Resources/SpamReportsTests.cs b/Source/StrongGrid.UnitTests/Resources/SpamReportsTests.cs
index 4c112afe..9b34d7e5 100644
--- a/Source/StrongGrid.UnitTests/Resources/SpamReportsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/SpamReportsTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,25 +16,25 @@ public class SpamReportsTests
{
#region FIELDS
- private const string ENDPOINT = "suppression/spam_reports";
+ internal const string ENDPOINT = "suppression/spam_reports";
- private const string SINGLE_SPAM_REPORT_JSON = @"[
+ internal const string SINGLE_SPAM_REPORT_JSON = @"[
{
- 'created': 1454433146,
- 'email': 'test1@example.com',
- 'ip': '10.89.32.5'
+ ""created"": 1454433146,
+ ""email"": ""test1@example.com"",
+ ""ip"": ""10.89.32.5""
}
]";
- private const string MULTIPLE_SPAM_REPORTS_JSON = @"[
+ internal const string MULTIPLE_SPAM_REPORTS_JSON = @"[
{
- 'created': 1443651141,
- 'email': 'user1@example.com',
- 'ip': '10.63.202.100'
+ ""created"": 1443651141,
+ ""email"": ""user1@example.com"",
+ ""ip"": ""10.63.202.100""
},
{
- 'created': 1443651154,
- 'email': 'user2@example.com',
- 'ip': '10.63.202.100'
+ ""created"": 1443651154,
+ ""email"": ""user2@example.com"",
+ ""ip"": ""10.63.202.100""
}
]";
@@ -46,7 +46,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SPAM_REPORT_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SPAM_REPORT_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/StatisticsTests.cs b/Source/StrongGrid.UnitTests/Resources/StatisticsTests.cs
index d7cc6874..e1823777 100644
--- a/Source/StrongGrid.UnitTests/Resources/StatisticsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/StatisticsTests.cs
@@ -19,53 +19,54 @@ public async Task GetGlobalStatsAsync()
// Arrange
var startDate = new DateTime(2015, 1, 1);
var endDate = new DateTime(2015, 1, 2);
+
var apiResponse = @"[
{
- 'date': '2015-01-01',
- 'stats': [
+ ""date"": ""2015-01-01"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 1,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 1,
- 'delivered': 1,
- 'invalid_emails': 1,
- 'opens': 1,
- 'processed': 2,
- 'requests': 3,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 1,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 1,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 1,
+ ""delivered"": 1,
+ ""invalid_emails"": 1,
+ ""opens"": 1,
+ ""processed"": 2,
+ ""requests"": 3,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 1,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
}
}
]
},
{
- 'date': '2015-01-02',
- 'stats': [
+ ""date"": ""2015-01-02"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 0,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 0,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
}
}
]
@@ -100,100 +101,100 @@ public async Task GetCategoryStatsAsync()
var apiResponse = @"[
{
- 'date': '2015 - 01 - 01',
- 'stats': [
+ ""date"": ""2015-01-01"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 0,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 0,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'cat1',
- 'type': 'category'
+ ""name"": ""cat1"",
+ ""type"": ""category""
},
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 0,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 0,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'cat2',
- 'type': 'category'
+ ""name"": ""cat2"",
+ ""type"": ""category""
}
]
},
{
- 'date': '2015-01-02',
- 'stats': [
+ ""date"": ""2015-01-02"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 10,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 10,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 10,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 10,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'cat1',
- 'type': 'category'
+ ""name"": ""cat1"",
+ ""type"": ""category""
},
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 6,
- 'deferred': 0,
- 'delivered': 5,
- 'invalid_emails': 0,
- 'opens': 6,
- 'processed': 0,
- 'requests': 5,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 5,
- 'unique_opens': 5,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 6
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 6,
+ ""deferred"": 0,
+ ""delivered"": 5,
+ ""invalid_emails"": 0,
+ ""opens"": 6,
+ ""processed"": 0,
+ ""requests"": 5,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 5,
+ ""unique_opens"": 5,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 6
},
- 'name': 'cat2',
- 'type': 'category'
+ ""name"": ""cat2"",
+ ""type"": ""category""
}
]
}
@@ -225,102 +226,103 @@ public async Task GetSubusersStatsAsync()
var subusers = new[] { "user1", "user2" };
var startDate = new DateTime(2015, 1, 1);
var endDate = new DateTime(2015, 1, 2);
+
var apiResponse = @"[
{
- 'date': '2015-01-01',
- 'stats': [
+ ""date"": ""2015-01-01"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 0,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 0,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'user1',
- 'type': 'subuser'
+ ""name"": ""user1"",
+ ""type"": ""subuser""
},
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 0,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 0,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'user2',
- 'type': 'subuser'
+ ""name"": ""user2"",
+ ""type"": ""subuser""
}
]
},
{
- 'date': '2015-01-02',
- 'stats': [
+ ""date"": ""2015-01-02"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 10,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'invalid_emails': 0,
- 'opens': 0,
- 'processed': 0,
- 'requests': 10,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 0
+ ""metrics"": {
+ ""blocks"": 10,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""invalid_emails"": 0,
+ ""opens"": 0,
+ ""processed"": 0,
+ ""requests"": 10,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 0
},
- 'name': 'user1',
- 'type': 'subuser'
+ ""name"": ""user1"",
+ ""type"": ""subuser""
},
{
- 'metrics': {
- 'blocks': 0,
- 'bounce_drops': 0,
- 'bounces': 0,
- 'clicks': 6,
- 'deferred': 0,
- 'delivered': 5,
- 'invalid_emails': 0,
- 'opens': 6,
- 'processed': 0,
- 'requests': 5,
- 'spam_report_drops': 0,
- 'spam_reports': 0,
- 'unique_clicks': 5,
- 'unique_opens': 5,
- 'unsubscribe_drops': 0,
- 'unsubscribes': 6
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounce_drops"": 0,
+ ""bounces"": 0,
+ ""clicks"": 6,
+ ""deferred"": 0,
+ ""delivered"": 5,
+ ""invalid_emails"": 0,
+ ""opens"": 6,
+ ""processed"": 0,
+ ""requests"": 5,
+ ""spam_report_drops"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 5,
+ ""unique_opens"": 5,
+ ""unsubscribe_drops"": 0,
+ ""unsubscribes"": 6
},
- 'name': 'user2',
- 'type': 'subuser'
+ ""name"": ""user2"",
+ ""type"": ""subuser""
}
]
}
@@ -352,34 +354,35 @@ public async Task GetCountryStatsAsync()
var country = "US";
var startDate = new DateTime(2014, 10, 1);
var endDate = new DateTime(2014, 10, 2);
+
var apiResponse = @"[
{
- 'date': '2014-10-01',
- 'stats': [
+ ""date"": ""2014-10-01"",
+ ""stats"": [
{
- 'metrics': {
- 'clicks': 0,
- 'opens': 1,
- 'unique_clicks': 0,
- 'unique_opens': 1
+ ""metrics"": {
+ ""clicks"": 0,
+ ""opens"": 1,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 1
},
- 'name': 'us',
- 'type': 'country'
+ ""name"": ""us"",
+ ""type"": ""country""
}
]
},
{
- 'date': '2014-10-02',
- 'stats': [
+ ""date"": ""2014-10-02"",
+ ""stats"": [
{
- 'metrics': {
- 'clicks': 0,
- 'opens': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0
+ ""metrics"": {
+ ""clicks"": 0,
+ ""opens"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0
},
- 'name': 'us',
- 'type': 'country'
+ ""name"": ""us"",
+ ""type"": ""country""
}
]
}
@@ -410,30 +413,31 @@ public async Task GetDeviceTypesStatsAsync()
// Arrange
var startDate = new DateTime(2014, 10, 1);
var endDate = new DateTime(2014, 10, 2);
+
var apiResponse = @"[
{
- 'date': '2014-10-01',
- 'stats': [
+ ""date"": ""2014-10-01"",
+ ""stats"": [
{
- 'metrics': {
- 'opens': 1,
- 'unique_opens': 1
+ ""metrics"": {
+ ""opens"": 1,
+ ""unique_opens"": 1
},
- 'name': 'Webmail',
- 'type': 'device'
+ ""name"": ""Webmail"",
+ ""type"": ""device""
}
]
},
{
- 'date': '2014-10-02',
- 'stats': [
+ ""date"": ""2014-10-02"",
+ ""stats"": [
{
- 'metrics': {
- 'opens': 0,
- 'unique_opens': 0
+ ""metrics"": {
+ ""opens"": 0,
+ ""unique_opens"": 0
},
- 'name': 'Webmail',
- 'type': 'device'
+ ""name"": ""Webmail"",
+ ""type"": ""device""
}
]
}
@@ -465,30 +469,31 @@ public async Task GetClientTypesStatsAsync()
// Arrange
var startDate = new DateTime(2014, 10, 1);
var endDate = new DateTime(2014, 10, 2);
+
var apiResponse = @"[
{
- 'date': '2014-10-01',
- 'stats': [
+ ""date"": ""2014-10-01"",
+ ""stats"": [
{
- 'metrics': {
- 'opens': 1,
- 'unique_opens': 1
+ ""metrics"": {
+ ""opens"": 1,
+ ""unique_opens"": 1
},
- 'name': 'Gmail',
- 'type': 'client'
+ ""name"": ""Gmail"",
+ ""type"": ""client""
}
]
},
{
- 'date': '2014-10-02',
- 'stats': [
+ ""date"": ""2014-10-02"",
+ ""stats"": [
{
- 'metrics': {
- 'opens': 0,
- 'unique_opens': 0
+ ""metrics"": {
+ ""opens"": 0,
+ ""unique_opens"": 0
},
- 'name': 'Gmail',
- 'type': 'client'
+ ""name"": ""Gmail"",
+ ""type"": ""client""
}
]
}
@@ -521,46 +526,47 @@ public async Task GetInboxProvidersStatsAsync()
var providers = new[] { "Gmail", "Hotmail" };
var startDate = new DateTime(2014, 10, 1);
var endDate = new DateTime(2014, 10, 2);
+
var apiResponse = @"[
{
- 'date': '2014-10-01',
- 'stats': [
+ ""date"": ""2014-10-01"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 1,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 1,
- 'delivered': 1,
- 'drops': 0,
- 'opens': 1,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 1
+ ""metrics"": {
+ ""blocks"": 1,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 1,
+ ""delivered"": 1,
+ ""drops"": 0,
+ ""opens"": 1,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 1
},
- 'name': 'Gmail',
- 'type': 'esp'
+ ""name"": ""Gmail"",
+ ""type"": ""esp""
}
]
},
{
- 'date': '2014-10-02',
- 'stats': [
+ ""date"": ""2014-10-02"",
+ ""stats"": [
{
- 'metrics': {
- 'blocks': 0,
- 'bounces': 0,
- 'clicks': 0,
- 'deferred': 0,
- 'delivered': 0,
- 'drops': 0,
- 'opens': 0,
- 'spam_reports': 0,
- 'unique_clicks': 0,
- 'unique_opens': 0
+ ""metrics"": {
+ ""blocks"": 0,
+ ""bounces"": 0,
+ ""clicks"": 0,
+ ""deferred"": 0,
+ ""delivered"": 0,
+ ""drops"": 0,
+ ""opens"": 0,
+ ""spam_reports"": 0,
+ ""unique_clicks"": 0,
+ ""unique_opens"": 0
},
- 'name': 'Gmail',
- 'type': 'esp'
+ ""name"": ""Gmail"",
+ ""type"": ""esp""
}
]
}
@@ -592,46 +598,47 @@ public async Task GetBrowsersStatsAsync()
var browsers = new[] { "Chrome", "Firefox" };
var startDate = new DateTime(2014, 10, 1);
var endDate = new DateTime(2014, 10, 2);
+
var apiResponse = @"[
{
- 'date': '2014-10-01',
- 'stats': [
+ ""date"": ""2014-10-01"",
+ ""stats"": [
{
- 'metrics': {
- 'clicks': 0,
- 'unique_clicks': 0
+ ""metrics"": {
+ ""clicks"": 0,
+ ""unique_clicks"": 0
},
- 'name': 'Chrome',
- 'type': 'browser'
+ ""name"": ""Chrome"",
+ ""type"": ""browser""
},
{
- 'metrics': {
- 'clicks': 1,
- 'unique_clicks': 1
+ ""metrics"": {
+ ""clicks"": 1,
+ ""unique_clicks"": 1
},
- 'name': 'Firefox',
- 'type': 'browser'
+ ""name"": ""Firefox"",
+ ""type"": ""browser""
}
]
},
{
- 'date': '2014-10-02',
- 'stats': [
+ ""date"": ""2014-10-02"",
+ ""stats"": [
{
- 'metrics': {
- 'clicks': 0,
- 'unique_clicks': 0
+ ""metrics"": {
+ ""clicks"": 0,
+ ""unique_clicks"": 0
},
- 'name': 'Chrome',
- 'type': 'browser'
+ ""name"": ""Chrome"",
+ ""type"": ""browser""
},
{
- 'metrics': {
- 'clicks': 1,
- 'unique_clicks': 1
+ ""metrics"": {
+ ""clicks"": 1,
+ ""unique_clicks"": 1
},
- 'name': 'Firefox',
- 'type': 'browser'
+ ""name"": ""Firefox"",
+ ""type"": ""browser""
}
]
}
diff --git a/Source/StrongGrid.UnitTests/Resources/SubusersTests.cs b/Source/StrongGrid.UnitTests/Resources/SubusersTests.cs
index 1b009b49..80a3c701 100644
--- a/Source/StrongGrid.UnitTests/Resources/SubusersTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/SubusersTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -7,6 +6,7 @@
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -17,60 +17,60 @@ public class SubusersTests
{
#region FIELDS
- private const string ENDPOINT = "subusers";
+ internal const string ENDPOINT = "subusers";
- private const string SINGLE_SUBUSER_JSON = @"{
- 'id': 1,
- 'username': 'TestUser',
- 'email': 'Test@example.com',
- 'disabled': true
+ internal const string SINGLE_SUBUSER_JSON = @"{
+ ""id"": 1,
+ ""username"": ""TestUser"",
+ ""email"": ""Test@example.com"",
+ ""disabled"": true
}";
- private const string SINGLE_SUBUSER_CREATED_JSON = @"{
- 'id': 1,
- 'username': 'TestUser',
- 'password': 'somepass',
- 'email': 'Test@example.com',
- 'ips': [
- '1.1.1.1',
- '2.2.2.2'
+ internal const string SINGLE_SUBUSER_CREATED_JSON = @"{
+ ""id"": 1,
+ ""username"": ""TestUser"",
+ ""password"": ""somepass"",
+ ""email"": ""Test@example.com"",
+ ""ips"": [
+ ""1.1.1.1"",
+ ""2.2.2.2""
]
}";
- private const string MULTIPLE_SUBUSER_JSON = @"[
+ internal const string MULTIPLE_SUBUSER_JSON = @"[
{
- 'id': 1,
- 'username': 'TestUser',
- 'email': 'Test@example.com',
- 'disabled': false
+ ""id"": 1,
+ ""username"": ""TestUser"",
+ ""email"": ""Test@example.com"",
+ ""disabled"": false
},
{
- 'id': 2,
- 'username': 'John',
- 'email': 'John@example.com',
- 'disabled': true
+ ""id"": 2,
+ ""username"": ""John"",
+ ""email"": ""John@example.com"",
+ ""disabled"": true
}
]";
- private const string MULTIPLE_IPS_JSON = @"[
- '1.1.1.1',
- '2.2.2.2'
+ internal const string MULTIPLE_IPS_JSON = @"[
+ ""1.1.1.1"",
+ ""2.2.2.2""
]";
- private const string MONITOR_SETTINGS_JSON = @"{
- 'email': 'test@example.com',
- 'frequency': 500
+ internal const string MONITOR_SETTINGS_JSON = @"{
+ ""email"": ""test@example.com"",
+ ""frequency"": 500
}";
- private const string SINGLE_REPUTATION_JSON = @"[
+ internal const string SINGLE_REPUTATION_JSON = @"[
{
- 'username': 'example_subuser',
- 'reputation': 99
+ ""username"": ""example_subuser"",
+ ""reputation"": 99
}
]";
- private const string MULTIPLE_REPUTATIONS_JSON = @"[
+ internal const string MULTIPLE_REPUTATIONS_JSON = @"[
{
- 'username': 'example_subuser',
- 'reputation': 99
+ ""username"": ""example_subuser"",
+ ""reputation"": 99
},
{
- 'username': 'example_subuser2',
- 'reputation': 95.2
+ ""username"": ""example_subuser2"",
+ ""reputation"": 95.2
}
]";
@@ -82,7 +82,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SUBUSER_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SUBUSER_JSON);
// Assert
result.ShouldNotBeNull();
@@ -98,7 +98,7 @@ public void Parse_json_created()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SUBUSER_CREATED_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SUBUSER_CREATED_JSON);
// Assert
result.ShouldNotBeNull();
@@ -116,7 +116,7 @@ public void Parse_json_MonitorSettings()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(MONITOR_SETTINGS_JSON);
+ var result = JsonSerializer.Deserialize(MONITOR_SETTINGS_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/SuppresionsTests.cs b/Source/StrongGrid.UnitTests/Resources/SuppresionsTests.cs
index e6ef1289..1e7a7897 100644
--- a/Source/StrongGrid.UnitTests/Resources/SuppresionsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/SuppresionsTests.cs
@@ -13,50 +13,50 @@ public class SuppresionsTests
{
#region FIELDS
- private const string ENDPOINT = "asm";
- private const string ALL_GROUPS_JSON = @"{
- 'suppressions': [
+ internal const string ENDPOINT = "asm";
+ internal const string ALL_GROUPS_JSON = @"{
+ ""suppressions"": [
{
- 'description': 'Optional description.',
- 'id': 1,
- 'is_default': true,
- 'name': 'Weekly News',
- 'suppressed': true
+ ""description"": ""Optional description."",
+ ""id"": 1,
+ ""is_default"": true,
+ ""name"": ""Weekly News"",
+ ""suppressed"": true
},
{
- 'description': 'Some daily news.',
- 'id': 2,
- 'is_default': true,
- 'name': 'Daily News',
- 'suppressed': true
+ ""description"": ""Some daily news."",
+ ""id"": 2,
+ ""is_default"": true,
+ ""name"": ""Daily News"",
+ ""suppressed"": true
},
{
- 'description': 'An old group.',
- 'id': 2,
- 'is_default': false,
- 'name': 'Old News',
- 'suppressed': false
+ ""description"": ""An old group."",
+ ""id"": 2,
+ ""is_default"": false,
+ ""name"": ""Old News"",
+ ""suppressed"": false
}
]
}";
- private const string ALL_SUPPRESSIONS_JSON = @"[
+ internal const string ALL_SUPPRESSIONS_JSON = @"[
{
- 'email':'test @example.com',
- 'group_id': 1,
- 'group_name': 'Weekly News',
- 'created_at': 1410986704
+ ""email"":""test @example.com"",
+ ""group_id"": 1,
+ ""group_name"": ""Weekly News"",
+ ""created_at"": 1410986704
},
{
- 'email':'test1@example.com',
- 'group_id': 2,
- 'group_name': 'Daily News',
- 'created_at': 1411493671
+ ""email"":""test1@example.com"",
+ ""group_id"": 2,
+ ""group_name"": ""Daily News"",
+ ""created_at"": 1411493671
},
{
- 'email':'test2@example.com',
- 'group_id': 2,
- 'group_name': 'Daily News',
- 'created_at': 1411493671
+ ""email"":""test2@example.com"",
+ ""group_id"": 2,
+ ""group_name"": ""Daily News"",
+ ""created_at"": 1411493671
}
]";
@@ -115,8 +115,8 @@ public async Task GetUnsubscribedAddressesAsync()
var groupId = 123;
var apiResponse = @"[
- 'test1@example.com',
- 'test2@example.com'
+ ""test1@example.com"",
+ ""test2@example.com""
]";
var mockHttp = new MockHttpMessageHandler();
@@ -145,9 +145,9 @@ public async Task AddAddressToUnsubscribeGroupAsync_single_email()
var email = "test1@example.com";
var apiResponse = @"{
- 'recipient_emails': [
- 'test1@example.com',
- 'test2@example.com'
+ ""recipient_emails"": [
+ ""test1@example.com"",
+ ""test2@example.com""
]
}";
@@ -173,9 +173,9 @@ public async Task AddAddressToUnsubscribeGroupAsync_multiple_emails()
var emails = new[] { "test1@example.com", "test2@example.com" };
var apiResponse = @"{
- 'recipient_emails': [
- 'test1@example.com',
- 'test2@example.com'
+ ""recipient_emails"": [
+ ""test1@example.com"",
+ ""test2@example.com""
]
}";
@@ -222,9 +222,9 @@ public async Task IsSuppressedAsync_true()
var groupId = 123;
var apiResponse = @"[
- 'a@a.com',
- 'b@b.com',
- 'test@example.com'
+ ""a@a.com"",
+ ""b@b.com"",
+ ""test@example.com""
]";
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT, "groups", groupId, "suppressions/search")).Respond("application/json", apiResponse);
@@ -249,8 +249,8 @@ public async Task IsSuppressedAsync_false()
var groupId = 123;
var apiResponse = @"[
- 'a@a.com',
- 'b@b.com'
+ ""a@a.com"",
+ ""b@b.com""
]";
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetSendGridApiUri(ENDPOINT, "groups", groupId, "suppressions/search")).Respond("application/json", apiResponse);
diff --git a/Source/StrongGrid.UnitTests/Resources/TeammatesTests.cs b/Source/StrongGrid.UnitTests/Resources/TeammatesTests.cs
index 6d35bbce..d7a86029 100644
--- a/Source/StrongGrid.UnitTests/Resources/TeammatesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/TeammatesTests.cs
@@ -1,10 +1,10 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -15,107 +15,107 @@ public class TeammatesTests
{
#region FIELDS
- private const string ENDPOINT = "teammates";
+ internal const string ENDPOINT = "teammates";
- private const string MULTIPLE_ACCESS_REQUESTS_JSON = @"[
+ internal const string MULTIPLE_ACCESS_REQUESTS_JSON = @"[
{
- 'id': 1,
- 'scope_group_name': 'Mail Settings',
- 'username': 'teammate1',
- 'email': 'teammate1@example.com',
- 'first_name': 'Teammate',
- 'last_name': 'One'
+ ""id"": 1,
+ ""scope_group_name"": ""Mail Settings"",
+ ""username"": ""teammate1"",
+ ""email"": ""teammate1@example.com"",
+ ""first_name"": ""Teammate"",
+ ""last_name"": ""One""
},
{
- 'id': 2,
- 'scope_group_name': 'Stats',
- 'username': 'teammate2',
- 'email': 'teammate2@example.com',
- 'first_name': 'Teammate',
- 'last_name': 'Two'
+ ""id"": 2,
+ ""scope_group_name"": ""Stats"",
+ ""username"": ""teammate2"",
+ ""email"": ""teammate2@example.com"",
+ ""first_name"": ""Teammate"",
+ ""last_name"": ""Two""
}
]";
- private const string SINGLE_INVITATION_JSON = @"{
- 'email': 'teammate1 @example.com',
- 'scopes': [
- 'user.profile.read',
- 'user.profile.update'
+ internal const string SINGLE_INVITATION_JSON = @"{
+ ""email"": ""teammate1 @example.com"",
+ ""scopes"": [
+ ""user.profile.read"",
+ ""user.profile.update""
],
- 'is_admin': false
+ ""is_admin"": false
}";
- private const string MULTIPLE_INVITATIONS_JSON = @"{
- 'result': [
+ internal const string MULTIPLE_INVITATIONS_JSON = @"{
+ ""result"": [
{
- 'email': 'user1@example.com',
- 'scopes': [
- 'user.profile.read',
- 'user.profile.edit'
+ ""email"": ""user1@example.com"",
+ ""scopes"": [
+ ""user.profile.read"",
+ ""user.profile.edit""
],
- 'is_admin': false,
- 'pending_id': 'abcd123abc',
- 'expiration_date': 1456424263
+ ""is_admin"": false,
+ ""pending_id"": ""abcd123abc"",
+ ""expiration_date"": 1456424263
},
{
- 'email': 'user2@example.com',
- 'scopes': [],
- 'is_admin': true,
- 'pending_id': 'bcde234bcd',
- 'expiration_date': 1456424263
+ ""email"": ""user2@example.com"",
+ ""scopes"": [],
+ ""is_admin"": true,
+ ""pending_id"": ""bcde234bcd"",
+ ""expiration_date"": 1456424263
}
]
}";
- private const string SINGLE_TEAMMATE_JSON = @"{
- 'username': 'teammate1',
- 'email': 'teammate1@example.com',
- 'first_name': 'Jane',
- 'last_name': 'Doe',
- 'user_type': 'owner',
- 'is_admin': true,
- 'phone': '123-345-3453',
- 'website': 'www.example.com',
- 'company': 'ACME Inc.',
- 'address': '123 Acme St',
- 'address2': '',
- 'city': 'City',
- 'state': 'CA',
- 'country': 'USA',
- 'zip': '12345'
+ internal const string SINGLE_TEAMMATE_JSON = @"{
+ ""username"": ""teammate1"",
+ ""email"": ""teammate1@example.com"",
+ ""first_name"": ""Jane"",
+ ""last_name"": ""Doe"",
+ ""user_type"": ""owner"",
+ ""is_admin"": true,
+ ""phone"": ""123-345-3453"",
+ ""website"": ""www.example.com"",
+ ""company"": ""ACME Inc."",
+ ""address"": ""123 Acme St"",
+ ""address2"": """",
+ ""city"": ""City"",
+ ""state"": ""CA"",
+ ""country"": ""USA"",
+ ""zip"": ""12345""
}";
- private const string MULTIPLE_TEAMMATES_JSON = @"{
- 'result': [
+ internal const string MULTIPLE_TEAMMATES_JSON = @"{
+ ""result"": [
{
- 'username': 'teammate2',
- 'email': 'teammate2@example.com',
- 'first_name': 'John',
- 'last_name': 'Doe',
- 'user_type': 'teammate',
- 'is_admin': false,
- 'phone': '123-345-3453',
- 'website': 'www.example.com',
- 'company': 'ACME Inc.',
- 'address': '123 Acme St',
- 'address2': '',
- 'city': 'City',
- 'state': 'CA',
- 'country': 'USA',
- 'zip': '12345'
+ ""username"": ""teammate2"",
+ ""email"": ""teammate2@example.com"",
+ ""first_name"": ""John"",
+ ""last_name"": ""Doe"",
+ ""user_type"": ""teammate"",
+ ""is_admin"": false,
+ ""phone"": ""123-345-3453"",
+ ""website"": ""www.example.com"",
+ ""company"": ""ACME Inc."",
+ ""address"": ""123 Acme St"",
+ ""address2"": """",
+ ""city"": ""City"",
+ ""state"": ""CA"",
+ ""country"": ""USA"",
+ ""zip"": ""12345""
},
{
- 'username': 'teammate3',
- 'email': 'teammate3@example.com',
- 'first_name': 'Steve',
- 'last_name': 'Doe',
- 'user_type': 'admin',
- 'is_admin': true,
- 'phone': '123-345-3453',
- 'website': 'www.example.com',
- 'company': 'ACME Inc.',
- 'address': '123 Acme St',
- 'address2': '',
- 'city': 'City',
- 'state': 'CA',
- 'country': 'USA',
- 'zip': '12345'
+ ""username"": ""teammate3"",
+ ""email"": ""teammate3@example.com"",
+ ""first_name"": ""Steve"",
+ ""last_name"": ""Doe"",
+ ""user_type"": ""admin"",
+ ""is_admin"": true,
+ ""phone"": ""123-345-3453"",
+ ""website"": ""www.example.com"",
+ ""company"": ""ACME Inc."",
+ ""address"": ""123 Acme St"",
+ ""address2"": """",
+ ""city"": ""City"",
+ ""state"": ""CA"",
+ ""country"": ""USA"",
+ ""zip"": ""12345""
}
]
}";
@@ -128,7 +128,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_TEAMMATE_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_TEAMMATE_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/TemplatesTests.cs b/Source/StrongGrid.UnitTests/Resources/TemplatesTests.cs
index a71592ae..063363d0 100644
--- a/Source/StrongGrid.UnitTests/Resources/TemplatesTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/TemplatesTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,51 +16,51 @@ public class TemplatesTests
{
#region FIELDS
- private const string ENDPOINT = "templates";
+ internal const string ENDPOINT = "templates";
- private const string SINGLE_TEMPLATE_JSON = @"{
- 'id': 'e8ac01d5-a07a-4a71-b14c-4721136fe6aa',
- 'name': 'example template name',
- 'versions': [
+ internal const string SINGLE_TEMPLATE_JSON = @"{
+ ""id"": ""e8ac01d5-a07a-4a71-b14c-4721136fe6aa"",
+ ""name"": ""example template name"",
+ ""versions"": [
{
- 'id': 'de37d11b-082a-42c0-9884-c0c143015a47',
- 'user_id': 1234,
- 'template_id': 'd51480ba-ca3f-465c-bc3e-ceb71d73c38d',
- 'active': 1,
- 'name': 'example version',
- 'html_content': '<%body%>Click to Reset',
- 'plain_content': 'Click to Reset<%body%>',
- 'subject': '<%subject%>',
- 'updated_at': '2014-05-22 20:05:21'
+ ""id"": ""de37d11b-082a-42c0-9884-c0c143015a47"",
+ ""user_id"": 1234,
+ ""template_id"": ""d51480ba-ca3f-465c-bc3e-ceb71d73c38d"",
+ ""active"": 1,
+ ""name"": ""example version"",
+ ""html_content"": ""<%body%>Click to Reset"",
+ ""plain_content"": ""Click to Reset<%body%>"",
+ ""subject"": ""<%subject%>"",
+ ""updated_at"": ""2014-05-22 20:05:21""
}
]
}";
- private const string MULTIPLE_TEMPLATES_JSON = @"{
- 'templates': [
+ internal const string MULTIPLE_TEMPLATES_JSON = @"{
+ ""templates"": [
{
- 'id': 'e8ac01d5-a07a-4a71-b14c-4721136fe6aa',
- 'name': 'example template name',
- 'versions': [
+ ""id"": ""e8ac01d5-a07a-4a71-b14c-4721136fe6aa"",
+ ""name"": ""example template name"",
+ ""versions"": [
{
- 'id': '5997fcf6-2b9f-484d-acd5-7e9a99f0dc1f',
- 'template_id': '9c59c1fb-931a-40fc-a658-50f871f3e41c',
- 'active': 1,
- 'name': 'example version name',
- 'updated_at': '2014-03-19 18:56:33'
+ ""id"": ""5997fcf6-2b9f-484d-acd5-7e9a99f0dc1f"",
+ ""template_id"": ""9c59c1fb-931a-40fc-a658-50f871f3e41c"",
+ ""active"": 1,
+ ""name"": ""example version name"",
+ ""updated_at"": ""2014-03-19 18:56:33""
}
]
}
]
}";
- private const string SINGLE_TEMPLATE_VERSION_JSON = @"{
- 'id': '8aefe0ee-f12b-4575-b5b7-c97e21cb36f3',
- 'template_id': 'ddb96bbc-9b92-425e-8979-99464621b543',
- 'active': 1,
- 'name': 'example_version_name',
- 'html_content': '<%body%>',
- 'plain_content': '<%body%>',
- 'subject': '<%subject%>',
- 'updated_at': '2014-03-19 18:56:33'
+ internal const string SINGLE_TEMPLATE_VERSION_JSON = @"{
+ ""id"": ""8aefe0ee-f12b-4575-b5b7-c97e21cb36f3"",
+ ""template_id"": ""ddb96bbc-9b92-425e-8979-99464621b543"",
+ ""active"": 1,
+ ""name"": ""example_version_name"",
+ ""html_content"": ""<%body%>"",
+ ""plain_content"": ""<%body%>"",
+ ""subject"": ""<%subject%>"",
+ ""updated_at"": ""2014-03-19 18:56:33""
}";
#endregion
@@ -71,7 +71,7 @@ public void Parse_Template_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_TEMPLATE_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_TEMPLATE_JSON);
// Assert
result.ShouldNotBeNull();
@@ -86,7 +86,7 @@ public void Parse_TemplateVersion_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_TEMPLATE_VERSION_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_TEMPLATE_VERSION_JSON);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Resources/UnsubscribeGroupsTests.cs b/Source/StrongGrid.UnitTests/Resources/UnsubscribeGroupsTests.cs
index 909c7229..d270ee91 100644
--- a/Source/StrongGrid.UnitTests/Resources/UnsubscribeGroupsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/UnsubscribeGroupsTests.cs
@@ -1,10 +1,10 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -15,30 +15,30 @@ public class UnsubscribeGroupsTests
{
#region FIELDS
- private const string ENDPOINT = "asm/groups";
+ internal const string ENDPOINT = "asm/groups";
- private const string SINGLE_SUPPRESSION_GROUP_JSON = @"{
- 'id': 1,
- 'name': 'Product Suggestions',
- 'description': 'Suggestions for products our users might like.',
- 'is_default': true
+ internal const string SINGLE_SUPPRESSION_GROUP_JSON = @"{
+ ""id"": 1,
+ ""name"": ""Product Suggestions"",
+ ""description"": ""Suggestions for products our users might like."",
+ ""is_default"": true
}";
- private const string MULTIPLE_SUPPRESSION_GROUPS_JSON = @"[
+ internal const string MULTIPLE_SUPPRESSION_GROUPS_JSON = @"[
{
- 'id': 100,
- 'name': 'Newsletters',
- 'description': 'Our monthly newsletter.',
- 'last_email_sent_at': null,
- 'is_default': true,
- 'unsubscribes': 400
+ ""id"": 100,
+ ""name"": ""Newsletters"",
+ ""description"": ""Our monthly newsletter."",
+ ""last_email_sent_at"": null,
+ ""is_default"": true,
+ ""unsubscribes"": 400
},
{
- 'id': 101,
- 'name': 'Alerts',
- 'description 2': 'Emails triggered by user-defined rules.',
- 'last_email_sent_at': null,
- 'is_default': false,
- 'unsubscribes': 1
+ ""id"": 101,
+ ""name"": ""Alerts"",
+ ""description 2"": ""Emails triggered by user-defined rules."",
+ ""last_email_sent_at"": null,
+ ""is_default"": false,
+ ""unsubscribes"": 1
}
]";
@@ -50,7 +50,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_SUPPRESSION_GROUP_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_SUPPRESSION_GROUP_JSON);
// Assert
result.ShouldNotBeNull();
@@ -69,9 +69,9 @@ public async Task CreateAsync()
var isDefault = true;
var apiResponse = @"{
- 'name': 'Product Suggestions',
- 'description': 'Suggestions for products our users might like.',
- 'is_default': true
+ ""name"": ""Product Suggestions"",
+ ""description"": ""Suggestions for products our users might like."",
+ ""is_default"": true
}";
var mockHttp = new MockHttpMessageHandler();
diff --git a/Source/StrongGrid.UnitTests/Resources/UserTests.cs b/Source/StrongGrid.UnitTests/Resources/UserTests.cs
index 33516b04..8b7ae6ef 100644
--- a/Source/StrongGrid.UnitTests/Resources/UserTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/UserTests.cs
@@ -1,4 +1,3 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
@@ -6,6 +5,7 @@
using System;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -16,19 +16,19 @@ public class UserTests
{
#region FIELDS
- private const string ENDPOINT = "user/profile";
-
- private const string SINGLE_PROFILE_JSON = @"{
- 'address': '814 West Chapman Avenue',
- 'city': 'Orange',
- 'company': 'SendGrid',
- 'country': 'US',
- 'first_name': 'Test',
- 'last_name': 'User',
- 'phone': '555-555-5555',
- 'state': 'CA',
- 'website': 'http://www.sendgrid.com',
- 'zip': '92868'
+ internal const string ENDPOINT = "user/profile";
+
+ internal const string SINGLE_PROFILE_JSON = @"{
+ ""address"": ""814 West Chapman Avenue"",
+ ""city"": ""Orange"",
+ ""company"": ""SendGrid"",
+ ""country"": ""US"",
+ ""first_name"": ""Test"",
+ ""last_name"": ""User"",
+ ""phone"": ""555-555-5555"",
+ ""state"": ""CA"",
+ ""website"": ""http://www.sendgrid.com"",
+ ""zip"": ""92868""
}";
#endregion
@@ -39,7 +39,7 @@ public void Parse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_PROFILE_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_PROFILE_JSON);
// Assert
result.ShouldNotBeNull();
@@ -79,8 +79,8 @@ public async Task GetAccountAsync()
{
// Arrange
var apiResponse = @"{
- 'type': 'free',
- 'reputation': 99.7
+ ""type"": ""free"",
+ ""reputation"": 99.7
}";
var mockHttp = new MockHttpMessageHandler();
@@ -126,7 +126,7 @@ public async Task GetEmailAsync()
{
// Arrange
var apiResponse = @"{
- 'email': 'test@example.com'
+ ""email"": ""test@example.com""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -151,7 +151,7 @@ public async Task UpdateEmailAsync()
var email = "test@example.com";
var apiResponse = @"{
- 'email': 'test@example.com'
+ ""email"": ""test@example.com""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -174,7 +174,7 @@ public async Task GetUsernameAsync()
{
// Arrange
var apiResponse = @"{
- 'username': 'test_username'
+ ""username"": ""test_username""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -199,7 +199,7 @@ public async Task UpdateUsernameAsync()
var username = "test_username";
var apiResponse = @"{
- 'username': 'test_username'
+ ""username"": ""test_username""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -222,13 +222,13 @@ public async Task GetCreditsAsync()
{
// Arrange
var apiResponse = @"{
- 'remain': 200,
- 'total': 200,
- 'overage': 0,
- 'used': 0,
- 'last_reset': '2013-01-01',
- 'next_reset': '2013-02-01',
- 'reset_frequency': 'monthly'
+ ""remain"": 200,
+ ""total"": 200,
+ ""overage"": 0,
+ ""used"": 0,
+ ""last_reset"": ""2013-01-01"",
+ ""next_reset"": ""2013-02-01"",
+ ""reset_frequency"": ""monthly""
}";
var mockHttp = new MockHttpMessageHandler();
@@ -279,10 +279,10 @@ public async Task GetPermissionsAsync()
{
// Arrange
var apiResponse = @"{
- 'scopes': [
- 'aaa',
- 'bbb',
- 'ccc'
+ ""scopes"": [
+ ""aaa"",
+ ""bbb"",
+ ""ccc""
]
}";
diff --git a/Source/StrongGrid.UnitTests/Resources/WebhookSettingsTests.cs b/Source/StrongGrid.UnitTests/Resources/WebhookSettingsTests.cs
index 39a879ff..3bcc52d4 100644
--- a/Source/StrongGrid.UnitTests/Resources/WebhookSettingsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/WebhookSettingsTests.cs
@@ -1,10 +1,10 @@
-using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
using System.Net;
using System.Net.Http;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
@@ -15,30 +15,30 @@ public class WebhookSettingsTests
{
#region FIELDS
- private const string EVENT_ENDPOINT = "user/webhooks/event";
- private const string INBOUNDPARSE_ENDPOINT = "user/webhooks/parse";
-
- private const string SINGLE_EVENT_WEBHOOK_SETTING_JSON = @"{
- 'enabled': true,
- 'url': 'url',
- 'group_resubscribe': true,
- 'delivered': true,
- 'group_unsubscribe': true,
- 'spam_report': true,
- 'bounce': true,
- 'deferred': true,
- 'unsubscribe': true,
- 'processed': true,
- 'open': true,
- 'click': true,
- 'dropped': true
+ internal const string EVENT_ENDPOINT = "user/webhooks/event";
+ internal const string INBOUNDPARSE_ENDPOINT = "user/webhooks/parse";
+
+ internal const string SINGLE_EVENT_WEBHOOK_SETTING_JSON = @"{
+ ""enabled"": true,
+ ""url"": ""url"",
+ ""group_resubscribe"": true,
+ ""delivered"": true,
+ ""group_unsubscribe"": true,
+ ""spam_report"": true,
+ ""bounce"": true,
+ ""deferred"": true,
+ ""unsubscribe"": true,
+ ""processed"": true,
+ ""open"": true,
+ ""click"": true,
+ ""dropped"": true
}";
- private const string SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON = @"{
- 'hostname': 'myhostname.com',
- 'url': 'http://email.myhosthame.com',
- 'spam_check': true,
- 'send_raw': false
+ internal const string SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON = @"{
+ ""hostname"": ""myhostname.com"",
+ ""url"": ""http://email.myhosthame.com"",
+ ""spam_check"": true,
+ ""send_raw"": false
}";
#endregion
@@ -49,7 +49,7 @@ public void Parse_event_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_EVENT_WEBHOOK_SETTING_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_EVENT_WEBHOOK_SETTING_JSON);
// Assert
result.ShouldNotBeNull();
@@ -73,7 +73,7 @@ public void Parse_inboundparse_json()
// Arrange
// Act
- var result = JsonConvert.DeserializeObject(SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON);
+ var result = JsonSerializer.Deserialize(SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON);
// Assert
result.ShouldNotBeNull();
@@ -89,19 +89,19 @@ public async Task GetEventWebhookSettingsAsync()
// Arrange
var apiResponse = @"{
- 'enabled': true,
- 'url': 'url',
- 'group_resubscribe': true,
- 'delivered': true,
- 'group_unsubscribe': true,
- 'spam_report': true,
- 'bounce': true,
- 'deferred': true,
- 'unsubscribe': true,
- 'processed': true,
- 'open': true,
- 'click': true,
- 'dropped': true
+ ""enabled"": true,
+ ""url"": ""url"",
+ ""group_resubscribe"": true,
+ ""delivered"": true,
+ ""group_unsubscribe"": true,
+ ""spam_report"": true,
+ ""bounce"": true,
+ ""deferred"": true,
+ ""unsubscribe"": true,
+ ""processed"": true,
+ ""open"": true,
+ ""click"": true,
+ ""dropped"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -150,19 +150,19 @@ public async Task UpdateEventWebhookSettingsAsync()
var unsubscribe = true;
var apiResponse = @"{
- 'enabled': true,
- 'url': 'url',
- 'group_resubscribe': true,
- 'delivered': true,
- 'group_unsubscribe': true,
- 'spam_report': true,
- 'bounce': true,
- 'deferred': true,
- 'unsubscribe': true,
- 'processed': true,
- 'open': true,
- 'click': true,
- 'dropped': true
+ ""enabled"": true,
+ ""url"": ""url"",
+ ""group_resubscribe"": true,
+ ""delivered"": true,
+ ""group_unsubscribe"": true,
+ ""spam_report"": true,
+ ""bounce"": true,
+ ""deferred"": true,
+ ""unsubscribe"": true,
+ ""processed"": true,
+ ""open"": true,
+ ""click"": true,
+ ""dropped"": true
}";
var mockHttp = new MockHttpMessageHandler();
@@ -225,7 +225,7 @@ public async Task GetInboundParseWebhookSettings()
public async Task GetAllInboundParseWebhookSettings()
{
// Arrange
- var apiResponse = "{'result':[" +
+ var apiResponse = "{\"result\":[" +
SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON + "," +
SINGLE_INBOUNDPARSE_WEBHOOK_SETTING_JSON +
"]}";
diff --git a/Source/StrongGrid.UnitTests/Resources/WebhookStatsTests.cs b/Source/StrongGrid.UnitTests/Resources/WebhookStatsTests.cs
index 5ccb37d1..e2758c99 100644
--- a/Source/StrongGrid.UnitTests/Resources/WebhookStatsTests.cs
+++ b/Source/StrongGrid.UnitTests/Resources/WebhookStatsTests.cs
@@ -1,4 +1,4 @@
-using RichardSzalay.MockHttp;
+using RichardSzalay.MockHttp;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Resources;
@@ -21,21 +21,21 @@ public async Task GetGlobalStatsAsync()
var endDate = new DateTime(2015, 1, 2);
var apiResponse = @"[
{
- 'date': '2015-01-01',
- 'stats': [
+ ""date"": ""2015-01-01"",
+ ""stats"": [
{
- 'metrics': {
- 'received': 1
+ ""metrics"": {
+ ""received"": 1
}
}
]
},
{
- 'date': '2015-01-02',
- 'stats': [
+ ""date"": ""2015-01-02"",
+ ""stats"": [
{
- 'metrics': {
- 'received': 3
+ ""metrics"": {
+ ""received"": 3
}
}
]
diff --git a/Source/StrongGrid.UnitTests/StrongGrid.UnitTests.csproj b/Source/StrongGrid.UnitTests/StrongGrid.UnitTests.csproj
index 028f2ba5..e14f3370 100644
--- a/Source/StrongGrid.UnitTests/StrongGrid.UnitTests.csproj
+++ b/Source/StrongGrid.UnitTests/StrongGrid.UnitTests.csproj
@@ -1,4 +1,4 @@
-
+
net48;netcoreapp3.1;net5.0
@@ -18,6 +18,17 @@
+
+
+ $(DefineConstants);RELEASE;TRACE
+ false
+ portable
+ true
+
+
diff --git a/Source/StrongGrid.UnitTests/Utilities/CategoryConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/CategoryConverterTests.cs
index 89e59720..f0413978 100644
--- a/Source/StrongGrid.UnitTests/Utilities/CategoryConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/CategoryConverterTests.cs
@@ -1,103 +1,75 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.IO;
+using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class CategoryConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new CategoryConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeFalse();
- }
-
- [Fact]
- public void CanConvert()
- {
- // Act
- var converter = new CategoryConverter();
-
- // Assert
- converter.CanConvert(null).ShouldBeTrue();
- }
-
[Fact]
public void Write()
{
// Arrange
- var writer = (JsonWriter)null;
- var value = (object)null;
- var serializer = (JsonSerializer)null;
+ var value = new[] { "abc123" };
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new CategoryConverter();
// Act
- Should.Throw(() => converter.WriteJson(writer, value, serializer));
+ Should.Throw(() => converter.Write(jsonWriter, value, options));
}
[Fact]
public void Read_single()
{
// Arrange
- var json = "'category1'";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var json = "\"category1\"";
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new CategoryConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
- result.ShouldBeOfType();
-
- var resultAsArray = (string[])result;
- resultAsArray.Length.ShouldBe(1);
- resultAsArray[0].ShouldBe("category1");
+ result.Length.ShouldBe(1);
+ result[0].ShouldBe("category1");
}
[Fact]
public void Read_multiple()
{
// Arrange
- var json = "['category1','category2','category3']";
+ var json = "[\"category1\",\"category2\",\"category3\"]";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new CategoryConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
- result.ShouldBeOfType();
-
- var resultAsArray = (string[])result;
- resultAsArray.Length.ShouldBe(3);
- resultAsArray[0].ShouldBe("category1");
- resultAsArray[1].ShouldBe("category2");
- resultAsArray[2].ShouldBe("category3");
+ result.Length.ShouldBe(3);
+ result[0].ShouldBe("category1");
+ result[1].ShouldBe("category2");
+ result[2].ShouldBe("category3");
}
}
}
diff --git a/Source/StrongGrid.UnitTests/Utilities/CustomFieldsConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/CustomFieldsConverterTests.cs
index c6406c9e..48c8f8ab 100644
--- a/Source/StrongGrid.UnitTests/Utilities/CustomFieldsConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/CustomFieldsConverterTests.cs
@@ -1,113 +1,63 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Utilities;
using System;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class CustomFieldsConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new CustomFieldsConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
- [Fact]
- public void CanConvert()
- {
- // Act
- var converter = new CustomFieldsConverter();
-
- // Assert
- converter.CanConvert(null).ShouldBeTrue();
- }
-
[Fact]
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = new Field[]
{
new Field() { Id = "a", Name = "field1", Value = "111111" },
new Field() { Id = "b", Name = "field2", Value = 222222 },
new Field() { Id = "c", Name = "field3", Value = new DateTime(2020, 2, 7, 14, 56, 0, DateTimeKind.Utc) },
};
- var serializer = new JsonSerializer();
- var converter = new CustomFieldsConverter();
-
- // Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBe("{\"a\":\"111111\",\"b\":222222,\"c\":\"2020-02-07T14:56:00.0000000Z\"}");
- }
-
- [Fact]
- public void Read_invalid()
- {
- // Arrange
- var json = @"[
- { 'first': 'this first JSON is invalid for this converter' },
- { 'second': 'this second JSON is also invalid for this converter' }
- ]";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
- var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new CustomFieldsConverter();
// Act
- jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
- // Assert
- result.ShouldNotBeNull();
- result.ShouldBeOfType();
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
- var resultAsArray = (Field[])result;
- resultAsArray.Length.ShouldBe(0);
+ // Assert
+ result.ShouldBe("{\"a\":\"111111\",\"b\":222222,\"c\":\"2020-02-07T14:56:00.0000000Z\"}");
}
[Fact]
public void Read_multiple()
{
- // Arrange
var json = @"{
- 'a': '2020-02-07T14:51:00Z',
- 'b': 'abc123',
- 'c': 123
+ ""a"": ""2020-02-07T14:51:00Z"",
+ ""b"": ""abc123"",
+ ""c"": 123
}";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new CustomFieldsConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
@@ -118,7 +68,7 @@ public void Read_multiple()
resultAsArray[0].Name.ShouldBe("a");
resultAsArray[0].ShouldBeOfType>();
- ((Field)resultAsArray[0]).Value.ShouldBe(new DateTime(2020, 2, 7, 14, 51, 0, DateTimeKind.Utc));
+ ((Field)resultAsArray[0]).Value.ToUniversalTime().ShouldBe(new DateTime(2020, 2, 7, 14, 51, 0, DateTimeKind.Utc));
resultAsArray[1].Name.ShouldBe("b");
resultAsArray[1].ShouldBeOfType>();
diff --git a/Source/StrongGrid.UnitTests/Utilities/EpochConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/EpochConverterTests.cs
index d20157ab..bcb7061d 100644
--- a/Source/StrongGrid.UnitTests/Utilities/EpochConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/EpochConverterTests.cs
@@ -1,26 +1,15 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class EpochConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new EpochConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
[Fact]
public void CanConvert_true()
{
@@ -43,87 +32,44 @@ public void CanConvert_false()
converter.CanConvert(type).ShouldBeFalse();
}
- [Fact]
- public void Write_null()
- {
- // Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
- var value = (DateTime?)null;
- var serializer = new JsonSerializer();
-
- var converter = new EpochConverter();
-
- // Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBeEmpty();
- }
-
[Fact]
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = new DateTime(2017, 3, 28, 14, 30, 0, DateTimeKind.Utc);
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new EpochConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBe("1490711400");
- }
-
- [Fact]
- public void Read_null()
- {
- // Arrange
- var json = "";
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
- var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
-
- var converter = new EpochConverter();
-
- // Act
- jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
- result.ShouldBeNull();
+ result.ShouldBe("1490711400");
}
[Fact]
- public void Read_date()
+ public void Read()
{
// Arrange
var json = "1490711400";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new EpochConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldBe(new DateTime(2017, 3, 28, 14, 30, 0, DateTimeKind.Utc));
diff --git a/Source/StrongGrid.UnitTests/Utilities/ExtensionsTests.cs b/Source/StrongGrid.UnitTests/Utilities/ExtensionsTests.cs
index eeebf40d..0a93e796 100644
--- a/Source/StrongGrid.UnitTests/Utilities/ExtensionsTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/ExtensionsTests.cs
@@ -1,5 +1,5 @@
using Shouldly;
-using StrongGrid.Utilities;
+using StrongGrid.Models.Legacy;
using System;
using Xunit;
@@ -58,5 +58,25 @@ public void ToUnixTime_2016()
// Assert
result.ShouldBe(1468155111);
}
+
+ [Fact]
+ public void ToEnum_throws_when_invalid_value()
+ {
+ Should.Throw(() => "This is not a valid value".ToEnum());
+ }
+
+ [Theory]
+ [InlineData("in progress", CampaignStatus.InProgress)]
+ [InlineData("IN PROGRESS", CampaignStatus.InProgress)]
+ [InlineData("In Progress", CampaignStatus.InProgress)]
+ [InlineData("In progress", CampaignStatus.InProgress)]
+ public void ToEnum_is_case_insensitive(string descripion, CampaignStatus expectedStatus)
+ {
+ // Act
+ var result = descripion.ToEnum();
+
+ // Assert
+ result.ShouldBe(expectedStatus);
+ }
}
}
diff --git a/Source/StrongGrid.UnitTests/Utilities/IntegerBooleanConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/IntegerBooleanConverterTests.cs
index 75358968..dd56308c 100644
--- a/Source/StrongGrid.UnitTests/Utilities/IntegerBooleanConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/IntegerBooleanConverterTests.cs
@@ -1,26 +1,15 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class IntegerBooleanConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new IntegerBooleanConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
[Fact]
public void CanConvert_true()
{
@@ -43,43 +32,24 @@ public void CanConvert_false()
converter.CanConvert(type).ShouldBeFalse();
}
- [Fact]
- public void Write_null()
- {
- // Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
- var value = (bool?)null;
- var serializer = new JsonSerializer();
-
- var converter = new IntegerBooleanConverter();
-
- // Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBeEmpty();
- }
-
[Fact]
public void Write_true()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = true;
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new IntegerBooleanConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
+
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
result.ShouldBe("1");
@@ -89,43 +59,23 @@ public void Write_true()
public void Write_false()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = false;
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new IntegerBooleanConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBe("0");
- }
-
- [Fact]
- public void Read_null()
- {
- // Arrange
- var json = "";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
- var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
-
- var converter = new IntegerBooleanConverter();
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
- // Act
- jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
- result.ShouldBeNull();
+ result.ShouldBe("0");
}
[Fact]
@@ -133,22 +83,19 @@ public void Read_true()
{
// Arrange
var json = "1";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new IntegerBooleanConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
- result.ShouldBeOfType();
- ((bool)result).ShouldBeTrue();
+ result.ShouldBeTrue();
}
[Fact]
@@ -156,22 +103,19 @@ public void Read_false()
{
// Arrange
var json = "\"Anything other than the numeral 1 should yield false\"";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new IntegerBooleanConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
- result.ShouldBeOfType();
- ((bool)result).ShouldBeFalse();
+ result.ShouldBeFalse();
}
}
}
diff --git a/Source/StrongGrid.UnitTests/Utilities/KeyValuePairEnumerationConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/KeyValuePairEnumerationConverterTests.cs
index 98ab766c..7cce6c72 100644
--- a/Source/StrongGrid.UnitTests/Utilities/KeyValuePairEnumerationConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/KeyValuePairEnumerationConverterTests.cs
@@ -1,26 +1,16 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
+using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class KeyValuePairEnumerationConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new KeyValuePairEnumerationConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
[Fact]
public void CanConvert_true()
{
@@ -36,18 +26,20 @@ public void CanConvert_true()
public void Write_null()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
- var value = (object)null;
- var serializer = new JsonSerializer();
+ var value = (KeyValuePair[])null;
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new KeyValuePairEnumerationConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
+
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
result.ShouldBeEmpty();
@@ -57,22 +49,24 @@ public void Write_null()
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = new[]
{
new KeyValuePair("key1", "value1"),
new KeyValuePair("key2", "value2")
};
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new KeyValuePairEnumerationConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
+
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
result.ShouldBe("{\"key1\":\"value1\",\"key2\":\"value2\"}");
@@ -83,18 +77,16 @@ public void Read()
{
// Arrange
var json = "{ \"some_value\": \"QWERTY\", \"another_value\": \"ABC_123\" }";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
- var objectType = typeof(KeyValuePair[]);
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
+ var objectType = (Type)null;
+ var options = new JsonSerializerOptions();
var converter = new KeyValuePairEnumerationConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Utilities/LegacyCustomFieldsConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/LegacyCustomFieldsConverterTests.cs
index b26bbe7c..774baadb 100644
--- a/Source/StrongGrid.UnitTests/Utilities/LegacyCustomFieldsConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/LegacyCustomFieldsConverterTests.cs
@@ -1,44 +1,34 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class LegacyCustomFieldsConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new LegacyCustomFieldsConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
- [Fact]
- public void CanConvert()
+ [Theory]
+ [InlineData(typeof(StrongGrid.Models.Legacy.Field[]), true)]
+ [InlineData((Type)null, false)]
+ [InlineData(typeof(TimeSpan), false)]
+ [InlineData(typeof(string), false)]
+ [InlineData(typeof(StrongGrid.Models.Field), false)]
+ public void CanConvert(Type typeToConvert, bool expected)
{
// Act
var converter = new LegacyCustomFieldsConverter();
// Assert
- converter.CanConvert(null).ShouldBeTrue();
+ converter.CanConvert(typeToConvert).ShouldBe(expected);
}
[Fact]
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = new StrongGrid.Models.Legacy.Field[]
{
new StrongGrid.Models.Legacy.Field() { Id = 1, Name = "field1", Value = "111111" },
@@ -47,13 +37,20 @@ public void Write()
new StrongGrid.Models.Legacy.Field() { Id = 4, Name = "field4", Value = new DateTime(2017, 3, 28, 13, 55, 0) },
new StrongGrid.Models.Legacy.Field() { Id = 5, Name = "field5", Value = null }
};
- var serializer = new JsonSerializer();
+
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new LegacyCustomFieldsConverter();
// Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
+
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
result.ShouldBe("[{\"value\":\"111111\",\"id\":1,\"name\":\"field1\"},{\"value\":222222,\"id\":2,\"name\":\"field2\"},{\"id\":3,\"name\":\"field3\"},{\"value\":\"2017-03-28T13:55:00\",\"id\":4,\"name\":\"field4\"},{\"id\":5,\"name\":\"field5\"}]");
@@ -63,26 +60,22 @@ public void Write()
public void Read_invalid()
{
// Arrange
- var json = "{ 'name': 'this JSON is invalid for this converter' }";
+ var json = "{ \"name\": \"this JSON is invalid for this converter\" }";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new LegacyCustomFieldsConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
- result.ShouldBeOfType();
-
- var resultAsArray = (StrongGrid.Models.Legacy.Field[])result;
- resultAsArray.Length.ShouldBe(0);
+ result.Length.ShouldBe(0);
}
[Fact]
@@ -90,21 +83,31 @@ public void Read_unknown_fieldtype()
{
// Arrange
var json = @"[
- { 'id':0, 'name':'field0', 'type':'__bogus__' }
+ { ""id"":0, ""name"":""field0"", ""type"":""__bogus__"" }
]";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new LegacyCustomFieldsConverter();
// Act
jsonReader.Read();
- Should.Throw(() => converter.ReadJson(jsonReader, objectType, existingValue, serializer))
- .Message.ShouldBe("__bogus__ is an unknown field type");
+
+ // This try...catch is a workaround for the fact that we can't use the following code:
+ // Should.Throw(() => converter.Read(ref jsonReader, objectType, options)).Message.ShouldBe("__bogus__ is an unknown field type");
+ // due to the following compile time error:
+ // Cannot use ref local 'jsonReader' inside an anonymous method, lambda expression, or query expression
+ try
+ {
+ var fields = converter.Read(ref jsonReader, objectType, options);
+ }
+ catch (Exception e) when (e.Message == "__bogus__ is an unknown field type")
+ {
+ // This is the expected exception
+ }
}
[Fact]
@@ -112,25 +115,24 @@ public void Read_multiple()
{
// Arrange
var json = @"[
- { 'id':0, 'name':'field0', 'type':'date', 'value':1490709300 },
- { 'id':1, 'name':'field1', 'type':'date' },
- { 'id':2, 'name':'field2', 'type':'text', 'value':'abc123' },
- { 'id':3, 'name':'field3', 'type':'text' },
- { 'id':4, 'name':'field4', 'type':'number', 'value':123 },
- { 'id':5, 'name':'field5', 'type':'number' }
+ { ""id"":0, ""name"":""field0"", ""type"":""date"", ""value"":1490709300 },
+ { ""id"":1, ""name"":""field1"", ""type"":""date"" },
+ { ""id"":2, ""name"":""field2"", ""type"":""text"", ""value"":""abc123"" },
+ { ""id"":3, ""name"":""field3"", ""type"":""text"" },
+ { ""id"":4, ""name"":""field4"", ""type"":""number"", ""value"":123 },
+ { ""id"":5, ""name"":""field5"", ""type"":""number"" }
]";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new LegacyCustomFieldsConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
diff --git a/Source/StrongGrid.UnitTests/Utilities/MetricsConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/MetricsConverterTests.cs
index 087d9411..ef49681f 100644
--- a/Source/StrongGrid.UnitTests/Utilities/MetricsConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/MetricsConverterTests.cs
@@ -1,53 +1,45 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class MetricsConverterTests
{
- [Fact]
- public void Properties()
+ [Theory]
+ [InlineData(typeof(KeyValuePair[]), true)]
+ [InlineData((Type)null, false)]
+ [InlineData(typeof(TimeSpan), false)]
+ [InlineData(typeof(string), false)]
+ [InlineData(typeof(StrongGrid.Models.Field), false)]
+ public void CanConvert(Type typeToConvert, bool expected)
{
- // Act
+ // Arrange
var converter = new MetricsConverter();
// Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeFalse();
+ converter.CanConvert(typeToConvert).ShouldBe(expected);
}
- [Fact]
- public void CanConvert()
- {
- // Act
- var converter = new MetricsConverter();
- var type = (Type)null;
-
- // Assert
- converter.CanConvert(type).ShouldBeTrue();
- }
[Fact]
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
- var value = (object)null;
- var serializer = new JsonSerializer();
+ var value = (KeyValuePair[])null;
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new MetricsConverter();
// Act
- Should.Throw(() => converter.WriteJson(writer, value, serializer));
+ Should.Throw(() => converter.Write(jsonWriter, value, options));
}
[Fact]
@@ -56,28 +48,24 @@ public void Read()
// Arrange
var json = "{\"metric1\":1,\"metric2\":2}";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new MetricsConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
result.ShouldNotBeNull();
- result.ShouldBeOfType[]>();
-
- var resultAsArray = (KeyValuePair[])result;
- resultAsArray.Length.ShouldBe(2);
- resultAsArray[0].Key.ShouldBe("metric1");
- resultAsArray[0].Value.ShouldBe(1);
- resultAsArray[1].Key.ShouldBe("metric2");
- resultAsArray[1].Value.ShouldBe(2);
+ result.Length.ShouldBe(2);
+ result[0].Key.ShouldBe("metric1");
+ result[0].Value.ShouldBe(1);
+ result[1].Key.ShouldBe("metric2");
+ result[1].Value.ShouldBe(2);
}
}
}
diff --git a/Source/StrongGrid.UnitTests/Utilities/SendGridDateTimeConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/SendGridDateTimeConverterTests.cs
index 1e8d23f5..74c783e2 100644
--- a/Source/StrongGrid.UnitTests/Utilities/SendGridDateTimeConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/SendGridDateTimeConverterTests.cs
@@ -1,110 +1,37 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Utilities;
using System;
using System.IO;
using System.Text;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
{
public class SendGridDateTimeConverterTests
{
- [Fact]
- public void Properties()
- {
- // Act
- var converter = new SendGridDateTimeConverter();
-
- // Assert
- converter.CanRead.ShouldBeTrue();
- converter.CanWrite.ShouldBeTrue();
- }
-
- [Fact]
- public void CanConvert_true()
- {
- // Act
- var converter = new SendGridDateTimeConverter();
- var type = typeof(DateTime);
-
- // Assert
- converter.CanConvert(type).ShouldBeTrue();
- }
-
- [Fact]
- public void CanConvert_false()
- {
- // Act
- var converter = new SendGridDateTimeConverter();
- var type = (Type)null;
-
- // Assert
- converter.CanConvert(type).ShouldBeFalse();
- }
-
- [Fact]
- public void Write_null()
- {
- // Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
- var value = (object)null;
- var serializer = new JsonSerializer();
-
- var converter = new SendGridDateTimeConverter();
-
- // Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
-
- // Assert
- result.ShouldBeEmpty();
- }
-
[Fact]
public void Write()
{
// Arrange
- var sb = new StringBuilder();
- var sw = new StringWriter(sb);
- var writer = new JsonTextWriter(sw);
-
var value = new DateTime(2017, 3, 28, 16, 19, 0, DateTimeKind.Utc);
- var serializer = new JsonSerializer();
-
- var converter = new SendGridDateTimeConverter();
-
- // Act
- converter.WriteJson(writer, value, serializer);
- var result = sb.ToString();
- // Assert
- result.ShouldBe("\"2017-03-28 16:19:00\"");
- }
-
- [Fact]
- public void Read_null()
- {
- // Arrange
- var json = "";
-
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
- var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var ms = new MemoryStream();
+ var jsonWriter = new Utf8JsonWriter(ms);
+ var options = new JsonSerializerOptions();
var converter = new SendGridDateTimeConverter();
// Act
- jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ converter.Write(jsonWriter, value, options);
+ jsonWriter.Flush();
+
+ ms.Position = 0;
+ var sr = new StreamReader(ms);
+ var result = sr.ReadToEnd();
// Assert
- result.ShouldBeNull();
+ result.ShouldBe("\"2017-03-28 16:19:00\"");
}
[Fact]
@@ -113,22 +40,19 @@ public void Read()
// Arrange
var json = "\"2017-03-28 16:19:00\"";
- var textReader = new StringReader(json);
- var jsonReader = new JsonTextReader(textReader);
+ var jsonUtf8 = (ReadOnlySpan)Encoding.UTF8.GetBytes(json);
+ var jsonReader = new Utf8JsonReader(jsonUtf8);
var objectType = (Type)null;
- var existingValue = (object)null;
- var serializer = new JsonSerializer();
+ var options = new JsonSerializerOptions();
var converter = new SendGridDateTimeConverter();
// Act
jsonReader.Read();
- var result = converter.ReadJson(jsonReader, objectType, existingValue, serializer);
+ var result = converter.Read(ref jsonReader, objectType, options);
// Assert
- result.ShouldNotBeNull();
- result.ShouldBeOfType();
- ((DateTime)result).ShouldBe(new DateTime(2017, 3, 28, 16, 19, 0, DateTimeKind.Utc));
+ result.ShouldBe(new DateTime(2017, 3, 28, 16, 19, 0, DateTimeKind.Utc));
}
}
}
diff --git a/Source/StrongGrid.UnitTests/Utilities/StringEnumConverterTests.cs b/Source/StrongGrid.UnitTests/Utilities/StringEnumConverterTests.cs
index cb2e1b47..305f5508 100644
--- a/Source/StrongGrid.UnitTests/Utilities/StringEnumConverterTests.cs
+++ b/Source/StrongGrid.UnitTests/Utilities/StringEnumConverterTests.cs
@@ -1,6 +1,6 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Models.Legacy;
+using System.Text.Json;
using Xunit;
namespace StrongGrid.UnitTests.Utilities
@@ -15,10 +15,10 @@ public class StringEnumConverterTests
public void Case_insensitive(string json, CampaignStatus expectedStatus)
{
// Arrange
- var value = $"'{json}'";
+ var value = $"\"{json}\"";
// Act
- var result = JsonConvert.DeserializeObject(value);
+ var result = JsonSerializer.Deserialize(value);
// Assert
result.ShouldBe(expectedStatus);
diff --git a/Source/StrongGrid.UnitTests/Utils.cs b/Source/StrongGrid.UnitTests/Utils.cs
index 832c0d25..4283ea04 100644
--- a/Source/StrongGrid.UnitTests/Utils.cs
+++ b/Source/StrongGrid.UnitTests/Utils.cs
@@ -5,6 +5,7 @@
using StrongGrid.Utilities;
using System;
using System.Linq;
+using System.Net.Http.Formatting;
namespace StrongGrid.UnitTests
{
@@ -18,6 +19,14 @@ public static Pathoschild.Http.Client.IClient GetFluentClient(MockHttpMessageHan
var client = new FluentClient(new Uri(SENDGRID_API_BASE_URI), httpClient);
client.SetRequestCoordinator(new SendGridRetryStrategy());
client.Filters.Remove();
+
+ // Replace the built-in Json formatter
+ var defaultJsonFormatter = client.Formatters.OfType().Single();
+ client.Formatters.Remove(defaultJsonFormatter);
+ client.Formatters.Add(new JsonFormatter());
+
+ // Order is important: DiagnosticHandler must be first.
+ // Also, the list of filters must be kept in sync with the filters in BaseClient in the StrongGrid project.
client.Filters.Add(new DiagnosticHandler(LogLevel.Debug, LogLevel.Error));
client.Filters.Add(new SendGridErrorHandler());
return client;
diff --git a/Source/StrongGrid.UnitTests/WebhookParserTests.cs b/Source/StrongGrid.UnitTests/WebhookParserTests.cs
index 4f0e73bf..a5c0e336 100644
--- a/Source/StrongGrid.UnitTests/WebhookParserTests.cs
+++ b/Source/StrongGrid.UnitTests/WebhookParserTests.cs
@@ -1,12 +1,11 @@
-using Newtonsoft.Json;
using Shouldly;
using StrongGrid.Models;
using StrongGrid.Models.Webhooks;
-using StrongGrid.Utilities;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
+using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
@@ -18,164 +17,164 @@ public class WebhookParserTests
private const string PROCESSED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'pool': {
- 'name':'new_MY_test',
- 'id':210
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""pool"": {
+ ""name"":""new_MY_test"",
+ ""id"":210
},
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'processed',
- 'category':'cat facts',
- 'sg_event_id':'rbtnWrG1DVDGGGFHFyun0A==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.000000000000000000000',
- 'asm_group_id':123456
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""processed"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""rbtnWrG1DVDGGGFHFyun0A=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.000000000000000000000"",
+ ""asm_group_id"":123456
}";
private const string BOUNCED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'bounce',
- 'category':'cat facts',
- 'sg_event_id':'6g4ZI7SA-xmRDv57GoPIPw==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'reason':'500 unknown recipient',
- 'status':'5.0.0',
- 'type':'bounce'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""bounce"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""6g4ZI7SA-xmRDv57GoPIPw=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""reason"":""500 unknown recipient"",
+ ""status"":""5.0.0"",
+ ""type"":""bounce""
}";
private const string DEFERRED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'deferred',
- 'category':'cat facts',
- 'sg_event_id':'t7LEShmowp86DTdUW8M-GQ==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'response':'400 try again later',
- 'attempt':'5'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""deferred"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""t7LEShmowp86DTdUW8M-GQ=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""response"":""400 try again later"",
+ ""attempt"":""5""
}";
private const string DROPPED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'dropped',
- 'category':'cat facts',
- 'sg_event_id':'zmzJhfJgAfUSOW80yEbPyw==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'reason':'Bounced Address',
- 'status':'5.0.0'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""dropped"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""zmzJhfJgAfUSOW80yEbPyw=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""reason"":""Bounced Address"",
+ ""status"":""5.0.0""
}";
private const string BLOCKED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'bounce',
- 'category':'cat facts',
- 'sg_event_id':'6g4ZI7SA-xmRDv57GoPIPw==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'reason':'500 unknown recipient',
- 'status':'5.0.0',
- 'type':'blocked'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""bounce"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""6g4ZI7SA-xmRDv57GoPIPw=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""reason"":""500 unknown recipient"",
+ ""status"":""5.0.0"",
+ ""type"":""blocked""
}";
private const string DELIVERED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'delivered',
- 'category':'cat facts',
- 'sg_event_id':'rWVYmVk90MjZJ9iohOBa3w==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'response':'250 OK'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""delivered"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""rWVYmVk90MjZJ9iohOBa3w=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""response"":""250 OK""
}";
private const string CLICKED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'click',
- 'category':'cat facts',
- 'sg_event_id':'kCAi1KttyQdEKHhdC-nuEA==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'useragent':'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
- 'ip':'255.255.255.255',
- 'url':'http://www.sendgrid.com/'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""click"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""kCAi1KttyQdEKHhdC-nuEA=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""useragent"":""Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"",
+ ""ip"":""255.255.255.255"",
+ ""url"":""http://www.sendgrid.com/""
}";
private const string OPENED_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'open',
- 'sg_machine_open': false,
- 'category':'cat facts',
- 'sg_event_id':'FOTFFO0ecsBE-zxFXfs6WA==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'useragent':'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
- 'ip':'255.255.255.255'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""open"",
+ ""sg_machine_open"": false,
+ ""category"":""cat facts"",
+ ""sg_event_id"":""FOTFFO0ecsBE-zxFXfs6WA=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""useragent"":""Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"",
+ ""ip"":""255.255.255.255""
}";
private const string SPAMREPORT_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'spamreport',
- 'category':'cat facts',
- 'sg_event_id':'37nvH5QBz858KGVYCM4uOA==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""spamreport"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""37nvH5QBz858KGVYCM4uOA=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0""
}";
private const string UNSUBSCRIBE_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'unsubscribe',
- 'category':'cat facts',
- 'sg_event_id':'zz_BjPgU_5pS-J8vlfB1sg==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0'
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""unsubscribe"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""zz_BjPgU_5pS-J8vlfB1sg=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0""
}";
private const string GROUPUNSUBSCRIBE_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'group_unsubscribe',
- 'category':'cat facts',
- 'sg_event_id':'ahSCB7xYcXFb-hEaawsPRw==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'useragent':'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
- 'ip':'255.255.255.255',
- 'url':'http://www.sendgrid.com/',
- 'asm_group_id':10
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""group_unsubscribe"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""ahSCB7xYcXFb-hEaawsPRw=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""useragent"":""Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"",
+ ""ip"":""255.255.255.255"",
+ ""url"":""http://www.sendgrid.com/"",
+ ""asm_group_id"":10
}";
private const string GROUPRESUBSCRIBE_JSON = @"
{
- 'email':'example@test.com',
- 'timestamp':1513299569,
- 'smtp-id':'<14c5d75ce93.dfd.64b469@ismtpd-555>',
- 'event':'group_resubscribe',
- 'category':'cat facts',
- 'sg_event_id':'w_u0vJhLT-OFfprar5N93g==',
- 'sg_message_id':'14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0',
- 'useragent':'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
- 'ip':'255.255.255.255',
- 'url':'http://www.sendgrid.com/',
- 'asm_group_id':10
+ ""email"":""example@test.com"",
+ ""timestamp"":1513299569,
+ ""smtp-id"":""<14c5d75ce93.dfd.64b469@ismtpd-555>"",
+ ""event"":""group_resubscribe"",
+ ""category"":""cat facts"",
+ ""sg_event_id"":""w_u0vJhLT-OFfprar5N93g=="",
+ ""sg_message_id"":""14c5d75ce93.dfd.64b469.filter0001.16648.5515E0B88.0"",
+ ""useragent"":""Mozilla/4.0 (compatible; MSIE 6.1; Windows XP; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"",
+ ""ip"":""255.255.255.255"",
+ ""url"":""http://www.sendgrid.com/"",
+ ""asm_group_id"":10
}";
private const string INBOUND_EMAIL_WEBHOOK = @"--xYzZY
@@ -600,7 +599,7 @@ public void Parse_processed_JSON()
// Arrange
// Act
- var result = (ProcessedEvent)JsonConvert.DeserializeObject(PROCESSED_JSON, new WebHookEventConverter());
+ var result = (ProcessedEvent)JsonSerializer.Deserialize(PROCESSED_JSON);
// Assert
result.AsmGroupId.ShouldBe(123456);
@@ -626,7 +625,7 @@ public void Parse_bounced_JSON()
// Arrange
// Act
- var result = (BouncedEvent)JsonConvert.DeserializeObject(BOUNCED_JSON, new WebHookEventConverter());
+ var result = (BouncedEvent)JsonSerializer.Deserialize(BOUNCED_JSON);
// Assert
result.Categories.Length.ShouldBe(1);
@@ -639,7 +638,7 @@ public void Parse_bounced_JSON()
result.Reason.ShouldBe("500 unknown recipient");
result.SmtpId.ShouldBe("<14c5d75ce93.dfd.64b469@ismtpd-555>");
result.Status.ShouldBe("5.0.0");
- result.Type.ShouldBe(StrongGrid.Models.Webhooks.BounceType.HardBounce);
+ result.Type.ShouldBe(StrongGrid.Models.BounceType.Bounce);
result.Timestamp.ToUnixTime().ShouldBe(1513299569);
result.UniqueArguments.ShouldNotBeNull();
result.UniqueArguments.Count.ShouldBe(0);
@@ -651,7 +650,7 @@ public void Parse_deferred_JSON()
// Arrange
// Act
- var result = (DeferredEvent)JsonConvert.DeserializeObject(DEFERRED_JSON, new WebHookEventConverter());
+ var result = (DeferredEvent)JsonSerializer.Deserialize(DEFERRED_JSON);
// Assert
result.AsmGroupId.ShouldBeNull();
@@ -675,7 +674,7 @@ public void Parse_dropped_JSON()
// Arrange
// Act
- var result = (DroppedEvent)JsonConvert.DeserializeObject(DROPPED_JSON, new WebHookEventConverter());
+ var result = (DroppedEvent)JsonSerializer.Deserialize(DROPPED_JSON);
// Assert
result.Categories.Length.ShouldBe(1);
@@ -698,7 +697,7 @@ public void Parse_delivered_JSON()
// Arrange
// Act
- var result = (DeliveredEvent)JsonConvert.DeserializeObject(DELIVERED_JSON, new WebHookEventConverter());
+ var result = (DeliveredEvent)JsonSerializer.Deserialize(DELIVERED_JSON);
// Assert
result.AsmGroupId.ShouldBeNull();
@@ -722,7 +721,7 @@ public void Parse_clicked_JSON()
// Arrange
// Act
- var result = (ClickedEvent)JsonConvert.DeserializeObject(CLICKED_JSON, new WebHookEventConverter());
+ var result = (ClickedEvent)JsonSerializer.Deserialize(CLICKED_JSON);
// Assert
result.Categories.Length.ShouldBe(1);
@@ -746,7 +745,7 @@ public void Parse_opened_JSON()
// Arrange
// Act
- var result = (OpenedEvent)JsonConvert.DeserializeObject(OPENED_JSON, new WebHookEventConverter());
+ var result = (OpenedEvent)JsonSerializer.Deserialize(OPENED_JSON);
// Assert
result.Email.ShouldBe("example@test.com");
@@ -764,7 +763,7 @@ public void Parse_spamreport_JSON()
// Arrange
// Act
- var result = (SpamReportEvent)JsonConvert.DeserializeObject(SPAMREPORT_JSON, new WebHookEventConverter());
+ var result = (SpamReportEvent)JsonSerializer.Deserialize(SPAMREPORT_JSON);
// Assert
result.Email.ShouldBe("example@test.com");
@@ -780,7 +779,7 @@ public void Parse_unsubscribe_JSON()
// Arrange
// Act
- var result = (UnsubscribeEvent)JsonConvert.DeserializeObject(UNSUBSCRIBE_JSON, new WebHookEventConverter());
+ var result = (UnsubscribeEvent)JsonSerializer.Deserialize(UNSUBSCRIBE_JSON);
// Assert
result.Email.ShouldBe("example@test.com");
@@ -796,7 +795,7 @@ public void Parse_groupunsubscribe_JSON()
// Arrange
// Act
- var result = (GroupUnsubscribeEvent)JsonConvert.DeserializeObject(GROUPUNSUBSCRIBE_JSON, new WebHookEventConverter());
+ var result = (GroupUnsubscribeEvent)JsonSerializer.Deserialize(GROUPUNSUBSCRIBE_JSON);
// Assert
result.Email.ShouldBe("example@test.com");
@@ -814,7 +813,7 @@ public void Parse_groupresubscribe_JSON()
// Arrange
// Act
- var result = (GroupResubscribeEvent)JsonConvert.DeserializeObject(GROUPRESUBSCRIBE_JSON, new WebHookEventConverter());
+ var result = (GroupResubscribeEvent)JsonSerializer.Deserialize(GROUPRESUBSCRIBE_JSON);
// Assert
result.Email.ShouldBe("example@test.com");
@@ -859,6 +858,7 @@ public async Task Bounced()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(BouncedEvent));
+ result[0].EventType.ShouldBe(EventType.Bounce);
}
}
@@ -877,6 +877,7 @@ public async Task Deferred()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(DeferredEvent));
+ result[0].EventType.ShouldBe(EventType.Deferred);
}
}
@@ -895,6 +896,7 @@ public async Task Dropped()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(DroppedEvent));
+ result[0].EventType.ShouldBe(EventType.Dropped);
}
}
@@ -913,6 +915,7 @@ public async Task Clicked()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(ClickedEvent));
+ result[0].EventType.ShouldBe(EventType.Click);
}
}
@@ -931,6 +934,7 @@ public async Task Opened()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(OpenedEvent));
+ result[0].EventType.ShouldBe(EventType.Open);
}
}
@@ -949,6 +953,7 @@ public async Task Unsubscribe()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(UnsubscribeEvent));
+ result[0].EventType.ShouldBe(EventType.Unsubscribe);
}
}
@@ -967,6 +972,7 @@ public async Task GroupUnsubscribe()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(GroupUnsubscribeEvent));
+ result[0].EventType.ShouldBe(EventType.GroupUnsubscribe);
}
}
@@ -985,6 +991,7 @@ public async Task GroupResubscribe()
result.ShouldNotBeNull();
result.Length.ShouldBe(1);
result[0].GetType().ShouldBe(typeof(GroupResubscribeEvent));
+ result[0].EventType.ShouldBe(EventType.GroupResubscribe);
}
}
diff --git a/Source/StrongGrid.sln b/Source/StrongGrid.sln
index 9a3ab9ac..d0534889 100644
--- a/Source/StrongGrid.sln
+++ b/Source/StrongGrid.sln
@@ -1,13 +1,15 @@

Microsoft Visual Studio Solution File, Format Version 12.00
-# Visual Studio Version 16
-VisualStudioVersion = 16.0.28803.202
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31612.314
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid", "StrongGrid\StrongGrid.csproj", "{F4CEAECC-A03A-46C6-ACD5-18D1CD067624}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid.IntegrationTests", "StrongGrid.IntegrationTests\StrongGrid.IntegrationTests.csproj", "{818E076C-1700-4F0A-A83E-3BA6376D06B7}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid.UnitTests", "StrongGrid.UnitTests\StrongGrid.UnitTests.csproj", "{570AEC9F-D4A9-497D-B464-7F440B2B7538}"
EndProject
-Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid.UnitTests", "StrongGrid.UnitTests\StrongGrid.UnitTests.csproj", "{8C68D4FA-EE10-4E79-87F2-10A426224B9F}"
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid.IntegrationTests", "StrongGrid.IntegrationTests\StrongGrid.IntegrationTests.csproj", "{FAD1894F-C98B-479C-BCAB-A00E21DDB9C9}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StrongGrid.Benchmark", "StrongGrid.Benchmark\StrongGrid.Benchmark.csproj", "{251D652A-F466-4DD3-B178-6FDFA0041044}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@@ -19,14 +21,18 @@ Global
{F4CEAECC-A03A-46C6-ACD5-18D1CD067624}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4CEAECC-A03A-46C6-ACD5-18D1CD067624}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F4CEAECC-A03A-46C6-ACD5-18D1CD067624}.Release|Any CPU.Build.0 = Release|Any CPU
- {818E076C-1700-4F0A-A83E-3BA6376D06B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {818E076C-1700-4F0A-A83E-3BA6376D06B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {818E076C-1700-4F0A-A83E-3BA6376D06B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {818E076C-1700-4F0A-A83E-3BA6376D06B7}.Release|Any CPU.Build.0 = Release|Any CPU
- {8C68D4FA-EE10-4E79-87F2-10A426224B9F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
- {8C68D4FA-EE10-4E79-87F2-10A426224B9F}.Debug|Any CPU.Build.0 = Debug|Any CPU
- {8C68D4FA-EE10-4E79-87F2-10A426224B9F}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {8C68D4FA-EE10-4E79-87F2-10A426224B9F}.Release|Any CPU.Build.0 = Release|Any CPU
+ {570AEC9F-D4A9-497D-B464-7F440B2B7538}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {570AEC9F-D4A9-497D-B464-7F440B2B7538}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {570AEC9F-D4A9-497D-B464-7F440B2B7538}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {570AEC9F-D4A9-497D-B464-7F440B2B7538}.Release|Any CPU.Build.0 = Release|Any CPU
+ {FAD1894F-C98B-479C-BCAB-A00E21DDB9C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {FAD1894F-C98B-479C-BCAB-A00E21DDB9C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {FAD1894F-C98B-479C-BCAB-A00E21DDB9C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {FAD1894F-C98B-479C-BCAB-A00E21DDB9C9}.Release|Any CPU.Build.0 = Release|Any CPU
+ {251D652A-F466-4DD3-B178-6FDFA0041044}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {251D652A-F466-4DD3-B178-6FDFA0041044}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {251D652A-F466-4DD3-B178-6FDFA0041044}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {251D652A-F466-4DD3-B178-6FDFA0041044}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
diff --git a/Source/StrongGrid/BaseClient.cs b/Source/StrongGrid/BaseClient.cs
index 887b960a..1401b57c 100644
--- a/Source/StrongGrid/BaseClient.cs
+++ b/Source/StrongGrid/BaseClient.cs
@@ -5,7 +5,9 @@
using StrongGrid.Resources;
using StrongGrid.Utilities;
using System;
+using System.Linq;
using System.Net.Http;
+using System.Net.Http.Formatting;
using System.Reflection;
namespace StrongGrid
@@ -286,6 +288,11 @@ public BaseClient(string apiKey, HttpClient httpClient, bool disposeClient, Stro
_fluentClient.Filters.Remove();
+ // Replace the built-in Json formatter
+ var defaultJsonFormatter = _fluentClient.Formatters.OfType().Single();
+ _fluentClient.Formatters.Remove(defaultJsonFormatter);
+ _fluentClient.Formatters.Add(new JsonFormatter());
+
// Order is important: DiagnosticHandler must be first.
// Also, the list of filters must be kept in sync with the filters in Utils.GetFluentClient in the unit testing project.
_fluentClient.Filters.Add(new DiagnosticHandler(_options.LogLevelSuccessfulCalls, _options.LogLevelFailedCalls, _logger));
diff --git a/Source/StrongGrid/Extensions/Internal.cs b/Source/StrongGrid/Extensions/Internal.cs
index f8328dad..ed46737f 100644
--- a/Source/StrongGrid/Extensions/Internal.cs
+++ b/Source/StrongGrid/Extensions/Internal.cs
@@ -1,18 +1,19 @@
using HttpMultipartParser;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
using Pathoschild.Http.Client;
using StrongGrid.Models;
using StrongGrid.Utilities;
using System;
using System.Collections.Generic;
+using System.ComponentModel;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
+using System.Runtime.Serialization;
using System.Text;
+using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
@@ -72,6 +73,7 @@ internal static long ToUnixTime(this DateTime date, UnixTimePrecision precision
/// automatically calculated based on the charset in the response. Also, UTF-8
/// encoding will be used if the charset is absent from the response, is blank
/// or contains an invalid value.
+ /// The cancellation token.
/// The string content of the response.
///
/// This method is an improvement over the built-in ReadAsStringAsync method
@@ -106,7 +108,7 @@ internal static long ToUnixTime(this DateTime date, UnixTimePrecision precision
/// var responseContent = await response.Content.ReadAsStringAsync(null).ConfigureAwait(false);
///
///
- internal static async Task ReadAsStringAsync(this HttpContent httpContent, Encoding encoding)
+ internal static async Task ReadAsStringAsync(this HttpContent httpContent, Encoding encoding, CancellationToken cancellationToken = default)
{
var content = string.Empty;
@@ -120,7 +122,8 @@ internal static async Task ReadAsStringAsync(this HttpContent httpConten
// exception on subsequent attempts to read the content of the stream
using (var ms = Utils.MemoryStreamManager.GetStream())
{
- await contentStream.CopyToAsync(ms).ConfigureAwait(false);
+ const int defaultBufferSize = 81920;
+ await contentStream.CopyToAsync(ms, defaultBufferSize, cancellationToken).ConfigureAwait(false);
ms.Position = 0;
using (var sr = new StreamReader(ms, encoding))
{
@@ -196,12 +199,12 @@ internal static string GetParameterValue(this MultipartFormDataParser parser, st
/// The response.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
/// Indicates if an exception should be thrown when the specified JSON property is missing from the response.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
/// Returns the strongly typed object.
/// An error occurred processing the response.
- internal static Task AsObject(this IResponse response, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonConverter jsonConverter = null)
+ internal static Task AsObject(this IResponse response, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonSerializerOptions options = null)
{
- return response.Message.Content.AsObject(propertyName, throwIfPropertyIsMissing, jsonConverter);
+ return response.Message.Content.AsObject(propertyName, throwIfPropertyIsMissing, options);
}
/// Asynchronously retrieve the JSON encoded response body and convert it to an object of the desired type.
@@ -209,68 +212,53 @@ internal static Task AsObject(this IResponse response, string propertyName
/// The request.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
/// Indicates if an exception should be thrown when the specified JSON property is missing from the response.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
/// Returns the strongly typed object.
/// An error occurred processing the response.
- internal static async Task AsObject(this IRequest request, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonConverter jsonConverter = null)
- {
- var response = await request.AsResponse().ConfigureAwait(false);
- return await response.AsObject(propertyName, throwIfPropertyIsMissing, jsonConverter).ConfigureAwait(false);
- }
-
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
- /// An error occurred processing the response.
- internal static Task AsRawJsonObject(this IResponse response, string propertyName = null, bool throwIfPropertyIsMissing = true)
- {
- return response.Message.Content.AsRawJsonObject(propertyName, throwIfPropertyIsMissing);
- }
-
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
- /// An error occurred processing the response.
- internal static async Task AsRawJsonObject(this IRequest request, string propertyName = null, bool throwIfPropertyIsMissing = true)
+ internal static async Task AsObject(this IRequest request, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonSerializerOptions options = null)
{
var response = await request.AsResponse().ConfigureAwait(false);
- return await response.AsRawJsonObject(propertyName, throwIfPropertyIsMissing).ConfigureAwait(false);
- }
-
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
- /// An error occurred processing the response.
- internal static Task AsRawJsonArray(this IResponse response, string propertyName = null, bool throwIfPropertyIsMissing = true)
- {
- return response.Message.Content.AsRawJsonArray(propertyName, throwIfPropertyIsMissing);
- }
-
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
- /// An error occurred processing the response.
- internal static async Task AsRawJsonArray(this IRequest request, string propertyName = null, bool throwIfPropertyIsMissing = true)
- {
- var response = await request.AsResponse().ConfigureAwait(false);
- return await response.AsRawJsonArray(propertyName, throwIfPropertyIsMissing).ConfigureAwait(false);
+ return await response.AsObject(propertyName, throwIfPropertyIsMissing, options).ConfigureAwait(false);
}
/// Asynchronously retrieve the JSON encoded content and convert it to a 'PaginatedResponse' object.
/// The response model to deserialize into.
/// The response.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
/// Returns the paginated response.
/// An error occurred processing the response.
- internal static Task> AsPaginatedResponse(this IResponse response, string propertyName = null, JsonConverter jsonConverter = null)
+ internal static Task> AsPaginatedResponse(this IResponse response, string propertyName = null, JsonSerializerOptions options = null)
{
- return response.Message.Content.AsPaginatedResponse(propertyName, jsonConverter);
+ return response.Message.Content.AsPaginatedResponse(propertyName, options);
}
/// Asynchronously retrieve the JSON encoded content and convert it to a 'PaginatedResponse' object.
/// The response model to deserialize into.
/// The request.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
/// Returns the paginated response.
/// An error occurred processing the response.
- internal static async Task> AsPaginatedResponse(this IRequest request, string propertyName = null, JsonConverter jsonConverter = null)
+ internal static async Task> AsPaginatedResponse(this IRequest request, string propertyName = null, JsonSerializerOptions options = null)
{
var response = await request.AsResponse().ConfigureAwait(false);
- return await response.AsPaginatedResponse(propertyName, jsonConverter).ConfigureAwait(false);
+ return await response.AsPaginatedResponse(propertyName, options).ConfigureAwait(false);
+ }
+
+ /// Get a raw JSON document representation of the response.
+ /// An error occurred processing the response.
+ internal static Task AsRawJsonDocument(this IResponse response, string propertyName = null, bool throwIfPropertyIsMissing = true)
+ {
+ return response.Message.Content.AsRawJsonDocument(propertyName, throwIfPropertyIsMissing);
+ }
+
+ /// Get a raw JSON document representation of the response.
+ /// An error occurred processing the response.
+ internal static async Task AsRawJsonDocument(this IRequest request, string propertyName = null, bool throwIfPropertyIsMissing = true)
+ {
+ var response = await request.AsResponse().ConfigureAwait(false);
+ return await response.AsRawJsonDocument(propertyName, throwIfPropertyIsMissing).ConfigureAwait(false);
}
/// Set the body content of the HTTP request.
@@ -421,109 +409,6 @@ internal static async Task GetCurrentScopes(this Pathoschild.Http.Clie
return scopes;
}
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, string value)
- {
- if (string.IsNullOrEmpty(value)) return;
- jsonObject.AddDeepProperty(propertyName, value);
- }
-
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, T value, JsonConverter converter = null)
- {
- if (EqualityComparer.Default.Equals(value, default)) return;
-
- var jsonSerializer = new JsonSerializer();
- if (converter != null)
- {
- jsonSerializer.Converters.Add(converter);
- }
-
- jsonObject.AddDeepProperty(propertyName, JToken.FromObject(value, jsonSerializer));
- }
-
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, IEnumerable value, JsonConverter converter = null)
- {
- if (value == null || !value.Any()) return;
-
- var jsonSerializer = new JsonSerializer();
- if (converter != null)
- {
- jsonSerializer.Converters.Add(converter);
- }
-
- jsonObject.AddDeepProperty(propertyName, JArray.FromObject(value.ToArray(), jsonSerializer));
- }
-
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, Parameter parameter, JsonConverter converter = null)
- {
- var jsonSerializer = new JsonSerializer();
- if (converter != null)
- {
- jsonSerializer.Converters.Add(converter);
- }
-
- AddPropertyIfValue(jsonObject, propertyName, parameter, value => JToken.FromObject(value, jsonSerializer));
- }
-
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, Parameter> parameter, JsonConverter converter = null)
- {
- var jsonSerializer = new JsonSerializer();
- if (converter != null)
- {
- jsonSerializer.Converters.Add(converter);
- }
-
- AddPropertyIfValue(jsonObject, propertyName, parameter, value => JArray.FromObject(value.ToArray(), jsonSerializer));
- }
-
- internal static void AddPropertyIfEnumValue(this JObject jsonObject, string propertyName, Parameter parameter, JsonConverter converter = null)
- {
- var jsonSerializer = new JsonSerializer();
- if (converter != null)
- {
- jsonSerializer.Converters.Add(converter);
- }
-
- AddPropertyIfValue(jsonObject, propertyName, parameter, value => JToken.Parse(JsonConvert.SerializeObject(value)).ToString());
- }
-
- internal static void AddPropertyIfValue(this JObject jsonObject, string propertyName, Parameter parameter, Func convertValueToJsonToken)
- {
- if (convertValueToJsonToken == null) throw new ArgumentNullException(nameof(convertValueToJsonToken));
- if (!parameter.HasValue) return;
-
- jsonObject.AddDeepProperty(propertyName, parameter.Value == null ? null : convertValueToJsonToken(parameter.Value));
- }
-
- internal static void AddDeepProperty(this JObject jsonObject, string propertyName, JToken value)
- {
- var separatorLocation = propertyName.IndexOf('/');
-
- if (separatorLocation == -1)
- {
- jsonObject.Add(propertyName, value);
- }
- else
- {
- var name = propertyName.Substring(0, separatorLocation);
- var childrenName = propertyName.Substring(separatorLocation + 1);
-
- var property = jsonObject.Value(name);
- if (property == null)
- {
- property = new JObject();
- jsonObject.Add(name, property);
- }
-
- property.AddDeepProperty(childrenName, value);
- }
- }
-
- internal static T GetPropertyValue(this JToken item, string name, T defaultValue = default)
- {
- if (item[name] == null) return defaultValue;
- return item[name].Value();
- }
-
internal static async Task ForEachAsync(this IEnumerable items, Func> action, int maxDegreeOfParalellism)
{
var allTasks = new List>();
@@ -680,6 +565,54 @@ internal static async Task CompressAsync(this Stream source)
return compressedStream;
}
+ /// Convert an enum to its string representation.
+ /// The enum type.
+ /// The value.
+ /// The string representation of the enum value.
+ /// Inspired by: https://stackoverflow.com/questions/10418651/using-enummemberattribute-and-doing-automatic-string-conversions .
+ internal static string ToEnumString(this T enumValue)
+ where T : Enum
+ {
+ var enumMemberAttribute = enumValue.GetAttributeOfType();
+ if (enumMemberAttribute != null) return enumMemberAttribute.Value;
+
+ var descriptionAttribute = enumValue.GetAttributeOfType();
+ if (descriptionAttribute != null) return descriptionAttribute.Description;
+
+ return enumValue.ToString();
+ }
+
+ /// Parses a string into its corresponding enum value.
+ /// The enum type.
+ /// The string value.
+ /// The enum representayionm of the string value.
+ /// Inspired by: https://stackoverflow.com/questions/10418651/using-enummemberattribute-and-doing-automatic-string-conversions .
+ internal static T ToEnum(this string str)
+ where T : Enum
+ {
+ var enumType = typeof(T);
+ foreach (var name in Enum.GetNames(enumType))
+ {
+ // See if there's a matching 'EnumMember' attribute
+ var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).SingleOrDefault();
+ if (enumMemberAttribute != null && string.Equals(enumMemberAttribute.Value, str, StringComparison.OrdinalIgnoreCase)) return (T)Enum.Parse(enumType, name);
+
+ // See if there's a matching 'Description' attribute
+ var descriptionAttribute = ((DescriptionAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(DescriptionAttribute), true)).SingleOrDefault();
+ if (descriptionAttribute != null && string.Equals(descriptionAttribute.Description, str, StringComparison.OrdinalIgnoreCase)) return (T)Enum.Parse(enumType, name);
+
+ // See if the value matches the name
+ if (string.Equals(name, str, StringComparison.OrdinalIgnoreCase)) return (T)Enum.Parse(enumType, name);
+ }
+
+ throw new ArgumentException($"There is no value in the {enumType.Name} enum that corresponds to '{str}'.");
+ }
+
+ internal static T ToObject(this JsonElement element, JsonSerializerOptions options = null)
+ {
+ return JsonSerializer.Deserialize(element.GetRawText(), options);
+ }
+
private static async Task<(bool, string)> GetErrorMessage(HttpResponseMessage message)
{
// Assume there is no error
@@ -735,23 +668,26 @@ internal static async Task CompressAsync(this Stream source)
{
try
{
+ var jsonContent = JsonDocument.Parse(responseContent);
+ var foundErrors = jsonContent.RootElement.TryGetProperty("errors", out JsonElement jsonErrors);
+ var foundError = jsonContent.RootElement.TryGetProperty("error", out JsonElement jsonError);
+
// Check for the presence of property called 'errors'
- var jObject = JObject.Parse(responseContent);
- var errorsArray = (JArray)jObject["errors"];
- if (errorsArray != null && errorsArray.Count > 0)
+ if (foundErrors && jsonErrors.ValueKind == JsonValueKind.Array)
{
- errorMessage = string.Join(Environment.NewLine, errorsArray.Select(error => error["message"].Value()));
+ var errors = jsonErrors.EnumerateArray()
+ .Select(jsonElement => jsonElement.GetProperty("message").GetString())
+ .ToArray();
+
+ errorMessage = string.Join(Environment.NewLine, errors);
isError = true;
}
- else
+
+ // Check for the presence of property called 'error'
+ else if (foundError)
{
- // Check for the presence of property called 'error'
- var errorProperty = jObject["error"];
- if (errorProperty != null)
- {
- errorMessage = errorProperty.Value();
- isError = true;
- }
+ errorMessage = jsonError.GetString();
+ isError = true;
}
}
catch
@@ -768,109 +704,65 @@ internal static async Task CompressAsync(this Stream source)
/// The content.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
/// Indicates if an exception should be thrown when the specified JSON property is missing from the response.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
+ /// The cancellation token.
/// Returns the strongly typed object.
/// An error occurred processing the response.
- private static async Task AsObject(this HttpContent httpContent, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonConverter jsonConverter = null)
+ private static async Task AsObject(this HttpContent httpContent, string propertyName = null, bool throwIfPropertyIsMissing = true, JsonSerializerOptions options = null, CancellationToken cancellationToken = default)
{
var responseContent = await httpContent.ReadAsStringAsync(null).ConfigureAwait(false);
- var serializer = new JsonSerializer();
- if (jsonConverter != null) serializer.Converters.Add(jsonConverter);
-
- if (!string.IsNullOrEmpty(propertyName))
+ if (string.IsNullOrEmpty(propertyName))
{
- var jObject = JObject.Parse(responseContent);
- var jProperty = jObject.Property(propertyName);
- if (jProperty == null)
- {
- if (throwIfPropertyIsMissing)
- {
- throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
- }
- else
- {
- return default;
- }
- }
+ return JsonSerializer.Deserialize(responseContent, options);
+ }
- return jProperty.Value.ToObject(serializer);
+ var jsonDoc = JsonDocument.Parse(responseContent, (JsonDocumentOptions)default);
+ if (jsonDoc.RootElement.TryGetProperty(propertyName, out JsonElement property))
+ {
+ var propertyContent = property.GetRawText();
+ return JsonSerializer.Deserialize(propertyContent, options);
}
- else if (typeof(T).IsArray)
+ else if (throwIfPropertyIsMissing)
{
- return JArray.Parse(responseContent).ToObject(serializer);
+ throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
}
else
{
- return JObject.Parse(responseContent).ToObject(serializer);
+ return default;
}
}
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
+ /// Get a raw JSON object representation of the response.
/// The content.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
/// Indicates if an exception should be thrown when the specified JSON property is missing from the response.
+ /// The cancellation token.
/// Returns the response body, or null if the response has no body.
/// An error occurred processing the response.
- private static async Task AsRawJsonObject(this HttpContent httpContent, string propertyName = null, bool throwIfPropertyIsMissing = true)
+ private static async Task AsRawJsonDocument(this HttpContent httpContent, string propertyName = null, bool throwIfPropertyIsMissing = true, CancellationToken cancellationToken = default)
{
- var responseContent = await httpContent.ReadAsStringAsync(null).ConfigureAwait(false);
+ var responseContent = await httpContent.ReadAsStringAsync(null, cancellationToken).ConfigureAwait(false);
- if (!string.IsNullOrEmpty(propertyName))
- {
- var jObject = JObject.Parse(responseContent);
- var jProperty = jObject.Property(propertyName);
- if (jProperty == null)
- {
- if (throwIfPropertyIsMissing)
- {
- throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
- }
- else
- {
- return default;
- }
- }
+ var jsonDoc = JsonDocument.Parse(responseContent, (JsonDocumentOptions)default);
- return (JObject)jProperty.Value;
- }
- else
+ if (string.IsNullOrEmpty(propertyName))
{
- return JObject.Parse(responseContent);
+ return jsonDoc;
}
- }
-
- /// Get a raw JSON object representation of the response, which can also be accessed as a dynamic value.
- /// The content.
- /// The name of the JSON property (or null if not applicable) where the desired data is stored.
- /// Indicates if an exception should be thrown when the specified JSON property is missing from the response.
- /// Returns the response body, or null if the response has no body.
- /// An error occurred processing the response.
- private static async Task AsRawJsonArray(this HttpContent httpContent, string propertyName = null, bool throwIfPropertyIsMissing = true)
- {
- var responseContent = await httpContent.ReadAsStringAsync(null).ConfigureAwait(false);
- if (!string.IsNullOrEmpty(propertyName))
+ if (jsonDoc.RootElement.TryGetProperty(propertyName, out JsonElement property))
{
- var jObject = JObject.Parse(responseContent);
- var jProperty = jObject.Property(propertyName);
- if (jProperty == null)
- {
- if (throwIfPropertyIsMissing)
- {
- throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
- }
- else
- {
- return default;
- }
- }
-
- return (JArray)jProperty.Value;
+ var propertyContent = property.GetRawText();
+ return JsonDocument.Parse(propertyContent, (JsonDocumentOptions)default);
+ }
+ else if (throwIfPropertyIsMissing)
+ {
+ throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
}
else
{
- return JArray.Parse(responseContent);
+ return default;
}
}
@@ -878,21 +770,17 @@ private static async Task AsRawJsonArray(this HttpContent httpContent, s
/// The response model to deserialize into.
/// The content.
/// The name of the JSON property (or null if not applicable) where the desired data is stored.
- /// Converter that will be used during deserialization.
+ /// Options to control behavior Converter during parsing.
+ /// The cancellation token.
/// Returns the response body, or null if the response has no body.
/// An error occurred processing the response.
- private static async Task> AsPaginatedResponse(this HttpContent httpContent, string propertyName, JsonConverter jsonConverter = null)
+ private static async Task> AsPaginatedResponse(this HttpContent httpContent, string propertyName, JsonSerializerOptions options = null, CancellationToken cancellationToken = default)
{
- var responseContent = await httpContent.ReadAsStringAsync(null).ConfigureAwait(false);
- var jObject = JObject.Parse(responseContent);
-
- var metadata = jObject.Property("_metadata").Value.ToObject();
-
- var serializer = new JsonSerializer();
- if (jsonConverter != null) serializer.Converters.Add(jsonConverter);
+ var jsonDocument = await httpContent.AsRawJsonDocument(null, false, cancellationToken).ConfigureAwait(false);
+ var metadataProperty = jsonDocument.RootElement.GetProperty("_metadata");
+ var metadata = JsonSerializer.Deserialize(metadataProperty.GetRawText(), options);
- var jProperty = jObject.Property(propertyName);
- if (jProperty == null)
+ if (!jsonDocument.RootElement.TryGetProperty(propertyName, out JsonElement jProperty))
{
throw new ArgumentException($"The response does not contain a field called '{propertyName}'", nameof(propertyName));
}
@@ -903,7 +791,7 @@ private static async Task> AsPaginatedResponse(this Http
CurrentPageToken = metadata.SelfToken,
NextPageToken = metadata.NextToken,
TotalRecords = metadata.Count,
- Records = jProperty.Value?.ToObject(serializer) ?? Array.Empty()
+ Records = JsonSerializer.Deserialize(jProperty.GetRawText(), options)
};
return result;
diff --git a/Source/StrongGrid/Models/AccessEntry.cs b/Source/StrongGrid/Models/AccessEntry.cs
index 8b6273f4..13a2c643 100644
--- a/Source/StrongGrid/Models/AccessEntry.cs
+++ b/Source/StrongGrid/Models/AccessEntry.cs
@@ -1,6 +1,6 @@
-using Newtonsoft.Json;
using StrongGrid.Utilities;
using System;
+using System.Text.Json.Serialization;
namespace StrongGrid.Models
{
@@ -15,7 +15,7 @@ public class AccessEntry
///
/// true if access was granted; otherwise, false.
///
- [JsonProperty("allowed", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("allowed")]
public bool Allowed { get; set; }
///
@@ -24,7 +24,7 @@ public class AccessEntry
///
/// The authorization method.
///
- [JsonProperty("auth_method", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("auth_method")]
public string AuthorizationMethod { get; set; }
///
@@ -33,7 +33,7 @@ public class AccessEntry
///
/// The date.
///
- [JsonProperty("first_at", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("first_at")]
[JsonConverter(typeof(EpochConverter))]
public DateTime FirstAccessOn { get; set; }
@@ -43,7 +43,7 @@ public class AccessEntry
///
/// The ip address.
///
- [JsonProperty("ip", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("ip")]
public string IpAddress { get; set; }
///
@@ -52,7 +52,7 @@ public class AccessEntry
///
/// The user name.
///
- [JsonProperty("last_at", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("last_at")]
[JsonConverter(typeof(EpochConverter))]
public DateTime LatestAccessOn { get; set; }
@@ -62,7 +62,7 @@ public class AccessEntry
///
/// The location.
///
- [JsonProperty("location", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("location")]
public string Location { get; set; }
}
}
diff --git a/Source/StrongGrid/Models/AccessRequest.cs b/Source/StrongGrid/Models/AccessRequest.cs
index d5682362..e30172b1 100644
--- a/Source/StrongGrid/Models/AccessRequest.cs
+++ b/Source/StrongGrid/Models/AccessRequest.cs
@@ -1,4 +1,4 @@
-using Newtonsoft.Json;
+using System.Text.Json.Serialization;
namespace StrongGrid.Models
{
@@ -13,7 +13,7 @@ public class AccessRequest
///
/// The identifier.
///
- [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("id")]
public long Id { get; set; }
///
@@ -22,7 +22,7 @@ public class AccessRequest
///
/// The scope.
///
- [JsonProperty("scope_group_name", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("scope_group_name")]
public string ScopeGroupName { get; set; }
///
@@ -31,7 +31,7 @@ public class AccessRequest
///
/// The user name.
///
- [JsonProperty("username", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("username")]
public string Username { get; set; }
///
@@ -40,7 +40,7 @@ public class AccessRequest
///
/// The email.
///
- [JsonProperty("email", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("email")]
public string Email { get; set; }
///
@@ -49,7 +49,7 @@ public class AccessRequest
///
/// The first name.
///
- [JsonProperty("first_name", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("first_name")]
public string FirstName { get; set; }
///
@@ -58,7 +58,7 @@ public class AccessRequest
///
/// The last name.
///
- [JsonProperty("lastname", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("lastname")]
public string LastName { get; set; }
}
}
diff --git a/Source/StrongGrid/Models/Account.cs b/Source/StrongGrid/Models/Account.cs
index ab15ef41..2c9bf168 100644
--- a/Source/StrongGrid/Models/Account.cs
+++ b/Source/StrongGrid/Models/Account.cs
@@ -1,4 +1,4 @@
-using Newtonsoft.Json;
+using System.Text.Json.Serialization;
namespace StrongGrid.Models
{
@@ -13,7 +13,7 @@ public class Account
///
/// The type.
///
- [JsonProperty("type", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("type")]
public string Type { get; set; }
///
@@ -22,7 +22,7 @@ public class Account
///
/// The reputation.
///
- [JsonProperty("reputation", NullValueHandling = NullValueHandling.Ignore)]
+ [JsonPropertyName("reputation")]
public float Reputation { get; set; }
}
}
diff --git a/Source/StrongGrid/Models/AddIpAddressResult.cs b/Source/StrongGrid/Models/AddIpAddressResult.cs
index 37dc59c7..fab5d463 100644
--- a/Source/StrongGrid/Models/AddIpAddressResult.cs
+++ b/Source/StrongGrid/Models/AddIpAddressResult.cs
@@ -1,4 +1,4 @@
-using Newtonsoft.Json;
+using System.Text.Json.Serialization;
namespace StrongGrid.Models
{
@@ -17,7 +17,7 @@ public class AddIpAddressResult
///
/// An array of