Example #1
0
        public IEnumerable <TodoItem> Remove(params Guid[] Ids)
        {
            List <TodoItem> removedItems = new List <TodoItem>();

            if (Ids.Count() == 0)
            {
                return(removedItems);
            }
            try
            {
                using (TodoContext db = new TodoContext())
                {
                    var exists = Get(db, Ids).ToList();
                    foreach (var Id in Ids)
                    {
                        var exist = exists.FirstOrDefault(item => item.Id.Equals(Id));
                        if (exist != null)
                        {
                            removedItems.Add(exist);
                            var entry = db.Entry(exist);
                            entry.State = System.Data.Entity.EntityState.Deleted;
                        }
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
            return(removedItems);
        }
Example #2
0
        public TDomainCriteria BuildDomainCriteria()
        {
            criteria = new TDomainCriteria
            {
                MaximumResult = MaximumResults,
                FirstResult   = FirstResult,
                SortOrder     = sortOrder
            };
            criteria.SafeAnd(new EqualityFilter("Id", Id));

            if (Ids.IsNotNull() && Ids.Count() > 0)
            {
                criteria.SafeAnd(new EqualityFilter("Id", Ids, FilterType.In));
            }

            if (NotEqualIds.IsNotNull() && NotEqualIds.Count() > 0)
            {
                criteria.SafeAnd(new EqualityFilter("Id", NotEqualIds, FilterType.NotIn));
            }

            criteria.Aggregations.AddRange(Aggregations);

            OnBuildDomainCriteria(criteria);

            if (FailOnNoCriteriaSpecified)
            {
                Invariant.IsFalse(criteria.IsEmpty(), () => "Criteria requires at least one filter");
            }

            return(criteria);
        }
Example #3
0
        /// <summary>
        /// 若不填Id則取全部, 填了取部分
        /// </summary>
        /// <param name="db"></param>
        /// <param name="Ids"></param>
        /// <returns></returns>
        private IQueryable <TodoItem> Get(TodoContext db, params Guid[] Ids)
        {
            var query = db.TodoItems.AsQueryable();

            if (Ids.Count() > 0)
            {
                query = query.Where(item => Ids.Contains(item.Id));
            }
            return(query);
        }
Example #4
0
        public Config(ILoggerFactory loggerFactory)
        {
            ILogger <Config> logger = loggerFactory.CreateLogger <Config>();

            logger.LogDebug($"Retrieving {EnvNames.IdsPath}");
            string idsPath = Environment.GetEnvironmentVariable(EnvNames.IdsPath)
                             ?? throw new Exception($"Environment variable {EnvNames.IdsPath} not set");

            logger.LogDebug($"Retrieving {EnvNames.ClientsPath}");
            string clientsPath = Environment.GetEnvironmentVariable(EnvNames.ClientsPath)
                                 ?? throw new Exception($"Environment variable {EnvNames.ClientsPath} not set");

            logger.LogDebug($"Retrieving {EnvNames.ApisPath}");
            string apisPath = Environment.GetEnvironmentVariable(EnvNames.ApisPath)
                              ?? throw new Exception($"Environment variable {EnvNames.ApisPath} not set");

            logger.LogInformation($"Retrieving data from {idsPath}");
            string idsData = File.ReadAllText(idsPath);

            logger.LogTrace($"Found data {idsPath}: {idsData}");
            Ids = JsonConvert.DeserializeObject <IdentityResource[]>(idsData);
            logger.LogInformation($"Found {Ids.Count()} clients in {idsPath}");

            logger.LogInformation($"Retrieving data from {clientsPath}");
            string clientData = File.ReadAllText(clientsPath);

            logger.LogTrace($"Found data {clientData}: {clientData}");
            Clients = JsonConvert.DeserializeObject <Client[]>(clientData);
            logger.LogInformation($"Found {Clients.Count()} clients in {clientsPath}");

            logger.LogInformation($"Retrieving data from {apisPath}");
            string apisData = File.ReadAllText(apisPath);

            logger.LogTrace($"Found data {apisData}: {apisData}");
            Apis = JsonConvert.DeserializeObject <ApiResource[]>(apisData);
            logger.LogInformation($"Found {Apis.Count()} clients in {apisPath}");
        }
Example #5
0
        /// <summary>
        /// Prepares the WHERE clause of the SQL query from the <see cref="Filter"/> argument: WHERE ABC
        /// </summary>
        private string PrepareWhereSql(QxCompilationContext ctx)
        {
            var ps = ctx.Parameters;

            // WHERE is cached
            if (_cachedWhere == null)
            {
                string whereFilter       = null;
                string whereInIds        = null;
                string whereInParentIds  = null;
                string whereInPropValues = null;

                if (Filter != null)
                {
                    whereFilter = Filter.Expression.CompileToBoolean(ctx);
                }

                if (Ids != null && Ids.Any())
                {
                    if (Ids.Count() == 1)
                    {
                        string paramName = ps.AddParameter(Ids.Single());
                        whereInIds = $"[P].[Id] = @{paramName}";
                    }
                    else
                    {
                        var isIntKey    = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == KeyType.String;

                        // Prepare the ids table
                        DataTable idsTable = isIntKey ? RepositoryUtilities.DataTable(Ids.Select(id => new IdListItem {
                            Id = (int)id
                        }))
                            : isStringKey?RepositoryUtilities.DataTable(Ids.Select(id => new StringListItem {
                            Id = id.ToString()
                        }))
                                                 : throw new InvalidOperationException("Only string and Integer Ids are supported");

                        //
                        var idsTvp = new SqlParameter("@Ids", idsTable)
                        {
                            TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer Ids are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(idsTvp);
                        whereInIds = $"[P].[Id] IN (SELECT Id FROM @Ids)";
                    }
                }

                if (ParentIds != null)
                {
                    if (!ParentIds.Any())
                    {
                        if (IncludeRoots)
                        {
                            whereInParentIds = $"[P].[ParentId] IS NULL";
                        }
                    }
                    else if (ParentIds.Count() == 1)
                    {
                        string paramName = ps.AddParameter(ParentIds.Single());
                        whereInParentIds = $"[P].[ParentId] = @{paramName}";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                    else
                    {
                        var isIntKey    = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == KeyType.String;

                        // Prepare the data table
                        var    parentIdsTable = new DataTable();
                        string idName         = "Id";
                        var    idType         = KeyType switch
                        {
                            KeyType.String => typeof(string),
                            KeyType.Int => typeof(int),
                            _ => throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"),
                        };

                        var column = new DataColumn(idName, idType);
                        if (isStringKey)
                        {
                            column.MaxLength = 450; // Just for performance
                        }
                        parentIdsTable.Columns.Add(column);
                        foreach (var id in ParentIds.Where(e => e != null))
                        {
                            DataRow row = parentIdsTable.NewRow();
                            row[idName] = id;
                            parentIdsTable.Rows.Add(row);
                        }

                        // Prepare the TVP
                        var parentIdsTvp = new SqlParameter("@ParentIds", parentIdsTable)
                        {
                            TypeName = KeyType == KeyType.Int ? "[dbo].[IdList]" : KeyType == KeyType.String ? "[dbo].[StringList]" : throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(parentIdsTvp);
                        whereInParentIds = $"[P].[ParentId] IN (SELECT Id FROM @ParentIds)";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(PropName) && Values != null && Values.Any())
                {
                    var propDesc = ResultDescriptor.Property(PropName);
                    var propType = propDesc.Type;

                    var isIntKey    = propType == typeof(int?) || propType == typeof(int);
                    var isStringKey = propType == typeof(string);

                    // Prepare the ids table
                    DataTable valuesTable =
                        isStringKey ? RepositoryUtilities.DataTable(Values.Select(id => new StringListItem {
                        Id = id.ToString()
                    })) :
                        isIntKey?RepositoryUtilities.DataTable(Values.Select(id => new IdListItem {
                        Id = (int)id
                    })) :
                        throw new InvalidOperationException("Only string and Integer Ids are supported");

                    var valuesTvp = new SqlParameter("@Values", valuesTable)
                    {
                        TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer values are supported"),
                                         SqlDbType = SqlDbType.Structured
                    };

                    ps.AddParameter(valuesTvp);
                    whereInPropValues = $"[P].[{propDesc.Name}] IN (SELECT Id FROM @Values)";
                }

                // The final WHERE clause (if any)
                string whereSql = "";

                var clauses = new List <string> {
                    whereFilter, whereInIds, whereInParentIds, whereInPropValues
                }.Where(e => !string.IsNullOrWhiteSpace(e));
                if (clauses.Any())
                {
                    whereSql = clauses.Aggregate((c1, c2) => $"{c1}) AND ({c2}");
                    whereSql = $"WHERE ({whereSql})";
                }

                _cachedWhere = whereSql;
            }

            return(_cachedWhere);
        }
Example #6
0
        // TODO: Use Engine.GetVisibleRegions(Husk husk);

        public bool Judge(Husk husk)
        {
            if (Ids?.Count() > 0)
            {
                return(Ids.Contains(husk.Location.Id));
            }

            if (Region.HasValue)
            {
                Location location = husk.Location.GetLocation();

                if (Structure.HasValue)
                {
                    var results = location.Filter(Structure.Value);

                    if (results.Any(x => (Interaction == InteractionType.View ? husk.Hitbox.Sight : husk.Hitbox.Reach)
                                    .Intersects(x.Shape)))
                    {
                        return(true);
                    }
                }

                if (Location.HasValue)
                {
                    if (Construct.HasValue && (location as Construct) != null)
                    {
                        if (!Construct.Value.HasFlag((location as Construct).Tag))
                        {
                            return(false);
                        }
                    }

                    if (!Location.Value.HasFlag(location.Type))
                    {
                        return(false);
                    }
                }

                if (!Region.Value.HasFlag(location.Subtype))
                {
                    return(false);
                }
            }

            if (X.HasValue && Y.HasValue)
            {
                float x = husk.Location.X;
                float y = husk.Location.Y;

                if (!string.IsNullOrWhiteSpace(Id))
                {
                    if (Id != husk.Location.Id)
                    {
                        return(false);
                    }
                }

                if (Width > 0 && Height > 0)
                {
                    return(RegionF.Contains(X.Value, Y.Value, Width, Height, x, y));
                }

                if (Radius > 0)
                {
                    return(CircleF.Contains(X.Value, Y.Value, Radius, x, y));
                }

                return((Interaction == InteractionType.View ? husk.Hitbox.Sight : husk.Hitbox.Reach)
                       .Contains(X.Value, Y.Value));
            }

            if (!string.IsNullOrWhiteSpace(Id))
            {
                if (Depth == BindDepth.In)
                {
                    Location location = Engine.World.Find(Id);

                    return(location.GetChildren().Any(x => x.Id == husk.Location.Id));
                }

                return(Id == husk.Location.Id);
            }

            Console.WriteLine("No eligible regions were matched.");
            return(false);
        }
Example #7
0
        /// <summary>
        /// Prepares the WHERE clause of the SQL query from the <see cref="Filter"/> argument: WHERE ABC
        /// </summary>
        private string PrepareWhere(Func <Type, string> sources, JoinTree joinTree, SqlStatementParameters ps, int userId, DateTime?userToday)
        {
            // WHERE is cached
            if (_cachedWhere == null)
            {
                string whereFilter      = null;
                string whereInIds       = null;
                string whereInParentIds = null;

                if (Filter != null)
                {
                    whereFilter = QueryTools.FilterToSql(Filter, sources, ps, joinTree, userId, userToday);
                }

                if (Ids != null && Ids.Count() >= 1)
                {
                    if (Ids.Count() == 1)
                    {
                        string paramName = ps.AddParameter(Ids.Single());
                        whereInIds = $"[P].[Id] = @{paramName}";
                    }
                    else
                    {
                        var isIntKey    = (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == typeof(string);

                        // Prepare the ids table
                        DataTable idsTable = isIntKey ? RepositoryUtilities.DataTable(Ids.Select(id => new { Id = (int)id }))
                            : isStringKey?RepositoryUtilities.DataTable(Ids.Select(id => new { Id = id.ToString() }))
                                                 : throw new InvalidOperationException("Only string and Integer Ids are supported");

                        //
                        var idsTvp = new SqlParameter("@Ids", idsTable)
                        {
                            TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer Ids are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(idsTvp);
                        whereInIds = $"[P].[Id] IN (SELECT Id FROM @Ids)";
                    }
                }

                if (ParentIds != null)
                {
                    if (!ParentIds.Any())
                    {
                        if (IncludeRoots)
                        {
                            whereInParentIds = $"[P].[ParentId] IS NULL";
                        }
                    }
                    else if (ParentIds.Count() == 1)
                    {
                        string paramName = ps.AddParameter(ParentIds.Single());
                        whereInParentIds = $"[P].[ParentId] = @{paramName}";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                    else
                    {
                        var isIntKey    = (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int);
                        var isStringKey = KeyType == typeof(string);

                        // Prepare the data table
                        DataTable parentIdsTable = new DataTable();
                        string    propName       = "Id";
                        var       column         = new DataColumn(propName, KeyType);
                        if (isStringKey)
                        {
                            column.MaxLength = 450; // Just for performance
                        }
                        parentIdsTable.Columns.Add(column);
                        foreach (var id in ParentIds.Where(e => e != null))
                        {
                            DataRow row = parentIdsTable.NewRow();
                            row[propName] = id;
                            parentIdsTable.Rows.Add(row);
                        }

                        // Prepare the TVP
                        var parentIdsTvp = new SqlParameter("@ParentIds", parentIdsTable)
                        {
                            TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer ParentIds are supported"),
                                             SqlDbType = SqlDbType.Structured
                        };

                        ps.AddParameter(parentIdsTvp);
                        whereInParentIds = $"[P].[ParentId] IN (SELECT Id FROM @ParentIds)";
                        if (IncludeRoots)
                        {
                            whereInParentIds += " OR [P].[ParentId] IS NULL";
                        }
                    }
                }

                // The final WHERE clause (if any)
                string whereSql = "";

                var clauses = new List <string> {
                    whereFilter, whereInIds, whereInParentIds
                }.Where(e => e != null);
                if (clauses.Any())
                {
                    whereSql = clauses.Aggregate((c1, c2) => $"{c1}) AND ({c2}");
                    whereSql = $"WHERE ({whereSql})";
                }

                _cachedWhere = whereSql;
            }

            return(_cachedWhere);
        }