private static void ShowValidatePostalReply(ValidatePostalReply reply) { Console.WriteLine("Postal Code Details:"); if (reply.PostalDetail != null) { printString(reply.PostalDetail.CityFirstInitials, "City Initials"); printString(reply.PostalDetail.CleanedPostalCode, "Cleaned Postal Code"); printString(reply.PostalDetail.StateOrProvinceCode, "State or Province Code"); Console.WriteLine(); if (reply.PostalDetail.LocationDescriptions != null) { LocationDescription[] locations = reply.PostalDetail.LocationDescriptions; for (int i = 0; i < locations.Length; i++) { LocationDescription location = locations[i]; printString(location.LocationId, "Location Id"); if (location.LocationNumberSpecified) { printString(location.LocationNumber.ToString(), "Location Number"); } printString(location.AirportId, "Airport Id"); printString(location.CountryCode, "Country Code"); if (location.FedExEuropeFirstOriginSpecified) { printString(location.FedExEuropeFirstOrigin.ToString(), "FedEx Europe First Origin"); } printString(location.PostalCode, "Postal Code"); printString(location.StateOrProvinceCode, "State or Province Code"); printString(location.ServiceArea, "Service Area"); if (location.RestrictedShipmentSpecialServices != null) { ShipmentSpecialServiceType[] shipServices = location.RestrictedShipmentSpecialServices; Console.WriteLine("Shipment Special Services -"); for (int j = 0; j < shipServices.Length; i++) { printString(shipServices[j].ToString(), j.ToString()); } } if (location.RestrictedPackageSpecialServices != null) { PackageSpecialServiceType[] packageServices = location.RestrictedPackageSpecialServices; Console.WriteLine("Package Special Services -"); for (int j = 0; j < packageServices.Length; i++) { printString(packageServices[j].ToString(), j.ToString()); } } Console.WriteLine(); } } } }
public DataTable LocationDataTable(string tableName, string locationIdentifier) { Log.DebugFormat("Create LocationDataTable {0}, {1}", tableName, locationIdentifier); DataTable locationTable = new DataTable(tableName); locationTable.Columns.Add("UniqueId", typeof(Guid)); locationTable.Columns.Add("LocationIdentifier", typeof(string)); locationTable.Columns.Add("LocationName", typeof(string)); locationTable.Columns.Add("UtcOffset", typeof(TimeSpan)); locationTable.Columns.Add("UtcOffsetString", typeof(string)); locationTable.Columns.Add("Description", typeof(string)); locationTable.Columns.Add("Latitude", typeof(double)); locationTable.Columns.Add("Longitude", typeof(double)); locationTable.Columns.Add("Elevation", typeof(double)); locationTable.Columns.Add("ElevationUnit", typeof(string)); locationTable.Columns.Add("ElevationUnitSymbol", typeof(string)); locationTable.Columns.Add("LocationType", typeof(string)); locationTable.Columns.Add("IsExternal", typeof(bool)); locationTable.Columns.Add("Tags", typeof(object)); locationTable.Columns.Add("LocationIdentifierAndNameInformation", typeof(string)); locationTable.Columns.Add("LocationExtraInformation", typeof(string)); DataRow dataRow = locationTable.NewRow(); LocationDescription locDescription = _Common.GetLocationDescriptionByIdentifier(locationIdentifier); LocationDataServiceResponse locData = _Common.GetLocationData(locationIdentifier); dataRow["UniqueId"] = locDescription.UniqueId; dataRow["LocationIdentifier"] = locationIdentifier; dataRow["LocationName"] = locDescription.Name; dataRow["UtcOffset"] = TimeSpan.FromHours(locData.UtcOffset); dataRow["UtcOffsetString"] = _Common.GetOffsetString(locData.UtcOffset); dataRow["Description"] = locData.Description; dataRow["Latitude"] = locData.Latitude; dataRow["Longitude"] = locData.Longitude; dataRow["Elevation"] = locData.Elevation; dataRow["ElevationUnit"] = locData.ElevationUnits; dataRow["ElevationUnitSymbol"] = _Common.GetUnitSymbol(locData.ElevationUnits); dataRow["LocationType"] = locData.LocationType; dataRow["IsExternal"] = locDescription.IsExternalLocation; dataRow["Tags"] = locDescription.Tags; dataRow["LocationIdentifierAndNameInformation"] = Resources.LocationIdentifier + ": " + locationIdentifier + ", " + Resources.LocationName + ": " + locDescription.Name; dataRow["LocationExtraInformation"] = Resources.UtcOffset + ": " + _Common.GetOffsetString(locData.UtcOffset) + ", " + Resources.Latitude + ": " + locData.Latitude + ", " + Resources.Longitude + ": " + locData.Longitude + ", " + Resources.Elevation + ": " + locData.Elevation.ToString() + ((string.IsNullOrEmpty(locData.Elevation.ToString()) ? "" : " " + locData.ElevationUnits)); locationTable.Rows.Add(dataRow); return(locationTable); }
private void InternalSetLocation(Team team, Location location, Transform locationTarget) { var desc = new LocationDescription(team, location); if (locations.ContainsKey(desc)) { locations[desc] = locationTarget; } else { locations.Add(desc, locationTarget); } }
private Transform InternalGetLocationTransform(Team team, Location location) { var desc = new LocationDescription(team, location); if (locations.ContainsKey(desc)) { var t = locations[desc]; return(t); } else { throw new System.Exception("ServiceLocator target not defined: (" + team + " " + location + ")"); } }
public override int GetHashCode() { int result = 0; result ^= RootPath.GetHashCode(); if (VersionControlSystem != null) { result ^= VersionControlSystem.GetHashCode(); } if (LocationDescription != null) { result ^= LocationDescription.GetHashCode(); } result ^= Name.GetHashCode(); return(result); }
public void PrintDescription() { string[] description = LocationDescription.Split(' '); for (int i = 0; i < description.Count(); i++) { if (ColoredWords.Exists(x => x.ToLower() == description[i].ToLower())) { Console.ForegroundColor = ItemColor; Console.Write(description[i]); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.Write(description[i]); } Console.Write(' '); } }
public void InsertObservation(string assignedOffering, LocationDataServiceResponse location, LocationDescription locationDescription, TimeSeriesDataServiceResponse timeSeries, TimeSeriesDescription timeSeriesDescription) { var xmlTemplatePath = IsSpatialLocationDefined(location) ? @"XmlTemplates\InsertObservation.xml" : @"XmlTemplates\InsertObservationWithNoGeoSpatial.xml"; const string pointTokenSeparator = ";"; const string pointBlockSeparator = "@"; var observablePropertyFieldName = SanitizeIdentifier($" {timeSeries.Parameter}_{timeSeries.Label}".Replace(" ", "_")); // TODO: Figure this mapping out var substitutions = CreateSubstitutions(timeSeries) .Concat(new Dictionary <string, string> { { "{__offeringUri__}", assignedOffering }, { "{__featureOfInterestName__}", location.LocationName }, { "{__featureOfInterestLatitude__}", $"{location.Latitude}" }, { "{__featureOfInterestLongitude__}", $"{location.Longitude}" }, { "{__observablePropertyUnit__}", SanitizeUnitSymbol(timeSeries.Unit) }, { "{__observablePropertyFieldName__}", observablePropertyFieldName }, { "{__resultTime__}", $"{FixedResultTime:O}" }, { "{__pointTokenSeparator__}", pointTokenSeparator }, { "{__pointBlockSeparator__}", pointBlockSeparator }, }) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value); var procedureUniqueId = substitutions[ProcedureUniqueIdKey]; var existingSensor = FindExistingSensor(procedureUniqueId); for (var insertedPoints = 0; insertedPoints < timeSeries.Points.Count;) { var points = timeSeries.Points .Skip(insertedPoints) .Take(MaximumPointsPerObservation) .ToList(); substitutions["{__phenomenonStartTime__}"] = $"{points.First().Timestamp.DateTimeOffset:O}"; substitutions["{__phenomenonEndTime__}"] = $"{points.Last().Timestamp.DateTimeOffset:O}"; substitutions["{__pointCount__}"] = $"{points.Count}"; substitutions["{__pointValues__}"] = string.Join(pointBlockSeparator, points.Select(p => $"{p.Timestamp.DateTimeOffset:O}{pointTokenSeparator}{p.Value.Display}")); existingSensor.PhenomenonTime = existingSensor.PhenomenonTime .Concat(new[] { points.Last().Timestamp.DateTimeOffset }) .OrderBy(x => x) .ToList(); insertedPoints += points.Count; var xml = TransformXmlTemplate(xmlTemplatePath, substitutions); Log.Info($"Posting {points.Count} data points to '{procedureUniqueId}' ..."); PostPox(xml); } }
public LocationCoordinateAndDescription() { locationCoordinate = new LocationCoordinate(); locationDescription = new LocationDescription(); }
public LocationCoordinateAndDescription(LocationCoordinate coordinate, LocationDescription description) { Coordinate = coordinate; Description = description; }
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."))); } }
public static bool TryGetLocationDescription(this IAquariusClient client, string locationIdentifier, out LocationDescription locationDescription) { var locationDescriptions = client.Publish.Get(new LocationDescriptionListServiceRequest { LocationIdentifier = locationIdentifier }).LocationDescriptions; if (locationDescriptions.Count == 1) { locationDescription = locationDescriptions .First(); return(true); } locationDescription = default; if (!locationDescriptions.Any()) { return(false); } throw new ExpectedException($"{locationDescriptions.Count} ambiguous location identifiers matched '{locationIdentifier}': {string.Join(", ", locationDescriptions.Select(l => l.Identifier))}"); }
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."))); } }
public static void PopulateGrivViewMapNomnatatim(DataGridView dataGridView, int columnIndex, LocationCoordinate locationCoordinateSearch, bool onlyFromCache, bool canReverseGeocoder, bool forceReloadUsingReverseGeocoder, bool createNewAccurateLocationUsingSearchLocation) { GlobalData.IsPopulatingMapLocation = true; try { LocationCoordinateAndDescription locationCoordinateAndDescriptionInDatabase = null; float locationAccuracyLatitude = Properties.Settings.Default.LocationAccuracyLatitude; float locationAccuracyLongitude = Properties.Settings.Default.LocationAccuracyLongitude; //LocationDescription locationDescription = null; LocationDescription locationDescription = null; #region Get Location Info from User when allowed DataGridViewGenericColumn dataGridViewGenericColumn = DataGridViewHandler.GetColumnDataGridViewGenericColumn(dataGridView, columnIndex); if (!forceReloadUsingReverseGeocoder && dataGridViewGenericColumn?.Metadata != null) { #region Get UserInput Location data Metadata metadataUser = new Metadata(MetadataBrokerType.Empty); GetUserInputChanges(dataGridView, ref metadataUser, null, columnIndex); #endregion if (!string.IsNullOrEmpty(metadataUser.LocationName) || !string.IsNullOrEmpty(metadataUser.LocationCity) || !string.IsNullOrEmpty(metadataUser.LocationState) || !string.IsNullOrEmpty(metadataUser.LocationCountry)) { locationDescription = new LocationDescription(metadataUser.LocationName, metadataUser.LocationCity, metadataUser.LocationState, metadataUser.LocationCountry); #region createNewAccurateLocationUsingSearchLocation if (createNewAccurateLocationUsingSearchLocation) { try { LocationCoordinateAndDescription locationCoordinateAndDescriptionFromUserInput = new LocationCoordinateAndDescription( locationCoordinateSearch, locationDescription); DatabaseAndCacheLocationAddress.WriteLocationName(locationCoordinateSearch, locationCoordinateAndDescriptionFromUserInput); dataGridView.EndEdit(); //Remove + sign AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerMedia, tagMediaCoordinates, ReadWriteAccess.AllowCellReadAndWrite), locationCoordinateSearch.ToString(), false); } catch { //DEBUG } } #endregion } } #endregion if (locationCoordinateSearch != null) { #region Get Nearby Location Coordinate and Info in Database locationCoordinateAndDescriptionInDatabase = DatabaseAndCacheLocationAddress.AddressLookupAndReverseGeocoder( locationCoordinateSearch, locationAccuracyLatitude, locationAccuracyLongitude, onlyFromCache: onlyFromCache, canReverseGeocoder: canReverseGeocoder, metadataLocationDescription: locationDescription, forceReloadUsingReverseGeocoder: false); #endregion #region If Asked to Reload, reload from UsingReverseGeocoder if (forceReloadUsingReverseGeocoder && locationCoordinateAndDescriptionInDatabase != null) { locationCoordinateAndDescriptionInDatabase = DatabaseAndCacheLocationAddress.AddressLookupAndReverseGeocoder( locationCoordinateSearch, locationAccuracyLatitude, locationAccuracyLongitude, onlyFromCache: false, canReverseGeocoder: true, metadataLocationDescription: null, forceReloadUsingReverseGeocoder: true); } #endregion } else { #region No coordinates found AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerMedia, tagMediaCoordinates, ReadWriteAccess.AllowCellReadAndWrite), null, false); #endregion } #region Show Tooltip when Use need Nearby coordinate int rowIndex = DataGridViewHandler.GetRowIndex(dataGridView, headerMedia, tagMediaCoordinates); if (locationCoordinateAndDescriptionInDatabase != null && locationCoordinateSearch != locationCoordinateAndDescriptionInDatabase.Coordinate) { DataGridViewHandler.SetCellToolTipText(dataGridView, columnIndex, rowIndex, "Near by location used: " + locationCoordinateAndDescriptionInDatabase.Coordinate.ToString()); } else { DataGridViewHandler.SetCellToolTipText(dataGridView, columnIndex, rowIndex, ""); } #endregion #region No data location data loaded, set as readonly bool isReadOnly = (locationCoordinateAndDescriptionInDatabase == null); #endregion #region Updated DataGridView with new data AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerNominatim, tagLocationName, ReadWriteAccess.AllowCellReadAndWrite), locationCoordinateAndDescriptionInDatabase?.Description.Name, isReadOnly); AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerNominatim, tagCity, ReadWriteAccess.AllowCellReadAndWrite), locationCoordinateAndDescriptionInDatabase?.Description.City, isReadOnly); AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerNominatim, tagProvince, ReadWriteAccess.AllowCellReadAndWrite), locationCoordinateAndDescriptionInDatabase?.Description.Region, isReadOnly); AddRow(dataGridView, columnIndex, new DataGridViewGenericRow(headerNominatim, tagCountry, ReadWriteAccess.AllowCellReadAndWrite), locationCoordinateAndDescriptionInDatabase?.Description.Country, isReadOnly); #endregion } catch (Exception ex) { KryptonMessageBox.Show("Unexpected error occur.\r\nException message:" + ex.Message + "\r\n", "Unexpected error occur", MessageBoxButtons.OK, MessageBoxIcon.Error, showCtrlCopy: true); } finally { GlobalData.IsPopulatingMapLocation = false; } }
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."))); } }