public void testDbPutGetOne()
        {
            var fn = getTempFile();

            try
            {
                using (var storage = new LiteDBStorage(fn))
                {
                    Assert.AreEqual(0, storage.TotalItems);

                    var expected = "hello world";
                    storage.Put(expected);

                    Assert.AreEqual(1, storage.TotalItems);

                    var actual = storage.TakeLast(1);

                    Assert.AreEqual(1, storage.TotalItems);

                    var delete = storage.Delete(new List <string> {
                        actual[0].Id
                    });

                    Assert.IsTrue(delete);
                    Assert.AreEqual(expected, actual[0].Item);
                }
            }
            finally
            {
                File.Delete(fn);
            }
        }
        public void testLoadGet()
        {
            storage = new LiteDBStorage(_testDbFilename);

            Assert.AreEqual(0, storage.TotalItems);

            var queue    = new PersistentBlockingQueue(storage, new PayloadToJsonString());
            var endpoint = new SnowplowHttpCollectorEndpoint(host: _collectorHostUri, port: 8080, protocol: HttpProtocol.HTTP, method: HttpMethod.GET, byteLimitGet: 50000);
            var emitter  = new AsyncEmitter(endpoint: endpoint, queue: queue, sendLimit: 25);

            var clientSession = new ClientSession(_testClientSessionFilename);

            Assert.IsFalse(tracker.Started);
            tracker.Start(emitter: emitter, clientSession: clientSession, trackerNamespace: "testNamespace", appId: "testAppId", encodeBase64: false, synchronous: false);
            Assert.IsTrue(tracker.Started);

            for (int i = 0; i < 100; i++)
            {
                tracker.Track(new Structured()
                              .SetCategory("exampleCategory")
                              .SetAction("exampleAction")
                              .SetLabel("exampleLabel")
                              .SetProperty("exampleProperty")
                              .SetValue(17)
                              .Build()
                              );
            }

            tracker.Flush();
            tracker.Stop();
            Assert.IsFalse(tracker.Started);
        }
Exemple #3
0
 private static void ListUsers(TrackerProperties trackerProperties)
 {
     using (var storage = new LiteDBStorage(trackerProperties))
     {
         foreach (User user in storage.GetUsers())
         {
             Console.WriteLine(
                 "[{0}][{1}] {2} - [{3}] {4} - [{5}] {6}",
                 user.LocalId,
                 user.CharacterId,
                 user.CharacterName,
                 user.CorporationId,
                 user.CorporationName,
                 user.AllianceId,
                 user.AllianceName);
             if (user.RestrictedServers.Any())
             {
                 foreach (var s in user.RestrictedServers)
                 {
                     Console.WriteLine(" - {0}", s);
                 }
             }
         }
     }
 }
        public void stopTracker()
        {
            storage.Dispose();
            storage = null;

            tracker.Stop();
            tracker = null;
        }
        public void testDbInit()
        {
            var fn        = getTempFile();
            int itemCount = -1;

            using (var storage = new LiteDBStorage(fn))
            {
                itemCount = storage.TotalItems;
            }

            File.Delete(fn);
            Assert.AreEqual(0, itemCount);
        }
