Ejemplo n.º 1
0
        public void AddEvent_ScopedKeyWrite_Success()
        {
            const string 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: (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;
                    }

                    throw new Exception("Unexpected value");
                });
            }

            Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "CustomKey" }));
        }
Ejemplo n.º 2
0
        public void Roundtrip_RndIV_Success()
        {
            const string vendor_guid = "abc";
            const bool   isRead      = false;

            var str = "{\"filters\": [{\"property_name\": \"vendor_id\",\"operator\": \"eq\",\"property_value\": \"VENDOR_GUID\"}],\"allowed_operations\": [ \"READ_OR_WRITE\" ]}";

            str = str.Replace("VENDOR_GUID", vendor_guid);

            if (isRead)
            {
                str = str.Replace("READ_OR_WRITE", "read");
            }
            else
            {
                str = str.Replace("READ_OR_WRITE", "write");
            }

            var rnd = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] bytes = new byte[16];
            rnd.GetBytes(bytes);

            var IV = String.Concat(bytes.Select(b => b.ToString("X2"))); Trace.WriteLine("IV: " + IV);

            var scopedKey = ScopedKey.EncryptString(SettingsEnv.MasterKey, str, IV); //System.Text.Encoding.Default.GetString(bytes));
            var decrypted = ScopedKey.Decrypt(SettingsEnv.MasterKey, scopedKey);

            Trace.WriteLine("decrypted: " + decrypted);

            var settings = new ProjectSettingsProvider(SettingsEnv.ProjectId, writeKey: scopedKey);
            var client   = new KeenClient(settings);

            client.AddEvent("X", new { vendor_id = "abc", X = "123" });
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public KeenLogger()
 {
     Logger = new LoggingDefaultImplementation();
     if (!ConfigurationManagerHelper.GetValueOnKey("stardust.logToKeen", false))
     {
         return;
     }
     try
     {
         if (keenClient != null)
         {
             return;
         }
         var prjSettings = new ProjectSettingsProvider(GetProjectId(), writeKey: GetProjectKey());
         keenClient = new KeenClient(prjSettings);
         keenClient.AddGlobalProperty("serviceHost", Utilities.GetServiceName());
         keenClient.AddGlobalProperty("environment", "Config");
         keenClient.AddGlobalProperty("configSet", "ALL");
         keenClient.AddGlobalProperty("machine", Environment.MachineName);
         keenClient.AddGlobalProperty("datacenterKey", "cnfpxwe");
         var prjReadSettings = new ProjectSettingsProvider(GetProjectId(), readKey: GetProjectReadKey());
         keenReadClient = new KeenClient(prjReadSettings);
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 4
0
        public void GetCollectionSchema_EmptyProjectId_Throws()
        {
            var settings = new ProjectSettingsProvider("X", SettingsEnv.MasterKey);
            var client   = new KeenClient(settings);

            Assert.Throws <KeenException>(() => client.GetSchema(""));
        }
Ejemplo n.º 5
0
        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()));
            });
        }
Ejemplo n.º 6
0
        public async void Notify()
        {
            var text = await Request.Content.ReadAsStringAsync();

            var projSettings = new ProjectSettingsProvider("5a402d20c9e77c0001ff1a04", writeKey: "EF4BE1AF9688F1B19D207932A0E6F1726EDA4E0E17F523F23953EE2D2BAEAE0213F1EC16A1D4CD32D5DE570F259FFFDAC0ED5639866329B98FC7B1C63D4B7F8675C56E6437F574E64B40B45120846C8637FADD43F34F2E4B77FB5EC4FDB82DDF");
            var cli          = new KeenClient(projSettings);

            cli.AddEvent("Notify", new {
                data = text
            });
        }
Ejemplo n.º 7
0
        public void CreateAccessKey_Success()
        {
            var settings = new ProjectSettingsProvider(projectId: "X", masterKey: SettingsEnv.MasterKey); // Replace X with respective value
            var client   = new KeenClient(settings);

            if (UseMocks)
            {
                client.AccessKeys = new AccessKeysMock(settings,
                                                       createAccessKey: new Func <AccessKey, IProjectSettings, JObject>((e, p) =>
                {
                    Assert.True(p == settings, "Incorrect Settings");
                    Assert.NotNull(e.Name, "Expected a name for the newly created Key");
                    Assert.NotNull(e.Permitted, "Expected a list of high level actions this key can perform");
                    Assert.NotNull(e.Options, "Expected an object containing more details about the key’s permitted and restricted functionality");
                    if ((p == settings) && (e.Name == "TestAccessKey") && (e.IsActive) && e.Permitted.First() == "queries" && e.Options.CachedQueries.Allowed.First() == "my_cached_query")
                    {
                        return(new JObject());
                    }
                    else
                    {
                        throw new Exception("Unexpected value");
                    }
                }));
            }

            HashSet <string> permissions = new HashSet <string>()
            {
                "queries"
            };
            List <QueryFilter> qFilters = new List <QueryFilter>()
            {
                new QueryFilter("customer.id", QueryFilter.FilterOperator.Equals(), "asdf12345z")
            };
            CachedQueries cachedQueries = new CachedQueries();

            cachedQueries.Allowed = new HashSet <string>()
            {
                "my_cached_query"
            };
            Options options = new Options()
            {
                Queries = new Core.AccessKey.Queries {
                    Filters = qFilters
                },
                CachedQueries = cachedQueries
            };

            Assert.DoesNotThrow(() => client.CreateAccessKey(new AccessKey {
                Name = "TestAccessKey", IsActive = true, Options = options, Permitted = permissions
            }));
        }
