/// @param savable /// The savable to deserialize from file /// /// @return Whether the data was successfully loaded /// public static void Load(this ISavable savable) { var jsonData = new Dictionary <string, object>(); string filePath = string.Format(k_filePathFormat, savable.GetType().ToString()); if (FileSystem.DoesFileExist(filePath, FileSystem.Location.Persistent)) { jsonData = JsonWrapper.ParseJsonFile(filePath, FileSystem.Location.Persistent); if (jsonData == null) { // Delete the corrupted file FileSystem.DeleteFile(filePath, FileSystem.Location.Persistent); // Load a backup string backup = string.Format(k_filePathBackupFormat, savable.GetType().ToString()); jsonData = JsonWrapper.ParseJsonFile(backup, FileSystem.Location.Persistent); } } else if (FileSystem.DoesFileExist(filePath, FileSystem.Location.Cache)) { // Legacy file in cache jsonData = JsonWrapper.ParseJsonFile(filePath, FileSystem.Location.Cache); } savable.Deserialize(jsonData); }
internal bool SaveConfig(ISavable config, bool markUser, string descErr) { IEnumerable <ConfigurazioneSuFile> selectedConfig; UInt64 userId; //Check if config already exists selectedConfig = from tmp in configurations where tmp.config.SavableName == config.SavableName && tmp.config.SavableParentName == config.SavableParentName && tmp.type == config.GetType() select tmp; userId = markUser == true ? App.CurrentUserId : 0; selectedConfig = from tmp in selectedConfig where tmp.userId == userId select tmp; if (selectedConfig.Count() == 0) { //Creazione di una nuova ConfigurazioneSuFile configurazione = new ConfigurazioneSuFile(); configurazione.type = config.GetType(); configurazione.userId = userId; configurazione.config = config; configurations.Add(configurazione); } else if (selectedConfig.Count() == 1) { //Aggiornamento della config esistente selectedConfig.ElementAt(0).config = config; } else { Log.main.Add(new Mess(LogType.Warn, Log.main.warnUserText, "nel file di configurazione:<" + fullFilePath + ">, ho trovato più di una impostazione con " + descErr + ", l'impostazione non sarà salvata")); return(false); } return(true); }
public static string SaveObj(ISavable obj) { Debug.Log(obj); FieldInfo[] prop = obj.GetType().GetFields(); Array.Sort(prop, delegate(FieldInfo x, FieldInfo y) { return(x.Name.CompareTo(y.Name)); }); List <string> comps = new List <string>(); comps.Add(obj.getPrefab()); string STransform = JsonUtility.ToJson(new STransform(((Component)obj).gameObject.transform)); comps.Add(STransform); foreach (FieldInfo p in prop) { //Debug.Log(p); if (null != p && !p.IsNotSerialized) { Debug.Log(p); Type pType = p.FieldType; object pVal = p.GetValue(obj); pVal = Convert.ChangeType(pVal, pType); //Debug.Log(pVal); comps.Add(JsonUtility.ToJson(pVal)); } } ListContainer <string> compsContainer = new ListContainer <string>(); compsContainer.lis = comps; string retval = JsonUtility.ToJson(compsContainer); return(retval); }
/// <summary> /// Writes the object. /// </summary> /// <param name="value">Value.</param> /// <param name="type">Type.</param> protected virtual void WriteObject(object value, Type type) { if (value is ISavable) { m_Writer.Write("{"); m_IsFirstProperty = true; ISavable savable = value as ISavable; savable.OnWrite(this); m_Writer.Write("}"); } else if (SaveGameTypeManager.HasType(type)) { m_Writer.Write("{"); m_IsFirstProperty = true; SaveGameType saveGameType = SaveGameTypeManager.GetType(type); saveGameType.Write(value, this); m_Writer.Write("}"); } #if !UNITY_WSA || !UNITY_WINRT else if (value is ISerializable) { SerializationInfo info = new SerializationInfo(type, new FormatterConverter()); ISerializable serializable = value as ISerializable; serializable.GetObjectData(info, new StreamingContext(StreamingContextStates.All)); WriteSerializationInfo(info); } #endif else { WriteSavableMembers(value, type); } }
public static void LoadProject <T>(ISavable <T> view, bool dialog = false, bool message = true) { if (dialog) { Directory.CreateDirectory(view.DefaultSaveFolder); } string path = dialog ? IOHelper.LoadProjectDialog(view.DefaultSaveFolder) : view.AutoSavePath; // If the file name is not an empty string open it for saving. if (path == "") { return; } try { view.SetSaveData(LoadJson <T>(path)); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); Console.WriteLine(ex.Message); if (message) { MessageBox.Show("Project could not be loaded!"); ex.Show(); } } }
//Friend Function DammiConfig(ByRef config As Configs.Base, distinguiUtente As Boolean, descErr As String, Optional tipoLogErr As Tipi = Tipi._Nothing) As Boolean internal bool GetConfig(ref ISavable config, bool markUser, Mess logMess) { IEnumerable <ConfigurazioneSuFile> configFiltrate; string name, parent; Type type; name = config.SavableName; parent = config.SavableParentName; type = config.GetType(); configFiltrate = from tmp in configurations where tmp.config.SavableName == name && tmp.config.SavableParentName == parent && tmp.type == type select tmp; if (markUser == true) { configFiltrate = from tmp in configFiltrate where tmp.userId == App.CurrentUserId select tmp; } if (configFiltrate.Count() == 0) { logMess.testoDaLoggare = "nel file di configurazione:<" + fullFilePath + ">, non ho trovato impostazioni con " + logMess.testoDaLoggare; Log.main.Add(logMess); return(false); } else if (configFiltrate.Count() > 1) { logMess.testoDaLoggare = "nel file di configurazione:<" + fullFilePath + ">, ho trovato più di una impostazione con " + logMess.testoDaLoggare + ", sarà preso il primo valore"; Log.main.Add(new Mess(LogType.ERR, Log.main.errUserText, logMess.testoDaLoggare)); //In questo caso deve essere sempre errore per questo ho utilizzato un nuovo mess } config = configFiltrate.ElementAt(0).config; return(true); }
/// <summary> /// Load specified ISavable object from a stream /// </summary> /// <param name="savable">ISavable to load</param> /// <param name="stream">Stream to load</param> public static void LoadFromStream(ISavable savable, PCBinaryLoadStream stream) { if (savable == null) { throw new ArgumentNullException("Invalid ISavable object."); } savable.Load(stream); }
public void Add(ISavable obj) { lock (_queue) { _queue.Enqueue(obj); Monitor.Pulse(_queue); } }
/// <summary> /// Save specified ISavable object to stream /// </summary> /// <param name="savable">ISavable to save</param> /// <param name="stream">Stream to save</param> public static void SaveToStream(ISavable savable, PCBinarySaveStream stream) { if (savable == null) { throw new ArgumentNullException("Invalid ISavable object."); } savable.Save(stream); }
public static void Save() { foreach (PluginPair plugin in AllPlugins) { ISavable savable = plugin.Plugin as ISavable; savable?.Save(); } }
/// <summary> /// Create an instance of XmlSaveStream and save given ISavable /// </summary> /// <param name="savable">ISavable to save</param> public XmlSaveStream(ISavable savable) { Document = new XmlDocument(); XmlElement rootNode = new XmlElement("SaveData"); savable.Save(rootNode, this); Document.AppendChild(rootNode); }
public void LoadGame() { var savableObjects = FindObjectsOfType <MonoBehaviour>().Where(monoObject => monoObject is ISavable).ToList(); ISavable playerObject = savableObjects.First(monoObject => monoObject is PlayerController) as ISavable; playerObject?.LoadData(GameSave.playerSaveData); }
public async void Load <T>(ISavable <T> savable) { var tmp = await backEndSaveSystem.Load <T>(objectID); savable.OnLoad(tmp); EventBroker.Instance().SendMessage(new EventAfterLoad(objectID)); //Debug.Log("Object loaded from backEndSaveSystem: " + objectID); }
public static void Load(ISavable savable) { BinaryFormatter bf = new BinaryFormatter(); Stream stream = new FileStream(SAVE_BASE_PATH + savable.GetDefaultFileName(), FileMode.Open); SaveDataBase save = (SaveDataBase)bf.Deserialize(stream); savable.LoadSaveData(save); }
public void SaveToFile(string directoryPath, string fileName, ISavable report) { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } File.WriteAllText(Path.Combine(directoryPath, fileName), report.ToString()); }
private ISavable GetBusinessObject() { ISavable businessObject = null; BindingSource source = _dataSource as BindingSource; if (source != null) businessObject = source.DataSource as ISavable; return businessObject; }
public static void SaveToolFile <T, T2>(ISavable <T> view, T2 obj, bool dialog = false) { if (dialog) { Directory.CreateDirectory(view.DefaultSaveFolder); } string path = dialog ? IOHelper.SaveProjectDialog(view.DefaultSaveFolder) : view.AutoSavePath; SaveJson(path, obj); }
public static T2 LoadToolFile <T, T2>(ISavable <T> view, bool dialog = false) { if (dialog) { Directory.CreateDirectory(view.DefaultSaveFolder); } string path = dialog ? IOHelper.LoadProjectDialog(view.DefaultSaveFolder) : view.AutoSavePath; return(LoadJson <T2>(path)); }
internal AppSettings(XElement root, ISavable savable) { _content = root.Element("appSettings"); if (_content is null) { _content = new XElement("appSettings"); root.Add(_content); } _properties = new AppSettingsPropertySet(_content, savable); }
internal ConnectionStrings(XElement root, ISavable savable) { _content = root.Element("connectionStrings"); if (_content is null) { _content = new XElement("connectionStrings"); root.Add(_content); } _properties = new ConnectionStringsPropertySet(_content, savable); }
internal ConfigSections(XElement root, ISavable savable) { _content = root.Element("configSections"); if (_content is null) { _content = new XElement("configSections"); root.AddFirst(_content); } _groups = new ConfigSectionGroupSet(_content, root, savable); _sections = new ConfigSectionSet(_content, root, savable); }
public void SaveAs(ISavable savable, string fileName, string extension, string fileTypeName, string title) { var fileDialog = GetSaveFileDialog(fileName, extension, fileTypeName, title); if (fileDialog.ShowDialog() != true) { return; } savable.Save(fileDialog.FileName); }
public void CallGlobalDataSave(ISavable savable, SaveID Id) { if (GlobalGameData.ContainsKey(Id)) { GlobalGameData[Id] = savable.OnSave(); } else { GlobalGameData.Add(Id, savable.OnSave()); } }
public void CallRecordSave(Record record, ISavable savable, SaveID Id) { if (record.RecordGameData.ContainsKey(Id)) { record.RecordGameData[Id] = savable.OnSave(); } else { record.RecordGameData.Add(Id, savable.OnSave()); } }
public void Add(ISavable obj) { lock (_queue) { #if DEBUG ParallelUtility.countLocks("_queue"); #endif _queue.Enqueue(obj); Monitor.Pulse(_queue); } }
void OnBeforeSave(object sender, BeforeSaveEventArgs e) { DataMap map = e.DataMap; Type t = map.ObjectType; ISavable obj = e.DataObject; var audit = new SaveAudit { Action = e.SaveType, TableName = e.DataMap.DataItem.SaveToTable }; if (!string.IsNullOrEmpty(e.DataMap.DataItem.SchemaName)) { audit.SchemaName = e.DataMap.DataItem.SchemaName; } if (e.SaveType == SaveType.Insert) { foreach (PropertyInfo pi in t.GetProperties()) { if ((pi.Name == "DataRowState") || (pi.Name == "OriginalValues")) { continue; } audit.Properties.Add(new SaveAuditProperty(pi.Name, null, pi.GetValue(obj, null))); } } else if (e.SaveType == SaveType.Update) { foreach (IDataMapField field in e.DataMap.KeyFields) { audit.Keys.Add(new SaveAuditProperty(field.FieldName, field.Property.GetValue(obj, null), null)); } foreach (var kv in obj.OriginalValues) { PropertyInfo pi = t.GetProperty(kv.Key); object v = pi.GetValue(obj, null); if (((kv.Value != null) && (!kv.Value.Equals(v))) || ((kv.Value == null) && (v != null))) { audit.Properties.Add(new SaveAuditProperty(kv.Key, kv.Value, v)); } } } if ((AuditHandler != null) && (audit.Properties.Count > 0)) { AuditHandler(audit); } }
/// <summary> /// This event is raised when the active tab (designer) changes. /// </summary> private void DesignersManager_DesignerChanged(object sender, DesignerEventArgs e) { if (e.Designer == null || e.Designer.File == null || !(e.Designer is ISavable)) { this.Enabled = false; this.Text = "Save as..."; return; } this.m_CurrentSavable = (e.Designer as ISavable); this.Enabled = this.m_CurrentSavable.CanSave; this.Text = "Save " + this.m_CurrentSavable.SaveName + " as..."; }
private static async Task SaveFiles(string pathToBeatmapFile, string outputFolder, string audioFilename, IStoryboardable backgroundFileNames, ISavable savable) { string rootPath = Path.GetDirectoryName(pathToBeatmapFile) !; await AsyncSaveAudio(rootPath, outputFolder, audioFilename); SaveImages(rootPath, outputFolder, backgroundFileNames.ImagePaths); SaveConfig(outputFolder, savable); }
/// <summary> /// Resets all action behaviors. /// </summary> /// <param name="objectToBind">Target object.</param> public void ResetActionBehaviors(ISavable objectToBind) { InitializeControls(true); BindingSource rootSource = _dataSource as BindingSource; if (rootSource != null) { AddEventHooks(objectToBind); } _bindingSourceTree = BindingSourceHelper.InitializeBindingSourceTree(_container, rootSource); _bindingSourceTree.Bind(objectToBind); }
//---------------------------------------------------------------------------------------------------------------------- private void Window_Loaded_1(object sender, RoutedEventArgs e) { var viewModel = new PlayerViewModel(); DataContext = viewModel; IPlayerActionQueriable playerAction = DataContext as IPlayerActionQueriable; if (playerAction != null) { playerAction.PlayQuery += Play; playerAction.PauseQuery += Pause; playerAction.StopQuery += Stop; playerAction.ListChangeQuery += PlayerActionOnListChangeQuery; playerAction.FolderDialogQuery += playerAction_FolderDialogQuery; playerAction.ChangePathDialogQuery += playerAction_ChangePathDialogQuery; } ISavable saveModel = DataContext as ISavable; if (saveModel != null) { this.Closing += (s, ev) => saveModel.Save();; } // workPlayer.Stretch = Stretch.; workPlayer.StretchDirection = StretchDirection.Both; Binding bindingCurrentTrackDeletePressCommand = new Binding("CurrentTrackDeletePressCommand"); bindingCurrentTrackDeletePressCommand.Source = DataContext; BindingOperations.SetBinding(this, PlayerWindow.CurrentTrackDeletePressCommandProperty, bindingCurrentTrackDeletePressCommand); Binding bindingCurrentTrackDoubleClickCommand = new Binding("CurrentTrackDoubleClickCommand"); bindingCurrentTrackDoubleClickCommand.Source = DataContext; BindingOperations.SetBinding(this, PlayerWindow.CurrentTrackDoubleClickCommandProperty, bindingCurrentTrackDoubleClickCommand); IScrollIntoViewAction scrollIntoViewAction = (IScrollIntoViewAction)DataContext; scrollIntoViewAction.MainGridScrollIntoView += i => { ScrollIntoView(); }; playerAction.OnLoad(); DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromMilliseconds(500); timer.Tick += timer_Tick; timer.Start(); }
public void AddSavable(ISavable s) { savables.Add(s); }
public void RemoveSavable(ISavable s) { savables.Remove(s); }
private bool ExecuteSaveAction(ISavable savableObject, ITrackStatus trackableObject, CslaActionExtenderProperties props) { var result = true; bool okToContinue = true; BusinessBase businessObject = null; bool savableObjectIsBusinessBase = savableObject is BusinessBase; if (savableObjectIsBusinessBase) businessObject = savableObject as BusinessBase; if (savableObjectIsBusinessBase) { if (!businessObject.IsValid) { HasBrokenRulesEventArgs argsHasBrokenRules = new HasBrokenRulesEventArgs( props.CommandName, businessObject.GetBrokenRules().ErrorCount > 0, businessObject.GetBrokenRules().WarningCount > 0, businessObject.GetBrokenRules().InformationCount > 0, _autoShowBrokenRules); OnHasBrokenRules(argsHasBrokenRules); okToContinue = !argsHasBrokenRules.Cancel; //in case the client changed it _autoShowBrokenRules = argsHasBrokenRules.AutoShowBrokenRules; } } if (okToContinue) { if (savableObjectIsBusinessBase) { if (_autoShowBrokenRules && !businessObject.IsValid) { // todo: add child broken rules string brokenRules = string.Empty; foreach (var brokenRule in businessObject.GetBrokenRules()) { var lambdaBrokenRule = brokenRule; var friendlyName = PropertyInfoManager.GetRegisteredProperties(businessObject.GetType()).Find( c => c.Name == lambdaBrokenRule.Property).FriendlyName; brokenRules += string.Format("{0}: {1}{2}", friendlyName, brokenRule, Environment.NewLine); } #if !WEBGUI MessageBox.Show(brokenRules, Resources.ActionExtenderErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error); #else MessageBox.Show(brokenRules, Resources.ActionExtenderErrorCaption, MessageBoxButtons.OK, MessageBoxIcon.Error, messageBoxClosedHandler, false); #endif } } if (trackableObject.IsValid) { CslaActionCancelEventArgs savingArgs = new CslaActionCancelEventArgs(false, props.CommandName); OnObjectSaving(savingArgs); if (!savingArgs.Cancel) { _bindingSourceTree.Apply(); ISavable objectToSave; if (Csla.ApplicationContext.AutoCloneOnUpdate == false) objectToSave = ((ICloneable)savableObject).Clone() as ISavable;// if not AutoClone, clone manually else objectToSave = savableObject; if (objectToSave != null) { try { RemoveEventHooks(savableObject); savableObject = savableObject.Save() as ISavable; OnObjectSaved(new CslaActionEventArgs(props.CommandName)); switch (props.PostSaveAction) { case PostSaveActionType.None: if (props.RebindAfterSave) { _bindingSourceTree.Bind(savableObject); AddEventHooks(savableObject); } break; case PostSaveActionType.AndClose: CloseForm(); break; case PostSaveActionType.AndNew: OnSetForNew(new CslaActionEventArgs(props.CommandName)); AddEventHooks(savableObject); break; } } catch (Exception ex) { _bindingSourceTree.Bind(objectToSave); AddEventHooks(objectToSave); OnErrorEncountered(new ErrorEncounteredEventArgs(props.CommandName, new ObjectSaveException(ex))); // there was some problem result = false; } } else { // did not find bound object so don't bother raising the Clicked event result = false; } _bindingSourceTree.SetEvents(true); } } else { OnBusinessObjectInvalid(new CslaActionEventArgs(props.CommandName)); // object not valid or has broken rules set to invalidate it due to this control's properties result = false; } } else { // process was canceled from the HasBrokenRules event (okToContinue = false) result = false; } return result; }
private void RemoveEventHooks(ISavable objectToBind) { INotifyPropertyChanged propChangedObjParent = objectToBind as INotifyPropertyChanged; if (propChangedObjParent != null) { propChangedObjParent.PropertyChanged -= propChangedObj_PropertyChanged; } INotifyChildChanged propChangedObjChild = objectToBind as INotifyChildChanged; if (propChangedObjChild != null) { propChangedObjChild.ChildChanged -= propChangedObj_ChildChanged; } }
private void AddEventHooks(ISavable objectToBind) { // make sure to not attach many times RemoveEventHooks(objectToBind); INotifyPropertyChanged propChangedObjParent = objectToBind as INotifyPropertyChanged; if (propChangedObjParent != null) { propChangedObjParent.PropertyChanged += propChangedObj_PropertyChanged; } INotifyChildChanged propChangedObjChild = objectToBind as INotifyChildChanged; if (propChangedObjChild != null) { propChangedObjChild.ChildChanged += propChangedObj_ChildChanged; } }
private void ConfirmCancel(ISavable savableObject, string commandName) { MessageBoxConfirm( _warnOnCancelMessage, delegate(object delegateSender, EventArgs eventArgs) { if (((Form) delegateSender).DialogResult == DialogResult.Yes) { _bindingSourceTree.Cancel(savableObject); InitializeControls(true); OnClicked(new CslaActionEventArgs(commandName)); } } ); }
public SaveButtonViewModel(ISavable savable) { this.savable = savable; }
public void save(ISavable what) { BinaryWriter writer = new BinaryWriter(m_stream); what.save(writer); }