Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: update the user agent string for twilio-csharp #606

Merged
merged 26 commits into from
May 19, 2022
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
a56bdad
[DI-1569] modify user agent string format
claudiachua May 9, 2022
e402e30
[DI-1569] remove todo comments
claudiachua May 9, 2022
62b9b0d
remove linq functions as its not supported by net451
May 11, 2022
57f1dff
[DI-1569] remove front extra space from platform version
claudiachua May 11, 2022
f62987d
include twilio.sln
May 12, 2022
341ccc4
Merge branch 'DI-1569' of https://github.com/twilio/twilio-csharp int…
May 12, 2022
882b4a1
[DI-1569] Revert "include twilio.sln"
claudiachua May 12, 2022
02e7c8f
[DI-1569] remove user agent extensions from rest constructor
claudiachua May 12, 2022
a8f6a10
[DI-1569] Remove User Agent Extensions from Request object constructor
claudiachua May 13, 2022
5528c8c
[DI-1569] debug: commenting off UA extensions functionality
claudiachua May 13, 2022
887efdf
[DI-1569] debug: remove osArch
claudiachua May 13, 2022
2dde200
Revert "[DI-1569] debug: remove osArch"
claudiachua May 13, 2022
b4b0a22
[DI-1569] debug: comment off osArch to find test errors
claudiachua May 13, 2022
f302c06
[DI-1569] modify test case for WebRequestClient
claudiachua May 13, 2022
45366e0
[DI-1569] simplify WebRequestClient
claudiachua May 13, 2022
d8fad21
[DI-1569] debug: modify osArch to return Unknown if processor is not …
claudiachua May 13, 2022
ff06ba6
[DI-1569] adding back user-agent extensions functionality
claudiachua May 13, 2022
0d41ca9
[DI-1569] adding useragentextension backto request constructor
claudiachua May 13, 2022
b6033a0
[DI-1569] add useragentextension as class variables in restclient and…
claudiachua May 13, 2022
c11c4c3
[DI-1569] add test to RestClient
claudiachua May 13, 2022
945cc06
[DI-1569] add RequestAsync test for RestClient
claudiachua May 13, 2022
1e5f672
[DI-1569] move WebRequestClientTest to NET35 folder
claudiachua May 13, 2022
cc0633a
Revert "[DI-1569] move WebRequestClientTest to NET35 folder"
claudiachua May 13, 2022
e1427ed
[DI-1569] edits from code reviews
claudiachua May 18, 2022
c1afc1f
[DI-1569] use linq lib functions
claudiachua May 18, 2022
64b8f05
Merge branch 'main' into DI-1569
claudiachua May 19, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/Twilio/Clients/TwilioRestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ public class TwilioRestClient : ITwilioRestClient
/// </summary>
public string Edge { get; set; }

/// <summary>
/// Additions to the user agent string
/// </summary>
public string[] UserAgentExtensions { get; set; }

/// <summary>
/// Log level for logging
/// </summary>
Expand Down Expand Up @@ -95,6 +100,9 @@ public Response Request(Request request)
if (Edge != null)
request.Edge = Edge;

if (UserAgentExtensions != null)
request.UserAgentExtensions = UserAgentExtensions;

