static void Main(string[] args)
        {
            var tests = new List <TestScenario>();

            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test1()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test2()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test3()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test4()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test5()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test6()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test7()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test8()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test9()));
            tests.Add(new TestScenario(SolverType.PrioritizedPlannerClassesH, InstanceDescription.Test10()));


            TestingUtils.RunTests(tests, 5);

            /*
             * var wi = InstanceParser.Parse2("../../../../../src_py/test_warehouse.txt");
             * var cbs = new CBS(wi, 80000);
             * cbs.FindTours();
             */

            //TestingUtils.RunTests(PrioritizedPlanner, 10);

            Console.ReadKey();
        }
示例#2
0
        public static void UpdateReplication(InstanceDescription selfInstance, IInstanceEnumerator instanceEnumerator, string databaseName)
        {
            // Setup replication:
            using (var documentStore = new DocumentStore()
            {
                Url = selfInstance.InternalUrl
            })
            {
                log.Info("Ensuring database {0} is replicated from {1} at {2}", databaseName, selfInstance.Id, selfInstance.InternalUrl);

                documentStore.Initialize();

                using (var session = documentStore.OpenSession(databaseName))
                {
                    var documentId = new ReplicationDocument().Id; // Just to stay in sync with changes from RavenDb

                    var replicationDocument = session.Load <ReplicationDocument>(documentId) ?? new ReplicationDocument();

                    replicationDocument.Destinations = EnumerateReplicationDestinations(instanceEnumerator, selfInstance.IsRoleMaster).Select(i => new ReplicationDestination()
                    {
                        Url = string.Format("{0}/databases/{1}", i.InternalUrl, databaseName)
                    }).ToList();
                    session.Store(replicationDocument);
                    session.SaveChanges();
                }
            }
        }
示例#3
0
 /// <summary>
 /// 服务启动配置实例
 /// </summary>
 /// <param name="services">服务实例(这些服务将以单例模式运行)。</param>
 /// <param name="serverConfig">服务器配置</param>
 /// <param name="instanceDescription">服务器实例描述</param>
 /// <param name="loggerFactory">日志</param>
 public ThriftyBootstrap(
     IEnumerable <Object> services,
     ThriftyServerOptions serverConfig,
     InstanceDescription instanceDescription,
     ILoggerFactory loggerFactory = null) : this(new InstanceServiceLocator(services), serverConfig, instanceDescription, loggerFactory)
 {
     Guard.ArgumentNotNull(services, nameof(services));
 }
示例#4
0
        private void Logger()
        {
            var customLogger = _diHelper.GetCustomLogger();

            if (customLogger != null)
            {
                RegisterInstance <ILog>(customLogger);
            }
            else
            {
                LogConfigurations.ConfigureLogglyAppender();
                RegisterInstance <ILog>(LogManager.GetLogger(InstanceDescription.ToString()));
            }
        }
示例#5
0
        public static void UpdateReplication(InstanceDescription selfInstance, IInstanceEnumerator instanceEnumerator, DocumentDatabase database)
        {
            log.Info("Ensuring default database is replicated from {0} at {1}", selfInstance.Id, selfInstance.InternalUrl);

            var documentId = new ReplicationDocument().Id;

            var replicationDocument = new ReplicationDocument()
            {
                Destinations =
                    EnumerateReplicationDestinations(instanceEnumerator, selfInstance.IsRoleMaster).
                    Select(i => new ReplicationDestination()
                {
                    Url = i.InternalUrl
                }).
                    ToList()
            };

            database.Put(documentId, null, RavenJObject.FromObject(replicationDocument), new RavenJObject(), null);
        }
