public void AddressSearch_Speed() { List <Location> listLocations = Utils.ReadCSVFile(); #region Exact Search LocationCache cache = new LocationCache(listLocations); Stopwatch firstHit = new Stopwatch(); firstHit.Start(); _ = cache.GetAddressMatches("ab"); firstHit.Stop(); Stopwatch secondHit = new Stopwatch(); secondHit.Start(); _ = cache.GetAddressMatches("ab"); secondHit.Stop(); Assert.IsTrue(firstHit.ElapsedTicks > secondHit.ElapsedTicks); Console.WriteLine($"First Hit: {firstHit.ElapsedTicks} ticks\nSecond Hit: {secondHit.ElapsedTicks} ticks\n"); #endregion #region Partial Search LocationCache cachePartial = new LocationCache(listLocations); cachePartial.GetAddressMatches("a"); Stopwatch partial = new Stopwatch(); partial.Start(); _ = cachePartial.GetAddressMatches("ab"); partial.Stop(); LocationCache cacheNoPartial = new LocationCache(listLocations); Stopwatch noPartial = new Stopwatch(); noPartial.Start(); _ = cacheNoPartial.GetAddressMatches("ab"); noPartial.Stop(); Assert.IsTrue(noPartial.ElapsedTicks > partial.ElapsedTicks); Console.WriteLine($"Partial: {partial.ElapsedTicks} ticks\nNo Partial: {noPartial.ElapsedTicks} ticks\n"); #endregion }
public void CacheLocations() { var cachePath = System.Web.HttpContext.Current.Server.MapPath($"~/App_Data/inReachRepos/Global/Cache"); Directory.CreateDirectory(cachePath); var startTime = DateTime.Now; var locCache = new LocationCache(); if (System.IO.File.Exists($"{cachePath}/accloc")) { locCache = JsonConvert.DeserializeObject <LocationCache>( System.IO.File.ReadAllText($"{cachePath}/accloc")); } if (locCache.IsSyncing) { return; } try { locCache.IsSyncing = true; System.IO.File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); LocationService.CacheActionLocations(locCache.Locations); locCache.IsSyncing = false; locCache.LastSync = DateTime.Now; locCache.LastSyncMilliseconds = (startTime - locCache.LastSync).TotalMilliseconds; System.IO.File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); } catch (Exception e) { locCache.IsSyncing = false; System.IO.File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); Logger.Info($"Error Caching Locations {e.Message} at {e.StackTrace}"); } }
public LocationInfo GetLocationByUniqueId(string uniqueIdText) { if (!Guid.TryParse(uniqueIdText, out var uniqueId)) { throw new ArgumentException($"Can't parse '{uniqueIdText}' as a unique ID"); } var locationInfo = LocationCache.SingleOrDefault(l => Guid.Parse(l.UniqueId) == uniqueId); if (locationInfo != null) { return(locationInfo); } try { var location = Client.Provisioning.Get(new GetLocation { LocationUniqueId = uniqueId }); return(AddLocationInfo(location)); } catch (WebServiceException) { Log.Error($"LocationUniqueId {uniqueId:N} does not exist"); throw new ArgumentException($"LocationUniqueId {uniqueId:N} does not exist"); } }
private void process() { if (!Multiplayer.locations.ContainsKey(location)) { return; } LocationCache loc = Multiplayer.locations[location]; Vector2 pos = new Vector2(posX, posY); if (!loc.loc.objects.ContainsKey(pos)) { return; } Object obj = loc.loc.objects[pos]; if (obj.GetType() != typeof(Fence)) { return; } Fence fence = (Fence)obj; loc.ignoreUpdates = true; fence.gatePosition = gatePos; loc.getMonitor <Fence>().recheck(pos); loc.ignoreUpdates = false; }
public NewPostViewModel(LocationCache locationCache) { this.SaveCommand = new Command(this.SaveCommandExecute, this.SaveCommandCanExecute); this.CancelCommand = new Command(this.OnCancel); this.PropertyChanged += this.NewPostViewModelPropertyChanged; this.locationCache = locationCache; }
public GroupNewViewModel(LocationCache locationCache) { this.locationCache = locationCache; this.PickIconCommand = new Command(this.PickIconCommandExecute); this.SaveGroupCommand = new Command(this.SaveGroupCommandExecuteAsync); }
public SpecificMonitor(LocationCache theLoc, Dictionary <Vector2, BASETYPE> theContainer, Func <TYPE, STATE> stateFunc, Func <GameLocation, Vector2, PACKET> packetFunc) { loc = theLoc; container = theContainer; makeState = stateFunc; makePacket = packetFunc; }
public PostsViewModel(LocationCache locationCache) { this.Title = "Browse"; this.Posts = new ObservableCollection <PostEntryViewModel>(); this.LoadItemsCommand = new Command(this.ExecuteLoadItemsCommand); this.AddItemCommand = new Command(this.OnAddItem); this.locationCache = locationCache; }
public LocationInfo GetLocationByIdentifier(string locationIdentifier) { var locationInfo = LocationCache.SingleOrDefault(l => l.LocationIdentifier.Equals(locationIdentifier, StringComparison.InvariantCultureIgnoreCase)); if (locationInfo != null) { return(locationInfo); } if (LocationAliases.TryGetValue(locationIdentifier, out var aliasedIdentifier)) { locationInfo = LocationCache.SingleOrDefault(l => l.LocationIdentifier.Equals(aliasedIdentifier, StringComparison.InvariantCultureIgnoreCase)); if (locationInfo != null) { return(locationInfo); } locationIdentifier = aliasedIdentifier; } var locationDescriptions = Client.Publish.Get(new LocationDescriptionListServiceRequest { LocationIdentifier = locationIdentifier }) .LocationDescriptions; var locationDescription = locationDescriptions .FirstOrDefault(l => l.Identifier == locationIdentifier); if (locationDescription == null) { var closeMatches = locationDescriptions .Where(l => l.Identifier.Equals(locationIdentifier, StringComparison.InvariantCultureIgnoreCase)) .ToList(); if (closeMatches.Count == 1) { locationDescription = closeMatches.Single(); } } if (locationDescription == null) { Log.Error(!locationDescriptions.Any() ? $"Location '{locationIdentifier}' does not exist." : $"Location '{locationIdentifier}' has ambiguously found {locationDescriptions.Count} matches: {string.Join(", ", locationDescriptions.Select(l => l.Identifier))}"); return(AddUnknownLocationInfo(locationIdentifier)); } var location = Client.Provisioning.Get(new GetLocation { LocationUniqueId = locationDescription.UniqueId }); return(AddLocationInfo(location)); }
/// <summary> /// The one method to put different types of estate objects into caches. <br/> /// Key is chosen automatically. <br/> /// Method checks referential integrity on: <br/> /// EstateObject.SellerID - Person.key. <br/> /// EstateObject.LocationID - Location.key. /// </summary> /// <param name="value">Estate object to put into cache.</param> public static void PutEstateObject (EstateObject value) { using (var tx = Client.GetTransactions().TxStart()) { // Error if Person with key = value.SellerID is not found. if (!(PersonCache.ContainsKey(value.SellerID))) { tx.Commit(); throw new ReferentialException ("Can not put new entry into EstateObject cache.") { Operation = "put", TableName = "EstateObject", FieldName = "SellerID", ReadableMessage = $"Can not put new entry into EstateObject cache because Person with key {value.SellerID} does not exist." }; } // Error if Location not found. if (!(LocationCache.ContainsKey(value.LocationID))) { tx.Commit(); throw new ReferentialException ("Can not put new entry into EstateObject cache.") { Operation = "put", TableName = "EstateObject", FieldName = "LocationID", ReadableMessage = $"Can not put new entry into EstateObject cache because Location with key {value.LocationID} does not exist." }; } // Normal operation. int key = LastUsedKeys.Get("estateobject"); switch ((char)value.Variant) { case 'o': ObjectCache.Put (key, value); break; case 'h': HouseCache.Put (key, (House)value); break; case 'f': FlatCache.Put (key, (Flat)value); break; case 'l': LandplotCache.Put (key, (Landplot)value); break; default: break; } LastUsedKeys.Put("estateobject", key+1); tx.Commit(); } }
/// <summary> /// Get a dictionary where key is location id and value is district name. Is used for dropdowns. /// </summary> public static Dictionary <string, string> GetDistrictsOfTown(string town) { Dictionary <string, string> result = new Dictionary <string, string>(); foreach (var row in LocationCache.Query(new SqlFieldsQuery($"select _key, District from Locations where Town='{town}';"))) { result[row[0].ToString()] = row[1] as string; } return(result); }
/// <summary> /// Get list of towns of metioned region. Is used for dropdowns. /// </summary> public static ICollection <string> GetTownsOfRegion(string region) { List <string> result = new List <string>(); foreach (var row in LocationCache.Query(new SqlFieldsQuery($"select distinct Town from Locations where Region='{region}';"))) { result.Add(row[0] as string); } return(result); }
/// <summary> /// Put location entity into Location cache. /// </summary> /// <param name="value">Location entity to put into cache.</param> public static void PutLocation (Location value) { using (var tx = Client.GetTransactions().TxStart()) { int key = LastUsedKeys.Get("location"); LocationCache.Put(key, value); key++; LastUsedKeys.Put("location", key); tx.Commit(); } }
public PostsViewModel(LocationCache locationCache) { this.Title = "Browse"; this.Posts = new ObservableCollection <PostGetData>(); this.LoadItemsCommand = new Command(async() => await this.ExecuteLoadItemsCommand()); this.ItemTapped = new Command <PostGetData>(this.OnPostSelected); this.AddItemCommand = new Command(this.OnAddItem); this.locationCache = locationCache; }
private void process() { if (!Multiplayer.locations.ContainsKey(location)) { return; } Vector2 pos = new Vector2(posX, posY); TYPE obj = Util.deserialize <TYPE>(str); obj.reloadSprite(); LocationCache loc = Multiplayer.locations[location]; loc.ignoreUpdates = true; loc.loc.objects[pos] = obj; loc.getMonitor <TYPE>().recheck(pos); loc.ignoreUpdates = false; }
private LocationInfo AddLocationInfo(string locationName, string locationIdentifier, Offset utcOffset, Guid?uniqueId = null) { const long dummyId = 0; var locationInfo = InternalConstructor <LocationInfo> .Invoke( locationName, locationIdentifier, dummyId, uniqueId ?? Guid.Empty, utcOffset.ToTimeSpan().TotalHours); if (LocationCache.SingleOrDefault(l => l.LocationIdentifier == locationInfo.LocationIdentifier) == null) { LocationCache.Add(locationInfo); } return(locationInfo); }
private void process() { GameLocation loc = Game1.getLocationFromName(location); LocationCache cache = Multiplayer.locations[location]; if (loc is Forest) { //only the log here, sooo. ((Forest)loc).log = null; cache.prevForestLog = null; } else if (loc is Woods) { //check the stumps in the woods Woods map_woods = (Woods)loc; foreach (var clump in map_woods.stumps) { if (hashVec2(clump) == hash) { //we have found a removed stump! let's kill it :D map_woods.stumps.Remove(clump); cache.updateClumpsCache(map_woods.stumps); break; } } } else if (loc is Farm) { //check the resource clumps on the farm Farm map_farm = (Farm)loc; foreach (var clump in map_farm.resourceClumps) { if (hashVec2(clump) == hash) { //we have found a removed resource clump! let's kill it :D map_farm.resourceClumps.Remove(clump); cache.updateClumpsCache(map_farm.resourceClumps); break; } } } }
public void AddressSearch_Accuracy() { List <Location> listInitialLocations = new List <Location> { new Location(1, "Test1", "", "", "", 0, 0), new Location(2, "Te3", "", "", "", 0, 0), new Location(3, "abc4ewq", "", "", "", 0, 0), }; LocationCache cache = new LocationCache(listInitialLocations); List <Location> results = cache.GetAddressMatches("TE"); Assert.AreEqual(2, results.Count); Assert.IsTrue(results.Any(x => x.Id == 1)); Assert.IsTrue(results.Any(x => x.Id == 2)); results = cache.GetAddressMatches("e3"); Assert.AreEqual(1, results.Count); Assert.IsTrue(results.Any(x => x.Id == 2)); results = cache.GetAddressMatches("ET"); Assert.AreEqual(0, results.Count); results = cache.GetAddressMatches(""); Assert.AreEqual(0, results.Count); }
private void Initialize( bool useMultipleWriteLocations, bool enableEndpointDiscovery, bool isPreferredLocationsListEmpty) { this.databaseAccount = LocationCacheTests.CreateDatabaseAccount(useMultipleWriteLocations); this.preferredLocations = isPreferredLocationsListEmpty ? new List <string>().AsReadOnly() : new List <string>() { "location1", "location2", "location3" }.AsReadOnly(); this.cache = new LocationCache( this.preferredLocations, LocationCacheTests.DefaultEndpoint, enableEndpointDiscovery, 10, useMultipleWriteLocations); this.cache.OnDatabaseAccountRead(this.databaseAccount); this.mockedClient = new Mock <IDocumentClientInternal>(); mockedClient.Setup(owner => owner.ServiceEndpoint).Returns(LocationCacheTests.DefaultEndpoint); mockedClient.Setup(owner => owner.GetDatabaseAccountInternalAsync(It.IsAny <Uri>(), It.IsAny <CancellationToken>())).ReturnsAsync(this.databaseAccount); ConnectionPolicy connectionPolicy = new ConnectionPolicy() { EnableEndpointDiscovery = enableEndpointDiscovery, UseMultipleWriteLocations = useMultipleWriteLocations, }; foreach (string preferredLocation in this.preferredLocations) { connectionPolicy.PreferredLocations.Add(preferredLocation); } this.endpointManager = new GlobalEndpointManager(mockedClient.Object, connectionPolicy); }
/// <summary> /// Create new account, using Person entity, password, and optionally privilegies level. /// </summary> /// <param name="person"></param> /// <param name="password"></param> /// <param name="privilegies"></param> public static void CreateAccount(Person person, string password, char privilegies = 'c') { using (var tx = Client.GetTransactions().TxStart()) { // Referential integrity check if (CredentialCache.ContainsKey(person.Phone)) { tx.Commit(); throw new ReferentialException("Can not create new account.") { ReadableMessage = $"Can not create account because account with phone {person.Phone} already exists." }; } if (!LocationCache.ContainsKey(person.LocationID)) { tx.Commit(); throw new ReferentialException("Can not create new account.") { ReadableMessage = $"Can not create account because location with key {person.LocationID} does not exist." }; } // Normal operation int key = LastUsedKeys.Get("person"); PersonCache.Put(key, person); LastUsedKeys.Put("person", key + 1); Credential c = new Credential { Password = password, Privilegies = (byte)privilegies, Status = (byte)'n', PersonID = key }; CredentialCache.Put(person.Phone, c); tx.Commit(); } }
/// <summary> /// Put a person into the cache.<br/> /// This method checks referential integrity on field Person.LocationID: <br/> /// Location with _key = Person.LocationID has to exist. <br/> /// Otherwise, method throws ReferentialException. <br/> /// This and other put methods DO NOT validate the entity. /// </summary> /// <param name="p">Person to put into the cache.</param> public static void PutPerson (Person p) { using (var tx = Client.GetTransactions().TxStart()) { // Check if Location cache contains Location with key p.LocationID, throw error if not. if (!(LocationCache.ContainsKey(p.LocationID))) { tx.Commit(); throw new ReferentialException ("Can not put new entry into Person cache.") { Operation = "put", TableName = "Person", FieldName = "LocationID", ReadableMessage = $"Can not put new entry into Person cache because Location with key {p.LocationID} does not exist." }; } // Check if Credential cache contains Credential with key p.Phone, throw error if yes. if (CredentialCache.ContainsKey(p.Phone)) { tx.Commit(); throw new ReferentialException ("Can not put new entry into Person cache.") { Operation = "put", TableName = "Person", FieldName = "Phone", ReadableMessage = $"Can not put new entry into Person cache because Person with Phone '{p.Phone}' and Credential with the same key already exist." }; } // Normal operation. int key = LastUsedKeys.Get("person"); PersonCache.Put(key, p); key++; LastUsedKeys.Put ("person", key); tx.Commit(); } }
public Shell(Stream input, Stream output, Stream error) { _seenPrograms = new LocationCache(); _path = new List <System.IO.DirectoryInfo>(); _alias = new Dictionary <string, string>(); // Set up our I/O buffers, making sure we can read/write from them if (!input.CanRead) { throw new ArgumentException("Cannot read from given input stream."); } if (!output.CanWrite) { throw new ArgumentException("Cannot write to output stream."); } if (!error.CanWrite) { throw new ArgumentException("Cannot write to error stream."); } _input = input; _output = output; _error = error; }
/// <summary> /// Put ClientWish entity into the cache. <br/> /// Referential integrity check is done on: <br/> /// ClientWish.ClientID - Person.key <br/> /// ClientWish.LocationID - Location.key /// </summary> /// <param name="value">ClientWish to put into the cache.</param> public static void PutClientWish (ClientWish value) { using (var tx = Client.GetTransactions().TxStart()) { // Error if Person with key = value.ClientID is not found. if (!(PersonCache.ContainsKey(value.ClientID))) { tx.Commit(); throw new ReferentialException ("Can not put new entry into ClientWish cache.") { Operation = "put", TableName = "ClientWish", FieldName = "ClientID", ReadableMessage = $"Can not put new entry into ClientWish cache because Person with key {value.ClientID} does not exist." }; } // Error if Location not found. if (!(LocationCache.ContainsKey(value.LocationID))) { tx.Commit(); throw new ReferentialException ("Can not put new entry into ClientWish cache.") { Operation = "put", TableName = "ClientWish", FieldName = "LocationID", ReadableMessage = $"Can not put new entry into ClientWish cache because Location with key {value.LocationID} does not exist." }; } // Normal operation. int key = LastUsedKeys.Get ("clientwish"); ClientWishCache.Put (key, value); LastUsedKeys.Put ("clientwish", key+1); tx.Commit(); } }
private void process() { if (!Multiplayer.locations.ContainsKey(location)) { return; } LocationCache loc = Multiplayer.locations[location]; Vector2 pos = new Vector2(posX, posY); Chest obj = null; if (opener != -1) // Opened { obj = (Chest)loc.loc.objects[pos]; // If two people open a chest at the same it glitches out. It closes for both people, // but shows open even though nobody has it open, and nobody can open it. Clients // MIGHT be able to open it the next day (which would fix the issue), but I haven't // tested that. SFarmer farmer = (SFarmer )Util.GetInstanceField(typeof(Chest), obj, "opener"); if (farmer != null) { // Somebody already has it open. Normally you can't open a chest if someone // else has it open. But this is possible (like I mentioned above). // Not really sure what to do here. // For now, just ignore people who open it and have a higher ID. // This way it always results in one person having the chest open. // I can't just close it for us. Somehow that happens anyways when each person // gets this packet. Doing it this way means whoever has the lower ID keeps // it open, but the higher ID gets it closed. It should then behave normally, // as if the lower ID was the only one to open it. Hopefully? if (Multiplayer.getFarmerId(farmer) > Multiplayer.getMyId()) { return; } } // When opener is set, nobody can open the chest (vanilla). Util.SetInstanceField(typeof(Chest), obj, "opener", Multiplayer.getFarmer((byte)opener)); // Do the animation manually. It pops open instead of being smooth, but fixing // that would probably be a lot more work. // Setting frameCounter to -2 keeps the opening animation (which includes // opening the menu) from triggering (checks > -1), but prevents the closing // animation (which also clears opener) from triggering (checks == -1). obj.frameCounter = -2; obj.currentLidFrame = 135; if (Game1.currentLocation != null && loc.loc.name == Game1.currentLocation.name) { Game1.playSound("openChest"); } } else // Closed { obj = Util.deserialize <Chest>(str); obj.currentLidFrame = 135; obj.frameCounter = 2; if (Game1.currentLocation != null && loc.loc.name == Game1.currentLocation.name) { Game1.playSound("doorCreakReverse"); } } loc.ignoreUpdates = true; loc.loc.objects[pos] = obj; loc.getMonitor <Chest>().recheck(pos); loc.ignoreUpdates = false; }
public ChestMonitor(LocationCache loc) : base(loc, loc.loc.objects, (obj) => new ChestState(obj), (loc_, pos) => new ChestUpdatePacket(loc_, pos)) { }
protected void Application_Start() { Logger.Info($"App start"); ReportsControllerConfiguration.RegisterRoutes(GlobalConfiguration.Configuration); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configuration.AddJsonpFormatter(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AntiForgeryConfig.SuppressXFrameOptionsHeader = true; try { SettingsManager.Initiase(Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "inReachWeb")); SchedulerManager.AddJobs(JobTypeEnum.ExportJob); SchedulerManager.ClearAllJobs(); SchedulerManager.AddJobs(JobTypeEnum.InFuseExportJob); } catch (Exception e) { Console.WriteLine(e); Logger.Error($"Error loading settings {e.Message} at {e.StackTrace}"); } var startTime = DateTime.Now; var cachePath = HttpContext.Current.Server.MapPath($"~/App_Data/inReachRepos/Global/Cache"); Directory.CreateDirectory(cachePath); var locCache = new LocationCache(); if (File.Exists($"{cachePath}/accloc")) { locCache = JsonConvert.DeserializeObject <LocationCache>( File.ReadAllText($"{cachePath}/accloc")); } if (locCache.IsSyncing) { return; } try { locCache.IsSyncing = true; File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); LocationService.CacheActionLocations(locCache.Locations); locCache.IsSyncing = false; locCache.LastSync = DateTime.Now; locCache.LastSyncMilliseconds = (startTime - locCache.LastSync).TotalMilliseconds; File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); } catch (Exception e) { locCache.IsSyncing = false; File.WriteAllText($"{cachePath}/accloc", JsonConvert.SerializeObject(locCache)); Logger.Info($"Error Caching Locations {e.Message} at {e.StackTrace}"); } //ViewEngines.Engines.Insert(0, new inFuseViewEngine()); //var j = SchedulerManager.Jobs[0]; //var newjob = ((InFuseExportJob)j).ConvertExportJobToModular(); //newjob.Execute(); //var job = (ExportJob)SchedulerManager.Jobs[0]; //job.ConvertToModuleManager(); //job.RunJob(); //SchedulerManager.InitialiseJobs(); //ExportJobs = new FluentRegistry(); //JobManager.Initialize(ExportJobs); //ExportJobs.LoadExportJobs(); //Application["FluentRegistry"] = ExportJobs; }