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

Isolated JSON settings to library #5

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
33 changes: 19 additions & 14 deletions AmplitudeSharp/AmplitudeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ public static AmplitudeService Instance
private AmplitudeIdentify identification;
private SemaphoreSlim eventsReady;
private long sessionId;
private readonly JsonSerializerSettings apiJsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None,
};
private readonly JsonSerializerSettings persistenceJsonSerializerSettings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None,
};

/// <summary>
/// Sets Offline mode, which means the events are never sent to actual amplitude service
Expand All @@ -52,32 +63,26 @@ public bool OfflineMode
/// <summary>
/// Additional properties to send with every event
/// </summary>
public Dictionary<string, object> ExtraEventProperties { get; private set; } = new Dictionary<string, object>();
public Dictionary<string, object> ExtraEventProperties { get; } = new Dictionary<string, object>();

private AmplitudeService(string apiKey)
{
lockObject = new object();
api = new AmplitudeApi(apiKey);
api = new AmplitudeApi(apiKey, apiJsonSerializerSettings);
eventQueue = new List<IAmplitudeEvent>();
cancellationToken = new CancellationTokenSource();
eventsReady = new SemaphoreSlim(0);

JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.None
};
}

public void Dispose()
{
{
Uninitialize();
s_instance = null;
}

/// <summary>
/// Initialize AmplitudeSharp
/// Takes an API key for the project and, optionally,
/// Takes an API key for the project and, optionally,
/// a stream where offline/past events are stored
/// </summary>
/// <param name="apiKey">api key for the project to stream data to</param>
Expand Down Expand Up @@ -233,15 +238,15 @@ private void SaveEvents(Stream persistenceStore)
{
try
{
string persistedData = JsonConvert.SerializeObject(eventQueue, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects });
string persistedData = JsonConvert.SerializeObject(eventQueue, persistenceJsonSerializerSettings);
using (var writer = new StreamWriter(persistenceStore))
{
writer.Write(persistedData);
}
}
catch (Exception e)
{
AmplitudeService.s_logger(LogLevel.Error, $"Failed to persist events: {e.ToString()}");
AmplitudeService.s_logger(LogLevel.Error, $"Failed to persist events: {e}");
}
}
}
Expand All @@ -253,15 +258,15 @@ private void LoadPastEvents(Stream persistenceStore)
using (var reader = new StreamReader(persistenceStore))
{
string persistedData = reader.ReadLine();
var data = JsonConvert.DeserializeObject<List<IAmplitudeEvent>>(persistedData, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects });
var data = JsonConvert.DeserializeObject<List<IAmplitudeEvent>>(persistedData, persistenceJsonSerializerSettings);

eventQueue.InsertRange(0, data);
eventsReady.Release();
}
}
catch (Exception e)
{
AmplitudeService.s_logger(LogLevel.Error, $"Failed to load persisted events: {e.ToString()}");
AmplitudeService.s_logger(LogLevel.Error, $"Failed to load persisted events: {e}");
}
}

Expand Down
5 changes: 3 additions & 2 deletions AmplitudeSharp/AmplitudeSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@
<StartupObject />
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed">
<HintPath>..\..\..\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
Expand Down
25 changes: 14 additions & 11 deletions AmplitudeSharp/Api/AmplitudeApi.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace AmplitudeSharp.Api
{
Expand All @@ -29,16 +30,18 @@ class AmplitudeApi : IAmplitudeApi
private string apiKey;
private HttpClient httpClient;
private HttpClientHandler httpHandler;
private readonly JsonSerializerSettings jsonSerializerSettings;

public AmplitudeApi(string apiKey)
public AmplitudeApi(string apiKey, JsonSerializerSettings jsonSerializerSettings)
{
this.apiKey = apiKey;
this.jsonSerializerSettings = jsonSerializerSettings;

httpHandler = new HttpClientHandler();
httpHandler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
httpHandler.Proxy = WebRequest.GetSystemWebProxy();
httpHandler.UseProxy = true;

httpHandler = new HttpClientHandler {
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip,
Proxy = WebRequest.GetSystemWebProxy(),
UseProxy = true,
};
httpClient = new HttpClient(httpHandler);
}

Expand All @@ -49,21 +52,21 @@ public void ConfigureProxy(string proxyUserName, string proxyPassword)
httpHandler.Proxy = WebRequest.GetSystemWebProxy();
}
else
{
{
httpHandler.Proxy.Credentials = new NetworkCredential(proxyUserName, proxyPassword);
}
}
}

public override Task<SendResult> Identify(AmplitudeIdentify identification)
{
string data = Newtonsoft.Json.JsonConvert.SerializeObject(identification);
string data = JsonConvert.SerializeObject(identification, jsonSerializerSettings);

return DoApiCall("identify", "identification", data);
}

public override Task<SendResult> SendEvents(List<AmplitudeEvent> events)
{
string data = Newtonsoft.Json.JsonConvert.SerializeObject(events);
string data = JsonConvert.SerializeObject(events, jsonSerializerSettings);

return DoApiCall("httpapi", "event", data);
}
Expand Down Expand Up @@ -117,7 +120,7 @@ private async Task<SendResult> DoApiCall(string endPoint, string paramName, stri
catch (Exception e)
{
result = SendResult.ServerError;
AmplitudeService.s_logger(LogLevel.Warning, $"Failed to get device make/model: {e.ToString()}");
AmplitudeService.s_logger(LogLevel.Warning, $"Failed to get device make/model: {e}");
}
}

Expand Down