示例#6
0
        /// <summary>
        /// 服务启动配置实例
        /// </summary>
        /// <param name="serviceLocator">服务定位器</param>
        /// <param name="serverConfig">服务器配置</param>
        /// <param name="instanceDescription">服务器实例描述</param>
        /// <param name="loggerFactory">日志</param>
        public ThriftyBootstrap(
            IServiceLocator serviceLocator,
            ThriftyServerOptions serverConfig,
            InstanceDescription instanceDescription,
            ILoggerFactory loggerFactory = null)
        {
            Guard.ArgumentNotNull(serviceLocator, nameof(serviceLocator));
            Guard.ArgumentNotNull(serverConfig, nameof(serverConfig));
            Guard.ArgumentNotNull(instanceDescription, nameof(instanceDescription));

            this._logger = this._loggerFactory?.CreateLogger <ThriftyBootstrap>() ?? (ILogger)NullLogger.Instance;

            this._serverConfig = serverConfig;
            var checher = new ThriftyHealthCheck();

            this._serviceLocator      = new DelegateServiceLocator((ctx, x) => x == typeof(IHealthCheck) ? checher : serviceLocator.GetService(ctx, x));
            this._instanceDescription = instanceDescription;
            this._loggerFactory       = loggerFactory;
            this._services            = new HashSet <ThriftyServiceDescriptor> {
                new ThriftyServiceDescriptor(typeof(IHealthCheck))
            };
        }
 public IEnumerable<InstanceDescription> GetReplicationTargets(InstanceDescription self, IEnumerable<InstanceDescription> otherInstances)
 {
     return otherInstances;
 }
示例#8
0
 public TestScenario(SolverType solver, InstanceDescription description)
 {
     this.solver      = solver;
     this.description = description;
 }
