示例#1
0
文件: Startup.cs 项目: davutg/LookUp
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddEntityFramework().AddSqlite().AddDbContext<WorldContext>();
            services.AddTransient<SeedDataService>();
            services.AddScoped<IWorldRepository, WorldRepository>();
           
            using (var db = new WorldContext())
            {
                db.Database.EnsureCreated();
            }

            services.AddMvc(config=>
            {
                ////Redirects all requests to Https version
                //config.Filters.Add(new RequireHttpsAttribute());
                config.Filters.Add(new ResponseCacheFilter(new CacheProfile() { NoStore=true}));

            }).AddJsonOptions(opt=>
            {
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            services.AddIdentity<WorldUser, IdentityRole>(config =>
             {
                 config.User.RequireUniqueEmail = true;
                 config.Password.RequiredLength = 1;
                 config.Password.RequireLowercase = false;
                 config.Password.RequireNonLetterOrDigit = false;
                 config.Password.RequireDigit = false;
                 config.Cookies.ApplicationCookie.LoginPath = "/Auth/Login";
                 //Not to get Login Page for API calls
                 config.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
                 {
                     OnRedirectToLogin = context =>
                       {
                           if (context.Request.Path.StartsWithSegments("/api")
                           && context.Response.StatusCode==(int)HttpStatusCode.OK                           
                           )
                           {
                               context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                           }
                           else {
                               context.Response.Redirect(context.RedirectUri);
                           }
                           return Task.FromResult(0);
                       }
                 };
             }).AddEntityFrameworkStores<WorldContext>();
            
            //services.ConfigureCookieAuthentication(config =>
            //{
            //    config.LoginPath = "/Auth/Login";
            //});
#if DEBUG
            services.AddScoped<IMailService, MockMailService>();
#else
            services.AddScoped<IMailService, MockMailService>();
#endif
        }
示例#2
0
        private static void PrintHumanics(WorldContext context)
        {
            var humanics = context.Humanics.ToList();

            foreach (var humanic in humanics)
            {
                Console.WriteLine($"{humanic}");
            }
        }
        /// <summary>
        /// Create a camera entity.
        /// </summary>
        /// <param name="world">The world context.</param>
        /// <param name="centerX">The X point for the center of the camera.</param>
        /// <param name="centerY">The Y point for the center of the camera.</param>
        /// <param name="zoom">The zoom ratio of the camera.</param>
        /// <returns>The entity.</returns>
        public Entity CreateCamera(WorldContext world, float centerX, float centerY, float zoom)
        {
            Entity entity = world.EntityManager.CreateEntity();

            // Create the components
            world.EntityManager.AddComponent(entity, new CameraComponent());
            world.EntityManager.AddComponent(entity, new PositionComponent(new Vector2(centerX, centerY)));
            world.EntityManager.AddComponent(entity, new ScaleComponent(zoom));

            return entity;
        }
        /// <summary>
        /// Create a dwarf entity.
        /// </summary>
        /// <param name="world">The world context.</param>
        /// <param name="x">The x position.</param>
        /// <param name="y">The y position.</param>
        /// <returns>The entity.</returns>
        public Entity CreateDwarf(WorldContext world, float x, float y)
        {
            Entity entity = world.EntityManager.CreateEntity();

            // Prepare the args for the humanoid assembler
            var neckJoint = new HumanoidAssemblerArgs.RevoluteJoint(
                new Vector2(0, 11) * Const.PixelsToMeters,
                true,
                -MathHelper.Pi / 4,
                MathHelper.Pi / 4,
                false,
                0);
            var shoulderJoint = new HumanoidAssemblerArgs.RevoluteJoint(
                new Vector2(-2.5f, 8) * Const.PixelsToMeters,
                true,
                -MathHelper.Pi / 4,
                MathHelper.Pi / 4,
                false,
                0);
            var hipJoint = new HumanoidAssemblerArgs.RevoluteJoint(
                new Vector2(-2, 3) * Const.PixelsToMeters,
                true,
                -MathHelper.Pi / 4,
                MathHelper.Pi / 4,
                false,
                0);
            var args = new HumanoidAssemblerArgs(
                "dwarf",
                Const.CollisionGroupDwarf,
                new Vector2(x, y),                                  // Body position
                new Vector2(4, 0) * Const.PixelsToMeters,    // Right-left offset
                new Vector2(-5, 11) * Const.PixelsToMeters,  // Torso
                new Vector2(-2, 19) * Const.PixelsToMeters,  // Head
                new Vector2(-3, 9) * Const.PixelsToMeters,   // Arm
                new Vector2(-2, 3) * Const.PixelsToMeters,   // Leg
                new Vector2(-3, 20) * Const.PixelsToMeters,  // Beard
                neckJoint,                                          // Neck joint
                shoulderJoint,                                      // Shoulder joint
                hipJoint);                                          // Hip joint

            // Assemble the body
            var bodyAssembler = new HumanoidAssembler(world);
            bodyAssembler.AssembleBody(entity, args);

            return entity;
        }
        /// <summary>
        /// Load test level 1.
        /// </summary>
        /// <param name="world">The world context.</param>
        public void LoadTest1(WorldContext world)
        {
            // Create the camera entity
            this.entityFactory.CreateCamera(world, 1, 1, 1);

            // Add terrain
            this.entityFactory.CreateTerrain(
                world,
                -140,
                72,
                Const.PixelsToMeters,
                true,
                "Terrain\\Test1_Terrain",
                world.CurrentTime);

            // Add a dwarf
            this.entityFactory.CreateDwarf(world, 0, 50);
        }
    public void Cache(WorldContext worldContext)
    {
        sharkAIComponents = worldContext.GetComponentsContainer <SharkAIComponent>();

        h0ncker = worldContext.Get <InputComponent>(0).Entity;

        playersPositionComponent = h0ncker.GetComponent <PositionComponent>();

        timeComponent = worldContext.Get <TimeComponent>(0);

        vfxPoolComponent = worldContext.Get <VFXPoolComponent>(0);

        antagonistComponent = worldContext.Get <AntagonistComponent>(0);

        obstaclesLayer = LayerMask.NameToLayer("Obstacles");

        itemsLayer = LayerMask.NameToLayer("Items");

        enemiesLayer = LayerMask.NameToLayer("Enemies");

        playerLayer = LayerMask.NameToLayer("Player");
    }
示例#7
0
        static void Main(string[] args)
        {
            Database.SetInitializer(new ContextInitializer());

            using (var context = new WorldContext())
            {
                var areas = context.Areas.ToList();

                foreach (var area in areas)
                {
                    Console.WriteLine($"{area} is owned by {area.Owner}.");

                    PrintSiblings(area);
                    PrintHumanics(area);
                    PrintAreaChildren(area);
                }

                PrintHumanics(context);
            }

            Console.ReadLine();
        }
示例#8
0
 public void TableAttributeTest()
 {
     using (WorldContext context = new WorldContext())
     {
         context.Database.EnsureDeleted();
         context.Database.EnsureCreated();
         using (MySqlConnection conn = new MySqlConnection(context.Database.GetDbConnection().ConnectionString))
         {
             conn.Open();
             MySqlCommand cmd = new MySqlCommand("SHOW TABLES", conn);
             using (MySqlDataReader reader = cmd.ExecuteReader())
             {
                 Assert.True(reader.Read());
                 Assert.Equal("continentlist", reader.GetString(0)
                              , ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
                 Assert.True(reader.Read());
                 Assert.Equal("countrylist", reader.GetString(0)
                              , ignoreCase: true, ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true);
             }
         }
     }
 }
示例#9
0
        // GET: MerchantView
        public ActionResult Index()
        {
            WorldContext db = new WorldContext();

            var merchants = db.Merchants.Include("Items");             // Grab Merchants from database

            List <MerchantView> merchList = new List <MerchantView>(); // New list of MerchantView models

            foreach (Merchant m in merchants)                          // Transfer properties from Merchant to MerchantView and add to collection
            {
                merchList.Add(new MerchantView()
                {
                    Name      = m.Name,
                    Location  = m.Location,
                    Type      = m.Type,
                    ItemCount = new ItemCount {
                        itemCount = m.Items.Count
                    }
                });
            }

            return(View(merchList));
        }
        public void Can_generate_dynamic_delete_command_trees_for_self_ref_ia()
        {
            DbModel model;

            using (var context = new WorldContext())
            {
                model
                    = context
                      .InternalContext
                      .CodeFirstModel
                      .CachedModelBuilder
                      .BuildDynamicUpdateModel(ProviderRegistry.Sql2008_ProviderInfo);
            }

            var commandTreeGenerator
                = new ModificationCommandTreeGenerator(model);

            var commandTrees
                = commandTreeGenerator
                  .GenerateDelete(GetType().Namespace + ".Thing")
                  .ToList();

            Assert.Equal(1, commandTrees.Count());
        }
示例#11
0
 public void OneTimeTearDown()
 {
     using (WorldContext context = new WorldContext())
         context.Database.EnsureDeleted();
 }
        private void CreateTestPath(WorldContext world, TerrainComponent terrain, Point start, Point goal)
        {
            var testEntity = world.EntityManager.CreateEntity();

            // Create the path finder
            var pathFinder = new PathFinder(terrain);

            // Find the nodes along the path
            PathNode[] path;
            if (pathFinder.FindPath(start, goal, 1, 1, out path))
            {
                // Create the path component
                world.EntityManager.AddComponent(testEntity, new PathComponent(path));
            }
        }
示例#13
0
 public WorldCore()
 {
     _context = new WorldContext();
 }
        public void RestoreSaveData(object dataIn)
        {
            if (!enemy)
            {
                return;
            }

            EnemyData_v1 data = (EnemyData_v1)dataIn;

            if (data.loadID != LoadID)
            {
                return;
            }

            DaggerfallEntityBehaviour entityBehaviour = enemy.GetComponent <DaggerfallEntityBehaviour>();
            EnemySenses senses = enemy.GetComponent <EnemySenses>();
            EnemyMotor  motor  = enemy.GetComponent <EnemyMotor>();
            EnemyEntity entity = entityBehaviour.Entity as EnemyEntity;

            // Restore enemy career or class if different
            if (entity == null || entity.EntityType != data.entityType || entity.CareerIndex != data.careerIndex)
            {
                SetupDemoEnemy setupEnemy = enemy.GetComponent <SetupDemoEnemy>();
                setupEnemy.ApplyEnemySettings(data.entityType, data.careerIndex, data.mobileGender, data.isHostile, alliedToPlayer: data.alliedToPlayer);
                setupEnemy.AlignToGround();

                if (entity == null)
                {
                    entity = entityBehaviour.Entity as EnemyEntity;
                }
            }

            // Quiesce entity during state restore
            entity.Quiesce = true;

            // Restore enemy data
            entityBehaviour.gameObject.name = data.gameObjectName;
            enemy.transform.rotation        = data.currentRotation;
            entity.QuestFoeSpellQueueIndex  = data.questFoeSpellQueueIndex;
            entity.QuestFoeItemQueueIndex   = data.questFoeItemQueueIndex;
            entity.WabbajackActive          = data.wabbajackActive;
            entity.Items.DeserializeItems(data.items);
            entity.ItemEquipTable.DeserializeEquipTable(data.equipTable, entity.Items);
            entity.MaxHealth = data.startingHealth;
            entity.SetHealth(data.currentHealth, true);
            entity.SetFatigue(data.currentFatigue, true);
            entity.SetMagicka(data.currentMagicka, true);
            int team = data.team;

            if (team > 0)   // Added 1 to made backwards compatible. 0 = no team saved
            {
                entity.Team = (MobileTeams)(team - 1);
            }
            motor.IsHostile             = data.isHostile;
            senses.HasEncounteredPlayer = data.hasEncounteredPlayer;

            // Restore enemy position and migrate to floating y support for exteriors
            // Interiors seem to be working fine at this stage with any additional support
            // Dungeons are not involved with floating y and don't need any changes
            WorldContext enemyContext = GetEnemyWorldContext(enemy);

            if (enemyContext == WorldContext.Exterior)
            {
                RestoreExteriorPositionHandler(enemy, data, enemyContext);
            }
            else
            {
                // Everything else
                enemy.transform.position = data.currentPosition;
            }

            // Disable dead enemies
            if (data.isDead)
            {
                entityBehaviour.gameObject.SetActive(false);
            }

            // Restore quest resource link
            enemy.QuestSpawn = data.questSpawn;
            if (enemy.QuestSpawn)
            {
                // Add QuestResourceBehaviour to GameObject
                QuestResourceBehaviour questResourceBehaviour = entityBehaviour.gameObject.AddComponent <QuestResourceBehaviour>();
                questResourceBehaviour.RestoreSaveData(data.questResource);

                // Destroy QuestResourceBehaviour if no actual quest properties are restored from save
                if (questResourceBehaviour.QuestUID == 0 || questResourceBehaviour.TargetSymbol == null)
                {
                    enemy.QuestSpawn = false;
                    Destroy(questResourceBehaviour);
                }
            }

            // Restore instanced effect bundles
            GetComponent <EntityEffectManager>().RestoreInstancedBundleSaveData(data.instancedEffectBundles);

            // Resume entity
            entity.Quiesce = false;
        }
示例#15
0
        static void Main(string[] args)
        {
            //--------------------------------------------------------------------------------------------------------------------------
            // Module 3
            // Setup

            var dbContext = new WorldContext();
            // var continents = dbContext.Continent.ToList();
            // foreach (var c in continents)
            // {
            //     System.Console.WriteLine($"ID:{c.Id} Name:{c.Name}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Where Operator
            // Find out the countries with a population greater than 100 million

            // var countries = dbContext.Country
            //     .Where(c => c.Population >= 100000000);
            // // var countries = from c in dbContext.Country where c.Population > 100000000 select c;
            // foreach (var c in countries)
            // {
            //     Console.WriteLine($"{c.Name} => {c.Population}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The All Operator
            // Print whether all cities' population are greater than 1000

            // var result = dbContext.City.All(c => c.Population > 1000);
            // Console.WriteLine(result);

            //--------------------------------------------------------------------------------------------------------------------------
            // The Any Operator
            // Is there any continent data stored in the database?
            // Is there any city with a population that is greater than 10 million ?

            // var r1 = dbContext.Continent.Any();
            // var r2 = dbContext.City.Any(c => c.Population > 10000000);
            // Console.WriteLine(r1);
            // Console.WriteLine(r2);

            //--------------------------------------------------------------------------------------------------------------------------
            // The Contains Operator
            // Find out whether a given city is in the database

            // var seattle = new City { Name = "Seattle", District = "Washington" };
            // var result = dbContext.City.ToList()
            //     .Contains(seattle, new CityEqualityComparer());
            // System.Console.WriteLine(result);

            //--------------------------------------------------------------------------------------------------------------------------
            // Include Extension Method

            // var continents = dbContext.Continent
            //     .Include(nameof(Continent.Country));
            // foreach (var c in continents)
            // {
            //     Console.WriteLine($"{c.Name.PadRight(16)} {c.Country.Count}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Select Operator
            // Could you list the name of countries with a population greater than 1 billion?

            // var names = dbContext.Country
            //       .Where(c => c.Population > 100000000)
            //       .Select(c => c.Name);
            // foreach (var n in names)
            // {
            //     System.Console.WriteLine(n);
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The SelectMany Operator
            // Could you list the name of counties in North America and South America?

            // var names = dbContext.Continent
            //       .Include(nameof(Continent.Country))
            //       .Where(c => c.Name == "North America" || c.Name == "South America")
            //       .SelectMany(c => c.Country).Select(c => c.Name);

            // foreach (var n in names)
            // {
            //     System.Console.WriteLine(n);
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Intersect, Except, and Union Operator
            // Countries that either have a large surface area or have a large population.
            // Countries that have both large area and large population.
            // Countries that have a large area but not a large population.

            // var bigArea = dbContext.Country
            //     .OrderByDescending(c => c.SurfaceArea).Take(10);
            // var bigPopulation = dbContext.Country
            //     .OrderByDescending(c => c.Population).Take(10);

            // var r1 = bigArea.Union(bigPopulation);
            // var r2 = bigArea.Intersect(bigPopulation);
            // var r3 = bigArea.Except(bigPopulation);

            // Console.WriteLine("[Big Area or Big Population]");
            // foreach (var r in r1)
            // {
            //     Console.WriteLine(r.Name);
            // }

            // Console.WriteLine("========================");
            // Console.WriteLine("[Big Area and Big Population]");
            // foreach (var r in r2)
            // {
            //     Console.WriteLine(r.Name);
            // }

            // Console.WriteLine("========================");
            // Console.WriteLine("[Big Area but Not Big Population]");
            // foreach (var r in r3)
            // {
            //     Console.WriteLine(r.Name);
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Distinct Operator
            // Could you find out the continents that have countries in them? I do not think there are any countries in Antarctica, lets see if this is true.

            // var continents = dbContext.Country
            //       .Include(nameof(Country.Continent))
            //       .Select(c => c.Continent).Distinct();
            // foreach (var c in continents)
            // {
            //     System.Console.WriteLine(c.Name);
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The OrderBy and ThenByDescending Operator
            // Could you sort all counties by its continent, and then sort the counties in the same continent by population in the descending order?

            // var countries = dbContext.Country
            // .Include(nameof(Country.Continent))
            // .OrderBy(c => c.Continent.Name)
            // .ThenByDescending(c => c.Population);
            // // var countries =
            // //     from c in dbContext.Country.Include(nameof(Country.Continent))
            // //     orderby c.Continent.Name, c.Population descending
            // //     select c;

            // foreach (var c in countries)
            // {
            //     Console.WriteLine($"{c.Continent.Name} {c.Name} {c.Population}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The First, Last, and ElementAt Operator
            // Could you find out the country that has:
            // the largest surface area
            // the smallest surface area
            // the third largest surface area

            // var sorted = dbContext.Country.OrderByDescending(c => c.SurfaceArea).ToList();
            // var largest = sorted.First();
            // var thirdLarget = sorted.ElementAt(2);
            // var smallest = sorted.Last();

            // Console.WriteLine($"Largest: {largest.Name} {largest.SurfaceArea}");
            // Console.WriteLine($"Third: {thirdLarget.Name} {thirdLarget.SurfaceArea}");
            // Console.WriteLine($"Smallest: {smallest.Name} {smallest.SurfaceArea}");

            //--------------------------------------------------------------------------------------------------------------------------
            // The Single and SingleOrDefault Operator
            // Could you find out whether there is a city called: Seattle Kirkland Clara

            // try
            // {
            //     var seattle = dbContext.City.Single(c => c.Name == "Seattle");
            //     Console.WriteLine($"There is a city called Seattle.");
            // }
            // catch
            // {
            //     Console.WriteLine($"There maybe zero or more than one Seattle.");
            // }

            // try
            // {
            //     var foundOneKirkland = dbContext.City.Single(c => c.Name == "Kirkland");
            //     Console.WriteLine($"There is a city called Kirkland.");
            // }
            // catch
            // {
            //     Console.WriteLine($"There maybe zero or more than one Kirkland.");
            // }

            // try
            // {
            //     var foundOneSantaClara = dbContext.City.Single(c => c.Name == "Santa Clara");
            //     Console.WriteLine($"There is a city called Santa Clara.");
            // }
            // catch
            // {
            //     Console.WriteLine($"There maybe zero or more than one Santa Clara.");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Skip and Take Operator
            // Given the countries sorted by their surface area in a descending order, could you find out the:
            // largest five countries
            // countries in the 21st to 25th place
            // smallest five countries

            // var sorted = dbContext.Country.OrderByDescending(c => c.SurfaceArea);
            // var largest5 = sorted.Take(5);
            // var the21to25 = sorted.Skip(20).Take(5);
            // var smallest5 = sorted.ToList().TakeLast(5);

            // Console.WriteLine("[Largest 5]");
            // foreach (var c in largest5)
            // {
            //     Console.WriteLine($"{c.Name} {c.SurfaceArea}");
            // }

            // Console.WriteLine("===================");
            // Console.WriteLine("[Largest 21 to 25]");
            // foreach (var c in the21to25)
            // {
            //     Console.WriteLine($"{c.Name} {c.SurfaceArea}");
            // }

            // Console.WriteLine("===================");
            // Console.WriteLine("[Smallest 5]");
            // foreach (var c in smallest5)
            // {
            //     Console.WriteLine($"{c.Name} {c.SurfaceArea}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The ToArray, ToList, ToDictionary, and ToLookup Operator
            // Retrieve all continents and store them in an array?
            // Retrieve all continents and store them in a list?
            // Generate a dictionary for looking up the population of countries ?
            // Generate a Lookup < K, V > object for looking up country names by continent name ?

            // var array = dbContext.Continent.ToArray();
            // var list = dbContext.Continent.ToList();
            // var dict = dbContext.Country.ToDictionary(c => c.Name, c => c.Population);
            // var lookup = dbContext.Country.Include(nameof(Country.Continent))
            //     .ToLookup(c => c.Continent.Name, c => c.Name);

            // Console.WriteLine(array.Length);
            // Console.WriteLine(list.Count);
            // Console.WriteLine(dict["China"]);
            // Console.WriteLine(string.Join(",", lookup["Antarctica"]));

            //--------------------------------------------------------------------------------------------------------------------------
            // The Max, Min, Count and Sum Operator
            // Find the largest country area in Europe
            // the smallest country area in Europe
            // how many counties in Europe
            // the total population in Europe

            // var countries = dbContext.Country
            //     .Include(nameof(Country.Continent))
            //     .Where(c => c.Continent.Name == "Europe");

            // var largest = countries.Max(c => c.SurfaceArea);
            // var smallest = countries.Min(c => c.SurfaceArea);
            // var count = countries.Count();
            // var totalPopulation = countries.Sum(c => c.Population);

            // Console.WriteLine($"Europe Largest Country Area: {largest}");
            // Console.WriteLine($"Europe Smallest Country Area: {smallest}");
            // Console.WriteLine($"Europe Country Count: {count}");
            // Console.WriteLine($"Europe Total Population: {totalPopulation}");

            //--------------------------------------------------------------------------------------------------------------------------
            // The GroupBy Operator
            // Could you find the top 3 largest countries of each continent?

            // var countries = dbContext.Country
            //     .Include(nameof(Country.Continent))
            //     .OrderByDescending(c => c.SurfaceArea);

            // var result = countries.GroupBy(c => c.Continent.Name, c => c.Name)
            //     .Select(g => $"{g.Key}: {string.Join(",", g.Take(3))}");
            //// var result = from c in countries
            ////              group c.Name by c.Continent.Name into g
            ////              select $"{g.Key}: {string.Join(",", g.Take(3))}";

            // foreach (var r in result)
            // {
            //     Console.WriteLine(r);
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The Join Operator


            // var continents = dbContext.Continent.OrderBy(c => c.Name);
            // var countries = dbContext.Country.OrderBy(c => c.Name);

            // var result = continents.Join(countries,
            // c => c.Id, c => c.ContinentId,
            // (ctn, ctry) => new { Continent = ctn.Name, Country = ctry.Name });
            // // var result = from ctn in continents
            // //              join ctry in countries
            // //              on ctn.Id equals ctry.ContinentId
            // //              select new { Continent = ctn.Name, Country = ctry.Name };

            // foreach (var r in result)
            // {
            //     Console.WriteLine($"{r.Continent}\t {r.Country}");
            // }

            //--------------------------------------------------------------------------------------------------------------------------
            // The GroupJoin Operator

            var continents = dbContext.Continent.OrderBy(c => c.Name);
            var countries  = dbContext.Country.OrderBy(c => c.Name);

            var result = continents.GroupJoin(countries,
                                              ctn => ctn.Id, ctry => ctry.ContinentId,
                                              (ctn, g) => new { Continent = ctn.Name, CountryCount = g.Count() }
                                              );

            // var result = from ctn in continents
            //              join ctry in countries
            //              on ctn.Id equals ctry.ContinentId into g
            //              select new { Continent = ctn.Name, CountryCount = g.Count() };
            foreach (var item in result)
            {
                Console.WriteLine($"{item.Continent}: {item.CountryCount}");
            }
        }
示例#16
0
 public HomeController(IMailService service, WorldContext context)
 {
     _mailService = service;
     _context     = context;
 }
示例#17
0
 public SeedDataService(WorldContext context, UserManager<WorldUser> userManager,ILogger<SeedDataService> logger)
 {
     _context = context;
     _userManager = userManager;
     _logger = logger;
 }
示例#18
0
 public CountryController(WorldContext db)
 {
     this.db = db;
 }
示例#19
0
 public SpaceObjects GetInstanceFromData(WorldContext worldContext)
 {
     return(new SpaceObjects(worldContext, this));
 }
示例#20
0
 public StarSystems GetInstanceFromData(WorldContext worldContext)
 {
     return(new StarSystems(worldContext, this));
 }
示例#21
0
 public StopsController(WorldContext context)
 {
     _context = context;
 }
示例#22
0
 public WorldRepository(WorldContext context, ILogger<WorldRepository> logger)
 {
     this.context = context;
     this.logger = logger;
 }
示例#23
0
 public TheWorldRepository(WorldContext context, ILogger<TheWorldRepository> logger )
 {
     _logger = logger;
     _context = context;
 }
        public void Can_generate_dynamic_delete_command_trees_for_self_ref_ia()
        {
            DbModel model;

            using (var context = new WorldContext())
            {
                model
                    = context
                        .InternalContext
                        .CodeFirstModel
                        .CachedModelBuilder
                        .BuildDynamicUpdateModel(ProviderRegistry.Sql2008_ProviderInfo);
            }

            var commandTreeGenerator
                = new ModificationCommandTreeGenerator(model);

            var commandTrees
                = commandTreeGenerator
                    .GenerateDelete(GetType().Namespace + ".Thing")
                    .ToList();

            Assert.Equal(1, commandTrees.Count());
        }
    public void Handle(WorldContext worldContext)
    {
        for (int i = 0; i < antagonistComponents.Count; i++)
        {
            var antagonistComponent = (AntagonistComponent)antagonistComponents[i];

            if (antagonistComponent.IsMonologuing)
            {
                continue;
            }

            if (antagonistComponent.CurrentStage >= antagonistComponent.Settings.StageSettings.Length)
            {
                worldContext.Get <GameStateComponent>(0).GameState = GameState.VICTORY;

                return;
            }

            var currentStage = antagonistComponent.Settings.StageSettings[antagonistComponent.CurrentStage];

            int scoreCap = currentStage.ScoreCap;

            if (antagonistComponent.Score >= scoreCap)
            {
                gameStateComponent.GameState = GameState.PAUSED;

                var vfxInstance = vfxPoolComponent.VFXPool.Pop("Message (long)", currentStage.TextTypingDuration + 0.41f);

                var typer = vfxInstance.GameObject.GetComponent <Typer>();

                typer.Text = currentStage.TextVariants[UnityEngine.Random.Range(0, currentStage.TextVariants.Length)];

                typer.TextColor = currentStage.TextColor;

                vfxInstance.GameObject.transform.SetParent(canvasComponent.Canvas.transform, true);

                Transform messageTransform = antagonistComponent.MessageTransform;

                vfxInstance.GameObject.transform.position = messageTransform.position;

                vfxInstance.GameObject.GetComponent <AnimatedPopup>().StayDuration = currentStage.TextTypingDuration;

                Sequence sequence = DOTween.Sequence();

                sequence.Append(cameraComponent.Camera.transform.DOShakePosition(
                                    currentStage.TextTypingDuration + 0.41f,
                                    new Vector3(1f, 1f, 0f).normalized *currentStage.CameraShakeStrength, 15));

                sequence.InsertCallback(
                    currentStage.TextTypingDuration + 0.41f,
                    () =>
                {
                    gameStateComponent.GameState = GameState.RUNNING;

                    antagonistComponent.IsMonologuing = false;
                });

                vfxInstance.GameObject.SetActive(true);

                antagonistComponent.CurrentStage++;

                antagonistComponent.IsMonologuing = true;
            }
        }
    }
示例#26
0
 public LoresController(WorldContext context)
 {
     _context = context;
 }
示例#27
0
 public SeedDataService(WorldContext context, UserManager <WorldUser> userManager, ILogger <SeedDataService> logger)
 {
     _context     = context;
     _userManager = userManager;
     _logger      = logger;
 }
示例#28
0
        static void Main(string[] args)
        {
            var ctx = new WorldContext();

            ctx.Database.EnsureCreated();

            // Reset example
            ctx.Database.ExecuteSqlCommand("delete from Border");
            ctx.Database.ExecuteSqlCommand("delete from country");

            // Create countries
            var de = new Country();

            de.Name = "Germany";
            ctx.Countries.Add(de);
            ctx.SaveChanges();

            var nl = new Country();

            nl.Name = "Netherlands";
            ctx.Countries.Add(nl);
            nl.AddBorderToCounty(de);
            ctx.SaveChanges();

            var dk = new Country();

            dk.Name = "Denmark";
            ctx.Countries.Add(dk);
            dk.AddBorderToCounty(de);
            ctx.SaveChanges();

            var be = new Country();

            be.Name = "Belgium";
            ctx.Countries.Add(be);
            be.AddBorderToCounty(de);
            be.AddBorderToCounty(nl);
            ctx.SaveChanges();

            var fr = new Country();

            fr.Name = "France";
            ctx.Countries.Add(fr);
            fr.AddBorderToCounty(de);
            ctx.SaveChanges();

            var cz = new Country();

            cz.Name = "Czech Republic";
            ctx.Countries.Add(cz);
            cz.AddBorderToCounty(de);
            ctx.SaveChanges();

            var lu = new Country();

            lu.Name = "Luxembourg";
            ctx.Countries.Add(lu);
            lu.AddBorderToCounty(de);
            lu.AddBorderToCounty(fr);
            lu.AddBorderToCounty(be);
            ctx.SaveChanges();

            var pl = new Country();

            pl.Name = "Poland";
            ctx.Countries.Add(pl);
            pl.AddBorderToCounty(de);
            pl.AddBorderToCounty(cz);
            ctx.SaveChanges();

            var at = new Country();

            at.Name = "Austria";
            ctx.Countries.Add(at);
            at.AddBorderToCounty(de);
            at.AddBorderToCounty(cz);
            ctx.SaveChanges();

            var ch = new Country();

            ch.Name = "Switzerland";
            ctx.Countries.Add(ch);
            ch.AddBorderToCounty(de);
            ch.AddBorderToCounty(fr);
            ch.AddBorderToCounty(at);
            ctx.SaveChanges();

            Console.WriteLine("All countries with their borders");
            foreach (var country in ctx.Countries)
            {
                Console.WriteLine("--------- " + country.Name);

                // now explicitly load the neighboring countries, as Lazy Loading in EFC does not work
                //var borders1 = ctx.Countries.Where(x => x.IncomingBorders.Any(y => y.Country_Id == country.Id)).ToList();
                //var borders2 = ctx.Countries.Where(x => x.OutgoingBorders.Any(y => y.Country_Id1 == country.Id)).ToList();
                //var allborders = borders1.Union(borders2).OrderBy(x=>x.Name);;

                // better: encapsulated in the context class:
                var allborders = ctx.GetNeigbours(country.Id);

                foreach (var neighbour in allborders)
                {
                    Console.WriteLine(neighbour.Name);
                }
            }

            Console.WriteLine("=== DONE!");
            Console.ReadLine();
        }
示例#29
0
 public PlayerRandomNameRepository(WorldContext worldContext)
 {
     _worldContext = worldContext;
 }
示例#30
0
 public WorldContextSeedData(WorldContext context, UserManager<WorldUser> userManager)
 {
     this.context = context;
     this.userManager = userManager;
 }
 public WorldContextSeedData(WorldContext context)
 {
     _context = context;
 }
示例#32
0
        static void Main(string[] args)
        {
            // Read data
            var dbContext = new WorldContext();
            // var continents = dbContext.Continent.Include(c => c.Country)
            //         .ThenInclude(country => country.City);

            // // Construct XML
            // var rootElement = new XElement("world");
            // foreach (var continent in continents)
            // {
            //     var continentElement = new XElement("continent");
            //     continentElement.Add(new XAttribute("name", continent.Name));
            //     foreach (var country in continent.Country)
            //     {
            //         var countryElement = new XElement("country");
            //         countryElement.Add(new XAttribute("code", country.Code));
            //         countryElement.Add(new XAttribute("name", country.Name));
            //         countryElement.Add(new XAttribute("area", country.SurfaceArea));
            //         countryElement.Add(new XAttribute("population", country.Population));
            //         foreach (var city in country.City)
            //         {
            //             var cityElement = new XElement("city");
            //             cityElement.Add(new XAttribute("id", city.Id));
            //             cityElement.Add(new XAttribute("name", city.Name));
            //             cityElement.Add(new XAttribute("population", city.Population));
            //             countryElement.Add(cityElement);
            //         }
            //         continentElement.Add(countryElement);
            //     }
            //     rootElement.Add(continentElement);
            // }

            // // Persist in-memory XML data to XML file
            // var writer = XmlWriter.Create(@"./world.xml");
            // rootElement.WriteTo(writer);
            // writer.Flush();
            // writer.Close();
            // System.Console.WriteLine("DONE!");

            //---------------------------------------------------------------------------------

            var rootElement = XElement.Load(@"./world.xml");

            // Query 1:
            var continents = rootElement.Elements()
                             .Select(e => e.Attribute("name").Value);

            foreach (var item in continents)
            {
                System.Console.WriteLine(item);
            }

            // Query 2:
            var northAmericaPop = rootElement.Elements()
                                  .Single(e => e.Attribute("name").Value == "North America")
                                  .Descendants("country")
                                  .Sum(e => int.Parse(e.Attribute("population").Value));

            System.Console.WriteLine(northAmericaPop);
        }
示例#33
0
 public WorldRepository(WorldContext context, ILogger<WorldRepository> logger)
 {
     _context = context;
     _logger = logger;
 }
示例#34
0
        /// <summary>
        ///    Deserializes spacecraft from given steam using project's json settings.
        /// </summary>
        public static Spacecraft DeserializeFrom(Stream stream, WorldContext worldContext)
        {
            var data = Serialization.DeserializeDataFromJson <SpacecraftData>(stream);

            return((Spacecraft)data.GetInstanceFromData(worldContext));
        }
示例#35
0
 public SpaceObjects(WorldContext worldContext, SpaceObjectsData data)
 {
     WorldContext            = worldContext;
     _spaceObjectsDictionary = new Dictionary <Guid, SpaceObject>();
 }
示例#36
0
 public static ImmutableList <Tutorial> GetTutorialTriggers()
 {
     using (var context = new WorldContext())
         return(context.Tutorial.ToImmutableList());
 }
示例#37
0
        void RestoreExteriorPositionHandler(GameObject player, PlayerPositionData_v1 data, WorldContext playerContext)
        {
            // If player context matches serialized world context then player was saved after floating y change
            // Need to get relative difference between current and serialized world compensation to get actual y position
            if (playerContext == data.worldContext)
            {
                float diffY = GameManager.Instance.StreamingWorld.WorldCompensation.y - data.worldCompensation.y;
                player.transform.position = data.position + new Vector3(0, diffY, 0);
                return;
            }

            // Otherwise we migrate a legacy exterior position by adjusting for world compensation
            player.transform.position = data.position + GameManager.Instance.StreamingWorld.WorldCompensation;
        }
示例#38
0
 public static ImmutableList <Model.Disable> GetDisables()
 {
     using (var context = new WorldContext())
         return(context.Disable.ToImmutableList());
 }
示例#39
0
 public RaceController(WorldContext db)
 {
     this.db = db;
 }
 /// <summary>
 /// Initializes a new instance of the HumanoidAssembler class.
 /// </summary>
 /// <param name="world">The world context.</param>
 public HumanoidAssembler(WorldContext world)
 {
     this.world = world;
 }
示例#41
0
 public AppController(IMailService mailService, IConfigurationRoot config, WorldContext context)
 {
     _mailService = mailService;
     _config      = config;
     _context     = context;
 }
 public LocationsController(WorldContext context)
 {
     _context = context;
 }
        void RestoreExteriorPositionHandler(DaggerfallEnemy enemy, EnemyData_v1 data, WorldContext enemyContext)
        {
            // If enemy context matches serialized world context then enemy was saved after floating y change
            // Need to get relative difference between current and serialized world compensation to get actual y position
            if (enemyContext == data.worldContext)
            {
                float diffY = GameManager.Instance.StreamingWorld.WorldCompensation.y - data.worldCompensation.y;
                enemy.transform.position = data.currentPosition + new Vector3(0, diffY, 0);
                return;
            }

            // Otherwise we migrate a legacy exterior position by adjusting for world compensation
            enemy.transform.position = data.currentPosition + GameManager.Instance.StreamingWorld.WorldCompensation;
        }
示例#44
0
 public WorldsController(WorldContext context)
 {
     _context = context;
 }
 public WorldContextSeedData(WorldContext context,UserManager<WorldUser> userManager)
 {
     _context = context;
     _userManager = userManager;
 }
        /// <summary>
        /// Create a terrain entity from a bitmap image.
        /// </summary>
        /// <param name="world">The world context.</param>
        /// <param name="x">The top-left X position in world-coordinates.</param>
        /// <param name="y">The top-left Y position in world-coordinates.</param>
        /// <param name="scale">The scale ratio for the terrain.</param>
        /// <param name="isCollidable">Indicates whether the terrain can be collided with.</param>
        /// <param name="terrainBitmapName">The name of the terrain bitmap.</param>
        /// <param name="currentTime">The current time used as the terrain creation time.</param>
        /// <returns>The entity.</returns>
        public Entity CreateTerrain(
            WorldContext world,
            float x,
            float y,
            float scale,
            bool isCollidable,
            string terrainBitmapName,
            TimeSpan currentTime)
        {
            Entity entity = world.EntityManager.CreateEntity();

            // Load the terrain texture
            Texture2D texture = world.Resources.Load<Texture2D>(terrainBitmapName);

            // Create the terrain quad tree
            var terrainFactory = new TerrainFactory();
            ClipQuadTree<TerrainData> terrainQuadTree = terrainFactory.CreateTerrainQuadTree(texture, currentTime);

            // Build the path nodes from the terrain quad tree
            var pathBuilder = new PathBuilder(terrainQuadTree, 30, 5);
            Dictionary<Point, LinkedPathNode> pathNodes = pathBuilder.BuildPathNodes();

            // Create the terrain component
            var cTerrain = new TerrainComponent(terrainQuadTree, isCollidable, pathNodes);

            // Create the physics body. Initially this has no fixtures, as those are populated dynamically
            var body = new Body(world.Physics);
            var cPhysics = new PhysicsComponent(body);

            // Add components to entity
            world.EntityManager.AddComponent(entity, cTerrain);
            world.EntityManager.AddComponent(entity, cPhysics);
            world.EntityManager.AddComponent(entity, new PositionComponent(body, new Vector2(x, y)));
            world.EntityManager.AddComponent(entity, new ScaleComponent(scale));

            return entity;
        }