Exemple #6
0
        /// <summary>
        /// Start a tracker with a default emitter
        /// </summary>
        /// <param name="endpoint">Hostname of your collector</param>
        /// <param name="dbPath">A filename/path to store queued events in</param>
        /// <param name="method">The method used to send events to a collector. GET or POST</param>
        /// <param name="subject">Information on the user</param>
        /// <param name="clientSession"></param>
        /// <param name="trackerNamespace">Namespace of tracker</param>
        /// <param name="appId">Application ID of tracker</param>
        /// <param name="encodeBase64">Base64 encode collector parameters</param>
        /// <param name="synchronous">Whether to do I/O synchronously</param>
        /// <param name="desktopContextDelegate">Delegate for fetching the desktop context</param>
        /// <param name="mobileContextDelegate">Delegate for fetching the mobile context</param>
        /// <param name="geoLocationContextDelegate">Delegate for fetching the geo-location context</param>
        /// <param name="l">A logger to emit an activity stream to</param>
        public void Start(string endpoint, string dbPath, HttpMethod method = HttpMethod.POST, Subject subject = null, ClientSession clientSession = null,
                          string trackerNamespace = null, string appId = null, bool encodeBase64 = true, bool synchronous = true, DesktopContextDelegate desktopContextDelegate = null,
                          MobileContextDelegate mobileContextDelegate = null, GeoLocationContextDelegate geoLocationContextDelegate = null, ILogger l = null)
        {
            AsyncEmitter emitter;

            lock (_lock)
            {
                var dest    = new SnowplowHttpCollectorEndpoint(endpoint, method: method, l: l);
                var storage = new LiteDBStorage(dbPath);
                _storage = storage;
                var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());
                emitter = new AsyncEmitter(dest, queue, l: l);
            }
            Start(emitter, subject, clientSession, trackerNamespace, appId, synchronous, encodeBase64, desktopContextDelegate, mobileContextDelegate, geoLocationContextDelegate, l);
        }
        public void testDbPutMany()
        {
            var fn             = getTempFile();
            int insertionCount = 100;
            var expected       = new List <string>();

            try
            {
                using (var storage = new LiteDBStorage(fn))
                {
                    Assert.AreEqual(0, storage.TotalItems);

                    for (int i = 0; i < insertionCount; i++)
                    {
                        var generated = String.Format("{0}", i);
                        storage.Put(generated);
                        expected.Insert(0, generated);
                    }

                    Assert.AreEqual(insertionCount, storage.TotalItems);

                    var eventRecords = storage.TakeLast(insertionCount);

                    var eventIds = new List <string>();
                    var items    = new List <string>();

                    foreach (var record in eventRecords)
                    {
                        eventIds.Add(record.Id);
                        items.Add(record.Item);
                    }

                    var delete = storage.Delete(eventIds);

                    Assert.IsTrue(delete);
                    Assert.AreEqual(0, storage.TotalItems);

                    CollectionAssert.AreEqual(expected, items);
                }
            }
            finally
            {
                File.Delete(fn);
            }
        }
        public void testTracker()
        {
            var storage = new LiteDBStorage(_testDbFilename);

            Assert.AreEqual(0, storage.TotalItems);

            var queue = new PersistentBlockingQueue(storage, new PayloadToJsonString());

            var getRequestMock  = new MockGet();
            var postRequestMock = new MockPost();

            var endpoint = new SnowplowHttpCollectorEndpoint("snowplowanalytics.com",
                                                             postMethod: new SnowplowHttpCollectorEndpoint.PostDelegate(postRequestMock.HttpPost),
                                                             getMethod: new SnowplowHttpCollectorEndpoint.GetDelegate(getRequestMock.HttpGet));

            Assert.IsFalse(tracker.Started);

            tracker.Start(new AsyncEmitter(endpoint, queue, sendLimit: 1), trackerNamespace: "testNamespace", appId: "testAppId", encodeBase64: false);

            Assert.IsTrue(tracker.Started);
            Assert.IsTrue(ensureSubjectSet(tracker));
            Assert.IsTrue(ensurePageViewsWorkGet(tracker, getRequestMock));
            Assert.IsTrue(ensureStructEventsWorkGet(tracker, getRequestMock));
            Assert.IsTrue(ensureEcommerceTransactionWorksGet(tracker, getRequestMock));
            Assert.IsTrue(ensureUnstructEventGet(tracker, getRequestMock));

            tracker.Stop();

            Assert.IsFalse(tracker.Started);

            // Restart with base64 on
            tracker.Start(new AsyncEmitter(endpoint, queue, sendLimit: 1), trackerNamespace: "testNamespace", appId: "testAppId", encodeBase64: true);

            Assert.IsTrue(tracker.Started);
            Assert.IsTrue(ensureUnstructEventGet(tracker, getRequestMock, true));
            Assert.IsTrue(ensureScreenViewWorksGet(tracker, getRequestMock, true));
            Assert.IsTrue(ensureTimingWorksGet(tracker, getRequestMock, true));
            Assert.IsTrue(ensureContextsWorkGet(tracker, getRequestMock, true));
            Assert.IsTrue(ensureSettersWorkGet(tracker, getRequestMock));

            tracker.Stop();

            Assert.IsFalse(tracker.Started);
        }
        /// <summary>
        /// Halts the Tracker
        /// </summary>
        public static void Shutdown()
        {
            // Note: This will also stop the ClientSession and Emitter objects for you!
            Instance.Stop();

            // Note: Dispose of Storage to remove lock on database file!
            if (_storage != null)
            {
                _storage.Dispose();
                _storage = null;
            }

            if (_clientSession != null)
            {
                _clientSession = null;
            }

            SnowplowTrackerPlatformExtension.Current.StopLocationUpdates();

            // Reset session counters
            SessionMadeCount    = 0;
            SessionSuccessCount = 0;
            SessionFailureCount = 0;
        }
        /// <summary>
        /// Inits the Snowplow Tracker; after this point it can be accessed globally.
        /// </summary>
        /// <param name="emitterUri">The emitter URI</param>
        /// <param name="protocol">The protocol to use</param>
        /// <param name="port">The port the collector is on</param>
        /// <param name="method">The method to use</param>
        /// <param name="useClientSession">Whether to enable client session</param>
        /// <param name="useMobileContext">Whether to enable mobile contexts</param>
        /// <param name="useGeoLocationContext">Whether to enable geo-location contexts</param>
        public static void Init(
            string emitterUri,
            HttpProtocol protocol = HttpProtocol.HTTP,
            int?port                   = null,
            HttpMethod method          = HttpMethod.GET,
            bool useClientSession      = false,
            bool useMobileContext      = false,
            bool useGeoLocationContext = false)
        {
            var logger = new ConsoleLogger();

            var dest = new SnowplowHttpCollectorEndpoint(emitterUri, method: method, port: port, protocol: protocol, l: logger);

            // Note: Maintain reference to Storage as this will need to be disposed of manually
            _storage = new LiteDBStorage(SnowplowTrackerPlatformExtension.Current.GetLocalFilePath("events.db"));
            var queue = new PersistentBlockingQueue(_storage, new PayloadToJsonString());

            // Note: When using GET requests the sendLimit equals the number of concurrent requests - to many of these will break your application!
            var sendLimit = method == HttpMethod.GET ? 10 : 100;

            // Note: To make the tracker more battery friendly and less likely to drain batteries there are two settings to take note of here:
            //       1. The stopPollIntervalMs: Controls how often we look to the database for more events
            //       2. The deviceOnlineMethod: Is run before going to the database or attempting to send events, this will prevent any I/O from
            //          occurring unless you have an active network connection
            var emitter = new AsyncEmitter(dest, queue, sendLimit: sendLimit, stopPollIntervalMs: 1000, sendSuccessMethod: EventSuccessCallback,
                                           deviceOnlineMethod: SnowplowTrackerPlatformExtension.Current.IsDeviceOnline, l: logger);

            var userId = PropertyManager.GetStringValue(KEY_USER_ID, SnowplowCore.Utils.GetGUID());

            PropertyManager.SaveKeyValue(KEY_USER_ID, userId);

            var subject = new Subject()
                          .SetPlatform(Platform.Mob)
                          .SetUserId(userId)
                          .SetLang("en");

            if (useClientSession)
            {
                _clientSession = new ClientSession(SnowplowTrackerPlatformExtension.Current.GetLocalFilePath("client_session.dict"), l: logger);
            }

            // Note: You can either attach contexts to each event individually or for the more common contexts such as Desktop, Mobile and GeoLocation
            //       you can pass a delegate method which will then be called for each event automatically.

            MobileContextDelegate mobileContextDelegate = null;

            if (useMobileContext)
            {
                mobileContextDelegate = SnowplowTrackerPlatformExtension.Current.GetMobileContext;
            }

            GeoLocationContextDelegate geoLocationContextDelegate = null;

            if (useMobileContext)
            {
                geoLocationContextDelegate = SnowplowTrackerPlatformExtension.Current.GetGeoLocationContext;
            }

            // Attach the created objects and begin all required background threads!
            Instance.Start(emitter: emitter, subject: subject, clientSession: _clientSession, trackerNamespace: _trackerNamespace,
                           appId: _appId, encodeBase64: false, synchronous: false, mobileContextDelegate: mobileContextDelegate,
                           geoLocationContextDelegate: geoLocationContextDelegate, l: logger);

            // Reset session counters
            SessionMadeCount    = 0;
            SessionSuccessCount = 0;
            SessionFailureCount = 0;
        }
