Skip to content

Commit

Permalink
Updated to 1.6.0
Browse files Browse the repository at this point in the history
- Added RawEncoding Property
- Added Unicode Property
- Allow authentication with API Key
- Changes to Async to Sync calling.
  • Loading branch information
sgtfrankieboy committed Sep 19, 2017
1 parent 708cb84 commit 1bbf3de
Show file tree
Hide file tree
Showing 5 changed files with 137 additions and 39 deletions.
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ Install-Package SpryngApiHttpDotNet
To use the Spryng HTTP Api you must first create a new instance of the `SpryngHttpClient`:

```C#
SpryngHttpClient client = new SpryngHttpClient(username, password);
var client = pryngHttpClient.CreateClientWithPassword(username, password);
```

For sending SMS it is also possible to use an api key. Checking of credits does not work.


## Sending a SMS

Expand All @@ -37,7 +39,7 @@ You can now send the SMS using the client:
```C#
try
{
client.ExecuteSmsRequest(request);
await client.ExecuteSmsRequestAsync(request);
Console.WriteLine("SMS has been send!");
}
catch (SpryngHttpClientException ex)
Expand All @@ -46,10 +48,10 @@ catch (SpryngHttpClientException ex)
}
```

The API also provides an Async implementation which can be used in the same fashion as the synchronous api:
The API also provides an sync implementation which can be used in the same fashion as the asynchronous api:

```C#
await client.ExecuteSmsRequestAsync(request);
client.ExecuteSmsRequest(request);
```