Ejemplo n.º 8
0
        public static void Initialize()
        {
            LocalLogManager.AddLine("Analytics manager initialization");
            var projectSettings = new ProjectSettingsProvider(KeenProjectID, writeKey: KeenWriteKey);

            Client         = new KeenClient(projectSettings);
            DeferredClient = new KeenClient(projectSettings, new EventCacheMemory());

            var playerId = PlayerDataManager.CurrentPlayerId;

            Client.AddGlobalProperty("PlayerID", playerId);

            DeferredClient.AddGlobalProperty("PlayerID", playerId);
        }
Ejemplo n.º 9
0
 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: (e, p) =>
             {
                 if ((p == settings)
                     &&(p.ProjectId=="X"))
                     throw new KeenResourceNotFoundException();
                 throw new Exception("Unexpected value");
             });
     Assert.Throws<KeenResourceNotFoundException>(() => client.AddEvents("AddEventTest", new []{ new {AProperty = "AValue" }}));
 }
Ejemplo n.º 10
0
        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();
        }
Ejemplo n.º 11
0
        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);
                }
            }
        }
Ejemplo n.º 12
0
        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: (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" }));
        }
Ejemplo n.º 13
0
        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" });
        }
Ejemplo n.º 14
0
        public void GetCollectionSchema_InvalidProjectId_Throws()
        {
            var settings = new ProjectSettingsProvider("X", SettingsEnv.MasterKey);
            var client   = new KeenClient(settings);

            if (UseMocks)
            {
                client.EventCollection = new EventCollectionMock(settings,
                                                                 getSchema: (c, p) =>
                {
                    if ((p == settings) && (c == "X"))
                    {
                        throw new KeenException();
                    }
                    throw new Exception("Unexpected value");
                });
            }
            Assert.Throws <KeenException>(() => client.GetSchema("X"));
        }
Ejemplo n.º 15
0
        public void 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 == "X") && (e["X"].Value <string>() == "X"))
                    {
                        throw new KeenResourceNotFoundException(c);
                    }
                }));
            }

            Assert.Throws <KeenResourceNotFoundException>(() => client.AddEvent("X", new { X = "X" }));
        }
Ejemplo n.º 16
0
        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: (e, p) =>
                {
                    if ((p == settings) &&
                        (p.ProjectId == "X"))
                    {
                        throw new KeenResourceNotFoundException();
                    }
                    throw new Exception("Unexpected value");
                });
            }
            Assert.Throws <KeenResourceNotFoundException>(() => client.AddEvents("AddEventTest", new [] { new { AProperty = "AValue" } }));
        }
Ejemplo n.º 17
0
        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"));
        }
Ejemplo n.º 18
0
        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" } }));
        }
        public DeveroomTagger(ITextBuffer buffer, IIdeScope ideScope, bool immediateParsing)
        {
            _buffer   = buffer;
            _ideScope = ideScope;
            var project = ideScope.GetProject(buffer);

            _deveroomConfigurationProvider = ideScope.GetDeveroomConfigurationProvider(project);
            _projectSettingsProvider       = project?.GetProjectSettingsProvider();
            _discoveryService = project?.GetDiscoveryService();

            InitializeWithDiscoveryService(ideScope, project);

            _deveroomTagParser = new DeveroomTagParser(ideScope.Logger, ideScope.MonitoringService);
            _actionThrottler   = new ActionThrottler(() =>
            {
                if (ideScope.IsSolutionLoaded)
                {
                    ReCalculate(buffer.CurrentSnapshot);
                }
                else
                {
                    _actionThrottler.TriggerAction(forceDelayed: true);
                }
            });

            if (immediateParsing)
            {
                _tagsCache.Invalidate();
            }
            else
            {
                _tagsCache.ReCalculate(() => new TagsCache()); //empty valid result
                _actionThrottler.TriggerAction(forceDelayed: true);
            }

            SubscribeToEvents();
        }
