Skip to content

Commit 1410006

Browse files
Merge branch 'v3_beta' of https://github.com/sendgrid/sendgrid-csharp into v3_beta
2 parents b8f4179 + dea88a1 commit 1410006

File tree

10 files changed

+226
-150
lines changed

10 files changed

+226
-150
lines changed

SendGrid/Example/Program.cs

Lines changed: 74 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -4,87 +4,104 @@
44
using System.Net.Http;
55
using System.Net.Mail;
66
using Newtonsoft.Json.Linq;
7-
using SendGrid.Resources;
87

98
namespace Example
109
{
11-
internal class Program
12-
{
13-
// this code is used for the SMTPAPI examples
14-
private static void Main()
15-
{
10+
internal class Program
11+
{
12+
private static void Main()
13+
{
14+
// Test sending email
15+
var to = "[email protected]";
16+
var from = "[email protected]";
17+
var fromName = "Jane Doe";
18+
SendEmail(to, from, fromName);
19+
// Test viewing, creating, modifying and deleting API keys through our v3 Web API
20+
ApiKeys();
21+
}
22+
23+
private static void SendAsync(SendGrid.SendGridMessage message)
24+
{
25+
// Create credentials, specifying your user Name and password.
26+
var username = Environment.GetEnvironmentVariable("SENDGRID_USERNAME");
27+
var password = Environment.GetEnvironmentVariable("SENDGRID_PASSWORD");
28+
//string apikey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
29+
var credentials = new NetworkCredential(username, password);
30+
31+
// Create a Web transport for sending email.
32+
var transportWeb = new SendGrid.Web(credentials);
33+
//var transportWeb2 = new SendGrid.Web(apikey);
34+
35+
// Send the email.
36+
try
37+
{
38+
transportWeb.DeliverAsync(message).Wait();
39+
Console.WriteLine("Email sent to " + message.To.GetValue(0));
40+
Console.WriteLine("Press any key to continue.");
41+
Console.ReadKey();
42+
}
43+
catch (Exception ex)
44+
{
45+
Console.WriteLine(ex.Message);
46+
Console.WriteLine("Press any key to continue.");
47+
Console.ReadKey();
48+
}
49+
}
50+
51+
private static void SendEmail(string to, string from, string fromName)
52+
{
53+
// Create the email object first, then add the properties.
54+
var myMessage = new SendGrid.SendGridMessage();
55+
myMessage.AddTo(to);
56+
myMessage.From = new MailAddress(from, fromName);
57+
myMessage.Subject = "Testing the SendGrid Library";
58+
myMessage.Text = "Hello World! %tag%";
59+
60+
var subs = new List<String> { "私は%type%ラーメンが大好き" };
61+
myMessage.AddSubstitution("%tag%", subs);
62+
myMessage.AddSection("%type%", "とんこつ");
63+
64+
SendAsync(myMessage);
65+
}
66+
67+
private static void ApiKeys()
68+
{
1669
String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
1770
var client = new SendGrid.Client(apiKey);
18-
string _api_key_id;
1971

20-
// GET
21-
HttpResponseMessage responseGet = client.ApiKeys.Get();
72+
// GET API KEYS
73+
HttpResponseMessage responseGet = client.ApiKeys.Get().Result;
2274
Console.WriteLine(responseGet.StatusCode);
2375
Console.WriteLine(responseGet.Content.ReadAsStringAsync().Result);
2476
Console.WriteLine("These are your current API Keys. Press any key to continue.");
2577
Console.ReadKey();
26-
27-
// POST
28-
HttpResponseMessage responsePost = client.ApiKeys.Post("CSharpTestKey");
29-
string rawString = responsePost.Content.ReadAsStringAsync().Result;
78+
79+
// POST API KEYS
80+
HttpResponseMessage responsePost = client.ApiKeys.Post("CSharpTestKey").Result;
81+
var rawString = responsePost.Content.ReadAsStringAsync().Result;
3082
dynamic jsonObject = JObject.Parse(rawString);
31-
_api_key_id = jsonObject.api_key_id.ToString();
83+
var apiKeyId = jsonObject.api_key_id.ToString();
3284
Console.WriteLine(responsePost.StatusCode);
3385
Console.WriteLine(responsePost.Content.ReadAsStringAsync().Result);
3486
Console.WriteLine("API Key created. Press any key to continue.");
3587
Console.ReadKey();
3688

37-
// PATCH
38-
HttpResponseMessage responsePatch = client.ApiKeys.Patch(_api_key_id, "CSharpTestKeyPatched");
89+
// PATCH API KEYS
90+
HttpResponseMessage responsePatch = client.ApiKeys.Patch(apiKeyId, "CSharpTestKeyPatched").Result;
3991
Console.WriteLine(responsePatch.StatusCode);
4092
Console.WriteLine(responsePatch.Content.ReadAsStringAsync().Result);
4193
Console.WriteLine("API Key patched. Press any key to continue.");
4294
Console.ReadKey();
4395

44-
// DELETE
96+
// DELETE API KEYS
4597
Console.WriteLine("Deleting API Key, please wait.");
46-
client.ApiKeys.Delete(_api_key_id);
47-
HttpResponseMessage responseFinal = client.ApiKeys.Get();
98+
HttpResponseMessage responseDelete = client.ApiKeys.Delete(apiKeyId).Result;
99+
Console.WriteLine(responseDelete.StatusCode);
100+
HttpResponseMessage responseFinal = client.ApiKeys.Get().Result;
48101
Console.WriteLine(responseFinal.StatusCode);
49102
Console.WriteLine(responseFinal.Content.ReadAsStringAsync().Result);
50103
Console.WriteLine("API Key Deleted, press any key to end");
51104
Console.ReadKey();
52-
53-
// SEND EMAIL
54-
/*
55-
// Create the email object first, then add the properties.
56-
var myMessage = new SendGrid.SendGridMessage();
57-
myMessage.AddTo("[email protected]");
58-
myMessage.From = new MailAddress("[email protected]", "Elmer Thomas");
59-
myMessage.Subject = "Testing the SendGrid Library";
60-
myMessage.Text = "Hello World! %tag%";
61-
62-
var subs = new List<String> { "私は%type%ラーメンが大好き" };
63-
myMessage.AddSubstitution("%tag%",subs);
64-
myMessage.AddSection("%type%", "とんこつ");
65-
66-
SendAsync(myMessage);
67-
*/
68105
}
69-
70-
private static async void SendAsync(SendGrid.SendGridMessage message)
71-
{
72-
// Create credentials, specifying your user name and password.
73-
var credentials = new NetworkCredential("<sendgrid_username>", "<sendgrid_password>");
74-
75-
// Create a Web transport for sending email.
76-
var transportWeb = new SendGrid.Web(credentials);
77-
78-
// Send the email.
79-
try
80-
{
81-
await transportWeb.DeliverAsync(message);
82-
Console.WriteLine("Sent!");
83-
}
84-
catch (Exception ex)
85-
{
86-
Console.WriteLine(ex.Message);
87-
}
88-
}
89-
}
90-
}
106+
}
107+
}

