示例#1
0
        public void AddEvent(string collection, JObject anEvent)
        {
            JObject jsonResponse = null;

            try
            {
                var client  = new RestClient();
                var request = new RestRequest(_serverUrl + collection, Method.POST);
                request.AddHeader("Authorization", _prjSettings.WriteKey);
                request.AddParameter("application/json", anEvent.ToString(), ParameterType.RequestBody);

                var serverResponse = client.Execute(request);
                if (serverResponse == null)
                {
                    throw new KeenException("No response from host");
                }
                if (!serverResponse.ErrorMessage.IsNullOrWhiteSpace())
                {
                    throw new KeenException("AddEvent failed with status: " + serverResponse.ErrorMessage);
                }

                if (!serverResponse.Content.IsNullOrWhiteSpace())
                {
                    jsonResponse = JObject.Parse(serverResponse.Content);
                }
            }
            catch (Exception ex)
            {
                throw new KeenException("AddEvent failed", ex);
            }
            KeenUtil.CheckApiErrorCode(jsonResponse);
        }
示例#2
0
        public JObject GetSchema(string collection)
        {
            try
            {
                var client  = new RestClient();
                var request = new RestRequest(_serverUrl + collection, Method.GET);
                request.AddHeader("Authorization", _prjSettings.MasterKey);

                var serverResponse = client.Execute(request);
                if (serverResponse == null)
                {
                    throw new KeenException("No response from host");
                }
                if (!serverResponse.ErrorMessage.IsNullOrWhiteSpace())
                {
                    throw new KeenException("GetSchema failed with status: " + serverResponse.ErrorMessage);
                }
                var response = JObject.Parse(serverResponse.Content);
                KeenUtil.CheckApiErrorCode(response);
                return(response);
            }
            catch (Exception ex)
            {
                throw new KeenException("GetSchema failed", ex);
            }
        }
示例#3
0
        public void DeleteCollection(string collection)
        {
            JObject jsonResponse = null;

            try
            {
                var client  = new RestClient();
                var request = new RestRequest(_serverUrl + collection, Method.DELETE);
                request.AddHeader("Authorization", _prjSettings.MasterKey);

                var serverResponse = client.Execute(request);
                if (serverResponse == null)
                {
                    throw new KeenException("No response from host");
                }

                if (!serverResponse.ErrorMessage.IsNullOrWhiteSpace())
                {
                    throw new KeenException("DeleteCollection failed with error: " + serverResponse.ErrorMessage);
                }

                if (!serverResponse.Content.IsNullOrWhiteSpace())
                {
                    jsonResponse = JObject.Parse(serverResponse.Content);
                }
            }
            catch (Exception ex)
            {
                throw new KeenException("DeleteCollection failed " + ex.Message, ex);
            }
            // throw an exception with information from the json response
            KeenUtil.CheckApiErrorCode(jsonResponse);
        }
示例#4
0
        /// <summary>
        /// Add a single event to the specified collection.
        /// </summary>
        /// <param name="collection">Collection name</param>
        /// <param name="eventInfo">An object representing the event to be added.</param>
        /// <param name="addOns">Optional collection of Data Enhancement Add-ons</param>
        public void AddEvent(string collection, object eventInfo, IEnumerable <AddOn> addOns = null)
        {
            // Preconditions
            KeenUtil.ValidateEventCollectionName(collection);
            if (null == eventInfo)
            {
                throw new KeenException("Event data is required.");
            }
            if (_prjSettings.WriteKey.IsNullOrWhiteSpace())
            {
                throw new KeenException("Write API key is requried for AddEvent");
            }

            var jEvent = PrepareUserObject(eventInfo, addOns);

            // If an event cache has been provided, cache this event insead of sending it.
            if (null != EventCache)
            {
                EventCache.Add(new CachedEvent(collection, jEvent));
            }
            else
            {
                EventCollection.AddEvent(collection, jEvent);
            }
        }
示例#5
0
        /// <summary>
        /// Add all events in a single request.
        /// </summary>
        /// <param name="events"></param>
        /// <returns></returns>
        public IEnumerable <CachedEvent> AddEvents(JObject events)
        {
            JObject jsonResponse = null;

            try
            {
                var client  = new RestClient(_serverUrl);
                var request = new RestRequest("", Method.POST);
                request.AddHeader("Authorization", _prjSettings.WriteKey);
                request.AddHeader("Keen-Sdk", KeenUtil.GetSdkVersion());
                request.AddParameter("application/json", events.ToString(), ParameterType.RequestBody);

                var serverResponse = client.Execute(request);
                if (serverResponse == null)
                {
                    throw new KeenException("No response from host");
                }
                if (!serverResponse.ErrorMessage.IsNullOrWhiteSpace())
                {
                    throw new KeenException("AddEvents failed with status: " + serverResponse.ErrorMessage);
                }

                if (!serverResponse.Content.IsNullOrWhiteSpace())
                {
                    jsonResponse = JObject.Parse(serverResponse.Content);
                }
            }
            catch (Exception ex)
            {
                throw new KeenException("AddEvents failed", ex);
            }
            KeenUtil.CheckApiErrorCode(jsonResponse);

            try
            {
                // error checking, return failed events in the list,
                // or if the HTTP response is a failure, throw.
                var failedItems = from respCols in jsonResponse.Properties()
                                  from eventsCols in events.Properties()
                                  where respCols.Name == eventsCols.Name
                                  let collection = respCols.Name
                                                   let combined = eventsCols.Children().Children()
                                                                  .Zip(respCols.Children().Children(),
                                                                       (e, r) => new { eventObj = (JObject)e, result = (JObject)r })
                                                                  from e in combined
                                                                  where !(bool)(e.result.Property("success").Value)
                                                                  select new CachedEvent(collection, e.eventObj, KeenUtil.GetBulkApiError(e.result));

                return(failedItems);
            }
            catch (Exception ex)
            {
                throw new KeenException("AddEvents failed", ex);
            }
        }
