diff --git a/src/Twilio/Base/IOptions.cs b/src/Twilio/Base/IOptions.cs
index b966f47cd..dd632c148 100644
--- a/src/Twilio/Base/IOptions.cs
+++ b/src/Twilio/Base/IOptions.cs
@@ -2,74 +2,74 @@
using System.Collections.Generic;
namespace Twilio.Base
-{
+{
+ ///
+ /// Interface to wrap parameters of a resource
+ ///
+ /// Resource type
+ public interface IOptions where T : Resource
+ {
///
- /// Interface to wrap parameters of a resource
+ /// Generate the list of parameters for the request
///
- /// Resource type
- public interface IOptions where T : Resource
- {
- ///
- /// Generate the list of parameters for the request
- ///
- ///
- /// List of parameters for the request
- List> GetParams();
- }
-
+ ///
+ /// List of parameters for the request
+ List> GetParams();
+ }
+
+ ///
+ /// Parameters that are passed when reading resources
+ ///
+ /// Resource type
+ public abstract class ReadOptions : IOptions where T : Resource
+ {
+ private int? _pageSize;
+
///
- /// Parameters that are passed when reading resources
+ /// Page size to read
///
- /// Resource type
- public abstract class ReadOptions : IOptions where T : Resource
- {
- private int? _pageSize;
-
- ///
- /// Page size to read
- ///
- public int? PageSize
- {
- get { return _pageSize; }
- set
- {
- if (value == null)
- {
- return;
- }
-
- _pageSize = value.Value;
- }
- }
-
- private long? _limit;
-
- ///
- /// Maximum number of records to read
- ///
- public long? Limit
- {
- get { return _limit; }
- set
- {
- if (value == null)
- {
- return;
- }
-
- _limit = value;
- if (_pageSize == null)
- {
- _pageSize = (int) value.Value;
- }
- }
- }
-
- ///
- /// Generate the list of parameters for the request
- ///
- ///
- /// List of parameters for the request
- public abstract List> GetParams();
- }
+ public int? PageSize
+ {
+ get { return _pageSize; }
+ set
+ {
+ if (value == null)
+ {
+ return;
+ }
+
+ _pageSize = value.Value;
+ }
+ }
+
+ private long? _limit;
+
+ ///
+ /// Maximum number of records to read
+ ///
+ public long? Limit
+ {
+ get { return _limit; }
+ set
+ {
+ if (value == null)
+ {
+ return;
+ }
+
+ _limit = value;
+ if (_pageSize == null)
+ {
+ _pageSize = (int)value.Value;
+ }
+ }
+ }
+
+ ///
+ /// Generate the list of parameters for the request
+ ///
+ ///
+ /// List of parameters for the request
+ public abstract List> GetParams();
+ }
}
diff --git a/src/Twilio/Base/Page.cs b/src/Twilio/Base/Page.cs
index cf1a72234..18aa6d031 100644
--- a/src/Twilio/Base/Page.cs
+++ b/src/Twilio/Base/Page.cs
@@ -1,160 +1,160 @@
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Newtonsoft.Json;
-using Newtonsoft.Json.Linq;
-using Twilio.Rest;
-using static System.String;
-
-namespace Twilio.Base
-{
- ///
- /// Page of resources
- ///
- /// Resource type
- public class Page where T : Resource
- {
- ///
- /// Records for this page
- ///
- public List Records { get; }
-
- ///
- /// Page size
- ///
- public int PageSize { get; }
-
- private readonly string _uri;
- private readonly string _url;
- private readonly string _firstPageUri;
- private readonly string _firstPageUrl;
- private readonly string _nextPageUri;
- private readonly string _nextPageUrl;
- private readonly string _previousPageUri;
- private readonly string _previousPageUrl;
-
- private Page(
- List records,
- int pageSize,
- string uri = null,
- string url = null,
- string firstPageUri = null,
- string firstPageUrl = null,
- string previousPageUri = null,
- string previousPageUrl = null,
- string nextPageUri = null,
- string nextPageUrl = null
- )
- {
- Records = records;
- PageSize = pageSize;
- _uri = uri;
- _url = url;
- _firstPageUri = firstPageUri;
- _firstPageUrl = firstPageUrl;
- _nextPageUri = nextPageUri;
- _nextPageUrl = nextPageUrl;
- _previousPageUri = previousPageUri;
- _previousPageUrl = previousPageUrl;
- }
-
- private static string UrlFromUri(Domain domain, string uri)
- {
- return "https://" + domain + ".twilio.com" + uri;
- }
-
- ///
- /// Generate the first page URL
- ///
- /// Twilio subdomain
- /// URL for the first page of results
- public string GetFirstPageUrl(Domain domain)
- {
- return _firstPageUrl ?? UrlFromUri(domain, _firstPageUri);
- }
-
- ///
- /// Get the next page URL
- ///
- /// Twilio subdomain
- /// URL for the next page of results
- public string GetNextPageUrl(Domain domain)
- {
- return _nextPageUrl ?? UrlFromUri(domain, _nextPageUri);
- }
-
- ///
- /// Get the previous page URL
- ///
- /// Twilio subdomain
- /// URL for the previous page of results
- public string GetPreviousPageUrl(Domain domain)
- {
- return _previousPageUrl ?? UrlFromUri(domain, _previousPageUri);
- }
-
- ///
- /// Get the URL for the current page
- ///
- /// Twilio subdomain
- /// URL for the current page of results
- public string GetUrl(Domain domain)
- {
- return _url ?? UrlFromUri(domain, _uri);
- }
-
- ///
- /// Determines if there is another page of results
- ///
- /// true if there is a next page; false otherwise
- public bool HasNextPage()
- {
- return !IsNullOrEmpty(_nextPageUrl) || !IsNullOrEmpty(_nextPageUri);
- }
-
- ///
- /// Converts a JSON payload to a Page of results
- ///
- /// JSON key where the records are
- /// JSON payload
- /// Page of results
- public static Page FromJson(string recordKey, string json)
- {
- var root = JObject.Parse(json);
- var records = root[recordKey];
- var parsedRecords = records.Children().Select(
- record => JsonConvert.DeserializeObject(record.ToString())
- ).ToList();
-
- var uriNode = root["uri"];
- if (uriNode != null)
- {
- JToken pageSize;
- JToken firstPageUri;
- JToken nextPageUri;
- JToken previousPageUri;
-
- // v2010 API
- return new Page(
- parsedRecords,
- root.TryGetValue("page_size", out pageSize) ? root["page_size"].Value() : parsedRecords.Count,
- uri: uriNode.Value(),
- firstPageUri: root.TryGetValue("first_page_uri", out firstPageUri) ? root["first_page_uri"].Value() : null,
- nextPageUri: root.TryGetValue("next_page_uri", out nextPageUri) ? root["next_page_uri"].Value() : null,
- previousPageUri: root.TryGetValue("previous_page_uri", out previousPageUri) ? root["previous_page_uri"].Value() : null
- );
- }
-
- // next-gen API
- var meta = root["meta"];
- return new Page(
- parsedRecords,
- meta["page_size"].Value(),
- url: meta["url"].Value(),
- firstPageUrl: meta["first_page_url"].Value(),
- nextPageUrl: meta["next_page_url"].Value(),
- previousPageUrl: meta["previous_page_url"].Value()
- );
- }
- }
-}
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using Newtonsoft.Json;
+using Newtonsoft.Json.Linq;
+using Twilio.Rest;
+using static System.String;
+
+namespace Twilio.Base
+{
+ ///
+ /// Page of resources
+ ///
+ /// Resource type
+ public class Page where T : Resource
+ {
+ ///
+ /// Records for this page
+ ///
+ public List Records { get; }
+
+ ///
+ /// Page size
+ ///
+ public int PageSize { get; }
+
+ private readonly string _uri;
+ private readonly string _url;
+ private readonly string _firstPageUri;
+ private readonly string _firstPageUrl;
+ private readonly string _nextPageUri;
+ private readonly string _nextPageUrl;
+ private readonly string _previousPageUri;
+ private readonly string _previousPageUrl;
+
+ private Page(
+ List records,
+ int pageSize,
+ string uri = null,
+ string url = null,
+ string firstPageUri = null,
+ string firstPageUrl = null,
+ string previousPageUri = null,
+ string previousPageUrl = null,
+ string nextPageUri = null,
+ string nextPageUrl = null
+ )
+ {
+ Records = records;
+ PageSize = pageSize;
+ _uri = uri;
+ _url = url;
+ _firstPageUri = firstPageUri;
+ _firstPageUrl = firstPageUrl;
+ _nextPageUri = nextPageUri;
+ _nextPageUrl = nextPageUrl;
+ _previousPageUri = previousPageUri;
+ _previousPageUrl = previousPageUrl;
+ }
+
+ private static string UrlFromUri(Domain domain, string uri)
+ {
+ return "https://" + domain + ".twilio.com" + uri;
+ }
+
+ ///
+ /// Generate the first page URL
+ ///
+ /// Twilio subdomain
+ /// URL for the first page of results
+ public string GetFirstPageUrl(Domain domain)
+ {
+ return _firstPageUrl ?? UrlFromUri(domain, _firstPageUri);
+ }
+
+ ///
+ /// Get the next page URL
+ ///
+ /// Twilio subdomain
+ /// URL for the next page of results
+ public string GetNextPageUrl(Domain domain)
+ {
+ return _nextPageUrl ?? UrlFromUri(domain, _nextPageUri);
+ }
+
+ ///
+ /// Get the previous page URL
+ ///
+ /// Twilio subdomain
+ /// URL for the previous page of results
+ public string GetPreviousPageUrl(Domain domain)
+ {
+ return _previousPageUrl ?? UrlFromUri(domain, _previousPageUri);
+ }
+
+ ///
+ /// Get the URL for the current page
+ ///
+ /// Twilio subdomain
+ /// URL for the current page of results
+ public string GetUrl(Domain domain)
+ {
+ return _url ?? UrlFromUri(domain, _uri);
+ }
+
+ ///
+ /// Determines if there is another page of results
+ ///
+ /// true if there is a next page; false otherwise
+ public bool HasNextPage()
+ {
+ return !IsNullOrEmpty(_nextPageUrl) || !IsNullOrEmpty(_nextPageUri);
+ }
+
+ ///
+ /// Converts a JSON payload to a Page of results
+ ///
+ /// JSON key where the records are
+ /// JSON payload
+ /// Page of results
+ public static Page FromJson(string recordKey, string json)
+ {
+ var root = JObject.Parse(json);
+ var records = root[recordKey];
+ var parsedRecords = records.Children().Select(
+ record => JsonConvert.DeserializeObject(record.ToString())
+ ).ToList();
+
+ var uriNode = root["uri"];
+ if (uriNode != null)
+ {
+ JToken pageSize;
+ JToken firstPageUri;
+ JToken nextPageUri;
+ JToken previousPageUri;
+
+ // v2010 API
+ return new Page(
+ parsedRecords,
+ root.TryGetValue("page_size", out pageSize) ? root["page_size"].Value() : parsedRecords.Count,
+ uri: uriNode.Value(),
+ firstPageUri: root.TryGetValue("first_page_uri", out firstPageUri) ? root["first_page_uri"].Value() : null,
+ nextPageUri: root.TryGetValue("next_page_uri", out nextPageUri) ? root["next_page_uri"].Value() : null,
+ previousPageUri: root.TryGetValue("previous_page_uri", out previousPageUri) ? root["previous_page_uri"].Value() : null
+ );
+ }
+
+ // next-gen API
+ var meta = root["meta"];
+ return new Page(
+ parsedRecords,
+ meta["page_size"].Value(),
+ url: meta["url"].Value(),
+ firstPageUrl: meta["first_page_url"].Value(),
+ nextPageUrl: meta["next_page_url"].Value(),
+ previousPageUrl: meta["previous_page_url"].Value()
+ );
+ }
+ }
+}
diff --git a/src/Twilio/Base/Resource.cs b/src/Twilio/Base/Resource.cs
index 69354a900..0f0ae89a4 100644
--- a/src/Twilio/Base/Resource.cs
+++ b/src/Twilio/Base/Resource.cs
@@ -1,4 +1,4 @@
namespace Twilio.Base
-{
- public abstract class Resource {}
+{
+ public abstract class Resource { }
}
\ No newline at end of file
diff --git a/src/Twilio/Base/ResourceSet.cs b/src/Twilio/Base/ResourceSet.cs
index 15110b7d8..d64879b1e 100644
--- a/src/Twilio/Base/ResourceSet.cs
+++ b/src/Twilio/Base/ResourceSet.cs
@@ -4,118 +4,118 @@
using Twilio.Clients;
namespace Twilio.Base
-{
+{
+ ///
+ /// A collection of resources of type T
+ ///
+ ///
+ /// Resource Type
+ public class ResourceSet : IEnumerable where T : Resource
+ {
///
- /// A collection of resources of type T
+ /// Automatically iterate through pages of results
+ ///
+ public bool AutoPaging { get; set; }
+
+ private readonly ITwilioRestClient _client;
+ private readonly ReadOptions _options;
+ private readonly long _pageLimit;
+
+ private long _pages;
+ private long _processed;
+ private Page _page;
+ private IEnumerator _iterator;
+
+ ///
+ /// Create a new resource set
///
///
- /// Resource Type
- public class ResourceSet : IEnumerable where T : Resource
- {
- ///
- /// Automatically iterate through pages of results
- ///
- public bool AutoPaging { get; set; }
-
- private readonly ITwilioRestClient _client;
- private readonly ReadOptions _options;
- private readonly long _pageLimit;
-
- private long _pages;
- private long _processed;
- private Page _page;
- private IEnumerator _iterator;
-
- ///
- /// Create a new resource set
- ///
- ///
- /// Page of resources
- /// Read options
- /// Client to make requests
- public ResourceSet(Page page, ReadOptions options, ITwilioRestClient client)
- {
- _page = page;
- _options = options;
- _client = client;
-
- _iterator = page.Records.GetEnumerator();
- _processed = 0;
- _pages = 1;
- _pageLimit = long.MaxValue;
-
- AutoPaging = true;
-
- if (_options.Limit != null)
- {
- _pageLimit = (long) (Math.Ceiling((double) _options.Limit.Value / page.PageSize));
- }
- }
-
- ///
- /// Get iterator for resources
- ///
- ///
- /// IEnumerator of resources
- public IEnumerator GetEnumerator()
- {
- while (_page != null)
- {
- _iterator.Reset();
- while (_iterator.MoveNext())
- {
- // Exit if we've reached item limit
- if (_options.Limit != null && _processed > _options.Limit.Value)
- {
- yield break;
- }
-
- _processed++;
- yield return _iterator.Current;
- }
-
- if (AutoPaging && _page.HasNextPage())
- {
- FetchNextPage();
- }
- else
- {
- break;
- }
- }
- }
-
- ///
- /// Get iterator for resources
- ///
- ///
- /// IEnumerator of resources
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
-
- private void FetchNextPage()
- {
- if (!_page.HasNextPage() || _pages >= _pageLimit)
- {
- _page = null;
- _iterator = null;
- return;
- }
-
- _pages++;
- _page = (Page)GetNextPage().Invoke(null, new object[]{ _page, _client });
- _iterator = _page.Records.GetEnumerator();
- }
-
- private static MethodInfo GetNextPage()
- {
+ /// Page of resources
+ /// Read options
+ /// Client to make requests
+ public ResourceSet(Page page, ReadOptions options, ITwilioRestClient client)
+ {
+ _page = page;
+ _options = options;
+ _client = client;
+
+ _iterator = page.Records.GetEnumerator();
+ _processed = 0;
+ _pages = 1;
+ _pageLimit = long.MaxValue;
+
+ AutoPaging = true;
+
+ if (_options.Limit != null)
+ {
+ _pageLimit = (long)(Math.Ceiling((double)_options.Limit.Value / page.PageSize));
+ }
+ }
+
+ ///
+ /// Get iterator for resources
+ ///
+ ///
+ /// IEnumerator of resources
+ public IEnumerator GetEnumerator()
+ {
+ while (_page != null)
+ {
+ _iterator.Reset();
+ while (_iterator.MoveNext())
+ {
+ // Exit if we've reached item limit
+ if (_options.Limit != null && _processed > _options.Limit.Value)
+ {
+ yield break;
+ }
+
+ _processed++;
+ yield return _iterator.Current;
+ }
+
+ if (AutoPaging && _page.HasNextPage())
+ {
+ FetchNextPage();
+ }
+ else
+ {
+ break;
+ }
+ }
+ }
+
+ ///
+ /// Get iterator for resources
+ ///
+ ///
+ /// IEnumerator of resources
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
+ return GetEnumerator();
+ }
+
+ private void FetchNextPage()
+ {
+ if (!_page.HasNextPage() || _pages >= _pageLimit)
+ {
+ _page = null;
+ _iterator = null;
+ return;
+ }
+
+ _pages++;
+ _page = (Page)GetNextPage().Invoke(null, new object[] { _page, _client });
+ _iterator = _page.Records.GetEnumerator();
+ }
+
+ private static MethodInfo GetNextPage()
+ {
#if !NET35
- return typeof(T).GetRuntimeMethod("NextPage", new[]{ typeof(Page), typeof(ITwilioRestClient) });
+ return typeof(T).GetRuntimeMethod("NextPage", new[] { typeof(Page), typeof(ITwilioRestClient) });
#else
return typeof(T).GetMethod("NextPage", new[]{ typeof(Page), typeof(ITwilioRestClient) });
#endif
- }
- }
+ }
+ }
}
diff --git a/src/Twilio/Clients/ITwilioRestClient.cs b/src/Twilio/Clients/ITwilioRestClient.cs
index 496c03f9f..958f87a17 100644
--- a/src/Twilio/Clients/ITwilioRestClient.cs
+++ b/src/Twilio/Clients/ITwilioRestClient.cs
@@ -1,44 +1,44 @@
using Twilio.Http;
namespace Twilio.Clients
-{
+{
+ ///
+ /// Interface for a Twilio Client
+ ///
+ public interface ITwilioRestClient
+ {
///
- /// Interface for a Twilio Client
+ /// Get the account sid all requests are made against
///
- public interface ITwilioRestClient
- {
- ///
- /// Get the account sid all requests are made against
- ///
- string AccountSid { get; }
-
- ///
- /// Get the region requests are made against
- ///
- string Region { get; }
-
- ///
- /// Get the http client that makes requests
- ///
- HttpClient HttpClient { get; }
-
- ///
- /// Make a request to Twilio
- ///
- ///
- /// Request to make
- /// response of the request
- Response Request(Request request);
-
+ string AccountSid { get; }
+
+ ///
+ /// Get the region requests are made against
+ ///
+ string Region { get; }
+
+ ///
+ /// Get the http client that makes requests
+ ///
+ HttpClient HttpClient { get; }
+
+ ///
+ /// Make a request to Twilio
+ ///
+ ///
+ /// Request to make
+ /// response of the request
+ Response Request(Request request);
+
#if !NET35
- ///
- /// Make a request to Twilio
- ///
- ///
- /// Request to make
- /// response of the request
- System.Threading.Tasks.Task RequestAsync(Request request);
+ ///
+ /// Make a request to Twilio
+ ///
+ ///
+ /// Request to make
+ /// response of the request
+ System.Threading.Tasks.Task RequestAsync(Request request);
#endif
- }
+ }
}
diff --git a/src/Twilio/Clients/TwilioRestClient.cs b/src/Twilio/Clients/TwilioRestClient.cs
index 641050a2d..139d60335 100644
--- a/src/Twilio/Clients/TwilioRestClient.cs
+++ b/src/Twilio/Clients/TwilioRestClient.cs
@@ -14,261 +14,261 @@
#endif
namespace Twilio.Clients
-{
+{
+ ///
+ /// Implementation of a TwilioRestClient.
+ ///
+ public class TwilioRestClient : ITwilioRestClient
+ {
///
- /// Implementation of a TwilioRestClient.
+ /// Client to make HTTP requests
///
- public class TwilioRestClient : ITwilioRestClient
- {
- ///
- /// Client to make HTTP requests
- ///
- public HttpClient HttpClient { get; }
-
- ///
- /// Account SID to use for requests
- ///
- public string AccountSid { get; }
-
- ///
- /// Twilio region to make requests to
- ///
- public string Region { get; }
-
- ///
- /// Twilio edge to make requests to
- ///
- public string Edge { get; set; }
-
- ///
- /// Log level for logging
- ///
- public string LogLevel { get; set; } = Environment.GetEnvironmentVariable("TWILIO_LOG_LEVEL");
- private readonly string _username;
- private readonly string _password;
-
- ///
- /// Constructor for a TwilioRestClient
- ///
- ///
- /// username for requests
- /// password for requests
- /// account sid to make requests for
- /// region to make requests for
- /// http client used to make the requests
- /// edge to make requests for
- public TwilioRestClient(
- string username,
- string password,
- string accountSid = null,
- string region = null,
- HttpClient httpClient = null,
- string edge = null
- )
- {
- _username = username;
- _password = password;
-
- AccountSid = accountSid ?? username;
- HttpClient = httpClient ?? DefaultClient();
-
- Region = region;
- Edge = edge;
- }
-
- ///
- /// Make a request to the Twilio API
- ///
- ///
- /// request to make
- /// response of the request
- public Response Request(Request request)
- {
- request.SetAuth(_username, _password);
-
- if (LogLevel == "debug")
- LogRequest(request);
-
- if (Region != null)
- request.Region = Region;
-
- if (Edge != null)
- request.Edge = Edge;
-
- Response response;
- try
- {
- response = HttpClient.MakeRequest(request);
- if (LogLevel == "debug")
- {
- Console.WriteLine("response.status: " + response.StatusCode);
- Console.WriteLine("response.headers: " + response.Headers);
- }
- }
- catch (Exception clientException)
- {
- throw new ApiConnectionException(
- "Connection Error: " + request.Method + request.ConstructUrl(),
- clientException
- );
- }
- return ProcessResponse(response);
- }
-
+ public HttpClient HttpClient { get; }
+
+ ///
+ /// Account SID to use for requests
+ ///
+ public string AccountSid { get; }
+
+ ///
+ /// Twilio region to make requests to
+ ///
+ public string Region { get; }
+
+ ///
+ /// Twilio edge to make requests to
+ ///
+ public string Edge { get; set; }
+
+ ///
+ /// Log level for logging
+ ///
+ public string LogLevel { get; set; } = Environment.GetEnvironmentVariable("TWILIO_LOG_LEVEL");
+ private readonly string _username;
+ private readonly string _password;
+
+ ///
+ /// Constructor for a TwilioRestClient
+ ///
+ ///
+ /// username for requests
+ /// password for requests
+ /// account sid to make requests for
+ /// region to make requests for
+ /// http client used to make the requests
+ /// edge to make requests for
+ public TwilioRestClient(
+ string username,
+ string password,
+ string accountSid = null,
+ string region = null,
+ HttpClient httpClient = null,
+ string edge = null
+ )
+ {
+ _username = username;
+ _password = password;
+
+ AccountSid = accountSid ?? username;
+ HttpClient = httpClient ?? DefaultClient();
+
+ Region = region;
+ Edge = edge;
+ }
+
+ ///
+ /// Make a request to the Twilio API
+ ///
+ ///
+ /// request to make
+ /// response of the request
+ public Response Request(Request request)
+ {
+ request.SetAuth(_username, _password);
+
+ if (LogLevel == "debug")
+ LogRequest(request);
+
+ if (Region != null)
+ request.Region = Region;
+
+ if (Edge != null)
+ request.Edge = Edge;
+
+ Response response;
+ try
+ {
+ response = HttpClient.MakeRequest(request);
+ if (LogLevel == "debug")
+ {
+ Console.WriteLine("response.status: " + response.StatusCode);
+ Console.WriteLine("response.headers: " + response.Headers);
+ }
+ }
+ catch (Exception clientException)
+ {
+ throw new ApiConnectionException(
+ "Connection Error: " + request.Method + request.ConstructUrl(),
+ clientException
+ );
+ }
+ return ProcessResponse(response);
+ }
+
#if !NET35
- ///
- /// Make a request to the Twilio API
- ///
- ///
- /// request to make
- /// Task that resolves to the response of the request
- public async Task RequestAsync(Request request)
- {
- request.SetAuth(_username, _password);
-
- if (Region != null)
- request.Region = Region;
-
- if (Edge != null)
- request.Edge = Edge;
-
- Response response;
- try
- {
- response = await HttpClient.MakeRequestAsync(request);
- }
- catch (Exception clientException)
- {
- throw new ApiConnectionException(
- "Connection Error: " + request.Method + request.ConstructUrl(),
- clientException
- );
- }
- return ProcessResponse(response);
- }
-
- private static HttpClient DefaultClient()
- {
- return new SystemNetHttpClient();
- }
+ ///
+ /// Make a request to the Twilio API
+ ///
+ ///
+ /// request to make
+ /// Task that resolves to the response of the request
+ public async Task RequestAsync(Request request)
+ {
+ request.SetAuth(_username, _password);
+
+ if (Region != null)
+ request.Region = Region;
+
+ if (Edge != null)
+ request.Edge = Edge;
+
+ Response response;
+ try
+ {
+ response = await HttpClient.MakeRequestAsync(request);
+ }
+ catch (Exception clientException)
+ {
+ throw new ApiConnectionException(
+ "Connection Error: " + request.Method + request.ConstructUrl(),
+ clientException
+ );
+ }
+ return ProcessResponse(response);
+ }
+
+ private static HttpClient DefaultClient()
+ {
+ return new SystemNetHttpClient();
+ }
#else
private static HttpClient DefaultClient()
{
return new WebRequestClient();
}
#endif
-
- private static Response ProcessResponse(Response response)
- {
- if (response == null)
- {
- throw new ApiConnectionException("Connection Error: No response received.");
- }
-
- if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode < HttpStatusCode.BadRequest)
- {
- return response;
- }
-
- // Deserialize and throw exception
- RestException restException = null;
- try
- {
- restException = RestException.FromJson(response.Content);
- }
- catch (JsonReaderException) { /* Allow null check below to handle */ }
-
- if (restException == null)
- {
- throw new ApiException("Api Error: " + response.StatusCode + " - " + (response.Content ?? "[no content]"));
- }
-
- throw new ApiException(
- restException.Code,
- (int)response.StatusCode,
- restException.Message ?? "Unable to make request, " + response.StatusCode,
- restException.MoreInfo,
- restException.Details
- );
- }
-
- ///
- /// Test that this application can use updated SSL certificates on
- /// api.twilio.com:8443. It's a bit easier to call this method from
- /// TwilioClient.ValidateSslCertificate().
- ///
- public static void ValidateSslCertificate()
- {
- ValidateSslCertificate(DefaultClient());
- }
-
- ///
- /// Test that this application can use updated SSL certificates on
- /// api.twilio.com:8443. Generally, you'll want to use the version of this
- /// function that takes no parameters unless you have a reason not to.
- ///
- ///
- /// HTTP Client to use for testing the request
- public static void ValidateSslCertificate(HttpClient client)
- {
- Request request = new Request("GET", "api", ":8443/", null);
-
- try
- {
- Response response = client.MakeRequest(request);
-
- if (!response.StatusCode.Equals(HttpStatusCode.OK))
- {
- throw new CertificateValidationException(
- "Unexpected response from certificate endpoint",
- request,
- response
- );
- }
- }
- catch (CertificateValidationException e)
- {
- throw e;
- }
- catch (Exception e)
- {
- throw new CertificateValidationException(
- "Connection to api.twilio.com:8443 failed",
- e,
- request
- );
- }
- }
-
- ///
- /// Format request information when LogLevel is set to debug
- ///
- ///
- /// HTTP request
- private static void LogRequest(Request request)
- {
- Console.WriteLine("-- BEGIN Twilio API Request --");
- Console.WriteLine("request.method: " + request.Method);
- Console.WriteLine("request.URI: " + request.Uri);
-
- if (request.QueryParams != null)
- {
- request.QueryParams.ForEach(parameter => Console.WriteLine(parameter.Key + ":" + parameter.Value));
- }
-
- if (request.HeaderParams != null)
- {
- for (int i = 0; i < request.HeaderParams.Count; i++)
- {
- var lowercaseHeader = request.HeaderParams[i].Key.ToLower();
- if (lowercaseHeader.Contains("authorization") == false)
- {
- Console.WriteLine(request.HeaderParams[i].Key + ":" + request.HeaderParams[i].Value);
- }
- }
- }
-
- Console.WriteLine("-- END Twilio API Request --");
- }
- }
+
+ private static Response ProcessResponse(Response response)
+ {
+ if (response == null)
+ {
+ throw new ApiConnectionException("Connection Error: No response received.");
+ }
+
+ if (response.StatusCode >= HttpStatusCode.OK && response.StatusCode < HttpStatusCode.BadRequest)
+ {
+ return response;
+ }
+
+ // Deserialize and throw exception
+ RestException restException = null;
+ try
+ {
+ restException = RestException.FromJson(response.Content);
+ }
+ catch (JsonReaderException) { /* Allow null check below to handle */ }
+
+ if (restException == null)
+ {
+ throw new ApiException("Api Error: " + response.StatusCode + " - " + (response.Content ?? "[no content]"));
+ }
+
+ throw new ApiException(
+ restException.Code,
+ (int)response.StatusCode,
+ restException.Message ?? "Unable to make request, " + response.StatusCode,
+ restException.MoreInfo,
+ restException.Details
+ );
+ }
+
+ ///
+ /// Test that this application can use updated SSL certificates on
+ /// api.twilio.com:8443. It's a bit easier to call this method from
+ /// TwilioClient.ValidateSslCertificate().
+ ///
+ public static void ValidateSslCertificate()
+ {
+ ValidateSslCertificate(DefaultClient());
+ }
+
+ ///
+ /// Test that this application can use updated SSL certificates on
+ /// api.twilio.com:8443. Generally, you'll want to use the version of this
+ /// function that takes no parameters unless you have a reason not to.
+ ///
+ ///
+ /// HTTP Client to use for testing the request
+ public static void ValidateSslCertificate(HttpClient client)
+ {
+ Request request = new Request("GET", "api", ":8443/", null);
+
+ try
+ {
+ Response response = client.MakeRequest(request);
+
+ if (!response.StatusCode.Equals(HttpStatusCode.OK))
+ {
+ throw new CertificateValidationException(
+ "Unexpected response from certificate endpoint",
+ request,
+ response
+ );
+ }
+ }
+ catch (CertificateValidationException e)
+ {
+ throw e;
+ }
+ catch (Exception e)
+ {
+ throw new CertificateValidationException(
+ "Connection to api.twilio.com:8443 failed",
+ e,
+ request
+ );
+ }
+ }
+
+ ///
+ /// Format request information when LogLevel is set to debug
+ ///
+ ///
+ /// HTTP request
+ private static void LogRequest(Request request)
+ {
+ Console.WriteLine("-- BEGIN Twilio API Request --");
+ Console.WriteLine("request.method: " + request.Method);
+ Console.WriteLine("request.URI: " + request.Uri);
+
+ if (request.QueryParams != null)
+ {
+ request.QueryParams.ForEach(parameter => Console.WriteLine(parameter.Key + ":" + parameter.Value));
+ }
+
+ if (request.HeaderParams != null)
+ {
+ for (int i = 0; i < request.HeaderParams.Count; i++)
+ {
+ var lowercaseHeader = request.HeaderParams[i].Key.ToLower();
+ if (lowercaseHeader.Contains("authorization") == false)
+ {
+ Console.WriteLine(request.HeaderParams[i].Key + ":" + request.HeaderParams[i].Value);
+ }
+ }
+ }
+
+ Console.WriteLine("-- END Twilio API Request --");
+ }
+ }
}
diff --git a/src/Twilio/Converters/HttpMethodConverter.cs b/src/Twilio/Converters/HttpMethodConverter.cs
index 4aea19539..4c1616125 100644
--- a/src/Twilio/Converters/HttpMethodConverter.cs
+++ b/src/Twilio/Converters/HttpMethodConverter.cs
@@ -3,72 +3,72 @@
using Newtonsoft.Json.Linq;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Convert between strings and HttpMethod
+ ///
+ public class HttpMethodConverter : JsonConverter
+ {
///
- /// Convert between strings and HttpMethod
+ /// Write the HTTP method out to json
///
- public class HttpMethodConverter : JsonConverter
- {
- ///
- /// Write the HTTP method out to json
- ///
- ///
- /// json writer
- /// value to write serialize
- /// json serialize
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- var t = JToken.FromObject(value.ToString());
- t.WriteTo(writer);
- }
-
- ///
- /// Deserialize a string into a HttpMethod
- ///
- ///
- /// json reader
- /// type of object
- ///
- ///
- ///
- /// Deserialized HttpMethod
- public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
- {
- var token = reader.Value as string;
- if (token == null)
- {
- return null;
- }
-
- switch (token.ToLower())
- {
- case "get":
- return Http.HttpMethod.Get;
-
- case "post":
- return Http.HttpMethod.Post;
-
- case "put":
- return Http.HttpMethod.Put;
-
- case "delete":
- return Http.HttpMethod.Delete;
-
- default:
- return null;
- }
- }
-
- ///
- /// Determine if an object can be converted to HttpMethod
- ///
- ///
- /// object type
- /// true if the type is an HttpMethod; false otherwise
- public override bool CanConvert(Type objectType)
- {
- return objectType == typeof(Http.HttpMethod);
- }
- }
+ ///
+ /// json writer
+ /// value to write serialize
+ /// json serialize
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ var t = JToken.FromObject(value.ToString());
+ t.WriteTo(writer);
+ }
+
+ ///
+ /// Deserialize a string into a HttpMethod
+ ///
+ ///
+ /// json reader
+ /// type of object
+ ///
+ ///
+ ///
+ /// Deserialized HttpMethod
+ public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
+ {
+ var token = reader.Value as string;
+ if (token == null)
+ {
+ return null;
+ }
+
+ switch (token.ToLower())
+ {
+ case "get":
+ return Http.HttpMethod.Get;
+
+ case "post":
+ return Http.HttpMethod.Post;
+
+ case "put":
+ return Http.HttpMethod.Put;
+
+ case "delete":
+ return Http.HttpMethod.Delete;
+
+ default:
+ return null;
+ }
+ }
+
+ ///
+ /// Determine if an object can be converted to HttpMethod
+ ///
+ ///
+ /// object type
+ /// true if the type is an HttpMethod; false otherwise
+ public override bool CanConvert(Type objectType)
+ {
+ return objectType == typeof(Http.HttpMethod);
+ }
+ }
}
diff --git a/src/Twilio/Converters/MarshalConverter.cs b/src/Twilio/Converters/MarshalConverter.cs
index 2e7f8d3f1..d4bbe5e9a 100644
--- a/src/Twilio/Converters/MarshalConverter.cs
+++ b/src/Twilio/Converters/MarshalConverter.cs
@@ -1,21 +1,21 @@
using System;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Convert strings to objects
+ ///
+ public class MarshalConverter
+ {
///
- /// Convert strings to objects
+ /// Convert a date time string to a DateTime object
///
- public class MarshalConverter
- {
- ///
- /// Convert a date time string to a DateTime object
- ///
- /// date time string to convert
- /// Converted DateTime object
- public static DateTime DateTimeFromString(string dateTimeString)
- {
- return DateTime.Parse(dateTimeString);
- }
- }
+ /// date time string to convert
+ /// Converted DateTime object
+ public static DateTime DateTimeFromString(string dateTimeString)
+ {
+ return DateTime.Parse(dateTimeString);
+ }
+ }
}
diff --git a/src/Twilio/Converters/PhoneNumberConverter.cs b/src/Twilio/Converters/PhoneNumberConverter.cs
index ba158463d..7a744c59f 100644
--- a/src/Twilio/Converters/PhoneNumberConverter.cs
+++ b/src/Twilio/Converters/PhoneNumberConverter.cs
@@ -3,50 +3,50 @@
using Newtonsoft.Json.Linq;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Convert between strings and a PhoneNumber
+ ///
+ public class PhoneNumberConverter : JsonConverter
+ {
///
- /// Convert between strings and a PhoneNumber
+ /// Write value to JsonWriter
///
- public class PhoneNumberConverter : JsonConverter
- {
- ///
- /// Write value to JsonWriter
- ///
- /// Writer to write to
- /// Value to write
- /// unsued
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- var t = JToken.FromObject(value.ToString());
- t.WriteTo(writer);
- }
-
- ///
- /// Convert a string to a PhoneNumber
- ///
- /// JsonReader to read from
- /// unused
- /// unused
- /// unsued
- /// Converted PhoneNumber
- public override object ReadJson(
- JsonReader reader,
- Type objectType,
- object existingValue,
- JsonSerializer serializer
- )
- {
- return new Types.PhoneNumber(reader.Value as string);
- }
-
- ///
- /// Determines if an object converted to a PhoneNumber
- ///
- /// Type of object
- /// true if an object can be converted; false otherwise
- public override bool CanConvert(Type objectType)
- {
- return objectType == typeof(Enum);
- }
- }
+ /// Writer to write to
+ /// Value to write
+ /// unsued
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ var t = JToken.FromObject(value.ToString());
+ t.WriteTo(writer);
+ }
+
+ ///
+ /// Convert a string to a PhoneNumber
+ ///
+ /// JsonReader to read from
+ /// unused
+ /// unused
+ /// unsued
+ /// Converted PhoneNumber
+ public override object ReadJson(
+ JsonReader reader,
+ Type objectType,
+ object existingValue,
+ JsonSerializer serializer
+ )
+ {
+ return new Types.PhoneNumber(reader.Value as string);
+ }
+
+ ///
+ /// Determines if an object converted to a PhoneNumber
+ ///
+ /// Type of object
+ /// true if an object can be converted; false otherwise
+ public override bool CanConvert(Type objectType)
+ {
+ return objectType == typeof(Enum);
+ }
+ }
}
diff --git a/src/Twilio/Converters/PrefixedCollapsibleMap.cs b/src/Twilio/Converters/PrefixedCollapsibleMap.cs
index 5ca7bb96a..c5e5cf09d 100644
--- a/src/Twilio/Converters/PrefixedCollapsibleMap.cs
+++ b/src/Twilio/Converters/PrefixedCollapsibleMap.cs
@@ -2,54 +2,54 @@
using System.Linq;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Flatten nested maps and give all entries a prefix
+ ///
+ public class PrefixedCollapsibleMap
+ {
+ private static Dictionary Flatten(
+ Dictionary dict,
+ Dictionary result,
+ List previous
+ )
+ {
+ foreach (var entry in dict)
+ {
+ var next = new List(previous) { entry.Key };
+
+ if (entry.Value.GetType() == typeof(Dictionary))
+ {
+ Flatten((Dictionary)entry.Value, result, next);
+ }
+ else
+ {
+ result.Add(string.Join(".", next.ToArray()), entry.Value.ToString());
+ }
+ }
+
+ return result;
+ }
+
///
- /// Flatten nested maps and give all entries a prefix
+ /// Flatten Dictionary separating nested keys with a .
///
- public class PrefixedCollapsibleMap
- {
- private static Dictionary Flatten(
- Dictionary dict,
- Dictionary result,
- List previous
- )
- {
- foreach (var entry in dict)
- {
- var next = new List(previous) { entry.Key };
-
- if (entry.Value.GetType() == typeof(Dictionary))
- {
- Flatten((Dictionary)entry.Value, result, next);
- }
- else
- {
- result.Add(string.Join(".", next.ToArray()), entry.Value.ToString());
- }
- }
-
- return result;
- }
-
- ///
- /// Flatten Dictionary separating nested keys with a .
- ///
- /// Dictionary to flatten
- /// Prefix to give all entries
- /// Flattened Dictionary
- public static Dictionary Serialize(
- Dictionary inputDict,
- string prefix
- )
- {
- if (inputDict == null || !inputDict.Any())
- {
- return new Dictionary();
- }
-
- var flattened = Flatten(inputDict, new Dictionary(), new List());
- return flattened.ToDictionary(entry => prefix + "." + entry.Key, entry => entry.Value);
- }
- }
+ /// Dictionary to flatten
+ /// Prefix to give all entries
+ /// Flattened Dictionary
+ public static Dictionary Serialize(
+ Dictionary inputDict,
+ string prefix
+ )
+ {
+ if (inputDict == null || !inputDict.Any())
+ {
+ return new Dictionary();
+ }
+
+ var flattened = Flatten(inputDict, new Dictionary(), new List());
+ return flattened.ToDictionary(entry => prefix + "." + entry.Key, entry => entry.Value);
+ }
+ }
}
diff --git a/src/Twilio/Converters/Promoter.cs b/src/Twilio/Converters/Promoter.cs
index 04d62ce8c..c675e7e14 100644
--- a/src/Twilio/Converters/Promoter.cs
+++ b/src/Twilio/Converters/Promoter.cs
@@ -2,31 +2,31 @@
using System.Collections.Generic;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Promote objects
+ ///
+ public class Promoter
+ {
///
- /// Promote objects
+ /// Convert a string URL to a Uri object
///
- public class Promoter
- {
- ///
- /// Convert a string URL to a Uri object
- ///
- /// URL to convert
- /// Converted Uri
- public static Uri UriFromString(string url)
- {
- return new Uri(url);
- }
-
- ///
- /// Promote a single entry to a List of one
- ///
- /// single entry to promote
- /// List of the single object
- public static List ListOfOne(T one)
- {
- return new List {one};
- }
- }
+ /// URL to convert
+ /// Converted Uri
+ public static Uri UriFromString(string url)
+ {
+ return new Uri(url);
+ }
+
+ ///
+ /// Promote a single entry to a List of one
+ ///
+ /// single entry to promote
+ /// List of the single object
+ public static List ListOfOne(T one)
+ {
+ return new List { one };
+ }
+ }
}
diff --git a/src/Twilio/Converters/Serializers.cs b/src/Twilio/Converters/Serializers.cs
index f5360c35d..23a7c78ac 100644
--- a/src/Twilio/Converters/Serializers.cs
+++ b/src/Twilio/Converters/Serializers.cs
@@ -3,49 +3,49 @@
using Newtonsoft.Json;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Serialization methods for various datatypes before making requests to the API
+ ///
+ public class Serializers
+ {
+
///
- /// Serialization methods for various datatypes before making requests to the API
+ /// Produce a json string from input if possible
///
- public class Serializers
- {
-
- ///
- /// Produce a json string from input if possible
- ///
- /// Object to serialize to json
- /// A json string
- public static string JsonObject(object input)
- {
- return (input is string) ? (string) input : JsonConvert.SerializeObject(input);
- }
-
- ///
- /// Produce a ISO 8601 UTC compatible string from input if possible
- ///
- /// DateTime instance to serialize to string
- /// A string
- public static string DateTimeIso8601(DateTime? input)
- {
- if (input == null) return null;
-
- return input.Value.ToString("yyyy-MM-ddTHH:mm:ssZ");
- }
-
- public static string Url(Uri input)
- {
- if (input == null)
- {
- return null;
- }
-
- string originalString = input.OriginalString;
- if (input is Types.EmptyUri && Types.EmptyUri.Uri.Equals(originalString))
- {
- return string.Empty;
- }
-
- return originalString;
- }
- }
+ /// Object to serialize to json
+ /// A json string
+ public static string JsonObject(object input)
+ {
+ return (input is string) ? (string)input : JsonConvert.SerializeObject(input);
+ }
+
+ ///
+ /// Produce a ISO 8601 UTC compatible string from input if possible
+ ///
+ /// DateTime instance to serialize to string
+ /// A string
+ public static string DateTimeIso8601(DateTime? input)
+ {
+ if (input == null) return null;
+
+ return input.Value.ToString("yyyy-MM-ddTHH:mm:ssZ");
+ }
+
+ public static string Url(Uri input)
+ {
+ if (input == null)
+ {
+ return null;
+ }
+
+ string originalString = input.OriginalString;
+ if (input is Types.EmptyUri && Types.EmptyUri.Uri.Equals(originalString))
+ {
+ return string.Empty;
+ }
+
+ return originalString;
+ }
+ }
}
diff --git a/src/Twilio/Converters/StringEnumConverter.cs b/src/Twilio/Converters/StringEnumConverter.cs
index deb44ac00..071650819 100644
--- a/src/Twilio/Converters/StringEnumConverter.cs
+++ b/src/Twilio/Converters/StringEnumConverter.cs
@@ -6,105 +6,105 @@
using Twilio.Types;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Converts between enums and strings
+ ///
+ public class StringEnumConverter : JsonConverter
+ {
///
- /// Converts between enums and strings
+ /// Writes value to a JsonWriter
///
- public class StringEnumConverter : JsonConverter
- {
- ///
- /// Writes value to a JsonWriter
- ///
- /// JsonWriter to use
- /// value to write
- /// unused
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- var t = JToken.FromObject(value.ToString());
- t.WriteTo(writer);
- }
-
- ///
- /// Converts string to an enum
- ///
- /// JsonReader to read from
- /// unused
- /// unused
- /// unused
- /// Converted object
- public override object ReadJson(
- JsonReader reader,
- Type objectType,
- object existingValue,
- JsonSerializer serializer
- )
- {
- if (reader.Value == null)
- {
- // Value is null for 'Null' tokens and 'StartArray' tokens. If it's the former, stop now!
- if (reader.TokenType == JsonToken.Null)
- {
- return null;
- }
+ /// JsonWriter to use
+ /// value to write
+ /// unused
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ var t = JToken.FromObject(value.ToString());
+ t.WriteTo(writer);
+ }
+
+ ///
+ /// Converts string to an enum
+ ///
+ /// JsonReader to read from
+ /// unused
+ /// unused
+ /// unused
+ /// Converted object
+ public override object ReadJson(
+ JsonReader reader,
+ Type objectType,
+ object existingValue,
+ JsonSerializer serializer
+ )
+ {
+ if (reader.Value == null)
+ {
+ // Value is null for 'Null' tokens and 'StartArray' tokens. If it's the former, stop now!
+ if (reader.TokenType == JsonToken.Null)
+ {
+ return null;
+ }
#if !NET35
- if (objectType.GenericTypeArguments.Length == 0)
+ if (objectType.GenericTypeArguments.Length == 0)
#else
if (objectType.GetGenericArguments().Length == 0)
#endif
- {
- return null;
- }
- var constructedListType = MakeGenericType(objectType);
- var results = (IList) Activator.CreateInstance(constructedListType);
- reader.Read();
-
- while (reader.Value != null)
- {
- var e = CreateEnum(objectType);
- e.FromString(reader.Value as string);
- results.Add(e);
- reader.Read();
- }
-
- return results;
- }
-
- var instance = (StringEnum) Activator.CreateInstance(objectType);
- instance.FromString(reader.Value as string);
-
- return instance;
- }
-
- ///
- /// Determines if an object can be converted
- ///
- /// Object type to convert
- /// true if it can be converted; false otherwise
- public override bool CanConvert(Type objectType)
- {
- return objectType == typeof(Enum);
- }
-
- private static Type MakeGenericType(Type objectType)
- {
- var listType = typeof(List<>);
-
+ {
+ return null;
+ }
+ var constructedListType = MakeGenericType(objectType);
+ var results = (IList)Activator.CreateInstance(constructedListType);
+ reader.Read();
+
+ while (reader.Value != null)
+ {
+ var e = CreateEnum(objectType);
+ e.FromString(reader.Value as string);
+ results.Add(e);
+ reader.Read();
+ }
+
+ return results;
+ }
+
+ var instance = (StringEnum)Activator.CreateInstance(objectType);
+ instance.FromString(reader.Value as string);
+
+ return instance;
+ }
+
+ ///
+ /// Determines if an object can be converted
+ ///
+ /// Object type to convert
+ /// true if it can be converted; false otherwise
+ public override bool CanConvert(Type objectType)
+ {
+ return objectType == typeof(Enum);
+ }
+
+ private static Type MakeGenericType(Type objectType)
+ {
+ var listType = typeof(List<>);
+
#if !NET35
- return listType.MakeGenericType(objectType.GenericTypeArguments[0]);
+ return listType.MakeGenericType(objectType.GenericTypeArguments[0]);
#else
return listType.MakeGenericType(objectType.GetGenericArguments()[0]);
#endif
- }
-
- private static StringEnum CreateEnum(Type objectType)
- {
+ }
+
+ private static StringEnum CreateEnum(Type objectType)
+ {
#if !NET35
- return (StringEnum) Activator.CreateInstance(objectType.GenericTypeArguments[0]);
+ return (StringEnum)Activator.CreateInstance(objectType.GenericTypeArguments[0]);
#else
return (StringEnum) Activator.CreateInstance(objectType.GetGenericArguments()[0]);
#endif
- }
- }
+ }
+ }
}
diff --git a/src/Twilio/Converters/TwimlConverter.cs b/src/Twilio/Converters/TwimlConverter.cs
index b99b8a154..38a1613d5 100644
--- a/src/Twilio/Converters/TwimlConverter.cs
+++ b/src/Twilio/Converters/TwimlConverter.cs
@@ -3,50 +3,50 @@
using Newtonsoft.Json.Linq;
namespace Twilio.Converters
-{
+{
+ ///
+ /// Convert between strings and a Twiml
+ ///
+ public class TwimlConverter : JsonConverter
+ {
///
- /// Convert between strings and a Twiml
+ /// Write value to JsonWriter
///
- public class TwimlConverter : JsonConverter
- {
- ///
- /// Write value to JsonWriter
- ///
- /// Writer to write to
- /// Value to write
- /// unused
- public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
- {
- var t = JToken.FromObject(value.ToString());
- t.WriteTo(writer);
- }
-
- ///
- /// Convert a string to a Twiml
- ///
- /// JsonReader to read from
- /// unused
- /// unused
- /// unused
- /// Converted Twiml
- public override object ReadJson(
- JsonReader reader,
- Type objectType,
- object existingValue,
- JsonSerializer serializer
- )
- {
- return new Types.Twiml(reader.Value as string);
- }
-
- ///
- /// Determines if an object converted to a Twiml
- ///
- /// Type of object
- /// true if an object can be converted; false otherwise
- public override bool CanConvert(Type objectType)
- {
- return objectType == typeof(Enum);
- }
- }
+ /// Writer to write to
+ /// Value to write
+ /// unused
+ public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
+ {
+ var t = JToken.FromObject(value.ToString());
+ t.WriteTo(writer);
+ }
+
+ ///
+ /// Convert a string to a Twiml
+ ///
+ /// JsonReader to read from
+ /// unused
+ /// unused
+ /// unused
+ /// Converted Twiml
+ public override object ReadJson(
+ JsonReader reader,
+ Type objectType,
+ object existingValue,
+ JsonSerializer serializer
+ )
+ {
+ return new Types.Twiml(reader.Value as string);
+ }
+
+ ///
+ /// Determines if an object converted to a Twiml
+ ///
+ /// Type of object
+ /// true if an object can be converted; false otherwise
+ public override bool CanConvert(Type objectType)
+ {
+ return objectType == typeof(Enum);
+ }
+ }
}
diff --git a/src/Twilio/Exceptions/ApiException.cs b/src/Twilio/Exceptions/ApiException.cs
index e9433dead..348ed4a46 100644
--- a/src/Twilio/Exceptions/ApiException.cs
+++ b/src/Twilio/Exceptions/ApiException.cs
@@ -2,67 +2,67 @@
using System.Collections.Generic;
namespace Twilio.Exceptions
-{
+{
+ ///
+ /// POCO to represent an API Exception
+ ///
+ public class ApiException : TwilioException
+ {
///
- /// POCO to represent an API Exception
+ /// Twilio error code
///
- public class ApiException : TwilioException
- {
- ///
- /// Twilio error code
- ///
- public int Code { get; }
-
- ///
- /// HTTP status code
- ///
- public int Status { get; }
-
- ///
- /// More info if any was provided
- ///
- public string MoreInfo { get; }
-
- ///
- /// Any more details about the error, if any were provided
- ///
- public Dictionary Details { get; }
-
- ///
- /// Create a ApiException with message
- ///
- /// Exception message
- public ApiException(string message) : base(message) {}
-
- ///
- /// Create an ApiException from another Exception
- ///
- /// Exception message
- /// Exception to copy detatils from
- public ApiException(string message, Exception exception) : base(message, exception) {}
-
- ///
- /// Create an ApiException
- ///
- /// Twilio error code
- /// HTTP status code
- /// Error message
- /// More info if provided
- /// Details if provided
- /// Original exception
- public ApiException(
- int code,
- int status,
- string message,
- string moreInfo,
- Dictionary details = null,
- Exception exception = null
- ) : base(message, exception)
- {
- Code = code;
- Status = status;
- MoreInfo = moreInfo;
- Details = details;
- }
- }
+ public int Code { get; }
+
+ ///
+ /// HTTP status code
+ ///
+ public int Status { get; }
+
+ ///
+ /// More info if any was provided
+ ///
+ public string MoreInfo { get; }
+
+ ///
+ /// Any more details about the error, if any were provided
+ ///
+ public Dictionary Details { get; }
+
+ ///
+ /// Create a ApiException with message
+ ///
+ /// Exception message
+ public ApiException(string message) : base(message) { }
+
+ ///
+ /// Create an ApiException from another Exception
+ ///
+ /// Exception message
+ /// Exception to copy detatils from
+ public ApiException(string message, Exception exception) : base(message, exception) { }
+
+ ///
+ /// Create an ApiException
+ ///
+ /// Twilio error code
+ /// HTTP status code
+ /// Error message
+ /// More info if provided
+ /// Details if provided
+ /// Original exception
+ public ApiException(
+ int code,
+ int status,
+ string message,
+ string moreInfo,
+ Dictionary details = null,
+ Exception exception = null
+ ) : base(message, exception)
+ {
+ Code = code;
+ Status = status;
+ MoreInfo = moreInfo;
+ Details = details;
+ }
+ }
}
diff --git a/src/Twilio/Exceptions/CertificateValidationException.cs b/src/Twilio/Exceptions/CertificateValidationException.cs
index f966384a5..0e0c0c028 100644
--- a/src/Twilio/Exceptions/CertificateValidationException.cs
+++ b/src/Twilio/Exceptions/CertificateValidationException.cs
@@ -2,45 +2,45 @@
using Twilio.Http;
namespace Twilio.Exceptions
-{
+{
+ ///
+ /// Error thrown specifically when validating SSL connection
+ ///
+ public class CertificateValidationException : TwilioException
+ {
///
- /// Error thrown specifically when validating SSL connection
+ /// Request object that triggered the exception
///
- public class CertificateValidationException : TwilioException
- {
- ///
- /// Request object that triggered the exception
- ///
- public Request Request { get; }
-
- ///
- /// Response object that triggered the exception, if available
- ///
- public Response Response { get; }
-
- ///
- /// Construct a CertificateValidationException
- ///
- /// Error message
- /// The Request that triggered the exception
- /// The Response (if available) that triggered the exception
- public CertificateValidationException(string message, Request request, Response response)
- : base(message)
- {
- Request = request;
- Response = response;
- }
-
- ///
- /// Construct a CertificateValidationException
- ///
- /// Error message
- /// The parent exception
- /// The Request that triggered the exception
- public CertificateValidationException(string message, Exception exception, Request request)
- : base(message, exception)
- {
- Request = request;
- }
- }
+ public Request Request { get; }
+
+ ///
+ /// Response object that triggered the exception, if available
+ ///
+ public Response Response { get; }
+
+ ///
+ /// Construct a CertificateValidationException
+ ///
+ /// Error message
+ /// The Request that triggered the exception
+ /// The Response (if available) that triggered the exception
+ public CertificateValidationException(string message, Request request, Response response)
+ : base(message)
+ {
+ Request = request;
+ Response = response;
+ }
+
+ ///
+ /// Construct a CertificateValidationException
+ ///
+ /// Error message
+ /// The parent exception
+ /// The Request that triggered the exception
+ public CertificateValidationException(string message, Exception exception, Request request)
+ : base(message, exception)
+ {
+ Request = request;
+ }
+ }
}
diff --git a/src/Twilio/Exceptions/RestException.cs b/src/Twilio/Exceptions/RestException.cs
index af6b5942b..8c12b285b 100644
--- a/src/Twilio/Exceptions/RestException.cs
+++ b/src/Twilio/Exceptions/RestException.cs
@@ -2,83 +2,85 @@
using System.Collections.Generic;
namespace Twilio.Exceptions
-{
+{
+ ///
+ /// Exception from Twilio API
+ ///
+ [JsonObject(MemberSerialization.OptIn)]
+ public class RestException : TwilioException
+ {
///
- /// Exception from Twilio API
+ /// Twilio error code
///
- [JsonObject(MemberSerialization.OptIn)]
- public class RestException : TwilioException
- {
- ///
- /// Twilio error code
- ///
- [JsonProperty("code")]
- public int Code { get; private set; }
-
- ///
- /// HTTP status code
- ///
+ [JsonProperty("code")]
+ public int Code { get; private set; }
+
+ ///
+ /// HTTP status code
+ ///
+ [JsonProperty("status")]
+ public int Status { get; private set; }
+
+ ///
+ /// Error message
+ ///
+ public override string Message
+ {
+ get
+ {
+ return _message;
+ }
+ }
+
+ [JsonProperty("message")]
+ private string _message
+ {
+ get; set;
+ }
+
+ ///
+ /// More info if provided
+ ///
+ [JsonProperty("more_info")]
+ public string MoreInfo { get; private set; }
+
+ ///
+ /// Details if provided
+ ///
+ [JsonProperty("details")]
+ public Dictionary Details { get; private set; }
+
+ ///
+ /// Create an empty RestException
+ ///
+ public RestException() { }
+ private RestException(
[JsonProperty("status")]
- public int Status { get; private set; }
-
- ///
- /// Error message
- ///
- public override string Message {
- get
- {
- return _message;
- }
- }
-
+ int status,
[JsonProperty("message")]
- private string _message
- {
- get; set;
- }
-
- ///
- /// More info if provided
- ///
+ string message,
+ [JsonProperty("code")]
+ int code,
[JsonProperty("more_info")]
- public string MoreInfo { get; private set; }
-
- ///
- /// Details if provided
- ///
+ string moreInfo,
[JsonProperty("details")]
- public Dictionary Details { get; private set; }
-
- ///
- /// Create an empty RestException
- ///
- public RestException() {}
- private RestException(
- [JsonProperty("status")]
- int status,
- [JsonProperty("message")]
- string message,
- [JsonProperty("code")]
- int code,
- [JsonProperty("more_info")]
- string moreInfo,
- [JsonProperty("details")]
- Dictionary details
- ) {
- Status = status;
- Code = code;
- _message = message;
- MoreInfo = moreInfo;
- Details = details;
- }
-
- ///
- /// Create a RestException from a JSON payload
- ///
- /// JSON string to parse
- public static RestException FromJson(string json)
- {
- return JsonConvert.DeserializeObject(json);
- }
- }
+ Dictionary details
+ )
+ {
+ Status = status;
+ Code = code;
+ _message = message;
+ MoreInfo = moreInfo;
+ Details = details;
+ }
+
+ ///
+ /// Create a RestException from a JSON payload
+ ///
+ /// JSON string to parse
+ public static RestException FromJson(string json)
+ {
+ return JsonConvert.DeserializeObject(json);
+ }
+ }
}
diff --git a/src/Twilio/Exceptions/TwilioException.cs b/src/Twilio/Exceptions/TwilioException.cs
index 0693d62a2..3dd41a86a 100644
--- a/src/Twilio/Exceptions/TwilioException.cs
+++ b/src/Twilio/Exceptions/TwilioException.cs
@@ -1,60 +1,60 @@
using System;
namespace Twilio.Exceptions
-{
+{
+ ///
+ /// Base TwilioException
+ ///
+ public class TwilioException : Exception
+ {
///
- /// Base TwilioException
+ /// Create an empty TwilioException
///
- public class TwilioException : Exception
- {
- ///
- /// Create an empty TwilioException
- ///
- public TwilioException() {}
-
- ///
- /// Create a TwilioException from an error message
- ///
- /// Error message
- public TwilioException (string message) : base(message) {}
-
- ///
- /// Create a TwilioException from message and another exception
- ///
- /// Error message
- /// Original Exception
- public TwilioException(string message, Exception exception) : base(message, exception) {}
- }
-
+ public TwilioException() { }
+
///
- /// Exception related to connection errors
+ /// Create a TwilioException from an error message
///
- public class ApiConnectionException : TwilioException
- {
- ///
- /// Create an ApiConnectionException from a message
- ///
- /// Error message
- public ApiConnectionException(string message) : base(message) {}
-
- ///
- /// Create an ApiConnectionException from a message and another Exception
- ///
- /// Error message
- /// Original Exception
- public ApiConnectionException(string message, Exception exception) : base(message, exception) {}
- }
-
+ /// Error message
+ public TwilioException(string message) : base(message) { }
+
+ ///
+ /// Create a TwilioException from message and another exception
+ ///
+ /// Error message
+ /// Original Exception
+ public TwilioException(string message, Exception exception) : base(message, exception) { }
+ }
+
+ ///
+ /// Exception related to connection errors
+ ///
+ public class ApiConnectionException : TwilioException
+ {
+ ///
+ /// Create an ApiConnectionException from a message
+ ///
+ /// Error message
+ public ApiConnectionException(string message) : base(message) { }
+
+ ///
+ /// Create an ApiConnectionException from a message and another Exception
+ ///
+ /// Error message
+ /// Original Exception
+ public ApiConnectionException(string message, Exception exception) : base(message, exception) { }
+ }
+
+ ///
+ /// Exception related to Authentication Errors
+ ///
+ public class AuthenticationException : TwilioException
+ {
///
- /// Exception related to Authentication Errors
+ /// Create AuthenticationException from an error messsage
///
- public class AuthenticationException : TwilioException
- {
- ///
- /// Create AuthenticationException from an error messsage
- ///
- /// Error message
- public AuthenticationException(string message) : base(message) {}
- }
+ /// Error message
+ public AuthenticationException(string message) : base(message) { }
+ }
}
diff --git a/src/Twilio/Http/HttpClient.cs b/src/Twilio/Http/HttpClient.cs
index 674ab133e..dd01c37d7 100644
--- a/src/Twilio/Http/HttpClient.cs
+++ b/src/Twilio/Http/HttpClient.cs
@@ -1,54 +1,54 @@
using System;
namespace Twilio.Http
-{
+{
+ ///
+ /// Base http client used to make Twilio requests
+ ///
+ public abstract class HttpClient
+ {
///
- /// Base http client used to make Twilio requests
+ /// The last request made by this client
///
- public abstract class HttpClient
- {
- ///
- /// The last request made by this client
- ///
- public Request LastRequest { get; protected set; }
-
- ///
- /// The last response received by this client
- ///
- public Response LastResponse { get; protected set; }
-
- ///
- /// Make a request to Twilio, returns non-2XX responses as well
- ///
- ///
- /// request to make
- /// throws exception on network or connection errors.
- /// response of the request
- public abstract Response MakeRequest(Request request);
-
+ public Request LastRequest { get; protected set; }
+
+ ///
+ /// The last response received by this client
+ ///
+ public Response LastResponse { get; protected set; }
+
+ ///
+ /// Make a request to Twilio, returns non-2XX responses as well
+ ///
+ ///
+ /// request to make
+ /// throws exception on network or connection errors.
+ /// response of the request
+ public abstract Response MakeRequest(Request request);
+
#if !NET35
- ///
- /// Make an async request to Twilio, returns non-2XX responses as well
- ///
- ///
- /// request to make
- /// throws exception on network or connection errors.
- /// response of the request
- public abstract System.Threading.Tasks.Task MakeRequestAsync(Request request);
+ ///
+ /// Make an async request to Twilio, returns non-2XX responses as well
+ ///
+ ///
+ /// request to make
+ /// throws exception on network or connection errors.
+ /// response of the request
+ public abstract System.Threading.Tasks.Task MakeRequestAsync(Request request);
#endif
-
- ///
- /// Set the authentication string for the request
- ///
- ///
- /// username of the request
- /// password of the request
- /// authentication string
- public string Authentication(string username, string password)
- {
- var credentials = username + ":" + password;
- var encoded = System.Text.Encoding.UTF8.GetBytes(credentials);
- return Convert.ToBase64String(encoded);
- }
- }
+
+ ///
+ /// Set the authentication string for the request
+ ///
+ ///
+ /// username of the request
+ /// password of the request
+ /// authentication string
+ public string Authentication(string username, string password)
+ {
+ var credentials = username + ":" + password;
+ var encoded = System.Text.Encoding.UTF8.GetBytes(credentials);
+ return Convert.ToBase64String(encoded);
+ }
+ }
}
diff --git a/src/Twilio/Http/HttpMethod.cs b/src/Twilio/Http/HttpMethod.cs
index ed4e23820..c60a76f68 100644
--- a/src/Twilio/Http/HttpMethod.cs
+++ b/src/Twilio/Http/HttpMethod.cs
@@ -1,93 +1,93 @@
namespace Twilio.Http
-{
+{
+ ///
+ /// Represents an HTTP Method
+ ///
+ public class HttpMethod
+ {
///
- /// Represents an HTTP Method
+ /// Constant for GET method
///
- public class HttpMethod
- {
- ///
- /// Constant for GET method
- ///
- public static readonly HttpMethod Get = new HttpMethod("GET");
-
- ///
- /// Constant for POST method
- ///
- public static readonly HttpMethod Post = new HttpMethod("POST");
-
- ///
- /// Constant for PUT method
- ///
- public static readonly HttpMethod Put = new HttpMethod("PUT");
-
- ///
- /// Constant for DELETE method
- ///
- public static readonly HttpMethod Delete = new HttpMethod("DELETE");
-
- private readonly string _value;
-
- ///
- /// Create a method from a string
- ///
- /// Method name
- public HttpMethod(string method)
- {
- _value = method.ToUpper();
- }
-
- ///
- /// Convert from string to HttpMethod
- ///
- /// value to convert
- public static implicit operator HttpMethod(string value)
- {
- return new HttpMethod(value);
- }
-
- ///
- /// Compare HttpMethod
- ///
- /// object to compare with
- /// true if the HttpMethod are equal; false otherwise
- public override bool Equals(object obj)
- {
- if (obj == null)
- {
- return false;
- }
-
- if (ReferenceEquals(this, obj))
- {
- return true;
- }
-
- if (obj.GetType() != typeof(HttpMethod))
- {
- return false;
- }
-
- var other = (HttpMethod)obj;
- return _value == other._value;
- }
-
- ///
- /// Get the hash code of the HttpMethod
- ///
- /// the hash code of the HttpMethod
- public override int GetHashCode()
- {
- unchecked { return _value?.GetHashCode () ?? 0; }
- }
-
- ///
- /// Get the string representation of the HttpMethod
- ///
- /// string representation of the HttpMethod
- public override string ToString()
- {
- return _value;
- }
- }
+ public static readonly HttpMethod Get = new HttpMethod("GET");
+
+ ///
+ /// Constant for POST method
+ ///
+ public static readonly HttpMethod Post = new HttpMethod("POST");
+
+ ///
+ /// Constant for PUT method
+ ///
+ public static readonly HttpMethod Put = new HttpMethod("PUT");
+
+ ///
+ /// Constant for DELETE method
+ ///
+ public static readonly HttpMethod Delete = new HttpMethod("DELETE");
+
+ private readonly string _value;
+
+ ///
+ /// Create a method from a string
+ ///
+ /// Method name
+ public HttpMethod(string method)
+ {
+ _value = method.ToUpper();
+ }
+
+ ///
+ /// Convert from string to HttpMethod
+ ///
+ /// value to convert
+ public static implicit operator HttpMethod(string value)
+ {
+ return new HttpMethod(value);
+ }
+
+ ///
+ /// Compare HttpMethod
+ ///
+ /// object to compare with
+ /// true if the HttpMethod are equal; false otherwise
+ public override bool Equals(object obj)
+ {
+ if (obj == null)
+ {
+ return false;
+ }
+
+ if (ReferenceEquals(this, obj))
+ {
+ return true;
+ }
+
+ if (obj.GetType() != typeof(HttpMethod))
+ {
+ return false;
+ }
+
+ var other = (HttpMethod)obj;
+ return _value == other._value;
+ }
+
+ ///
+ /// Get the hash code of the HttpMethod
+ ///
+ /// the hash code of the HttpMethod
+ public override int GetHashCode()
+ {
+ unchecked { return _value?.GetHashCode() ?? 0; }
+ }
+
+ ///
+ /// Get the string representation of the HttpMethod
+ ///
+ /// string representation of the HttpMethod
+ public override string ToString()
+ {
+ return _value;
+ }
+ }
}
diff --git a/src/Twilio/Http/Request.cs b/src/Twilio/Http/Request.cs
index 148572885..efa1bab5a 100644
--- a/src/Twilio/Http/Request.cs
+++ b/src/Twilio/Http/Request.cs
@@ -11,274 +11,274 @@
#endif
namespace Twilio.Http
-{
+{
+ ///
+ /// Twilio request object
+ ///
+ public class Request
+ {
+ private static readonly string DEFAULT_REGION = "us1";
+
///
- /// Twilio request object
+ /// HTTP Method
///
- public class Request
- {
- private static readonly string DEFAULT_REGION = "us1";
-
- ///
- /// HTTP Method
- ///
- public HttpMethod Method { get; }
-
- public Uri Uri { get; private set; }
-
- ///
- /// Auth username
- ///
- public string Username { get; set; }
-
- ///
- /// Auth password
- ///
- public string Password { get; set; }
-
- ///
- /// Twilio region
- ///
- public string Region { get; set; }
-
- ///
- /// Twilio edge
- ///
- public string Edge { get; set; }
-
- ///
- /// Query params
- ///
- public List> QueryParams { get; private set; }
-
- ///
- /// Post params
- ///
- public List> PostParams { get; private set; }
-
- ///
- /// Header params
- ///
- public List> HeaderParams { get; private set; }
-
- ///
- /// Create a new Twilio request
- ///
- /// HTTP Method
- /// Request URL
- public Request(HttpMethod method, string url)
- {
- Method = method;
- Uri = new Uri(url);
- QueryParams = new List>();
- PostParams = new List>();
- HeaderParams = new List>();
- }
-
- ///
- /// Create a new Twilio request
- ///
- /// HTTP method
- /// Twilio subdomain
- /// Request URI
- /// Twilio region
- /// Query parameters
- /// Post data
- /// Twilio edge
- /// Custom header data
- public Request(
- HttpMethod method,
- Domain domain,
- string uri,
- string region = null,
- List> queryParams = null,
- List> postParams = null,
- string edge = null,
- List> headerParams = null
- )
- {
- Method = method;
- Uri = new Uri("https://" + domain + ".twilio.com" + uri);
- Region = region;
- Edge = edge;
-
- QueryParams = queryParams ?? new List>();
- PostParams = postParams ?? new List>();
- HeaderParams = headerParams ?? new List>();
- }
-
- ///
- /// Construct the request URL
- ///
- /// Built URL including query parameters
- public Uri ConstructUrl()
- {
- var uri = buildUri();
- return QueryParams.Count > 0 ?
- new Uri(uri.AbsoluteUri + "?" + EncodeParameters(QueryParams)) :
- new Uri(uri.AbsoluteUri);
- }
-
- public Uri buildUri()
- {
- if (Region != null || Edge != null)
- {
- var uriBuilder = new UriBuilder(Uri);
- var pieces = uriBuilder.Host.Split('.');
- var product = pieces[0];
- var domain = String.Join(".", pieces.Skip(pieces.Length - 2).ToArray());
-
- var region = Region;
- var edge = Edge;
-
- if (pieces.Length == 4) // product.region.twilio.com
- {
- region = region ?? pieces[1];
- }
- else if (pieces.Length == 5) // product.edge.region.twilio.com
- {
- edge = edge ?? pieces[1];
- region = region ?? pieces[2];
- }
-
- if (edge != null && region == null)
- region = DEFAULT_REGION;
-
- string[] parts = { product, edge, region, domain };
-
- uriBuilder.Host = String.Join(".", Array.FindAll(parts, part => !string.IsNullOrEmpty(part)));
- return uriBuilder.Uri;
- }
-
- return Uri;
- }
-
- ///
- /// Set auth for the request
- ///
- /// Auth username
- /// Auth password
- public void SetAuth(string username, string password)
- {
- Username = username;
- Password = password;
- }
-
- private static string EncodeParameters(IEnumerable> data)
- {
- var result = "";
- var first = true;
- foreach (var pair in data)
- {
- if (first)
- {
- first = false;
- }
- else
- {
- result += "&";
- }
-
+ public HttpMethod Method { get; }
+
+ public Uri Uri { get; private set; }
+
+ ///
+ /// Auth username
+ ///
+ public string Username { get; set; }
+
+ ///
+ /// Auth password
+ ///
+ public string Password { get; set; }
+
+ ///
+ /// Twilio region
+ ///
+ public string Region { get; set; }
+
+ ///
+ /// Twilio edge
+ ///
+ public string Edge { get; set; }
+
+ ///
+ /// Query params
+ ///
+ public List> QueryParams { get; private set; }
+
+ ///
+ /// Post params
+ ///
+ public List> PostParams { get; private set; }
+
+ ///
+ /// Header params
+ ///
+ public List> HeaderParams { get; private set; }
+
+ ///
+ /// Create a new Twilio request
+ ///
+ /// HTTP Method
+ /// Request URL
+ public Request(HttpMethod method, string url)
+ {
+ Method = method;
+ Uri = new Uri(url);
+ QueryParams = new List>();
+ PostParams = new List>();
+ HeaderParams = new List>();
+ }
+
+ ///
+ /// Create a new Twilio request
+ ///
+ /// HTTP method
+ /// Twilio subdomain
+ /// Request URI
+ /// Twilio region
+ /// Query parameters
+ /// Post data
+ /// Twilio edge
+ /// Custom header data
+ public Request(
+ HttpMethod method,
+ Domain domain,
+ string uri,
+ string region = null,
+ List> queryParams = null,
+ List> postParams = null,
+ string edge = null,
+ List> headerParams = null
+ )
+ {
+ Method = method;
+ Uri = new Uri("https://" + domain + ".twilio.com" + uri);
+ Region = region;
+ Edge = edge;
+
+ QueryParams = queryParams ?? new List>();
+ PostParams = postParams ?? new List>();
+ HeaderParams = headerParams ?? new List>();
+ }
+
+ ///
+ /// Construct the request URL
+ ///
+ /// Built URL including query parameters
+ public Uri ConstructUrl()
+ {
+ var uri = buildUri();
+ return QueryParams.Count > 0 ?
+ new Uri(uri.AbsoluteUri + "?" + EncodeParameters(QueryParams)) :
+ new Uri(uri.AbsoluteUri);
+ }
+
+ public Uri buildUri()
+ {
+ if (Region != null || Edge != null)
+ {
+ var uriBuilder = new UriBuilder(Uri);
+ var pieces = uriBuilder.Host.Split('.');
+ var product = pieces[0];
+ var domain = String.Join(".", pieces.Skip(pieces.Length - 2).ToArray());
+
+ var region = Region;
+ var edge = Edge;
+
+ if (pieces.Length == 4) // product.region.twilio.com
+ {
+ region = region ?? pieces[1];
+ }
+ else if (pieces.Length == 5) // product.edge.region.twilio.com
+ {
+ edge = edge ?? pieces[1];
+ region = region ?? pieces[2];
+ }
+
+ if (edge != null && region == null)
+ region = DEFAULT_REGION;
+
+ string[] parts = { product, edge, region, domain };
+
+ uriBuilder.Host = String.Join(".", Array.FindAll(parts, part => !string.IsNullOrEmpty(part)));
+ return uriBuilder.Uri;
+ }
+
+ return Uri;
+ }
+
+ ///
+ /// Set auth for the request
+ ///
+ /// Auth username
+ /// Auth password
+ public void SetAuth(string username, string password)
+ {
+ Username = username;
+ Password = password;
+ }
+
+ private static string EncodeParameters(IEnumerable> data)
+ {
+ var result = "";
+ var first = true;
+ foreach (var pair in data)
+ {
+ if (first)
+ {
+ first = false;
+ }
+ else
+ {
+ result += "&";
+ }
+
#if !NET35
- result += WebUtility.UrlEncode(pair.Key) + "=" + WebUtility.UrlEncode(pair.Value);
+ result += WebUtility.UrlEncode(pair.Key) + "=" + WebUtility.UrlEncode(pair.Value);
#else
result += HttpUtility.UrlEncode(pair.Key) + "=" + HttpUtility.UrlEncode(pair.Value);
#endif
- }
-
- return result;
- }
-
- ///
- /// Encode POST data for transfer
- ///
- /// Encoded byte array
- public byte[] EncodePostParams()
- {
- return Encoding.UTF8.GetBytes(EncodeParameters(PostParams));
- }
-
- ///
- /// Add query parameter to request
- ///
- /// name of parameter
- /// value of parameter
- public void AddQueryParam(string name, string value)
- {
- AddParam(QueryParams, name, value);
- }
-
- ///
- /// Add a parameter to the request payload
- ///
- /// name of parameter
- /// value of parameter
- public void AddPostParam(string name, string value)
- {
- AddParam(PostParams, name, value);
- }
-
- ///
- /// Add a header parameter
- ///
- /// name of parameter
- /// value of parameter
- public void AddHeaderParam(string name, string value)
- {
- AddParam(HeaderParams, name, value);
- }
-
- private static void AddParam(ICollection> list, string name, string value)
- {
- list.Add(new KeyValuePair(name, value));
- }
-
- ///
- /// Compare request
- ///
- /// object to compare to
- /// true if requests are equal; false otherwise
- public override bool Equals(object obj)
- {
- if (obj == null)
- {
- return false;
- }
-
- if (ReferenceEquals(this, obj))
- {
- return true;
- }
- if (obj.GetType() != typeof(Request))
- {
- return false;
- }
-
- var other = (Request)obj;
- return Method.Equals(other.Method) &&
- buildUri().Equals(other.buildUri()) &&
- QueryParams.All(other.QueryParams.Contains) &&
- other.QueryParams.All(QueryParams.Contains) &&
- PostParams.All(other.PostParams.Contains) &&
- other.PostParams.All(PostParams.Contains) &&
- HeaderParams.All(other.HeaderParams.Contains) &&
- other.HeaderParams.All(HeaderParams.Contains);
- }
-
- ///
- /// Generate hash code for request
- ///
- /// generated hash code
- public override int GetHashCode()
- {
- unchecked
- {
- return (Method?.GetHashCode() ?? 0) ^
- (buildUri()?.GetHashCode() ?? 0) ^
- (QueryParams?.GetHashCode() ?? 0) ^
- (PostParams?.GetHashCode() ?? 0) ^
- (HeaderParams?.GetHashCode() ?? 0);
- }
- }
- }
+ }
+
+ return result;
+ }
+
+ ///
+ /// Encode POST data for transfer
+ ///
+ /// Encoded byte array
+ public byte[] EncodePostParams()
+ {
+ return Encoding.UTF8.GetBytes(EncodeParameters(PostParams));
+ }
+
+ ///
+ /// Add query parameter to request
+ ///
+ /// name of parameter
+ /// value of parameter
+ public void AddQueryParam(string name, string value)
+ {
+ AddParam(QueryParams, name, value);
+ }
+
+ ///
+ /// Add a parameter to the request payload
+ ///
+ /// name of parameter
+ /// value of parameter
+ public void AddPostParam(string name, string value)
+ {
+ AddParam(PostParams, name, value);
+ }
+
+ ///
+ /// Add a header parameter
+ ///
+ /// name of parameter
+ /// value of parameter
+ public void AddHeaderParam(string name, string value)
+ {
+ AddParam(HeaderParams, name, value);
+ }
+
+ private static void AddParam(ICollection> list, string name, string value)
+ {
+ list.Add(new KeyValuePair(name, value));
+ }
+
+ ///
+ /// Compare request
+ ///
+ /// object to compare to
+ /// true if requests are equal; false otherwise
+ public override bool Equals(object obj)
+ {
+ if (obj == null)
+ {
+ return false;
+ }
+
+ if (ReferenceEquals(this, obj))
+ {
+ return true;
+ }
+ if (obj.GetType() != typeof(Request))
+ {
+ return false;
+ }
+
+ var other = (Request)obj;
+ return Method.Equals(other.Method) &&
+ buildUri().Equals(other.buildUri()) &&
+ QueryParams.All(other.QueryParams.Contains) &&
+ other.QueryParams.All(QueryParams.Contains) &&
+ PostParams.All(other.PostParams.Contains) &&
+ other.PostParams.All(PostParams.Contains) &&
+ HeaderParams.All(other.HeaderParams.Contains) &&
+ other.HeaderParams.All(HeaderParams.Contains);
+ }
+
+ ///
+ /// Generate hash code for request
+ ///
+ /// generated hash code
+ public override int GetHashCode()
+ {
+ unchecked
+ {
+ return (Method?.GetHashCode() ?? 0) ^
+ (buildUri()?.GetHashCode() ?? 0) ^
+ (QueryParams?.GetHashCode() ?? 0) ^
+ (PostParams?.GetHashCode() ?? 0) ^
+ (HeaderParams?.GetHashCode() ?? 0);
+ }
+ }
+ }
}
diff --git a/src/Twilio/Http/Response.cs b/src/Twilio/Http/Response.cs
index 4e19fef1e..dca9d6ff3 100644
--- a/src/Twilio/Http/Response.cs
+++ b/src/Twilio/Http/Response.cs
@@ -7,38 +7,38 @@
#endif
namespace Twilio.Http
-{
+{
+ ///
+ /// Twilio response
+ ///
+ public class Response
+ {
///
- /// Twilio response
+ /// HTTP status code
///
- public class Response
- {
- ///
- /// HTTP status code
- ///
- public HttpStatusCode StatusCode { get; }
-
- ///
- /// Content string
- ///
- public string Content { get; }
-
- ///
- /// Headers
- ///
- public Headers Headers { get; }
-
- ///
- /// Create a new Response
- ///
- /// HTTP status code
- /// Content string
- /// Headers
- public Response(HttpStatusCode statusCode, string content, Headers headers = null)
- {
- StatusCode = statusCode;
- Content = content;
- Headers = headers;
- }
- }
+ public HttpStatusCode StatusCode { get; }
+
+ ///
+ /// Content string
+ ///
+ public string Content { get; }
+
+ ///
+ /// Headers
+ ///
+ public Headers Headers { get; }
+
+ ///
+ /// Create a new Response
+ ///
+ /// HTTP status code
+ /// Content string
+ /// Headers
+ public Response(HttpStatusCode statusCode, string content, Headers headers = null)
+ {
+ StatusCode = statusCode;
+ Content = content;
+ Headers = headers;
+ }
+ }
}
diff --git a/src/Twilio/Http/SystemNetHttpClient.cs b/src/Twilio/Http/SystemNetHttpClient.cs
index 724d4fb62..56251c84c 100644
--- a/src/Twilio/Http/SystemNetHttpClient.cs
+++ b/src/Twilio/Http/SystemNetHttpClient.cs
@@ -1,106 +1,106 @@
-#if !NET35
-using System;
-using System.IO;
-using System.Net.Http;
-using System.Net.Http.Headers;
-using System.Threading.Tasks;
-using System.Runtime.InteropServices;
-
-namespace Twilio.Http
-{
- ///
- /// Sample client to make HTTP requests
- ///
- public class SystemNetHttpClient : HttpClient
- {
-#if NET451
- private string PlatVersion = " (.NET Framework 4.5.1+)";
-#else
- private string PlatVersion = $" ({RuntimeInformation.FrameworkDescription})";
-#endif
-
- private readonly System.Net.Http.HttpClient _httpClient;
-
- ///
- /// Create new HttpClient
- ///
- /// HTTP client to use
- public SystemNetHttpClient(System.Net.Http.HttpClient httpClient = null)
- {
- _httpClient = httpClient ?? new System.Net.Http.HttpClient(new HttpClientHandler() { AllowAutoRedirect = false });
- }
-
- ///
- /// Make a synchronous request
- ///
- /// Twilio request
- /// Twilio response
- public override Response MakeRequest(Request request)
- {
- try
- {
- var task = MakeRequestAsync(request);
- task.Wait();
- return task.Result;
- }
- catch (AggregateException ae)
- {
- // Combine nested AggregateExceptions
- ae = ae.Flatten();
- throw ae.InnerExceptions[0];
- }
- }
-
- ///
- /// Make an asynchronous request
- ///
- /// Twilio response
- /// Task that resolves to the response
- public override async Task MakeRequestAsync(Request request)
- {
- var httpRequest = BuildHttpRequest(request);
- if (!Equals(request.Method, HttpMethod.Get))
- {
- httpRequest.Content = new FormUrlEncodedContent(request.PostParams);
- }
-
- this.LastRequest = request;
- this.LastResponse = null;
-
- var httpResponse = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false);
- var reader = new StreamReader(await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false));
-
- // Create and return a new Response. Keep a reference to the last
- // response for debugging, but don't return it as it may be shared
- // among threads.
- var response = new Response(httpResponse.StatusCode, await reader.ReadToEndAsync().ConfigureAwait(false), httpResponse.Headers);
- this.LastResponse = response;
- return response;
- }
-
- private HttpRequestMessage BuildHttpRequest(Request request)
- {
- var httpRequest = new HttpRequestMessage(
- new System.Net.Http.HttpMethod(request.Method.ToString()),
- request.ConstructUrl()
- );
-
- var authBytes = Authentication(request.Username, request.Password);
- httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authBytes);
-
- httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
-
- var libraryVersion = "twilio-csharp/" + AssemblyInfomation.AssemblyInformationalVersion + PlatVersion;
- httpRequest.Headers.TryAddWithoutValidation("User-Agent", libraryVersion);
-
- foreach (var header in request.HeaderParams)
- {
- httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
- }
-
- return httpRequest;
- }
- }
-}
-#endif
+#if !NET35
+using System;
+using System.IO;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Threading.Tasks;
+using System.Runtime.InteropServices;
+
+namespace Twilio.Http
+{
+ ///
+ /// Sample client to make HTTP requests
+ ///
+ public class SystemNetHttpClient : HttpClient
+ {
+#if NET451
+ private string PlatVersion = " (.NET Framework 4.5.1+)";
+#else
+ private string PlatVersion = $" ({RuntimeInformation.FrameworkDescription})";
+#endif
+
+ private readonly System.Net.Http.HttpClient _httpClient;
+
+ ///
+ /// Create new HttpClient
+ ///
+ /// HTTP client to use
+ public SystemNetHttpClient(System.Net.Http.HttpClient httpClient = null)
+ {
+ _httpClient = httpClient ?? new System.Net.Http.HttpClient(new HttpClientHandler() { AllowAutoRedirect = false });
+ }
+
+ ///
+ /// Make a synchronous request
+ ///
+ /// Twilio request
+ /// Twilio response
+ public override Response MakeRequest(Request request)
+ {
+ try
+ {
+ var task = MakeRequestAsync(request);
+ task.Wait();
+ return task.Result;
+ }
+ catch (AggregateException ae)
+ {
+ // Combine nested AggregateExceptions
+ ae = ae.Flatten();
+ throw ae.InnerExceptions[0];
+ }
+ }
+
+ ///
+ /// Make an asynchronous request
+ ///
+ /// Twilio response
+ /// Task that resolves to the response
+ public override async Task MakeRequestAsync(Request request)
+ {
+ var httpRequest = BuildHttpRequest(request);
+ if (!Equals(request.Method, HttpMethod.Get))
+ {
+ httpRequest.Content = new FormUrlEncodedContent(request.PostParams);
+ }
+
+ this.LastRequest = request;
+ this.LastResponse = null;
+
+ var httpResponse = await _httpClient.SendAsync(httpRequest).ConfigureAwait(false);
+ var reader = new StreamReader(await httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false));
+
+ // Create and return a new Response. Keep a reference to the last
+ // response for debugging, but don't return it as it may be shared
+ // among threads.
+ var response = new Response(httpResponse.StatusCode, await reader.ReadToEndAsync().ConfigureAwait(false), httpResponse.Headers);
+ this.LastResponse = response;
+ return response;
+ }
+
+ private HttpRequestMessage BuildHttpRequest(Request request)
+ {
+ var httpRequest = new HttpRequestMessage(
+ new System.Net.Http.HttpMethod(request.Method.ToString()),
+ request.ConstructUrl()
+ );
+
+ var authBytes = Authentication(request.Username, request.Password);
+ httpRequest.Headers.Authorization = new AuthenticationHeaderValue("Basic", authBytes);
+
+ httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));
+
+ var libraryVersion = "twilio-csharp/" + AssemblyInfomation.AssemblyInformationalVersion + PlatVersion;
+ httpRequest.Headers.TryAddWithoutValidation("User-Agent", libraryVersion);
+
+ foreach (var header in request.HeaderParams)
+ {
+ httpRequest.Headers.TryAddWithoutValidation(header.Key, header.Value);
+ }
+
+ return httpRequest;
+ }
+ }
+}
+#endif
diff --git a/src/Twilio/JWT/AccessToken/ChatGrant.cs b/src/Twilio/JWT/AccessToken/ChatGrant.cs
index bc3e57221..d7eb05817 100644
--- a/src/Twilio/JWT/AccessToken/ChatGrant.cs
+++ b/src/Twilio/JWT/AccessToken/ChatGrant.cs
@@ -1,76 +1,76 @@
using System.Collections.Generic;
namespace Twilio.Jwt.AccessToken
-{
+{
+ ///
+ /// Grant to use for Twilio Chat
+ ///
+ public class ChatGrant : IGrant
+ {
///
- /// Grant to use for Twilio Chat
+ /// Service SID
///
- public class ChatGrant : IGrant
- {
- ///
- /// Service SID
- ///
- public string ServiceSid { get; set; }
-
- ///
- /// Endpoint ID
- ///
- public string EndpointId { get; set; }
-
- ///
- /// Deployment role SID
- ///
- public string DeploymentRoleSid { get; set; }
-
- ///
- /// Push credential SID
- ///
- public string PushCredentialSid { get; set; }
-
- ///
- /// Get the grant name
- ///
- ///
- /// name of the grant
- public string Key
- {
- get
- {
- return "chat";
- }
- }
-
- ///
- /// Get the grant payload
- ///
- ///
- /// payload of the grant
- public object Payload
- {
- get
- {
- var payload = new Dictionary();
-
- if (ServiceSid != null)
- {
- payload.Add("service_sid", ServiceSid);
- }
- if (EndpointId != null)
- {
- payload.Add("endpoint_id", EndpointId);
- }
- if (DeploymentRoleSid != null)
- {
- payload.Add("deployment_role_sid", DeploymentRoleSid);
- }
- if (PushCredentialSid != null)
- {
- payload.Add("push_credential_sid", PushCredentialSid);
- }
-
- return payload;
- }
- }
-
- }
+ public string ServiceSid { get; set; }
+
+ ///
+ /// Endpoint ID
+ ///
+ public string EndpointId { get; set; }
+
+ ///
+ /// Deployment role SID
+ ///
+ public string DeploymentRoleSid { get; set; }
+
+ ///
+ /// Push credential SID
+ ///
+ public string PushCredentialSid { get; set; }
+
+ ///
+ /// Get the grant name
+ ///
+ ///
+ /// name of the grant
+ public string Key
+ {
+ get
+ {
+ return "chat";
+ }
+ }
+
+ ///
+ /// Get the grant payload
+ ///
+ ///
+ /// payload of the grant
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+
+ if (ServiceSid != null)
+ {
+ payload.Add("service_sid", ServiceSid);
+ }
+ if (EndpointId != null)
+ {
+ payload.Add("endpoint_id", EndpointId);
+ }
+ if (DeploymentRoleSid != null)
+ {
+ payload.Add("deployment_role_sid", DeploymentRoleSid);
+ }
+ if (PushCredentialSid != null)
+ {
+ payload.Add("push_credential_sid", PushCredentialSid);
+ }
+
+ return payload;
+ }
+ }
+
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/ConversationsGrant.cs b/src/Twilio/JWT/AccessToken/ConversationsGrant.cs
index 4f13c7784..aa6390eb2 100644
--- a/src/Twilio/JWT/AccessToken/ConversationsGrant.cs
+++ b/src/Twilio/JWT/AccessToken/ConversationsGrant.cs
@@ -2,47 +2,47 @@
namespace Twilio.Jwt.AccessToken
{
+ ///
+ /// Grant to use for Twilio Conversations
+ ///
+ [System.Obsolete("ConversationsGrant is deprecated, use VideoGrant instead")]
+ public class ConversationsGrant : IGrant
+ {
///
- /// Grant to use for Twilio Conversations
+ /// Configuration profile SID for the grant
///
- [System.Obsolete("ConversationsGrant is deprecated, use VideoGrant instead")]
- public class ConversationsGrant : IGrant
+ public string ConfigurationProfileSid { get; set; }
+
+ ///
+ /// Get the grant key
+ ///
+ ///
+ /// grant key
+ public string Key
{
- ///
- /// Configuration profile SID for the grant
- ///
- public string ConfigurationProfileSid { get; set; }
+ get
+ {
+ return "rtc";
+ }
+ }
- ///
- /// Get the grant key
- ///
- ///
- /// grant key
- public string Key
+ ///
+ /// Get the grant payload
+ ///
+ ///
+ /// grant payload
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+ if (ConfigurationProfileSid != null)
{
- get
- {
- return "rtc";
- }
+ payload.Add("configuration_profile_sid", ConfigurationProfileSid);
}
- ///
- /// Get the grant payload
- ///
- ///
- /// grant payload
- public object Payload
- {
- get
- {
- var payload = new Dictionary();
- if (ConfigurationProfileSid != null)
- {
- payload.Add("configuration_profile_sid", ConfigurationProfileSid);
- }
-
- return payload;
- }
- }
+ return payload;
+ }
}
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/IGrant.cs b/src/Twilio/JWT/AccessToken/IGrant.cs
index 179beac30..2644f03b7 100644
--- a/src/Twilio/JWT/AccessToken/IGrant.cs
+++ b/src/Twilio/JWT/AccessToken/IGrant.cs
@@ -1,22 +1,22 @@
namespace Twilio.Jwt.AccessToken
{
+ ///
+ /// Grant used in Access Tokens
+ ///
+ public interface IGrant
+ {
///
- /// Grant used in Access Tokens
+ /// Get the name of the grant.
///
- public interface IGrant
- {
- ///
- /// Get the name of the grant.
- ///
- ///
- /// String - the name of the grant
- string Key { get; }
+ ///
+ /// String - the name of the grant
+ string Key { get; }
- ///
- /// Get the data of the grant
- ///
- ///
- /// Object - the data of the grant
- object Payload { get; }
- }
+ ///
+ /// Get the data of the grant
+ ///
+ ///
+ /// Object - the data of the grant
+ object Payload { get; }
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/IpMessagingGrant.cs b/src/Twilio/JWT/AccessToken/IpMessagingGrant.cs
index 06b95fb78..7aac3fdb2 100644
--- a/src/Twilio/JWT/AccessToken/IpMessagingGrant.cs
+++ b/src/Twilio/JWT/AccessToken/IpMessagingGrant.cs
@@ -2,76 +2,76 @@
namespace Twilio.Jwt.AccessToken
{
+ ///
+ /// Grant to use for IP Messaging
+ ///
+ [System.Obsolete("IpMessagingGrant is deprecated, use ChatGrant instead")]
+ public class IpMessagingGrant : IGrant
+ {
///
- /// Grant to use for IP Messaging
+ /// Service SID
///
- [System.Obsolete("IpMessagingGrant is deprecated, use ChatGrant instead")]
- public class IpMessagingGrant : IGrant
+ public string ServiceSid { get; set; }
+
+ ///
+ /// Endpoint ID
+ ///
+ public string EndpointId { get; set; }
+
+ ///
+ /// Deployment role SID
+ ///
+ public string DeploymentRoleSid { get; set; }
+
+ ///
+ /// Push credential SID
+ ///
+ public string PushCredentialSid { get; set; }
+
+ ///
+ /// Get the grant name
+ ///
+ ///
+ /// name of the grant
+ public string Key
{
- ///
- /// Service SID
- ///
- public string ServiceSid { get; set; }
-
- ///
- /// Endpoint ID
- ///
- public string EndpointId { get; set; }
-
- ///
- /// Deployment role SID
- ///
- public string DeploymentRoleSid { get; set; }
-
- ///
- /// Push credential SID
- ///
- public string PushCredentialSid { get; set; }
+ get
+ {
+ return "ip_messaging";
+ }
+ }
- ///
- /// Get the grant name
- ///
- ///
- /// name of the grant
- public string Key
+ ///
+ /// Get the grant payload
+ ///
+ ///
+ /// payload of the grant
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+
+ if (ServiceSid != null)
{
- get
- {
- return "ip_messaging";
- }
+ payload.Add("service_sid", ServiceSid);
}
-
- ///
- /// Get the grant payload
- ///
- ///
- /// payload of the grant
- public object Payload
+ if (EndpointId != null)
{
- get
- {
- var payload = new Dictionary();
-
- if (ServiceSid != null)
- {
- payload.Add("service_sid", ServiceSid);
- }
- if (EndpointId != null)
- {
- payload.Add("endpoint_id", EndpointId);
- }
- if (DeploymentRoleSid != null)
- {
- payload.Add("deployment_role_sid", DeploymentRoleSid);
- }
- if (PushCredentialSid != null)
- {
- payload.Add("push_credential_sid", PushCredentialSid);
- }
-
- return payload;
- }
+ payload.Add("endpoint_id", EndpointId);
+ }
+ if (DeploymentRoleSid != null)
+ {
+ payload.Add("deployment_role_sid", DeploymentRoleSid);
+ }
+ if (PushCredentialSid != null)
+ {
+ payload.Add("push_credential_sid", PushCredentialSid);
}
+ return payload;
+ }
}
+
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/PlaybackGrant.cs b/src/Twilio/JWT/AccessToken/PlaybackGrant.cs
index 067beb400..5a7e7dc68 100644
--- a/src/Twilio/JWT/AccessToken/PlaybackGrant.cs
+++ b/src/Twilio/JWT/AccessToken/PlaybackGrant.cs
@@ -1,41 +1,41 @@
using System.Collections.Generic;
namespace Twilio.Jwt.AccessToken
-{
+{
+ ///
+ /// Grant to expose Twilio Live
+ ///
+ public class PlaybackGrant : IGrant
+ {
///
- /// Grant to expose Twilio Live
+ /// Grant payload
///
- public class PlaybackGrant : IGrant
- {
- ///
- /// Grant payload
- ///
- public Dictionary Grant { get; set; }
-
- ///
- /// Get the playback grant key
- ///
- ///
- /// the playback grant key
- public string Key
- {
- get
- {
- return "player";
- }
- }
-
- ///
- /// Get the playback grant payload
- ///
- ///
- /// the video grant payload
- public object Payload
- {
- get
- {
- return Grant;
- }
- }
- }
+ public Dictionary Grant { get; set; }
+
+ ///
+ /// Get the playback grant key
+ ///
+ ///
+ /// the playback grant key
+ public string Key
+ {
+ get
+ {
+ return "player";
+ }
+ }
+
+ ///
+ /// Get the playback grant payload
+ ///
+ ///
+ /// the video grant payload
+ public object Payload
+ {
+ get
+ {
+ return Grant;
+ }
+ }
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/SyncGrant.cs b/src/Twilio/JWT/AccessToken/SyncGrant.cs
index 81ab11ae1..47e9266fa 100755
--- a/src/Twilio/JWT/AccessToken/SyncGrant.cs
+++ b/src/Twilio/JWT/AccessToken/SyncGrant.cs
@@ -2,57 +2,57 @@
namespace Twilio.Jwt.AccessToken
{
+ ///
+ /// Grant for Twilio Sync
+ ///
+ public class SyncGrant : IGrant
+ {
///
- /// Grant for Twilio Sync
+ /// Sync service SID
///
- public class SyncGrant : IGrant
+ public string ServiceSid { get; set; }
+
+ ///
+ /// Endpoint ID
+ ///
+ public string EndpointId { get; set; }
+
+ ///
+ /// Get the grant key
+ ///
+ ///
+ /// the grant key
+ public string Key
{
- ///
- /// Sync service SID
- ///
- public string ServiceSid { get; set; }
-
- ///
- /// Endpoint ID
- ///
- public string EndpointId { get; set; }
+ get
+ {
+ return "data_sync";
+ }
+ }
- ///
- /// Get the grant key
- ///
- ///
- /// the grant key
- public string Key
+ ///
+ /// Get the grant payload
+ ///
+ ///
+ /// the grant payload
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+
+ if (ServiceSid != null)
{
- get
- {
- return "data_sync";
- }
+ payload.Add("service_sid", ServiceSid);
}
- ///
- /// Get the grant payload
- ///
- ///
- /// the grant payload
- public object Payload
+ if (EndpointId != null)
{
- get
- {
- var payload = new Dictionary();
-
- if (ServiceSid != null)
- {
- payload.Add("service_sid", ServiceSid);
- }
-
- if (EndpointId != null)
- {
- payload.Add("endpoint_id", EndpointId);
- }
-
- return payload;
- }
+ payload.Add("endpoint_id", EndpointId);
}
+
+ return payload;
+ }
}
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/Token.cs b/src/Twilio/JWT/AccessToken/Token.cs
index 0786ed39b..11372e9d6 100644
--- a/src/Twilio/JWT/AccessToken/Token.cs
+++ b/src/Twilio/JWT/AccessToken/Token.cs
@@ -2,137 +2,137 @@
using System.Collections.Generic;
namespace Twilio.Jwt.AccessToken
-{
+{
+ ///
+ /// Access Token for Twilio resources
+ ///
+ public class Token : BaseJwt
+ {
+ private readonly string _id;
+ private readonly string _accountSid;
+ private readonly string _identity;
+ private readonly DateTime? _nbf;
+ private readonly HashSet _grants;
+ private readonly string _region;
+
///
- /// Access Token for Twilio resources
+ /// Create a new Access Token
///
- public class Token : BaseJwt
- {
- private readonly string _id;
- private readonly string _accountSid;
- private readonly string _identity;
- private readonly DateTime? _nbf;
- private readonly HashSet _grants;
- private readonly string _region;
-
- ///
- /// Create a new Access Token
- ///
- /// Account SID
- /// Signing key SID
- /// Secret to encode with
- /// Token identity
- /// Token expiration
- /// Token nbf
- /// Token grants
- /// Token region
- public Token(
- string accountSid,
- string signingKeySid,
- string secret,
- string identity = null,
- DateTime? expiration = null,
- DateTime? nbf = null,
- HashSet grants = null,
- string region = null
- ) : base(secret, signingKeySid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
- {
- var now = BaseJwt.ConvertToUnixTimestamp(DateTime.UtcNow);
- this._id = signingKeySid + "-" + now;
- this._accountSid = accountSid;
- this._identity = identity;
- this._nbf = nbf;
- this._grants = grants;
- this._region = region;
- }
-
- ///
- /// Token ID
- ///
- public override string Id
- {
- get
- {
- return _id;
- }
- }
-
- ///
- /// Access token subject
- ///
- public override string Subject
- {
- get
- {
- return _accountSid;
- }
- }
-
- ///
- /// Token not before time
- ///
- public override DateTime? Nbf
- {
- get
- {
- return _nbf;
- }
- }
-
- ///
- /// The region associated with this account
- ///
- public string Region
- {
- get
- {
- return _region;
- }
- }
-
- ///
- /// Headers for an Access Token
- ///
- public override Dictionary Headers
- {
- get
- {
- var headers = new Dictionary { { "cty", "twilio-fpa;v=1" } };
-
- if (_region != null)
- {
- headers.Add("twr", _region);
- }
-
- return headers;
- }
- }
-
- ///
- /// Populate claims for the Access Token
- ///
- ///
- public override Dictionary Claims
- {
- get
- {
- var grants = new Dictionary();
- if (_identity != null)
- {
- grants.Add("identity", _identity);
- }
-
- if (_grants != null)
- {
- foreach (var grant in _grants)
- {
- grants.Add(grant.Key, grant.Payload);
- }
- }
-
- return new Dictionary { { "grants", grants } };
- }
- }
-
- }
+ /// Account SID
+ /// Signing key SID
+ /// Secret to encode with
+ /// Token identity
+ /// Token expiration
+ /// Token nbf
+ /// Token grants
+ /// Token region
+ public Token(
+ string accountSid,
+ string signingKeySid,
+ string secret,
+ string identity = null,
+ DateTime? expiration = null,
+ DateTime? nbf = null,
+ HashSet grants = null,
+ string region = null
+ ) : base(secret, signingKeySid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
+ {
+ var now = BaseJwt.ConvertToUnixTimestamp(DateTime.UtcNow);
+ this._id = signingKeySid + "-" + now;
+ this._accountSid = accountSid;
+ this._identity = identity;
+ this._nbf = nbf;
+ this._grants = grants;
+ this._region = region;
+ }
+
+ ///
+ /// Token ID
+ ///
+ public override string Id
+ {
+ get
+ {
+ return _id;
+ }
+ }
+
+ ///
+ /// Access token subject
+ ///
+ public override string Subject
+ {
+ get
+ {
+ return _accountSid;
+ }
+ }
+
+ ///
+ /// Token not before time
+ ///
+ public override DateTime? Nbf
+ {
+ get
+ {
+ return _nbf;
+ }
+ }
+
+ ///
+ /// The region associated with this account
+ ///
+ public string Region
+ {
+ get
+ {
+ return _region;
+ }
+ }
+
+ ///
+ /// Headers for an Access Token
+ ///
+ public override Dictionary Headers
+ {
+ get
+ {
+ var headers = new Dictionary { { "cty", "twilio-fpa;v=1" } };
+
+ if (_region != null)
+ {
+ headers.Add("twr", _region);
+ }
+
+ return headers;
+ }
+ }
+
+ ///
+ /// Populate claims for the Access Token
+ ///
+ ///
+ public override Dictionary Claims
+ {
+ get
+ {
+ var grants = new Dictionary();
+ if (_identity != null)
+ {
+ grants.Add("identity", _identity);
+ }
+
+ if (_grants != null)
+ {
+ foreach (var grant in _grants)
+ {
+ grants.Add(grant.Key, grant.Payload);
+ }
+ }
+
+ return new Dictionary { { "grants", grants } };
+ }
+ }
+
+ }
}
diff --git a/src/Twilio/JWT/AccessToken/VideoGrant.cs b/src/Twilio/JWT/AccessToken/VideoGrant.cs
index 75d64b755..d122df2ab 100644
--- a/src/Twilio/JWT/AccessToken/VideoGrant.cs
+++ b/src/Twilio/JWT/AccessToken/VideoGrant.cs
@@ -1,57 +1,57 @@
-using System.Collections.Generic;
-
-namespace Twilio.Jwt.AccessToken
-{
- ///
- /// Grant to expose Twilio Video
- ///
- public class VideoGrant : IGrant
- {
- ///
- /// Configuration profile SID
- ///
- [System.Obsolete("ConfigurationProfileSid is deprecated, use Room instead")]
- public string ConfigurationProfileSid { get; set; }
-
- ///
- /// Roome SID or name
- ///
- public string Room { get; set; }
-
- ///
- /// Get the Video grant key
- ///
- ///
- /// the video grant key
- public string Key
- {
- get
- {
- return "video";
- }
- }
-
- ///
- /// Get the video grant payload
- ///
- ///
- /// the video grant payload
- public object Payload
- {
- get
- {
- var payload = new Dictionary();
- if (ConfigurationProfileSid != null)
- {
- payload.Add("configuration_profile_sid", ConfigurationProfileSid);
- }
- if (Room != null)
- {
- payload.Add("room", Room);
- }
-
- return payload;
- }
- }
- }
-}
+using System.Collections.Generic;
+
+namespace Twilio.Jwt.AccessToken
+{
+ ///
+ /// Grant to expose Twilio Video
+ ///
+ public class VideoGrant : IGrant
+ {
+ ///
+ /// Configuration profile SID
+ ///
+ [System.Obsolete("ConfigurationProfileSid is deprecated, use Room instead")]
+ public string ConfigurationProfileSid { get; set; }
+
+ ///
+ /// Roome SID or name
+ ///
+ public string Room { get; set; }
+
+ ///
+ /// Get the Video grant key
+ ///
+ ///
+ /// the video grant key
+ public string Key
+ {
+ get
+ {
+ return "video";
+ }
+ }
+
+ ///
+ /// Get the video grant payload
+ ///
+ ///
+ /// the video grant payload
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+ if (ConfigurationProfileSid != null)
+ {
+ payload.Add("configuration_profile_sid", ConfigurationProfileSid);
+ }
+ if (Room != null)
+ {
+ payload.Add("room", Room);
+ }
+
+ return payload;
+ }
+ }
+ }
+}
diff --git a/src/Twilio/JWT/AccessToken/VoiceGrant.cs b/src/Twilio/JWT/AccessToken/VoiceGrant.cs
index 360c1bdbd..3a2e40c98 100644
--- a/src/Twilio/JWT/AccessToken/VoiceGrant.cs
+++ b/src/Twilio/JWT/AccessToken/VoiceGrant.cs
@@ -1,89 +1,89 @@
using System.Collections.Generic;
namespace Twilio.Jwt.AccessToken
-{
+{
+ ///
+ /// Grant to expose Twilio Voice
+ ///
+ public class VoiceGrant : IGrant
+ {
///
- /// Grant to expose Twilio Voice
+ /// Whether incoming connections are allowed (JS Client)
///
- public class VoiceGrant : IGrant
- {
- ///
- /// Whether incoming connections are allowed (JS Client)
- ///
- public bool IncomingAllow { get; set; }
-
- ///
- /// Outgoing application SID
- ///
- public string OutgoingApplicationSid { get; set; }
-
- ///
- /// Parameters to send to the outgoing application
- ///
- public Dictionary OutgoingApplicationParams { get; set; }
-
- ///
- /// Push credential SID
- ///
- public string PushCredentialSid { get; set; }
-
- ///
- /// Endpoint ID
- ///
- public string EndpointId { get; set; }
-
- ///
- /// Get the grant key
- ///
- ///
- /// the grant key
- public string Key
- {
- get
- {
- return "voice";
- }
- }
-
- ///
- /// Get the grant payload
- ///
- ///
- /// the grant payload
- public object Payload
- {
- get
- {
- var payload = new Dictionary();
- if (IncomingAllow == true)
- {
- var incoming = new Dictionary { { "allow", true } };
- payload.Add("incoming", incoming);
- }
-
- if (OutgoingApplicationSid != null)
- {
- var outgoing = new Dictionary { { "application_sid", OutgoingApplicationSid } };
- if (OutgoingApplicationParams != null)
- {
- outgoing.Add("params", OutgoingApplicationParams);
- }
-
- payload.Add("outgoing", outgoing);
- }
-
- if (PushCredentialSid != null)
- {
- payload.Add("push_credential_sid", PushCredentialSid);
- }
-
- if (EndpointId != null)
- {
- payload.Add("endpoint_id", EndpointId);
- }
-
- return payload;
- }
- }
- }
+ public bool IncomingAllow { get; set; }
+
+ ///
+ /// Outgoing application SID
+ ///
+ public string OutgoingApplicationSid { get; set; }
+
+ ///
+ /// Parameters to send to the outgoing application
+ ///
+ public Dictionary OutgoingApplicationParams { get; set; }
+
+ ///
+ /// Push credential SID
+ ///
+ public string PushCredentialSid { get; set; }
+
+ ///
+ /// Endpoint ID
+ ///
+ public string EndpointId { get; set; }
+
+ ///
+ /// Get the grant key
+ ///
+ ///
+ /// the grant key
+ public string Key
+ {
+ get
+ {
+ return "voice";
+ }
+ }
+
+ ///
+ /// Get the grant payload
+ ///
+ ///
+ /// the grant payload
+ public object Payload
+ {
+ get
+ {
+ var payload = new Dictionary();
+ if (IncomingAllow == true)
+ {
+ var incoming = new Dictionary { { "allow", true } };
+ payload.Add("incoming", incoming);
+ }
+
+ if (OutgoingApplicationSid != null)
+ {
+ var outgoing = new Dictionary { { "application_sid", OutgoingApplicationSid } };
+ if (OutgoingApplicationParams != null)
+ {
+ outgoing.Add("params", OutgoingApplicationParams);
+ }
+
+ payload.Add("outgoing", outgoing);
+ }
+
+ if (PushCredentialSid != null)
+ {
+ payload.Add("push_credential_sid", PushCredentialSid);
+ }
+
+ if (EndpointId != null)
+ {
+ payload.Add("endpoint_id", EndpointId);
+ }
+
+ return payload;
+ }
+ }
+ }
}
diff --git a/src/Twilio/JWT/Client/ClientCapability.cs b/src/Twilio/JWT/Client/ClientCapability.cs
index 1b264b803..233262289 100644
--- a/src/Twilio/JWT/Client/ClientCapability.cs
+++ b/src/Twilio/JWT/Client/ClientCapability.cs
@@ -2,63 +2,63 @@
using System.Collections.Generic;
namespace Twilio.Jwt
-{
+{
+ ///
+ /// JWT for Twilio Client
+ ///
+ public class ClientCapability : BaseJwt
+ {
+ private readonly HashSet _scopes;
+
///
- /// JWT for Twilio Client
+ /// Create a new Client JWT
///
- public class ClientCapability : BaseJwt
- {
- private readonly HashSet _scopes;
-
- ///
- /// Create a new Client JWT
- ///
- /// Twilio Account SID
- /// Twilio auth token
- /// JWT expiration
- /// Scopes to give access to
- public ClientCapability(
- string accountSid,
- string authToken,
- DateTime? expiration = null,
- HashSet scopes = null
- ) : base (authToken, accountSid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
- {
- this._scopes = scopes;
- }
-
- ///
- /// JWT headers
- ///
- public override Dictionary Headers
- {
- get
- {
- return new Dictionary();
- }
- }
-
- ///
- /// Get the JWT claims in JSON format
- ///
- public override Dictionary Claims
- {
- get
- {
- var claims = new Dictionary();
- if (_scopes != null)
- {
- var scopes = new List();
- foreach (var scope in _scopes)
- {
- scopes.Add(scope.Payload);
- }
-
- claims.Add("scope", String.Join(" ", scopes.ToArray()));
- }
-
- return claims;
- }
- }
- }
+ /// Twilio Account SID
+ /// Twilio auth token
+ /// JWT expiration
+ /// Scopes to give access to
+ public ClientCapability(
+ string accountSid,
+ string authToken,
+ DateTime? expiration = null,
+ HashSet scopes = null
+ ) : base(authToken, accountSid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
+ {
+ this._scopes = scopes;
+ }
+
+ ///
+ /// JWT headers
+ ///
+ public override Dictionary Headers
+ {
+ get
+ {
+ return new Dictionary();
+ }
+ }
+
+ ///
+ /// Get the JWT claims in JSON format
+ ///
+ public override Dictionary Claims
+ {
+ get
+ {
+ var claims = new Dictionary();
+ if (_scopes != null)
+ {
+ var scopes = new List();
+ foreach (var scope in _scopes)
+ {
+ scopes.Add(scope.Payload);
+ }
+
+ claims.Add("scope", String.Join(" ", scopes.ToArray()));
+ }
+
+ return claims;
+ }
+ }
+ }
}
diff --git a/src/Twilio/JWT/Client/EventStreamScope.cs b/src/Twilio/JWT/Client/EventStreamScope.cs
index 2b4987d8e..6016b5879 100644
--- a/src/Twilio/JWT/Client/EventStreamScope.cs
+++ b/src/Twilio/JWT/Client/EventStreamScope.cs
@@ -8,63 +8,63 @@
#endif
namespace Twilio.Jwt.Client
-{
+{
+ ///
+ /// Event stream scope for client capabilities
+ ///
+ public class EventStreamScope : IScope
+ {
+ private static readonly string Scope = "scope:stream:subscribe";
+
+ private readonly Dictionary _filters;
+
///
- /// Event stream scope for client capabilities
+ /// Create a new EventStreamScope
///
- public class EventStreamScope : IScope
- {
- private static readonly string Scope = "scope:stream:subscribe";
-
- private readonly Dictionary _filters;
-
- ///
- /// Create a new EventStreamScope
- ///
- /// filters to use
- public EventStreamScope(Dictionary filters = null)
- {
- this._filters = filters;
- }
-
- ///
- /// Generate scope payload
- ///
- public string Payload
- {
- get
- {
- var queryArgs = new List();
- queryArgs.Add("path=/2010-04-01/Events");
-
- if (_filters != null)
- {
- queryArgs.Add(BuildParameter("appParams", GetFilterParams()));
- }
-
- var queryString = String.Join("&", queryArgs.ToArray());
- return Scope + "?" + queryString;
- }
- }
-
- private string GetFilterParams()
- {
- var queryParams = new List();
- foreach (var entry in _filters)
- {
- queryParams.Add(BuildParameter(entry.Key, entry.Value));
- }
-
- return String.Join("&", queryParams.ToArray());
- }
-
- private string BuildParameter(string k, string v)
- {
+ /// filters to use
+ public EventStreamScope(Dictionary filters = null)
+ {
+ this._filters = filters;
+ }
+
+ ///
+ /// Generate scope payload
+ ///
+ public string Payload
+ {
+ get
+ {
+ var queryArgs = new List();
+ queryArgs.Add("path=/2010-04-01/Events");
+
+ if (_filters != null)
+ {
+ queryArgs.Add(BuildParameter("appParams", GetFilterParams()));
+ }
+
+ var queryString = String.Join("&", queryArgs.ToArray());
+ return Scope + "?" + queryString;
+ }
+ }
+
+ private string GetFilterParams()
+ {
+ var queryParams = new List();
+ foreach (var entry in _filters)
+ {
+ queryParams.Add(BuildParameter(entry.Key, entry.Value));
+ }
+
+ return String.Join("&", queryParams.ToArray());
+ }
+
+ private string BuildParameter(string k, string v)
+ {
#if !NET35
- return WebUtility.UrlEncode(k) + "=" + WebUtility.UrlEncode(v);
+ return WebUtility.UrlEncode(k) + "=" + WebUtility.UrlEncode(v);
#else
return HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(v);
#endif
- }
- }
+ }
+ }
}
diff --git a/src/Twilio/JWT/Client/IScope.cs b/src/Twilio/JWT/Client/IScope.cs
index 6c1e4a17b..ffd8471a8 100644
--- a/src/Twilio/JWT/Client/IScope.cs
+++ b/src/Twilio/JWT/Client/IScope.cs
@@ -1,15 +1,15 @@
using System;
namespace Twilio.Jwt
-{
+{
+ ///
+ /// Scope interface of client capabilities
+ ///
+ public interface IScope
+ {
///
- /// Scope interface of client capabilities
+ /// Generate the scope payload
///
- public interface IScope
- {
- ///
- /// Generate the scope payload
- ///
- string Payload { get; }
- }
+ string Payload { get; }
+ }
}
diff --git a/src/Twilio/JWT/Client/IncomingClientScope.cs b/src/Twilio/JWT/Client/IncomingClientScope.cs
index a30a8f389..2e00ce9f2 100644
--- a/src/Twilio/JWT/Client/IncomingClientScope.cs
+++ b/src/Twilio/JWT/Client/IncomingClientScope.cs
@@ -1,35 +1,35 @@
using System;
namespace Twilio.Jwt.Client
-{
+{
+ ///
+ /// Incoming client scope for client capabilities
+ ///
+ public class IncomingClientScope : IScope
+ {
+ private static readonly string Scope = "scope:client:incoming";
+
+ private readonly string _clientName;
+
///
- /// Incoming client scope for client capabilities
+ /// Create a new IncomingClientScope
///
- public class IncomingClientScope : IScope
- {
- private static readonly string Scope = "scope:client:incoming";
-
- private readonly string _clientName;
-
- ///
- /// Create a new IncomingClientScope
- ///
- /// Client name
- public IncomingClientScope(string clientName)
- {
- this._clientName = clientName;
- }
-
- ///
- /// Generate scope payload
- ///
- public string Payload
- {
- get
- {
- var query = "clientName=" + _clientName;
- return Scope + "?" + query;
- }
- }
- }
+ /// Client name
+ public IncomingClientScope(string clientName)
+ {
+ this._clientName = clientName;
+ }
+
+ ///
+ /// Generate scope payload
+ ///
+ public string Payload
+ {
+ get
+ {
+ var query = "clientName=" + _clientName;
+ return Scope + "?" + query;
+ }
+ }
+ }
}
diff --git a/src/Twilio/JWT/Client/OutgoingClientScope.cs b/src/Twilio/JWT/Client/OutgoingClientScope.cs
index 0bac692df..2cd8802d5 100644
--- a/src/Twilio/JWT/Client/OutgoingClientScope.cs
+++ b/src/Twilio/JWT/Client/OutgoingClientScope.cs
@@ -8,78 +8,78 @@
#endif
namespace Twilio.Jwt.Client
-{
+{
+ ///
+ /// Scope capability
+ ///
+ public class OutgoingClientScope : IScope
+ {
+ private static readonly string Scope = "scope:client:outgoing";
+
+ private readonly string _applicationSid;
+ private readonly string _clientName;
+ private readonly Dictionary _parameters;
+
///
- /// Scope capability
+ /// Create a new OutgoingClientScope
///
- public class OutgoingClientScope : IScope
- {
- private static readonly string Scope = "scope:client:outgoing";
-
- private readonly string _applicationSid;
- private readonly string _clientName;
- private readonly Dictionary _parameters;
-
- ///
- /// Create a new OutgoingClientScope
- ///
- /// Twilio Application SID
- /// Name of client
- /// Parameters to pass
- public OutgoingClientScope(
- string applicationSid,
- string clientName = null,
- Dictionary parameters = null
- )
- {
- this._applicationSid = applicationSid;
- this._clientName = clientName;
- this._parameters = parameters;
- }
-
- ///
- /// Generate scope payload
- ///
- public string Payload
- {
- get
- {
- var queryArgs = new List();
- queryArgs.Add(BuildParameter("appSid", _applicationSid));
-
- if (_clientName != null)
- {
- queryArgs.Add(BuildParameter("clientName", _clientName));
- }
-
- if (_parameters != null)
- {
- queryArgs.Add(BuildParameter("appParams", GetAppParams()));
- }
-
- var queryString = String.Join("&", queryArgs.ToArray());
- return Scope + "?" + queryString;
- }
- }
-
- private string GetAppParams()
- {
- var queryParams = new List();
- foreach (var entry in _parameters)
- {
- queryParams.Add(BuildParameter(entry.Key, entry.Value));
- }
-
- return String.Join("&", queryParams.ToArray());
- }
-
- private string BuildParameter(string k, string v)
- {
+ /// Twilio Application SID
+ /// Name of client
+ /// Parameters to pass
+ public OutgoingClientScope(
+ string applicationSid,
+ string clientName = null,
+ Dictionary parameters = null
+ )
+ {
+ this._applicationSid = applicationSid;
+ this._clientName = clientName;
+ this._parameters = parameters;
+ }
+
+ ///
+ /// Generate scope payload
+ ///
+ public string Payload
+ {
+ get
+ {
+ var queryArgs = new List();
+ queryArgs.Add(BuildParameter("appSid", _applicationSid));
+
+ if (_clientName != null)
+ {
+ queryArgs.Add(BuildParameter("clientName", _clientName));
+ }
+
+ if (_parameters != null)
+ {
+ queryArgs.Add(BuildParameter("appParams", GetAppParams()));
+ }
+
+ var queryString = String.Join("&", queryArgs.ToArray());
+ return Scope + "?" + queryString;
+ }
+ }
+
+ private string GetAppParams()
+ {
+ var queryParams = new List();
+ foreach (var entry in _parameters)
+ {
+ queryParams.Add(BuildParameter(entry.Key, entry.Value));
+ }
+
+ return String.Join("&", queryParams.ToArray());
+ }
+
+ private string BuildParameter(string k, string v)
+ {
#if !NET35
- return WebUtility.UrlEncode(k) + "=" + WebUtility.UrlEncode(v);
+ return WebUtility.UrlEncode(k) + "=" + WebUtility.UrlEncode(v);
#else
return HttpUtility.UrlEncode(k) + "=" + HttpUtility.UrlEncode(v);
#endif
- }
- }
+ }
+ }
}
diff --git a/src/Twilio/JWT/Taskrouter/Policy.cs b/src/Twilio/JWT/Taskrouter/Policy.cs
index b018744a5..28b95de71 100755
--- a/src/Twilio/JWT/Taskrouter/Policy.cs
+++ b/src/Twilio/JWT/Taskrouter/Policy.cs
@@ -2,75 +2,75 @@
using Twilio.Http;
namespace Twilio.Jwt.Taskrouter
-{
+{
+ ///
+ /// Policy for a TaskRouter token
+ ///
+ public class Policy
+ {
///
- /// Policy for a TaskRouter token
+ /// Filter requirements for a TaskRouter policy
///
- public class Policy
- {
- ///
- /// Filter requirements for a TaskRouter policy
- ///
- public sealed class FilterRequirement : Dictionary
- {
- private FilterRequirement(bool v)
- {
- Add("required", v);
- }
-
- ///
- /// Parameter is required
- ///
- public static readonly FilterRequirement Required = new FilterRequirement(true);
-
- ///
- /// Parameter is optional
- ///
- public static readonly FilterRequirement Optional = new FilterRequirement(false);
- }
-
- private readonly string _url;
- private readonly bool _allowed;
- private readonly HttpMethod _method;
- private readonly Dictionary _queryFilter;
- private readonly Dictionary _postFilter;
-
- ///
- /// Create a new Policy
- ///
- /// TaskRouter URL
- /// HTTP method
- /// Query param filters
- /// POST data filters
- /// Allow the JWT to access
- public Policy(
- string url,
- HttpMethod method,
- Dictionary queryFilter=null,
- Dictionary postFilter=null,
- bool allowed=true
- )
- {
- _url = url;
- _allowed = allowed;
- _method = method;
- _queryFilter = queryFilter ?? new Dictionary();
- _postFilter = postFilter ?? new Dictionary();
- }
-
- ///
- /// Returns dictionary representation of the Policy
- ///
- /// Dictionary representation of the Policy
- public Dictionary ToDict()
- {
- return new Dictionary {
+ public sealed class FilterRequirement : Dictionary
+ {
+ private FilterRequirement(bool v)
+ {
+ Add("required", v);
+ }
+
+ ///
+ /// Parameter is required
+ ///
+ public static readonly FilterRequirement Required = new FilterRequirement(true);
+
+ ///
+ /// Parameter is optional
+ ///
+ public static readonly FilterRequirement Optional = new FilterRequirement(false);
+ }
+
+ private readonly string _url;
+ private readonly bool _allowed;
+ private readonly HttpMethod _method;
+ private readonly Dictionary _queryFilter;
+ private readonly Dictionary _postFilter;
+
+ ///
+ /// Create a new Policy
+ ///
+ /// TaskRouter URL
+ /// HTTP method
+ /// Query param filters
+ /// POST data filters
+ /// Allow the JWT to access
+ public Policy(
+ string url,
+ HttpMethod method,
+ Dictionary queryFilter = null,
+ Dictionary postFilter = null,
+ bool allowed = true
+ )
+ {
+ _url = url;
+ _allowed = allowed;
+ _method = method;
+ _queryFilter = queryFilter ?? new Dictionary();
+ _postFilter = postFilter ?? new Dictionary();
+ }
+
+ ///
+ /// Returns dictionary representation of the Policy
+ ///
+ /// Dictionary representation of the Policy
+ public Dictionary ToDict()
+ {
+ return new Dictionary {
{ "url", _url },
{ "method", _method.ToString() },
{ "query_filter", _queryFilter },
{ "post_filter", _postFilter },
{ "allow", _allowed }
- };
- }
- }
+ };
+ }
+ }
}
diff --git a/src/Twilio/JWT/Taskrouter/PolicyUtils.cs b/src/Twilio/JWT/Taskrouter/PolicyUtils.cs
index e607e36b0..42f820fca 100644
--- a/src/Twilio/JWT/Taskrouter/PolicyUtils.cs
+++ b/src/Twilio/JWT/Taskrouter/PolicyUtils.cs
@@ -3,30 +3,30 @@
using Twilio.Http;
namespace Twilio.Jwt.Taskrouter
-{
+{
+ ///
+ /// Utility class for generating Policies
+ ///
+ public class PolicyUtils
+ {
+ private static readonly string TaskRouterEventUrl = "https://event-bridge.twilio.com/v1/wschannels";
+
+ private PolicyUtils() { }
+
///
- /// Utility class for generating Policies
+ /// Generate default event bridge policies
///
- public class PolicyUtils
- {
- private static readonly string TaskRouterEventUrl = "https://event-bridge.twilio.com/v1/wschannels";
-
- private PolicyUtils() {}
-
- ///
- /// Generate default event bridge policies
- ///
- /// Twilio account SID
- /// TaskRouter channel ID
- /// Default event bridge policies
- public static List DefaultEventBridgePolicies(string accountSid, string channelId)
- {
- var url = TaskRouterEventUrl + "/" + accountSid + "/" + channelId;
- return new List
+ /// Twilio account SID
+ /// TaskRouter channel ID
+ /// Default event bridge policies
+ public static List DefaultEventBridgePolicies(string accountSid, string channelId)
+ {
+ var url = TaskRouterEventUrl + "/" + accountSid + "/" + channelId;
+ return new List
{
{ new Policy(url, HttpMethod.Get) },
{ new Policy(url, HttpMethod.Post) }
- };
- }
- }
+ };
+ }
+ }
}
diff --git a/src/Twilio/JWT/Taskrouter/TaskRouterCapability.cs b/src/Twilio/JWT/Taskrouter/TaskRouterCapability.cs
index 9e79e92a0..379ad8657 100644
--- a/src/Twilio/JWT/Taskrouter/TaskRouterCapability.cs
+++ b/src/Twilio/JWT/Taskrouter/TaskRouterCapability.cs
@@ -2,98 +2,98 @@
using System.Collections.Generic;
namespace Twilio.Jwt.Taskrouter
-{
+{
+ ///
+ /// JWT for TaskRouter use
+ ///
+ public class TaskRouterCapability : BaseJwt
+ {
+ private readonly string _accountSid;
+ private readonly string _workspaceSid;
+ private readonly string _friendlyName;
+ private readonly string _channelId;
+ private readonly List _policies;
+
///
- /// JWT for TaskRouter use
+ /// Create a new TaskRouter JWT
///
- public class TaskRouterCapability : BaseJwt
- {
- private readonly string _accountSid;
- private readonly string _workspaceSid;
- private readonly string _friendlyName;
- private readonly string _channelId;
- private readonly List _policies;
-
- ///
- /// Create a new TaskRouter JWT
- ///
- /// Twilio account SID
- /// Twilio auth token
- /// TaskRouter workspace SID
- /// TaskRouter channel ID
- /// Friendly name for this JWT
- /// JWT expiration
- /// JWT policies
- public TaskRouterCapability(
- string accountSid,
- string authToken,
- string workspaceSid,
- string channelId,
- string friendlyName = null,
- DateTime? expiration = null,
- List policies = null
- ) : base(authToken, accountSid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
- {
- this._accountSid = accountSid;
- this._workspaceSid = workspaceSid;
- this._channelId = channelId;
- this._friendlyName = friendlyName;
- this._policies = policies;
- }
-
- ///
- /// Get the JWT headers
- ///
- public override Dictionary Headers
- {
- get
- {
- return new Dictionary();
- }
- }
-
- ///
- /// Generate JWT payload
- ///
- public override Dictionary Claims
- {
- get
- {
- var payload = new Dictionary
+ /// Twilio account SID
+ /// Twilio auth token
+ /// TaskRouter workspace SID
+ /// TaskRouter channel ID
+ /// Friendly name for this JWT
+ /// JWT expiration
+ /// JWT policies
+ public TaskRouterCapability(
+ string accountSid,
+ string authToken,
+ string workspaceSid,
+ string channelId,
+ string friendlyName = null,
+ DateTime? expiration = null,
+ List policies = null
+ ) : base(authToken, accountSid, expiration.HasValue ? expiration.Value : DateTime.UtcNow.AddSeconds(3600))
+ {
+ this._accountSid = accountSid;
+ this._workspaceSid = workspaceSid;
+ this._channelId = channelId;
+ this._friendlyName = friendlyName;
+ this._policies = policies;
+ }
+
+ ///
+ /// Get the JWT headers
+ ///
+ public override Dictionary Headers
+ {
+ get
+ {
+ return new Dictionary();
+ }
+ }
+
+ ///
+ /// Generate JWT payload
+ ///
+ public override Dictionary Claims
+ {
+ get
+ {
+ var payload = new Dictionary
{
{ "version", "v1" },
{ "account_sid", _accountSid },
{ "friendly_name", _friendlyName },
{ "workspace_sid", _workspaceSid },
{ "channel", _channelId }
- };
-
- if (_channelId.StartsWith("WK"))
- {
- payload.Add("worker_sid", _channelId);
- }
- else if (_channelId.StartsWith("WQ"))
- {
- payload.Add("taskqueue_sid", _channelId);
- }
-
- var payloadPolicies = new List