示例#9
0
        private static void ShellEvents_EngineStarted(SchubertOptions options, IServiceProvider serviceProvider)
        {
            ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();
            ILogger        logger        = loggerFactory.CreateLogger("Schubert");

            //这里启动 Swifty 服务端。
            if (!(_serviceExports?.IsEmpty ?? true)) //其实不可能为空,防止手贱的反射该方法报错。
            {
                IOptions <SwiftyOptions>  swiftyOptions = serviceProvider.GetRequiredService <IOptions <SwiftyOptions> >();
                IOptions <NetworkOptions> netOptions    = serviceProvider.GetRequiredService <IOptions <NetworkOptions> >();

                /***************
                *
                * 地址是个棘手的问题
                *
                * 1、bindingAddress 为指定的 ip 地址:
                * 此时我们默认使用这个绑定地址即是他想要注册的地址。
                *
                * 2、考虑 bindingAddress 为空的情况:
                * 为空时候认为他要使用 network 配置,如果要使用 binding any 必须显式设置为 0.0.0.0
                * 因此,当 bindingAddress 为空时候我们就默认也注册 network 配置的地址
                *
                * 3、再来一种情况,考虑 bindingAddress 设置为  any(即 0.0.0.0) :
                * 这时候总不能向注册中心去注册 0.0.0.0 吧
                * 因此提供一个 public address 单独作为注册地址才能完整的解决问题
                * 考虑当 public address 为空,bind address 指定了 0.0.0.0:
                * 这种情况直接再读一次 network 配置,认为他要 bind 端口是本机所有网卡,但是只注册 network 的配置。
                *
                * 似乎没有什么逻辑漏洞,有的话 Swifty 里会再次为我们检查,详情见 swifty 实现。
                *
                ***************/

                if (swiftyOptions.Value.Server.BindingAddress.IsNullOrWhiteSpace())
                {
                    swiftyOptions.Value.Server.BindingAddress = GetNetworkAddress(netOptions);
                }
                var address = swiftyOptions.Value.Server.PublicAddress.IfNullOrWhiteSpace(swiftyOptions.Value.Server.BindingAddress);
                address = address.CaseSensitiveEquals("0.0.0.0") ? GetNetworkAddress(netOptions) : address;


                bool enableEureka = !String.IsNullOrWhiteSpace(swiftyOptions.Value.Server.Eureka.EurekaServerServiceUrls);

                if (address.IsNullOrWhiteSpace() && enableEureka)
                {
                    string optionProperty = $"{nameof(SwiftyOptions)}.{nameof(SwiftyOptions.Server)}.{nameof(ExtendedSwiftyServerOptions.PublicAddress)}";
                    string bindProperty   = $"{nameof(SwiftyOptions)}.{nameof(SwiftyOptions.Server)}.{nameof(ExtendedSwiftyServerOptions.BindingAddress)}";

                    string error = $"无法确定 Swifty 服务要发布的地址,考虑以下三种方式:{System.Environment.NewLine}" +
                                   $"1、请使用 '{nameof(NetworkOptions)}' 配置本机网络。{System.Environment.NewLine}" +
                                   $"2、使用 '{optionProperty}' 属性配置注册地址。{System.Environment.NewLine}" +
                                   $"3、通过'{bindProperty}' 属性指定明确的 TCP 绑定地址。{System.Environment.NewLine}";

                    throw new SchubertException(error);
                }
                InstanceDescription desc    = new InstanceDescription($"{options.AppSystemName}", $"{options.Group}.{options.AppSystemName}", address);
                IServiceLocator     locator = new SchubertServiceLocator(loggerFactory);

                SwiftyBootstrap boot = new SwiftyBootstrap(locator, swiftyOptions.Value.Server, desc, loggerFactory);

                var servies = _serviceExports.ToArray();
                //其实也清理不了什么,上一步的对象已经被引用了,清理一个 ConcurrentBag 结构吧。
                _serviceExports = null;

                boot
                .Handles(handlers => handlers.Add(new ScopeInjectionEventHandler()))
                .EurekaConfig(swiftyOptions.Value.Server.EnableEureka, swiftyOptions.Value.Server.Eureka)
                .AddServices(servies)
                .Bind(address, swiftyOptions.Value.Server.Port)
                .StartAsync().ContinueWith(s =>
                {
                    if (s.Exception != null)
                    {
                        logger.WriteError(0, "启动 swifty 服务器发生错误。", s.Exception);
                    }
                    else
                    {
                        logger.WriteInformation(0, $"swifty 服务器已经启动。{System.Environment.NewLine}" +
                                                $"(port: {s.Result.Port},  services: {servies.Length},  eureka: {enableEureka.ToString().ToLower()})。");
                    }
                });
            }
            else
            {
                logger.WriteWarning($"开启了 Swifty 服务端功能,但是没有发现可用的 Swifty 服务,是否在接口上遗漏了 {nameof(RemoteServiceAttribute)} 或 {nameof(ThriftServiceAttribute)}。");
            }
        }
        public async Task <IActionResult> PostHerosLocations([FromBody] PassedGameData <int?> passedData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            DateTime now = DateTime.UtcNow;

            if (passedData.UserToken == null || passedData.ActionToken == null)
            {
                return(BadRequest(new DataError("securityErr", "No authorization controll.")));
            }
            UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken);

            if (dbtoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!dbtoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    dbtoken.UpdateToken(now);
                }
            }
            Heros       hero      = _context.Heros.FirstOrDefault(e => e.Name == passedData.ActionToken.HeroName);
            ActionToken gametoken = Security.CheckActionToken(_context, passedData.ActionToken, hero.HeroId);

            if (gametoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!gametoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    gametoken.UpdateToken(now);
                }
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                return(BadRequest(new DataError("databaseErr", "Failed to update tokens.")));
            }

            // can load location status - update status -> function (?)

            var location = _context.HerosLocations.FirstOrDefault(e => (e.HeroId == hero.HeroId) && (e.LocationIdentifier == hero.CurrentLocation));

            if (location == null)
            {
                return(BadRequest(new DataError("LocationErr", "Location is not available.")));
            }
            var descr = _context.LocationsDb.FirstOrDefault(e => e.LocationIdentifier == location.LocationIdentifier);

            if (descr == null)
            {
                return(BadRequest(new DataError("LocationErr", "LocationData is not available.")));
            }
            try
            {
                // TODO check location type -> vitual class or what?
                int LocationType = descr.LocationGlobalType;
                if (LocationType != 2)
                {
                    LocationDescription description = JsonConvert.DeserializeObject <LocationDescription>(descr.Sketch);
                    LocationState       state       = JsonConvert.DeserializeObject <LocationState>(location.Description);
                    description.LocationGlobalType = LocationType;

                    if (hero.Status == 1)
                    {
                        Traveling travel = _context.Traveling.FirstOrDefault(e => e.HeroId == hero.HeroId);
                        if (travel == null)
                        {
                            throw new Exception("Traveling hero without travel in DB.");
                        }
                        if (travel.HasEnded(now))
                        {
                            state                = description.MoveTo(travel.UpdatedLocationID(), state);
                            hero.Status          = 0;
                            location.Description = JsonConvert.SerializeObject(state);
                            _context.Traveling.Remove(travel);
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remove travel.")));
                            }
                            LocationResult <MainNodeResult> locationResult = description.GenLocalForm(state);
                            return(Ok(new { success = true, location = locationResult }));
                        }
                        else
                        {
                            return(BadRequest(new DataError("LocationErr", "Travel is not finished")));
                        }
                    }
                    else
                    {
                        return(BadRequest(new DataError("LocationErr", "Hero is not in travel mode")));
                    }
                }
                else
                {
                    InstanceDescription description = JsonConvert.DeserializeObject <InstanceDescription>(descr.Sketch);
                    InstanceState       state       = JsonConvert.DeserializeObject <InstanceState>(location.Description);
                    description.LocationGlobalType = LocationType;

                    if (hero.Status == 1)
                    {
                        Traveling travel = _context.Traveling.FirstOrDefault(e => e.HeroId == hero.HeroId);
                        if (travel == null)
                        {
                            throw new Exception("Traveling hero without travel in DB.");
                        }
                        if (travel.HasEnded(now))
                        {
                            state                = description.MoveTo(travel.UpdatedLocationID(), state);
                            hero.Status          = 0;
                            location.Description = JsonConvert.SerializeObject(state);
                            _context.Traveling.Remove(travel);
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remove travel.")));
                            }
                            LocationResult <InstanceNodeResult> locationResult = description.GenLocalForm(state);
                            return(Ok(new { success = true, location = locationResult }));
                        }
                        else
                        {
                            return(BadRequest(new DataError("LocationErr", "Travel is not finished")));
                        }
                    }
                    else
                    {
                        return(BadRequest(new DataError("LocationErr", "Hero is not in travel mode")));
                    }
                }
            }
            catch
            {
                return(BadRequest(new DataError("LocationErr", "Location is not available.")));
            }
        }
