diff options
author | Elmer Thomas <elmer@thinkingserious.com> | 2016-04-27 18:38:57 -0700 |
---|---|---|
committer | Elmer Thomas <elmer@thinkingserious.com> | 2016-04-27 18:38:57 -0700 |
commit | 8db5b1b63066d08105e7bedf622a0db0e5ae5ff9 (patch) | |
tree | 721785d33df7526e82d5ad0945acf67953a72e66 | |
parent | 172686ed8c1615b1cc1c508c55f31fe9c399b75e (diff) | |
download | sendgrid-csharp-8db5b1b63066d08105e7bedf622a0db0e5ae5ff9.zip sendgrid-csharp-8db5b1b63066d08105e7bedf622a0db0e5ae5ff9.tar.gz sendgrid-csharp-8db5b1b63066d08105e7bedf622a0db0e5ae5ff9.tar.bz2 |
Preparing for deploy
53 files changed, 2241 insertions, 4077 deletions
diff --git a/.github/ISSUE_TEMPLATE b/.github/ISSUE_TEMPLATE new file mode 100644 index 0000000..87c0676 --- /dev/null +++ b/.github/ISSUE_TEMPLATE @@ -0,0 +1,17 @@ +#### Issue Summary + +A summary of the issue and the environment in which it occurs. If suitable, include the steps required to reproduce the bug. Please feel free to include screenshots, screencasts, code examples. + + +#### Steps to Reproduce + +1. This is the first step +2. This is the second step +3. Further steps, etc. + +Any other information you want to share that is relevant to the issue being reported. Especially, why do you consider this to be a bug? What do you expect to happen instead? + +#### Technical details: + +* sendgrid-csharp Version: master (latest commit: [commit number]) +* .NET Version: 4.5.2
\ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index dd42d96..6fb4af8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ # Change Log All notable changes to this project will be documented in this file. +## [7.0.0] - XXXX-XX-XX +### Added +- Breaking change to support the v3 Web API +- New HTTP client +- v3 Mail Send helper + ## [6.3.4] - 2015-12-15 ###Added - Implemented the global stats /asm/stats endpoint [GET] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..94ed157 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,181 @@ +Hello! Thank you for choosing to help contribute to the sendgrid-csharp library. There are many ways you can contribute and help is always welcome. + +We use [Milestones](https://github.com/sendgrid/sendgrid-csharp/milestones) to help define current roadmaps, please feel free to grab an issue from the current milestone. Please indicate that you have begun work on it to avoid collisions. Once a PR is made, community review, comments, suggestions and additional PRs are welcomed and encouraged. + +* [Feature Request](#feature_request) +* [Submit a Bug Report](#submit_a_bug_report) +* [Improvements to the Codebase](#improvements_to_the_codebase) +* [Understanding the Code Base](#understanding_the_codebase) +* [Testing](#testing) +* [Style Guidelines & Naming Conventions](#style_guidelines_and_naming_conventions) +* [Creating a Pull Request](#creating_a_pull_request) + +There are a few ways to contribute, which we'll enumerate below: + +<a name="feature_request"></a> +## Feature Request + +If you'd like to make a feature request, please read this section. + +The GitHub issue tracker is the preferred channel for library feature requests, but please respect the following restrictions: + +- Please **search for existing issues** in order to ensure we don't have duplicate bugs/feature requests. +- Please be respectful and considerate of others when commenting on issues + +<a name="submit_a_bug_report"></a> +## Submit a Bug Report + +Note: DO NOT include your credentials in ANY code examples, descriptions, or media you make public. + +A software bug is a demonstrable issue in the code base. In order for us to diagnose the issue and respond as quickly as possible, please add as much detail as possible into your bug report. + +Before you decide to create a new issue, please try the following: + +1. Check the Github issues tab if the identified issue has already been reported, if so, please add a +1 to the existing post. +2. Update to the latest version of this code and check if issue has already been fixed +3. Copy and fill in the Bug Report Template we have provided below + +### Please use our Bug Report Template + +In order to make the process easier, we've included a sample bug report template (borrowed from [Ghost](https://github.com/TryGhost/Ghost/)). The template uses [GitHub flavored markdown](https://help.github.com/articles/github-flavored-markdown/) for formatting. + +``` +Short and descriptive example bug report title + +#### Issue Summary + +A summary of the issue and the environment in which it occurs. If suitable, include the steps required to reproduce the bug. Please feel free to include screenshots, screencasts, code examples. + + +#### Steps to Reproduce + +1. This is the first step +2. This is the second step +3. Further steps, etc. + +Any other information you want to share that is relevant to the issue being reported. Especially, why do you consider this to be a bug? What do you expect to happen instead? + +#### Technical details: + +* sendgrid-charp Version: master (latest commit: 2cb34372ef0f31352f7c90015a45e1200cb849da) +* .NET Version: 4.5.2 +``` + +<a name="improvements_to_the_codebase"></a> +## Improvements to the Codebase + +We welcome direct contributions to the sendgrid-csharp code base. Thank you! + +### Development Environment ### + +#### Install and run locally #### + +##### Prerequisites ##### + +* .NET 4.5.2 +* SendGrid.CSharp.HTTP.Client +* Newtonsoft.Json + +##### Initial setup: ##### + +``` +git clone https://github.com/sendgrid/sendgrid-csharp.git +``` + +Open `sendgrid-csharp/SendGrid/SendGrid.sln` + +##### Execute: ##### + +See the [Example project]() to get started quickly. + +<a name="understanding_the_codebase"></a> +## Understanding the Code Base + +**/Example/Example.cs** + +Working examples that demonstrate usage. + +**/SendGrid/SendGrid.cs** + +The main interface to the SendGrid API is the class `SendGridAPIClient`. + +<a name="testing"></a> +## Testing + +All PRs require passing tests before the PR will be reviewed. + +All test files are in the [`UnitTest`](https://github.com/sendgrid/sendgrid-csharp/tree/master/UnitTest) directory. + +For the purposes of contributing to this repo, please update the [`UnitTest.cs`](https://github.com/sendgrid/sendgrid-sharp/blob/master/UnitTest/UnitTest.cs) file with unit tests as you modify the code. + +Within the Test Explorer, click on the "Run All" link. + +### Execute: ### + +Click on the Example project, then click the `Start` button in the menu. + +<a name="style_guidelines_and_naming_conventions"></a> +## Style Guidelines & Naming Conventions + +Generally, we follow the style guidelines as suggested by the official language. However, we ask that you conform to the styles that already exist in the library. If you wish to deviate, please explain your reasoning. In this case, we generally follow the [C# Naming Conventions](https://msdn.microsoft.com/library/ms229045(v=vs.100).aspx) and the suggestions provided by the Visual Studio IDE. + +### Directory Structure + +* `SendGrid` for the interface to the SendGrid API +* `Example`, for example calls +* `UnitTest`, for all tests + +## Creating a Pull Request<a name="creating_a_pull_request"></a> + +1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork, + and configure the remotes: + + ```bash + # Clone your fork of the repo into the current directory + git clone https://github.com/sendgrid/sendgrid-csharp + # Navigate to the newly cloned directory + cd sendgrid-csharp + # Assign the original repo to a remote called "upstream" + git remote add upstream https://github.com/sendgrid/sendgrid-csharp + ``` + +2. If you cloned a while ago, get the latest changes from upstream: + + ```bash + git checkout <dev-branch> + git pull upstream <dev-branch> + ``` + +3. Create a new topic branch (off the main project development branch) to + contain your feature, change, or fix: + + ```bash + git checkout -b <topic-branch-name> + ``` + +4. Commit your changes in logical chunks. Please adhere to these [git commit + message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html) + or your code is unlikely be merged into the main project. Use Git's + [interactive rebase](https://help.github.com/articles/interactive-rebase) + feature to tidy up your commits before making them public. + +4a. Create tests. + +4b. Create or update the example code that demonstrates the functionality of this change to the code. + +5. Locally merge (or rebase) the upstream development branch into your topic branch: + + ```bash + git pull [--rebase] upstream master + ``` + +6. Push your topic branch up to your fork: + + ```bash + git push origin <topic-branch-name> + ``` + +7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) + with a clear title and description against the `master` branch. All tests must be passing before we will review the PR. + +If you have any additional questions, please feel free to [email](mailto:dx@sendgrid.com) us or create an issue in this repo.
\ No newline at end of file diff --git a/MIT.LICENSE b/LICENSE.txt index 585f8b3..a5e93d2 100644 --- a/MIT.LICENSE +++ b/LICENSE.txt @@ -1,21 +1,21 @@ -The MIT License (MIT)
-
-Copyright (c) 2016 SendGrid
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
+The MIT License (MIT) + +Copyright (c) 2016 SendGrid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. @@ -1,12 +1,8 @@ -[](https://travis-ci.org/sendgrid/sendgrid-csharp) +[](https://travis-ci.org/sendgrid/sendgrid-csharp) -See the [changelog](https://github.com/sendgrid/sendgrid-csharp/blob/master/CHANGELOG.md) for updates. +**This library allows you to quickly and easily use the SendGrid Web API via C Sharp with .NET.** -#Requirements - -As of 4.0.0, this library requires .NET 4.5 and above. [Fork with .NET 4.0 support](https://www.nuget.org/packages/SendGrid.Net40/) - -#Installation +# Installation To use SendGrid in your C# project, you can either <a href="https://github.com/sendgrid/sendgrid-csharp.git">download the SendGrid C# .NET libraries directly from our Github repository</a> or, if you have the NuGet package manager installed, you can grab them automatically. @@ -20,335 +16,89 @@ For a sample implementation, check the [Example](https://github.com/sendgrid/sen Add the following namespaces to use the library: ```csharp using System; -using System.Net; -using System.Net.Mail; +using System.Web.Script.Serialization; using SendGrid; ``` -#How to: Create an email +## Dependencies -Use the static **new SendGridMessage** constructor to create an email message that is of type **SendGridMessage**. Once the message is created, you can use **SendGridMessage** properties and methods to set values including the email sender, the email recipient, and the subject and body of the email. +- [SendGrid.CSharp.HTTP.Client](https://github.com/sendgrid/csharp-http-client) -The following example demonstrates how to create an email object and populate it: +## Environment Variables -```csharp -// Create the email object first, then add the properties. -var myMessage = new SendGridMessage(); +First, get your free SendGrid account [here](https://sendgrid.com/free?source=sendgrid-csharp). -// Add the message properties. -myMessage.From = new MailAddress("john@example.com"); +Next, update your environment with your [SENDGRID_API_KEY](https://app.sendgrid.com/settings/api_keys). -// Add multiple addresses to the To field. -List<String> recipients = new List<String> -{ - @"Jeff Smith <jeff@example.com>", - @"Anna Lidman <anna@example.com>", - @"Peter Saddow <peter@example.com>" -}; +# Quick Start -myMessage.AddTo(recipients); - -myMessage.Subject = "Testing the SendGrid Library"; - -//Add the HTML and Text bodies -myMessage.Html = "<p>Hello World!</p>"; -myMessage.Text = "Hello World plain text!"; -``` - -#How to: Send an Email - -After creating an email message, you can send it using the Web API provided by SendGrid. - -Sending email requires that you supply your SendGrid account credentials (username and password) OR a SendGrid API Key. API Key is the preferred method. API Keys are in beta. To configure API keys, visit https://sendgrid.com/beta/settings/api_keys - -To send an email message, use the **DeliverAsync** method on the **Web** transport class, which calls the SendGrid Web API. The following example shows how to send a message. +## v3 Web API endpoints ```csharp -// Create the email object first, then add the properties. -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Text = "Hello World!"; - -// Create a Web transport, using API Key -var transportWeb = new Web("This string is a SendGrid API key"); - -// Send the email. -transportWeb.DeliverAsync(myMessage); -// NOTE: If your developing a Console Application, use the following so that the API call has time to complete -// transportWeb.DeliverAsync(myMessage).Wait(); -``` - -#How to: Add an Attachment - -Attachments can be added to a message by calling the **AddAttachment** method and specifying the name and path of the file you want to attach, or by passing a stream. You can include multiple attachments by calling this method once for each file you wish to attach. The following example demonstrates adding an attachment to a message: - -```csharp -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Text = "Hello World!"; - -myMessage.AddAttachment(@"C:\file1.txt"); -``` - -You can also add attachments from the data's **Stream**. It can be done by calling the same method as above, **AddAttachment**, but by passing in the Stream of the data, and the filename you want it to show as in the message. - -```csharp -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Text = "Hello World!"; +using System; +using SendGrid; -using (var attachmentFileStream = new FileStream(@"C:\file.txt", FileMode.Open)) +namespace Example { - message.AddAttachment(attachmentFileStream, "My Cool File.txt"); + internal class Example + { + private static void Main() + { + String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); + dynamic sg = new SendGrid.SendGridAPIClient(apiKey); + dynamic response = sg.client.api_keys.get(queryParams: queryParams); + } + } } ``` -#How to: Use filters to enable footers, tracking, analytics and templates +# Announcements -SendGrid provides additional email functionality through the use of filters. These are settings that can be added to an email message to enable specific functionality such as click tracking, Google analytics, subscription tracking, and so on. For a full list of filters, see [Filter Settings](https://sendgrid.com/docs/API_Reference/SMTP_API/apps.html). +**BREAKING CHANGE as of XXXX.XX.XX** -Filters can be applied to **SendGrid** email messages using methods implemented as part of the **SendGrid** class. Before you can enable filters on an email message, you must first initialize the list of available filters by calling the **InitializeFilters** method. +Version `7.0.0` is a breaking change for the entire library. -The following examples demonstrate the footer and click tracking filters: +Version 7.0.0 brings you full support for all Web API v3 endpoints. We +have the following resources to get you started quickly: -##Footer -```csharp -// Create the email object first, then add the properties. -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Text = "Hello World!"; - -// Add a footer to the message. -myMessage.EnableFooter("PLAIN TEXT FOOTER", "<p><em>HTML FOOTER</em></p>"); -``` +- [SendGrid + Documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html) +- [Usage + Documentation](https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md) +- [Example + Code](https://github.com/sendgrid/sendgrid-csharp/blob/master/Example) -##Click tracking -```csharp -// Create the email object first, then add the properties. -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Html = "<p><a href=\"http://www.example.com\">Hello World Link!</a></p>"; -myMessage.Text = "Hello World!"; - -// true indicates that links in plain text portions of the email -// should also be overwritten for link tracking purposes. -myMessage.EnableClickTracking(true); -``` - -##Template -```csharp -// Create the email object first, then add the properties. -SendGridMessage myMessage = new SendGridMessage(); -myMessage.AddTo("anna@example.com"); -myMessage.From = new MailAddress("john@example.com", "John Smith"); -myMessage.Subject = "Testing the SendGrid Library"; -myMessage.Text = "Hello World!"; - -// Enable template engine, you must send the template id - myMessage.EnableTemplateEngine("template id"); -``` - -#How to: Use the [Web API v3](https://sendgrid.com/docs/API_Reference/Web_API_v3/index.html) - -Note: We have just begun to implement support for these endpoints and therefore only the following endpoints are currently supported. This functionality is located in the "SendGrid" project. - -## API Keys ## - -Please refer to [our documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html) for further details. - -List all API Keys belonging to the authenticated user [GET] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -// Leave off .Result for an asyncronous call -HttpResponseMessage responseGet = client.ApiKeys.Get().Result; -``` - -Generate a new API Key for the authenticated user [POST] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -var apiKeyName = "CSharpTestKey"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responsePost = client.ApiKeys.Post(apiKeyName).Result; -``` - -Update the name of an existing API Key [PATCH] +Thank you for your continued support! -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -var apiKeyName = "CSharpTestKey"; -ver apiKeyId = "<API Key ID>"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responsePatch = client.ApiKeys.Patch(apiKeyId, apiKeyName).Result; -``` +## Roadmap -Revoke an existing API Key [DELETE] +[Milestones](https://github.com/sendgrid/sendgrid-csharp/milestones) -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -ver apiKeyId = "<API Key ID>"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responseDelete = client.ApiKeys.Delete(apiKeyId).Result; -``` +## How to Contribute -## Unsubscribe Groups ## +We encourage contribution to our libraries, please see our [CONTRIBUTING](https://github.com/sendgrid/sendgrid-csharp/blob/master/CONTRIBUTING.md) guide for details. -Please refer to [our documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html) for further details. +* [Feature Request](https://github.com/sendgrid/sendgrid-csharp/blob/master/CONTRIBUTING.md#feature_request) +* [Bug Reports](https://github.com/sendgrid/sendgrid-csharp/blob/master/CONTRIBUTING.md#submit_a_bug_report) +* [Improvements to the Codebase](https://github.com/sendgrid/sendgrid-csharp/blob/master/CONTRIBUTING.md#improvements_to_the_codebase) -Retrieve all suppression groups associated with the user. [GET] +## Usage -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -// Leave off .Result for an asyncronous call -HttpResponseMessage responseGet = client.ApiKeys.Get().Result; -``` +- [SendGrid Docs](https://sendgrid.com/docs/API_Reference/index.html) +- [v3 Web API](https://github.com/sendgrid/sendgrid-csharp/blob/master/USAGE.md) +- [Example Code](https://github.com/sendgrid/sendgrid-csharp/blob/master/examples) +- [v3 Web API Mail Send Helper]() -Get information on a single suppression group. [GET] +## Unsupported Libraries -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -// Leave off .Result for an asyncronous call -HttpResponseMessage responseGet = client.UnsubscribeGroups.Get().Result; -``` - -Create a new suppression group. [POST] - -There is a limit of 25 groups per user. - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -var unsubscribeGroupName = "CSharpTestUnsubscribeGroup"; -var unsubscribeGroupDescription = "CSharp test Unsubscribe Group description."; -var unsubscribeGroupIsDefault = false; -// Leave off .Result for an asyncronous call -HttpResponseMessage responsePost = client.UnsubscribeGroups.Post(unsubscribeGroupName, unsubscribeGroupDescription, unsubscribeGroupIsDefault ).Result; -``` - -Delete a suppression group. [DELETE] - -You can only delete groups that have not been attached to sent mail in the last 60 days. If a recipient uses the “one-click unsubscribe” option on an email associated with a deleted group, that recipient will be added to the global suppression list. - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -ver unsubscribeGroupId = "<UNSUBSCRIBE GROUP ID>"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responseDelete = client.UnsubscribeGroups.Delete(unsubscribeGroupId).Result; -``` - -## Suppressions ## - -Please refer to [our documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html) for further details. - -Get suppressed addresses for a given group. [GET] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -// Leave off .Result for an asyncronous call -int groupId = <Group ID>; -HttpResponseMessage responseGet = client.Suppressions.Get(groupId).Result; -``` - -Add recipient addresses to the suppressions list for a given group. [POST] - -If the group has been deleted, this request will add the address to the global suppression. - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -string[] emails = { "example@example.com", "example2@example.com" }; -// Leave off .Result for an asyncronous call -HttpResponseMessage responsePost = client.Suppressions.Post(groupID, emails).Result; -``` - -Delete a recipient email from the suppressions list for a group. [DELETE] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -ver groupId = "<UNSUBSCRIBE GROUP ID>"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responseDelete1 = client.Suppressions.Delete(groupId, "example@example.com").Result; -``` - -## Global Suppressions ## - -Please refer to [our documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html) for further details. - -Check if a recipient address is in the global suppressions group. [GET] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -// Leave off .Result for an asyncronous call -string email = "example@example.com"; -HttpResponseMessage responseGet = client.GlobalSuppressions.Get(email).Result; -``` - -Add recipient addresses to the global suppression group. [POST] - -If the group has been deleted, this request will add the address to the global suppression. - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -string[] emails = { "example@example.com", "example2@example.com" }; -// Leave off .Result for an asyncronous call -HttpResponseMessage responsePost = client.GlobalSuppressions.Post(emails).Result; -``` - -Delete a recipient email from the global suppressions group. [DELETE] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -string email = "example@example.com"; -// Leave off .Result for an asyncronous call -HttpResponseMessage responseDelete1 = client.GlobalSuppressions.Delete(email).Result; -``` - -## Global Stats ## - -Please refer to [our documentation](https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html) for further details. - -Global Stats provide all of your user’s email statistics for a given date range. [GET] - -```csharp -String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); -var client = new SendGrid.Client(apiKey); -var startDate = "2015-11-01"; // required -var endDate = "2015-12-01"; -var aggregatedBy = "day"; // "week" or "month" are also options -// Leave off .Result for an asyncronous call -HttpResponseMessage responseGet = client.GlobalStats.Get(startDate, endDate, aggregatedBy).Result; -``` +- [Official and Unsupported SendGrid Libraries](https://sendgrid.com/docs/Integrate/libraries.html) -#How to: Testing +# About -* Load the solution (We have tested using the Visual Studio Community Edition) -* In the Test Explorer, click "Run All". Tests for the Mail Send v2 endpoint are in the "Tests" project, while the tests for the v3 endpoints are in the "UnitTests" project. Selecting "Run All" from the Test Explorer will run the tests in both projects. +![SendGrid Logo] +(https://assets3.sendgrid.com/mkt/assets/logos_brands/small/sglogo_2015_blue-9c87423c2ff2ff393ebce1ab3bd018a4.png) -You can also test the code by building and running our "Example" project. It will run through the examples using an interactive console. You will need your API key to run the examples against your account. +sendgrid-csharp is guided and supported by the SendGrid [Developer Experience Team](mailto:dx@sendgrid.com). -[SendGrid Documentation](http://www.sendgrid.com/docs) +sendgrid-csharp is maintained and funded by SendGrid, Inc. The names and logos for sendgrid-csharp are trademarks of SendGrid, Inc. -This readme adapted from [How to Send Email Using SendGrid with Windows Azure](http://www.windowsazure.com/en-us/develop/net/how-to-guides/sendgrid-email-service/) diff --git a/SendGrid/Example/Example.cs b/SendGrid/Example/Example.cs new file mode 100644 index 0000000..43ca32f --- /dev/null +++ b/SendGrid/Example/Example.cs @@ -0,0 +1,333 @@ +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; +using SendGrid.Helpers.Mail; + +namespace Example +{ + internal class Example + { + private static void Main() + { + // v3 Mail Helper + HelloEmail(); + KitchenSink(); + + // v3 Web API + ApiKeys(); + + } + + + private static void HelloEmail() + { + String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); + dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://3wyb2hp7emnqja6ys.stoplight-proxy.io"); + + Mail mail = new Mail(); + + Email email = new Email(); + email.Address = "dx@sendgrid.com"; + mail.From = email; + + Personalization personalization = new Personalization(); + email = new Email(); + email.Address = "elmer.thomas@sendgrid.com"; + personalization.AddTo(email); + personalization.AddHeader("X-Mock", "True"); + mail.AddPersonalization(personalization); + + mail.Subject = "Hello World from the SendGrid CSharp Library"; + + Content content = new Content(); + content.Type = "text/plain"; + content.Value = "Textual content"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/html"; + content.Value = "<html><body>HTML content</body></html>"; + mail.AddContent(content); + + String ret = mail.Get(); + + string requestBody = ret; + dynamic response = sg.client.mail.send.post(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine(ret); + Console.ReadLine(); + + } + + private static void KitchenSink() + { + String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); + dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://3wyb2hp7emnqja6ys.stoplight-proxy.io"); + + Mail mail = new Mail(); + + Email email = new Email(); + email.Name = "DX"; + email.Address = "dx@sendgrid.com"; + mail.From = email; + + mail.Subject = "Hello World from the SendGrid CSharp Library"; + + Personalization personalization = new Personalization(); + email = new Email(); + email.Name = "Elmer Thomas"; + email.Address = "elmer.thomas@sendgrid.com"; + personalization.AddTo(email); + email = new Email(); + email.Name = "Matt Bernier"; + email.Address = "matt.bernier@sendgrid.com"; + personalization.AddCc(email); + email = new Email(); + email.Name = "Eric Shallock"; + email.Address = "eric.shallock@sendgrid.com"; + personalization.AddCc(email); + personalization.AddBcc("elmer.thomas+secret@sengrid.com"); + personalization.AddBcc("elmer.thomas+secret@elmer.thomas.com"); + personalization.Subject = "Thank you for signing up, %name%"; + personalization.AddHeader("X-Test", "True"); + personalization.AddHeader("X-Mock", "True"); + personalization.AddSubstitution("%name%", "Elmer"); + personalization.AddSubstitution("%city%", "Moreno Valley"); + personalization.AddCustomArgs("marketing", "false"); + personalization.AddCustomArgs("transactional", "true"); + personalization.SendAt = 1461775051; + mail.AddPersonalization(personalization); + + personalization = new Personalization(); + email = new Email(); + email.Name = "Elmer Thomas"; + email.Address = "elmer.thomas@gmail.com"; + personalization.AddTo(email); + email = new Email(); + email.Name = "Matt Bernier"; + email.Address = "matt.bernier@sendgrid.com"; + personalization.AddCc(email); + email = new Email(); + email.Name = "Eric Shallock"; + email.Address = "eric.shallock@sendgrid.com"; + personalization.AddCc(email); + personalization.AddBcc("elmer.thomas+secret@sengrid.com"); + personalization.AddBcc("elmer.thomas+secret@elmer.thomas.com"); + personalization.Subject = "Thank you for signing up, %name%"; + personalization.AddHeader("X-Test", "True"); + personalization.AddHeader("X-Mock", "True"); + personalization.AddSubstitution("%name%", "Elmer"); + personalization.AddSubstitution("%city%", "Moreno Valley"); + personalization.AddCustomArgs("marketing", "false"); + personalization.AddCustomArgs("transactional", "true"); + personalization.SendAt = 1461775051; + mail.AddPersonalization(personalization); + + Content content = new Content(); + content.Type = "text/plain"; + content.Value = "Textual content"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/html"; + content.Value = "<html><body>HTML content</body></html>"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/calendar"; + content.Value = "Party Time!!"; + mail.AddContent(content); + + Attachment attachment = new Attachment(); + attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"; + attachment.Type = "application/pdf"; + attachment.Filename = "balance_001.pdf"; + attachment.Disposition = "attachment"; + attachment.ContentId = "Balance Sheet"; + mail.AddAttachment(attachment); + + attachment = new Attachment(); + attachment.Content = "iVBORw0KGgoAAAANSUhEUgAAAlgAAAC0CAMAAAB/oaI+AAACvlBMVEX///8aguLp8/wmiOMnieQ5k+bg7vtcpury+P0/lufX6foehOJCmOe92/er0fRToen9/v8hhuNkquvG4PjP5fkihuMjh+Mkh+MtjOQzkOVusO12tO77/f/8/v8cg+IfheMwjuVFmud/ue/+///t9f3u9v33+/5Wo+ppreyUxfGjzfP7/f4bguIri+QsjOQ8leY9leZdp+v6/P4ehONKnOhmrOx+uO+IvvCRw/Hc7Pvm8fzr9PwgheNHm+iayPKfy/PF3/jH4fji7/vo8vz1+v4ujeU0kOU6lOZIm+hSoOl4te601va62fbv9v3w9/30+f75/P4piuQyj+U2keZGmuhLnejE3/fZ6vodg+Japeptr+yTxPGy1fXB3ffS5vnq9Pz2+v74+/5Al+dZpOporex9uO+Du++LwPCMwPCSxPGcyfKlzvSp0PSv0/W+3Pe/3PfA3ffQ5vnU5/rf7fvh7/vn8vzz+f4qi+RBl+dsr+xxsu13te6Buu+Kv/CVxfKkzfSmzvSoz/S32Pa82vbC3vfK4vje7fsliOM1keVEmedOnulYpOpep+tgqOtqruxysu10s+11tO15tu58t+6EvO+FvPCNwfGZx/Kq0PSw1PWx1PWz1fXJ4vjb6/ooiuQvjeU3kuY7lOZDmedQn+lRoOlUoulXo+plq+x6tu57t+6byfKdyvOnz/S72vbO5PnV6PrW6Pra6/rd7Pvk8Pwxj+U+ludNnuhVoupfqOtnrOxwse2Cu++GvfCHvfCOwfGWxvKgy/O01vXL4/jR5vnY6vrj8Pvs9f04kubI4fjl8fxMnehbpepiqetjqutvse1zs+2Auu+XxvKYx/KeyvOizPPM4/nN5PnT5/nx9/1lq+trruyPwvGQwvGhzPOt0vW21/a42PbD3vdPn+mu0/WJv/Cs0v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OfbtzLz64lfvk2Yn4Rl8M7fByevAIpB3hc0eojQjKMKwto4Tf2ICwH3o+GzI+vWaS7W+HzO4kHpJZEDPVYalTfbqWBKnoXc9G+N/HShn9OmeRdnbx0fHrWqTQQBKYWUQuoqvblyl8L+p2GkaCDrI0hA+9ThMmRetpGkSCHvKnqT12R/WvAgaDVTSGBGw7bsJEvsG599OmuV0/h4aQgMIM70xJcxgkvRz8BQk0gAQc5qKblXE+mlMcPqDhI/AQYE6wFL/Ftr5O4ljMDBo9Ah+1zLIRakxxZJmo5UNjRxBgmAV6ulKZg4MJ/z8QHmOBmne5Jg0cwQAWuMSRSTRsBCNkNzMpVnWf0qARJNDLnFxtJKMoQQ6fmBCreT/ReBEkESQd6KY8JyMDQR73JcWqZScaK4IZ1JZJ8J+1jAaKYBKzDGOO/e80pmEimMbc60KxanhnFI0RwRJmcMNXo8eupOEhWMe9nkiSv3mbmlTQ0BAqh77fpMcVlfq68d61xQPIe0MgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCATC/1P8HzJOjPJg+R84AAAAAElFTkSuQmCC"; + attachment.Type = "image/png"; + attachment.Filename = "banner.png"; + attachment.Disposition = "inline"; + attachment.ContentId = "Banner"; + mail.AddAttachment(attachment); + + mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"; + + mail.AddHeader("X-Day", "Monday"); + mail.AddHeader("X-Month", "January"); + + mail.AddSection("%section1", "Substitution for Section 1 Tag"); + mail.AddSection("%section2", "Substitution for Section 2 Tag"); + + mail.AddCategory("customer"); + mail.AddCategory("vip"); + + mail.AddCustomArgs("campaign", "welcome"); + mail.AddCustomArgs("sequence", "2"); + + ASM asm = new ASM(); + asm.GroupId = 3; + List<int> groups_to_display = new List<int>() + { + 1, 4, 5 + }; + asm.GroupsToDisplay = groups_to_display; + mail.Asm = asm; + + mail.SendAt = 1461775051; + + mail.SetIpPoolId = "23"; + + mail.BatchId = "some_batch_id"; + + MailSettings mailSettings = new MailSettings(); + BCCSettings bccSettings = new BCCSettings(); + bccSettings.Enable = true; + bccSettings.Email = "dx@sendgrid.com"; + mailSettings.BccSettings = bccSettings; + BypassListManagement bypassListManagement = new BypassListManagement(); + bypassListManagement.Enable = true; + mailSettings.BypassListManagement = bypassListManagement; + FooterSettings footerSettings = new FooterSettings(); + footerSettings.Enable = true; + footerSettings.Text = "Some Footer Text"; + footerSettings.Html = "<bold>Some HTML Here</bold>"; + mailSettings.FooterSettings = footerSettings; + SandboxMode sandboxMode = new SandboxMode(); + sandboxMode.Enable = false; + mailSettings.SandboxMode = sandboxMode; + SpamCheck spamCheck = new SpamCheck(); + spamCheck.Enable = true; + spamCheck.Threshold = 1; + spamCheck.PostToUrl = "https://gotchya.example.com"; + mailSettings.SpamCheck = spamCheck; + mail.MailSettings = mailSettings; + + TrackingSettings trackingSettings = new TrackingSettings(); + ClickTracking clickTracking = new ClickTracking(); + clickTracking.Enable = false; + clickTracking.EnableText = false; + trackingSettings.ClickTracking = clickTracking; + OpenTracking openTracking = new OpenTracking(); + openTracking.Enable = true; + openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message"; + trackingSettings.OpenTracking = openTracking; + SubscriptionTracking subscriptionTracking = new SubscriptionTracking(); + subscriptionTracking.Enable = true; + subscriptionTracking.Text = "text to insert into the text/plain portion of the message"; + subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>"; + subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message"; + trackingSettings.SubscriptionTracking = subscriptionTracking; + Ganalytics ganalytics = new Ganalytics(); + ganalytics.Enable = true; + ganalytics.UtmCampaign = "some campaign"; + ganalytics.UtmContent = "some content"; + ganalytics.UtmMedium = "some medium"; + ganalytics.UtmSource = "some source"; + ganalytics.UtmTerm = "some term"; + trackingSettings.Ganalytics = ganalytics; + mail.TrackingSettings = trackingSettings; + + email = new Email(); + email.Address = "dx@sendgrid.com"; + mail.ReplyTo = email; + + String ret = mail.Get(); + + string requestBody = ret; + dynamic response = sg.client.mail.send.post(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine(ret); + Console.ReadLine(); + } + + private static void ApiKeys() + { + String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); + dynamic sg = new SendGrid.SendGridAPIClient(apiKey, "https://e9sk3d3bfaikbpdq7.stoplight-proxy.io"); + + string queryParams = @"{ + 'limit': 100 + }"; + dynamic response = sg.client.api_keys.get(queryParams: queryParams); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to POST."); + Console.ReadLine(); + + // POST + string requestBody = @"{ + 'name': 'My API Key 5', + 'scopes': [ + 'mail.send', + 'alerts.create', + 'alerts.read' + ] + }"; + response = sg.client.api_keys.post(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + JavaScriptSerializer jss = new JavaScriptSerializer(); + var ds_response = jss.Deserialize<Dictionary<string, dynamic>>(response.ResponseBody.ReadAsStringAsync().Result); + string api_key_id = ds_response["api_key_id"]; + + Console.WriteLine("\n\nPress any key to continue to GET single."); + Console.ReadLine(); + + // GET Single + response = sg.client.api_keys._(api_key_id).get(); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to PATCH."); + Console.ReadLine(); + + // PATCH + requestBody = @"{ + 'name': 'A New Hope' + }"; + response = sg.client.api_keys._(api_key_id).patch(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to PUT."); + Console.ReadLine(); + + // PUT + requestBody = @"{ + 'name': 'A New Hope', + 'scopes': [ + ' user.profile.read', + ' user.profile.update' + ] + }"; + response = sg.client.api_keys._(api_key_id).put(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to DELETE."); + Console.ReadLine(); + + // DELETE + response = sg.client.api_keys._(api_key_id).delete(); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to exit."); + Console.ReadLine(); + + } + } +} diff --git a/SendGrid/Example/Example.csproj b/SendGrid/Example/Example.csproj index 786d6fb..038265c 100644 --- a/SendGrid/Example/Example.csproj +++ b/SendGrid/Example/Example.csproj @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition="'$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition="'$(Platform)' == '' ">x86</Platform>
@@ -8,7 +8,7 @@ <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Example</RootNamespace>
<AssemblyName>Example</AssemblyName>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
+ <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
@@ -45,9 +45,13 @@ </DefineConstants>
</PropertyGroup>
<ItemGroup>
+ <Reference Include="CSharpHTTPClient, Version=1.0.2.0, Culture=neutral, PublicKeyToken=79219bf4e5ecaaca, processorArchitecture=MSIL">
+ <HintPath>..\packages\SendGrid.CSharp.HTTP.Client.1.0.2\lib\CSharpHTTPClient.dll</HintPath>
+ <Private>True</Private>
+ </Reference>
<Reference Include="Microsoft.CSharp" />
- <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
- <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
+ <Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
+ <HintPath>..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="SendGrid.SmtpApi, Version=1.3.1.0, Culture=neutral, PublicKeyToken=2ae73662c35d80e4, processorArchitecture=MSIL">
@@ -61,9 +65,8 @@ <Reference Include="System.Web.Extensions" />
</ItemGroup>
<ItemGroup>
- <Compile Include="Program.cs" />
+ <Compile Include="Example.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="WebApi.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config">
@@ -75,10 +78,6 @@ <WCFMetadata Include="Service References\" />
</ItemGroup>
<ItemGroup>
- <ProjectReference Include="..\SendGridMail\Mail.csproj">
- <Project>{3c687bef-ff50-44ad-8315-2d4237281af8}</Project>
- <Name>Mail</Name>
- </ProjectReference>
<ProjectReference Include="..\SendGrid\SendGrid.csproj">
<Project>{1c318867-440b-4eb9-99e3-c0cc2c556962}</Project>
<Name>SendGrid</Name>
diff --git a/SendGrid/Example/Program.cs b/SendGrid/Example/Program.cs deleted file mode 100644 index 447bd04..0000000 --- a/SendGrid/Example/Program.cs +++ /dev/null @@ -1,263 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Net.Http;
-using System.Net.Mail;
-using Newtonsoft.Json.Linq;
-
-namespace Example
-{
- internal class Program
- {
- private static void Main()
- {
- // Test sending email
- var to = "example@example.com";
- var from = "example@example.com";
- var fromName = "Jane Doe";
- SendEmail(to, from, fromName);
- // Test viewing, creating, modifying and deleting API keys through our v3 Web API
- ApiKeys();
- UnsubscribeGroups();
- Suppressions();
- GlobalSuppressions();
- GlobalStats();
- }
-
- private static void SendAsync(SendGrid.SendGridMessage message)
- {
- string apikey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
- // Create a Web transport for sending email.
- var transportWeb = new SendGrid.Web(apikey);
-
- // Send the email.
- try
- {
- transportWeb.DeliverAsync(message).Wait();
- Console.WriteLine("Email sent to " + message.To.GetValue(0));
- Console.WriteLine("\n\nPress any key to continue.");
- Console.ReadKey();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- Console.WriteLine("\n\nPress any key to continue.");
- Console.ReadKey();
- }
- }
-
- private static void SendEmail(string to, string from, string fromName)
- {
- // Create the email object first, then add the properties.
- var myMessage = new SendGrid.SendGridMessage();
- myMessage.AddTo(to);
- myMessage.From = new MailAddress(from, fromName);
- myMessage.Subject = "Testing the SendGrid Library";
- myMessage.Text = "Hello World! %tag%";
-
- var subs = new List<String> { "私は%type%ラーメンが大好き" };
- myMessage.AddSubstitution("%tag%", subs);
- myMessage.AddSection("%type%", "とんこつ");
-
- SendAsync(myMessage);
- }
-
- private static void ApiKeys()
- {
- String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
- var client = new SendGrid.Client(apiKey);
-
- // GET API KEYS
- HttpResponseMessage responseGet = client.ApiKeys.Get().Result;
- Console.WriteLine(responseGet.StatusCode);
- Console.WriteLine(responseGet.Content.ReadAsStringAsync().Result);
- Console.WriteLine("These are your current API Keys.\n\nPress any key to continue.");
- Console.ReadKey();
-
- // POST API KEYS
- HttpResponseMessage responsePost = client.ApiKeys.Post("CSharpTestKey").Result;
- var rawString = responsePost.Content.ReadAsStringAsync().Result;
- dynamic jsonObject = JObject.Parse(rawString);
- var apiKeyId = jsonObject.api_key_id.ToString();
- Console.WriteLine(responsePost.StatusCode);
- Console.WriteLine(responsePost.Content.ReadAsStringAsync().Result);
- Console.WriteLine("API Key created.\n\nPress any key to continue.");
- Console.ReadKey();
-
- // PATCH API KEYS
- HttpResponseMessage responsePatch = client.ApiKeys.Patch(apiKeyId, "CSharpTestKeyPatched").Result;
- Console.WriteLine(responsePatch.StatusCode);
- Console.WriteLine(responsePatch.Content.ReadAsStringAsync().Result);
- Console.WriteLine("API Key patched.\n\nPress any key to continue.");
- Console.ReadKey();
-
- // DELETE API KEYS
- Console.WriteLine("Deleting API Key, please wait.");
- HttpResponseMessage responseDelete = client.ApiKeys.Delete(apiKeyId).Result;
- Console.WriteLine(responseDelete.StatusCode);
- HttpResponseMessage responseFinal = client.ApiKeys.Get().Result;
- Console.WriteLine(responseFinal.StatusCode);
- Console.WriteLine(responseFinal.Content.ReadAsStringAsync().Result);
- Console.WriteLine("API Key Deleted.\n\nPress any key to end.");
- Console.ReadKey();
- }
-
- private static void UnsubscribeGroups()
- {
- String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
- var client = new SendGrid.Client(apiKey);
-
- // GET UNSUBSCRIBE GROUPS
- HttpResponseMessage responseGet = client.UnsubscribeGroups.Get().Result;
- Console.WriteLine(responseGet.StatusCode);
- Console.WriteLine(responseGet.Content.ReadAsStringAsync().Result);
- Console.WriteLine("These are your current Unsubscribe Groups. Press any key to continue.");
- Console.ReadKey();
-
- // GET A PARTICULAR UNSUBSCRIBE GROUP
- int unsubscribeGroupID = 69;
- HttpResponseMessage responseGetUnique = client.UnsubscribeGroups.Get(unsubscribeGroupID).Result;
- Console.WriteLine(responseGetUnique.StatusCode);
- Console.WriteLine(responseGetUnique.Content.ReadAsStringAsync().Result);
- Console.WriteLine("This is an Unsubscribe Group with ID: " + unsubscribeGroupID.ToString() + ".\n\nPress any key to continue.");
- Console.ReadKey();
-
- // POST UNSUBSCRIBE GROUP
- HttpResponseMessage responsePost = client.UnsubscribeGroups.Post("C Sharp Unsubscribes", "Testing the C Sharp Library", false).Result;
- var rawString = responsePost.Content.ReadAsStringAsync().Result;
- dynamic jsonObject = JObject.Parse(rawString);
- var unsubscribeGroupId = jsonObject.id.ToString();
- Console.WriteLine(responsePost.StatusCode);
- Console.WriteLine(responsePost.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Unsubscribe Group created.\n\nPress any key to continue.");
- Console.ReadKey();
-
- // DELETE UNSUBSCRIBE GROUP
- Console.WriteLine("Deleting Unsubscribe Group, please wait.");
- HttpResponseMessage responseDelete = client.UnsubscribeGroups.Delete(unsubscribeGroupId).Result;
- Console.WriteLine(responseDelete.StatusCode);
- HttpResponseMessage responseFinal = client.UnsubscribeGroups.Get().Result;
- Console.WriteLine(responseFinal.StatusCode);
- Console.WriteLine(responseFinal.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Unsubscribe Group Deleted.\n\nPress any key to end.");
- Console.ReadKey();
- }
-
- private static void Suppressions()
- {
- String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
- var client = new SendGrid.Client(apiKey);
-
- // GET SUPPRESSED ADDRESSES FOR A GIVEN GROUP
- int groupID = 69;
- HttpResponseMessage responseGetUnique = client.Suppressions.Get(groupID).Result;
- Console.WriteLine(responseGetUnique.StatusCode);
- Console.WriteLine(responseGetUnique.Content.ReadAsStringAsync().Result);
- Console.WriteLine("These are the suppressed emails with group ID: " + groupID.ToString() + ". Press any key to continue.");
- Console.ReadKey();
-
- // ADD EMAILS TO A SUPPRESSION GROUP
- string[] emails = { "example@example.com", "example2@example.com" };
- HttpResponseMessage responsePost = client.Suppressions.Post(groupID, emails).Result;
- var rawString = responsePost.Content.ReadAsStringAsync().Result;
- dynamic jsonObject = JObject.Parse(rawString);
- Console.WriteLine(responsePost.StatusCode);
- Console.WriteLine(responsePost.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Emails added to Suppression Group:" + groupID.ToString() + ".\n\nPress any key to continue.");
- Console.ReadKey();
-
- // DELETE EMAILS FROM A SUPPRESSION GROUP
- Console.WriteLine("Deleting emails from Suppression Group, please wait.");
- HttpResponseMessage responseDelete1 = client.Suppressions.Delete(groupID, "example@example.com").Result;
- Console.WriteLine(responseDelete1.StatusCode);
- HttpResponseMessage responseDelete2 = client.Suppressions.Delete(groupID, "example2@example.com").Result;
- Console.WriteLine(responseDelete2.StatusCode);
- HttpResponseMessage responseFinal = client.Suppressions.Get(groupID).Result;
- Console.WriteLine(responseFinal.StatusCode);
- Console.WriteLine(responseFinal.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Emails removed from Suppression Group" + groupID.ToString() + "Deleted.\n\nPress any key to end.");
- Console.ReadKey();
- }
-
- private static void GlobalSuppressions()
- {
- String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
- var client = new SendGrid.Client(apiKey);
-
- // CHECK IF EMAIL IS ON THE GLOBAL SUPPRESSION LIST
- var email = "elmer.thomas+test_global@gmail.com";
- HttpResponseMessage responseGetUnique = client.GlobalSuppressions.Get(email).Result;
- Console.WriteLine(responseGetUnique.StatusCode);
- Console.WriteLine(responseGetUnique.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Determines if the given email is listed on the Global Suppressions list. Press any key to continue.");
- Console.ReadKey();
-
- // ADD EMAILS TO THE GLOBAL SUPPRESSION LIST
- string[] emails = { "example@example.com", "example2@example.com" };
- HttpResponseMessage responsePost = client.GlobalSuppressions.Post(emails).Result;
- var rawString = responsePost.Content.ReadAsStringAsync().Result;
- dynamic jsonObject = JObject.Parse(rawString);
- Console.WriteLine(responsePost.StatusCode);
- Console.WriteLine(responsePost.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Emails added to Global Suppression Group.\n\nPress any key to continue.");
- Console.ReadKey();
-
- // DELETE EMAILS FROM THE GLOBAL SUPPRESSION GROUP
- Console.WriteLine("Deleting emails from Global Suppression Group, please wait.");
- HttpResponseMessage responseDelete1 = client.GlobalSuppressions.Delete("example@example.com").Result;
- Console.WriteLine(responseDelete1.StatusCode);
- HttpResponseMessage responseDelete2 = client.GlobalSuppressions.Delete("example2@example.com").Result;
- Console.WriteLine(responseDelete2.StatusCode);
- HttpResponseMessage responseFinal = client.GlobalSuppressions.Get("example@example.com").Result;
- Console.WriteLine(responseFinal.StatusCode);
- Console.WriteLine(responseFinal.Content.ReadAsStringAsync().Result);
- HttpResponseMessage responseFinal2 = client.GlobalSuppressions.Get("example2@example.com").Result;
- Console.WriteLine(responseFinal2.StatusCode);
- Console.WriteLine(responseFinal2.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Emails removed from Global Suppression Group.\n\nPress any key to end.");
- Console.ReadKey();
- }
-
- private static void GlobalStats()
- {
- String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User);
- var client = new SendGrid.Client(apiKey);
-
- // Global Stats provide all of your user’s email statistics for a given date range.
- var startDate = "2015-11-01";
- HttpResponseMessage response = client.GlobalStats.Get(startDate).Result;
- Console.WriteLine(response.StatusCode);
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Display global email stats, with start date " + startDate + "and no end date.\n\nPress any key to continue.");
- Console.ReadKey();
-
- var endDate = "2015-12-01";
- response = client.GlobalStats.Get(startDate, endDate).Result;
- Console.WriteLine(response.StatusCode);
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Display global email stats, with start date " + startDate + "and end date " + endDate + ".\n\nPress any key to continue.");
- Console.ReadKey();
-
- var aggregatedBy = "day";
- response = client.GlobalStats.Get(startDate, endDate, aggregatedBy).Result;
- Console.WriteLine(response.StatusCode);
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Display global email stats, with start date " + startDate + "and end date " + endDate + " and aggregated by " + aggregatedBy + ".\n\nPress any key to continue.");
- Console.ReadKey();
-
- aggregatedBy = "week";
- response = client.GlobalStats.Get(startDate, endDate, aggregatedBy).Result;
- Console.WriteLine(response.StatusCode);
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Display global email stats, with start date " + startDate + "and end date " + endDate + " and aggregated by " + aggregatedBy + ".\n\nPress any key to continue.");
- Console.ReadKey();
-
- aggregatedBy = "month";
- response = client.GlobalStats.Get(startDate, endDate, aggregatedBy).Result;
- Console.WriteLine(response.StatusCode);
- Console.WriteLine(response.Content.ReadAsStringAsync().Result);
- Console.WriteLine("Display global email stats, with start date " + startDate + "and end date " + endDate + " and aggregated by " + aggregatedBy + ".\n\nPress any key to continue.");
- Console.ReadKey();
- }
-
- }
-}
diff --git a/SendGrid/Example/WEBAPI.cs b/SendGrid/Example/WEBAPI.cs deleted file mode 100644 index 1238df0..0000000 --- a/SendGrid/Example/WEBAPI.cs +++ /dev/null @@ -1,544 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Net;
-using System.Net.Mail;
-using SendGrid;
-
-namespace Example
-{
- internal class Webapi
- {
- private readonly String _from;
- private readonly String _password;
- private readonly IEnumerable<String> _to;
- private readonly String _username;
-
- public Webapi(String username, String password, String from, IEnumerable<String> recipients)
- {
- _username = username;
- _password = password;
- _from = from;
- _to = recipients;
- }
-
- /// <summary>
- /// Send a simple HTML based email
- /// </summary>
- public void SimpleHTMLEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Html = "<html><p>Hello</p><p>World</p></html>";
-
- //set the message subject
- message.Subject = "Hello World HTML Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// Send a simple Plain Text email
- /// </summary>
- public void SimplePlaintextEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Text = "Hello World Plain Text";
-
- //set the message subject
- message.Subject = "Hello World Plain Text Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// Enable The Gravatar Filter.
- /// Currently the filter generates a 1x1 pixel gravatar image.
- /// http://docs.sendgrid.com/documentation/apps/gravatar/
- /// </summary>
- public void EnableGravatarEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Html = "<p style='color:red';>Hello World Gravatar Email</p>";
-
- //set the message subject
- message.Subject = "Hello World Gravatar Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable gravatar
- message.EnableGravatar();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// Enable the Open Tracking to track when emails are opened.
- /// http://docs.sendgrid.com/documentation/apps/open-tracking/
- /// </summary>
- public void EnableOpenTrackingEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Html = "<p style='color:red';>Hello World Plain Text</p>";
-
- //set the message subject
- message.Subject = "Hello World Open Tracking Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable gravatar
- message.EnableOpenTracking();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// Point the urls to Sendgrid Servers so that the clicks can be logged before
- /// being directed to the appropriate link
- /// http://docs.sendgrid.com/documentation/apps/click-tracking/
- /// </summary>
- public void EnableClickTrackingEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World HTML </p> <a href='http://microsoft.com'>Checkout Microsoft!!</a>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
-
- message.Text = "hello world http://microsoft.com";
-
- //set the message subject
- message.Subject = "Hello World Click Tracking Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable clicktracking
- message.EnableClickTracking();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// The Spam Checker filter, is useful when your web application allows your end users
- /// to create content that is then emailed through your SendGridMessage account.
- /// http://docs.sendgrid.com/documentation/apps/spam-checker-filter/
- /// </summary>
- public void EnableSpamCheckEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>VIAGRA!!!!!! Viagra!!! CHECKOUT THIS VIAGRA!!!! MALE ENHANCEMENT!!! </p>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
-
- //set the message subject
- message.Subject = "WIN A MILLION DOLLARS TODAY! WORK FROM HOME! A NIGERIAN PRINCE WANTS YOU!";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable spamcheck
- message.EnableSpamCheck();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// Add automatic unsubscribe links to the bottom of emails.
- /// http://docs.sendgrid.com/documentation/apps/subscription-tracking/
- /// </summary>
- public void EnableUnsubscribeEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Html = "This is the HTML body";
-
- message.Text = "This is the plain text body";
-
- //set the message subject
- message.Subject = "Hello World Unsubscribe Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable spamcheck
- //or optionally, you can specify 'replace' instead of the text and html in order to
- //place the link wherever you want.
- message.EnableUnsubscribe("Please click the following link to unsubscribe: <% %>",
- "Please click <% here %> to unsubscribe");
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
- /// http://docs.sendgrid.com/documentation/apps/footer/
- /// </summary>
- public void EnableFooterEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World</p>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
-
- message.Text = "Hello World plain text";
-
- //set the message subject
- message.Subject = "Hello World Footer Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //Enable Footer
- message.EnableFooter("PLAIN TEXT FOOTER", "<p color='blue'>HTML FOOTER TEXT</p>");
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// The Footer App will insert a custom footer at the bottom of the text and HTML bodies.
- /// http://docs.sendgrid.com/documentation/apps/google-analytics/
- /// </summary>
- public void EnableGoogleAnalytics()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World</p>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
- message.Html += "Checkout my page at <a href=\"http://microsoft.com\">Microsoft</a>";
-
- message.Text = "Hello World plain text";
-
- //set the message subject
- message.Subject = "Hello World Footer Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable Google Analytics
- message.EnableGoogleAnalytics("SendGridTest", "EMAIL", "Sendgrid", "ad-one", "My SG Campaign");
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// This feature wraps an HTML template around your email content.
- /// This can be useful for sending out newsletters and/or other HTML formatted messages.
- /// http://docs.sendgrid.com/documentation/apps/email-templates/
- /// </summary>
- public void EnableTemplateEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World</p>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
-
- message.Text = "Hello World plain text";
-
- //set the message subject
- message.Subject = "Hello World Template Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable template
- message.EnableTemplate("<p>My Email Template <% body %> is awesome!</p>");
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// This feature wraps an HTML template around your email content.
- /// This can be useful for sending out newsletters and/or other HTML formatted messages.
- /// hhttp://docs.sendgrid.com/documentation/apps/email-templates/
- /// </summary>
- public void EnableBypassListManagementEmail()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- var timestamp = DateTime.Now.ToString("HH:mm:ss tt");
- message.Html = "<p style='color:red';>Hello World</p>";
- message.Html += "<p>Sent At : " + timestamp + "</p>";
-
- message.Text = "Hello World plain text";
-
- //set the message subject
- message.Subject = "Hello World Bypass List Management Test";
-
- //create an instance of the Web transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable bypass list management
- message.EnableBypassListManagement();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
-
- /// <summary>
- /// This feature allows you to create a message template, and specify different replacement
- /// strings for each specific recipient
- /// </summary>
- public void AddSubstitutionValues()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Text = "Hi %name%! Pleased to meet you!";
-
- //set the message subject
- message.Subject = "Testing Substitution Values";
-
- //This replacement key must exist in the message body
- var replacementKey = "%name%";
-
- //There should be one value for each recipient in the To list
- var substitutionValues = new List<String> {"Mr Foo", "Mrs Raz"};
-
- message.AddSubstitution(replacementKey, substitutionValues);
-
- //create an instance of the SMTP transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable bypass list management
- message.EnableBypassListManagement();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// This feature adds key value identifiers to be sent back as arguments over the event api for
- /// various events
- /// </summary>
- public void AddUniqueIdentifiers()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Text = "Hello World";
-
- //set the message subject
- message.Subject = "Testing Unique Identifiers";
-
- var identifiers = new Dictionary<String, String>();
- identifiers["customer"] = "someone";
- identifiers["location"] = "somewhere";
-
- message.AddUniqueArgs(identifiers);
-
- //create an instance of the SMTP transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable bypass list management
- message.EnableBypassListManagement();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
-
- /// <summary>
- /// This feature tags the message with a specific tracking category, which will have aggregated stats
- /// viewable from your SendGridMessage account page.
- /// </summary>
- public void SetCategory()
- {
- //create a new message object
- var message = new SendGridMessage();
-
- //set the message recipients
- foreach (var recipient in _to)
- {
- message.AddTo(recipient);
- }
-
- //set the sender
- message.From = new MailAddress(_from);
-
- //set the message body
- message.Text = "Hello World";
-
- //set the message subject
- message.Subject = "Testing Categories";
-
- var category = "vipCustomers";
-
- message.SetCategory(category);
-
- //create an instance of the SMTP transport mechanism
- var transportInstance = new Web(new NetworkCredential(_username, _password));
-
- //enable bypass list management
- message.EnableBypassListManagement();
-
- //send the mail
- transportInstance.DeliverAsync(message);
- }
- }
-}
\ No newline at end of file diff --git a/SendGrid/Example/app.config b/SendGrid/Example/app.config index ea6ea7f..5cbb8d5 100644 --- a/SendGrid/Example/app.config +++ b/SendGrid/Example/app.config @@ -1,25 +1,25 @@ -<?xml version="1.0" encoding="utf-8"?>
+<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
+ <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
- <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
- <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0"/>
+ <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+ <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0" />
</dependentAssembly>
<dependentAssembly>
- <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
- <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0"/>
+ <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+ <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0" />
</dependentAssembly>
<dependentAssembly>
- <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
- <bindingRedirect oldVersion="0.0.0.0-2.2.18.0" newVersion="2.2.18.0"/>
+ <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
+ <bindingRedirect oldVersion="0.0.0.0-2.2.18.0" newVersion="2.2.18.0" />
</dependentAssembly>
<dependentAssembly>
- <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
- <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0"/>
+ <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
+ <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
diff --git a/SendGrid/Example/packages.config b/SendGrid/Example/packages.config index 8aa9f7b..a5881ad 100644 --- a/SendGrid/Example/packages.config +++ b/SendGrid/Example/packages.config @@ -1,5 +1,6 @@ <?xml version="1.0" encoding="utf-8"?>
<packages>
- <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
+ <package id="Newtonsoft.Json" version="8.0.3" targetFramework="net452" />
+ <package id="SendGrid.CSharp.HTTP.Client" version="1.0.2" targetFramework="net45" />
<package id="SendGrid.SmtpApi" version="1.3.1" targetFramework="net45" />
</packages>
\ No newline at end of file diff --git a/SendGrid/SendGrid.sln b/SendGrid/SendGrid.sln index 476f639..c80cffb 100644 --- a/SendGrid/SendGrid.sln +++ b/SendGrid/SendGrid.sln @@ -3,12 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14
VisualStudioVersion = 14.0.23107.0
MinimumVisualStudioVersion = 10.0.40219.1
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Tests", "Tests\Tests.csproj", "{0319E73A-7039-4858-B047-1EDF88BB6BD1}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Example", "Example\Example.csproj", "{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}"
- ProjectSection(ProjectDependencies) = postProject
- {3C687BEF-FF50-44AD-8315-2D4237281AF8} = {3C687BEF-FF50-44AD-8315-2D4237281AF8}
- EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{DAC6CBA4-41D4-490D-B9BE-A8E3AB2E8A96}"
ProjectSection(SolutionItems) = preProject
@@ -16,8 +11,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".nuget", ".nuget", "{DAC6CB .nuget\NuGet.targets = .nuget\NuGet.targets
EndProjectSection
EndProject
-Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mail", "SendGridMail\Mail.csproj", "{3C687BEF-FF50-44AD-8315-2D4237281AF8}"
-EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendGrid", "SendGrid\SendGrid.csproj", "{1C318867-440B-4EB9-99E3-C0CC2C556962}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UnitTests", "UnitTest\UnitTests.csproj", "{8A66032B-0D1C-4F24-B0E3-A250F31D09D8}"
@@ -35,22 +28,6 @@ Global Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|Any CPU.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|Any CPU.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|x86.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.BuildNet45|x86.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Debug|Any CPU.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Debug|Any CPU.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Debug|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Debug|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Debug|x86.ActiveCfg = Debug|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Release|Any CPU.Build.0 = Release|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Release|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Release|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {0319E73A-7039-4858-B047-1EDF88BB6BD1}.Release|x86.ActiveCfg = Release|Any CPU
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.BuildNet45|Any CPU.ActiveCfg = BuildNet45|Any CPU
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.BuildNet45|Mixed Platforms.ActiveCfg = Release|Any CPU
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.BuildNet45|x86.ActiveCfg = BuildNet45|Any CPU
@@ -60,22 +37,6 @@ Global {F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{F39ADCE7-63B5-406D-9BE8-C407920B6B8F}.Release|x86.ActiveCfg = Release|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Any CPU.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Any CPU.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|x86.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.BuildNet45|x86.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Any CPU.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Any CPU.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Debug|x86.ActiveCfg = Debug|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Any CPU.ActiveCfg = Release|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Any CPU.Build.0 = Release|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.ActiveCfg = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|Mixed Platforms.Build.0 = BuildNet45|Any CPU
- {3C687BEF-FF50-44AD-8315-2D4237281AF8}.Release|x86.ActiveCfg = Release|Any CPU
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Any CPU.ActiveCfg = Release|Any CPU
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Any CPU.Build.0 = Release|Any CPU
{1C318867-440B-4EB9-99E3-C0CC2C556962}.BuildNet45|Mixed Platforms.ActiveCfg = Release|Any CPU
diff --git a/SendGrid/SendGrid/App.config b/SendGrid/SendGrid/App.config index 03260cb..1c42520 100644 --- a/SendGrid/SendGrid/App.config +++ b/SendGrid/SendGrid/App.config @@ -1,14 +1,14 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <configuration> <startup> - <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> + <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/> </startup> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> - <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> - <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /> + <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/> + <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> -</configuration>
\ No newline at end of file +</configuration> diff --git a/SendGrid/SendGrid/Client.cs b/SendGrid/SendGrid/Client.cs index 6e86be1..fb08702 100644 --- a/SendGrid/SendGrid/Client.cs +++ b/SendGrid/SendGrid/Client.cs @@ -1,26 +1,16 @@ using System; -using System.Net.Http; -using System.Net.Http.Headers; using System.Reflection; -using System.Threading.Tasks; -using System.Text; -using SendGrid.Resources; -using System.Net; -using Newtonsoft.Json.Linq; +using System.Collections.Generic; +using SendGrid.CSharp.HTTP.Client; namespace SendGrid { - public class Client + public class SendGridAPIClient { private string _apiKey; - public APIKeys ApiKeys; - public UnsubscribeGroups UnsubscribeGroups; - public Suppressions Suppressions; - public GlobalSuppressions GlobalSuppressions; - public GlobalStats GlobalStats; public string Version; + public dynamic client; private Uri _baseUri; - private const string MediaType = "application/json"; private enum Methods { GET, POST, PATCH, DELETE @@ -31,103 +21,16 @@ namespace SendGrid /// </summary> /// <param name="apiKey">Your SendGrid API Key</param> /// <param name="baseUri">Base SendGrid API Uri</param> - public Client(string apiKey, string baseUri = "https://api.sendgrid.com/") + public SendGridAPIClient(string apiKey, string baseUri = "https://api.sendgrid.com", string version = "v3") { _baseUri = new Uri(baseUri); _apiKey = apiKey; Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); - ApiKeys = new APIKeys(this); - UnsubscribeGroups = new UnsubscribeGroups(this); - Suppressions = new Suppressions(this); - GlobalSuppressions = new GlobalSuppressions(this); - GlobalStats = new GlobalStats(this); - } - - /// <summary> - /// Create a client that connects to the SendGrid Web API - /// </summary> - /// <param name="method">HTTP verb, case-insensitive</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - /// <param name="data">An JObject representing the resource's data</param> - /// <returns>An asyncronous task</returns> - private async Task<HttpResponseMessage> RequestAsync(Methods method, string endpoint, JObject data) - { - using (var client = new HttpClient()) - { - try - { - client.BaseAddress = _baseUri; - client.DefaultRequestHeaders.Accept.Clear(); - client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaType)); - client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey); - client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + Version + ";csharp"); - - switch (method) - { - case Methods.GET: - return await client.GetAsync(endpoint); - case Methods.POST: - return await client.PostAsJsonAsync(endpoint, data); - case Methods.PATCH: - endpoint = _baseUri + endpoint; - StringContent content = new StringContent(data.ToString(), Encoding.UTF8, MediaType); - HttpRequestMessage request = new HttpRequestMessage - { - Method = new HttpMethod("PATCH"), - RequestUri = new Uri(endpoint), - Content = content - }; - return await client.SendAsync(request); - case Methods.DELETE: - return await client.DeleteAsync(endpoint); - default: - HttpResponseMessage response = new HttpResponseMessage(); - response.StatusCode = HttpStatusCode.MethodNotAllowed; - var message = "{\"errors\":[{\"message\":\"Bad method call, supported methods are GET, POST, PATCH and DELETE\"}]}"; - response.Content = new StringContent(message); - return response; - } - } - catch (Exception ex) - { - HttpResponseMessage response = new HttpResponseMessage(); - string message; - message = (ex is HttpRequestException) ? ".NET HttpRequestException" : ".NET Exception"; - message = message + ", raw message: \n\n"; - response.Content = new StringContent(message + ex.Message); - return response; - } - } - } - - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - /// <returns>The resulting message from the API call</returns> - public async Task<HttpResponseMessage> Get(string endpoint) - { - return await RequestAsync(Methods.GET, endpoint, null); - } - - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - /// <param name="data">An JObject representing the resource's data</param> - /// <returns>The resulting message from the API call</returns> - public async Task<HttpResponseMessage> Post(string endpoint, JObject data) - { - return await RequestAsync(Methods.POST, endpoint, data); - } - - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - /// <returns>The resulting message from the API call</returns> - public async Task<HttpResponseMessage> Delete(string endpoint) - { - return await RequestAsync(Methods.DELETE, endpoint, null); - } - - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - /// <param name="data">An JObject representing the resource's data</param> - /// <returns>The resulting message from the API call</returns> - public async Task<HttpResponseMessage> Patch(string endpoint, JObject data) - { - return await RequestAsync(Methods.PATCH, endpoint, data); + Dictionary<String, String> requestHeaders = new Dictionary<String, String>(); + requestHeaders.Add("Authorization", "Bearer " + apiKey); + requestHeaders.Add("Content-Type", "application/json"); + requestHeaders.Add("User-Agent", "sendgrid/" + Version + " csharp"); + client = new Client(baseUri, requestHeaders, version); } } } diff --git a/SendGrid/SendGrid/Helpers/Mail/Mail.cs b/SendGrid/SendGrid/Helpers/Mail/Mail.cs new file mode 100644 index 0000000..b41c5ed --- /dev/null +++ b/SendGrid/SendGrid/Helpers/Mail/Mail.cs @@ -0,0 +1,1254 @@ +using Newtonsoft.Json; +using System; +using System.Collections.Generic; + +namespace SendGrid.Helpers.Mail +{ + /// <summary> + /// Class Mail builds an object that sends an email through SendGrid. + /// </summary> + public class Mail + { + private Email from; + private String subject; + private List<Personalization> personalization; + private List<Content> contents; + private List<Attachment> attachments; + private String templateId; + private Dictionary<String, String> headers; + private Dictionary<String, String> sections; + private List<String> categories; + private Dictionary<String, String> customArgs; + private long sendAt; + private ASM asm; + private String batchId; + private String setIpPoolId; + private MailSettings mailSettings; + private TrackingSettings trackingSettings; + private Email replyTo; + + [JsonProperty(PropertyName = "from")] + public Email From + { + get + { + return from; + } + + set + { + from = value; + } + } + + [JsonProperty(PropertyName = "subject")] + public string Subject + { + get + { + return subject; + } + + set + { + subject = value; + } + } + + [JsonProperty(PropertyName = "personalization")] + public List<Personalization> Personalization + { + get + { + return personalization; + } + + set + { + personalization = value; + } + } + + [JsonProperty(PropertyName = "content")] + public List<Content> Contents + { + get + { + return contents; + } + + set + { + contents = value; + } + } + + [JsonProperty(PropertyName = "attachments")] + public List<Attachment> Attachments + { + get + { + return attachments; + } + + set + { + attachments = value; + } + } + + [JsonProperty(PropertyName = "template_id")] + public string TemplateId + { + get + { + return templateId; + } + + set + { + templateId = value; + } + } + + [JsonProperty(PropertyName = "headers")] + public Dictionary<string, string> Headers + { + get + { + return headers; + } + + set + { + headers = value; + } + } + + [JsonProperty(PropertyName = "sections")] + public Dictionary<string, string> Sections + { + get + { + return sections; + } + + set + { + sections = value; + } + } + + [JsonProperty(PropertyName = "categories")] + public List<string> Categories + { + get + { + return categories; + } + + set + { + categories = value; + } + } + + [JsonProperty(PropertyName = "custom_args")] + public Dictionary<string, string> CustomArgs + { + get + { + return customArgs; + } + + set + { + customArgs = value; + } + } + + [JsonProperty(PropertyName = "send_at")] + public long SendAt + { + get + { + return sendAt; + } + + set + { + sendAt = value; + } + } + + [JsonProperty(PropertyName = "asm")] + public ASM Asm + { + get + { + return asm; + } + + set + { + asm = value; + } + } + + [JsonProperty(PropertyName = "batch_id")] + public string BatchId + { + get + { + return batchId; + } + + set + { + batchId = value; + } + } + + [JsonProperty(PropertyName = "ip_pool_name")] + public string SetIpPoolId + { + get + { + return setIpPoolId; + } + + set + { + setIpPoolId = value; + } + } + + [JsonProperty(PropertyName = "mail_settings")] + public MailSettings MailSettings + { + get + { + return mailSettings; + } + + set + { + mailSettings = value; + } + } + + [JsonProperty(PropertyName = "tracking_settings")] + public TrackingSettings TrackingSettings + { + get + { + return trackingSettings; + } + + set + { + trackingSettings = value; + } + } + + [JsonProperty(PropertyName = "reply_to")] + public Email ReplyTo + { + get + { + return replyTo; + } + + set + { + replyTo = value; + } + } + + public void AddPersonalization(Personalization personalization) + { + if (Personalization == null) + { + Personalization = new List<Personalization>(); + } + Personalization.Add(personalization); + } + + public void AddContent(Content content) + { + if (Contents == null) + { + Contents = new List<Content>(); + } + Contents.Add(content); + } + + public void AddAttachment(Attachment attachment) + { + if (Attachments == null) + { + Attachments = new List<Attachment>(); + } + Attachments.Add(attachment); + } + + public void AddHeader(String key, String value) + { + if (headers == null) + { + headers = new Dictionary<String, String>(); + } + headers.Add(key, value); + } + + public void AddSection(String key, String value) + { + if (sections == null) + { + sections = new Dictionary<String, String>(); + } + sections.Add(key, value); + } + + public void AddCategory(String category) + { + if (Categories == null) + { + Categories = new List<String>(); + } + Categories.Add(category); + } + + public void AddCustomArgs(String key, String value) + { + if (customArgs == null) + { + customArgs = new Dictionary<String, String>(); + } + customArgs.Add(key, value); + } + + public String Get() + { + return JsonConvert.SerializeObject(this, + Formatting.None, + new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }); + } + } + + + public class ClickTracking + { + private bool enable; + private bool enableText; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "enable_text")] + public bool EnableText + { + get + { + return enableText; + } + + set + { + enableText = value; + } + } + } + + + public class OpenTracking + { + private bool enable; + private String substitutionTag; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "substitution_tag")] + public string SubstitutionTag + { + get + { + return substitutionTag; + } + + set + { + substitutionTag = value; + } + } + } + + + public class SubscriptionTracking + { + private bool enable; + private String text; + private String html; + private String substitutionTag; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "text")] + public string Text + { + get + { + return text; + } + + set + { + text = value; + } + } + + [JsonProperty(PropertyName = "html")] + public string Html + { + get + { + return html; + } + + set + { + html = value; + } + } + + [JsonProperty(PropertyName = "substitution_tag")] + public string SubstitutionTag + { + get + { + return substitutionTag; + } + + set + { + substitutionTag = value; + } + } + } + + + public class Ganalytics + { + private bool enable; + private String utmSource; + private String utmMedium; + private String utmTerm; + private String utmContent; + private String utmCampaign; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "utm_source")] + public string UtmSource + { + get + { + return utmSource; + } + + set + { + utmSource = value; + } + } + + [JsonProperty(PropertyName = "utm_medium")] + public string UtmMedium + { + get + { + return utmMedium; + } + + set + { + utmMedium = value; + } + } + + [JsonProperty(PropertyName = "utm_term")] + public string UtmTerm + { + get + { + return utmTerm; + } + + set + { + utmTerm = value; + } + } + + [JsonProperty(PropertyName = "utm_content")] + public string UtmContent + { + get + { + return utmContent; + } + + set + { + utmContent = value; + } + } + + [JsonProperty(PropertyName = "utm_name")] + public string UtmCampaign + { + get + { + return utmCampaign; + } + + set + { + utmCampaign = value; + } + } + } + + + public class TrackingSettings + { + private ClickTracking clickTracking; + private OpenTracking openTracking; + private SubscriptionTracking subscriptionTracking; + private Ganalytics ganalytics; + + [JsonProperty(PropertyName = "click_tracking")] + public ClickTracking ClickTracking + { + get + { + return clickTracking; + } + + set + { + clickTracking = value; + } + } + + [JsonProperty(PropertyName = "open_tracking")] + public OpenTracking OpenTracking + { + get + { + return openTracking; + } + + set + { + openTracking = value; + } + } + + [JsonProperty(PropertyName = "subscription_tracking")] + public SubscriptionTracking SubscriptionTracking + { + get + { + return subscriptionTracking; + } + + set + { + subscriptionTracking = value; + } + } + + [JsonProperty(PropertyName = "ganalytics")] + public Ganalytics Ganalytics + { + get + { + return ganalytics; + } + + set + { + ganalytics = value; + } + } + } + + + public class BCCSettings + { + private bool enable; + private String email; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "email")] + public string Email + { + get + { + return email; + } + + set + { + email = value; + } + } + } + + + public class BypassListManagement + { + private bool enable; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + } + + + public class FooterSettings + { + private bool enable; + private String text; + private String html; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "text")] + public string Text + { + get + { + return text; + } + + set + { + text = value; + } + } + + [JsonProperty(PropertyName = "html")] + public string Html + { + get + { + return html; + } + + set + { + html = value; + } + } + } + + + public class SandboxMode + { + private bool enable; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + } + + + public class SpamCheck + { + private bool enable; + private int threshold; + private String postToUrl; + + [JsonProperty(PropertyName = "enable")] + public bool Enable + { + get + { + return enable; + } + + set + { + enable = value; + } + } + + [JsonProperty(PropertyName = "threshold")] + public int Threshold + { + get + { + return threshold; + } + + set + { + threshold = value; + } + } + + [JsonProperty(PropertyName = "post_to_url")] + public string PostToUrl + { + get + { + return postToUrl; + } + + set + { + postToUrl = value; + } + } + } + + + public class MailSettings + { + private BCCSettings bccSettings; + private BypassListManagement bypassListManagement; + private FooterSettings footerSettings; + private SandboxMode sandboxMode; + private SpamCheck spamCheck; + + [JsonProperty(PropertyName = "bcc")] + public BCCSettings BccSettings + { + get + { + return bccSettings; + } + + set + { + bccSettings = value; + } + } + + [JsonProperty(PropertyName = "bypass_list_management")] + public BypassListManagement BypassListManagement + { + get + { + return bypassListManagement; + } + + set + { + bypassListManagement = value; + } + } + + [JsonProperty(PropertyName = "footer")] + public FooterSettings FooterSettings + { + get + { + return footerSettings; + } + + set + { + footerSettings = value; + } + } + + [JsonProperty(PropertyName = "sandbox_mode")] + public SandboxMode SandboxMode + { + get + { + return sandboxMode; + } + + set + { + sandboxMode = value; + } + } + + [JsonProperty(PropertyName = "spam_check")] + public SpamCheck SpamCheck + { + get + { + return spamCheck; + } + + set + { + spamCheck = value; + } + } + } + + + public class ASM + { + private int groupId; + private List<int> groupsToDisplay; + + [JsonProperty(PropertyName = "group_id")] + public int GroupId + { + get + { + return groupId; + } + + set + { + groupId = value; + } + } + + [JsonProperty(PropertyName = "groups_to_display")] + public List<int> GroupsToDisplay + { + get + { + return groupsToDisplay; + } + + set + { + groupsToDisplay = value; + } + } + } + + + public class Attachment + { + private String content; + private String type; + private String filename; + private String disposition; + private String contentId; + + [JsonProperty(PropertyName = "content")] + public string Content + { + get + { + return content; + } + + set + { + content = value; + } + } + + [JsonProperty(PropertyName = "type")] + public string Type + { + get + { + return type; + } + + set + { + type = value; + } + } + + [JsonProperty(PropertyName = "filename")] + public string Filename + { + get + { + return filename; + } + + set + { + filename = value; + } + } + + [JsonProperty(PropertyName = "disposition")] + public string Disposition + { + get + { + return disposition; + } + + set + { + disposition = value; + } + } + + [JsonProperty(PropertyName = "content_id")] + public string ContentId + { + get + { + return contentId; + } + + set + { + contentId = value; + } + } + } + + + public class Content + { + private String type; + private String value; + + [JsonProperty(PropertyName = "type")] + public string Type + { + get + { + return type; + } + + set + { + type = value; + } + } + + [JsonProperty(PropertyName = "value")] + public string Value + { + get + { + return value; + } + + set + { + this.value = value; + } + } + } + + + public class Email + { + private String name; + private String address; + + [JsonProperty(PropertyName = "name")] + public string Name + { + get + { + return name; + } + + set + { + name = value; + } + } + + [JsonProperty(PropertyName = "email")] + public string Address + { + get + { + return address; + } + + set + { + address = value; + } + } + } + + + public class Personalization + { + private List<Email> to; + private List<Email> cc; + private List<String> bcc; + private String subject; + private Dictionary<String, String> headers; + private Dictionary<String, String> substitutions; + private Dictionary<String, String> customArgs; + private long sendAt; + + [JsonProperty(PropertyName = "to")] + public List<Email> To + { + get + { + return to; + } + + set + { + to = value; + } + } + + [JsonProperty(PropertyName = "cc")] + public List<Email> Cc + { + get + { + return cc; + } + + set + { + cc = value; + } + } + + [JsonProperty(PropertyName = "bcc")] + public List<string> Bcc + { + get + { + return bcc; + } + + set + { + bcc = value; + } + } + + [JsonProperty(PropertyName = "subject")] + public string Subject + { + get + { + return subject; + } + + set + { + subject = value; + } + } + + [JsonProperty(PropertyName = "headers")] + public Dictionary<string, string> Headers + { + get + { + return headers; + } + + set + { + headers = value; + } + } + + [JsonProperty(PropertyName = "substitutions")] + public Dictionary<string, string> Substitutions + { + get + { + return substitutions; + } + + set + { + substitutions = value; + } + } + + [JsonProperty(PropertyName = "custom_args")] + public Dictionary<string, string> CustomArgs + { + get + { + return customArgs; + } + + set + { + customArgs = value; + } + } + + [JsonProperty(PropertyName = "send_at")] + public long SendAt + { + get + { + return sendAt; + } + + set + { + sendAt = value; + } + } + + public void AddTo(Email email) + { + if (to == null) + { + to = new List<Email>(); + + } + to.Add(email); + } + + public void AddCc(Email email) + { + if (cc == null) + { + cc = new List<Email>(); + } + cc.Add(email); + } + + public void AddBcc(String email) + { + if (bcc == null) + { + bcc = new List<String>(); + } + bcc.Add(email); + } + + public void AddHeader(String key, String value) + { + if (headers == null) + { + headers = new Dictionary<String, String>(); + } + headers.Add(key, value); + } + + public void AddSubstitution(String key, String value) + { + if (substitutions == null) + { + substitutions = new Dictionary<String, String>(); + } + substitutions.Add(key, value); + } + + public void AddCustomArgs(String key, String value) + { + if (customArgs == null) + { + customArgs = new Dictionary<String, String>(); + } + customArgs.Add(key, value); + } + } +} + diff --git a/SendGrid/SendGrid/Helpers/Mail/README.md b/SendGrid/SendGrid/Helpers/Mail/README.md new file mode 100644 index 0000000..6895f29 --- /dev/null +++ b/SendGrid/SendGrid/Helpers/Mail/README.md @@ -0,0 +1,16 @@ +**This helper allows you to quickly and easily build a Mail object for sending email through SendGrid.** + +## Dependencies + +- [JSON.Net](http://www.newtonsoft.com/json) + +# Quick Start + +Run the [example]() (make sure you have set your environment variable to include your SENDGRID_API_KEY). + +Click on the Example project, then click the `Start` button in the menu. + +## Usage + +- See the example for a complete working example. +- [Documentation]()
\ No newline at end of file diff --git a/SendGrid/SendGrid/Properties/AssemblyInfo.cs b/SendGrid/SendGrid/Properties/AssemblyInfo.cs index 9bf8337..19dd8fe 100644 --- a/SendGrid/SendGrid/Properties/AssemblyInfo.cs +++ b/SendGrid/SendGrid/Properties/AssemblyInfo.cs @@ -32,5 +32,5 @@ using System.Runtime.InteropServices; // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("6.3.4")] -[assembly: AssemblyFileVersion("6.3.4ss")] +[assembly: AssemblyVersion("7.0.0")] +[assembly: AssemblyFileVersion("7.0.0")] diff --git a/SendGrid/SendGrid/Resources/APIKeys.cs b/SendGrid/SendGrid/Resources/APIKeys.cs deleted file mode 100644 index 37bd4a7..0000000 --- a/SendGrid/SendGrid/Resources/APIKeys.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System.Net.Http; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; - -namespace SendGrid.Resources -{ - public class APIKeys - { - private string _endpoint; - private Client _client; - - /// <summary> - /// Constructs the SendGrid APIKeys object. - /// See https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html - /// </summary> - /// <param name="client">SendGrid Web API v3 client</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - public APIKeys(Client client, string endpoint = "v3/api_keys") - { - _endpoint = endpoint; - _client = client; - } - - /// <summary> - /// Get a list of active API Keys - /// </summary> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html</returns> - public async Task<HttpResponseMessage> Get() - { - return await _client.Get(_endpoint); - } - - /// <summary> - /// Create a new API key - /// </summary> - /// <param name="apiKeyName">Name of the new API Key</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html</returns> - public async Task<HttpResponseMessage> Post(string apiKeyName) - { - var data = new JObject {{"name", apiKeyName}}; - return await _client.Post(_endpoint, data); - } - - /// <summary> - /// Delete a API key - /// </summary> - /// <param name="apiKeyId">ID of the API Key to delete</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html</returns> - public async Task<HttpResponseMessage> Delete(string apiKeyId) - { - return await _client.Delete(_endpoint + "/" + apiKeyId); - } - - /// <summary> - /// Patch a API key - /// </summary> - /// <param name="apiKeyId">ID of the API Key to rename</param> - /// <param name="apiKeyName">New API Key name</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/API_Keys/index.html</returns> - public async Task<HttpResponseMessage> Patch(string apiKeyId, string apiKeyName) - { - var data = new JObject { { "name", apiKeyName } }; - return await _client.Patch(_endpoint + "/" + apiKeyId, data); - } - - } -}
\ No newline at end of file diff --git a/SendGrid/SendGrid/Resources/GlobalStats.cs b/SendGrid/SendGrid/Resources/GlobalStats.cs deleted file mode 100644 index 73f0b33..0000000 --- a/SendGrid/SendGrid/Resources/GlobalStats.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Net.Http; -using System.Threading.Tasks; -using System.Web; - -namespace SendGrid.Resources -{ - public class GlobalStats - { - private string _endpoint; - private Client _client; - - /// <summary> - /// Constructs the SendGrid GlobalStats object. - /// See https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html - /// </summary> - /// <param name="client">SendGrid Web API v3 client</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - public GlobalStats(Client client, string endpoint = "v3/stats") - { - _endpoint = endpoint; - _client = client; - } - - /// <summary> - /// https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html - /// </summary> - /// <param name="startDate">The starting date of the statistics to retrieve, formatted as YYYY-MM-DD.</param> - /// <param name="endDate">The end date of the statistics to retrieve, formatted as YYYY-MM-DD. Defaults to today.</param> - /// <param name="aggregatedBy">How to group the statistics, must be day|week|month</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Stats/global.html</returns> - public async Task<HttpResponseMessage> Get(string startDate, string endDate = null, string aggregatedBy = null) - { - var query = HttpUtility.ParseQueryString(string.Empty); - query["start_date"] = startDate; - if (endDate != null) - { - query["end_date"] = endDate; - } - if (aggregatedBy != null) - { - query["aggregated_by"] = aggregatedBy; - } - return await _client.Get(_endpoint + "?" + query); - } - - } -}
\ No newline at end of file diff --git a/SendGrid/SendGrid/Resources/GlobalSuppressions.cs b/SendGrid/SendGrid/Resources/GlobalSuppressions.cs deleted file mode 100644 index 36fcd18..0000000 --- a/SendGrid/SendGrid/Resources/GlobalSuppressions.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.Net.Http; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; - -namespace SendGrid.Resources -{ - public class GlobalSuppressions - { - private string _endpoint; - private Client _client; - - /// <summary> - /// Constructs the SendGrid Global Suppressions object. - /// See https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html - /// </summary> - /// <param name="client">SendGrid Web API v3 client</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - public GlobalSuppressions(Client client, string endpoint = "v3/asm/suppressions/global") - { - _endpoint = endpoint; - _client = client; - } - - /// <summary> - /// Check if a recipient address is in the global suppressions group. - /// </summary> - /// <param name="email">email address to check</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html</returns> - public async Task<HttpResponseMessage> Get(string email) - { - return await _client.Get(_endpoint + "/" + email); - } - - /// <summary> - /// Add recipient addresses to the global suppression group. - /// </summary> - /// <param name="recipient_emails">Array of email addresses to add to the suppression group</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html</returns> - public async Task<HttpResponseMessage> Post(string[] emails) - { - JArray receipient_emails = new JArray(); - foreach (string email in emails) { receipient_emails.Add(email); } - var data = new JObject(new JProperty("recipient_emails", receipient_emails)); - return await _client.Post(_endpoint, data); - } - - /// <summary> - /// Delete a recipient email from the global suppressions group. - /// </summary> - /// <param name="email">email address to be removed from the global suppressions group</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/global_suppressions.html</returns> - public async Task<HttpResponseMessage> Delete(string email) - { - return await _client.Delete(_endpoint + "/" + email); - } - } -}
\ No newline at end of file diff --git a/SendGrid/SendGrid/Resources/Suppressions.cs b/SendGrid/SendGrid/Resources/Suppressions.cs deleted file mode 100644 index 91bb38d..0000000 --- a/SendGrid/SendGrid/Resources/Suppressions.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System.Net.Http; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; - -namespace SendGrid.Resources -{ - public class Suppressions - { - private string _endpoint; - private Client _client; - - /// <summary> - /// Constructs the SendGrid Suppressions object. - /// See https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html - /// </summary> - /// <param name="client">SendGrid Web API v3 client</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - public Suppressions(Client client, string endpoint = "v3/asm/groups") - { - _endpoint = endpoint; - _client = client; - } - - /// <summary> - /// Get suppressed addresses for a given group. - /// </summary> - /// <param name="groupId">ID of the suppression group</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html</returns> - public async Task<HttpResponseMessage> Get(int groupId) - { - return await _client.Get(_endpoint + "/" + groupId.ToString() + "/suppressions"); - } - - /// <summary> - /// Add recipient addresses to the suppressions list for a given group. - /// - /// If the group has been deleted, this request will add the address to the global suppression. - /// </summary> - /// <param name="groupId">ID of the suppression group</param> - /// <param name="recipient_emails">Array of email addresses to add to the suppression group</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html</returns> - public async Task<HttpResponseMessage> Post(int groupId, string[] emails) - { - JArray receipient_emails = new JArray(); - foreach (string email in emails) { receipient_emails.Add(email); } - var data = new JObject(new JProperty("recipient_emails", receipient_emails)); - return await _client.Post(_endpoint + "/" + groupId.ToString() + "/suppressions", data); - } - - /// <summary> - /// Delete a suppression group. - /// </summary> - /// <param name="groupId">ID of the suppression group to delete</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/suppressions.html</returns> - public async Task<HttpResponseMessage> Delete(int groupId, string email) - { - return await _client.Delete(_endpoint + "/" + groupId.ToString() + "/suppressions/" + email); - } - } -}
\ No newline at end of file diff --git a/SendGrid/SendGrid/Resources/UnsubscribeGroups.cs b/SendGrid/SendGrid/Resources/UnsubscribeGroups.cs deleted file mode 100644 index db8e4d2..0000000 --- a/SendGrid/SendGrid/Resources/UnsubscribeGroups.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Net.Http; -using System.Threading.Tasks; -using Newtonsoft.Json.Linq; - -namespace SendGrid.Resources -{ - public class UnsubscribeGroups - { - private string _endpoint; - private Client _client; - - /// <summary> - /// Constructs the SendGrid UnsubscribeGroups object. - /// See https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html - /// </summary> - /// <param name="client">SendGrid Web API v3 client</param> - /// <param name="endpoint">Resource endpoint, do not prepend slash</param> - public UnsubscribeGroups(Client client, string endpoint = "v3/asm/groups") - { - _endpoint = endpoint; - _client = client; - } - - /// <summary> - /// Retrieve all suppression groups associated with the user. - /// </summary> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html</returns> - public async Task<HttpResponseMessage> Get() - { - return await _client.Get(_endpoint); - } - - /// <summary> - /// Get information on a single suppression group. - /// </summary> - /// <param name="unsubscribeGroupId">ID of the suppression group to delete</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html</returns> - public async Task<HttpResponseMessage> Get(int unsubscribeGroupId) - { - return await _client.Get(_endpoint + "/" + unsubscribeGroupId); - } - - /// <summary> - /// Create a new suppression group. - /// </summary> - /// <param name="unsubscribeGroupName">The name of the new suppression group</param> - /// <param name="unsubscribeGroupDescription">A description of the suppression group</param> - /// <param name="unsubscribeGroupIsDefault">Default value is false</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html</returns> - public async Task<HttpResponseMessage> Post(string unsubscribeGroupName, - string unsubscribeGroupDescription, - bool unsubscribeGroupIsDefault) - { - var data = new JObject {{"name", unsubscribeGroupName}, - {"description", unsubscribeGroupDescription}, - {"is_default", unsubscribeGroupIsDefault}}; - return await _client.Post(_endpoint, data); - } - - /// <summary> - /// Delete a suppression group. - /// </summary> - /// <param name="unsubscribeGroupId">ID of the suppression group to delete</param> - /// <returns>https://sendgrid.com/docs/API_Reference/Web_API_v3/Suppression_Management/groups.html</returns> - public async Task<HttpResponseMessage> Delete(string unsubscribeGroupId) - { - return await _client.Delete(_endpoint + "/" + unsubscribeGroupId); - } - } -}
\ No newline at end of file diff --git a/SendGrid/SendGrid/SendGrid.csproj b/SendGrid/SendGrid/SendGrid.csproj index 2f5bcf6..b2e832f 100644 --- a/SendGrid/SendGrid/SendGrid.csproj +++ b/SendGrid/SendGrid/SendGrid.csproj @@ -9,7 +9,7 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>SendGrid</RootNamespace> <AssemblyName>SendGrid</AssemblyName> - <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <TargetFrameworkProfile /> @@ -43,6 +43,10 @@ <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <ItemGroup> + <Reference Include="CSharpHTTPClient, Version=1.0.2.0, Culture=neutral, PublicKeyToken=79219bf4e5ecaaca, processorArchitecture=MSIL"> + <HintPath>..\packages\SendGrid.CSharp.HTTP.Client.1.0.2\lib\CSharpHTTPClient.dll</HintPath> + <Private>True</Private> + </Reference> <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath> <Private>True</Private> @@ -64,12 +68,8 @@ </ItemGroup> <ItemGroup> <Compile Include="Client.cs" /> + <Compile Include="Helpers\Mail\Mail.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Resources\GlobalSuppressions.cs" /> - <Compile Include="Resources\GlobalStats.cs" /> - <Compile Include="Resources\Suppressions.cs" /> - <Compile Include="Resources\UnsubscribeGroups.cs" /> - <Compile Include="Resources\APIKeys.cs" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> diff --git a/SendGrid/SendGrid/packages.config b/SendGrid/SendGrid/packages.config index b24a212..74b8a6b 100644 --- a/SendGrid/SendGrid/packages.config +++ b/SendGrid/SendGrid/packages.config @@ -2,4 +2,5 @@ <packages> <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" /> <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" /> + <package id="SendGrid.CSharp.HTTP.Client" version="1.0.2" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Exceptions/InvalidApiRequestException.cs b/SendGrid/SendGridMail/Exceptions/InvalidApiRequestException.cs deleted file mode 100644 index 7fd51ea..0000000 --- a/SendGrid/SendGridMail/Exceptions/InvalidApiRequestException.cs +++ /dev/null @@ -1,19 +0,0 @@ -using System; -using System.Net; - -namespace Exceptions -{ - public class InvalidApiRequestException : Exception - { - public InvalidApiRequestException(HttpStatusCode httpStatusCode, string[] errors, string httpResponsePhrase) - : base(httpResponsePhrase + " Check `Errors` for a list of errors returned by the API.") - { - ResponseStatusCode = httpStatusCode; - Errors = errors; - } - - public String[] Errors { get; set; } - - public HttpStatusCode ResponseStatusCode { get; private set; } - } -} diff --git a/SendGrid/SendGridMail/ISendGrid.cs b/SendGrid/SendGridMail/ISendGrid.cs deleted file mode 100644 index 38a931a..0000000 --- a/SendGrid/SendGridMail/ISendGrid.cs +++ /dev/null @@ -1,302 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net.Mail;
-using SendGrid.SmtpApi;
-
-namespace SendGrid
-{
- /// <summary>
- /// Represents the basic set of functions that will be called by the user
- /// includes basic message data manipulation and filter settings
- /// </summary>
- public interface ISendGrid
- {
- #region Properties
-
- MailAddress From { get; set; }
- MailAddress[] To { get; set; }
- MailAddress[] Cc { get; set; }
- MailAddress[] Bcc { get; set; }
- MailAddress[] ReplyTo { get; set; }
- Dictionary<String, MemoryStream> StreamedAttachments { get; set; }
- String[] Attachments { get; set; }
- String Subject { get; set; }
- Dictionary<String, String> Headers { get; set; }
- IHeader Header { get; set; }
- String Html { get; set; }
- String Text { get; set; }
-
- #endregion
-
- #region Interface for ITransport
-
- /// <summary>
- /// Used by the Transport object to create a MIME for SMTP
- /// </summary>
- /// <returns>MIME to be sent</returns>
- MailMessage CreateMimeMessage();
-
- #endregion
-
- #region Methods for setting data
-
- /// <summary>
- /// Add to the 'To' address.
- /// </summary>
- /// <param name="address">single string eg. 'you@company.com'</param>
- void AddTo(String address);
-
- /// <summary>
- /// Add to the 'To' address.
- /// </summary>
- /// <param name="addresses">list of email addresses as strings</param>
- void AddTo(IEnumerable<String> addresses);
-
- /// <summary>
- /// Add to the 'To' address.
- /// </summary>
- /// <param name="addresssInfo">
- /// the dictionary keys are the email addresses, which points to a dictionary of
- /// key substitutionValues pairs mapping to other address codes, such as { foo@bar.com => { 'DisplayName' => 'Mr Foo' }
- /// }
- /// </param>
- void AddTo(IDictionary<String, IDictionary<String, String>> addresssInfo);
-
- /// <summary>
- /// Defines a mapping between a replacement string in the text of the message to a section of
- /// substitution values to be used
- /// </summary>
- /// <param name="replacementTag">the string in the email that you'll replace eg. '-itemsOrdered-'</param>
- /// <param name="sectionValue">
- /// The content that will be substituted in for the replacementTag
- /// </param>
- void AddSection(String replacementTag, String sectionValue);
-
- /// <summary>
- /// Defines a mapping between a replacement string in the text of the message to a list of
- /// substitution values to be used, one per each recipient, in the same order as the recipients were added.
- /// </summary>
- /// <param name="replacementTag">the string in the email that you'll replace eg. '-name-'</param>
- /// <param name="substitutionValues">
- /// a list of values that will be substituted in for the replacementTag, one for each
- /// recipient
- /// </param>
- void AddSubstitution(String replacementTag, List<String> substitutionValues);
-
- /// <summary>
- /// This adds parameters and values that will be bassed back through SendGrid's
- /// Event API if an event notification is triggered by this email.
- /// </summary>
- /// <param name="identifiers">parameter substitutionValues pairs to be passed back on event notification</param>
- void AddUniqueArgs(IDictionary<String, String> identifiers);
-
- /// <summary>
- /// This sets the suppression group id for this email.
- /// </summary>
- /// <param name="id">the id of the suppression group</param>
- void SetAsmGroupId(int id);
-
- /// <summary>
- /// This sets the category for this email. Statistics are stored on a per category
- /// basis, so this can be useful for tracking on a per group basis.
- /// </summary>
- /// <param name="category">categories applied to the message</param>
- void SetCategory(String category);
-
- /// <summary>
- /// This sets the categories for this email. Statistics are stored on a per category
- /// basis, so this can be useful for tracking on a per group basis.
- /// </summary>
- /// <param name="categories">categories applied to the message</param>
- void SetCategories(IEnumerable<String> categories);
-
- /// <summary>
- /// This sets the IP Pool for this email.
- /// </summary>
- /// <param name="pool">The name of the pool with which to send the message.</param>
- void SetIpPool(String pool);
-
- /// <summary>
- /// Define a send_at timestamp to schedule this send for the future.
- /// </summary>
- /// <param name="sendTime">The time at which to send the email</param>
- void SetSendAt(DateTime sendTime);
-
- /// <summary>
- /// Define a send_each_at timestamp to schedule individual send times per message
- /// </summary>
- /// <param name="sendTimes">The times at which to send the emails</param>
- void SetSendEachAt(IEnumerable<DateTime> sendTimes);
-
- /// <summary>
- /// Add an attachment to the message.
- /// </summary>
- /// <param name="filePath">a fully qualified file path as a string</param>
- void AddAttachment(String filePath);
-
- /// <summary>
- /// Add a stream as an attachment to the message
- /// </summary>
- /// <param name="stream">Stream of file to be attached</param>
- /// <param name="name">Name of file to be attached</param>
- void AddAttachment(Stream stream, String name);
-
- void EmbedStreamImage(Stream stream, String name);
-
- /// <summary>
- /// GetRecipients returns a list of all the recepients by retrieving the to, cc, and bcc lists.
- /// </summary>
- /// <returns></returns>
- IEnumerable<String> GetRecipients();
-
- /// <summary>
- /// Add custom headers to the message
- /// </summary>
- /// <param name="headers">key substitutionValues pairs</param>
- void AddHeaders(IDictionary<String, String> headers);
-
- /// <summary>
- /// Gets the list of embedded images
- /// </summary>
- /// <returns></returns>
- IDictionary<string, string> GetEmbeddedImages();
-
- #endregion
-
- #region SMTP API Functions
-
- /// <summary>
- /// Disable the gravatar app
- /// </summary>
- void DisableGravatar();
-
- /// <summary>
- /// Disable the open tracking app
- /// </summary>
- void DisableOpenTracking();
-
- /// <summary>
- /// Disable the click tracking app
- /// </summary>
- void DisableClickTracking();
-
- /// <summary>
- /// Disable the spam check
- /// </summary>
- void DisableSpamCheck();
-
- /// <summary>
- /// Disable the unsubscribe app
- /// </summary>
- void DisableUnsubscribe();
-
- /// <summary>
- /// Disable the footer app
- /// </summary>
- void DisableFooter();
-
- /// <summary>
- /// Disable the Google Analytics app
- /// </summary>
- void DisableGoogleAnalytics();
-
- /// <summary>
- /// Disable the templates app
- /// </summary>
- void DisableTemplate();
-
- /// <summary>
- /// Disable Bcc app
- /// </summary>
- void DisableBcc();
-
- /// <summary>
- /// Disable the Bypass List Management app
- /// </summary>
- void DisableBypassListManagement();
-
- /// <summary>
- /// Inserts the gravatar image of the sender to the bottom of the message
- /// </summary>
- void EnableGravatar();
-
- /// <summary>
- /// Adds an invisible image to the end of the email which can track e-mail opens.
- /// </summary>
- void EnableOpenTracking();
-
- /// <summary>
- /// Causes all links to be overwritten, shortened, and pointed to SendGrid's servers so clicks will be tracked.
- /// </summary>
- /// <param name="includePlainText">true if links found in plain text portions of the message are to be overwritten</param>
- void EnableClickTracking(bool includePlainText = false);
-
- /// <summary>
- /// Provides notification when emails are deteched that exceed a predefined spam threshold.
- /// </summary>
- /// <param name="score">
- /// Emails with a SpamAssassin score over this substitutionValues will be considered spam and not be
- /// delivered.
- /// </param>
- /// <param name="url">SendGridMessage will send an HTTP POST request to this url when a message is detected as spam</param>
- void EnableSpamCheck(int score = 5, String url = null);
-
- /// <summary>
- /// Allow's SendGridMessage to manage unsubscribes and ensure these users don't get future emails from the sender
- /// </summary>
- /// <param name="text">String for the plain text email body showing what you want the message to look like.</param>
- /// <param name="html">String for the HTML email body showing what you want the message to look like.</param>
- void EnableUnsubscribe(String text, String html);
-
- /// <summary>
- /// Allow's SendGridMessage to manage unsubscribes and ensure these users don't get future emails from the sender
- /// </summary>
- /// <param name="replace">Tag in the message body to be replaced with the unsubscribe link and message</param>
- void EnableUnsubscribe(String replace);
-
- /// <summary>
- /// Attaches a message at the footer of the email
- /// </summary>
- /// <param name="text">Message for the plain text body of the email</param>
- /// <param name="html">Message for the HTML body of the email</param>
- void EnableFooter(String text = null, String html = null);
-
- /// <summary>
- /// Re-writes links to integrate with Google Analytics
- /// </summary>
- /// <param name="source">Name of the referrer source (e.g. Google, SomeDomain.com, NewsletterA)</param>
- /// <param name="medium">Name of the marketing medium (e.g. Email)</param>
- /// <param name="term">Identify paid keywords</param>
- /// <param name="content">Use to differentiate ads</param>
- /// <param name="campaign">Name of the campaign</param>
- void EnableGoogleAnalytics(String source, String medium, String term, String content = null, String campaign = null);
-
- /// <summary>
- /// Wraps an HTML template around your email content.
- /// </summary>
- /// <param name="html">HTML that your emails will be wrapped in, containing a body replacementTag.</param>
- void EnableTemplate(String html = null);
-
- /// <summary>
- /// Enable a Template Engine template via the template ID
- /// </summary>
- /// <param name="template_id">The ID of the Template Engine template to use.</param>
- void EnableTemplateEngine(String templateId);
-
- /// <summary>
- /// Automatically sends a blind carbon copy to an address for every e-mail sent, without
- /// adding that address to the header.
- /// </summary>
- /// <param name="email">A single email recipient</param>
- void EnableBcc(String email = null);
-
- /// <summary>
- /// Enabing this app will bypass the normal unsubscribe / bounce / spam report checks
- /// and queue the e-mail for delivery.
- /// </summary>
- void EnableBypassListManagement();
-
- #endregion
- }
-}
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Mail.csproj b/SendGrid/SendGridMail/Mail.csproj deleted file mode 100644 index 85ee4a3..0000000 --- a/SendGrid/SendGridMail/Mail.csproj +++ /dev/null @@ -1,154 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
- <SignAssembly>false</SignAssembly>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
- <DebugType>pdbonly</DebugType>
- <OutputPath>bin\Debug\</OutputPath>
- <DefineConstants>TRACE, DEBUG</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <RestorePackages>true</RestorePackages>
- <Prefer32Bit>false</Prefer32Bit>
- <BuildPackage>false</BuildPackage>
- <SignAssembly>false</SignAssembly>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)' == 'BuildNet45'">
- <SignAssembly>false</SignAssembly>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
- <DebugType>pdbonly</DebugType>
- <OutputPath>bin\BuildNet45\</OutputPath>
- <DefineConstants>TRACE, BUILD</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <RestorePackages>true</RestorePackages>
- <Prefer32Bit>false</Prefer32Bit>
- <BuildPackage>false</BuildPackage>
- <SignAssembly>false</SignAssembly>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)' == 'Release'">
- <SignAssembly>true</SignAssembly>
- <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
- <DebugType>pdbonly</DebugType>
- <Optimize>True</Optimize>
- <OutputPath>bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup>
- <ProjectGuid>{3C687BEF-FF50-44AD-8315-2D4237281AF8}</ProjectGuid>
- <PublishUrl>publish\</PublishUrl>
- <Install>true</Install>
- <InstallFrom>Disk</InstallFrom>
- <UpdateEnabled>false</UpdateEnabled>
- <UpdateMode>Foreground</UpdateMode>
- <UpdateInterval>7</UpdateInterval>
- <UpdateIntervalUnits>Days</UpdateIntervalUnits>
- <UpdatePeriodically>false</UpdatePeriodically>
- <UpdateRequired>false</UpdateRequired>
- <MapFileExtensions>true</MapFileExtensions>
- <ApplicationRevision>0</ApplicationRevision>
- <ApplicationVersion>1.0.0.%2a</ApplicationVersion>
- <IsWebBootstrapper>false</IsWebBootstrapper>
- <UseApplicationTrust>false</UseApplicationTrust>
- <BootstrapperEnabled>true</BootstrapperEnabled>
- <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
- <RestorePackages>true</RestorePackages>
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <TargetFrameworkProfile />
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
- </PropertyGroup>
- <PropertyGroup>
- <OutputType>Library</OutputType>
- </PropertyGroup>
- <PropertyGroup>
- <AssemblyName>SendGridMail</AssemblyName>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile>
- <SignAssembly>true</SignAssembly>
- <DefineConstants>TRACE, RELEASE</DefineConstants>
- <DebugType>
- </DebugType>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'BuildNet45|AnyCPU' ">
- <Optimize>false</Optimize>
- <SignAssembly>false</SignAssembly>
- <DebugType>
- </DebugType>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
- <SignAssembly>false</SignAssembly>
- <Optimize>false</Optimize>
- <DebugType>
- </DebugType>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup>
- <SignAssembly>true</SignAssembly>
- </PropertyGroup>
- <PropertyGroup>
- <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="SendGrid.SmtpApi, Version=1.3.1.0, Culture=neutral, PublicKeyToken=2ae73662c35d80e4, processorArchitecture=MSIL">
- <SpecificVersion>False</SpecificVersion>
- <HintPath>..\packages\SendGrid.SmtpApi.1.3.1\lib\net40\SendGrid.SmtpApi.dll</HintPath>
- </Reference>
- <Reference Include="System" />
- <Reference Include="System.Net" />
- <Reference Include="System.Net.Http" />
- <Reference Include="System.Xml" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="Exceptions\InvalidApiRequestException.cs" />
- <Compile Include="ISendGrid.cs" />
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="SendGrid.cs" />
- <Compile Include="Transport\ErrorChecker.cs" />
- <Compile Include="Transport\ITransport.cs" />
- <Compile Include="Transport\Web.cs" />
- </ItemGroup>
- <ItemGroup>
- <None Include="packages.config" />
- <None Include="sendgrid-csharp.snk" />
- </ItemGroup>
- <ItemGroup>
- <BootstrapperPackage Include=".NETFramework,Version=v4.0">
- <Visible>False</Visible>
- <ProductName>Microsoft .NET Framework 4 %28x86 and x64%29</ProductName>
- <Install>true</Install>
- </BootstrapperPackage>
- <BootstrapperPackage Include="Microsoft.Net.Client.3.5">
- <Visible>False</Visible>
- <ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
- <Install>false</Install>
- </BootstrapperPackage>
- <BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
- <Visible>False</Visible>
- <ProductName>.NET Framework 3.5 SP1</ProductName>
- <Install>false</Install>
- </BootstrapperPackage>
- <BootstrapperPackage Include="Microsoft.Windows.Installer.4.5">
- <Visible>False</Visible>
- <ProductName>Windows Installer 4.5</ProductName>
- <Install>true</Install>
- </BootstrapperPackage>
- </ItemGroup>
- <ItemGroup />
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
- <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
- Other similar extension points exist, see Microsoft.Common.targets.
- <Target Name="BeforeBuild">
- </Target>
- <Target Name="AfterBuild">
- </Target>
- -->
-</Project>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Properties/AssemblyInfo.cs b/SendGrid/SendGridMail/Properties/AssemblyInfo.cs deleted file mode 100644 index 540b5e9..0000000 --- a/SendGrid/SendGridMail/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-
-[assembly: AssemblyTitle("SendGridMail")]
-[assembly: AssemblyDescription("A client library for interfacing with the SendGridMessage API")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("SendGridMessage")]
-[assembly: AssemblyProduct("SendGridMail")]
-[assembly: AssemblyCopyright("Copyright © 2015")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-
-[assembly: Guid("193fa200-8430-4206-aacd-2d2bb2dfa6cf")]
-
-#if (BUILD)
-[assembly: InternalsVisibleTo("Tests," + "" +
- "PublicKey=0024000004800000940000000602000000240000525341310004000001000100812ec26a66c8e0" +
- "8c790704ac4b46bcc9da9f4bca4da0ec7c06ce6dcd73baeb2c5525f36a237b253e80e16febb4c0" +
- "52f50734d5e1cf3bf478d9c88f0f69df53b47306419182983bc35c33c3bafb5e90b9bd7aa7b9a9" +
- "da09abe3667d50db891012e077e4b9aefe9799a58222fa67127c230219755d7670073c7463d90c" +
- "f9e79dba")]
-#elif (DEBUG)
-[assembly: InternalsVisibleTo("Tests," + "" +
- "PublicKey=0024000004800000940000000602000000240000525341310004000001000100812ec26a66c8e0" +
- "8c790704ac4b46bcc9da9f4bca4da0ec7c06ce6dcd73baeb2c5525f36a237b253e80e16febb4c0" +
- "52f50734d5e1cf3bf478d9c88f0f69df53b47306419182983bc35c33c3bafb5e90b9bd7aa7b9a9" +
- "da09abe3667d50db891012e077e4b9aefe9799a58222fa67127c230219755d7670073c7463d90c" +
- "f9e79dba")]
-#else
-[assembly: InternalsVisibleTo("Tests," + "" +
- "PublicKey=0024000004800000940000000602000000240000525341310004000001000100812ec26a66c8e0" +
- "8c790704ac4b46bcc9da9f4bca4da0ec7c06ce6dcd73baeb2c5525f36a237b253e80e16febb4c0" +
- "52f50734d5e1cf3bf478d9c88f0f69df53b47306419182983bc35c33c3bafb5e90b9bd7aa7b9a9" +
- "da09abe3667d50db891012e077e4b9aefe9799a58222fa67127c230219755d7670073c7463d90c" +
- "f9e79dba")]
-#endif
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("6.3.4")]
-[assembly: AssemblyFileVersion("6.3.4")]
\ No newline at end of file diff --git a/SendGrid/SendGridMail/SendGrid.cs b/SendGrid/SendGridMail/SendGrid.cs deleted file mode 100644 index 1581f40..0000000 --- a/SendGrid/SendGridMail/SendGrid.cs +++ /dev/null @@ -1,550 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.IO;
-using System.Linq;
-using System.Net.Mail;
-using System.Net.Mime;
-using System.Text.RegularExpressions;
-using SendGrid.SmtpApi;
-
-namespace SendGrid
-{
- public class SendGridMessage : ISendGrid
- {
- #region constants/vars
-
- //apps list and settings
- private static readonly Dictionary<String, String> Filters = InitializeFilters();
- private readonly MailMessage _message;
- private static readonly Regex TemplateTest = new Regex(@"<%\s*body\s*%>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
- private static readonly Regex TextUnsubscribeTest = new Regex(@"<%\s*%>", RegexOptions.Compiled);
- private static readonly Regex HtmlUnsubscribeTest = new Regex(@"<%\s*([^\s%]+\s?)+\s*%>", RegexOptions.Compiled);
- private const string SinkHost = "sink.sendgrid.net";
-
- #endregion
-
- #region Initialization and Constructors
-
- /// <summary>
- /// Creates an instance of SendGrid's custom message object
- /// </summary>
- /// <returns></returns>
- public SendGridMessage() : this(new Header())
- {
-
- }
-
- public SendGridMessage(IHeader header)
- {
- _message = new MailMessage();
- Header = header;
- Headers = new Dictionary<string, string>();
- }
-
- public SendGridMessage(MailAddress from, MailAddress[] to,
- String subject, String html, String text, IHeader header = null) : this()
- {
- From = from;
- To = to;
-
- _message.Subject = subject;
-
- Text = text;
- Html = html;
- }
-
- private static Dictionary<string, string> InitializeFilters()
- {
- return
- new Dictionary<string, string>
- {
- {"Gravatar", "gravatar"},
- {"OpenTracking", "opentrack"},
- {"ClickTracking", "clicktrack"},
- {"SpamCheck", "spamcheck"},
- {"Unsubscribe", "subscriptiontrack"},
- {"Footer", "footer"},
- {"GoogleAnalytics", "ganalytics"},
- {"Template", "template"},
- {"Templates","templates"},
- {"Bcc", "bcc"},
- {"BypassListManagement", "bypass_list_management"}
- };
- }
-
- #endregion
-
- #region Properties
-
- public MailAddress From
- {
- get { return _message.From; }
- set { if (value != null) _message.From = value; }
- }
-
- public MailAddress[] ReplyTo
- {
- get { return _message.ReplyToList.ToArray(); }
- set
- {
- _message.ReplyToList.Clear();
- foreach (var replyTo in value)
- {
- _message.ReplyToList.Add(replyTo);
- }
- }
- }
-
- public MailAddress[] To
- {
- get
- {
- if (_sendToSink)
- {
- return _message.To
- .Select(ma => new MailAddress(string.Format("{0}_at_{1}@{2}", ma.User, ma.Host, SinkHost), ma.DisplayName))
- .ToArray();
- }
- return _message.To.ToArray();
- }
- set
- {
- _message.To.Clear();
- foreach (var mailAddress in value)
- {
- _message.To.Add(mailAddress);
- }
- }
- }
-
- public MailAddress[] Cc
- {
- get { return _message.CC.ToArray(); }
- set
- {
- _message.CC.Clear();
- foreach (var mailAddress in value)
- {
- _message.CC.Add(mailAddress);
- }
- }
- }
-
- public MailAddress[] Bcc
- {
- get { return _message.Bcc.ToArray(); }
- set
- {
- _message.Bcc.Clear();
- foreach (var mailAddress in value)
- {
- _message.Bcc.Add(mailAddress);
- }
- }
- }
-
- public String Subject
- {
- get { return _message.Subject; }
- set { if (value != null) _message.Subject = value; }
- }
-
- public Dictionary<String, String> Headers { get; set; }
- public IHeader Header { get; set; }
- public String Html { get; set; }
- public String Text { get; set; }
-
- #endregion
-
- #region Methods for setting data
-
- private List<String> _attachments = new List<String>();
- private Dictionary<String, MemoryStream> _streamedAttachments = new Dictionary<string, MemoryStream>();
- private Dictionary<String, String> _contentImages = new Dictionary<string, string>();
- private bool _sendToSink;
-
- public void AddTo(String address)
- {
- var mailAddress = new MailAddress(address);
- _message.To.Add(mailAddress);
- }
-
- public void AddTo(IEnumerable<String> addresses)
- {
- if (addresses == null) return;
-
- foreach (var address in addresses.Where(address => address != null))
- AddTo(address);
- }
-
- public void AddTo(IDictionary<String, IDictionary<String, String>> addresssInfo)
- {
- foreach (var mailAddress in from address in addresssInfo.Keys let table = addresssInfo[address] select new MailAddress(address, table.ContainsKey("DisplayName") ? table["DisplayName"] : null))
- {
- _message.To.Add(mailAddress);
- }
- }
-
- public void AddCc(string address)
- {
- var mailAddress = new MailAddress(address);
- _message.CC.Add(mailAddress);
- }
-
- public void AddCc(MailAddress address)
- {
- _message.CC.Add(address);
- }
-
- public void AddBcc(string address)
- {
- var mailAddress = new MailAddress(address);
- _message.Bcc.Add(mailAddress);
- }
-
- public void AddBcc(MailAddress address)
- {
- _message.Bcc.Add(address);
- }
-
- public Dictionary<String, MemoryStream> StreamedAttachments
- {
- get { return _streamedAttachments; }
- set { _streamedAttachments = value; }
- }
-
- public String[] Attachments
- {
- get { return _attachments.ToArray(); }
- set { _attachments = value.ToList(); }
- }
-
- public void EmbedImage(String filename, String cid) {
- _contentImages[filename] = cid;
- }
-
- public IDictionary<string, string> GetEmbeddedImages() {
- return new Dictionary<string, string>(_contentImages);
- }
-
- public void AddSubstitution(String replacementTag, List<String> substitutionValues)
- {
- //let the system complain if they do something bad, since the function returns null
- Header.AddSubstitution(replacementTag, substitutionValues);
- }
-
- public void AddSection(String replacementTag, String sectionValue)
- {
- Header.AddSection(replacementTag, sectionValue);
- }
-
- public void AddUniqueArgs(IDictionary<String, String> identifiers)
- {
- Header.AddUniqueArgs(identifiers);
- }
-
- public void SetAsmGroupId(int id)
- {
- Header.SetAsmGroupId(id);
- }
-
- public void SetIpPool(string pool)
- {
- Header.SetIpPool(pool);
- }
-
- public void SetSendAt(DateTime sendTime)
- {
- Header.SetSendAt(sendTime);
- }
-
- public void SetSendEachAt(IEnumerable<DateTime> sendTimes)
- {
- Header.SetSendEachAt(sendTimes);
- }
-
- public void SetCategory(String category)
- {
- Header.SetCategory(category);
- }
-
- public void SetCategories(IEnumerable<string> categories)
- {
- Header.SetCategories(categories);
- }
-
- public void AddAttachment(Stream stream, String name)
- {
- var ms = new MemoryStream();
- stream.CopyTo(ms);
- ms.Seek(0, SeekOrigin.Begin);
- StreamedAttachments[name] = ms;
- }
-
- public void EmbedStreamImage(Stream stream, String name)
- {
- var ms = new MemoryStream();
- stream.CopyTo(ms);
- ms.Seek(0, SeekOrigin.Begin);
- StreamedAttachments[name] = ms;
-
- _contentImages[name] = name;
- }
-
- public void AddAttachment(String filePath)
- {
- _attachments.Add(filePath);
- }
-
- public IEnumerable<String> GetRecipients()
- {
- var tos = _message.To.ToList();
- var ccs = _message.CC.ToList();
- var bccs = _message.Bcc.ToList();
-
- var rcpts = tos.Union(ccs.Union(bccs)).Select(address => address.Address);
- return rcpts;
- }
-
- public void AddHeaders(IDictionary<string, string> headers)
- {
- headers.Keys.ToList().ForEach(key => Headers[key] = headers[key]);
- }
-
- public void SendToSink(bool value = true)
- {
- _sendToSink = value;
- }
-
- #endregion
-
- #region SMTP API Functions
-
- public void DisableGravatar()
- {
- Header.DisableFilter(Filters["Gravatar"]);
- }
-
- public void DisableOpenTracking()
- {
- Header.DisableFilter(Filters["OpenTracking"]);
- }
-
- public void DisableClickTracking()
- {
- Header.DisableFilter(Filters["ClickTracking"]);
- }
-
- public void DisableSpamCheck()
- {
- Header.DisableFilter(Filters["SpamCheck"]);
- }
-
- public void DisableUnsubscribe()
- {
- Header.DisableFilter(Filters["Unsubscribe"]);
- }
-
- public void DisableFooter()
- {
- Header.DisableFilter(Filters["Footer"]);
- }
-
- public void DisableGoogleAnalytics()
- {
- Header.DisableFilter(Filters["GoogleAnalytics"]);
- }
-
- public void DisableTemplate()
- {
- Header.DisableFilter(Filters["Template"]);
- }
-
- public void DisableBcc()
- {
- Header.DisableFilter(Filters["Bcc"]);
- }
-
- public void DisableBypassListManagement()
- {
- Header.DisableFilter(Filters["BypassListManagement"]);
- }
-
- public void EnableGravatar()
- {
- Header.EnableFilter(Filters["Gravatar"]);
- }
-
- public void EnableOpenTracking()
- {
- Header.EnableFilter(Filters["OpenTracking"]);
- }
-
- public void EnableClickTracking(bool includePlainText = false)
- {
- var filter = Filters["ClickTracking"];
-
- Header.EnableFilter(filter);
- if (includePlainText)
- {
- Header.AddFilterSetting(filter, new List<string> {"enable_text"}, "1");
- }
- }
-
- public void EnableSpamCheck(int score = 5, string url = null)
- {
- var filter = Filters["SpamCheck"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"maxscore"}, score.ToString(CultureInfo.InvariantCulture));
- Header.AddFilterSetting(filter, new List<string> {"url"}, url);
- }
-
- public void EnableUnsubscribe(string text, string html)
- {
- var filter = Filters["Unsubscribe"];
-
- if (!TextUnsubscribeTest.IsMatch(text))
- {
- throw new Exception("Missing substitution replacementTag in text");
- }
-
- if (!HtmlUnsubscribeTest.IsMatch(html))
- {
- throw new Exception("Missing substitution replacementTag in html");
- }
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"text/plain"}, text);
- Header.AddFilterSetting(filter, new List<string> {"text/html"}, html);
- }
-
- public void EnableUnsubscribe(string replace)
- {
- var filter = Filters["Unsubscribe"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"replace"}, replace);
- }
-
- public void EnableFooter(string text = null, string html = null)
- {
- var filter = Filters["Footer"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"text/plain"}, text);
- Header.AddFilterSetting(filter, new List<string> {"text/html"}, html);
- }
-
- public void EnableGoogleAnalytics(string source, string medium, string term, string content = null,
- string campaign = null)
- {
- var filter = Filters["GoogleAnalytics"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"utm_source"}, source);
- Header.AddFilterSetting(filter, new List<string> {"utm_medium"}, medium);
- Header.AddFilterSetting(filter, new List<string> {"utm_term"}, term);
- Header.AddFilterSetting(filter, new List<string> {"utm_content"}, content);
- Header.AddFilterSetting(filter, new List<string> {"utm_campaign"}, campaign);
- }
-
- public void EnableTemplate(string html)
- {
- var filter = Filters["Template"];
-
- if (!TemplateTest.IsMatch(html))
- {
- throw new Exception("Missing <% body %> tag in template HTML");
- }
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"text/html"}, html);
- }
-
- public void EnableTemplateEngine(string templateId)
- {
- var filter = Filters["Templates"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> { "template_id" }, templateId);
- }
-
- public void EnableBcc(string email)
- {
- var filter = Filters["Bcc"];
-
- Header.EnableFilter(filter);
- Header.AddFilterSetting(filter, new List<string> {"email"}, email);
- }
-
- public void EnableBypassListManagement()
- {
- Header.EnableFilter(Filters["BypassListManagement"]);
- }
-
- #endregion
-
- public MailMessage CreateMimeMessage()
- {
- var smtpapi = Header.JsonString();
-
- if (!String.IsNullOrEmpty(smtpapi))
- _message.Headers.Add("X-Smtpapi", smtpapi);
-
- Headers.Keys.ToList().ForEach(k => _message.Headers.Add(k, Headers[k]));
-
- _message.Attachments.Clear();
- _message.AlternateViews.Clear();
-
- if (Attachments != null)
- {
- foreach (var attachment in Attachments)
- {
- _message.Attachments.Add(new Attachment(attachment, MediaTypeNames.Application.Octet));
- }
- }
-
- if (StreamedAttachments != null)
- {
- foreach (var attachment in StreamedAttachments)
- {
- attachment.Value.Position = 0;
- _message.Attachments.Add(new Attachment(attachment.Value, attachment.Key));
- }
- }
-
- if (Text != null)
- {
- var plainView = AlternateView.CreateAlternateViewFromString(Text, null, "text/plain");
- _message.AlternateViews.Add(plainView);
- }
-
- if (Html == null) return _message;
-
- var htmlView = AlternateView.CreateAlternateViewFromString(Html, null, "text/html");
- _message.AlternateViews.Add(htmlView);
-
- //message.SubjectEncoding = Encoding.GetEncoding(charset);
- //message.BodyEncoding = Encoding.GetEncoding(charset);
-
- return _message;
- }
-
- /// <summary>
- /// Helper function lets us look at the mime before it is sent
- /// </summary>
- /// <param name="directory">directory in which we store this mime message</param>
- internal void SaveMessage(String directory)
- {
- var client = new SmtpClient("localhost")
- {
- DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory,
- PickupDirectoryLocation = @"C:\temp"
- };
- var msg = CreateMimeMessage();
- client.Send(msg);
- }
- }
-}
\ No newline at end of file diff --git a/SendGrid/SendGridMail/SendGridMail.pfx b/SendGrid/SendGridMail/SendGridMail.pfx Binary files differdeleted file mode 100644 index 867e499..0000000 --- a/SendGrid/SendGridMail/SendGridMail.pfx +++ /dev/null diff --git a/SendGrid/SendGridMail/StreamedFileBody.cs b/SendGrid/SendGridMail/StreamedFileBody.cs deleted file mode 100644 index 125fe24..0000000 --- a/SendGrid/SendGridMail/StreamedFileBody.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Text;
-
-namespace SendGridMail
-{
- public class StreamedFileBody
- {
- private string _name;
- private string _filename;
- private byte[] _content;
-
- public StreamedFileBody(MemoryStream stream, String name)
- {
- if (stream == null) throw new ArgumentException("Invalid attachment stream");
- if (String.IsNullOrEmpty(name)) throw new ArgumentException("Invalid attachment name");
-
- _name = "files[" + Path.GetFileName(name) + "]";
- _filename = name;
- _content = stream.ToArray();
- }
-
- public byte[] GetContent(string boundry)
- {
- var bytes = new List<byte>();
-
- string paramBoundry = "--" + boundry + "\r\n";
- string stringParam = "Content-Disposition: form-data; name=\"" + _name + "\"; filename=\"" + _filename + "\"\r\n";
- string paramEnd = "Content-Type: image/png\r\n\r\n";
-
- bytes.AddRange(Encoding.ASCII.GetBytes(paramBoundry + stringParam + paramEnd));
- bytes.AddRange(_content);
- bytes.AddRange(Encoding.ASCII.GetBytes("\r\n"));
- return bytes.ToArray();
- }
- }
-}
diff --git a/SendGrid/SendGridMail/Transport/ErrorChecker.cs b/SendGrid/SendGridMail/Transport/ErrorChecker.cs deleted file mode 100644 index 035d2b8..0000000 --- a/SendGrid/SendGridMail/Transport/ErrorChecker.cs +++ /dev/null @@ -1,57 +0,0 @@ -namespace SendGrid -{ - using System; - using System.IO; - using System.Net; - using System.Net.Http; - using System.Threading.Tasks; - using System.Xml; - - using Exceptions; - - public static class ErrorChecker - { - public static void CheckForErrors(HttpResponseMessage response) - { - CheckForErrors(response, response.Content.ReadAsStreamAsync().Result); - } - - public static async Task CheckForErrorsAsync(HttpResponseMessage response) - { - CheckForErrors(response, await response.Content.ReadAsStreamAsync()); - } - - private static void CheckForErrors(HttpResponseMessage response, Stream stream) - { - if (response.StatusCode != HttpStatusCode.OK) - { - using (var reader = XmlReader.Create(stream)) - { - while (reader.Read()) - { - if (!reader.IsStartElement()) - { - continue; - } - - switch (reader.Name) - { - case "result": - continue; - case "message": - continue; - case "errors": - reader.ReadToFollowing("error"); - var message = reader.ReadElementContentAsString("error", reader.NamespaceURI); - throw new InvalidApiRequestException(response.StatusCode, new[] { message }, response.ReasonPhrase); - case "error": - throw new ProtocolViolationException(); - default: - throw new ArgumentException("Unknown element: " + reader.Name); - } - } - } - } - } - } -}
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Transport/ITransport.cs b/SendGrid/SendGridMail/Transport/ITransport.cs deleted file mode 100644 index 94a2d7f..0000000 --- a/SendGrid/SendGridMail/Transport/ITransport.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Threading.Tasks;
-
-
-namespace SendGrid
-{
- /// <summary>
- /// Encapsulates the transport mechanism so that it can be used in a generic way,
- /// regardless of the transport type
- /// </summary>
- public interface ITransport
- {
- /// <summary>
- /// Asynchronously delivers a message using the protocol of the derived class
- /// </summary>
- /// <param name="message">the message to be delivered</param>
- Task DeliverAsync(ISendGrid message);
- }
-}
\ No newline at end of file diff --git a/SendGrid/SendGridMail/Transport/Web.cs b/SendGrid/SendGridMail/Transport/Web.cs deleted file mode 100644 index dbf5d28..0000000 --- a/SendGrid/SendGridMail/Transport/Web.cs +++ /dev/null @@ -1,186 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Linq;
-using System.Net;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Reflection;
-using System.Threading.Tasks;
-using SendGrid.SmtpApi;
-
-// ReSharper disable MemberCanBePrivate.Global
-namespace SendGrid
-{
- public class Web : ITransport
- {
- #region Properties
-
- //TODO: Make this configurable
- public const String Endpoint = "https://api.sendgrid.com/api/mail.send.xml";
- private readonly NetworkCredential _credentials;
- private readonly HttpClient _client;
- private readonly string _apiKey;
-
- #endregion
-
- /// <summary>
- /// Creates a new Web interface for sending mail
- /// </summary>
- /// <param name="apiKey">The API Key with which to send</param>
- public Web(string apiKey)
- : this(apiKey, null, TimeSpan.FromSeconds(100)) { }
-
- /// <summary>
- /// Creates a new Web interface for sending mail
- /// </summary>
- /// <param name="credentials">SendGridMessage user parameters</param>
- public Web(NetworkCredential credentials)
- : this(null, credentials, TimeSpan.FromSeconds(100)) { }
-
- /// <summary>
- /// Creates a new Web interface for sending mail.
- /// </summary>
- /// <param name="apKey">The API Key with which to send</param>
- /// <param name="credentials">SendGridMessage user parameters</param>
- /// <param name="httpTimeout">HTTP request timeout</param>
- public Web(string apiKey, NetworkCredential credentials, TimeSpan httpTimeout)
- {
- _credentials = credentials;
- _client = new HttpClient();
- _apiKey = apiKey;
-
- var version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
- if (credentials == null)
- {
- _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _apiKey);
- }
- _client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "sendgrid/" + version + ";csharp");
- _client.Timeout = httpTimeout;
- }
-
- /// <summary>
- /// Asynchronously delivers a message over SendGrid's Web interface
- /// </summary>
- /// <param name="message"></param>
- public async Task DeliverAsync(ISendGrid message)
- {
- var content = new MultipartFormDataContent();
- AttachFormParams(message, content);
- AttachFiles(message, content);
- var response = await _client.PostAsync(Endpoint, content);
- await ErrorChecker.CheckForErrorsAsync(response);
- }
-
- #region Support Methods
-
- private void AttachFormParams(ISendGrid message, MultipartFormDataContent content)
- {
- var formParams = FetchFormParams(message);
- foreach (var keyValuePair in formParams)
- {
- content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
- }
- }
-
- private void AttachFiles(ISendGrid message, MultipartFormDataContent content)
- {
- var files = FetchFileBodies(message);
- foreach (var file in files)
- {
- var fs = new FileStream(file.Key, FileMode.Open, FileAccess.Read);
- var fileContent = new StreamContent(fs);
-
- fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
- {
- Name = "files[" + Path.GetFileName(file.Key) + "]",
- FileName = Path.GetFileName(file.Key)
- };
-
- fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
- content.Add(fileContent);
- }
-
- var streamingFiles = FetchStreamingFileBodies(message);
- foreach (var file in streamingFiles)
- {
- var stream = file.Value;
- var fileContent = new StreamContent(stream);
-
- fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
- {
- Name = "files[" + Path.GetFileName(file.Key) + "]",
- FileName = Path.GetFileName(file.Key)
- };
-
- fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
- content.Add(fileContent);
- }
- }
-
- internal List<KeyValuePair<String, String>> FetchFormParams(ISendGrid message)
- {
- var result = new List<KeyValuePair<string, string>>
- {
- new KeyValuePair<String, String>("headers",
- message.Headers.Count == 0 ? null : Utils.SerializeDictionary(message.Headers)),
- new KeyValuePair<String, String>("replyto",
- message.ReplyTo.Length == 0 ? null : message.ReplyTo.ToList().First().Address),
- new KeyValuePair<String, String>("from", message.From.Address),
- new KeyValuePair<String, String>("fromname", message.From.DisplayName),
- new KeyValuePair<String, String>("subject", message.Subject),
- new KeyValuePair<String, String>("text", message.Text),
- new KeyValuePair<String, String>("html", message.Html),
- new KeyValuePair<String, String>("x-smtpapi", message.Header.JsonString() ?? "")
- };
-
- //If the API key is not specified, use the username and password
- if (_credentials != null)
- {
- var creds = new List<KeyValuePair<string, string>>
- {
- new KeyValuePair<string, string>("api_user", _credentials.UserName),
- new KeyValuePair<string, string>("api_key", _credentials.Password)
- };
- result.AddRange(creds);
- }
-
- if (message.To != null)
- {
- result = result.Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("to[]", a.Address)))
- .Concat(message.To.ToList().Select(a => new KeyValuePair<String, String>("toname[]", a.DisplayName)))
- .ToList();
- }
-
- if (message.Cc != null)
- {
- result.AddRange(message.Cc.Select(c => new KeyValuePair<string, string>("cc[]", c.Address)));
- }
-
- if (message.Bcc != null)
- {
- result.AddRange(message.Bcc.Select(c => new KeyValuePair<string, string>("bcc[]", c.Address)));
- }
-
- if (message.GetEmbeddedImages().Count > 0) {
- result = result.Concat(message.GetEmbeddedImages().ToList().Select(x => new KeyValuePair<String, String>(string.Format("content[{0}]", x.Key), x.Value)))
- .ToList();
- }
- return result.Where(r => !String.IsNullOrEmpty(r.Value)).ToList();
- }
-
- internal IEnumerable<KeyValuePair<string, MemoryStream>> FetchStreamingFileBodies(ISendGrid message)
- {
- return message.StreamedAttachments.Select(kvp => kvp).ToList();
- }
-
- internal List<KeyValuePair<String, FileInfo>> FetchFileBodies(ISendGrid message)
- {
- return message.Attachments == null
- ? new List<KeyValuePair<string, FileInfo>>()
- : message.Attachments.Select(name => new KeyValuePair<String, FileInfo>(name, new FileInfo(name))).ToList();
- }
-
- #endregion
- }
-}
diff --git a/SendGrid/SendGridMail/Web/IWebApi.cs b/SendGrid/SendGridMail/Web/IWebApi.cs deleted file mode 100644 index 52d4cb2..0000000 --- a/SendGrid/SendGridMail/Web/IWebApi.cs +++ /dev/null @@ -1,45 +0,0 @@ -using System;
-using System.Collections.Generic;
-
-namespace SendGridMail.Web
-{
- interface IWebApi
- {
- String user { get; set; }
- String pass { get; set; }
-
- String GetBounces(int date, String days, DateTime start_date, DateTime end_date, int limit, int offset, int type, String email);
- void DeleteBounces(DateTime start_date, DateTime end_date, String type, String email);
- String GetBlocks(int days, DateTime start_date, DateTime end_date, String email);
- void DeleteBlocks(String email);
- String GetEmailParse(String hostname, String url);
- void SetEmailParse(String hostname, String url);
- void EditEmailParse(String hostname, String url);
- void DeleteEmailParse(String hostname);
- String GetNotificationUrl();
- void SetNotificationUrl(String url);
- void DeleteNotificationUrl();
- String GetFilter();
- void ActivateFilter(String name);
- void DeactivateFilter(String name);
- void SetupFilter(String user, String password, Dictionary<String, String> args);
- String GetFilterSettings(String name);
- void GetInvalidEmails(int date, int days, DateTime start_date, DateTime end_date, int limit, int offset, String email);
- void DeleteInvalidEmails(DateTime start_date, DateTime end_date, String email);
- String CountInvalidEmails(DateTime start_date, DateTime end_date);
- String GetProfile();
- void UpdateProfile(String First_name, String last_name, String address, String city, String state, String country, int zip, int phone, String website);
- void SetUsername(String username);
- void SetPassword(String password, String confpass);
- void SetEmail(String email);
- String GetSpamReports(int date, int days, DateTime start_date, DateTime end_date, int limit, int offset, String email);
- void DeleteSpamReports(DateTime start_date, DateTime end_date, String email);
- String GetStats(int days, DateTime start_date, DateTime end_date);
- String GetAggregateStats();
- String GetCategoryStats();
- String GetCategoryStats(String category, int days, DateTime start_date, DateTime end_date);
- String GetUnsubscribes(int date, int days, DateTime start_date, DateTime end_date, int limit, int offset, String email);
- void DeleteUnsubscribes(DateTime start_date, DateTime end_date, String email);
- void AddUnsubscribes(String email);
- }
-}
diff --git a/SendGrid/SendGridMail/app.config b/SendGrid/SendGridMail/app.config deleted file mode 100644 index 67113e6..0000000 --- a/SendGrid/SendGridMail/app.config +++ /dev/null @@ -1,3 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<configuration>
-</configuration>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/nuget/Sendgrid.2.1.1.nuspec b/SendGrid/SendGridMail/nuget/Sendgrid.2.1.1.nuspec deleted file mode 100644 index a6cc5f9..0000000 --- a/SendGrid/SendGridMail/nuget/Sendgrid.2.1.1.nuspec +++ /dev/null @@ -1,24 +0,0 @@ -<?xml version="1.0"?>
-<package xmlns="http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd">
- <metadata>
- <id>Sendgrid</id>
- <version>2.1.1</version>
- <title>SendGrid</title>
- <authors>CJ Buchmann, Tyler Bischel, Eric Becking, Brandon West</authors>
- <owners>CJ Buchmann, Tyler Bischel, Eric Becking, Brandon West</owners>
- <licenseUrl>https://github.com/sendgrid/sendgrid-csharp/blob/master/MIT.LICENSE</licenseUrl>
- <projectUrl>https://github.com/sendgrid/sendgrid-csharp</projectUrl>
- <requireLicenseAcceptance>false</requireLicenseAcceptance>
- <description>Basic C# client library and examples for using SendGrid API's to send mail. Github repo located at : https://github.com/sendgrid/sendgrid-csharp</description>
- <releaseNotes>BREAKING CHANGE: Deprecates SMTP transport and adds dependency on smtpapi package for building headers. - -For an example of how to continue using SMTP, see https://github.com/sendgrid/smtpapi-csharp</releaseNotes>
- <copyright>Copyright 2014</copyright>
- <tags>SendGrid Email Mail Microsoft Azure</tags>
- <dependencies>
- <dependency id="Microsoft.Net.Http" version="2.2.13" />
- <dependency id="Microsoft.Bcl.Async" version="1.0.16" />
- <dependency id="smtpapi" version="1.0.0" />
- </dependencies>
- </metadata>
-</package>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/nuget/lib/SendGridMail.dll b/SendGrid/SendGridMail/nuget/lib/SendGridMail.dll Binary files differdeleted file mode 100644 index 47d8c95..0000000 --- a/SendGrid/SendGridMail/nuget/lib/SendGridMail.dll +++ /dev/null diff --git a/SendGrid/SendGridMail/packages.config b/SendGrid/SendGridMail/packages.config deleted file mode 100644 index 030933b..0000000 --- a/SendGrid/SendGridMail/packages.config +++ /dev/null @@ -1,4 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<packages>
- <package id="SendGrid.SmtpApi" version="1.3.1" targetFramework="net45" />
-</packages>
\ No newline at end of file diff --git a/SendGrid/SendGridMail/sendgrid-csharp.snk b/SendGrid/SendGridMail/sendgrid-csharp.snk Binary files differdeleted file mode 100644 index aff2944..0000000 --- a/SendGrid/SendGridMail/sendgrid-csharp.snk +++ /dev/null diff --git a/SendGrid/Tests/Properties/AssemblyInfo.cs b/SendGrid/Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 8b518a9..0000000 --- a/SendGrid/Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System.Reflection;
-using System.Runtime.InteropServices;
-
-// General Information about an assembly is controlled through the following
-// set of attributes. Change these attribute values to modify the information
-// associated with an assembly.
-
-[assembly: AssemblyTitle("Tests")]
-[assembly: AssemblyDescription("")]
-[assembly: AssemblyConfiguration("")]
-[assembly: AssemblyCompany("")]
-[assembly: AssemblyProduct("Tests")]
-[assembly: AssemblyCopyright("Copyright © 2012")]
-[assembly: AssemblyTrademark("")]
-[assembly: AssemblyCulture("")]
-
-// Setting ComVisible to false makes the types in this assembly not visible
-// to COM components. If you need to access a type in this assembly from
-// COM, set the ComVisible attribute to true on that type.
-
-[assembly: ComVisible(false)]
-
-// The following GUID is for the ID of the typelib if this project is exposed to COM
-
-[assembly: Guid("ce0ad7f8-ecce-46c6-a057-f7aa74bb3518")]
-
-// Version information for an assembly consists of the following four values:
-//
-// Major Version
-// Minor Version
-// Build Number
-// Revision
-//
-// You can specify all the values or you can default the Build and Revision Numbers
-// by using the '*' as shown below:
-// [assembly: AssemblyVersion("1.0.*")]
-
-[assembly: AssemblyVersion("1.2.0")]
-[assembly: AssemblyFileVersion("1.2.0")]
\ No newline at end of file diff --git a/SendGrid/Tests/TestSendgrid.cs b/SendGrid/Tests/TestSendgrid.cs deleted file mode 100644 index 3ce0c6e..0000000 --- a/SendGrid/Tests/TestSendgrid.cs +++ /dev/null @@ -1,418 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.IO;
-using System.Net.Mail;
-using NUnit.Framework;
-using SendGrid.SmtpApi;
-using SendGrid;
-
-namespace Tests
-{
- [TestFixture]
- internal class TestSendgrid
- {
- [Test]
- public void CreateMimeMessage()
- {
- var message = new SendGridMessage();
- var attachment = Path.GetTempFileName();
- var text = "this is a test";
- var html = "<b>This<\b> is a better test";
- var headers = new KeyValuePair<String, String>("custom", "header");
- message.AddAttachment(attachment);
- message.Text = text;
- message.Html = html;
- message.AddTo("foo@bar.com");
- message.From = new MailAddress("foo@bar.com");
- message.AddHeaders(new Dictionary<string, string> {{headers.Key, headers.Value}});
- message.EnableGravatar();
-
- var mime = message.CreateMimeMessage();
-
- var sr = new StreamReader(mime.AlternateViews[0].ContentStream);
- var result = sr.ReadToEnd();
- Assert.AreEqual(text, result);
-
- sr = new StreamReader(mime.AlternateViews[1].ContentStream);
- result = sr.ReadToEnd();
- Assert.AreEqual(html, result);
-
- result = mime.Headers.Get(headers.Key);
- Assert.AreEqual(headers.Value, result);
-
- result = mime.Headers.Get("X-Smtpapi");
- var expected = "{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}";
- Assert.AreEqual(expected, result);
-
- result = mime.Attachments[0].Name;
- Assert.AreEqual(Path.GetFileName(attachment), result);
- }
-
- [Test]
- public void DisableBcc()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableBcc();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"bcc\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableBypassListManagement()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableBypassListManagement();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"bypass_list_management\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableClickTracking()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableClickTracking();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"clicktrack\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableFooter()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableFooter();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"footer\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableGoogleAnalytics()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableGoogleAnalytics();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"ganalytics\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableSpamCheck()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableSpamCheck();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"spamcheck\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableTemplate()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableTemplate();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"template\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void DisableUnsubscribe()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableUnsubscribe();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"subscriptiontrack\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void EnableBcc()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- var email = "somebody@someplace.com";
- sendgrid.EnableBcc(email);
-
- var json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"bcc\" : {\"settings\" : {\"enable\" : \"1\",\"email\" : \"" + email + "\"}}}}",
- json);
- }
-
- [Test]
- public void EnableBypassListManagement()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.EnableBypassListManagement();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"bypass_list_management\" : {\"settings\" : {\"enable\" : \"1\"}}}}", json);
- }
-
- [Test]
- public void EnableClickTracking()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
- sendgrid.EnableClickTracking(true);
-
- var json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"clicktrack\" : {\"settings\" : {\"enable\" : \"1\",\"enable_text\" : \"1\"}}}}",
- json);
- }
-
- [Test]
- public void EnableFooter()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- var text = "My Text";
- var html = "<body><p>hello, <% name %></p></body>";
- var escHtml = "<body><p>hello, <% name %><\\/p><\\/body>";
-
- sendgrid.EnableFooter(text, html);
-
- var json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"footer\" : {\"settings\" : {\"enable\" : \"1\",\"text\\/plain\" : \"" + text +
- "\",\"text\\/html\" : \"" + escHtml + "\"}}}}", json);
- }
-
- [Test]
- public void EnableGoogleAnalytics()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- var source = "SomeDomain.com";
- var medium = "Email";
- var term = "keyword1, keyword2, keyword3";
- var content = "PG, PG13";
- var campaign = "my_campaign";
-
- sendgrid.EnableGoogleAnalytics(source, medium, term, content, campaign);
-
- var jsonSource = "\"utm_source\" : \"SomeDomain.com\"";
- var jsonMedium = "\"utm_medium\" : \"" + medium + "\"";
- var jsonTerm = "\"utm_term\" : \"" + term + "\"";
- var jsonContent = "\"utm_content\" : \"" + content + "\"";
- var jsonCampaign = "\"utm_campaign\" : \"" + campaign + "\"";
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"ganalytics\" : {\"settings\" : {\"enable\" : \"1\"," +
- jsonSource + "," + jsonMedium + "," + jsonTerm + "," + jsonContent + "," + jsonCampaign +
- "}}}}",
- json);
- }
-
- [Test]
- public void EnableGravatar()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.EnableGravatar();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"1\"}}}}", json);
- }
-
- [Test]
- public void EnableOpenTracking()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.EnableOpenTracking();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"opentrack\" : {\"settings\" : {\"enable\" : \"1\"}}}}", json);
- }
-
- [Test]
- public void EnableSpamCheck()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- var score = 5;
- var url = "http://www.example.com";
- sendgrid.EnableSpamCheck(score, url);
-
- var json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"spamcheck\" : {\"settings\" : {\"enable\" : \"1\",\"maxscore\" : \"5\",\"url\" : \"http:\\/\\/www.example.com\"}}}}",
- json);
- }
-
- [Test]
- public void EnableTemplate()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
- var html = "<% body %>";
-
- var escHtml = "<% body %>";
- sendgrid.EnableTemplate(html);
-
- var json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"template\" : {\"settings\" : {\"enable\" : \"1\",\"text\\/html\" : \"" + escHtml +
- "\"}}}}", json);
-
- escHtml = "bad";
- Assert.Throws<Exception>(() => sendgrid.EnableTemplate(escHtml));
- }
-
- [Test]
- public void EnableUnsubscribe()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- var text = "<% %>";
- var html = "<% name %>";
-
- var jsonText = "\"text\\/plain\" : \"" + text + "\"";
- var jsonHtml = "\"text\\/html\" : \"" + html + "\"";
-
- sendgrid.EnableUnsubscribe(text, html);
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"subscriptiontrack\" : {\"settings\" : {\"enable\" : \"1\"," +
- jsonText + "," + jsonHtml + "}}}}", json);
-
- header = new Header();
- sendgrid = new SendGridMessage(header);
-
- var replace = "John";
- var jsonReplace = "\"replace\" : \"" + replace + "\"";
-
- sendgrid.EnableUnsubscribe(replace);
-
- json = header.JsonString();
- Assert.AreEqual(
- "{\"filters\" : {\"subscriptiontrack\" : {\"settings\" : {\"enable\" : \"1\"," + jsonReplace + "}}}}",
- json);
-
- text = "bad";
- html = "<% name %>";
- Assert.Throws<Exception>(() => sendgrid.EnableUnsubscribe(text, html));
-
- text = "<% %>";
- html = "bad";
- Assert.Throws<Exception>(() => sendgrid.EnableUnsubscribe(text, html));
- }
-
- [Test]
- public void TestDisableGravatar()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableGravatar();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"gravatar\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void TestDisableOpenTracking()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.DisableOpenTracking();
-
- var json = header.JsonString();
- Assert.AreEqual("{\"filters\" : {\"opentrack\" : {\"settings\" : {\"enable\" : \"0\"}}}}", json);
- }
-
- [Test]
- public void TestAddSection()
- {
- var header = new Header();
- var sendgrid = new SendGridMessage(header);
-
- sendgrid.AddSection("tag", "value");
-
- var json = header.JsonString();
- Assert.AreEqual("{\"section\" : {\"tag\" : \"value\"}}", json);
- }
-
- [Test]
- public void TestSendToSink()
- {
- // Arrange
-
- var message = new SendGridMessage();
- message.To = new[]
- {
- new MailAddress("foo@bar.com", "Foo Bar"),
- };
- message.AddTo("foo1@bar1.com");
-
- // Act
-
- message.SendToSink();
-
- // Assert
-
- Assert.AreEqual("foo_at_bar.com@sink.sendgrid.net", message.To[0].Address);
- Assert.AreEqual("Foo Bar", message.To[0].DisplayName);
-
- Assert.AreEqual("foo1_at_bar1.com@sink.sendgrid.net", message.To[1].Address);
- Assert.AreEqual("", message.To[1].DisplayName);
- }
-
- [Test]
- public void TestSendToSinkOff()
- {
- // Arrange
-
- var message = new SendGridMessage();
- message.To = new[]
- {
- new MailAddress("foo@bar.com", "Foo Bar"),
- };
- message.AddTo("foo1@bar1.com");
- message.SendToSink();
-
- // Act
-
- message.SendToSink(false);
-
- // Assert
-
- Assert.AreEqual("foo@bar.com", message.To[0].Address);
- Assert.AreEqual("Foo Bar", message.To[0].DisplayName);
-
- Assert.AreEqual("foo1@bar1.com", message.To[1].Address);
- Assert.AreEqual("", message.To[1].DisplayName);
- }
- }
-}
diff --git a/SendGrid/Tests/Tests.csproj b/SendGrid/Tests/Tests.csproj deleted file mode 100644 index ff31ea6..0000000 --- a/SendGrid/Tests/Tests.csproj +++ /dev/null @@ -1,123 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <PropertyGroup Condition=" '$(Configuration)' == 'BuildNet45' ">
- <SignAssembly>false</SignAssembly>
- <DebugSymbols>True</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>False</Optimize>
- <OutputPath>bin\BuildNet45\</OutputPath>
- <DefineConstants>BUILD;TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
- <DebugSymbols>True</DebugSymbols>
- <DebugType>full</DebugType>
- <Optimize>False</Optimize>
- <OutputPath>bin\Debug\</OutputPath>
- <DefineConstants>TRACE, DEBUG</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
- <SignAssembly>true</SignAssembly>
- <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile>
- <Optimize>True</Optimize>
- <OutputPath>bin\Release\</OutputPath>
- <DefineConstants>TRACE</DefineConstants>
- <ErrorReport>prompt</ErrorReport>
- <WarningLevel>4</WarningLevel>
- <Prefer32Bit>false</Prefer32Bit>
- </PropertyGroup>
- <PropertyGroup>
- <SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
- <RestorePackages>true</RestorePackages>
- <ProjectGuid>{0319E73A-7039-4858-B047-1EDF88BB6BD1}</ProjectGuid>
- <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
- <TargetFrameworkProfile />
- <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
- <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
- <AssemblyName>Tests</AssemblyName>
- </PropertyGroup>
- <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'BuildNet45|AnyCPU'">
- <DefineConstants>TRACE, BUILD</DefineConstants>
- <SignAssembly>false</SignAssembly>
- </PropertyGroup>
- <PropertyGroup>
- <OutputType>Library</OutputType>
- </PropertyGroup>
- <PropertyGroup>
- <SignAssembly>true</SignAssembly>
- </PropertyGroup>
- <PropertyGroup>
- <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile>
- </PropertyGroup>
- <ItemGroup>
- <Reference Include="Microsoft.CSharp" />
- <Reference Include="Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" />
- <Reference Include="Moq">
- <HintPath>..\packages\Moq.4.2.1402.2112\lib\net40\Moq.dll</HintPath>
- </Reference>
- <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
- <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
- <Private>True</Private>
- </Reference>
- <Reference Include="nunit.core, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" Condition="'$(OS)' != 'Unix'">
- <HintPath>..\packages\NUnitTestAdapter.2.0.0\lib\nunit.core.dll</HintPath>
- <Private>False</Private>
- </Reference>
- <Reference Include="nunit.core.interfaces, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" Condition="'$(OS)' != 'Unix'">
- <HintPath>..\packages\NUnitTestAdapter.2.0.0\lib\nunit.core.interfaces.dll</HintPath>
- <Private>False</Private>
- </Reference>
- <Reference Include="nunit.framework">
- <HintPath>..\packages\NUnit.2.6.3\lib\nunit.framework.dll</HintPath>
- </Reference>
- <Reference Include="nunit.util, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL" Condition="'$(OS)' != 'Unix'">
- <HintPath>..\packages\NUnitTestAdapter.2.0.0\lib\nunit.util.dll</HintPath>
- <Private>False</Private>
- </Reference>
- <Reference Include="NUnit.VisualStudio.TestAdapter, Version=2.0.0.0, Culture=neutral, PublicKeyToken=4cb40d35494691ac, processorArchitecture=MSIL" Condition="'$(OS)' != 'Unix'">
- <HintPath>..\packages\NUnitTestAdapter.2.0.0\lib\NUnit.VisualStudio.TestAdapter.dll</HintPath>
- <Private>False</Private>
- </Reference>
- <Reference Include="SendGrid.SmtpApi">
- <HintPath>..\packages\SendGrid.SmtpApi.1.3.1\lib\net40\SendGrid.SmtpApi.dll</HintPath>
- </Reference>
- <Reference Include="System" />
- <Reference Include="System.Net" />
- <Reference Include="System.Net.Http" />
- </ItemGroup>
- <ItemGroup>
- <Compile Include="Properties\AssemblyInfo.cs" />
- <Compile Include="TestSendgrid.cs" />
- <Compile Include="Transport\TestErrorChecker.cs" />
- <Compile Include="Transport\TestWebApi.cs" />
- </ItemGroup>
- <ItemGroup>
- <None Include="app.config">
- <SubType>Designer</SubType>
- </None>
- <None Include="packages.config">
- <SubType>Designer</SubType>
- </None>
- <None Include="sendgrid-csharp.snk" />
- </ItemGroup>
- <ItemGroup>
- <ProjectReference Include="..\SendGridMail\Mail.csproj">
- <Project>{3C687BEF-FF50-44AD-8315-2D4237281AF8}</Project>
- <Name>Mail</Name>
- </ProjectReference>
- <ProjectReference Include="..\SendGrid\SendGrid.csproj">
- <Project>{1c318867-440b-4eb9-99e3-c0cc2c556962}</Project>
- <Name>SendGrid</Name>
- </ProjectReference>
- </ItemGroup>
- <ItemGroup>
- <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
- </ItemGroup>
- <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
- <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
-</Project>
\ No newline at end of file diff --git a/SendGrid/Tests/Transport/TestErrorChecker.cs b/SendGrid/Tests/Transport/TestErrorChecker.cs deleted file mode 100644 index f178064..0000000 --- a/SendGrid/Tests/Transport/TestErrorChecker.cs +++ /dev/null @@ -1,34 +0,0 @@ -namespace Transport -{ - #region Using Directives - - using System; - using System.Net; - using System.Net.Http; - - using Exceptions; - - using NUnit.Framework; - - using SendGrid; - - #endregion - - [TestFixture] - public class TestErrorChecker - { - private const string BadUsernameOrPasswordResponseMessage = "<result><message>error</message><errors><error>Bad username / password</error></errors></result>"; - - [Test] - [ExpectedException(typeof(InvalidApiRequestException))] - public void WhenHttpResponseContainsBadUserErrorItIsDetectedAndAInvalidApiRequestIsThrown() - { - var response = new HttpResponseMessage(HttpStatusCode.BadRequest) - { - Content = new StringContent(BadUsernameOrPasswordResponseMessage) - }; - - ErrorChecker.CheckForErrors(response); - } - } -}
\ No newline at end of file diff --git a/SendGrid/Tests/Transport/TestWebApi.cs b/SendGrid/Tests/Transport/TestWebApi.cs deleted file mode 100644 index ecb1ad8..0000000 --- a/SendGrid/Tests/Transport/TestWebApi.cs +++ /dev/null @@ -1,97 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Net;
-using System.Net.Mail;
-using Moq;
-using NUnit.Framework;
-using SendGrid;
-
-namespace Transport
-{
- [TestFixture]
- internal class TestWebApi
- {
- private const string TestUsername = "username";
- private const string TestPassword = "password";
- private const string TestApiKey = "apikey";
-
- [Test]
- public void TestFetchFileBodies()
- {
- TestFetchFileBodiesHelper(new Web(new NetworkCredential(TestUsername, TestPassword)));
- TestFetchFileBodiesHelper(new Web(TestApiKey));
- }
-
- public void TestFetchFileBodiesHelper(Web webApi)
- {
- // Test using credentials
- var message = new Mock<ISendGrid>();
- var attachments = new[] {"foo", "bar", "foobar"};
- message.SetupProperty(foo => foo.Attachments, null);
- var result = webApi.FetchFileBodies(message.Object);
- Assert.AreEqual(0, result.Count);
-
- message.SetupProperty(foo => foo.Attachments, attachments);
- result = webApi.FetchFileBodies(message.Object);
- Assert.AreEqual(attachments.Count(), result.Count);
- for (var index = 0; index < attachments.Length; index++)
- Assert.AreEqual(result[index].Value.Name, attachments[index]);
- }
-
- [Test]
- public void TestFetchFormParams()
- {
- TestFetchFormParamsHelper(new Web(new NetworkCredential(TestUsername, TestPassword)), true);
- TestFetchFormParamsHelper(new Web(TestApiKey), false);
- }
-
- public void TestFetchFormParamsHelper(Web webApi, bool credentials)
- {
- // Test Variables
- const string toAddress = "foobar@outlook.com";
- const string ccAddress = "cc@outlook.com";
- const string bcc1Address = "bcc1@outlook.com";
- const string bcc2Address = "bcc2@outlook.com";
- MailAddress[] bccAddresses = {new MailAddress(bcc1Address), new MailAddress(bcc2Address)};
- const string fromAddress = "test@outlook.com";
- const string subject = "Test Subject";
- const string textBody = "Test Text Body";
- const string htmlBody = "<p>Test HTML Body</p>";
- const string headerKey = "headerkey";
- var testHeader = new Dictionary<string, string> { { headerKey, "headervalue" } };
- const string categoryName = "Example Category";
-
- var message = new SendGridMessage();
- message.AddTo(toAddress);
- message.AddCc(ccAddress);
- message.Bcc = bccAddresses;
- message.From = new MailAddress(fromAddress);
- message.Subject = subject;
- message.Text = textBody;
- message.Html = htmlBody;
- message.AddHeaders(testHeader);
- message.Header.SetCategory(categoryName);
-
- var result = webApi.FetchFormParams(message);
- if (credentials)
- {
- Assert.True(result.Any(r => r.Key == "api_user" && r.Value == TestUsername));
- Assert.True(result.Any(r => r.Key == "api_key" && r.Value == TestPassword));
- }
- Assert.True(result.Any(r => r.Key == "to[]" && r.Value == toAddress));
- Assert.True(result.Any(r => r.Key == "cc[]" && r.Value == ccAddress));
- Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc1Address));
- Assert.True(result.Any(r => r.Key == "bcc[]" && r.Value == bcc2Address));
- Assert.True(result.Any(r => r.Key == "from" && r.Value == fromAddress));
- Assert.True(result.Any(r => r.Key == "subject" && r.Value == subject));
- Assert.True(result.Any(r => r.Key == "text" && r.Value == textBody));
- Assert.True(result.Any(r => r.Key == "html" && r.Value == htmlBody));
- Assert.True(
- result.Any(
- r => r.Key == "headers" && r.Value == String.Format("{{\"{0}\":\"{1}\"}}", headerKey, testHeader[headerKey])));
- Assert.True(
- result.Any(r => r.Key == "x-smtpapi" && r.Value == String.Format("{{\"category\" : \"{0}\"}}", categoryName)));
- }
- }
-}
diff --git a/SendGrid/Tests/app.config b/SendGrid/Tests/app.config deleted file mode 100644 index 199cd2d..0000000 --- a/SendGrid/Tests/app.config +++ /dev/null @@ -1,26 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<configuration>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-2.6.9.0" newVersion="2.6.9.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
- <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
- <startup>
- <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
- </startup>
-</configuration>
\ No newline at end of file diff --git a/SendGrid/Tests/packages.config b/SendGrid/Tests/packages.config deleted file mode 100644 index 8b08e52..0000000 --- a/SendGrid/Tests/packages.config +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="utf-8"?>
-<packages>
- <package id="Moq" version="4.2.1402.2112" targetFramework="net4" />
- <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net45" />
- <package id="NUnit" version="2.6.3" targetFramework="net4" />
- <package id="NUnitTestAdapter" version="2.0.0" targetFramework="net45" />
- <package id="SendGrid.SmtpApi" version="1.3.1" targetFramework="net45" />
-</packages>
\ No newline at end of file diff --git a/SendGrid/Tests/sendgrid-csharp.snk b/SendGrid/Tests/sendgrid-csharp.snk Binary files differdeleted file mode 100644 index aff2944..0000000 --- a/SendGrid/Tests/sendgrid-csharp.snk +++ /dev/null diff --git a/SendGrid/UnitTest/UnitTest.cs b/SendGrid/UnitTest/UnitTest.cs index 11f55cd..fac59f9 100644 --- a/SendGrid/UnitTest/UnitTest.cs +++ b/SendGrid/UnitTest/UnitTest.cs @@ -1,282 +1,241 @@ using System; -using System.Net; -using System.Net.Http; -using System.Threading.Tasks; using NUnit.Framework; -using Newtonsoft.Json.Linq; -using SendGrid; -using Newtonsoft.Json; +using SendGrid.Helpers.Mail; +using System.Collections.Generic; namespace UnitTest { + // Test the initialization of the Client [TestFixture] public class APIKeys { - static string _baseUri = "https://api.sendgrid.com/"; static string _apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); - public Client client = new Client(_apiKey, _baseUri); - private static string _api_key_id = ""; + public dynamic sg = new SendGrid.SendGridAPIClient(_apiKey); [Test] - public void ApiKeysIntegrationTest() + public void TestSendGridAPIClient() { - TestGet(); - TestPost(); - TestPatch(); - TestDelete(); + Assert.AreEqual(sg.client.Host, "https://api.sendgrid.com"); + Assert.AreEqual(sg.client.Version, "v3"); + Assert.AreEqual(sg.client.RequestHeaders["Authorization"], "Bearer " + _apiKey); + Assert.AreEqual(sg.client.RequestHeaders["Content-Type"], "application/json"); + Assert.AreEqual(sg.client.RequestHeaders["User-Agent"], "sendgrid/" + sg.Version + " csharp"); } - - private void TestGet() - { - HttpResponseMessage response = client.ApiKeys.Get().Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - string jsonString = jsonObject.result.ToString(); - Assert.IsNotNull(jsonString); - } - - private void TestPost() - { - HttpResponseMessage response = client.ApiKeys.Post("CSharpTestKey").Result; - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - string api_key = jsonObject.api_key.ToString(); - _api_key_id = jsonObject.api_key_id.ToString(); - string name = jsonObject.name.ToString(); - Assert.IsNotNull(api_key); - Assert.IsNotNull(_api_key_id); - Assert.IsNotNull(name); - } - - private void TestPatch() - { - HttpResponseMessage response = client.ApiKeys.Patch(_api_key_id, "CSharpTestKeyPatched").Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - _api_key_id = jsonObject.api_key_id.ToString(); - string name = jsonObject.name.ToString(); - Assert.IsNotNull(_api_key_id); - Assert.IsNotNull(name); - } - - private void TestDelete() - { - HttpResponseMessage response = client.ApiKeys.Delete(_api_key_id).Result; - Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); - } - - [Test] - public void TestGetOnce() - { - var responseGet = client.ApiKeys.Get().Result; - } - - [Test] - public void TestGetTenTimes() - { - HttpResponseMessage responseGet; - for (int i = 0; i < 10; i++) - { - responseGet = client.ApiKeys.Get().Result; - } - } - - [Test] - public void TestGetTenTimesAsync() - { - Task[] tasks = new Task[10]; - for (int i = 0; i < 10; i++) - { - tasks[i] = client.ApiKeys.Get(); - } - Task.WaitAll(tasks); - } - } - - [TestFixture] - public class UnsubscribeGroups - { - static string _baseUri = "https://api.sendgrid.com/"; - static string _apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); - public Client client = new Client(_apiKey, _baseUri); - private static string _unsubscribe_groups_key_id = ""; - - [Test] - public void UnsubscribeGroupsIntegrationTest() - { - int unsubscribeGroupId = 69; - - TestGet(); - TestGetUnique(unsubscribeGroupId); - TestPost(); - TestDelete(); - } - - private void TestGet() - { - HttpResponseMessage response = client.UnsubscribeGroups.Get().Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JsonConvert.DeserializeObject(rawString); - Assert.IsNotNull(jsonObject); - } - - private void TestGetUnique(int unsubscribeGroupId) - { - HttpResponseMessage response = client.UnsubscribeGroups.Get(unsubscribeGroupId).Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JsonConvert.DeserializeObject(rawString); - Assert.IsNotNull(jsonObject); - } - - private void TestPost() - { - HttpResponseMessage response = client.UnsubscribeGroups.Post("C Sharp Unsubscribes", "Testing the C Sharp Library", false).Result; - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - string name = jsonObject.name.ToString(); - string description = jsonObject.description.ToString(); - _unsubscribe_groups_key_id = jsonObject.id.ToString(); - bool is_default = jsonObject.is_default; - Assert.IsNotNull(name); - Assert.IsNotNull(description); - Assert.IsNotNull(_unsubscribe_groups_key_id); - Assert.IsNotNull(is_default); - } - - private void TestDelete() - { - HttpResponseMessage response = client.UnsubscribeGroups.Delete(_unsubscribe_groups_key_id).Result; - Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); - } - } + // Test the building of the v3/mail/send request body [TestFixture] - public class Suppressions + public class Mail { - static string _baseUri = "https://api.sendgrid.com/"; static string _apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); - public Client client = new Client(_apiKey, _baseUri); + public dynamic sg = new SendGrid.SendGridAPIClient(_apiKey); + // Base case for sending an email [Test] - public void SuppressionsIntegrationTest() - { - int unsubscribeGroupId = 69; - - TestGet(unsubscribeGroupId); - string[] emails = { "example@example.com", "example2@example.com" }; - TestPost(unsubscribeGroupId, emails); - TestDelete(unsubscribeGroupId, "example@example.com"); - TestDelete(unsubscribeGroupId, "example2@example.com"); - } - - private void TestGet(int unsubscribeGroupId) + public void TestHelloEmail() { - HttpResponseMessage response = client.Suppressions.Get(unsubscribeGroupId).Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JsonConvert.DeserializeObject(rawString); - Assert.IsNotNull(jsonObject); - } - - private void TestPost(int unsubscribeGroupId, string[] emails) - { - HttpResponseMessage response = client.Suppressions.Post(unsubscribeGroupId, emails).Result; - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - string recipient_emails = jsonObject.recipient_emails.ToString(); - Assert.IsNotNull(recipient_emails); - } - - private void TestDelete(int unsubscribeGroupId, string email) - { - HttpResponseMessage response = client.Suppressions.Delete(unsubscribeGroupId, email).Result; - Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); - } - - } - - [TestFixture] - public class GlobalSuppressions - { - static string _baseUri = "https://api.sendgrid.com/"; - static string _apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); - public Client client = new Client(_apiKey, _baseUri); + SendGrid.Helpers.Mail.Mail mail = new SendGrid.Helpers.Mail.Mail(); - [Test] - public void GlobalSuppressionsIntegrationTest() - { - string email = "example3@example.com"; + Email email = new Email(); + email.Address = "dx@sendgrid.com"; + mail.From = email; - TestGet(email); - string[] emails = { "example1@example.com", "example2@example.com" }; - TestPost(emails); - TestDelete("example1@example.com"); - TestDelete("example2@example.com"); - } + Personalization personalization = new Personalization(); + email = new Email(); + email.Address = "elmer.thomas@sendgrid.com"; + personalization.AddTo(email); + mail.AddPersonalization(personalization); - private void TestGet(string email) - { - HttpResponseMessage response = client.GlobalSuppressions.Get(email).Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JsonConvert.DeserializeObject(rawString); - Assert.IsNotNull(jsonObject); - } + mail.Subject = "Hello World from the SendGrid CSharp Library"; - private void TestPost(string[] emails) - { - HttpResponseMessage response = client.GlobalSuppressions.Post(emails).Result; - Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JObject.Parse(rawString); - string recipient_emails = jsonObject.recipient_emails.ToString(); - Assert.IsNotNull(recipient_emails); - } + Content content = new Content(); + content.Type = "text/plain"; + content.Value = "Textual content"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/html"; + content.Value = "<html><body>HTML content</body></html>"; + mail.AddContent(content); - private void TestDelete(string email) - { - HttpResponseMessage response = client.GlobalSuppressions.Delete(email).Result; - Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode); + String ret = mail.Get(); + Assert.AreEqual(ret, "{\"from\":{\"email\":\"dx@sendgrid.com\"},\"subject\":\"Hello World from the SendGrid CSharp Library\",\"personalization\":[{\"to\":[{\"email\":\"elmer.thomas@sendgrid.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"<html><body>HTML content</body></html>\"}]}"); } - } - - [TestFixture] - public class GlobalStats - { - static string _baseUri = "https://api.sendgrid.com/"; - static string _apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY"); - public Client client = new Client(_apiKey, _baseUri); + // All paramaters available for sending an email [Test] - public void GlobalStatsIntegrationTest() - { - string startDate = "2015-11-01"; - string endDate = "2015-12-01"; - string aggregatedBy = "day"; - TestGet(startDate); - TestGet(startDate, endDate); - TestGet(startDate, endDate, aggregatedBy); - aggregatedBy = "week"; - TestGet(startDate, endDate, aggregatedBy); - aggregatedBy = "month"; - TestGet(startDate, endDate, aggregatedBy); - } - - private void TestGet(string startDate, string endDate=null, string aggregatedBy=null) - { - HttpResponseMessage response = client.GlobalStats.Get(startDate, endDate, aggregatedBy).Result; - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - string rawString = response.Content.ReadAsStringAsync().Result; - dynamic jsonObject = JsonConvert.DeserializeObject(rawString); - Assert.IsNotNull(jsonObject); + public void TestKitchenSink() + { + SendGrid.Helpers.Mail.Mail mail = new SendGrid.Helpers.Mail.Mail(); + + Email email = new Email(); + email.Name = "DX"; + email.Address = "dx@sendgrid.com"; + mail.From = email; + + mail.Subject = "Hello World from the SendGrid CSharp Library"; + + Personalization personalization = new Personalization(); + email = new Email(); + email.Name = "Elmer Thomas"; + email.Address = "elmer.thomas@sendgrid.com"; + personalization.AddTo(email); + email = new Email(); + email.Name = "Matt Bernier"; + email.Address = "matt.bernier@sendgrid.com"; + personalization.AddCc(email); + email = new Email(); + email.Name = "Eric Shallock"; + email.Address = "eric.shallock@sendgrid.com"; + personalization.AddCc(email); + personalization.AddBcc("elmer.thomas+secret@sengrid.com"); + personalization.AddBcc("elmer.thomas+secret@elmer.thomas.com"); + personalization.Subject = "Thank you for signing up, %name%"; + personalization.AddHeader("X-Test", "True"); + personalization.AddHeader("X-Mock", "True"); + personalization.AddSubstitution("%name%", "Elmer"); + personalization.AddSubstitution("%city%", "Moreno Valley"); + personalization.AddCustomArgs("marketing", "false"); + personalization.AddCustomArgs("transactional", "true"); + personalization.SendAt = 1461775051; + mail.AddPersonalization(personalization); + + personalization = new Personalization(); + email = new Email(); + email.Name = "Elmer Thomas"; + email.Address = "elmer.thomas@gmail.com"; + personalization.AddTo(email); + email = new Email(); + email.Name = "Matt Bernier"; + email.Address = "matt.bernier@sendgrid.com"; + personalization.AddCc(email); + email = new Email(); + email.Name = "Eric Shallock"; + email.Address = "eric.shallock@sendgrid.com"; + personalization.AddCc(email); + personalization.AddBcc("elmer.thomas+secret@sengrid.com"); + personalization.AddBcc("elmer.thomas+secret@elmer.thomas.com"); + personalization.Subject = "Thank you for signing up, %name%"; + personalization.AddHeader("X-Test", "True"); + personalization.AddHeader("X-Mock", "True"); + personalization.AddSubstitution("%name%", "Elmer"); + personalization.AddSubstitution("%city%", "Moreno Valley"); + personalization.AddCustomArgs("marketing", "false"); + personalization.AddCustomArgs("transactional", "true"); + personalization.SendAt = 1461775051; + mail.AddPersonalization(personalization); + + Content content = new Content(); + content.Type = "text/plain"; + content.Value = "Textual content"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/html"; + content.Value = "<html><body>HTML content</body></html>"; + mail.AddContent(content); + content = new Content(); + content.Type = "text/calendar"; + content.Value = "Party Time!!"; + mail.AddContent(content); + + Attachment attachment = new Attachment(); + attachment.Content = "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12"; + attachment.Type = "application/pdf"; + attachment.Filename = "balance_001.pdf"; + attachment.Disposition = "attachment"; + attachment.ContentId = "Balance Sheet"; + mail.AddAttachment(attachment); + + attachment = new Attachment(); + attachment.Content = "iVBORw0KGgoAAAANSUhEUgAAAlgAAAC0CAMAAAB/oaI+AAACvlBMVEX///8aguLp8/wmiOMnieQ5k+bg7vtcpury+P0/lufX6foehOJCmOe92/er0fRToen9/v8hhuNkquvG4PjP5fkihuMjh+Mkh+MtjOQzkOVusO12tO77/f/8/v8cg+IfheMwjuVFmud/ue/+///t9f3u9v33+/5Wo+ppreyUxfGjzfP7/f4bguIri+QsjOQ8leY9leZdp+v6/P4ehONKnOhmrOx+uO+IvvCRw/Hc7Pvm8fzr9PwgheNHm+iayPKfy/PF3/jH4fji7/vo8vz1+v4ujeU0kOU6lOZIm+hSoOl4te601va62fbv9v3w9/30+f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3mbmlTQ0BAqh77fpMcVlfq68d61xQPIe0MgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCATC/1P8HzJOjPJg+R84AAAAAElFTkSuQmCC"; + attachment.Type = "image/png"; + attachment.Filename = "banner.png"; + attachment.Disposition = "inline"; + attachment.ContentId = "Banner"; + mail.AddAttachment(attachment); + + mail.TemplateId = "13b8f94f-bcae-4ec6-b752-70d6cb59f932"; + + mail.AddHeader("X-Day", "Monday"); + mail.AddHeader("X-Month", "January"); + + mail.AddSection("%section1", "Substitution for Section 1 Tag"); + mail.AddSection("%section2", "Substitution for Section 2 Tag"); + + mail.AddCategory("customer"); + mail.AddCategory("vip"); + + mail.AddCustomArgs("campaign", "welcome"); + mail.AddCustomArgs("sequence", "2"); + + ASM asm = new ASM(); + asm.GroupId = 3; + List<int> groups_to_display = new List<int>() + { + 1, 4, 5 + }; + asm.GroupsToDisplay = groups_to_display; + mail.Asm = asm; + + mail.SendAt = 1461775051; + + mail.SetIpPoolId = "23"; + + mail.BatchId = "some_batch_id"; + + MailSettings mailSettings = new MailSettings(); + BCCSettings bccSettings = new BCCSettings(); + bccSettings.Enable = true; + bccSettings.Email = "dx@sendgrid.com"; + mailSettings.BccSettings = bccSettings; + BypassListManagement bypassListManagement = new BypassListManagement(); + bypassListManagement.Enable = true; + mailSettings.BypassListManagement = bypassListManagement; + FooterSettings footerSettings = new FooterSettings(); + footerSettings.Enable = true; + footerSettings.Text = "Some Footer Text"; + footerSettings.Html = "<bold>Some HTML Here</bold>"; + mailSettings.FooterSettings = footerSettings; + SandboxMode sandboxMode = new SandboxMode(); + sandboxMode.Enable = false; + mailSettings.SandboxMode = sandboxMode; + SpamCheck spamCheck = new SpamCheck(); + spamCheck.Enable = true; + spamCheck.Threshold = 1; + spamCheck.PostToUrl = "https://gotchya.example.com"; + mailSettings.SpamCheck = spamCheck; + mail.MailSettings = mailSettings; + + TrackingSettings trackingSettings = new TrackingSettings(); + ClickTracking clickTracking = new ClickTracking(); + clickTracking.Enable = false; + clickTracking.EnableText = false; + trackingSettings.ClickTracking = clickTracking; + OpenTracking openTracking = new OpenTracking(); + openTracking.Enable = true; + openTracking.SubstitutionTag = "Optional tag to replace with the open image in the body of the message"; + trackingSettings.OpenTracking = openTracking; + SubscriptionTracking subscriptionTracking = new SubscriptionTracking(); + subscriptionTracking.Enable = true; + subscriptionTracking.Text = "text to insert into the text/plain portion of the message"; + subscriptionTracking.Html = "<bold>HTML to insert into the text/html portion of the message</bold>"; + subscriptionTracking.SubstitutionTag = "text to insert into the text/plain portion of the message"; + trackingSettings.SubscriptionTracking = subscriptionTracking; + Ganalytics ganalytics = new Ganalytics(); + ganalytics.Enable = true; + ganalytics.UtmCampaign = "some campaign"; + ganalytics.UtmContent = "some content"; + ganalytics.UtmMedium = "some medium"; + ganalytics.UtmSource = "some source"; + ganalytics.UtmTerm = "some term"; + trackingSettings.Ganalytics = ganalytics; + mail.TrackingSettings = trackingSettings; + + email = new Email(); + email.Address = "dx@sendgrid.com"; + mail.ReplyTo = email; + + String ret = mail.Get(); + Assert.AreEqual(ret, "{\"from\":{\"name\":\"DX\",\"email\":\"dx@sendgrid.com\"},\"subject\":\"Hello World from the SendGrid CSharp Library\",\"personalization\":[{\"to\":[{\"name\":\"Elmer Thomas\",\"email\":\"elmer.thomas@sendgrid.com\"}],\"cc\":[{\"name\":\"Matt Bernier\",\"email\":\"matt.bernier@sendgrid.com\"},{\"name\":\"Eric Shallock\",\"email\":\"eric.shallock@sendgrid.com\"}],\"bcc\":[\"elmer.thomas+secret@sengrid.com\",\"elmer.thomas+secret@elmer.thomas.com\"],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Elmer\",\"%city%\":\"Moreno Valley\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051},{\"to\":[{\"name\":\"Elmer Thomas\",\"email\":\"elmer.thomas@gmail.com\"}],\"cc\":[{\"name\":\"Matt Bernier\",\"email\":\"matt.bernier@sendgrid.com\"},{\"name\":\"Eric Shallock\",\"email\":\"eric.shallock@sendgrid.com\"}],\"bcc\":[\"elmer.thomas+secret@sengrid.com\",\"elmer.thomas+secret@elmer.thomas.com\"],\"subject\":\"Thank you for signing up, %name%\",\"headers\":{\"X-Test\":\"True\",\"X-Mock\":\"True\"},\"substitutions\":{\"%name%\":\"Elmer\",\"%city%\":\"Moreno Valley\"},\"custom_args\":{\"marketing\":\"false\",\"transactional\":\"true\"},\"send_at\":1461775051}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"<html><body>HTML content</body></html>\"},{\"type\":\"text/calendar\",\"value\":\"Party Time!!\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"iVBORw0KGgoAAAANSUhEUgAAAlgAAAC0CAMAAAB/oaI+AAACvlBMVEX///8aguLp8/wmiOMnieQ5k+bg7vtcpury+P0/lufX6foehOJCmOe92/er0fRToen9/v8hhuNkquvG4PjP5fkihuMjh+Mkh+MtjOQzkOVusO12tO77/f/8/v8cg+IfheMwjuVFmud/ue/+///t9f3u9v33+/5Wo+ppreyUxfGjzfP7/f4bguIri+QsjOQ8leY9leZdp+v6/P4ehONKnOhmrOx+uO+IvvCRw/Hc7Pvm8fzr9PwgheNHm+iayPKfy/PF3/jH4fji7/vo8vz1+v4ujeU0kOU6lOZIm+hSoOl4te601va62fbv9v3w9/30+f75/P4piuQyj+U2keZGmuhLnejE3/fZ6vodg+Japeptr+yTxPGy1fXB3ffS5vnq9Pz2+v74+/5Al+dZpOpor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KBQCAQCAQCgUAgEAgEAoFAIBAIBAKBQCAQCATC/1P8HzJOjPJg+R84AAAAAElFTkSuQmCC\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"headers\":{\"X-Day\":\"Monday\",\"X-Month\":\"January\"},\"sections\":{\"%section1\":\"Substitution for Section 1 Tag\",\"%section2\":\"Substitution for Section 2 Tag\"},\"categories\":[\"customer\",\"vip\"],\"custom_args\":{\"campaign\":\"welcome\",\"sequence\":\"2\"},\"send_at\":1461775051,\"asm\":{\"group_id\":3,\"groups_to_display\":[1,4,5]},\"batch_id\":\"some_batch_id\",\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"dx@sendgrid.com\"},\"bypass_list_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Some Footer Text\",\"html\":\"<bold>Some HTML Here</bold>\"},\"sandbox_mode\":{},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://gotchya.example.com\"}},\"tracking_settings\":{\"click_tracking\":{},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"<bold>HTML to insert into the text/html portion of the message</bold>\",\"substitution_tag\":\"text to insert into the text/plain portion of the message\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_medium\":\"some medium\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_name\":\"some campaign\"}},\"reply_to\":{\"email\":\"dx@sendgrid.com\"}}"); } } } diff --git a/SendGrid/UnitTest/UnitTests.csproj b/SendGrid/UnitTest/UnitTests.csproj index d6ef8ae..c076d2a 100644 --- a/SendGrid/UnitTest/UnitTests.csproj +++ b/SendGrid/UnitTest/UnitTests.csproj @@ -8,7 +8,7 @@ <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>UnitTest</RootNamespace> <AssemblyName>UnitTest</AssemblyName> - <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> + <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids> <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion> @@ -42,6 +42,10 @@ <AssemblyOriginatorKeyFile>sendgrid-csharp.snk</AssemblyOriginatorKeyFile> </PropertyGroup> <ItemGroup> + <Reference Include="CSharpHTTPClient, Version=1.0.2.0, Culture=neutral, PublicKeyToken=79219bf4e5ecaaca, processorArchitecture=MSIL"> + <HintPath>..\packages\SendGrid.CSharp.HTTP.Client.1.0.2\lib\CSharpHTTPClient.dll</HintPath> + <Private>True</Private> + </Reference> <Reference Include="Microsoft.CSharp" /> <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath> @@ -69,6 +73,7 @@ </Reference> <Reference Include="System" /> <Reference Include="System.Net.Http" /> + <Reference Include="System.Web.Extensions" /> </ItemGroup> <Choose> <When Condition="('$(VisualStudioVersion)' == '10.0' or '$(VisualStudioVersion)' == '') and '$(TargetFrameworkVersion)' == 'v3.5'"> diff --git a/SendGrid/UnitTest/app.config b/SendGrid/UnitTest/app.config index 8f7aefe..dbaad53 100644 --- a/SendGrid/UnitTest/app.config +++ b/SendGrid/UnitTest/app.config @@ -1,11 +1,11 @@ -<?xml version="1.0" encoding="utf-8"?> +<?xml version="1.0" encoding="utf-8"?> <configuration> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> - <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /> - <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /> + <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/> + <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0"/> </dependentAssembly> </assemblyBinding> </runtime> -<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /></startup></configuration> +<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/></startup></configuration> diff --git a/SendGrid/UnitTest/packages.config b/SendGrid/UnitTest/packages.config index 6cc1a28..1157672 100644 --- a/SendGrid/UnitTest/packages.config +++ b/SendGrid/UnitTest/packages.config @@ -3,4 +3,5 @@ <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" /> <package id="NUnit" version="2.6.4" targetFramework="net45" /> <package id="NUnitTestAdapter" version="2.0.0" targetFramework="net45" /> + <package id="SendGrid.CSharp.HTTP.Client" version="1.0.2" targetFramework="net45" /> </packages>
\ No newline at end of file diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000..8bdad19 --- /dev/null +++ b/USAGE.md @@ -0,0 +1,94 @@ +```csharp +using System; +using System.Collections.Generic; +using System.Web.Script.Serialization; +using SendGrid.Helpers.Mail; + +namespace Example +{ + internal class Example + { + private static void Main() + { + String apiKey = Environment.GetEnvironmentVariable("SENDGRID_APIKEY", EnvironmentVariableTarget.User); + dynamic sg = new SendGrid.SendGridAPIClient(apiKey); + + string queryParams = @"{ + 'limit': 100 + }"; + dynamic response = sg.client.api_keys.get(queryParams: queryParams); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to POST."); + Console.ReadLine(); + + // POST + string requestBody = @"{ + 'name': 'My API Key 5', + 'scopes': [ + 'mail.send', + 'alerts.create', + 'alerts.read' + ] + }"; + response = sg.client.api_keys.post(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + JavaScriptSerializer jss = new JavaScriptSerializer(); + var ds_response = jss.Deserialize<Dictionary<string, dynamic>>(response.ResponseBody.ReadAsStringAsync().Result); + string api_key_id = ds_response["api_key_id"]; + + Console.WriteLine("\n\nPress any key to continue to GET single."); + Console.ReadLine(); + + // GET Single + response = sg.client.api_keys._(api_key_id).get(); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to PATCH."); + Console.ReadLine(); + + // PATCH + requestBody = @"{ + 'name': 'A New Hope' + }"; + response = sg.client.api_keys._(api_key_id).patch(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to PUT."); + Console.ReadLine(); + + // PUT + requestBody = @"{ + 'name': 'A New Hope', + 'scopes': [ + ' user.profile.read', + ' user.profile.update' + ] + }"; + response = sg.client.api_keys._(api_key_id).put(requestBody: requestBody); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseBody.ReadAsStringAsync().Result); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to continue to DELETE."); + Console.ReadLine(); + + // DELETE + response = sg.client.api_keys._(api_key_id).delete(); + Console.WriteLine(response.StatusCode); + Console.WriteLine(response.ResponseHeaders.ToString()); + + Console.WriteLine("\n\nPress any key to exit."); + Console.ReadLine(); + } + } +} +```
\ No newline at end of file |