Exemple #11
0
        private static void AddUser(TrackerProperties trackerProperties)
        {
            if (string.IsNullOrEmpty(trackerProperties.CharacterName))
            {
                throw new ArgumentException("Character name is not set");
            }
            var client = new ESIClient();
            var user   = client.GetUserByCharacterName(trackerProperties.CharacterName).GetAwaiter().GetResult();

            if (user == null)
            {
                Console.WriteLine("ERROR: unable to load EVE character {0}", trackerProperties.CharacterName);
                return;
            }
            if (!string.IsNullOrEmpty(trackerProperties.ServerRestrictions))
            {
                var serverTokens = trackerProperties.ServerRestrictions
                                   .Split(
                    new char[] { ';', ',' },
                    StringSplitOptions.RemoveEmptyEntries)
                                   .Select(t => t.Trim());
                user.RestrictedServers.Clear();
                foreach (string token in serverTokens)
                {
                    user.RestrictedServers.Add(token);
                }
            }
            using (var storage = new LiteDBStorage(trackerProperties))
            {
                var storedUser = storage.GetUser(user.CharacterName);
                if (storedUser != null)
                {
                    user.LocalId = storedUser.LocalId;
                    if (storage.UpdateUser(user))
                    {
                        Console.WriteLine(
                            "Updated user [{0}][{1}] {2} - [{3}] {4} - [{5}] {6}",
                            user.LocalId,
                            user.CharacterId,
                            user.CharacterName,
                            user.CorporationId,
                            user.CorporationName,
                            user.AllianceId,
                            user.AllianceName);
                        if (user.RestrictedServers.Any())
                        {
                            Console.WriteLine("Server restrictions:");
                            foreach (var s in user.RestrictedServers)
                            {
                                Console.WriteLine(" - {0}", s);
                            }
                        }
                        else
                        {
                            Console.WriteLine("No server restrictions set");
                        }
                    }
                    else
                    {
                        Console.WriteLine("ERROR: user update failed");
                    }
                }
                else
                {
                    var id = storage.AddUser(user);
                    if (id > 0)
                    {
                        Console.WriteLine(
                            "Added user [{0}][{1}] {2} - [{3}] {4} - [{5}] {6}",
                            id,
                            user.CharacterId,
                            user.CharacterName,
                            user.CorporationId,
                            user.CorporationName,
                            user.AllianceId,
                            user.AllianceName);
                        if (user.RestrictedServers.Any())
                        {
                            Console.WriteLine("Server restrictions:");
                            foreach (var s in user.RestrictedServers)
                            {
                                Console.WriteLine(" - {0}", s);
                            }
                        }
                        else
                        {
                            Console.WriteLine("No server restrictions set");
                        }
                    }
                    else
                    {
                        Console.WriteLine("ERROR: user creation failed");
                    }
                }
            }
        }