/*************************************************************************************************************************/ /// <summary> /// open directory with configuration file</summary> public string GetGlobalConfigDirectory() { return(Os.Combine( Os.GetApplicationsDirectory(), this.configFileDirectory )); }
/*************************************************************************************************************************/ // SHORTCUTS /// <summary> /// get path from lnk file in windows </summary> public static string[] GetShortcutTargetFile(string shortcutFilename) { try { string pathOnly = Os.GetDirectoryName(shortcutFilename); string filenameOnly = Os.GetFileName(shortcutFilename); Shell shell = new Shell(); Folder folder = shell.NameSpace(pathOnly); FolderItem folderItem = folder.ParseName(filenameOnly); if (folderItem != null) { Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink; if (link.Arguments != "") { return(new string[] { link.Path, link.Arguments }); } return(new string[] { link.Path, "" }); } } catch (Exception e) { Program.log.Write("GetShortcutTargetFile error: " + e.Message); } return(new string[] { "", "" }); }
/// <summary> /// copy file or directory </summary> public static bool Copy(string SourcePath, string DestinationPath, CopyProgressDelegate callback = null) { try { if (Directory.Exists(SourcePath)) { foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories)) { Os.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath)); } foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories)) { CopyByBlock(newPath, newPath.Replace(SourcePath, DestinationPath), callback); } } else if (File.Exists(SourcePath)) { CopyByBlock(SourcePath, Os.Combine(DestinationPath, Os.GetFileName(SourcePath)), callback); } return(true); } catch (Exception ex) { Program.log.Write(ex.Message); return(false); } }
/*************************************************************************************************************************/ // IMAGE public void LoadImage() { if (this.imagepath != "" && Os.FileExists(this.imagepath)) { try { string ext = ""; ext = Os.GetExtension(this.imagepath).ToLower(); if (ext == ".jpg" || ext == ".png" || ext == ".ico" || ext == ".bmp") { this.image = Media.GetImage(this.imagepath); if (ext != ".ico") { this.image.MakeTransparent(Color.White); } this.height = this.image.Height; this.width = this.image.Width; this.isimage = true; } } catch (Exception ex) { Program.log.Write("load image from xml error: " + ex.Message); } } else { this.imagepath = ""; } }
/// <summary> /// load global config file from json file</summary> private void LoadConfigFile() { try { Program.log.Write("loadConfigFile: path:" + this.optionsFilePath); string inputJSON = Os.ReadAllText(this.optionsFilePath); if (Os.FileExists(this.optionsFilePath)) { string xml = Os.GetFileContent(this.optionsFilePath); XmlReaderSettings xws = new XmlReaderSettings { CheckCharacters = false }; using (XmlReader xr = XmlReader.Create(new StringReader(xml), xws)) { XElement root = XElement.Load(xr); this.LoadParams(root); } } } catch (Exception ex) { Program.log.Write("loadConfigFile: " + ex.Message); } }
/*************************************************************************************************************************/ // Recent files /// <summary> /// add path to recent files</summary> public void AddRecentFile(String path) { if (Os.FileExists(path)) { this.recentFiles.Remove(path); this.recentFiles.Insert(0, path); } }
/// <summary> /// get parent directory of FileName path </summary> public static string GetFileDirectory(string FileName) { if (FileName.Trim().Length > 0 && Os.FileExists(FileName)) { return(new FileInfo(FileName).Directory.FullName); } return(null); }
public AboutForm(Main main) { this.main = main; this.InitializeComponent(); this.labelLicenceType.Text = this.main.programOptions.license; this.labelVersionNumber.Text = Os.GetThisAssemblyVersion(); this.linkLabelMe.Text = this.main.programOptions.author; this.labelHomepage.Text = this.main.programOptions.home_page; }
/// <summary> /// open file on position </summary> public static void OpenFileOnPosition(string fileName, long pos = 0) { String editFileCmd = "subl \"%FILENAME%\":%LINE%";; editFileCmd = editFileCmd.Replace("%FILENAME%", Os.NormalizedFullPath(fileName)); editFileCmd = editFileCmd.Replace("%LINE%", pos.ToString()); Program.log.Write("diagram: openlink: open file on position " + editFileCmd); Os.RunCommand(editFileCmd); }
/// <summary> /// check if diagramPath file path has good extension </summary> public static bool IsDiagram(string diagramPath) { diagramPath = NormalizePath(diagramPath); if (Os.FileExists(diagramPath) && Path.GetExtension(diagramPath).ToLower() == ".diagram") { return(true); } return(false); }
/*************************************************************************************************************************/ // FILE EXTENSION /// <summary> /// get file extension</summary> public static string GetExtension(string file) { string ext = ""; if (file != "" && Os.FileExists(file)) { ext = Path.GetExtension(file).ToLower(); } return(ext); }
/// <summary> /// meke filePath relative to currentPath. /// If is set inCurrentDir path is converted to relative only /// if currentPath is parent of filePath</summary> public static string MakeRelative(string filePath, string currentPath, bool inCurrentDir = true) { filePath = filePath.Trim(); currentPath = currentPath.Trim(); if (currentPath == "") { return(filePath); } if (!Os.FileExists(filePath) && !Os.DirectoryExists(filePath)) { return(filePath); } filePath = Os.GetFullPath(filePath); if (Os.FileExists(currentPath)) { currentPath = Os.GetDirectoryName(currentPath); } if (!Os.DirectoryExists(currentPath)) { return(filePath); } currentPath = Os.GetFullPath(currentPath); Uri pathUri = new Uri(filePath); // Folders must end in a slash if (!currentPath.EndsWith(Path.DirectorySeparatorChar.ToString())) { currentPath += Path.DirectorySeparatorChar; } int pos = filePath.ToLower().IndexOf(currentPath.ToLower()); if (inCurrentDir && pos != 0) // skip files outside of currentPath { return(filePath); } Uri folderUri = new Uri(currentPath); return(Uri.UnescapeDataString( folderUri.MakeRelativeUri(pathUri) .ToString() .Replace('/', Path.DirectorySeparatorChar) )); }
/// <summary> /// remove old not existing diagrams from recent files</summary> public void RemoveOldRecentFiles() { List <String> newRecentFiles = new List <String>(); foreach (String path in this.recentFiles) { if (Os.FileExists(path)) { newRecentFiles.Add(path); } } this.recentFiles = newRecentFiles; }
private static void Main() //UID4670767500 { #if !DEBUG System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; #endif Program.log.Write("Start application: " + Os.GetThisAssemblyLocation()); Program.log.Write("Version : " + Os.GetThisAssemblyVersion()); #if DEBUG Program.log.Write("Debug mode"); #else Program.log.Write("Production mode"); #endif // aplication default settings #if CORE Application.SetHighDpiMode(HighDpiMode.SystemAware); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // prevent catch global exception in production mode #if !DEBUG try { #endif main = new Main(); if (main.mainform != null) { Application.Run(main.mainform); } else { main.ExitApplication(); } #if !DEBUG // catch all exception globaly in release mode and prevent application crash } catch (Exception e) // global exception handling { log.Write("Application crash: message:" + e.Message); MessageBox.Show("Application crash: message:" + e.Message); System.Environment.Exit(1); //close application with error code 1 } #endif }
/// <summary> ///get icon from lnk file in windows </summary> public static string GetShortcutIcon(String shortcutFilename) { String pathOnly = Os.GetDirectoryName(shortcutFilename); String filenameOnly = Os.GetFileName(shortcutFilename); Shell shell = new Shell(); Folder folder = shell.NameSpace(pathOnly); FolderItem folderItem = folder.ParseName(filenameOnly); if (folderItem != null) { Shell32.ShellLinkObject link = (Shell32.ShellLinkObject)folderItem.GetLink; link.GetIconLocation(out String iconlocation); return(iconlocation); } return(String.Empty); }
/// <summary> /// open path in system if exist </summary> public static void OpenPathInSystem(string path) { if (Os.FileExists(path)) // OPEN FILE { try { string parent_diectory = Os.GetFileDirectory(path); System.Diagnostics.Process.Start(parent_diectory); } catch (Exception ex) { Program.log.Write("openPathInSystem open file: error:" + ex.Message); } } else if (Os.DirectoryExists(path)) // OPEN DIRECTORY { try { System.Diagnostics.Process.Start(path); } catch (Exception ex) { Program.log.Write("openPathInSystem open directory: error:" + ex.Message); } } }
/*************************************************************************************************************************/ // PLUGINS /// <summary> /// load plugins from assebmblies</summary> public void LoadPugins() { // load external plugins UID9841812564 plugins = new Plugins(); // load plugins from current application directory (portable mode) string pluginsLocalDirectory = Os.Combine(Os.GetCurrentApplicationDirectory(), this.pluginsDirectoryName); if (Os.DirectoryExists(pluginsLocalDirectory)) { plugins.LoadPlugins(pluginsLocalDirectory); } #if !DEBUG // load plugins from global plugins directory string pluginsGlobalDirectory = Os.Combine(this.programOptionsFile.GetGlobalConfigDirectory(), this.pluginsDirectoryName); if (Os.DirectoryExists(pluginsGlobalDirectory)) { plugins.LoadPlugins(pluginsGlobalDirectory); } #endif }
/*************************************************************************************************************************/ /// <summary> /// load global config file from portable file configuration or global file configuration /// </summary> /// <param name="parameters">reference to parameter object</param> public ProgramOptionsFile(ProgramOptions programOptions) { this.programOptions = programOptions; // use local config file this.optionsFilePath = Os.Combine(Os.GetCurrentApplicationDirectory(), this.configFileName); // use global config file if local version not exist if (!Os.FileExists(this.optionsFilePath)) { this.optionsFilePath = Os.Combine( this.GetGlobalConfigDirectory(), this.configFileName ); } // open config file if exist if (Os.FileExists(this.optionsFilePath)) { this.LoadConfigFile(); } else { string globalConfigDirectory = Os.Combine( Os.GetApplicationsDirectory(), this.configFileDirectory ); // create global config directory if not exist if (!Os.DirectoryExists(globalConfigDirectory)) { Os.CreateDirectory(globalConfigDirectory); } // if config file dosn't exist create one with default values this.SaveConfigFile(); } }
/*************************************************************************************************************************/ // DIRECTORY OPERATIONS /// <summary> /// check if path is directory</summary> public static bool IsDirectory(string path) { return(Os.DirectoryExists(path)); }
/// <summary> /// decompress string with directory structure to path</summary> public static void DecompressPath(string compressedData, string destinationPath) { if (!Os.DirectoryExists(destinationPath)) { return; } destinationPath = Os.NormalizedFullPath(destinationPath); string xml = Unzip(compressedData); XmlReaderSettings xws = new XmlReaderSettings { CheckCharacters = false }; string version = ""; List <EDirectory> directories = new List <EDirectory>(); List <EFile> files = new List <EFile>(); try { using (XmlReader xr = XmlReader.Create(new StringReader(xml), xws)) { XElement xRoot = XElement.Load(xr); if (xRoot.Name.ToString() == "archive") { foreach (XElement xEl in xRoot.Elements()) { if (xEl.Name.ToString() == "version") { version = xEl.Value; } if (xEl.Name.ToString() == "directories") { foreach (XElement xDirectory in xEl.Descendants()) { if (xDirectory.Name.ToString() == "directory") { string name = ""; foreach (XElement xData in xDirectory.Descendants()) { if (xData.Name.ToString() == "name") { name = xData.Value; } } if (name.Trim() != "") { EDirectory eDirectory = new EDirectory { name = name }; directories.Add(eDirectory); } } } } if (xEl.Name.ToString() == "files") { foreach (XElement xFile in xEl.Descendants()) { if (xFile.Name.ToString() == "file") { string name = ""; string data = ""; foreach (XElement xData in xFile.Descendants()) { if (xData.Name.ToString() == "name") { name = xData.Value; } if (xData.Name.ToString() == "data") { data = xData.Value; } } if (name.Trim() != "" && data.Trim() != "") { EFile eFile = new EFile { name = name, data = data }; files.Add(eFile); } } } } } } } } catch (Exception ex) { Program.log.Write("decompress file xml error: " + ex.Message); } foreach (EDirectory directory in directories) { string newDirPath = Os.Combine(destinationPath, directory.name); if (!Os.Exists(newDirPath)) { Os.CreateDirectory(newDirPath); } } foreach (EFile file in files) { string newFilePath = Os.Combine(destinationPath, file.name); if (!Os.Exists(newFilePath)) { Os.WriteAllBytes( newFilePath, Convert.FromBase64String( file.data ) ); } } // process dirrectories create to path // process files create to path }
/*************************************************************************************************************************/ // COMPRESS DIRECTORY /// <summary> /// compress directory with files to string</summary> public static string CompressPath(string path) { if (!Os.Exists(path)) { return(""); } path = Os.NormalizedFullPath(path); List <EDirectory> directories = new List <EDirectory>(); List <EFile> files = new List <EFile>(); if (Os.IsFile(path)) { EFile eFile = new EFile { name = Os.GetFileName(path), data = Convert.ToBase64String( Os.ReadAllBytes(path) ) }; files.Add(eFile); } if (Os.IsDirectory(path)) { List <string> filePaths = new List <string>(); List <string> directoryPaths = new List <string>(); Os.Search(path, filePaths, directoryPaths); int pathLength = path.Length + 1; foreach (string dirPath in directoryPaths) { EDirectory eDirectory = new EDirectory { name = dirPath.Substring(pathLength) }; directories.Add(eDirectory); } foreach (string filePath in filePaths) { EFile eFile = new EFile { name = filePath.Substring(pathLength), data = Convert.ToBase64String( File.ReadAllBytes(filePath) ) }; files.Add(eFile); } } XElement xRoot = new XElement("archive"); xRoot.Add(new XElement("version", "1")); XElement xDirectories = new XElement("directories"); foreach (EDirectory directory in directories) { XElement xDirectory = new XElement("directory"); xDirectory.Add( new XElement( "name", directory.name ) ); xDirectories.Add(xDirectory); } xRoot.Add(xDirectories); XElement xFiles = new XElement("files"); foreach (EFile file in files) { XElement xFile = new XElement("file"); xFile.Add( new XElement( "name", file.name ) ); xFile.Add( new XElement( "data", file.data ) ); xFiles.Add(xFile); } xRoot.Add(xFiles); StringBuilder sb = new StringBuilder(); XmlWriterSettings xws = new XmlWriterSettings { OmitXmlDeclaration = true, CheckCharacters = false, Indent = true }; using (XmlWriter xw = XmlWriter.Create(sb, xws)) { xRoot.WriteTo(xw); } return(Zip(sb.ToString())); }
/// <summary> /// process comand line arguments</summary> public void ParseCommandLineArguments(string[] args) // [PARSE] [COMMAND LINE] UID5172911205 { // options - create new file with given name if not exist bool CommandLineCreateIfNotExistFile = false; bool ShowCommandLineHelp = false; bool ShowDebugConsole = false; // list of diagram files names for open List <String> CommandLineOpen = new List <String>(); String arg; for (int i = 0; i < args.Length; i++) { //skip application name if (i == 0) { continue; } // current processing argument arg = args[i]; // [COMAND LINE] [CREATE] oprions create new file with given name if not exist if (arg == "-h" || arg == "--help" || arg == "/?") { ShowCommandLineHelp = true; break; } if (arg == "-c" || arg == "--console") { ShowDebugConsole = true; break; } if (arg == "-e") { CommandLineCreateIfNotExistFile = true; break; } // [COMAND LINE] [OPEN] check if argument is diagram file if (Os.GetExtension(arg).ToLower() == ".diagram") { CommandLineOpen.Add(arg); break; } Program.log.Write("bed commmand line argument: " + arg); } if (ShowDebugConsole) { this.ShowConsole(); } // open diagram given as arguments if (ShowCommandLineHelp) { String help = "diagram -h --help /? >> show this help\n" + "diagram -c --console /? >> show debug console\n" + "diagram -e {filename} >> create file if not exist\n" + "diagram {filepath} {filepath} >> open existing file\n"; MessageBox.Show(help, "Command line parameters"); return; } if (CommandLineOpen.Count == 0) { if (this.programOptions.defaultDiagram != "" && Os.FileExists(this.programOptions.defaultDiagram)) { this.OpenDiagram(this.programOptions.defaultDiagram); // open default diagram if default diagram is set } else if (this.programOptions.openLastFile && this.programOptions.recentFiles.Count > 0 && Os.FileExists(this.programOptions.recentFiles[0])) { this.OpenDiagram(this.programOptions.recentFiles[0]); // open last file if user option is enabled UID2130542088 } else { this.OpenDiagram(); //open empty diagram UID5981683893 } return; } for (int i = 0; i < CommandLineOpen.Count; i++) { string file = CommandLineOpen[i]; // tray create diagram file if command line option is set if (CommandLineCreateIfNotExistFile && !Os.FileExists(file)) { try { Os.CreateEmptyFile(file); } catch (Exception ex) { Program.log.Write("create empty diagram file error: " + ex.Message); } } if (Os.FileExists(file)) { this.OpenDiagram(file); //UID2130542088 } } // cose application if is not diagram model opened this.CloseEmptyApplication(); }
/// <summary> /// open directori with global configuration</summary> public void OpenConfigDir() { Os.ShowDirectoryInExternalApplication(Os.GetDirectoryName(this.programOptionsFile.optionsFilePath)); }
/// <summary> /// open existing diagram or create new empty diagram /// Create diagram model and then open diagram view on this model</summary> public bool OpenDiagram(String FilePath = "") //UID1771511767 { Program.log.Write("Program : OpenDiagram: " + FilePath); if (passwordForm != null) // prevent open diagram if another diagram triing open { return(false); } // open new empty diagram in main process if (FilePath == "" && !server.mainProcess) { // if server already exist in system, send him message whitch open empty diagram server.SendMessage("open:"); return(false); } // open diagram in current program instance if (FilePath == "" && server.mainProcess) { // create new model Diagram emptyDiagram = new Diagram(this); Diagrams.Add(emptyDiagram); // open diagram view on diagram model emptyDiagram.OpenDiagramView(); return(false); } // open existing diagram file if (!Os.FileExists(FilePath)) { return(false); } FilePath = Os.NormalizedFullPath(FilePath); // if server already exist in system, send him message whitch open diagram file if (!server.mainProcess) { FilePath = Os.GetFullPath(FilePath); server.SendMessage("open:" + FilePath); //UID1105610325 return(false); } // open diagram in current program instance // check if file is already opened in current instance bool alreadyOpen = false; foreach (Diagram openedDiagram in Diagrams) { if (openedDiagram.FileName != FilePath) { continue; } openedDiagram.FocusToView(); alreadyOpen = true; break; } if (alreadyOpen) { return(false); } Diagram diagram = new Diagram(this); //UID8780020416 lock (diagram) { // create new model if (!diagram.OpenFile(FilePath)) { return(false); } this.programOptions.AddRecentFile(FilePath); #if !MONO RecentFiles.AddToRecentlyUsedDocs(FilePath); // add to system recent files #endif Diagrams.Add(diagram); // open diagram view on diagram model DiagramView newDiagram = diagram.OpenDiagramView(); //UID3015837184 this.plugins.OpenDiagramAction(diagram); //UID0290845816 Program.log.Write("bring focus"); Media.BringToFront(newDiagram); //UID4510272263 } return(true); }
public void CheckUpdates(bool showCurrentVersionStatus = false) { Job.DoJob( new DoWorkEventHandler( delegate(object o, DoWorkEventArgs args) { try { string currentVersion = Os.GetThisAssemblyVersion(); Program.log.Write("CheckUpdates current version: " + currentVersion); string lastVersion = Network.GetWebPage(this.homepage + this.lastversionFile); Program.log.Write("CheckUpdates last version: " + lastVersion); if (lastVersion == null) { return; } lastVersion = lastVersion.TrimEnd('\r', '\n').Trim(); Version localVersion = new Version(currentVersion); Version serverVersion = new Version(lastVersion); if (serverVersion.CompareTo(localVersion) == 1) { string signature = Network.GetWebPage(this.homepage + this.signatureFile); signature = signature.TrimEnd('\r', '\n').Trim(); if (signature == null || signature.Length < 64) { return; } UpdateForm updateForm = new UpdateForm(); updateForm.ShowDialog(); if (updateForm.CanUpdate()) { string tempPath = Os.Combine(Os.GetTempPath(), this.updateFolderName); string executablePath = tempPath + Os.GetSeparator() + this.updateExecutableName; Os.RemoveDirectory(tempPath); Os.CreateDirectory(tempPath); string downloadFromUrl = installationUrl.Replace("{VERSION}", lastVersion); Program.log.Write("CheckUpdates downloading: " + downloadFromUrl); Network.DownloadFile(downloadFromUrl, executablePath); string downloadedFileChecksum = Hash.GetFileHash(executablePath); if (downloadedFileChecksum == signature) { Os.RunProcess(executablePath); } else { Program.log.Write("CheckUpdates error: invalid signature"); } } else if (updateForm.SkipVersion()) { } } else { if (showCurrentVersionStatus) { MessageBox.Show("You have last version."); } } } catch (Exception ex) { Program.log.Write("CheckUpdates error: " + ex.Message); } } ), new RunWorkerCompletedEventHandler( delegate(object o, RunWorkerCompletedEventArgs args) { } ) ); }
/*************************************************************************************************************************/ // FILE OPERATIONS /// <summary> /// check if path is file</summary> public static bool IsFile(string path) { return(Os.FileExists(path)); }
/// <summary> /// get current running application executable directory /// Example: c:\Program Files\Infinite Diagram\ /// </summary> public static String GetCurrentApplicationDirectory() { return(Os.GetDirectoryName(Application.ExecutablePath)); }