示例#11
0
        public async Task <IActionResult> PostTraveling([FromBody] PassedGameData <int> passedData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            DateTime now = DateTime.UtcNow;

            if (passedData.UserToken == null || passedData.ActionToken == null)
            {
                return(BadRequest(new DataError("securityErr", "No authorization controll.")));
            }
            UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken);

            if (dbtoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!dbtoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    dbtoken.UpdateToken(now);
                }
            }
            Heros       hero      = _context.Heros.FirstOrDefault(e => e.Name == passedData.ActionToken.HeroName);
            ActionToken gametoken = Security.CheckActionToken(_context, passedData.ActionToken, hero.HeroId);

            if (gametoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!gametoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    gametoken.UpdateToken(now);
                }
            }
            // if can go there
            if (hero.Status == 0)
            {
                var location = _context.HerosLocations.FirstOrDefault(e => (e.HeroId == hero.HeroId) && (e.LocationIdentifier == hero.CurrentLocation));
                if (location == null)
                {
                    return(BadRequest(new DataError("LocationErr", "Location is not available.")));
                }
                var descr = _context.LocationsDb.FirstOrDefault(e => e.LocationIdentifier == location.LocationIdentifier);
                if (descr == null)
                {
                    return(BadRequest(new DataError("LocationErr", "LocationData is not available.")));
                }
                try
                {
                    // TODO check location type
                    AstarResult astar       = null;
                    int         TravelScale = 0;
                    int         Start       = -1;
                    string      StartName   = "";
                    int         Target      = -1;
                    string      TargetName  = "";

                    int LocationType = descr.LocationGlobalType;
                    if (LocationType != 2)
                    {
                        LocationDescription description = JsonConvert.DeserializeObject <LocationDescription>(descr.Sketch);
                        LocationState       state       = JsonConvert.DeserializeObject <LocationState>(location.Description);
                        description.LocationGlobalType = descr.LocationGlobalType;

                        int GlobalNodeID = description.GlobalMainNodeID(passedData.Data, state);
                        if (GlobalNodeID == state.CurrentLocation)
                        {
                            throw new Exception("Moving nowhere");
                        }
                        astar       = LocationHandler.DistanceToMove(description, state, passedData.Data);
                        TravelScale = description.TravelScale;
                        Start       = state.CurrentLocation;
                        StartName   = description.MainNodes.First(e => e.NodeID == state.CurrentLocation).Name;
                        Target      = GlobalNodeID;
                        TargetName  = description.MainNodes.First(e => e.NodeID == GlobalNodeID).Name;
                    }
                    else
                    {
                        InstanceDescription description = JsonConvert.DeserializeObject <InstanceDescription>(descr.Sketch);
                        InstanceState       state       = JsonConvert.DeserializeObject <InstanceState>(location.Description);
                        description.LocationGlobalType = descr.LocationGlobalType;

                        int GlobalNodeID = description.GlobalMainNodeID(passedData.Data, state);
                        if (GlobalNodeID == state.CurrentLocation)
                        {
                            throw new Exception("Moving nowhere");
                        }
                        astar       = LocationHandler.DistanceToMove(description, state, passedData.Data);
                        TravelScale = description.TravelScale;
                        Start       = state.CurrentLocation;
                        Target      = GlobalNodeID;
                        TargetName  = passedData.Data.ToString();
                    }

                    double TravelTime = LocationHandler.TimeTravel(astar.Distance, TravelScale, 18 * hero.VelocityFactor);

                    Traveling travel = new Traveling()
                    {
                        EndTime     = now.AddSeconds(TravelTime),
                        HeroId      = hero.HeroId,
                        IsReverse   = false,
                        ReverseTime = null,
                        Start       = Start,
                        StartName   = StartName,
                        StartTime   = now,
                        Target      = Target,
                        TargetName  = TargetName,
                    };
                    hero.Status = 1;
                    _context.Traveling.Add(travel);
                    TravelResult travelResult = travel.GenTravelResult(now);
                    try
                    {
                        await _context.SaveChangesAsync();

                        return(Ok(new { success = true, travel = travelResult }));
                    }
                    catch (DbUpdateException)
                    {
                        return(BadRequest(new DataError("databaseErr", "Failed to remember travel.")));
                    }
                }
                catch
                {
                    return(BadRequest(new DataError("LocationErr", "Location is not available.")));
                }
            }
            else
            {
                return(BadRequest(new DataError("LocationErr", "Hero is not able to travel.")));
            }
        }
