We Are Hiring

Using SendGrid with Visual Studio 2013 Preview for Windows 8.1 Development


Posted on

SendGrid is attending the VSIP Summit in Redmond, WA this week as proud Visual Studio partners. Our goal is to learn as much as we can about the Visual Studio community in order to better serve our customers that utilize the Visual Studio IDE for their development work. Today, you can integrate our Nuget package and C# library with the 2012 version of Visual Studio; While the Nuget package is not ready for the bleeding edge 2013 Visual Studio Preview, we want to make sure that you elite, future thinking developers have the tools you need to begin implementing SendGrid in your apps today.

In this blog post, I’ll show you how to use our Web API via Microsoft’s HTTPClient Class to send emails and track the statistics using Visual Studio 2013 Preview on Windows 8.1.

Prerequisites

I first created this app using VMWare in an OSX environment; however, the app was then re-created on a Windows Surface Pro.

The following is the OS and development environment that was used to create this tutorial:

Once you have installed the above, you are ready to continue with the tutorial. If you decide to complete the tutorial in another environment, please let us know your results in the comments. Thanks!

If you are using Visual Studio 2012, check out this tutorial on how to use our Nuget package and .NET C# library.

Preview of Completed App

The purpose of this app is to demonstrate how to use SendGrid’s Web API inside of a native Windows 8 app using C#. When completed, you will have a working example that can send an email and display email statistics. The app simply asks for an email address you have emailed with SendGrid:
Final demo screenshot (1 of 2)

Then provides statistics on that email address:
Final demo screenshot (2 of 2)

Building the App

OK, now it’s time to fire up Visual Studio 2013 and get to the fun! If you are new to .NET C# Windows 8 programming, I suggest you first work through these series of tutorials on the MSDN.

First, we will create a new Visual C# blank XAML app as pictured below. You may be prompted to get a developer license for Windows 8.1 Preview. Go ahead, I’ll wait :)

New Visual C# XAMP Project

To build the initial interface for the first page of the app, complete this tutorial starting at step 1. Then apply the following changes to the default code.

In the MainPage.xaml file, make the following adjustments.

  • Rename the TextBlock text to read “What is your email?”.
  • Rename the TextBox x:Name to be emailInput.

In the MainPage.xaml.cs file, replace the contents of the Button_Click function with the following code.

cs
var to = emailInput.Text;
var from = "you@yourdomain.com";
var subject = "Testing Windows 8";
var text = "Email body text.";
var html = "Email body html.";
var api_user = "SendGrid_username";
var api_key = "SendGrid_key";
Send_Email(to, from, subject, text, html, api_user, api_key);

In the same file, define the Send_Email function as follows.

public async void Send_Email(string to, string from, string subject, string text, string html, string api_user, string api_key)
{
HttpClient client = new HttpClient();
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("to", to));
postData.Add(new KeyValuePair<string, string>("from", from));
postData.Add(new KeyValuePair<string, string>("subject", subject));
postData.Add(new KeyValuePair<string, string>("text", text));
postData.Add(new KeyValuePair<string, string>("html", html));
postData.Add(new KeyValuePair<string, string>("api_user", api_user));
postData.Add(new KeyValuePair<string, string>("api_key", api_key));

HttpContent content = new FormUrlEncodedContent(postData);
string mailURI = “https://sendgrid.com/api/mail.send.json”;

var response = await client.PostAsync(mailURI, content);

if (response.IsSuccessStatusCode)
{
greetingOutput.Text = “Thanks for trying out our SendGrid demo! Check your email ( ” + emailInput.Text + ” ) for follow up information.”;
}
else
{
greetingOutput.Text = “Error! Reason: ” + response.ReasonPhrase + ” Status Code: ” + response.StatusCode;
}
}

Finally, add the following library.

using System.Net.Http;

You can explore more of our Web API mail endpoint parameters at our documentation.

Run the app (click F5), type in your email address, click the Say “Hello” button and you should receive an email to the address you enter.

Email sent successfully

Now, let’s add the page that will display the email statistics by going to Project->Add New Item and choosing Split Page as depicted below. You will prompted to resolve dependencies, make sure you click Yes.

Create the email statistics page

Change the page title by clicking on the canvas. Note that you will have to extend the bounding box on the right for the text to fit properly as shown below.

Change the email statistics page title

Now we need to add a navigation button on our home page that links to the newly created Statistics page. Modify the code in MainPage.xaml as follows.

Change the email statistics page title

Now we will add an event handler to the button that will navigate to the Statistics page. While the newly created button is selected, input the following in the Properties pane.