SendGrid/SendGrid.sln

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -62,36 +62,36 @@ Global
6262
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.Release|x86.ActiveCfg = Release|Any CPU
6363
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Any CPU.ActiveCfg = BuildNet45|Any CPU
6464
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Any CPU.Build.0 = BuildNet45|Any CPU
65-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.ActiveCfg = Debug|Any CPU
66-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.Build.0 = Debug|Any CPU
65+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
66+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.Build.0 = BuildNet45|Any CPU
6767
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|x86.ActiveCfg = BuildNet45|Any CPU
6868
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|x86.Build.0 = BuildNet45|Any CPU
6969
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Any CPU.ActiveCfg = BuildNet45|Any CPU
7070
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Any CPU.Build.0 = BuildNet45|Any CPU
71-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
72-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
71+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
72+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.Build.0 = BuildNet45|Any CPU
7373
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|x86.ActiveCfg = Debug|Any CPU
7474
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
7575
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Any CPU.Build.0 = Release|Any CPU
76-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.ActiveCfg = Debug|Any CPU
77-
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.Build.0 = Debug|Any CPU
76+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
77+
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.Build.0 = BuildNet45|Any CPU
7878
{3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|x86.ActiveCfg = Release|Any CPU
7979
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Any CPU.ActiveCfg = Release|Any CPU
8080
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Any CPU.Build.0 = Release|Any CPU
81-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Mixed Platforms.ActiveCfg = Debug|Any CPU
82-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Mixed Platforms.Build.0 = Debug|Any CPU
81+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Mixed Platforms.ActiveCfg = Release|Any CPU
82+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Mixed Platforms.Build.0 = Release|Any CPU
8383
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|x86.ActiveCfg = Release|Any CPU
8484
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|x86.Build.0 = Release|Any CPU
8585
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
8686
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Any CPU.Build.0 = Debug|Any CPU
87-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
88-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
87+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Mixed Platforms.ActiveCfg = Release|Any CPU
88+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|Mixed Platforms.Build.0 = Release|Any CPU
8989
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|x86.ActiveCfg = Debug|Any CPU
9090
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Debug|x86.Build.0 = Debug|Any CPU
9191
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Any CPU.ActiveCfg = Release|Any CPU
9292
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Any CPU.Build.0 = Release|Any CPU
93-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Mixed Platforms.ActiveCfg = Debug|Any CPU
94-
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Mixed Platforms.Build.0 = Debug|Any CPU
93+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
94+
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|Mixed Platforms.Build.0 = Release|Any CPU
9595
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|x86.ActiveCfg = Release|Any CPU
9696
{1C318867-440B-4EB9-99E3-C0CC2C556962}.Release|x86.Build.0 = Release|Any CPU
9797
{8A66032B-0D1C-4F24-B0E3-A250F31D09D8}.BuildNet45|Any CPU.ActiveCfg = Release|Any CPU

SendGrid/SendGrid/Client.cs

Lines changed: 48 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,33 @@
55
using System.Threading.Tasks;
66
using System.Text;
77
using SendGrid.Resources;
8-
using System.Web.Script.Serialization;
98
using System.Net;
9+
using Newtonsoft.Json.Linq;
1010

1111
namespace SendGrid
1212
{
1313
public class Client
1414
{
15-
private HttpResponseMessage _response = new HttpResponseMessage();
1615
private string _apiKey;
17-
private Uri _baseUri;
1816
public APIKeys ApiKeys;
17+
public string Version;
18+
private Uri _baseUri;
19+
private const string MediaType = "application/json";
20+
private enum Methods
21+
{
22+
GET, POST, PATCH, DELETE
23+
}
1924

2025
/// <summary>
21-
/// Create a client that connects to the SendGrid Web API
22-
/// </summary>
23-
/// <param name="apiKey">Your SendGrid API Key</param>
24-
/// <param name="baseUri">Base SendGrid API Uri</param>
26+
/// Create a client that connects to the SendGrid Web API
27+
/// </summary>
28+
/// <param name="apiKey">Your SendGrid API Key</param>
29+
/// <param name="baseUri">Base SendGrid API Uri</param>
2530
public Client(string apiKey, string baseUri = "https://api.sendgrid.com/")
2631
{
2732
_baseUri = new Uri(baseUri);
2833
_apiKey = apiKey;
34+
Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
2935
ApiKeys = new APIKeys(this);
3036
}
3137

@@ -34,96 +40,86 @@ public Client(string apiKey, string baseUri = "https://api.sendgrid.com/")
3440
/// </summary>
3541
/// <param name="method">HTTP verb, case-insensitive</param>
3642
/// <param name="endpoint">Resource endpoint, do not prepend slash</param>
37-
/// <param name="data">An object representing the resource's data</param>
43+
/// <param name="data">An JObject representing the resource's data</param>
3844
/// <returns>An asyncronous task</returns>
39-
private async Task RequestAsync(string method, string endpoint, Object data)
45+
private async Task<HttpResponseMessage> RequestAsync(Methods method, string endpoint, JObject data)
4046
{
4147
using (var client = new HttpClient())
4248
{
4349
try
4450
{
4551
client.BaseAddress = _baseUri;
4652
client.DefaultRequestHeaders.Accept.Clear();
47-
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
53+
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType));
4854
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
49-
var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
50-
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");
55+
client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + Version + ";csharp");
5156

52-
switch (method.ToLower())
57+
switch (method)
5358
{
54-
case "get":
55-
_response = await client.GetAsync(endpoint);
56-
break;
57-
case "post":
58-
_response = await client.PostAsJsonAsync(endpoint, data);
59-
break;
60-
case "patch":
59+
case Methods.GET:
60+
return await client.GetAsync(endpoint);
61+
case Methods.POST:
62+
return await client.PostAsJsonAsync(endpoint, data);
63+
case Methods.PATCH:
6164
endpoint = _baseUri + endpoint;
62-
StringContent content = new StringContent(data.ToString(), Encoding.UTF8, "application/json");
65+
StringContent content = new StringContent(data.ToString(), Encoding.UTF8, MediaType);
6366
HttpRequestMessage request = new HttpRequestMessage
6467
{
6568
Method = new HttpMethod("PATCH"),
6669
RequestUri = new Uri(endpoint),
6770
Content = content
6871
};
69-
_response = await client.SendAsync(request);
70-
break;
71-
case "delete":
72-
_response = await client.DeleteAsync(endpoint);
73-
break;
72+
return await client.SendAsync(request);
73+
case Methods.DELETE:
74+
return await client.DeleteAsync(endpoint);
7475
default:
75-
_response.StatusCode = HttpStatusCode.MethodNotAllowed;
76-
_response.Content = new StringContent("Bad method call: " + method);
77-
break;
76+
HttpResponseMessage response = new HttpResponseMessage();
77+
response.StatusCode = HttpStatusCode.MethodNotAllowed;
78+
var message = "{\"errors\":[{\"message\":\"Bad method call, supported methods are GET, POST, PATCH and DELETE\"}]}";
79+
response.Content = new StringContent(message);
80+
return response;
7881
}
7982
}
80-
catch (HttpRequestException hre)
81-
{
82-
_response.StatusCode = HttpStatusCode.InternalServerError;
83-
_response.Content = new StringContent(hre.ToString());
84-
}
8583
catch (Exception ex)
8684
{
87-
_response.StatusCode = HttpStatusCode.InternalServerError;
88-
_response.Content = new StringContent(ex.ToString());
85+
HttpResponseMessage response = new HttpResponseMessage();
86+
string message;
87+
message = (ex is HttpRequestException) ? ".NET HttpRequestException" : ".NET Exception";
88+
message = message + ", raw message: \n\n";
89+
response.Content = new StringContent(message + ex.Message);
90+
return response;
8991
}
9092
}
9193
}
9294

