Exemple #1
0
        public void ReadKeyOnly_Success()
        {
            var settings = new ProjectSettingsProvider(SettingsEnv.ProjectId, readKey: SettingsEnv.ReadKey); 
            var client = new KeenClient(settings);

            if (!UseMocks)
            {
                // Server is required for this test
                // Also, test depends on existance of collection "AddEventTest"
                Assert.DoesNotThrow(() => client.Query(QueryType.Count(), "AddEventTest", ""));
            }
        }
        static void Main (string[] args)
        {
            // Loading Keen.IO Keys and Misc. from Config File
            _keenIOProjectID = ConfigurationManager.AppSettings["keenIOProjectID"];
            _keenIOMasterKey = ConfigurationManager.AppSettings["keenIOMasterKey"];
            _keenIOWriteKey  = ConfigurationManager.AppSettings["keenIOWriteKey"];
            _keenIOReadKey   = ConfigurationManager.AppSettings["keenIOReadKey"];
            _bucketName      = ConfigurationManager.AppSettings["keenIOBucketName"];
            
            // Creating Keen.IO Variables - Yes, i am setting my read key as the master key, so that you can read the bucket I have created with data
            var projectSettings = new ProjectSettingsProvider (_keenIOProjectID,masterKey:_keenIOReadKey);
            var keenClient      = new KeenClient (projectSettings);


            /*********************************************************************
             *          EXECUTING SIMPLE ANALYTICS QUERIES ON KEEN.IO 
             **********************************************************************/

            // Query 1 - Average App Price grouped by Category
            Dictionary<String,String> parameters = new Dictionary<String,String>();
            parameters.Add ("event_collection", "PlayStore2014");
            parameters.Add ("target_property", "Price");
            parameters.Add ("group_by", "Category");

            JObject keenResponse = keenClient.Query (KeenConstants.QueryAverage, parameters);

            PrintQueryTitle ("Query 1 - Average App Price grouped by Category");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();

            // Query 2 - Most Expensive app for sale of each category
            keenResponse = keenClient.Query (KeenConstants.QueryMaximum, parameters);

            PrintQueryTitle ("Query 2 - Most Expensive app for sale of each category");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();
            
            // Query 3 - Most Expensive App for sale of all (without group by)
            parameters.Remove ("group_by");
            keenResponse = keenClient.Query (KeenConstants.QueryMaximum, parameters);

            PrintQueryTitle ("Query 3 - Most Expensive App for sale of all (without group by)");
            Console.WriteLine (keenResponse.ToSafeString ());
            PrintSeparator ();

            Console.ReadKey ();

        }
 public void AddEvents_InvalidProject_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X", writeKey: settingsEnv.WriteKey);
     var client = new KeenClient(settings);
     if (UseMocks)
         client.Event = new EventMock(settings,
             AddEvents: new Func<JObject, IProjectSettings, IEnumerable<CachedEvent>>((e, p) =>
             {
                 if ((p == settings)
                     &&(p.ProjectId=="X"))
                     throw new KeenException();
                 else
                     throw new Exception("Unexpected value");
             }));
     Assert.Throws<KeenException>(() => client.AddEvents("AddEventTest", new []{ new {AProperty = "AValue" }}));
 }
        static void Main (string[] args)
        {
            // Loading Keen.IO Keys and Misc. from Config File
            _keenIOProjectID = ConfigurationManager.AppSettings["keenIOProjectID"];
            _keenIOMasterKey = ConfigurationManager.AppSettings["keenIOMasterKey"];
            _keenIOWriteKey  = ConfigurationManager.AppSettings["keenIOWriteKey"];
            _keenIOReadKey   = ConfigurationManager.AppSettings["keenIOReadKey"];
            _bucketName      = ConfigurationManager.AppSettings["keenIOBucketName"];

            // Configuring MongoDB Wrapper for connection and queries
            MongoDBWrapper mongoDB   = new MongoDBWrapper ();
            string fullServerAddress = String.Join (":", Consts.MONGO_SERVER, Consts.MONGO_PORT);
            mongoDB.ConfigureDatabase (Consts.MONGO_USER, Consts.MONGO_PASS, Consts.MONGO_AUTH_DB, fullServerAddress, Consts.MONGO_TIMEOUT, Consts.MONGO_DATABASE, Consts.MONGO_COLLECTION);

            // Creating Keen.IO Variables
            var projectSettings = new ProjectSettingsProvider (_keenIOProjectID, _keenIOMasterKey, _keenIOWriteKey, _keenIOReadKey);
            var keenClient      = new KeenClient (projectSettings);

            // From This point on, you can change your code to reflect your own "Reading" logic
            // What I've done is simply read the records from the MongoDB database and Upload them to Keen.IO
            foreach (var currentApp in mongoDB.FindMatch<AppModel> (Query.NE ("Uploaded", true)))
            {
                try
                {
                    // Adding Event to Keen.IO
                    keenClient.AddEvent ("PlayStore2014", currentApp);

                    // Incrementing Counter
                    _appsCounter++;

                    // Console feedback Every 100 Processed Apps
                    if (_appsCounter % 100 == 0)
                    {
                        Console.WriteLine ("Uploaded : " + _appsCounter);
                    }

                    mongoDB.SetUpdated (currentApp.Url);
                }
                catch (Exception ex)
                {
                    Console.WriteLine ("\n\t" + ex.Message);
                }
            }
        }
        public void Encrypt_64CharKeyWithFilter_Success()
        {
            var settings = new ProjectSettingsProvider("projId", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");

            IDictionary<string, object> filter = new ExpandoObject();
            filter.Add("property_name", "account_id");
            filter.Add("operator", "eq");
            filter.Add("property_value", 123);

            dynamic secOpsIn = new ExpandoObject();
            secOpsIn.filters = new List<object>() { filter };
            secOpsIn.allowed_operations = new List<string>() { "read" };
            Assert.DoesNotThrow(() =>
            {
                var scopedKey = ScopedKey.Encrypt(settings.MasterKey, (object)secOpsIn);
                var decrypted = ScopedKey.Decrypt(settings.MasterKey, scopedKey);
                var secOpsOut = JObject.Parse(decrypted);
                Assert.True(secOpsIn.allowed_operations[0] == (string)(secOpsOut["allowed_operations"].First()));
            });
        }
        public async Task Async_AddEvent_ValidProjectIdInvalidWriteKey_Throws()
        {
            var settings = new ProjectSettingsProvider(projectId: settingsEnv.ProjectId, writeKey: "X");
            var client = new KeenClient(settings);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(settings,
                    AddEvent: new Action<string, JObject, IProjectSettings>((c, e, p) =>
                    {
                        if ((p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "Value"))
                            throw new KeenInvalidApiKeyException(c);
                    }));

            await client.AddEventAsync("AddEventTest", new { AProperty = "Value" });
        }
        public void AddEvent_ScopedKeyWrite_Success()
        {
            var scope = "{\"timestamp\": \"2014-02-25T22:09:27.320082\", \"allowed_operations\": [\"write\"]}";
            var scopedKey = ScopedKey.EncryptString(settingsEnv.MasterKey, scope);
            var settings = new ProjectSettingsProvider(masterKey: settingsEnv.MasterKey, projectId: settingsEnv.ProjectId, writeKey: scopedKey);

            var client = new KeenClient(settings);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(settings,
                    AddEvent: new Action<string, JObject, IProjectSettings>((c, e, p) =>
                    {
                        var key = JObject.Parse(ScopedKey.Decrypt(p.MasterKey, p.WriteKey));
                        if ((key["allowed_operations"].Values<string>().First()=="write") && (p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>()=="CustomKey"))
                            return;
                        else
                            throw new Exception("Unexpected value");
                    }));

            Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "CustomKey" }));
        }
 public void AddEvent_ValidProjectIdInvalidWriteKey_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: settingsEnv.ProjectId, writeKey: "X");
     var client = new KeenClient(settings);
     if (UseMocks)
         client.EventCollection = new EventCollectionMock(settings,
             AddEvent: new Action<string, JObject, IProjectSettings>((c, e, p) =>
             {
                 if ((p == settings) && (c == "X") && (e["X"].Value<string>() == "X"))
                     throw new KeenInvalidApiKeyException(c);
             }));
     Assert.Throws<KeenInvalidApiKeyException>(() => client.AddEvent("X", new { X = "X" }));
 }
 public void GetCollectionSchema_InvalidProjectId_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X", masterKey: settingsEnv.MasterKey);
     var client = new KeenClient(settings);
     if (UseMocks)
         client.EventCollection = new EventCollectionMock(settings,
             GetSchema: new Func<string, IProjectSettings, JObject>((c, p) =>
             {
                 if ((p == settings) && (c == "X"))
                     throw new KeenResourceNotFoundException();
                 else
                     throw new Exception("Unexpected value");
             }));
     Assert.Throws<KeenResourceNotFoundException>(() => client.GetSchema("X"));
 }
 public void GetCollectionSchema_EmptyProjectId_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X", masterKey: settingsEnv.MasterKey);
     var client = new KeenClient(settings);
     Assert.Throws<KeenException>(() => client.GetSchema(""));
 }
 public void Constructor_ProjectSettingsNoMasterOrWriteKeys_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X");
     Assert.Throws<KeenException>(() => new KeenClient(settings));
 }
        static void Main(string[] args)
        {
            // Loading Keen.IO Keys and Misc. from Config File
            _keenIOProjectID = ConfigurationManager.AppSettings["keenIOProjectID"];
            _keenIOMasterKey = ConfigurationManager.AppSettings["keenIOMasterKey"];
            _keenIOWriteKey  = ConfigurationManager.AppSettings["keenIOWriteKey"];
            _keenIOReadKey   = ConfigurationManager.AppSettings["keenIOReadKey"];
            _bucketName      = ConfigurationManager.AppSettings["keenIOBucketName"];

            // Configuring MongoDB Wrapper for connection and queries
            MongoDBWrapper mongoDB   = new MongoDBWrapper ();
            string fullServerAddress = String.Join (":", Consts.MONGO_SERVER, Consts.MONGO_PORT);
            mongoDB.ConfigureDatabase (Consts.MONGO_USER, Consts.MONGO_PASS, Consts.MONGO_AUTH_DB, fullServerAddress, Consts.MONGO_TIMEOUT, Consts.MONGO_DATABASE, Consts.MONGO_COLLECTION);

            // Creating Keen.IO Variables
            var projectSettings = new ProjectSettingsProvider (_keenIOProjectID, _keenIOMasterKey, _keenIOWriteKey, _keenIOReadKey);
            var keenClient      = new KeenClient (projectSettings);

            var eventsToSend = new List<AppModel>();
            long totalProcessed = 0;
            long totalSent = 0;

            DateTime start = DateTime.Now;

            // From This point on, you can change your code to reflect your own "Reading" logic
            // What I've done is simply read the records from the MongoDB database and Upload them to Keen.IO

            // if(args.Length != 0 && args[0] == "reset")
            {
                int count = 0;

                foreach (var currentApp in mongoDB.FindMatch<AppModel>(Query.NE("Uploaded", true)))
                {
                    mongoDB.SetUpdated(currentApp.Url, false);
                    ++count;

                    if((count % 100) == 0)
                    {
                        Console.WriteLine("Reset update for {0}", count);
                    }
                }
            }

            foreach (var currentApp in mongoDB.FindMatch<AppModel> (Query.NE ("Uploaded", true)))
            {
                if (eventsToSend.Count < 1000)
                {
                    eventsToSend.Add(currentApp);
                    continue;
                }

                var sent = SendEventsToKeep(keenClient, eventsToSend, mongoDB);

                totalProcessed += eventsToSend.Count;
                totalSent += sent;

                Console.WriteLine("processed {0} events took {1}: ({2} events per sec)", totalProcessed, DateTime.Now - start, ((double)totalProcessed) / (DateTime.Now - start).TotalSeconds);

                eventsToSend.Clear();
            }

            {
                var sent = SendEventsToKeep(keenClient, eventsToSend, mongoDB);
                totalProcessed += eventsToSend.Count;
                Console.WriteLine("processed {0} events took {1}: ({2} events per sec)", totalProcessed, DateTime.Now - start, ((double)totalProcessed) / (DateTime.Now - start).TotalSeconds);
            }

            if(totalProcessed != totalSent)
            {
                totalProcessed = 0;
                totalSent = 0;

                foreach (var currentApp in mongoDB.FindMatch<AppModel>(Query.NE("Uploaded", true)))
                {
                    if (eventsToSend.Count < 1)
                    {
                        eventsToSend.Add(currentApp);
                        continue;
                    }

                    var sent = SendEventsToKeep(keenClient, eventsToSend, mongoDB);

                    totalProcessed += eventsToSend.Count;
                    totalSent += sent;

                    Console.WriteLine("processed {0} events took {1}: ({2} events per sec)", totalProcessed, DateTime.Now - start, ((double)totalProcessed) / (DateTime.Now - start).TotalSeconds);

                    eventsToSend.Clear();
                }

                {
                    var sent = SendEventsToKeep(keenClient, eventsToSend, mongoDB);
                    totalProcessed += eventsToSend.Count;
                    Console.WriteLine("processed {0} events took {1}: ({2} events per sec)", totalProcessed, DateTime.Now - start, ((double)totalProcessed) / (DateTime.Now - start).TotalSeconds);
                }
            }
        }
        public void Async_AddEvent_InvalidProjectId_Throws()
        {
            var settings = new ProjectSettingsProvider(projectId: "X", writeKey: SettingsEnv.WriteKey);
            var client = new KeenClient(settings);
            if (UseMocks)
                client.EventCollection = new EventCollectionMock(settings,
                    addEvent: new Action<string, JObject, IProjectSettings>((c, e, p) =>
                    {
                        if ((p == settings) && (c == "AddEventTest") && (e["AProperty"].Value<string>() == "Value"))
                            throw new KeenResourceNotFoundException(c);
                    }));

            Assert.ThrowsAsync<Keen.Core.KeenResourceNotFoundException>( () => client.AddEventAsync("AddEventTest", new { AProperty = "Value" }));
        }