Exemplo n.º 1
0
        public void UpdateAvailableImages()
        {
            DateTime ts_Start = DateTime.Now;

            UpdateAvailableImagesRec();

            int count = 0;

            ParseNodeDesc((d) => { if (d.HasImage)
                                   {
                                       count++;
                                   }
                          });

            Loggers.WriteInformation(LogTags.Image, string.Format("Update available images took {0} ms\n   {1} taxon have images", (DateTime.Now - ts_Start).Milliseconds, count));
        }
Exemplo n.º 2
0
 public static CommentFileDesc CreateOnlyIfFileExists(CommentsCollection _collection, string _name)
 {
     try
     {
         string path = Path.Combine(_collection.Path, _name + ".html");
         if (File.Exists(path))
         {
             return(new CommentFileDesc(_collection, _name));
         }
     }
     catch (Exception e)
     {
         Loggers.WriteError(LogTags.Data, "Loading comment for " + _name + " raise an exception:\n" + e.Message);
     }
     return(null);
 }
Exemplo n.º 3
0
        //=========================================================================================
        // generic function to load
        //
        public static TaxonTreeNode Load(string _fileName)
        {
            if (_fileName == string.Empty)
            {
                return(null);
            }
            DateTime ts_Start = DateTime.Now;

            if (!File.Exists(_fileName))
            {
                return(null);
            }
            Cursor.Current = Cursors.WaitCursor;
            string extension = Path.GetExtension(_fileName).ToLower();

            if (extension == ".tol")
            {
                FormAbout.SetSplashScreenMessage(".. Loading data ...", false, new Action(() => CancelLoad()));
            }
            else
            {
                FormAbout.SetSplashScreenMessage(".. Loading data ...");
            }

            TaxonTreeNode result = null;

            if (extension == ".xml")
            {
                result = LoadXML(_fileName);
            }
            if (extension == ".tol")
            {
                result = LoadBin(_fileName);
            }
            if (extension == ".txt")
            {
                result = LoadTxt(_fileName);
            }
            Loggers.WriteInformation(LogTags.Data, string.Format("Loading {0} took {1} ms ", _fileName, (int)((DateTime.Now - ts_Start).TotalMilliseconds)));
            if (result != null)
            {
                result.AfterLoad();
            }
            Cursor.Current = Cursors.Default;
            return(result);
        }
Exemplo n.º 4
0
        //-----------------------------------------------------------------------------------------
        // Save  infos
        public void SaveInfos()
        {
            string filename = System.IO.Path.Combine(Path, "_infos.xml");

            TreeOfLife.Helpers.FileSystem.EnsureReadOnlyFlagIsOff(filename);
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ImageCollection));
                using (TextWriter writer = new StreamWriter(filename))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch (Exception e)
            {
                Loggers.WriteWarning(LogTags.Collection, "Exception while saving file : \n    " + filename + "\n" + e.Message);
            }
        }
Exemplo n.º 5
0
        public bool Save(bool chooseFile = false, FileFilterIndexEnum _preferredFileExt = FileFilterIndexEnum.Xml)
        {
            if (!HasFile)
            {
                string message = "Cannot save that list in a file, it has not the HasFile flag set !";
                MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            if (chooseFile || String.IsNullOrWhiteSpace(FileName))
            {
                SaveFileDialog sfd = new SaveFileDialog
                {
                    FileName         = FileName,
                    InitialDirectory = GetFolder(),
                    FilterIndex      = 2 * (int)_preferredFileExt,
                    Filter           = FileFilters,
                    AddExtension     = true
                };
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    return(false);
                }
                FileName = sfd.FileName;
            }

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(TaxonList));
                using (TextWriter writer = new StreamWriter(FileName))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch (Exception e)
            {
                Loggers.WriteError(LogTags.Data, "Exception while saving file : \n    " + FileName + "\n" + e.Message);
                return(false);
            }
            return(true);
        }
Exemplo n.º 6
0
 public static TaxonTreeNode LoadXMLFromMemory(MemoryStream ms)
 {
     try
     {
         XmlSerializer deserializer = new XmlSerializer(typeof(TaxonTreeNode));
         object        obj          = deserializer.Deserialize(ms);
         (obj as TaxonTreeNode).UpdateFather();
         (obj as TaxonTreeNode).Visible = true;
         return(obj as TaxonTreeNode);
     }
     catch (Exception e)
     {
         string message = "Exception while loading from memory : \n\n";
         message += e.Message;
         if (e.InnerException != null)
         {
             message += "\n" + e.InnerException.Message;
         }
         Loggers.WriteError(LogTags.Data, message);
     }
     return(null);
 }
