Exemple #1
0
        public void testHttpGetPingServer()
        {
            // test a get method against the endpoint - skipped because it really pings the server
            string returns200    = "http://snowplowanalytics.com";
            string returns404    = "http://snowplowanalytics.com/nothere/ok";
            string cannotConnect = "http://localhost:1231";

            var resp = SnowplowHttpCollectorEndpoint.HttpGet(returns200, false, new List <string> {
                "0"
            });

            Assert.AreEqual(200, resp.StatusCodeTask.Result);

            var bad = SnowplowHttpCollectorEndpoint.HttpGet(returns404, false, new List <string> {
                "0"
            });

            Assert.AreEqual(404, bad.StatusCodeTask.Result);

            var nowhere = SnowplowHttpCollectorEndpoint.HttpGet(cannotConnect, false, new List <string> {
                "0"
            });

            Assert.AreEqual(-1, nowhere.StatusCodeTask.Result);
        }
        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
        public void testSendGetRequestNon200ResponseHttps()
        {
            var getReq = new MockGet()
            {
                StatusCode = 500
            };
            var endpoint = new SnowplowHttpCollectorEndpoint("somewhere.com", HttpProtocol.HTTPS, getMethod: new GetDelegate(getReq.HttpGet));
            var payload  = new Payload();

            payload.Add("hello", "world");
            payload.Add("ts", "123");

            var sendList = new List <Tuple <string, Payload> >();

            sendList.Add(Tuple.Create("0", payload));

            var sendResult = endpoint.Send(sendList);

            Assert.IsTrue(sendResult.FailureIds.Count == 1);
            Assert.IsTrue(getReq.Queries.Count == 1);

            var actual        = getReq.Queries[0];
            var expectedRegex = new Regex("https://somewhere\\.com/i\\?hello=world&ts=123&stm=[0-9]{13}");

            Assert.IsTrue(expectedRegex.Match(actual).Success, String.Format("{0} doesn't match {1}", actual, expectedRegex.ToString()));
        }
Exemple #4
0
        public void testHttpPostPingSever()
        {
            // test the post method against an endpoint - skipped because it's really a manual test
            string returns200    = "http://requestb.in/sqt0d1sq";
            string returns403    = "http://snowplowanalytics.com/nothere/ok";
            string cannotConnect = "http://*****:*****@"[{""foo"":""bar""}]", false, new List <string> {
                "0"
            });

            Assert.AreEqual(200, resp.StatusCodeTask.Result);

            var bad = SnowplowHttpCollectorEndpoint.HttpPost(returns403, @"[{""foo"":""bar""}]", false, new List <string> {
                "0"
            });

            Assert.AreEqual(403, bad.StatusCodeTask.Result);

            var nowhere = SnowplowHttpCollectorEndpoint.HttpPost(cannotConnect, @"[{""foo"":""bar""}]", false, new List <string> {
                "0"
            });

            Assert.AreEqual(-1, nowhere.StatusCodeTask.Result);
        }
Exemple #5
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 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);
        }
Exemple #7
0
        public void testPostHttpNon200Response()
        {
            var postReq = new MockPost()
            {
                StatusCode = 404
            };
            var endpoint = new SnowplowHttpCollectorEndpoint("somewhere.com", HttpProtocol.HTTPS, method: HttpMethod.POST, postMethod: new PostDelegate(postReq.HttpPost));
            var payload  = new Payload();

            payload.Add("foo", "bar");

            var sendList = new List <Tuple <string, Payload> >();

            sendList.Add(Tuple.Create("0", payload));

            var sendResult = endpoint.Send(sendList);

            Assert.IsTrue(sendResult.FailureIds.Count == 1);
            Assert.IsTrue(postReq.Queries.Count == 1);
        }
Exemple #8
0
        public void testGetPortIsSet()
        {
            var getReq   = new MockGet();
            var endpoint = new SnowplowHttpCollectorEndpoint("somewhere.com", HttpProtocol.HTTPS, getMethod: new GetDelegate(getReq.HttpGet), port: 999);
            var payload  = new Payload();

            payload.Add("foo", "bar");

            var sendList = new List <Tuple <string, Payload> >();

            sendList.Add(Tuple.Create("0", payload));

            var sendResult = endpoint.Send(sendList);

            Assert.IsTrue(sendResult.SuccessIds.Count == 1);
            Assert.IsTrue(getReq.Queries.Count == 1);

            var actual        = getReq.Queries[0];
            var expectedRegex = new Regex("https://somewhere\\.com:999/i\\?foo=bar&stm=[0-9]{13}");

            Assert.IsTrue(expectedRegex.Match(actual).Success, String.Format("{0} doesn't match {1}", actual, expectedRegex.ToString()));
        }
Exemple #9
0
        public void testGetIgnoreSchemePathQueryInUri()
        {
            var getReq   = new MockGet();
            var endpoint = new SnowplowHttpCollectorEndpoint("something://somewhere.com/things?1=1", HttpProtocol.HTTPS, getMethod: new GetDelegate(getReq.HttpGet));
            var payload  = new Payload();

            payload.Add("sample", "value");

            var sendList = new List <Tuple <string, Payload> >();

            sendList.Add(Tuple.Create("0", payload));

            var sendResult = endpoint.Send(sendList);

            Assert.IsTrue(sendResult.SuccessIds.Count == 1);
            Assert.IsTrue(getReq.Queries.Count == 1);

            var actual        = getReq.Queries[0];
            var expectedRegex = new Regex("https://somewhere\\.com/i\\?sample=value&stm=[0-9]{13}");

            Assert.IsTrue(expectedRegex.Match(actual).Success, String.Format("{0} doesn't match {1}", actual, expectedRegex.ToString()));
        }
Exemple #10
0
        public void testPostHttpGood()
        {
            var postReq  = new MockPost();
            var endpoint = new SnowplowHttpCollectorEndpoint("somewhere.com", HttpProtocol.HTTPS, method: HttpMethod.POST, postMethod: new PostDelegate(postReq.HttpPost));
            var payload  = new Payload();

            payload.Add("foo", "bar");

            var sendList = new List <Tuple <string, Payload> >();

            sendList.Add(Tuple.Create("0", payload));

            var sendResult = endpoint.Send(sendList);

            Assert.IsTrue(sendResult.SuccessIds.Count == 1);
            Assert.IsTrue(postReq.Queries.Count == 1);
            Assert.AreEqual(@"https://somewhere.com/com.snowplowanalytics.snowplow/tp2", postReq.Queries[0].Uri);

            var actual        = postReq.Queries[0].PostData;
            var expectedRegex = new Regex("{\\\"schema\\\":\\\"iglu:com\\.snowplowanalytics\\.snowplow/payload_data/jsonschema/1-0-4\\\",\\\"data\\\":\\[{\\\"foo\\\":\\\"bar\\\",\\\"stm\\\":\\\"[0-9]{13}\\\"}\\]}");

            Assert.IsTrue(expectedRegex.Match(actual).Success, String.Format("{0} doesn't match {1}", actual, expectedRegex.ToString()));
        }
        /// <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;
        }