Skip to content
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
95 changes: 41 additions & 54 deletions AmplitudeSharp/AmplitudeService.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
Expand All @@ -13,75 +13,68 @@ namespace AmplitudeSharp
{
public class AmplitudeService : IDisposable
{
public static AmplitudeService s_instance;
private static AmplitudeService s_instance;
internal static Action<LogLevel, string> s_logger;

public static AmplitudeService Instance
{
get
{
return s_instance;
}
}
public static AmplitudeService Instance => s_instance;

private object lockObject;
private List<IAmplitudeEvent> eventQueue;
private CancellationTokenSource cancellationToken;
private readonly object lockObject;
private readonly List<IAmplitudeEvent> eventQueue;
private readonly CancellationTokenSource cancellationToken;
private Thread sendThread;
private AmplitudeApi api;
private readonly AmplitudeApi api;
private AmplitudeIdentify identification;
private SemaphoreSlim eventsReady;
private long sessionId;
private readonly SemaphoreSlim eventsReady;
private long sessionId = -1;
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
/// This is meant for testing
/// </summary>
public bool OfflineMode
{
get
{
return api.OfflineMode;
}
set
{
api.OfflineMode = value;
}
get => api.OfflineMode;
set => api.OfflineMode = value;
}

/// <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>
/// <param name="persistenceStream">optinal, stream with saved event data <seealso cref="Uninitialize(Stream)"/></param>
/// <param name="persistenceStream">optional, stream with saved event data <seealso cref="Uninitialize(Stream)"/></param>
/// <param name="logger">Action delegate for logging purposes, if none is specified <see cref="System.Diagnostics.Debug.WriteLine(object)"/> is used</param>
/// <returns></returns>
public static AmplitudeService Initialize(string apiKey, Action<LogLevel, string> logger = null, Stream persistenceStream = null)
Expand Down Expand Up @@ -179,33 +172,25 @@ public void NewSession()
sessionId = DateTime.UtcNow.ToUnixEpoch();
}

/// <summary>
/// Log an event without any parameters
/// </summary>
/// <param name="eventName">the name of the event</param>
public void Track(string eventName)
{
Track(eventName, null);
}

/// <summary>
/// Log an event with parameters
/// </summary>
/// <param name="eventName">the name of the event</param>
/// <param name="properties">parameters for the event (this can just be a dynamic class)</param>
public void Track(string eventName, object properties)
public void Track(string eventName, object properties = null )
{
var identification = this.identification;

if (identification != null)
{
AmplitudeEvent e = new AmplitudeEvent(eventName, properties, ExtraEventProperties)
{
SessionId = sessionId
SessionId = sessionId,
UserId = identification.UserId,
DeviceId = identification.DeviceId,
};

e.UserId = identification.UserId;
e.DeviceId = identification.DeviceId;
QueueEvent(e);
}
else
Expand Down Expand Up @@ -233,15 +218,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 +238,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()}");
s_logger(LogLevel.Error, $"Failed to load persisted events: {e}");
}
}

Expand All @@ -270,9 +255,11 @@ private void LoadPastEvents(Stream persistenceStore)
/// </summary>
private void StartSendThread()
{
sendThread = new Thread(UploadThread);
sendThread.Name = $"{nameof(AmplitudeSharp)} Upload Thread";
sendThread.Priority = ThreadPriority.BelowNormal;
sendThread = new Thread(UploadThread)
{
Name = $"{nameof(AmplitudeSharp)} Upload Thread",
Priority = ThreadPriority.BelowNormal,
};
sendThread.Start();
}

Expand Down Expand Up @@ -357,7 +344,7 @@ private async void UploadThread()
catch (Exception e)
{
// No matter what exception happens, we just quit
s_logger(LogLevel.Error, "Upload thread terminated with: " + e.ToString());
s_logger(LogLevel.Error, "Upload thread terminated with: " + e);
}
}
}
Expand Down
82 changes: 12 additions & 70 deletions AmplitudeSharp/AmplitudeSharp.csproj
Original file line number Diff line number Diff line change
@@ -1,70 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D8A6ABA8-3B25-4D8E-9B29-D6BA8BF83DAB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>AmplitudeSharp</RootNamespace>
<AssemblyName>AmplitudeSharp</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<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>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Management" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AmplitudeService.cs" />
<Compile Include="Api\AmplitudeApi.cs" />
<Compile Include="Api\AmplitudeIdentify.cs" />
<Compile Include="Api\AmplitudeEvent.cs" />
<Compile Include="Api\IAmplitudeEvent.cs" />
<Compile Include="LogLevel.cs" />
<Compile Include="Utils\CollectionExtensions.cs" />
<Compile Include="Utils\DateTimeExtensions.cs" />
<Compile Include="DeviceHelper.cs" />
<Compile Include="DeviceProperties.cs" />
<Compile Include="NativeMethods.cs" />
<Compile Include="NetFxHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UserProperties.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net9.0</TargetFrameworks>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
</ItemGroup>

</Project>
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
Loading