Exemplo n.º 7
0
        //---------------------------------------------------------------------------------
        private void ButtonCreateComment_Click(object sender, EventArgs e)
        {
            if (Edited == null)
            {
                return;
            }
            if (TaxonComments.CommentFile(Edited) != null)
            {
                return;
            }
            TaxonComments.CommentFileCreateResult result = TaxonComments.CommentFileCreate(Edited);
            if (result == TaxonComments.CommentFileCreateResult.Success)
            {
                splitContainerComments.Visible = false;
                Comments.RefreshContent(true);
                return;
            }

            string message = "Creation failed:\n    ";

            if (result == TaxonComments.CommentFileCreateResult.ExistsAlready)
            {
                message += "a comment file already exists";
            }
            else if (result == TaxonComments.CommentFileCreateResult.NoNameAndID)
            {
                message += "taxon as no name or id, click on ID button to create a new TOL ID";
            }
            else if (result == TaxonComments.CommentFileCreateResult.NoCollection)
            {
                message += "No available collection, edit collections before creating comments";
            }
            else
            {
                message += "unknown reason";
            }
            Loggers.WriteError(LogTags.Comment, message);
        }
Exemplo n.º 8
0
        public void Save(string _filename, string _exeRef = null)
        {
            BeforeSave(_exeRef);
            string filepath = Path.GetDirectoryName(_filename);

            try
            {
                if (!Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }

                XmlSerializer serializer = new XmlSerializer(typeof(Config));
                using (TextWriter writer = new StreamWriter(_filename))
                {
                    serializer.Serialize(writer, this);
                }
            }
            catch (Exception e)
            {
                Loggers.WriteError(LogTags.Congif, "Exception while saving config file : \n    " + _filename + "\n" + e.Message);
            }
        }
Exemplo n.º 9
0
 //=========================================================================================
 // txt file
 //
 static TaxonTreeNode LoadTxt(string _filename)
 {
     try
     {
         int ch = 0;
         using (StreamReader sr = new StreamReader(_filename))
         {
             ch = (int)sr.Read();
             while (ch != -1)
             {
                 if (ch == '(')
                 {
                     break;
                 }
                 if (ch == (int)Keys.Return || ch == '>')
                 {
                     break;
                 }
                 ch = (int)sr.Read();
             }
         }
         if (ch == '(')
         {
             return(LoadNewick(_filename));
         }
         if (ch == (int)Keys.Return || ch == '>')
         {
             return(LoadJacFile(_filename));
         }
         Loggers.WriteError(LogTags.Data, "Cannot recognize file forma : \n    " + _filename);
         return(null);
     }
     catch
     {
         return(null);
     }
 }