示例#6
0
        /// <summary>
        /// Retrieve the schema for the specified collection. This requires
        /// a value for the project settings Master API key.
        /// </summary>
        /// <param name="collection"></param>
        public JObject GetSchema(string collection)
        {
            // Preconditions
            KeenUtil.ValidateEventCollectionName(collection);
            if (_prjSettings.MasterKey.IsNullOrWhiteSpace())
            {
                throw new KeenException("Master API key is requried for GetSchema");
            }

            return(EventCollection.GetSchema(collection));
        }
示例#7
0
        /// <summary>
        /// Delete the specified collection. Deletion may be denied for collections with many events.
        /// Master API key is required.
        /// </summary>
        /// <param name="collection">Name of collection to delete.</param>
        public void DeleteCollection(string collection)
        {
            // Preconditions
            KeenUtil.ValidateEventCollectionName(collection);
            if (_prjSettings.MasterKey.IsNullOrWhiteSpace())
            {
                throw new KeenException("Master API key is requried for DeleteCollection");
            }

            EventCollection.DeleteCollection(collection);
        }
示例#8
0
        /// <summary>
        /// Convert a user-supplied object to a JObject that can be sent to the Keen.IO API.
        ///
        /// This writes any global properies to the object and records the time.
        /// </summary>
        /// <param name="eventInfo"></param>
        /// <param name="addOns">Optional collection of Data Enhancement Add-ons</param>
        /// <returns></returns>
        private JObject PrepareUserObject(object eventInfo, IEnumerable <AddOn> addOns)
        {
            var jEvent = JObject.FromObject(eventInfo);

            // Add global properties to the event
            foreach (var p in _globalProperties)
            {
                // If the property value is an IDynamicPropertyValue,
                // exec the Value() to generate the property value.
                var dynProp = p.Value as IDynamicPropertyValue;
                if (dynProp == null)
                {
                    KeenUtil.ValidatePropertyName(p.Key);
                    jEvent.Add(p.Key, JToken.FromObject(p.Value));
                }
                else
                {
                    var val = dynProp.Value();
                    if (null == val)
                    {
                        throw new KeenException(string.Format("Dynamic property \"{0}\" returned a null value", p.Key));
                    }
                    jEvent.Add(p.Key, JToken.FromObject(val));
                }
            }

            // Ensure this event has a 'keen' object of the correct type
            if (null == jEvent.Property("keen"))
            {
                jEvent.Add("keen", new JObject());
            }
            else if (jEvent.Property("keen").Value.GetType() != typeof(JObject))
            {
                throw new KeenException(string.Format("Value of property \"keen\" must be an object, is {0}", jEvent.Property("keen").GetType()));
            }

            var keen = ((JObject)jEvent.Property("keen").Value);

            if (addOns.Any())
            {
                keen.Add("addons", JArray.FromObject(addOns));
            }

            // Set the keen.timestamp if it has not already been set
            if (null == keen.Property("timestamp"))
            {
                keen.Add("timestamp", DateTime.Now);
            }

            return(jEvent);
        }
示例#9
0
        /// <summary>
        /// Add a static global property. This property will be added to
        /// every event.
        /// </summary>
        /// <param name="property">Property name</param>
        /// <param name="value">Property value. This may be a simple value, array, or object,
        /// or an object that supports IDynamicPropertyValue returning one of those.</param>
        public void AddGlobalProperty(string property, object value)
        {
            // Verify that the property name is allowable, and that the value is populated.
            KeenUtil.ValidatePropertyName(property);
            if (value == null)
            {
                throw new KeenException("Global properties must have a non-null value.");
            }
            var dynProp = value as IDynamicPropertyValue;

            if (dynProp != null)
            {
                // Execute the property once before it is needed to check the value
                ExecDynamicPropertyValue(property, dynProp);
            }

            _globalProperties.Add(property, value);
        }
示例#10
0
        /// <summary>
        /// Get details of all schemas in the project.
        /// </summary>
        /// <returns></returns>
        public JArray GetSchemas()
        {
            try
            {
                var client  = new RestClient(_serverUrl);
                var request = new RestRequest("", Method.GET);
                request.AddHeader("Authorization", _prjSettings.MasterKey);
                request.AddHeader("Keen-Sdk", KeenUtil.GetSdkVersion());

                var serverResponse = client.Execute(request);
                if (serverResponse == null)
                {
                    throw new KeenException("No response from host");
                }
                if (!serverResponse.ErrorMessage.IsNullOrWhiteSpace())
                {
                    throw new KeenException("GetSchemas failed with status: " + serverResponse.ErrorMessage);
                }

                JArray jsonResponse = null;
                try
                {
                    // The response should be an array. An error will cause a parse failure.
                    jsonResponse = JArray.Parse(serverResponse.Content);
                }
                catch (Exception)
                {
                    var obj = JObject.Parse(serverResponse.Content);
                    KeenUtil.CheckApiErrorCode(obj);
                }

                return(jsonResponse);
            }
            catch (Exception ex)
            {
                throw new KeenException("GetSchemas failed", ex);
            }
        }