Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Apr 24, 2024. It is now read-only.

Commit 75efc16

Browse files
dailycodingf2prateek
authored andcommitted
Gzip header (#75)
* Add gzip deflate option for request header * Add Unit test for GZip configuration * Compress request content with GZip algorithm * Update function name and description for compressing request data.
1 parent 134837b commit 75efc16

File tree

7 files changed

+133
-17
lines changed

7 files changed

+133
-17
lines changed

Analytics/Config.cs

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Linq;
44
using System.Text;
@@ -21,6 +21,8 @@ public class Config
2121

2222
internal bool Async { get; set; }
2323

24+
internal bool CompressRequest { get; set; }
25+
2426
internal TimeSpan Timeout { get; set; }
2527

2628
public Config()
@@ -93,5 +95,18 @@ public Config SetAsync(bool async)
9395
this.Async = async;
9496
return this;
9597
}
98+
99+
/// <summary>
100+
/// Sets the API request header uses GZip option.
101+
/// Enable this when the network is the bottleneck for your application (typically in client side applications).
102+
/// If useGZip is set, it compresses request content with GZip algorithm
103+
/// </summary>
104+
/// <param name="bCompress">True to compress request header, false for no compression</param>
105+
/// <returns></returns>
106+
public Config SetRequestCompression(bool bCompress)
107+
{
108+
this.CompressRequest = bCompress;
109+
return this;
110+
}
96111
}
97112
}

Analytics/Request/BlockingRequestHandler.cs

Lines changed: 49 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
using Segment.Exception;
1414
using Segment.Model;
1515
using Segment.Stats;
16+
using System.IO;
17+
using System.IO.Compression;
1618

1719
namespace Segment.Request
1820
{
@@ -83,23 +85,28 @@ internal BlockingRequestHandler(Client client, TimeSpan timeout)
8385
this._client = client;
8486
this.Timeout = timeout;
8587

88+
// Create HttpClient instance in .Net 3.5
8689
#if NET35
8790
_httpClient = new HttpClient { Timeout = Timeout };
88-
// set proxy
89-
if (!string.IsNullOrEmpty(_client.Config.Proxy))
90-
_httpClient.Proxy = new WebProxy(_client.Config.Proxy);
9191
#else
92+
var handler = new HttpClientHandler();
93+
#endif
94+
95+
// Set proxy information
9296
if (!string.IsNullOrEmpty(_client.Config.Proxy))
9397
{
94-
var handler = new HttpClientHandler
95-
{
96-
Proxy = new WebProxy(_client.Config.Proxy),
97-
UseProxy = true
98-
};
99-
_httpClient = new HttpClient(handler) { Timeout = Timeout };
98+
#if NET35
99+
_httpClient.Proxy = new WebProxy(_client.Config.Proxy);
100+
#else
101+
handler.Proxy = new WebProxy(_client.Config.Proxy);
102+
handler.UseProxy = true;
103+
#endif
100104
}
101-
else
102-
_httpClient = new HttpClient() { Timeout = Timeout };
105+
106+
// Initialize HttpClient instance with given configuration
107+
#if NET35
108+
#else
109+
_httpClient = new HttpClient(handler) { Timeout = Timeout };
103110
#endif
104111
}
105112

@@ -135,6 +142,29 @@ public async Task MakeRequest(Batch batch)
135142
_httpClient.DefaultRequestHeaders.Add("User-Agent", szUserAgent);
136143
#endif
137144

145+
// Prepare request data;
146+
var requestData = Encoding.UTF8.GetBytes(json);
147+
148+
// Compress request data if compression is set
149+
if (_client.Config.CompressRequest)
150+
{
151+
#if NET35
152+
_httpClient.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
153+
#else
154+
//_httpClient.DefaultRequestHeaders.Add("Content-Encoding", "gzip");
155+
#endif
156+
157+
// Compress request data with GZip
158+
using (MemoryStream memory = new MemoryStream())
159+
{
160+
using (GZipStream gzip = new GZipStream(memory, CompressionMode.Compress, true))
161+
{
162+
gzip.Write(requestData, 0, requestData.Length);
163+
}
164+
requestData = memory.ToArray();
165+
}
166+
}
167+
138168
Logger.Info("Sending analytics request to Segment.io ..", new Dict
139169
{
140170
{ "batch id", batch.MessageId },
@@ -156,7 +186,7 @@ public async Task MakeRequest(Batch batch)
156186

157187
try
158188
{
159-
var response = Encoding.UTF8.GetString(_httpClient.UploadData(uri, "POST", Encoding.UTF8.GetBytes(json)));
189+
var response = Encoding.UTF8.GetString(_httpClient.UploadData(uri, "POST", requestData));
160190
watch.Stop();
161191

162192
Succeed(batch, watch.ElapsedMilliseconds);
@@ -187,10 +217,16 @@ public async Task MakeRequest(Batch batch)
187217
}
188218
}
189219
}
220+
190221
#else
191222
watch.Start();
192223