Response response;
try
{
Expand Down Expand Up @@ -132,6 +140,9 @@ public async Task<Response> RequestAsync(Request request)
if (Edge != null)
request.Edge = Edge;

if (UserAgentExtensions != null)
request.UserAgentExtensions = UserAgentExtensions;

Response response;
try
{
Expand Down
17 changes: 15 additions & 2 deletions src/Twilio/Http/Net35/WebRequestClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Twilio.Http.Net35
/// </summary>
public class WebRequestClient : HttpClient
{
private const string PlatVersion = " (.NET 3.5)";
private const string PlatVersion = ".NET/3.5";
private HttpWebRequestFactory factory;

public WebRequestClient(HttpWebRequestFactory factory = null)
Expand Down Expand Up @@ -63,7 +63,20 @@ private IHttpWebRequestWrapper BuildHttpRequest(Request request)
{
IHttpWebRequestWrapper httpRequest = this.factory.Create(request.ConstructUrl());

httpRequest.UserAgent = "twilio-csharp/" + AssemblyInfomation.AssemblyInformationalVersion + PlatVersion;
string helperLibVersion = AssemblyInfomation.AssemblyInformationalVersion;
string osName = System.Environment.OSVersion.Platform.ToString();
string osArch = System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") ?? "Unknown";
var libraryVersion = System.String.Format("twilio-csharp/{0} ({1} {2}) {3}", helperLibVersion,osName,osArch,PlatVersion);
claudiachua marked this conversation as resolved.
Show resolved Hide resolved

if (request.UserAgentExtensions != null)
{
foreach (var extension in request.UserAgentExtensions)
{
libraryVersion += " " + extension;
}
}

httpRequest.UserAgent = libraryVersion;

httpRequest.Method = request.Method.ToString();
httpRequest.Accept = "application/json";
Expand Down
6 changes: 6 additions & 0 deletions src/Twilio/Http/Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ public class Request
/// </summary>
public string Edge { get; set; }

/// <summary>
/// Additions to the user agent string
/// </summary>
public string[] UserAgentExtensions { get; set; }

/// <summary>
/// Query params
/// </summary>
Expand Down Expand Up @@ -86,6 +91,7 @@ public Request(HttpMethod method, string url)
/// <param name="postParams">Post data</param>
/// <param name="edge">Twilio edge</param>
/// <param name="headerParams">Custom header data</param>

claudiachua marked this conversation as resolved.
Show resolved Hide resolved
public Request(
HttpMethod method,
Domain domain,
Expand Down
45 changes: 42 additions & 3 deletions src/Twilio/Http/SystemNetHttpClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ namespace Twilio.Http
public class SystemNetHttpClient : HttpClient
{
#if NET451
private string PlatVersion = " (.NET Framework 4.5.1+)";
private string PlatVersion = ".NET Framework 4.5.1+";
#else
private string PlatVersion = $" ({RuntimeInformation.FrameworkDescription})";
private string PlatVersion = $"{RuntimeInformation.FrameworkDescription}";
claudiachua marked this conversation as resolved.
Show resolved Hide resolved
#endif

private readonly System.Net.Http.HttpClient _httpClient;
Expand Down Expand Up @@ -91,7 +91,46 @@ private HttpRequestMessage BuildHttpRequest(Request request)
httpRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
httpRequest.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

var libraryVersion = "twilio-csharp/" + AssemblyInfomation.AssemblyInformationalVersion + PlatVersion;
int lastSpaceIndex = PlatVersion.LastIndexOf(" ");
System.Text.StringBuilder PlatVersionSb= new System.Text.StringBuilder(PlatVersion);
PlatVersionSb[lastSpaceIndex] = '/';

string helperLibVersion = AssemblyInfomation.AssemblyInformationalVersion;

string osName = "Unknown";
#if !NETSTANDARD1_4
osName = Environment.OSVersion.Platform.ToString();
#else
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
osName = "Windows";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
osName = "MacOS";
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
osName = "Linux";
}
#endif

string osArch;
#if !NET451
osArch = RuntimeInformation.OSArchitecture.ToString();
#else
osArch = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") ?? "Unknown";
#endif
var libraryVersion = String.Format("twilio-csharp/{0} ({1} {2}) {3}", helperLibVersion,osName,osArch,PlatVersionSb);

if (request.UserAgentExtensions != null)
{
foreach (var extension in request.UserAgentExtensions)
{
libraryVersion += " " + extension;
}
}

httpRequest.Headers.TryAddWithoutValidation("User-Agent", libraryVersion);

foreach (var header in request.HeaderParams)
Expand Down
28 changes: 28 additions & 0 deletions test/Twilio.Test/Clients/TwilioRestClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ public void RequestPropagatesEdgeAndRegion()
Assert.AreEqual(request.Region, "us1");
}

[Test]
public void RequestWithUserAgentExtensions()
{
client.MakeRequest(Arg.Any<Request>()).Returns(new Response(HttpStatusCode.OK, "OK"));
Request request = new Request(HttpMethod.Get, "https://verify.twilio.com/");
string[] userAgentExtensions = new string[] { "twilio-run/2.0.0-test", "flex-plugin/3.4.0" };
TwilioRestClient twilioClient = new TwilioRestClient("foo", "bar", httpClient: client);
twilioClient.UserAgentExtensions = userAgentExtensions;

twilioClient.Request(request);

Assert.AreEqual(request.UserAgentExtensions, userAgentExtensions);
}

#if !NET35
[Test]
public async Task RequestAsyncPropagatesEdgeAndRegion()
Expand All @@ -161,6 +175,20 @@ public async Task RequestAsyncPropagatesEdgeAndRegion()
Assert.AreEqual(request.Edge, "frankfurt");
Assert.AreEqual(request.Region, "us1");
}

[Test]
public async Task RequestAsyncWithUserAgentExtensions()
{
client.MakeRequestAsync(Arg.Any<Request>()).Returns(new Response(HttpStatusCode.OK, "OK"));
Request request = new Request(HttpMethod.Get, "https://verify.twilio.com/");
string[] userAgentExtensions = new string[] { "twilio-run/2.0.0-test", "flex-plugin/3.4.0" };
TwilioRestClient twilioClient = new TwilioRestClient("foo", "bar", httpClient: client);
twilioClient.UserAgentExtensions = userAgentExtensions;

await twilioClient.RequestAsync(request);

Assert.AreEqual(request.UserAgentExtensions, userAgentExtensions);
}
#endif
}
}
25 changes: 24 additions & 1 deletion test/Twilio.Test/Http/SystemNetHttpClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Twilio.Http;
using HttpMethod = Twilio.Http.HttpMethod;
Expand Down Expand Up @@ -237,7 +238,29 @@ public void TestMakeRequestAddsHeadersAndUserAgent()
Assert.AreEqual("utf-8", internalRequest.Headers.AcceptEncoding.ToString());

Assert.IsNotNull(internalRequest.Headers.UserAgent);
StringAssert.StartsWith("twilio-csharp/", internalRequest.Headers.UserAgent.ToString());
Regex rgx = new Regex(@"^twilio-csharp/[0-9.]+\s\(\w+\s\w+\)\s[.\s\w]+/[^\s]+$");
Assert.IsTrue(rgx.IsMatch(internalRequest.Headers.UserAgent.ToString()));
}