Ejemplo n.º 20
0
 public void GetCollectionSchema_EmptyProjectId_Throws()
 {
     var settings = new ProjectSettingsProvider("X", SettingsEnv.MasterKey);
     var client = new KeenClient(settings);
     Assert.Throws<KeenException>(() => client.GetSchema(""));
 }
Ejemplo n.º 21
0
 public void GetCollectionSchema_InvalidProjectId_Throws()
 {
     var settings = new ProjectSettingsProvider("X", SettingsEnv.MasterKey);
     var client = new KeenClient(settings);
     if (UseMocks)
         client.EventCollection = new EventCollectionMock(settings,
             getSchema: (c, p) =>
             {
                 if ((p == settings) && (c == "X"))
                     throw new KeenException();
                 throw new Exception("Unexpected value");
             });
     Assert.Throws<KeenException>(() => client.GetSchema("X"));
 }
Ejemplo n.º 22
0
        public void Constructor_ProjectSettingsNoMasterOrWriteKeys_Throws()
        {
            var settings = new ProjectSettingsProvider(projectId: "X");

            Assert.Throws <KeenException>(() => new KeenClient(settings));
        }
Ejemplo n.º 23
0
 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: (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" }));
 }
Ejemplo n.º 24
0
        public void AddEvent_ScopedKeyWrite_Success()
        {
            const string 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: (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;
                        throw new Exception("Unexpected value");
                    });

            Assert.DoesNotThrow(() => client.AddEvent("AddEventTest", new { AProperty = "CustomKey" }));
        }
Ejemplo n.º 25
0
        public async Task <ActionResult> Landing()
        {
            if (Request.QueryString.HasKeys() && !String.IsNullOrEmpty(Request.QueryString[0]))
            {
                AuthTokenRequest request = new AuthTokenRequest
                {
                    code = Request.QueryString[0]
                };

                HttpClient    client  = new HttpClient();
                StringContent content = new StringContent(JsonConvert.SerializeObject(request));
                var           result  = await client.PostAsync("https://developer.globelabs.com.ph/oauth/access_token?app_id=" + request.app_id + "&app_secret=" + request.app_secret + "&code=" + request.code, content);

                var resultContent = await result.Content.ReadAsStringAsync();

                AuthTokenResult response = JsonConvert.DeserializeObject <AuthTokenResult>(resultContent);

                if (response != null)
                {
                    SMSSendRequest sms = new SMSSendRequest
                    {
                        outboundSMSMessageRequest = new SMSSendRequestBody
                        {
                            clientCorrelator       = "1",
                            senderAddress          = "3667",
                            outboundSMSTextMessage = new SMSMessage
                            {
                                message = "the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog. the quick brown fox jumps over the lazy dog. the quick brown fox jump 160 hello this is the second message"
                            },
                            address = "tel:+639155018529"
                        }
                    };

                    //content = new StringContent(JsonConvert.SerializeObject(sms), Encoding.UTF8, "application/json");
                    //result = await client.PostAsync("https://devapi.globelabs.com.ph/smsmessaging/v1/outbound/" + "3667" + "/requests?access_token=" + response.access_token, content);
                    //resultContent = await result.Content.ReadAsStringAsync();

                    var projSettings = new ProjectSettingsProvider("5a402d20c9e77c0001ff1a04", writeKey: "EF4BE1AF9688F1B19D207932A0E6F1726EDA4E0E17F523F23953EE2D2BAEAE0213F1EC16A1D4CD32D5DE570F259FFFDAC0ED5639866329B98FC7B1C63D4B7F8675C56E6437F574E64B40B45120846C8637FADD43F34F2E4B77FB5EC4FDB82DDF");
                    //var cli = new KeenClient(projSettings);

                    //content = new StringContent(JsonConvert.SerializeObject(new {
                    //}), Encoding.UTF8, "application/json");

                    try
                    {
                        var acc_tok = response.access_token;
                        result = await client.GetAsync("https://devapi.globelabs.com.ph/location/v1/queries/location?access_token=" + response.access_token + "&address=09155018529&requestedAccuracy=100");

                        resultContent = await result.Content.ReadAsStringAsync();
                    }
                    catch (Exception ex)
                    {
                    }


                    //cli.AddEvent("Location", new
                    //{
                    //    message = resultContent
                    //});


                    //cli.AddEvent("Outgoing", new
                    //{
                    //    address = sms.outboundSMSMessageRequest.address,
                    //    message = sms.outboundSMSMessageRequest.outboundSMSTextMessage.message
                    //});
                }
            }

            return(View());
        }
Ejemplo n.º 26
0
 public void Constructor_ProjectSettingsNoMasterOrWriteKeys_Throws()
 {
     var settings = new ProjectSettingsProvider(projectId: "X");
     Assert.Throws<KeenException>(() => new KeenClient(settings));
 }
Ejemplo n.º 27
0
        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);
                }
            }
        }