193-
var response = await _httpClient.PostAsync(uri, new StringContent(json, Encoding.UTF8, "application/json")).ConfigureAwait(false);
224+
ByteArrayContent content = new ByteArrayContent(requestData);
225+
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
226+
if (_client.Config.CompressRequest)
227+
content.Headers.ContentEncoding.Add("gzip");
228+
229+
var response = await _httpClient.PostAsync(uri, content).ConfigureAwait(false);
194230

195231
watch.Stop();
196232

Test.Net35/ConnectionTests.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Text;
44
using NUnit.Framework;
@@ -28,6 +28,19 @@ public void ProxyTestNet35()
2828
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
2929
}
3030

31+
[Test()]
32+
public void GZipTestNet35()
33+
{
34+
// Set GZip/Deflate on request header
35+
Analytics.Initialize(Constants.WRITE_KEY, new Config().SetAsync(false).SetRequestCompression(true));
36+
37+
Actions.Identify(Analytics.Client);
38+
39+
Assert.AreEqual(1, Analytics.Client.Statistics.Submitted);
40+
Assert.AreEqual(1, Analytics.Client.Statistics.Succeeded);
41+
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
42+
}
43+
3144
static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args)
3245
{
3346
if (args != null)

Test.Net45/ConnectionTests.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Text;
44
using NUnit.Framework;
@@ -28,6 +28,19 @@ public void ProxyTestNet45()
2828
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
2929
}
3030

31+
[Test()]
32+
public void GZipTestNet45()
33+
{
34+
// Set GZip/Deflate on request header
35+
Analytics.Initialize(Constants.WRITE_KEY, new Config().SetAsync(false).SetRequestCompression(true));
36+
37+
Actions.Identify(Analytics.Client);
38+
39+
Assert.AreEqual(1, Analytics.Client.Statistics.Submitted);
40+
Assert.AreEqual(1, Analytics.Client.Statistics.Succeeded);
41+
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
42+
}
43+
3144
static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args)
3245
{
3346
if (args != null)

Test.NetStandard20/ConnectionTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,19 @@ public void ProxyTestNetStanard20()
2828
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
2929
}
3030

31+
[Test()]
32+
public void GZipTestNetStanard20()
33+
{
34+
// Set proxy address, like as "http://localhost:8888"
35+
Analytics.Initialize(Constants.WRITE_KEY, new Config().SetAsync(false).SetGZip(true));
36+
37+
Actions.Identify(Analytics.Client);
38+
39+
Assert.AreEqual(1, Analytics.Client.Statistics.Submitted);
40+
Assert.AreEqual(1, Analytics.Client.Statistics.Succeeded);
41+
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
42+
}
43+
3144
static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args)
3245
{
3346
if (args != null)

Test.UniversalApp/ConnectionTests.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ public void ProxyTestNetPortable()
2929
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
3030
}
3131

32+
[TestMethod]
33+
public void GZipTestNetPortable()
34+
{
35+
// Set proxy address, like as "http://localhost:8888"
36+
Analytics.Initialize(Constants.WRITE_KEY, new Config().SetAsync(false).SetGZip(true));
37+
38+
Actions.Identify(Analytics.Client);
39+
40+
Assert.AreEqual(1, Analytics.Client.Statistics.Submitted);
41+
Assert.AreEqual(1, Analytics.Client.Statistics.Succeeded);
42+
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
43+
}
44+
3245
static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args)
3346
{
3447
if (args != null)

Test/ConnectionTests.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
using System;
1+
using System;
22
using System.Collections.Generic;
33
using System.Text;
44
using NUnit.Framework;
@@ -28,6 +28,19 @@ public void ProxyTest()
2828
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
2929
}
3030

31+
[Test()]
32+
public void GZipTest()
33+
{
34+
// Set GZip/Deflate on request header
35+
Analytics.Initialize(Constants.WRITE_KEY, new Config().SetAsync(false).SetRequestCompression(true));
36+
37+
Actions.Identify(Analytics.Client);
38+
39+
Assert.AreEqual(1, Analytics.Client.Statistics.Submitted);
40+
Assert.AreEqual(1, Analytics.Client.Statistics.Succeeded);
41+
Assert.AreEqual(0, Analytics.Client.Statistics.Failed);
42+
}
43+
3144
static void LoggingHandler(Logger.Level level, string message, IDictionary<string, object> args)
3245
{
3346
if (args != null)

0 commit comments

Comments
 (0)