Exemplo n.º 10
0
        public void SaveBin(string _fileName)
        {
            TaxonUtils.LockMainWindow();
            try
            {
                using (ProgressDialog progressDlg = new ProgressDialog())
                {
                    progressDlg.StartPosition = FormStartPosition.CenterScreen;
                    progressDlg.Show();

                    ProgressItem piSave = progressDlg.Add("Saving ...", null, 0, Count());
                    using (FileStream fs = File.Create(_fileName, 65536, FileOptions.None))
                    {
                        using (DeflateStream deflateStream = new DeflateStream(fs, CompressionMode.Compress))
                        {
                            using (BinaryWriter w = new BinaryWriter(deflateStream))
                            //using (BinaryWriter w = new BinaryWriter(fs))
                            {
                                w.Write(SaveBinVersion);
                                SaveBin(w, new SaveBinProgress(piSave));
                                w.Close();
                                deflateStream.Close();
                                fs.Close();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Loggers.WriteError(LogTags.Data, "Exception while saving config file : \n    " + _fileName + "\n" + e.Message);
            }
            finally
            {
                TaxonUtils.UnlockMainWindow();
            }
        }
Exemplo n.º 11
0
 //méthode load
 public static TaxonTreeNode LoadXML(string _fileName)
 {
     try
     {
         XmlSerializer deserializer = new XmlSerializer(typeof(TaxonTreeNode));
         TextReader    reader       = new StreamReader(_fileName);
         object        obj          = deserializer.Deserialize(reader);
         reader.Close();
         (obj as TaxonTreeNode).UpdateFather();
         (obj as TaxonTreeNode).Visible = true;
         return(obj as TaxonTreeNode);
     }
     catch (Exception e)
     {
         string message = "Exception while loading " + _fileName + " : \n\n";
         message += e.Message;
         if (e.InnerException != null)
         {
             message += "\n" + e.InnerException.Message;
         }
         Loggers.WriteError(LogTags.Data, message);
     }
     return(null);
 }
Exemplo n.º 12
0
        //=========================================================================================
        // Jac File load
        //
        static TaxonTreeNode LoadJacFile(string _filename)
        {
            try
            {
                using (StreamReader sr = new StreamReader(_filename))
                {
                    TaxonTreeNode root        = new TaxonTreeNode(new TaxonDesc("__ignore__"));
                    TaxonTreeNode currentNode = root;
                    int           currentTab  = 0;
                    int           currentLine = 0;

                    string line;
                    // read header line
                    while ((line = sr.ReadLine()) != null)
                    {
                        currentLine++;
                        int tab = 0;
                        while (line.StartsWith("\t"))
                        {
                            tab++; line = line.Substring(1);
                        }
                        if (tab > currentTab)
                        {
                            if (tab - currentTab > 1 || currentNode.Children.Count == 0)
                            {
                                Loggers.WriteError(LogTags.Data, _filename + "(" + currentLine.ToString() + ") too many tabs");
                                return(null);
                            }
                            currentTab  = tab;
                            currentNode = currentNode.Children[currentNode.Children.Count - 1];
                        }
                        else if (tab < currentTab)
                        {
                            while (currentTab != tab)
                            {
                                if (currentNode == root)
                                {
                                    Loggers.WriteError(LogTags.Data, _filename + "(" + currentLine.ToString() + ") tabulation error");
                                    return(null);
                                }
                                currentTab--;
                                currentNode = currentNode.Father;
                            }
                        }

                        string[]      parts   = line.Split('>');
                        TaxonTreeNode newNode = new TaxonTreeNode(new TaxonDesc()
                        {
                            RefMultiName    = new Helpers.MultiName(parts[0]),
                            FrenchMultiName = parts.Length < 2 || String.IsNullOrWhiteSpace(parts[1]) ? null : new Helpers.MultiName(parts[1]),
                            ClassicRank     = parts.Length < 3 || String.IsNullOrWhiteSpace(parts[2]) ? ClassicRankEnum.None : ClassicRankEnumExt.FromString(parts[2]),
                            Flags           = (parts.Length < 4 || String.IsNullOrWhiteSpace(parts[3])) ? 0 : FlagsEnumExt.FromString(parts[3]),
                            RedListCategory = (parts.Length < 5 || String.IsNullOrWhiteSpace(parts[4])) ? RedListCategoryEnum.NotEvaluated : RedListCategoryExt.FromString(parts[4]),
                        }
                                                                  );
                        currentNode.AddChild(newNode);
                    }

                    return(root);
                }
            }
            catch (Exception e)
            {
                Loggers.WriteError(LogTags.Data, "Exception raised while reading file " + _filename + "\n   " + e.Message);
                return(null);
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("fr-FR");
            Application.CurrentCulture = cultureInfo;
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // Init system
            Loggers.Register(new LogFile(null, true));

            LogMessageBox logMessageBox = new LogMessageBox();

            logMessageBox.SetVerboseMode(VerboseModeEnum.OnlyErrors);
            Loggers.Register(logMessageBox);

            SystemConfig.OnRunningModeChanged += Loggers_OnRunningModeChanged;

            Loggers.WriteInformation("Starting TreeOfLife : " + DateTime.Now.ToLongDateString());
#if USER
            SystemConfig.RunningMode = SystemConfig.RunningModeEnum.User;
#else
            SystemConfig.RunningMode = SystemConfig.RunningModeEnum.Admin;
#endif
            TaxonUtils.MyConfig = Config.Load("auto");
            // TaxonUtils.MyConfig.ToData();

            //Console.WriteLine(TaxonUtils.);
            if (!TaxonUtils.MyConfig.offline)
            {
                bool ok = TaxonUtils.CheckConnection();

                if (!ok)
                {
                    TaxonUtils.MyConfig.dataInitialized = false;
                    Console.WriteLine(TaxonUtils.MyConfig.dataInitialized);
                }
            }

            InitForm initForm = new InitForm();
            if (!TaxonUtils.MyConfig.dataInitialized)
            {
                initForm.ShowDialog();
                TaxonUtils.MyConfig.rootDirectory = TOLData.AppDataDirectory();
                Console.WriteLine(TaxonUtils.MyConfig.rootDirectory);
            }
            else
            {
                TOLData.offline = TaxonUtils.MyConfig.offline;
            }

            if (!initForm.quit)
            {
                TOLData.initSounds();


                FormAbout.DoSplashScreen();
                //----- config
                FormAbout.SetSplashScreenMessage(".. Loading config ...");

                TaxonUtils.initCollections();

                Application.Run(new Form1(args));
            }
        }
Exemplo n.º 14
0
        private void ButtonImport_Click(object sender, EventArgs e)
        {
            string logFile = Path.Combine(TaxonUtils.GetLogPath(), "TagBatchImport.log");

            using (StreamWriter log = new StreamWriter(logFile))
            {
                string[] srcFiles = null;
                bool     error    = false;
                if (!Directory.Exists(textBoxSource.Text))
                {
                    log.WriteLine("Folder " + textBoxSource.Text + " does not exists");
                    error = true;
                }
                else
                {
                    try
                    {
                        srcFiles = Directory.GetFiles(textBoxSource.Text, "*.txt");
                        if (srcFiles.Length == 0)
                        {
                            log.WriteLine("Folder " + textBoxSource.Text + " contains no txt files");
                            error = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.WriteLine("Exception while getting list of txt file in folder " + textBoxSource.Text);
                        log.WriteLine("    " + ex.Message);
                        error = true;
                    }
                }

                if (!Directory.Exists(textBoxDestination.Text))
                {
                    log.WriteLine("Folder " + textBoxDestination.Text + " does not exists");
                    error = true;
                }

                if (error)
                {
                    log.WriteLine("Initialization error, stop batch import");
                    return;
                }

                bool overwriteAlways = radioButtonOverwrite.Checked;
                bool overwriteNever  = radioButtonLeaveIt.Checked;
                int  skippedFiles    = 0;
                int  errorFiles      = 0;

                foreach (string file in srcFiles)
                {
                    log.WriteLine();
                    log.WriteLine("--------------------------------------------------");
                    log.WriteLine("---> Import " + file);

                    string destinationFile = Path.Combine(textBoxDestination.Text, Path.GetFileNameWithoutExtension(file));
                    destinationFile = Path.ChangeExtension(destinationFile, ".lot");
                    if (File.Exists(destinationFile))
                    {
                        if (overwriteNever)
                        {
                            log.WriteLine("Import skipped, file " + destinationFile + " already exists");
                            skippedFiles++;
                            continue;
                        }
                        else if (!overwriteAlways)
                        {
                            DateTime datedest = File.GetLastWriteTime(destinationFile);
                            DateTime datesrc  = File.GetLastWriteTime(file);
                            if (datedest >= datesrc)
                            {
                                log.WriteLine("Import skipped, file " + destinationFile + " already exists and is newer than source file");
                                skippedFiles++;
                                continue;
                            }
                        }

                        try
                        {
                            File.Delete(destinationFile);
                        }
                        catch
                        {
                            log.WriteLine("Import skipped, file " + destinationFile + " already exists");
                            log.WriteLine("And got an error while trying to delete it");
                            errorFiles++;
                            continue;
                        }
                    }

                    while (_Searchtool == null)
                    {
                        Console.WriteLine("Wait search tool");
                        Thread.Sleep(100);
                    }

                    TaxonList.ImportFileResult result = TaxonList.ImportFile(file, _Searchtool, false);

                    TaxonList list = new TaxonList {
                        HasFile = true, FileName = destinationFile
                    };
                    list.FromTaxonTreeNodeList(result.List);

                    try
                    {
                        list.Save(false, TaxonList.FileFilterIndexEnum.ListOfTaxons);
                    }
                    catch (Exception ex)
                    {
                        log.WriteLine("Exception while saving list to " + destinationFile);
                        log.WriteLine("    " + ex.Message);
                        errorFiles++;
                        continue;
                    }

                    log.WriteLine(string.Format("    taxons found: {0}", result.TaxonsFound));
                    log.WriteLine(string.Format("    taxons not found: {0}", result.TaxonNotFound));
                    log.WriteLine(string.Format("for more details, look at " + result.LogFilename + " file"));
                    log.WriteLine(string.Format("==> Saved in " + destinationFile));
                }

                string message = "Batch import done,\n";
                message += string.Format("{0} total files scanned\n", srcFiles.Length);
                message += string.Format("{0} files skipped\n", skippedFiles);
                message += string.Format("{0} files not imported due to an error\n", errorFiles);
                message += string.Format("{0} files imported\n", srcFiles.Length - skippedFiles - errorFiles);
                message += string.Format("for more details, look at {0}", logFile);
                Loggers.WriteInformation(LogTags.Data, message);
                log.WriteLine("");
                log.WriteLine("==================================================");
                log.Write(message);
            }
        }