[Test]
public void TestMakeRequestAddUserAgentExtensions()
{
string[] userAgentExtensions = new string[] { "twilio-run/2.0.0-test", "flex-plugin/3.4.0" };

this._mockHttp.Respond("https://api.twilio.com/v1/Resource.json", HttpStatusCode.OK);

Request testRequest = new Request(HttpMethod.Get, "https://api.twilio.com/v1/Resource.json");
testRequest.UserAgentExtensions = userAgentExtensions;
testRequest.SetAuth("username", "password");

this.TwilioHttpClient.MakeRequest(testRequest);

HttpRequestMessage internalRequest = this._mockHttp.InternalRequest;
string userAgent = internalRequest.Headers.UserAgent.ToString();
var actualUserAgent = userAgent.Split(' ');
var actualUserAgentExtensions = new string[userAgentExtensions.Length];
Array.Copy(actualUserAgent, actualUserAgent.Length - userAgentExtensions.Length, actualUserAgentExtensions, 0, userAgentExtensions.Length);
CollectionAssert.AreEqual(userAgentExtensions, actualUserAgentExtensions);
}
}
}
Expand Down
26 changes: 25 additions & 1 deletion test/Twilio.Test/Http/WebRequestClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using System.Collections.Specialized;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Twilio.Tests.Http
{
Expand Down Expand Up @@ -185,7 +186,30 @@ public void TestMakeRequestAddsHeadersAndUserAgent()
Assert.Contains("Authorization", this._mockRequest.Headers.AllKeys);
Assert.AreEqual("Basic " + authString, this._mockRequest.Headers["Authorization"]);

StringAssert.StartsWith("twilio-csharp/", this._mockRequest.UserAgent);
Assert.IsNotNull(this._mockRequest.UserAgent);
Regex rgx = new Regex(@"^twilio-csharp/[0-9.]+\s\(\w+\s\w+\)\s.NET/3.5$");
Assert.IsTrue(rgx.IsMatch(this._mockRequest.UserAgent));
}

[Test]
public void TestMakeRequestAddUserAgentExtensions()
{
// Setup
this._mockResponse.StatusCode = HttpStatusCode.OK;
string[] userAgentExtensions = new string[] { "twilio-run/2.0.0-test", "flex-plugin/3.4.0" };

// Run Test
var request = new Request(HttpMethod.Post, "https://api.twilio.com/v1/Resource.json");
request.UserAgentExtensions = userAgentExtensions;
request.SetAuth("user", "pass");

var response = this.TwilioClient.MakeRequest(request);

// Assert
var actualUserAgent = this._mockRequest.UserAgent.Split(' ');
var actualUserAgentExtensions = new string[userAgentExtensions.Length];
Array.Copy(actualUserAgent, actualUserAgent.Length - userAgentExtensions.Length, actualUserAgentExtensions, 0, userAgentExtensions.Length);
claudiachua marked this conversation as resolved.
Show resolved Hide resolved
CollectionAssert.AreEqual(userAgentExtensions, actualUserAgentExtensions);
}
}
}
Expand Down