public ActionResult DeleteEntries(IList <Publication> pubs) { DataPersistence.DeletePublications(pubs); ViewData["DeletionResult"] = "Deletion of " + pubs.Count + " entries was a success."; return(Redirect("/Entry")); }
/// <summary> /// Creates a mob of all levels and instantiates them /// </summary> /// <param name="name">The base name of the mob</param> /// <param name="parentID">The prototype ID of the parent room</param> /// <returns>A list of instance mob IDs</returns> public static List <uint?> CreateAndInstantiateAllLevels(string name, uint?parentID) { var mobs = new List <uint?>(); var parentRoom = DataAccess.Get <Room>(parentID, CacheType.Instance); var protoRoom = DataAccess.Get <Room>(parentRoom?.Prototype, CacheType.Prototype); // Fail gracefully upon an invalid room ID if (parentRoom == null) { Logger.Error(nameof(AutogenMob), nameof(CreateAndInstantiateAllLevels), "Invalid Room ID. Cannot create and instantiate mobs."); return(new List <uint?>()); } foreach (var level in Enum.GetValues(typeof(MobLevel))) { var mob = Mob.NewPrototype((uint)parentID, (MobLevel)level); var levelName = MobLevelModifier.MapName((MobLevel)level); var desc = $"{levelName} {name}"; protoRoom.Animates.AddEntity(mob.Prototype, mob, true); mob.ShortDescription = $"a {desc}"; mob.LongDescription = $"A {desc} is here."; mob.Name = $"{levelName} {name}"; DataPersistence.SaveObject(mob); mobs.Add(mob.Spawn(true, (uint)parentRoom.Animates.Instance)); } DataPersistence.SaveObject(protoRoom); return(mobs); }
protected async Task <int> ProcessPresetDirectory(string presetDirectory, PresetBank bank, bool persist = true) { var count = 0; if (!Directory.Exists(presetDirectory)) { return(count); } Logger.Debug($"ProcessPresetDirectory {presetDirectory}"); var dirInfo = new DirectoryInfo(presetDirectory); foreach (var file in dirInfo.EnumerateFiles("*" + Extension)) { count++; if (persist) { var presetData = File.ReadAllText(file.FullName); var presetInfo = GetPreset(file.Name, presetData, bank); presetInfo.preset.SourceFile = file.FullName; await DataPersistence.PersistPreset(presetInfo.preset, presetInfo.presetData); } } foreach (var directory in dirInfo.EnumerateDirectories()) { count += await ProcessPresetDirectory(directory.FullName, bank.CreateRecursive(directory.Name), persist); } return(count); }
protected override bool Retrieve(IPersistence persistence, ref ePersistence phase) { base.Retrieve(persistence, ref phase); switch (phase) { case ePersistence.Initial: DataPersistence.Retrieve(persistence); string json = persistence.GetFieldValue(Constants.ModelDatasource, ""); if (json != "") { Dictionary <string, List <string> > fromJson = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(json); foreach (string key in fromJson.Keys) { IMapping mapping = new IMappingImpl(); mapping.DecisionModelNode = Tree.GetNodeByReference(key); mapping.FromStringArray(fromJson[key]); DecisionModelDataSources.Add(mapping); } } break; } return(true); }
protected async Task GetPresetsUsingFullBank(PresetBank bank, int start, int numPresets, string sourceFile) { if (start < 0) { Logger.Error("GetPresets start index is less than 0, ignoring. This is probably a bug or a " + "misconfiguration. Please report this including the full log file."); return; } var endIndex = start + numPresets; if (endIndex > PluginInstance.Plugin.PluginInfo.ProgramCount) { Logger.Error( $"Tried to retrieve presets between the index {start} and {endIndex}, but this would exceed maximum " + $"program count of {PluginInstance.Plugin.PluginInfo.ProgramCount}, ignoring. You might wish to " + "report this as a bug."); return; } for (var index = start; index < endIndex; index++) { PluginInstance.SetProgram(index); var preset = new PresetParserMetadata { PresetName = PluginInstance.GetCurrentProgramName(), BankPath = bank.BankPath, SourceFile = sourceFile + ":" + index, Plugin = PluginInstance.Plugin }; await DataPersistence.PersistPreset(preset, PluginInstance.GetChunk(false)); } }
public IList <string> GetNewPublications(string pageCreationTime) { IList <string> retVal = new List <string>(); try { DateTime d = DateTime.Parse(pageCreationTime); var pubs = (from publications in DataPersistence.GetSession().Linq <Publication>() select publications).ToList(); foreach (Publication publication in pubs) { if (publication.CreationTime != null && publication.CreationTime.Value.CompareTo(d) > 0) { retVal.Add(publication.FormatAsNewRow()); } } return(retVal); } catch (ArgumentNullException) { return(null); } catch (FormatException) { return(null); } catch (InvalidOperationException) { return(null); } }
protected override bool Persist(IPersistence persistence, ref ePersistence phase) { base.Persist(persistence, ref phase); switch (phase) { case ePersistence.Initial: DataPersistence.Persist(persistence); Dictionary <string, List <string> > toJson = new Dictionary <string, List <string> >(); foreach (IMapping mapping in DecisionModelDataSources) { toJson.Add(mapping.DecisionModelNode.Reference, mapping.ToStringArray()); } string json = ""; if (toJson.Count > 0) { json = JsonConvert.SerializeObject(toJson); } persistence.UpsertField(Constants.ModelDatasource, json); break; } return(true); }
/// <summary> /// Points an exit to another room. /// </summary> /// <param name="exit">The direction to set</param> /// <param name="room">The ID of the room</param> public void SetExit(Constants.EXIT exit, uint?room) { switch (exit) { case Constants.EXIT.NORTH: Exits.North = room; return; case Constants.EXIT.EAST: Exits.East = room; return; case Constants.EXIT.SOUTH: Exits.South = room; return; case Constants.EXIT.WEST: Exits.West = room; return; case Constants.EXIT.UP: Exits.Up = room; return; case Constants.EXIT.DOWN: Exits.Down = room; return; } // Update persistence since data structure has changed if (CacheType == CacheType.Prototype) { DataPersistence.SaveObject(this); } }
public ActionResult Publication(Publication a) { Dictionary <string, string> errors = a.CheckForValidity(); var matchingCiteKeys = (from pubs in DataPersistence.GetSession().Linq <Publication>() where pubs.CiteKey.Equals(a.CiteKey) select pubs); int ckCount = matchingCiteKeys.Count(); if (ckCount > 0 && a.Id == 0) { string linkToOther = "";// "<a href=\"Publication/" + matchingCiteKeys.First().Id + "\" target=\"_blank\">Click here to open the clash in a new window</a>"; const string ckKey = "CiteKey"; if (errors.ContainsKey(ckKey)) { errors[ckKey] += ". " + ErrorMessages.CiteKeyNotUnique + " " + linkToOther; } errors.Add(ckKey, ErrorMessages.CiteKeyNotUnique + " " + linkToOther); } // there are no errors if this is the case) if (errors.Count == 0 && ModelState.IsValid) { a.Owner = HttpContext.User.Identity.Name; a.SaveOrUpdateInDatabase(); return(Redirect("~/Entry")); } foreach (KeyValuePair <string, string> kvp in errors) { ModelState.AddModelError(kvp.Key, kvp.Value); } return(View(a)); }
protected override bool Retrieve(IPersistence persistence, ref ePersistence phase) { base.Retrieve(persistence, ref phase); switch (phase) { case ePersistence.Initial: _ShortName = persistence.GetFieldValue(Constants.Domain_Short_Name, ""); string relativePath = persistence.GetFieldValue(Constants.Domain_Sub_Model, ""); _Model = persistence.GetFullPath(relativePath); if (_Model != "") { Tree.AddSubModel(this); } _Methods.Clear(); _Methods.AddRange(persistence.GetFieldValues(Constants.Domain_Methods, "")); DataPersistence.Retrieve(persistence); break; } return(true); }
/// <summary> /// Creates a new room and adds it to the Prototype cache /// </summary> /// <param name="parentID">The parent ID of the area to add this room to.</param> /// <returns>The new prototype room</returns> public static Room NewPrototype(uint parentID) { var newRoom = new Room(); newRoom.Animates.CacheType = CacheType.Prototype; newRoom.Items.CacheType = CacheType.Prototype; newRoom.ShopItems.CacheType = CacheType.Prototype; newRoom.StorageItems.CacheType = CacheType.Prototype; var area = DataAccess.Get <Area>(parentID, CacheType.Prototype); if (area == null) { throw new LocaleException($"Failed to locate parent ID ({parentID}) when generating new room protoype."); } DataAccess.Add <Room>(newRoom, CacheType.Prototype); newRoom.Animates.PrototypeParents.Add((uint)newRoom.Prototype); newRoom.Items.PrototypeParents.Add((uint)newRoom.Prototype); newRoom.ShopItems.PrototypeParents.Add((uint)newRoom.Prototype); newRoom.StorageItems.PrototypeParents.Add((uint)newRoom.Prototype); DataAccess.Add <EntityContainer>(newRoom.Animates, CacheType.Prototype); DataAccess.Add <EntityContainer>(newRoom.Items, CacheType.Prototype); DataAccess.Add <EntityContainer>(newRoom.ShopItems, CacheType.Prototype); DataAccess.Add <EntityContainer>(newRoom.StorageItems, CacheType.Prototype); area.Rooms.AddEntity(newRoom.Prototype, newRoom, true); DataPersistence.SaveObject(newRoom); return(newRoom); }
/// <summary> /// Creates a new area and adds it to the Prototype cache /// </summary> /// <param name="parentID">The parent ID of the world to add this area to.</param> /// <returns>The new prototype room</returns> public static Area NewPrototype(uint parentID) { var newArea = new Area(); newArea.Rooms.CacheType = CacheType.Prototype; newArea.AutogeneratedPrototypeItems.CacheType = CacheType.Prototype; newArea.AutogeneratedPrototypeMobs.CacheType = CacheType.Prototype; var world = DataAccess.Get <World>(parentID, CacheType.Prototype); if (world == null) { throw new LocaleException($"Failed to locate parent ID ({parentID}) when generating new area protoype."); } DataAccess.Add <Area>(newArea, CacheType.Prototype); newArea.Rooms.PrototypeParents.Add((uint)newArea.Prototype); newArea.AutogeneratedPrototypeItems.PrototypeParents.Add((uint)newArea.Prototype); newArea.AutogeneratedPrototypeMobs.PrototypeParents.Add((uint)newArea.Prototype); DataAccess.Add <EntityContainer>(newArea.Rooms, CacheType.Prototype); DataAccess.Add <EntityContainer>(newArea.AutogeneratedPrototypeItems, CacheType.Prototype); DataAccess.Add <EntityContainer>(newArea.AutogeneratedPrototypeMobs, CacheType.Prototype); world.Areas.AddEntity(newArea.Prototype, newArea, true); DataPersistence.SaveObject(newArea); return(newArea); }
public override async Task DoScan() { InitializeInternal(); var parser = new KoaBankFileParser(ExportConfig.KoaFileHeader, ExportConfig.KoaPresetNameLength, ExportConfig.KoaPresetLength, ExportConfig.KoaNumPresets); var converter = new RolandConverter(ExportConfig); converter.LoadDefinitionFromCsvString(Encoding.UTF8.GetString(GetDefinitionData())); foreach (var presetFile in PresetFiles) { var presets = parser.Parse(presetFile); var presetBankName = Path.GetFileNameWithoutExtension(presetFile); foreach (var parsedPreset in presets) { converter.SetFileMemory(parsedPreset.PresetData); var preset = new PresetParserMetadata { PresetName = parsedPreset.PresetName.Trim(), Plugin = PluginInstance.Plugin, BankPath = presetBankName, SourceFile = presetFile + ":" + parsedPreset.Index }; PostProcessPreset(preset, converter); await DataPersistence.PersistPreset(preset, converter.Export()); } } await base.DoScan(); }
public BallisticsCalculatorViewModel() { _FileName = ""; _TrajectoryPlot = new PlotModel(); _TrajectoryPlot.Title = "Trajectory"; _WindagePlot = new PlotModel(); _WindagePlot.Title = "Horizontal Deviation"; RaisePropertyChanged(nameof(TrajectoryPlot)); _BulletTypes = new List <string>(); string[] values = Enum.GetNames(typeof(BulletShapeEnum)); foreach (string B in values) { _BulletTypes.Add(B.ToString()); } EstimateBCCommand = new RelayCommand(GetTestBulletBC, null); OpenBCestimatorCommand = new RelayCommand(OpenBCestimator, null); RunPreShotCheckCommand = new RelayCommand(RunPreShotCheck, null); ShootCommand = new RelayCommand(Shoot, null); SaveFileCommand = new RelayCommand(SaveFile, null); SaveFileAsCommand = new RelayCommand(SaveFileAs, null); OpenRangeFinderCommand = new RelayCommand(OpenRangeFinder, null); ZeroLocationCommand = new RelayCommand(ZeroLocation, null); ShotLocationCommand = new RelayCommand(ShotLocation, null); DataPersistence lDP = new DataPersistence(); Ballistics lBCls; string lf = lDP.AppDataFolder + "\\default.bdf"; lBCls = lDP.ParseBallisticSolution(lf); _MyBallisticsCalculator = lBCls; if (_MyBallisticsCalculator.ShotDistance == 0) { _MyBallisticsCalculator.ShotDistance = _MyBallisticsCalculator.MaxRange() * 0.75; } Shoot(); }
public static void CreateNewProfile(string profileName) { PlayerProfile newProfile = new PlayerProfile(profileName); playerProfiles.Add(newProfile); DataPersistence.SaveGameData(); }
public void UpdateHighscore() { if (score.GetScore() > DataPersistence.GetHighScore()) { DataPersistence.SetHighScore(score.GetScore()); } }
public void AnswerCallback(GameObject gameObject) { float correctAnswer = 0; // Find the value of the correct answer foreach (Tuple <float, bool> ans in question.answers) { if (ans.Item2) { correctAnswer = ans.Item1; break; } } // If the player did not collide with anything if (gameObject == null) { // Reset the multiplier and decrement the life count score.ResetMultiplier(); --lifeCount; // Show the incorrect panel with the message StartCoroutine(ShowIncorrectPanel(question.question + " = " + correctAnswer)); return; } // Get the answer collided by the player float answer = float.Parse(answers[int.Parse(gameObject.name)].transform.Find("text").GetComponent <TextMesh>().text);; // The player answered wrongly if (answer != correctAnswer) { // Reset the multiplier, decrement the life count and show the incorrect panel score.ResetMultiplier(); --lifeCount; StartCoroutine(ShowIncorrectPanel(question.question + " = " + correctAnswer)); } else { // Increase the multiplier and show the correct panel score.IncrementMultiplier(); StartCoroutine(ShowCorrectPanel()); } // Remove the collided object Destroy(gameObject); // Update the life count display lifeText.text = lifeCount + "x"; // End the game if the life count falls to 0 if (lifeCount <= 0) { // Update the highscore and load the game over scene UpdateHighscore(); DataPersistence.SetPreviousScore(score.GetScore()); SceneManager.LoadScene("GameOver"); } }
void Start() { currentScoreText.text = "Current Score: " + DataPersistence.GetPreviousScore().ToString(); highScoreText.text = "Highscore: " + DataPersistence.GetHighScore().ToString(); ReplayGameOverButton.onClick.AddListener(ReplayGameOver); QuitGameOverButton.onClick.AddListener(QuitGameOver); }
public ActionResult DeleteAllEntries() { ISession ses = DataPersistence.GetSession(); ses.Delete("from Publication p"); ses.Flush(); return(Redirect("/")); }
public int HasPublicationChanged(string queryString) { var split = queryString.Split(' '); int id = 0; string pageCreationTime = ""; int count = 0; foreach (string s in split) { if (!String.IsNullOrEmpty(s)) { if (count == 0) { pageCreationTime = s; } if (count == 1) { pageCreationTime += " " + s; } if (count == 2) { id = Int32.Parse(s); } count++; } } if (id == -1) { return(-1); // page is at creation stage, so does not exist in the db and cannot have changed. } ISession ses = DataPersistence.GetSession(); DateTime d = DateTime.Parse(pageCreationTime); Publication pub = null; if (id > 0) { pub = (from p in ses.Linq <Publication>() where p.Id == id select p).First(); } if (pub == null) { return(-1); // means that the publication does not exist in the db and therefore cannot have changed } if (pub.DeletionTime > d) { return(1); // 1 signifies deletion since page load } if (pub.AmendmentTime > d) { return(2); // 2 signifies amendment since page load } return(0); // 0 signifies no change since page load }
// Start is called before the first frame update void Start() { isMuted = DataPersistence.GetMute(); SoundButton.GetComponentInChildren <Text>().text = isMuted ? "Sound Off" : "Sound On"; SoundButton.onClick.AddListener(() => { if (isMuted) { DataPersistence.SetMute(false); SoundButton.GetComponentInChildren <Text>().text = "Sound On"; isMuted = false; } else { DataPersistence.SetMute(true); SoundButton.GetComponentInChildren <Text>().text = "Sound Off"; isMuted = true; } }); imgAgeGrp = DropdownAge.GetComponent <Image>(); imgDifficulty = DropdownDifficulty.GetComponent <Image>(); Debug.Log(DataPersistence.Settings.GetAgeGroup()); if (DataPersistence.Settings.GetDifficulty() == Difficulty.EASY) { DropdownDifficulty.value = 0; imgDifficulty.sprite = easy; } else if (DataPersistence.Settings.GetDifficulty() == Difficulty.MEDIUM) { DropdownDifficulty.value = 1; imgDifficulty.sprite = medium; } else if (DataPersistence.Settings.GetDifficulty() == Difficulty.HARD) { DropdownDifficulty.value = 2; imgDifficulty.sprite = hard; } if (DataPersistence.Settings.GetAgeGroup() == AgeGroup._6TO8) { DropdownAge.value = 0; imgAgeGrp.sprite = grp1; } else if (DataPersistence.Settings.GetAgeGroup() == AgeGroup._9TO10) { DropdownAge.value = 1; imgAgeGrp.sprite = grp2; } else if (DataPersistence.Settings.GetAgeGroup() == AgeGroup._11TO12) { DropdownAge.value = 2; imgAgeGrp.sprite = grp3; } }
/// <summary> /// Handles the CacheObjectRemoved event. Only DataAccess should call this directly. /// </summary> /// <param name="source">The object raising the event</param> /// <param name="args">The args containing the ID of the entity to remove</param> protected override void OnCacheObjectRemoved(object source, CacheObjectEventArgs args) { _entityList.Remove(args.ID); OnEntityRemoved(new CacheObjectEventArgs(args.ID, CacheType)); // Persist this entity to disk since the data structure has changed if (CacheType == CacheType.Prototype) { DataPersistence.SaveObject(this); } }
private void SaveFile() { if (_FileName == "") { SaveFileAs(); return; } DataPersistence lDP = new DataPersistence(); lDP.SaveBallisticSolutionData(_MyBallisticsCalculator, _FileName); }
private void RunOperation(ObfuscationInfo obfuscationOperation, StatusInformation status = null) { IEnumerable <string> originData = null; DataPersistence.ConnectionString = obfuscationOperation.Destination.ConnectionString; var dataSet = DataPersistence.GetTableData(obfuscationOperation); DataTable scrambledDataTable = null; switch (obfuscationOperation.Origin.DataSourceType) { case DataSourceType.CSV: originData = GetSourceData(obfuscationOperation); break; case DataSourceType.DNIGenerator: originData = DniNie.GenerateDNI(dataSet.Tables[0].Rows.Count); break; case DataSourceType.NIEGenerator: originData = DniNie.GenerateNIE(dataSet.Tables[0].Rows.Count); break; case DataSourceType.NIFGenerator: originData = DniNie.GenerateNIF(dataSet.Tables[0].Rows.Count); break; case DataSourceType.Scramble: scrambledDataTable = ScrambleDataSet(obfuscationOperation.Destination, dataSet); break; default: originData = new List <string>(); break; } if (status == null) { status = new StatusInformation(); } if (obfuscationOperation.Origin.DataSourceType == DataSourceType.Scramble) { UpdateDataSet(dataSet, scrambledDataTable, obfuscationOperation); } else { UpdateDataset(dataSet, originData, obfuscationOperation.Destination.Columns[0].Name); } status.Message = $"...Saving obfuscation on {obfuscationOperation.Destination.Name}"; StatusChanged?.Invoke(status, null); DataPersistence.PersistOfuscation(obfuscationOperation, dataSet); }
// Use this for initialization void Awake() { if (data == null) { DontDestroyOnLoad(this); data = this; } else { Destroy(this); } }
public IList <string> DoSearchRaw(string searchString) { IList <string> retVal = new List <string>(); var s = DataPersistence.GetActivePublicationsMatching(searchString); foreach (var v in s) { retVal.Add(v.ToHtmlTableRowWithLinks()); } return(retVal); }
public bool DeletePublication(int deletionId) { try { DataPersistence.DeletePublication(deletionId); } catch { return(false); } return(true); }
public ActionResult RestorePublication(int?id) { if (id == null) { return(Redirect("/Entry/")); } int notNullId = (int)id; DataPersistence.RestorePublication(notNullId); ViewData["message"] = "Item was restored successfully"; return(Redirect("/Entry/Publication/" + notNullId)); }
public ActionResult Search(string s) { if (String.IsNullOrEmpty(s)) { return(View()); } var res = DataPersistence.GetActivePublicationsMatching(s); ViewData["searchterm"] = s; return(View(res)); }
public ActionResult DeletePublication(int id) { var pub = (from p in (DataPersistence.GetSession().Linq <Publication>()) where p.Id == id select p); if (pub.Count() < 1) { Redirect("/Entry/Publication"); } return(View(pub.First())); }
/// <summary> /// Initializes a new Data instance with the given name. /// This name is used to resolve the path to the persisted data. /// </summary> /// <param name="planName">Name of the training plan.</param> public Data(string planName) { Instance = this; // create persistence handler for this `Data` instance. var persistence = new DataPersistence(this); // load persisted data // NOTE: Must load training plan first because its name is needed to find the other files _trainingPlan = persistence.LoadPlan(planName); _trainingPlan.SetData(this); Pace = persistence.LoadPace(); _workouts = new List<Workout>(persistence.LoadWorkouts()); _categories = new List<WorkoutCategory>(persistence.LoadCategories()); Logger.Info("Data instantiated"); }