9395
/// <param name="endpoint">Resource endpoint, do not prepend slash</param>
9496
/// <returns>The resulting message from the API call</returns>
95-
public HttpResponseMessage Get(string endpoint)
97+
public async Task<HttpResponseMessage> Get(string endpoint)
9698
{
97-
RequestAsync("GET", endpoint, null).Wait();
98-
return _response;
99+
return await RequestAsync(Methods.GET, endpoint, null);
99100
}
100101

101102
/// <param name="endpoint">Resource endpoint, do not prepend slash</param>
102-
/// <param name="data">An object representing the resource's data</param>
103+
/// <param name="data">An JObject representing the resource's data</param>
103104
/// <returns>The resulting message from the API call</returns>
104-
public HttpResponseMessage Post(string endpoint, object data)
105+
public async Task<HttpResponseMessage> Post(string endpoint, JObject data)
105106
{
106-
RequestAsync("POST", endpoint, data).Wait();
107-
return _response;
107+
return await RequestAsync(Methods.POST, endpoint, data);
108108
}
109109

110110
/// <param name="endpoint">Resource endpoint, do not prepend slash</param>
111111
/// <returns>The resulting message from the API call</returns>
112-
public HttpResponseMessage Delete(string endpoint)
112+
public async Task<HttpResponseMessage> Delete(string endpoint)
113113
{
114-
RequestAsync("DELETE", endpoint, null).Wait();
115-
return _response;
114+
return await RequestAsync(Methods.DELETE, endpoint, null);
116115
}
117116

118117
/// <param name="endpoint">Resource endpoint, do not prepend slash</param>
119-
/// <param name="data">An object representing the resource's data</param>
118+
/// <param name="data">An JObject representing the resource's data</param>
120119
/// <returns>The resulting message from the API call</returns>
121-
public HttpResponseMessage Patch(string endpoint, object data)
120+
public async Task<HttpResponseMessage> Patch(string endpoint, JObject data)
122121
{
123-
var json = new JavaScriptSerializer().Serialize(data);
124-
RequestAsync("PATCH", endpoint, json).Wait();
125-
return _response;
122+
return await RequestAsync(Methods.PATCH, endpoint, data);
126123
}
127-
128124
}
129125
}

0 commit comments

Comments
 (0)