#### SmsRequest Options
Expand All @@ -74,3 +76,5 @@ double remainingCredits = client.GetCreditAmount();
// Asynchronous
double remainingCredits = await client.GetCreditAmountAsync();
```

When using the API Key it is not possible to get your credit amount.
6 changes: 2 additions & 4 deletions SpryngApiHttpDotNet.Example/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ static void Main(string[] args)
string password = GetInput("Password", true);

// Create a new SpryngHttpClient with the given Username and Password.
SpryngHttpClient client = new SpryngHttpClient(username, password);
SpryngHttpClient client = SpryngHttpClient.CreateClientWithPassword(username, password);

// Get the amount of credits left in the account.
Console.WriteLine("Available Credits: {0}", client.GetCreditAmount());

// Make a new SmsRequest
SmsRequest request = new SmsRequest()
{
Destinations = new string[] { "31612345678", "31698765432" },
Destinations = new string[] { GetInput("Destination") },
Sender = GetInput("Sender"),
Body = GetInput("Body")
};
Expand All @@ -41,8 +41,6 @@ static void Main(string[] args)
Console.WriteLine("An Exception occured!\n{0}", ex.Message);
}



Console.ReadKey(true);
}

Expand Down
20 changes: 16 additions & 4 deletions SpryngApiHttpDotNet/Models/Sms/SmsRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,26 @@ public class SmsRequest
public string Route { get; set; }

/// <summary>
/// If you wish to send Long SMS
/// If you wish to send Long SMS.
/// <para>When using long sms the system will automatically devide your message into messages up to 153 characters per SMS.</para>
/// </summary>
/// <remarks>
/// When using long sms the system will automatically devide your message into messages up to 153 characters per SMS.
/// </remarks>
/// <value>False</value>
public bool AllowLong { get; set; }

/// <summary>
/// If you wish to use Unicode in SMS. This will double the used characters per SMS.
/// <para>Unicode support needs to be enabled by Spryng Support for the route.</para>
/// </summary>
/// <value>False</value>
public bool EnableUnicode { get; set; }

/// <summary>
/// If you wish to use characters like the Euro sign.
/// <para>Raw Encoding support needs to be enabled by Spryng Support for the route.</para>
/// </summary>
/// <value>False</value>
public bool EnableRawEncoding { get; set; }

public SmsRequest()
{
AllowLong = false;
Expand Down
4 changes: 2 additions & 2 deletions SpryngApiHttpDotNet/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,5 @@
// 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.5.2.0")]
[assembly: AssemblyFileVersion("1.5.2.0")]
[assembly: AssemblyVersion("1.6.0.0")]
[assembly: AssemblyFileVersion("1.6.0.0")]
134 changes: 109 additions & 25 deletions SpryngApiHttpDotNet/SpryngHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@ namespace Spryng
public class SpryngHttpClient
{
private static readonly string ApiEndpoint = "https://api.spryngsms.com/api/";
private static readonly string ApiEndpointCheck = "check.php";
private static readonly string ApiEndpointSend = "send.php";
private static readonly string ApiEndpoint_Check = "check.php";
private static readonly string ApiEndpoint_Send = "send.php";

private readonly string _username;
private readonly string _password;
private readonly string _apikey;
private readonly bool _usePassword;
private readonly HttpClient _httpClient;

/// <summary>
Expand All @@ -28,18 +30,75 @@ public class SpryngHttpClient
/// <param name="password">Chosen by user when signing up.</param>
/// <param name="httpMessageHandler">The HTTP handler stack to use for sending requests.</param>
/// <exception cref="ArgumentException">An <see cref="ArgumentException"/> if the <paramref name="username"/> or <paramref name="password"/> are invalid.</exception>
public SpryngHttpClient(string username, string password, HttpMessageHandler httpMessageHandler = null)
public SpryngHttpClient(string username, string password, HttpMessageHandler httpMessageHandler = null)
: this(username, password, false, httpMessageHandler)
{
}

/// <summary>
/// Create a new instance of the <see cref="SpryngHttpClient"/>.
/// </summary>
/// <param name="username">Chosen by user when signing up.</param>
/// <param name="secret">The apikey or Password depending on what the value of <paramref name="isApiKey"/> is.</param>
/// <param name="isApiKey">Wether the given secret is a apikey or password.</param>
/// <param name="httpMessageHandler">The HTTP handler stack to use for sending requests.</param>
/// <exception cref="ArgumentException">An <see cref="ArgumentException"/> if the <paramref name="username"/> or <paramref name="secret"/> are invalid.</exception>
public SpryngHttpClient(string username, string secret, bool isApiKey, HttpMessageHandler httpMessageHandler = null)
{
if (string.IsNullOrEmpty(username) || username.Length < 2 || username.Length > 32)
throw new ArgumentException("Username must be between 2 and 32 characters.");
if (string.IsNullOrEmpty(password) || password.Length < 6 || password.Length > 32)
throw new ArgumentException("Password must be between 6 and 32 characters.");

_username = username;
_password = password;
_httpClient = createHttpClient(httpMessageHandler);

if (isApiKey)
{
_apikey = secret;
_usePassword = false;
}
else
{
if (string.IsNullOrEmpty(secret) || secret.Length < 6 || secret.Length > 32)
throw new ArgumentException("Password must be between 6 and 32 characters.");

_password = secret;
_usePassword = true;
}


_httpClient = CreateHttpClient(httpMessageHandler);
}

/// <summary>
/// Create a new instance of the <see cref="SpryngHttpClient"/> using a Password as authentication.
/// </summary>
/// <param name="username">Chosen by user when signing up.</param>
/// <param name="password">Chosen by user when signing up.</param>
/// <param name="httpMessageHandler">The HTTP handler stack to use for sending requests.</param>
/// <exception cref="ArgumentException">An <see cref="ArgumentException"/> if the <paramref name="username"/> or <paramref name="password"/> are invalid.</exception>
public static SpryngHttpClient CreateClientWithPassword(string username, string password, HttpMessageHandler httpMessageHandler = null)
{
return new SpryngHttpClient(
username: username,
secret: password,
isApiKey: false,
httpMessageHandler: httpMessageHandler);
}

/// <summary>
/// Create a new instance of the <see cref="SpryngHttpClient"/> using an API Key as authentication.
/// </summary>
/// <param name="username">Chosen by user when signing up.</param>
/// <param name="apikey">API Key used to authenticate.</param>
/// <param name="httpMessageHandler">The HTTP handler stack to use for sending requests.</param>
/// <exception cref="ArgumentException">An <see cref="ArgumentException"/> if the <paramref name="username"/> or <paramref name="password"/> are invalid.</exception>
public static SpryngHttpClient CreateClientWithApiKey(string username, string apikey, HttpMessageHandler httpMessageHandler = null)
{
return new SpryngHttpClient(
username: username,
secret: apikey,
isApiKey: true,
httpMessageHandler: httpMessageHandler);
}

/// <summary>
/// Execute a SMS request and get its response.
Expand All @@ -51,7 +110,7 @@ public void ExecuteSmsRequest(SmsRequest request)
{
try
{
var task = Task.Run(async () => { await ExecuteSmsRequestAsync(request); });
var task = Task.Run(async () => await ExecuteSmsRequestAsync(request).ConfigureAwait(false));
task.Wait();
}
catch (AggregateException ex)
Expand All @@ -69,12 +128,8 @@ public void ExecuteSmsRequest(SmsRequest request)
public async Task ExecuteSmsRequestAsync(SmsRequest request)
{
// Set the predefined data for the SMS Send request.
var requestData = new Dictionary<string, string>()
{
{ "OPERATION", "send" },
{ "USERNAME", _username },
{ "PASSWORD", _password }
};
var requestData = CreateRequestDictionary();
requestData.Add("OPERATION", "send");

// Validate Destinations field
if (request.Destinations == null || !request.Destinations.Any() || request.Destinations.Count() > 100)
Expand Down Expand Up @@ -112,6 +167,11 @@ public async Task ExecuteSmsRequestAsync(SmsRequest request)
throw new ArgumentException("Body can't be longer than 160 without enabling 'ALLOWLONG'.");
}

if (request.EnableUnicode)
requestData.Add("UNICODE", "1");
if (request.EnableRawEncoding)
requestData.Add("RAWENCODING", "1");

requestData.Add("ALLOWLONG", request.AllowLong ? "1" : "0");
requestData.Add("BODY", request.Body);

Expand All @@ -121,7 +181,7 @@ public async Task ExecuteSmsRequestAsync(SmsRequest request)

// Make HTTP Request to Spryng API and Parse the result.

var result = await executeHttpRequest(ApiEndpointSend, requestData);
var result = await ExecuteHttpRequest(ApiEndpoint_Send, requestData).ConfigureAwait(false);

var resultInt = int.Parse(result);

Expand All @@ -137,11 +197,9 @@ public async Task ExecuteSmsRequestAsync(SmsRequest request)
/// <exception cref="SpryngHttpClientException"></exception>
public async Task<double> GetCreditAmountAsync()
{
var result = await executeHttpRequest(ApiEndpointCheck, new Dictionary<string, string>()
{
{ "Username", _username },
{ "Password", _password }
});
var requestData = CreateRequestDictionary();

var result = await ExecuteHttpRequest(ApiEndpoint_Check, requestData).ConfigureAwait(false);

double credits = double.Parse(result, CultureInfo.GetCultureInfo("en-US"));

Expand All @@ -160,7 +218,9 @@ public double GetCreditAmount()
{
try
{
return GetCreditAmountAsync().Result;
var task = Task.Run(async () => await GetCreditAmountAsync().ConfigureAwait(false));
task.Wait();
return task.Result;
}
catch (AggregateException ex)
{
Expand All @@ -169,20 +229,44 @@ public double GetCreditAmount()
}
}

private async Task<string> executeHttpRequest(string relativePath, Dictionary<string, string> parameters)
/// <summary>
/// Creates a new instance of the request dictionary.
/// </summary>
/// <returns></returns>
private Dictionary<string, string> CreateRequestDictionary()
{
if(_usePassword)
{
return new Dictionary<string, string>()
{
{ "USERNAME", _username },
{ "PASSWORD", _password },
};
}
else
{
return new Dictionary<string, string>()
{
{ "USERNAME", _username },
{ "SECRET", _apikey }
};
}
}

private async Task<string> ExecuteHttpRequest(string relativePath, Dictionary<string, string> parameters)
{
// Create the post data string using our custom URL Encoding so we can properly send special characters.
var postData = string.Join("&", parameters.Select(kvp => $"{kvp.Key}={Utilities.CustomUrlEncode(kvp.Value)}"));

// Create the String Content, set it to the Encoding used by the service and make sure we send as a form.
var stringContent = new StringContent(postData, Encoding.GetEncoding("ISO-8859-1"), "application/x-www-form-urlencoded");

var result = await _httpClient.PostAsync(relativePath, stringContent);
var result = await _httpClient.PostAsync(relativePath, stringContent).ConfigureAwait(false);

return await result.Content.ReadAsStringAsync();
return await result.Content.ReadAsStringAsync().ConfigureAwait(false);
}

private HttpClient createHttpClient(HttpMessageHandler handler)
private HttpClient CreateHttpClient(HttpMessageHandler handler)
{
HttpClient httpClient;
if (handler == null)
Expand Down

0 comments on commit 1bbf3de

Please sign in to comment.