示例#12
0
        /// <summary>
        /// Generates an test instance. The instance is parametrized by warehouse size, number of agents
        /// existence of the special area such as freezer. TBD: More advanced parameters such as item distribution.
        /// </summary>
        /// <param name="aisles"></param>
        /// <param name="crossAisles"></param>
        /// <param name="aisleRows"></param>
        /// <param name="storageLevels"></param>
        /// <param name="items"></param>
        /// <param name="agents"></param>
        /// <param name="specialArea"></param>
        /// <returns></returns>
        public static WarehouseInstance GenerateInstance(InstanceDescription instanceDescriptoon, int seed)
        {
            var rand        = new Random(seed);
            var layout      = instanceDescriptoon.layout;
            var storageDesc = instanceDescriptoon.storageDescription;
            var orderDesc   = instanceDescriptoon.ordersDescription;

            // Generate the grid
            // TODO: Special storage
            int width  = 3 * layout.aisles - 2;
            int height = 2 * layout.crossAisles + (layout.crossAisles - 1) * layout.aisleRows + 6;

            Location[,] grid = new Location[width, height];
            List <StorageRack> storage = new List <StorageRack>();

            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < height; j++)
                {
                    if (isFloor(i, j))
                    {
                        grid[i, j] = new Floor();
                    }
                    else if (isStaging(i, j))
                    {
                        grid[i, j] = new StagingArea();
                    }
                    else
                    {
                        var rack = new StorageRack(storageDesc.storageLevels);
                        grid[i, j] = rack;
                        storage.Add(rack);
                    }
                }
            }

            // Fill the empty shelves randomly, more advanced methods will be implemented
            if (storageDesc.randomizedPlacement)
            {
                var itemsList = GenerateRandomItems(storageDesc.uniqueItems, storage.Count * storageDesc.storageLevels, rand);
                int itemsIdx  = 0;
                foreach (var rack in storage)
                {
                    for (int j = 0; j < storageDesc.storageLevels; j++)
                    {
                        rack.items[j] = itemsList[itemsIdx++];
                    }
                }
            }
            else
            {
                // TODO: Zone item placement?
                throw new NotImplementedException("Other than random placement of items not implemented.");
            }

            // Generate orders
            var orders = GenerateRandomOrders(orderDesc.agents, orderDesc.itemsPerOrder, orderDesc.ordersPerAgent,
                                              storageDesc.uniqueItems, orderDesc.ordersVariance, orderDesc.itemsVariance, rand);

            return(new WarehouseInstance(grid, orders));


            bool isFloor(int x, int y)
            {
                return(x % 3 == 0 ||
                       y == 0 ||
                       y == height - 1 ||
                       (y - 3) % (layout.aisleRows + 2) == 0 ||
                       (y - 3) % (layout.aisleRows + 2) == 1);
            }

            bool isStaging(int x, int y)
            {
                return((y == 1 || y == 2 || y == height - 2 || y == height - 3) &&
                       (x != 0 && x != width - 1));
            }
        }
        private IEnumerable<InstanceDescription> GetReplicationTargets( out InstanceDescription self )
        {
            var recipe  = GetRecipe();
            self        = InstanceEnumerator.GetSelf();

            if (recipe != null)
            {
                return recipe.GetReplicationTargets(self, InstanceEnumerator.GetOthers());
            }

            log.Warn("No replication recipe selected");
            return null;
        }
        private string GetReplicationUrl(string databaseName, InstanceDescription destination)
        {
            var baseUrl = ConfigurationProvider.GetSetting(ConfigurationSettingsKeys.ReplicationUsePublicEndpoint, true)
                              ? destination.ExternalUrl
                              : destination.InternalUrl;

            return databaseName == null ? baseUrl : string.Format("{0}/databases/{1}", baseUrl, databaseName);
        }
