Exemplo n.º 1
0
        /// <summary>
        /// Generates a query that matches against a specific segment
        /// </summary>
        /// <param name="segment">Segment to match</param>
        /// <returns>Query</returns>
        static string GenerateSegmentMatchQuery(NcbtSegment segment)
        {
            // Build query
            var queryBuilder = new StringBuilder();

            queryBuilder.Append("{ '$and':[ ");

            segment.CriterionGroups.ForEach(cg =>
            {
                queryBuilder.Append("{ '$or':[ ");

                cg.Criterions.ForEach(c =>
                {
                    queryBuilder.Append("{ '" + c.PropertyAlias + ".Value':");

                    queryBuilder.Append(GenerateCriterionMatchQuery(c));

                    queryBuilder.Append(" },"); // End criterion object. Mongo doesn't care about the extra comma on the last object in the array
                });

                queryBuilder.Append("] },"); // End '$or' array
            });

            queryBuilder.Append("] }"); // End '$and' array

            // Return query
            return(queryBuilder.ToString());
        }
Exemplo n.º 2
0
        /// <summary>
        /// Generates a query that matches a user against a specific segment taking specific properties into account
        /// </summary>
        /// <param name="segment">Segment to match</param>
        /// <param name="properties">Dictionary of properties to include or not</param>
        /// <returns>Query</returns>
        static string GenerateSegmentWithPropertiesMatchQuery(NcbtSegment segment, IReadOnlyDictionary <string, bool> properties)
        {
            // Build query
            var queryBuilder = new StringBuilder();

            queryBuilder.Append("{ '$and':[ ");

            properties.ForEach(p =>
            {
                if (p.Value)
                {
                    queryBuilder.Append("{ '" + p.Key + "': { $exists: true, $nin: [null] }},");
                }
                else
                {
                    queryBuilder.Append("{ '" + p.Key + "': { $exists: false }},");
                }
            });
            queryBuilder.Append(GenerateSegmentMatchQuery(segment));

            queryBuilder.Append("] }"); // End '$and' array

            // Return query
            return(queryBuilder.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// Generates a query that matches a user against a specific segment and checks if that segment needs to be inserted or updated on the user
        /// </summary>
        /// <param name="visitorId">Id of the visitor</param>
        /// <param name="segment">Segment to match</param>
        /// <returns>Query</returns>
        static string GenerateNeedsPersistenceQuery(string visitorId, NcbtSegment segment)
        {
            var queryBuilder = new StringBuilder();

            queryBuilder.Append("{ '$and':[ ");

            queryBuilder.Append("{ '_id': ObjectId('" + visitorId + "') }");
            if (segment.Persistence != 0)
            {
                queryBuilder.Append(",");
                queryBuilder.Append("{ '$or':[ ");
                queryBuilder.Append(
                    "{ 'ncbt.persistedSegments.{SEGMENT}': { '$lt': {DATE} } }"
                    .Replace("{SEGMENT}", segment.Alias)
                    .Replace("{DATE}", $"ISODate(\"{DateTime.UtcNow.AddDays(-(segment.Persistence >= 0 ? segment.Persistence : 0)).ToString("O")}\")"));
                queryBuilder.Append(",");
                queryBuilder.Append("{ 'ncbt.persistedSegments.{SEGMENT}': { $exists: false } }".Replace("{SEGMENT}", segment.Alias));
                queryBuilder.Append("] },"); // End '$or' array
            }
            else
            {
                queryBuilder.Append(GenerateSegmentMatchQuery(segment));
            }
            queryBuilder.Append("] }"); // End '$and' array

            // Return query
            return(queryBuilder.ToString());
        }
Exemplo n.º 4
0
        public long CountVisitorsInSegment(NcbtSegment segment)
        {
            if (segment == null || !segment.HasCriterions)
            {
                return(0);
            }

            return(collection.CountAsync(BsonDocument.Parse(GenerateSegmentMatchQuery(segment))).Result);
        }
Exemplo n.º 5
0
        public IReadOnlyCollection <dynamic> GetVisitorsInSegmentWithProperties(NcbtSegment segment, IReadOnlyDictionary <string, bool> properties)
        {
            if (segment == null || !segment.HasCriterions)
            {
                return(new List <dynamic>());
            }

            return(collection.Find(BsonDocument.Parse(GenerateSegmentWithPropertiesMatchQuery(segment, properties)))
                   .ToListAsync()
                   .Result);
        }
Exemplo n.º 6
0
        public IReadOnlyCollection <dynamic> GetVisitorsInSegment(NcbtSegment segment)
        {
            if (segment == null || !segment.HasCriterions)
            {
                return(new List <dynamic>());
            }

            return(collection.Find(BsonDocument.Parse(GenerateSegmentMatchQuery(segment)))
                   .ToListAsync()
                   .Result);
        }
Exemplo n.º 7
0
        public virtual bool IsVisitorInSegment(string visitorId, NcbtSegment segment)
        {
            if (visitorId.IsNullOrWhiteSpace())
            {
                return(false);
            }

            if (segment == null || !segment.HasCriterions)
            {
                return(false);
            }

            return(collection.CountAsync(BsonDocument.Parse(GenerateIsVisitorInSegmentQuery(visitorId, segment)))
                   .Result > 0);
        }
Exemplo n.º 8
0
        public bool IsVisitorInSegment(string visitorId, NcbtSegment segment)
        {
            var row = GetVisitorSegments(visitorId, segment);

            if (row == null)
            {
                return(false);
            }

            if (segment.Persistence > 0)
            {
                return(DateTime.UtcNow.AddDays(segment.Persistence) > row.CreatedUtc);
            }

            return(segment.Persistence < 0);
        }
Exemplo n.º 9
0
        public void AddToSegment(string visitorId, NcbtSegment segment)
        {
            var row = GetVisitorSegments(visitorId, segment);

            if (row == null)
            {
                using (var connection = connectionFactory())
                    using (var command = connection.CreateCommand())
                    {
                        command.CommandText = "INSERT INTO dbo.ncBtVisitorSegment (VisitorId, SegmentAlias, CreatedUtc) VALUES (@visitorId, @segmentAlias, @createdUtc);";
                        command.Parameters.AddWithValue("@visitorId", visitorId);
                        command.Parameters.AddWithValue("@segmentAlias", segment.Alias);
                        command.Parameters.AddWithValue("@createdUtc", DateTime.UtcNow);
                        command.ExecuteNonQuery();
                    }
            }
        }
Exemplo n.º 10
0
        public dynamic Save(dynamic node)
        {
            try
            {
                // Try casting to a segment
                var segment = JsonConvert.DeserializeObject <NcbtSegment>(((JObject)node).ToString());

                // Save segment
                var success = segment.Save();

                // Return updated segment
                return(NcbtSegment.GetById(segment.Id));
            }
            catch (Exception e)
            {
                return(e);
            }
        }
Exemplo n.º 11
0
        public long CountVisitorsInSegment(NcbtSegment segment)
        {
            var persistence = segment.Persistence;

            // If nothing is "persisted" (though it is) we don't include them
            // in the stats.
            if (persistence == 0)
            {
                return(0);
            }

            using (var connection = connectionFactory())
                using (var command = connection.CreateCommand())
                {
                    command.Parameters.AddWithValue("@segmentAlias", segment.Alias);

                    if (persistence < 0)
                    {
                        command.CommandText = $"SELECT COUNT(*) FROM {VisitorSegment.TableName} WHERE {nameof(VisitorSegment.SegmentAlias)} = @segmentAlias;";
                        return((int)command.ExecuteScalar());
                    }

                    command.CommandText = $"SELECT {nameof(VisitorSegment.CreatedUtc)} FROM {VisitorSegment.TableName} WHERE {nameof(VisitorSegment.SegmentAlias)} = @segmentAlias;";

                    using (var reader = command.ExecuteReader())
                    {
                        var rows = 0;
                        var now  = DateTime.Now;

                        while (reader.Read())
                        {
                            var persistedAt = reader.GetDateTime(0);

                            if ((now - persistedAt).TotalDays <= persistence)
                            {
                                rows++;
                            }
                        }

                        return(rows);
                    }
                }
        }
Exemplo n.º 12
0
        public void AddToSegment(string visitorId, NcbtSegment segment)
        {
            if (visitorId == null)
            {
                throw new ArgumentNullException(nameof(visitorId));
            }

            if (segment == null)
            {
                throw new ArgumentNullException(nameof(segment));
            }

            var options = new UpdateOptions {
                IsUpsert = true
            };
            var update = new BsonDocument("$set", new BsonDocument(new Dictionary <string, object> {
                { "ncbt.persistedSegments." + segment.Alias, DateTime.UtcNow }
            }));
            var filter = BsonDocument.Parse(GenerateNeedsPersistenceQuery(visitorId, segment));

            collection.UpdateOneAsync(filter, update, options);
        }
Exemplo n.º 13
0
 public void Delete(int id)
 {
     NcbtSegment.DeleteById(id);
 }
Exemplo n.º 14
0
 public dynamic GetAllLight()
 {
     return(NcbtSegment.GetAllLight());
 }
Exemplo n.º 15
0
 public dynamic GetLightById(int id)
 {
     return(NcbtSegment.GetLightById(id));
 }