Add event handler to navigate to the statistics page

You will then be transported to a new function in MainPage.xaml.cs. Add the following code inside the function.

if (this.Frame != null)
{
this.Frame.Navigate(typeof(Statistics));
}

Open the Statistics.xaml.cs file and add the following code.

using System.Net.Http;
using Windows.Data.Json;

Inside the Statistics Class add the following public class.

public class EmailStatistics
{
public string ImagePath { get; set; }
public string Title { get; set; }
public string Subtitle { get; set; }
public string ImagePathDetail { get; set; }
public string TitleDetail { get; set; }
public string SubtitleDetail { get; set; }
}

At the end of the Statistics function, add the following code.

// Populate the email statistics
Get_Statistics("30");

Then, define the Get_Statistics function as follows.

public async void Get_Statistics(string days)
{
HttpClient client = new HttpClient();
var api_user = "sendgrid_username";
var api_key = "sendgrid_key";
var aggregate = "1";
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("days", days));
postData.Add(new KeyValuePair<string, string>("aggregate", aggregate));
postData.Add(new KeyValuePair<string, string>("api_user", api_user));
postData.Add(new KeyValuePair<string, string>("api_key", api_key));

HttpContent content = new FormUrlEncodedContent(postData);
string mailURI = “https://sendgrid.com/api/stats.get.json”;

var response = await client.PostAsync(mailURI, content);
var unique = await response.Content.ReadAsStringAsync();
JsonValue value = JsonValue.Parse(unique);
double requests = value.GetObject().GetNamedNumber(“requests”);
double delivered = value.GetObject().GetNamedNumber(“delivered”);
double opens = value.GetObject().GetNamedNumber(“opens”);

// Update the ListView
var emailStatistics = new[]
{
new EmailStatistics {ImagePath = “http://upload.wikimedia.org/wikipedia/commons/7/72/Crystal_Clear_action_player_play.png”, Title = “Emails Sent”, Subtitle = requests.ToString() + ” requests.”, ImagePathDetail = “http://upload.wikimedia.org/wikipedia/commons/8/8c/Crystal_Clear_app_help_index.png”, TitleDetail = requests.ToString() + ” Sent Emails”, SubtitleDetail = “This is the number of emails sent in the past ” + days + ” days.”},
new EmailStatistics {ImagePath = “http://upload.wikimedia.org/wikipedia/commons/d/d6/Crystal_Clear_action_apply.png”, Title = “Emails Delivered”, Subtitle = delivered.ToString() + ” emails delivered.”, ImagePathDetail = “http://upload.wikimedia.org/wikipedia/commons/8/8c/Crystal_Clear_app_help_index.png”, TitleDetail = delivered.ToString() + ” Emails Delivered”, SubtitleDetail = “This is the number of emails delivered in the past ” + days + ” days.”},
new EmailStatistics {ImagePath = “http://upload.wikimedia.org/wikipedia/commons/7/72/Crystal_Clear_app_amor.png”, Title = “Emails Opened”, Subtitle = opens.ToString() + ” emails opened.”, ImagePathDetail = “http://upload.wikimedia.org/wikipedia/commons/8/8c/Crystal_Clear_app_help_index.png”, TitleDetail = opens.ToString() + ” Opened Emails”, SubtitleDetail = “This is the number of emails opened in the past ” + days + ” days.”}
};

this.itemListView.ItemsSource = emailStatistics;
}

Learn more about our statistics Web API endpoint at our documentation.

Next we are going to add a refresh button so that we easily update the statistics from within the app. Drag the button from the toolbar to the canvas.

Drag the refresh button onto the screen

In the properties panel, change the Content to be Refresh and then click the event handler icon and add the value Button_Click to Click. This will open the function in Statistics.xaml.cs where you will add the following code.

Get_Statistics("30");

Optionally, you can update the images in the Assets folder to give your app some style according to these specifications.

In Conclusion

Congrats! You now have a working sample app that uses our Web API to send emails and track the statistics using Visual Studio 2013 Preview on Windows 8.1! Please let us know how this tutorial worked for you in the comments. If you run into any issues, please don’t hesitate to reach out, we all love to help!

Note that a newly refactored Nuget package that will working with Visual Studio 2013 is in the works. Check back here or on Twitter for the announcment when its released.


Elmer Thomas is SendGrid's Hacker in Residence. His mission is to help SendGrid live up to its slogan: "Email Delivery. Simplified" by improving the lives of developers, both internally and externally. Via all sorts of hackery, of course. Follow his exploits on Twitter and GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>