示例#15
0
        public async Task <IActionResult> PostLocationAction([FromBody] PassedGameData <int> passedData)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            DateTime now = DateTime.UtcNow;

            if (passedData.UserToken == null || passedData.ActionToken == null)
            {
                return(BadRequest(new DataError("securityErr", "No authorization controll.")));
            }
            UserToken dbtoken = Security.CheckUserToken(this._context, passedData.UserToken);

            if (dbtoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!dbtoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    dbtoken.UpdateToken(now);
                }
            }
            Heros       hero      = _context.Heros.FirstOrDefault(e => e.Name == passedData.ActionToken.HeroName);
            ActionToken gametoken = Security.CheckActionToken(_context, passedData.ActionToken, hero.HeroId);

            if (gametoken == null)
            {
                return(BadRequest(new DataError("securityErr", "Your data has probably been stolen or modified manually. We suggest password's change.")));
            }
            else
            {
                if (!gametoken.IsTimeValid(now))
                {
                    return(BadRequest(new DataError("timeoutErr", "You have been too long inactive. Relogin is required.")));
                }
                else
                {
                    gametoken.UpdateToken(now);
                }
            }
            // now do your stuff...
            if (hero.Status == 0)
            {
                var location = _context.HerosLocations.FirstOrDefault(e => (e.HeroId == hero.HeroId) && (e.LocationIdentifier == hero.CurrentLocation));
                if (location == null)
                {
                    return(BadRequest(new DataError("LocationErr", "Location is not available.")));
                }
                var descr = _context.LocationsDb.FirstOrDefault(e => e.LocationIdentifier == location.LocationIdentifier);
                if (descr == null)
                {
                    return(BadRequest(new DataError("LocationErr", "LocationData is not available.")));
                }
                try
                {
                    // TODO check location type
                    int LocationType = descr.LocationGlobalType;
                    if (LocationType != 2)
                    {
                        LocationDescription description = JsonConvert.DeserializeObject <LocationDescription>(descr.Sketch);
                        LocationState       state       = JsonConvert.DeserializeObject <LocationState>(location.Description);
                        description.LocationGlobalType = descr.LocationGlobalType;

                        var CurrentNode = description.MainNodes.FirstOrDefault(e => e.NodeID == state.CurrentLocation);

                        if (CurrentNode.Data == -1)
                        {
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remember travel.")));
                            }
                            return(BadRequest(new DataError("notImplementedErr", "This feature has not been implemented yet. We are working on it!")));
                        }
                        try
                        {
                            if (!LocationHandler.OptionsForLocation.ContainsKey(CurrentNode.LocationType))
                            {
                                throw new Exception();
                            }
                            if (!LocationHandler.LocationTypeFunctions.ContainsKey(LocationHandler.OptionsForLocation[CurrentNode.LocationType][passedData.Data]))
                            {
                                throw new Exception();
                            }
                            var func = LocationHandler.LocationTypeFunctions[LocationHandler.OptionsForLocation[CurrentNode.LocationType][passedData.Data]];
                            func(_context, hero, CurrentNode.Data);
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remember action.")));
                            }
                        }
                        catch (OperationException e)
                        {
                            return(BadRequest(new DataError(e.ErrorClass, e.Message)));
                        }
                        catch
                        {
                            return(BadRequest(new DataError("notImplementedErr", "This feature has not been implemented yet. We are working on it!")));
                        }
                    }
                    else
                    {
                        InstanceDescription description = JsonConvert.DeserializeObject <InstanceDescription>(descr.Sketch);
                        InstanceState       state       = JsonConvert.DeserializeObject <InstanceState>(location.Description);
                        description.LocationGlobalType = descr.LocationGlobalType;

                        var CurrentNode = description.MainNodes.FirstOrDefault(e => e.NodeID == state.CurrentLocation);

                        if (CurrentNode.Data == -1)
                        {
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remember travel.")));
                            }
                            return(BadRequest(new DataError("notImplementedErr", "This feature has not been implemented yet. We are working on it!")));
                        }
                        try
                        {
                            if (!LocationHandler.OptionsForInstances.ContainsKey(CurrentNode.InstanceType))
                            {
                                throw new Exception();
                            }
                            if (!LocationHandler.InstanceTypeFunctions.ContainsKey(LocationHandler.OptionsForInstances[CurrentNode.InstanceType][passedData.Data]))
                            {
                                throw new Exception();
                            }
                            var func = LocationHandler.InstanceTypeFunctions[LocationHandler.OptionsForInstances[CurrentNode.InstanceType][passedData.Data]];
                            func(_context, hero, CurrentNode.Data);
                            try
                            {
                                await _context.SaveChangesAsync();
                            }
                            catch (DbUpdateException)
                            {
                                return(BadRequest(new DataError("databaseErr", "Failed to remember action.")));
                            }
                        }
                        catch
                        {
                            return(BadRequest(new DataError("notImplementedErr", "This feature has not been implemented yet. We are working on it!")));
                        }
                    }
                    // load new hero status
                    try
                    {
                        var heroStatus = LocationHandler.GetHeroGeneralStatus(_context, hero, now);
                        return(Ok(new { success = true, location = heroStatus.Location, statusData = heroStatus.StatusData, heroStatus = heroStatus.HeroStatus }));
                    }
                    catch (Exception e)
                    {
                        return(BadRequest(new DataError("statusErr", e.Message)));
                    }
                }
                catch
                {
                    return(BadRequest(new DataError("LocationErr", "Location is not available.")));
                }
            }
            else
            {
                return(BadRequest(new DataError("LocationErr", "Hero is not able to change state.")));
            }
        }