public void BackupClient(string file, byte[] data) { if (!SdeAppConfiguration.BackupsManagerState || !IsStarted || _backupThread.IsCrashed) { return; } if (file == null) { throw new ArgumentNullException("file"); } if (data == null) { return; } try { string relativePath = GrfPath.Combine("client", Path.GetFileName(file)); //.ReplaceFirst(GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath) + (isFtp ? "/" : "\\"), ""); if (String.IsNullOrEmpty(relativePath)) { return; } _validateOpened(); string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}"); File.WriteAllBytes(tempFile, data); string fullPath = GrfPath.Combine(_paths[_currentId], relativePath); _localToGrfPath[_currentId][tempFile] = fullPath; } catch { } }
public void Backup(string file) { if (!SdeAppConfiguration.BackupsManagerState || !IsStarted || _backupThread.IsCrashed) { return; } if (file == null) { throw new ArgumentNullException("file"); } try { string relativePath = file.ReplaceFirst(GrfPath.GetDirectoryName(ProjectConfiguration.DatabasePath) + IOHelper.Slash, ""); if (String.IsNullOrEmpty(relativePath)) { return; } _validateOpened(); string fullPath = GrfPath.Combine(_paths[_currentId], relativePath); string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}"); IOHelper.Copy(file, tempFile); _localToGrfPath[_currentId][tempFile] = fullPath; } catch { } }
public void Backup(string file) { if (!SdeAppConfiguration.BackupsManagerState || !_isStarted || _isCrashed) { return; } if (file == null) { throw new ArgumentNullException("file"); } try { string relativePath = file.ReplaceFirst(GrfPath.GetDirectoryName(SdeFiles.ServerDbPath) + "\\", ""); if (String.IsNullOrEmpty(relativePath)) { return; } _validateOpened(); if (!_paths.ContainsKey(_currentId)) { _paths[_currentId] = _getGrfPath(); } string fullPath = GrfPath.Combine(_paths[_currentId], relativePath); string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}"); File.Copy(file, tempFile); _grf.Commands.AddFileAbsolute(fullPath, tempFile); } catch { } }
public override sealed void LoadFromClipboard(string content) { bool fileExists; try { fileExists = File.Exists(content); } catch { fileExists = false; } string path; if (fileExists) { path = content; } else { path = TemporaryFilesManager.GetTemporaryFilePath("clipboard_{0:000}"); File.WriteAllText(path, content); } DbDebugItem <TKey> debug = new DbDebugItem <TKey>(this); debug.FilePath = path; string text = File.ReadAllText(path); OnLoadFromClipboard(debug, text, path, this); Attached["FromUserRawInput"] = true; Table.EnableRawEvents = true; OnLoadDataFromClipboard(debug, text, path, this); }
public App() { Configuration.ConfigAsker = SdeAppConfiguration.ConfigAsker; ProjectConfiguration.ConfigAsker = SdeAppConfiguration.ConfigAsker; Settings.TempPath = GrfPath.Combine(SdeAppConfiguration.ProgramDataPath, "~tmp"); ErrorHandler.SetErrorHandler(new SdeErrorHandler()); TemporaryFilesManager.ClearTemporaryFiles(); }
private static void _writeLuaFiles(LuaParser accId, LuaParser accName, AbstractDb <int> db) { string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accId.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncAccId, File.ReadAllBytes(file)); file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accName.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncAccName, File.ReadAllBytes(file)); }
public override void AddNewItemRaw() { try { string defaultValue = Clipboard.ContainsText() ? Clipboard.GetText() : ""; InputDialog dialog = new InputDialog("Paste the database lines here.", "Add new raw items", defaultValue, false, false); dialog.Owner = WpfUtilities.TopWindow; dialog.TextBoxInput.Loaded += delegate { dialog.TextBoxInput.SelectAll(); dialog.TextBoxInput.Focus(); }; dialog.TextBoxInput.AcceptsReturn = true; dialog.TextBoxInput.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; dialog.TextBoxInput.TextWrapping = TextWrapping.NoWrap; dialog.TextBoxInput.Height = 200; dialog.TextBoxInput.MinHeight = 200; dialog.TextBoxInput.MaxHeight = 200; dialog.TextBoxInput.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto; dialog.ShowDialog(); if (dialog.Result == MessageBoxResult.OK) { try { Table.Commands.BeginEdit(new GroupCommand <TKey, TValue>()); string text = dialog.Input; string tempPath = TemporaryFilesManager.GetTemporaryFilePath("db_tmp_{0:0000}.txt"); File.WriteAllText(tempPath, text); GenericDatabase gdb = (GenericDatabase)Database; gdb.GetDb <TKey>(Settings.DbData).LoadDb(tempPath); } catch { Table.Commands.CancelEdit(); } finally { Table.Commands.EndEdit(); } _listView_SelectionChanged(this, null); } } catch (Exception err) { ErrorHandler.HandleException(err); } }
private void _save(string path = null) { _async.SetAndRunOperation(new GrfThread(delegate { try { Progress = -1; LuaParser accId = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding); Dictionary <string, string> accIdT = new Dictionary <string, string>(); accId.Tables["ACCESSORY_IDs"] = accIdT; LuaParser accName = new LuaParser(new byte[0], true, p => new Lub(p).Decompile(), EncodingService.DisplayEncoding, EncodingService.DisplayEncoding); Dictionary <string, string> accNameT = new Dictionary <string, string>(); accName.Tables["AccNameTable"] = accNameT; foreach (var item in _obItems.Where(item => item.Id > 0).Where(item => !String.IsNullOrEmpty(item.AccId))) { accIdT[item.AccId] = item.Id.ToString(CultureInfo.InvariantCulture); } if (path == null) { _multiGrf.Clear(); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); _writeAccName(file, EncodingService.DisplayEncoding); _multiGrf.SetData(ProjectConfiguration.SyncAccName, File.ReadAllBytes(file)); file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); accId.Write(file, EncodingService.DisplayEncoding); _multiGrf.SetData(ProjectConfiguration.SyncAccId, File.ReadAllBytes(file)); _multiGrf.SaveAndReload(); } else { Directory.CreateDirectory(path); _writeAccName(GrfPath.Combine(path, "accname.lub"), EncodingService.DisplayEncoding); accId.Write(GrfPath.Combine(path, "accessoryid.lub"), EncodingService.DisplayEncoding); } } catch (Exception err) { ErrorHandler.HandleException(err); } finally { Progress = 100f; } }, this, 200)); }
public static void SetDraggable(Image imagePreview, GrfImageWrapper wrapper) { imagePreview.Dispatch(delegate { imagePreview.MouseMove += (e, a) => { if (a.LeftButton == MouseButtonState.Pressed) { VirtualFileDataObject virtualFileDataObject = new VirtualFileDataObject(); string name = (string)imagePreview.Tag; List <FileDescriptor> descriptors = new List <FileDescriptor> { new FileDescriptor { Name = name + (name.GetExtension() == null ? Imaging.GuessExtension(((BitmapSource)imagePreview.Source).Format) : ""), Argument = wrapper, StreamContents = (grfData, filePath, stream, argument) => { GrfImageWrapper image = (GrfImageWrapper)argument; if (image.Image != null) { GrfImage grfImage = image.Image; string outputPath = TemporaryFilesManager.GetTemporaryFilePath("image_{0:0000}") + Imaging.GuessExtension(grfImage.GrfImageType); grfImage.Save(outputPath); var data = File.ReadAllBytes(outputPath); stream.Write(data, 0, data.Length); image.Image.Save(outputPath); } } } }; virtualFileDataObject.Source = DragAndDropSource.Other; virtualFileDataObject.SetData(descriptors); try { DoDragDrop(null, virtualFileDataObject, DragDropEffects.Copy); } catch (Exception err) { ErrorHandler.HandleException(err); } } }; }); }
public static void StoreFile(string path) { if (path == null) { return; } if (File.Exists(path)) { string temp = TemporaryFilesManager.GetTemporaryFilePath("sdb_store_{0:0000}.dat"); _storedFiles[path] = temp; File.Copy(path, temp); } else { _storedFiles[path] = null; } }
private void _buttonOk_Click(object sender, RoutedEventArgs e) { string tempFile = TemporaryFilesManager.GetTemporaryFilePath("script_tmp_{0:0000}.py"); try { if (_oldHeight != default(GridLength) && _rowConsole.Height.Value > 0) { _oldHeight = new GridLength(_rowConsole.Height.Value); } if (!_editor.ProjectDatabase.AllTables.Any(p => p.Value.IsLoaded)) { throw new Exception("No databases loaded."); } File.WriteAllText(tempFile, _textEditor.Text); _tbOutput.Text = new ScriptInterpreter().Execute(_editor.FindTopmostTab(), tempFile); if (_tbOutput.Text != "") { _tbOutput.Text = ">>> CONSOLE OUTPUT\r\n" + _tbOutput.Text; _tbOutput.Visibility = Visibility.Visible; if (_oldHeight == default(GridLength)) { _oldHeight = new GridLength(150); } _rowConsole.Height = _oldHeight; } else { _button_ConsoleClose_Click(null, null); } } catch (Exception err) { ErrorHandler.HandleException(err); } finally { GrfPath.Delete(tempFile); } }
private static void ConfigureEnvironment() { ConsoleBackend.Instance.WindowTitle = "Renode"; string configFile = null; string emul8Dir; if (Misc.TryGetEmul8Directory(out emul8Dir)) { var localConfig = Path.Combine(emul8Dir, "renode.config"); if (File.Exists(localConfig)) { configFile = localConfig; } } Emulator.UserDirectoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".renode"); ConfigurationManager.Initialize(configFile ?? Path.Combine(Emulator.UserDirectoryPath, "config")); TemporaryFilesManager.Initialize(Path.GetTempPath(), "renode-"); }
public static void StoreFile(string path) { if (path == null) { return; } if (IOHelper.Exists(path)) { string temp = TemporaryFilesManager.GetTemporaryFilePath("sdb_store_{0:0000}.dat"); _storedFiles[path] = temp; _lastModified[path] = new FileInfo(temp).LastWriteTime; IOHelper.Copy(path, temp); } else { _lastModified[path] = default(DateTime); _storedFiles[path] = null; } }
public override void ImportFromFile(string fileDefault = null) { try { string file = fileDefault ?? PathRequest.OpenFileCde("filter", "All db files|*.conf;*.txt"); if (file == "clipboard") { if (!Clipboard.ContainsText()) { return; } file = TemporaryFilesManager.GetTemporaryFilePath("clipboard_{0:0000}.txt"); File.WriteAllText(file, Clipboard.GetText()); } if (file != null) { try { Table.Commands.BeginEdit(new GroupCommand <TKey, TValue>()); GenericDatabase gdb = (GenericDatabase)Database; gdb.GetDb <TKey>(Settings.DbData).LoadDb(file); } catch { Table.Commands.CancelEdit(); } finally { Table.Commands.EndEdit(); } _listView_SelectionChanged(this, null); } } catch (Exception err) { ErrorHandler.HandleException(err); } }
public void Start(string dbPath) { if (!SdeAppConfiguration.BackupsManagerState || _backupThread.IsCrashed) { return; } if (dbPath == null) { throw new ArgumentNullException("dbPath"); } _currentId++; _validateOpened(); BackupInfo info = new BackupInfo(new TextConfigAsker(new byte[] { })); info.DestinationPath = GrfPath.GetDirectoryName(dbPath); if (!_paths.ContainsKey(_currentId)) { _paths[_currentId] = _getGrfPath(); } if (!_localToGrfPath.ContainsKey(_currentId)) { _localToGrfPath[_currentId] = new Dictionary <string, string>(); } string fullPath = GrfPath.CombineUrl(_paths[_currentId], InfoName); string tempFile = TemporaryFilesManager.GetTemporaryFilePath("backup_local_copy_{0:0000}"); File.WriteAllBytes(tempFile, info.GetData()); _localToGrfPath[_currentId][tempFile] = fullPath; IsStarted = true; }
public void Save(string filename) { if (!File.Exists(filename)) { GrfPath.CreateDirectoryFromFile(filename); using (var writer = File.Create(filename)) { Save(writer); } return; } string tempFile = TemporaryFilesManager.GetTemporaryFilePath(Process.GetCurrentProcess().Id + "_mapcache_{0:0000}.dat"); using (var writer = File.Create(tempFile)) { Save(writer); } GrfPath.CreateDirectoryFromFile(filename); GrfPath.Delete(filename); File.Copy(tempFile, filename); GrfPath.Delete(tempFile); }
static DbPathLocator() { TemporaryFilesManager.UniquePattern("sdb_store_{0:0000}.dat"); }
static IronPythonDialog() { TemporaryFilesManager.UniquePattern("script_tmp_{0:0000}.py"); PythonEditorList.Constants = PythonEditorList.Constants.Distinct().ToList(); PythonEditorList.Tables = PythonEditorList.Tables.Distinct().ToList(); }
static Mapcache() { TemporaryFilesManager.UniquePattern(Process.GetCurrentProcess().Id + "_mapcache_{0:0000}.dat"); }
public override void ImportFromFile(string fileDefault = null, bool autoIncrement = false) { try { string file = fileDefault ?? PathRequest.OpenFileCde("filter", "All db files|*.conf;*.txt"); if (file == "clipboard") { if (!Clipboard.ContainsText()) { return; } file = TemporaryFilesManager.GetTemporaryFilePath("clipboard_{0:0000}.txt"); File.WriteAllText(file, Clipboard.GetText()); } if (file != null) { try { Table.Commands.Begin(); ProjectDatabase.GetDb <TKey>(Settings.DbData).LoadFromClipboard(file); } catch { Table.Commands.CancelEdit(); } finally { Table.Commands.EndEdit(); if (autoIncrement && typeof(TKey) == typeof(int)) { var cmds = Table.Commands.GetUndoCommands(); if (cmds.Count > 0) { var lastCmd = cmds.Last() as GroupCommand <TKey, TValue>; if (lastCmd != null) { if (lastCmd.Commands.Count > 0 && lastCmd.Commands.OfType <ChangeTupleProperties <TKey, TValue> >().Count() == 1) { var firstKey = lastCmd.Commands.First().Key; var tuple = new ReadableTuple <TKey>(firstKey, Table.AttributeList); var oldTuple = (ReadableTuple <TKey>)(object) Table.TryGetTuple(firstKey); tuple.Copy(oldTuple); tuple.Added = true; ProjectDatabase.Commands.Undo(); Table.Commands.AddTuple(tuple.GetKey <TKey>(), (TValue)(object)tuple, false, true, null); } } } } } _listView_SelectionChanged(this, null); } } catch (Exception err) { ErrorHandler.HandleException(err); } }
static AllLoaders() { TemporaryFilesManager.UniquePattern("sdb_store_{0:0000}.dat"); }
public static string GetNextPath() { return(TemporaryFilesManager.GetTemporaryFilePath("va_{0:000}.bmp")); }
static ValidationErrorView() { TemporaryFilesManager.UniquePattern("va_{0:000}.bmp"); }
/// <summary> /// Initializes the <see cref="BackupEngine"/> class. /// </summary> static BackupEngine() { Instance.Init(); TemporaryFilesManager.UniquePattern("backup_local_copy_{0:0000}"); }
public static void WriteMobLuaFiles(AbstractDb <int> db) { // Ensures this is only written once if (ProjectConfiguration.SynchronizeWithClientDatabases && db.DbSource == ServerDbs.Mobs && ProjectConfiguration.SyncMobTables) { var metaTable = db.ProjectDatabase.GetMetaTable <int>(ServerDbs.Mobs); //var table = Attached["jobtbl_T"] as Dictionary<string, string>; // Load the tables DbDebugItem <int> debug = new DbDebugItem <int>(db); DbAttachLuaLoaderUpper(debug, "jobtbl", ProjectConfiguration.SyncMobId); var table = db.Attached["jobtbl_T"] as Dictionary <string, string>; if (table != null) { Dictionary <int, Npc> npcs = new Dictionary <int, Npc>(); var dataJobName = debug.AbsractDb.ProjectDatabase.MetaGrf.GetData(ProjectConfiguration.SyncMobName); if (dataJobName == null) { return; } LuaParser parser = new LuaParser(dataJobName, true, p => new Lub(p).Decompile(), EncodingService.DetectEncoding(dataJobName), EncodingService.DisplayEncoding); var jobNames = parser.Tables["JobNameTable"]; // Load the npcs from the lua files first foreach (var keyPair in table) { npcs[Int32.Parse(keyPair.Value)] = new Npc { NpcName = keyPair.Key }; } foreach (var keyPair in jobNames) { var key = keyPair.Key.Trim('[', ']'); var ingameSprite = keyPair.Value.Trim('\"'); int ival; if (!Int32.TryParse(key, out ival)) { key = key.Substring(7); var npcKeyPair = npcs.FirstOrDefault(p => p.Value.NpcName == key); if (npcKeyPair.Equals(default(KeyValuePair <int, Npc>))) { // Key not found // We ignore it } else { npcs[npcKeyPair.Key] = new Npc(npcKeyPair.Value) { IngameSprite = ingameSprite }; //npcKeyPair.Value = new ingameSprite; } continue; } npcs[ival] = new Npc { IngameSprite = ingameSprite }; } foreach (var tuple in metaTable.FastItems.OrderBy(p => p.Key)) { var ssprite = "JT_" + (tuple.GetValue <string>(ServerMobAttributes.SpriteName) ?? ""); var csprite = tuple.GetValue <string>(ServerMobAttributes.ClientSprite); if (ssprite != "JT_") { // not empty if (npcs.ContainsKey(tuple.Key)) { npcs[tuple.Key] = new Npc(npcs[tuple.Key]) { IngameSprite = csprite, NpcName = ssprite }; } else { Npc npc = new Npc { IngameSprite = csprite, NpcName = ssprite }; npcs[tuple.Key] = npc; } } } // Validation HashSet <string> duplicates = new HashSet <string>(); foreach (var npc in npcs) { if (!duplicates.Add(npc.Value.NpcName)) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "Duplicate mob name (" + npc.Value.NpcName + ") for mobid " + npc.Key + " while saving npcidentity and jobname. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } if (LatinOnly(npc.Value.NpcName) != npc.Value.NpcName) { DbIOErrorHandler.Handle(StackTraceException.GetStrackTraceException(), "The mob name (" + npc.Value.NpcName + ") is invalid, only ASCII characters are allowed. Consider using '" + LatinOnly(npc.Value.NpcName) + "' as the name instead. The files have not been resaved."); DbIOErrorHandler.Focus(); return; } } // Converts back to a lua format { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobId, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["jobtbl"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { dico[npc.Value.NpcName] = npc.Key.ToString(CultureInfo.InvariantCulture); } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobId, File.ReadAllBytes(file)); } { BackupEngine.Instance.BackupClient(ProjectConfiguration.SyncMobName, db.ProjectDatabase.MetaGrf); string file = TemporaryFilesManager.GetTemporaryFilePath("tmp2_{0:0000}.lua"); parser.Tables.Clear(); var dico = new Dictionary <string, string>(); parser.Tables["JobNameTable"] = dico; foreach (var npc in npcs.OrderBy(p => p.Key)) { var ingameSprite = LatinUpper((npc.Value.IngameSprite ?? "")); if (!String.IsNullOrEmpty(ingameSprite.GetExtension())) { ingameSprite = ingameSprite.ReplaceExtension(ingameSprite.GetExtension().ToLower()); } if (string.IsNullOrEmpty(ingameSprite)) { continue; } dico["[jobtbl." + npc.Value.NpcName + "]"] = "\"" + ingameSprite + "\""; } parser.Write(file, EncodingService.DisplayEncoding); db.ProjectDatabase.MetaGrf.SetData(ProjectConfiguration.SyncMobName, File.ReadAllBytes(file)); } } } }
private void _miPaste_Click(object sender, RoutedEventArgs e) { try { if (_tab.List.SelectedItem == null) { return; } if (!Clipboard.ContainsText()) { return; } ReadableTuple <int> tuple = (ReadableTuple <int>)_tab.List.SelectedItem; string text = Clipboard.GetText(); StringBuilder builder = new StringBuilder(); string sid = tuple.GetKey <int>().ToString(CultureInfo.InvariantCulture); string name = tuple.GetStringValue(ServerMobAttributes.KRoName.Index); foreach (string line in text.Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries)) { string[] args = line.Split(','); if (args.Length < 5) { throw new Exception("Not enough arguments to parse the lines (invalid clipboard data)."); } builder.AppendLine(String.Join(",", new string[] { sid, name + "@" + args[1].Split('@')[1] }.Concat(args.Skip(2)).ToArray())); } string tempPath = TemporaryFilesManager.GetTemporaryFilePath("db_tmp_{0:0000}.txt"); File.WriteAllText(tempPath, builder.ToString()); AbstractDb <string> db; var isEnabled = _tab.GetDb <string>(ServerDbs.MobSkills2).IsEnabled; if (_tab.Settings.DbData == ServerDbs.Mobs || !isEnabled) { db = _tab.GetDb <string>(ServerDbs.MobSkills); } else { db = _tab.GetDb <string>(ServerDbs.MobSkills2); } var table = db.Table; try { table.Commands.Begin(); db.LoadFromClipboard(tempPath); } catch { table.Commands.CancelEdit(); } finally { table.Commands.EndEdit(); _tab.Update(); } } catch (Exception err) { ErrorHandler.HandleException(err); } }
private string _getTempPath() { return(TemporaryFilesManager.GetTemporaryFilePath("sftp_{0:0000}.file")); }
static SftpFileManager() { TemporaryFilesManager.UniquePattern("sftp_{0:0000}.file"); }
public string Execute(GDbTab core, string code) { MemoryStream stream = new MemoryStream(); string output = ""; _core = core; Script script = new Script(); try { TableHelper.EnableTupleTrace = true; if (_core == null) { throw new Exception("No database tab selected."); } _selected = new ObservableList <Tuple>(); foreach (var tuple in _core._listView.SelectedItems.OfType <Tuple>().OrderBy(p => p)) { _selected.Add(tuple); } _selectionChanged = false; _selected.CollectionChanged += delegate { _selectionChanged = true; }; _mEngine.Runtime.IO.SetOutput(stream, EncodingService.DisplayEncoding); _mEngine.Runtime.IO.SetErrorOutput(stream, EncodingService.DisplayEncoding); _mScope = _mEngine.CreateScope(); List <object> dbs = new List <object>(); foreach (var serverDb in ServerDbs.ListDbs) { var db = _core.DbComponent.TryGetDb(serverDb); if (db != null) { if (db.AttributeList.PrimaryAttribute.DataType == typeof(int)) { var adb = (AbstractDb <int>)db; dbs.Add(adb); TableHelper.Tables.Add(adb.Table); _mScope.SetVariable(serverDb.Filename.ToLower().Replace(" ", "_"), adb.Table); } else if (db.AttributeList.PrimaryAttribute.DataType == typeof(string)) { var adb = (AbstractDb <string>)db; dbs.Add(adb); TableHelper.Tables.Add(adb.Table); _mScope.SetVariable(serverDb.Filename.ToLower().Replace(" ", "_"), adb.Table); } } } _mScope.SetVariable("item_db_m", _core.DbComponent.GetMeta <int>(ServerDbs.Items)); _mScope.SetVariable("mob_db_m", _core.DbComponent.GetMeta <int>(ServerDbs.Mobs)); _mScope.SetVariable("mob_skill_db_m", _core.DbComponent.GetMeta <string>(ServerDbs.MobSkills)); _mScope.SetVariable("selection", _selected); _mScope.SetVariable("database", _core.ProjectDatabase); _mScope.SetVariable("script", script); //_mScope.SetVariable("ServerDbs", DynamicHelpers.GetPythonTypeFromType(typeof(ServerDbs))); _selectedDb = null; _to <int>(_core.DbComponent, p => { _selectedDb = p.Table; _mScope.SetVariable("selected_db", p.Table); }); _to <string>(_core.DbComponent, p => { _selectedDb = p.Table; _mScope.SetVariable("selected_db", p.Table); }); string temp = TemporaryFilesManager.GetTemporaryFilePath("python_script_{0:0000}.py"); byte[] file = File.ReadAllBytes(code); Encoding encoding = EncodingService.DetectEncoding(file); using (StreamWriter writer = new StreamWriter(File.Create(temp), encoding)) using (StreamReader reader = new StreamReader(code)) { writer.WriteLine("#!/usr/bin/env python"); writer.WriteLine("# -*- coding: {0} -*- ", encoding.CodePage); while (!reader.EndOfStream) { string line = reader.ReadLine(); if (line == null) { continue; } writer.WriteLine(EncodingService.FromAnyTo(line, encoding)); } } ScriptSource source = _mEngine.CreateScriptSourceFromFile(temp); foreach (var db in dbs) { _to <int>(db, _onBegin); _to <string>(db, _onBegin); } try { try { source.Execute(_mScope); } catch (OperationCanceledException) { } if (stream.Position > 0) { stream.Seek(0, SeekOrigin.Begin); byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); output = EncodingService.DisplayEncoding.GetString(data); Clipboard.SetDataObject(EncodingService.DisplayEncoding.GetString(data)); } } catch { foreach (var db in dbs) { _to <int>(db, p => p.Table.Commands.CancelEdit()); _to <string>(db, p => p.Table.Commands.CancelEdit()); } throw; } finally { foreach (var db in dbs) { _to <int>(db, _onEnd); _to <string>(db, _onEnd); } stream.Close(); _core.Filter(); _core.Update(); } } catch (Exception err) { ErrorHandler.HandleException(err); } finally { TableHelper.EnableTupleTrace = false; TableHelper.Tables.Clear(); } return(output); }
static ScriptInterpreter() { TemporaryFilesManager.UniquePattern("python_script_{0:0000}.py"); }