Exemplo n.º 1
0
        static void Main()
        {
            CmdArgs cmdArgs = new CmdArgs(Environment.GetCommandLineArgs());

             if (cmdArgs.Options.Count <= 0 && cmdArgs.Parameters.Count <= 0 && cmdArgs.Arguments.Count <= 1)
             {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
            return;
             }

             AttachConsole(ATTACH_PARENT_PROCESS);

             if (cmdArgs.HasParameter("sc"))
             {
            ScriptCompiler script = new ScriptCompiler();

            if (!script.Run(new FileName(cmdArgs.Parameter("s")), cmdArgs))
               Console.WriteLine("The run failed.");
            else
               Console.WriteLine("The run was ok.");
             }
             else if (cmdArgs.HasParameter("sv"))
             {
            Console.WriteLine("Run VB.NET script is not implemented yet.");
             }
             else if (cmdArgs.HasParameter("l"))
             {
            Console.WriteLine("Run from DLL is not implemented yet.");
             }
             else
             {
            Console.WriteLine("");
            Console.WriteLine("To launch visual interface: MohidToolBox");
            Console.WriteLine("To use command line:        MohidToolbox [[--sc][--sv] scriptfilename] [--l dllfilename]");
            Console.WriteLine("");
            Console.WriteLine("       --sc : Used to indicate a CSharp script file name");
            Console.WriteLine("       --sv : Used to indicate a VB.NET script file name (not implemented)");
            Console.WriteLine("       --l  : Used to indicate a DLL script file name (not implemented)");
            Console.WriteLine("");
            Console.WriteLine("If no options are present, the visual interface will be launched.");
            Console.WriteLine("ATTENTION: Only ONE of the above options can be used at a time");
            Console.WriteLine("");
            Console.WriteLine("Press a key...");
             }

             return;
        }
Exemplo n.º 2
0
        //protected bool FindTemplatesSpecialSetup(ConfigNode toMatch)
        //{
        //   if (toMatch.Name == "template.special.setup")
        //      return true;
        //   return false;
        //}
        protected bool LoadConfig(CmdArgs args)
        {
            Config cfg = new Config();

             string configFile;
             if (args.HasParameter("cfg"))
            configFile = args.Parameter("cfg");
             else
            configFile = "sim.cfg";

             if (args.HasParameter("max.iter"))
            maxIterations = int.Parse(args.Parameter("max.iter"));
             else
            maxIterations = -1;

             cfg.ConfigFile.FullPath = configFile;
             if (!cfg.Load())
            return false;

             ConfigNode root = cfg.Root;

             try
             {
            sim.SimDirectory = root["sim.folder", "sim"].AsFilePath();
            if (!log.Load(root["log.file", sim.SimDirectory.Path + "sim.log"].AsFileName()))
               return false;

            RestartFailedRun = root["restart.failed.run", true].AsBool();
            if (log.Count > 0)
            {
               ConfigNode lastEntry = log[log.Count - 1];
               if (!lastEntry["run.status"].AsBool())
               {
                  if (RestartFailedRun)
                  {
                     sim.Start = lastEntry["sim.start"].AsDateTime(dateFormat);
                     sim.SimLenght = lastEntry["sim.lenght"].AsDouble();
                     simID = lastEntry["sim.id"].AsInt();
                  }
                  else
                     return false;
               }
               else
               {
                  sim.Start = lastEntry["sim.end"].AsDateTime(dateFormat);
                  sim.SimLenght = root["sim.lenght", 14].AsDouble();
                  simID = lastEntry["sim.id"].AsInt() + 1;
               }
            }
            else
            {
               sim.Start = root["sim.start"].AsDateTime(dateFormat);
               sim.SimLenght = root["sim.lenght", 14].AsDouble();
               simID = 1;
            }

            sim.WorkingDirectory = root["working.folder", "."].AsFilePath();
            sim.CheckRun = root["check.run", true].AsBool();
            sim.Verbose = root["verbose", true].AsBool();
            sim.Wait = root["wait", true].AsBool();
            sim.SuccessString = root["check.this", "successfully terminated"].AsString();
            sim.DataDirectory = root["data.folder", sim.SimDirectory.Path + "data"].AsFilePath();
            sim.SetupRunPeriod = root["setup.run.period", false].AsBool();
            if (sim.SetupRunPeriod)
            {
               sim.EndTAG = root["sim.end.tag", "<<end>>"].AsString();
               sim.StartTAG = root["sim.start.tag", "<<start>>"].AsString();
            }
            sim.SetupRunPeriod = root["wait", false].AsBool();
            sim.SaveOutput = true;
            sim.OutputFile = new FileName(sim.SimDirectory.Path + "res" + System.IO.Path.DirectorySeparatorChar + root["output.file", "result.txt"].AsString());
            sim.Executable = new FileName(sim.SimDirectory.Path + "exe" + System.IO.Path.DirectorySeparatorChar + root["mohid.executable", "mohid.exe"].AsString());
            sim.CreateInputFiles = root["use.templates", false].AsBool();
            endOfSimulation = root["sim.end"].AsDateTime(dateFormat);
            resFolder = root["results.folder", sim.SimDirectory.Path + "res"].AsFilePath();
            storeFolder = root["store.folder", sim.SimDirectory.Path + "store"].AsFilePath();
            oldFolder = root["old.folder", sim.SimDirectory.Path + "old"].AsFilePath();

            if (sim.SetupRunPeriod && !sim.CreateInputFiles)
               return false;

            if (sim.CreateInputFiles)
            {
               InputFileTemplate newTemplate;
               List<ConfigNode> itfList = root.ChildNodes.FindAll(FindFirstTemplateInfoBlocks);
               foreach (ConfigNode ticn in itfList)
               {
                  newTemplate = new InputFileTemplate(ticn["file"].AsFileName().FullPath,
                                                      (InputFileTemplateType)Enum.Parse(typeof(InputFileTemplateType), ticn["type", "data"].AsString(), true));
                  first.Add(newTemplate);
               }

               changeTemplates = root["change.templates", true].AsBool();
               if (changeTemplates)
               {
                  itfList = root.ChildNodes.FindAll(FindNextTemplateInfoBlocks);
                  foreach (ConfigNode ticn in itfList)
                  {
                     newTemplate = new InputFileTemplate(ticn["file"].AsFileName().FullPath,
                                                         (InputFileTemplateType)Enum.Parse(typeof(InputFileTemplateType), ticn["type", "data"].AsString(), true));
                     next.Add(newTemplate);
                  }
               }

               //itfList = root.ChildNodes.FindAll(FindTemplatesSpecialSetup);
               //if (itfList.Count > 0)
               //{
               //   templatesSpecialSetup = true;
               //}
               //else
               //   templatesSpecialSetup = false;
            }
             }
             catch
             {
            return false;
             }

             return true;
        }
Exemplo n.º 3
0
        static int Main(string[] args)
        {
            CmdArgs cmdArgs = null;
             Exception e = null;
             bool sendMail = false;
             bool sendSMS = false;
             bool verbose = true;
             IMohidSim stdScript = null;
             int return_value = 0;

             try
             {
            Setup.StandardSetup();
            cmdArgs = new CmdArgs(args);

            if (cmdArgs.HasOption("v"))
               verbose = true;
            else
               verbose = false;

            if (cmdArgs.HasParameter("m"))
               sendMail = true;

            if (cmdArgs.HasParameter("s"))
               sendSMS = true;

            if (cmdArgs.HasOption("i"))
               stdScript = (IMohidSim)new StandardScript();
             }
             catch (Exception ex)
             {
            if (verbose)
               Console.WriteLine("[{0}] Model Runner: Exception raised during initialization: {0}", DateTime.Now, ex.Message);

            return -1;
             }

             try
             {
            MohidRunEngine mre = new MohidRunEngine();
            mre.Verbose = verbose;
            mre.Run(cmdArgs, stdScript);
             }
             catch (Exception ex)
             {
            e = ex;
            return_value = -1;
             }

             if (sendMail)
             {
            try
            {
               Config cfg = new Config(cmdArgs.Parameter("m"));
               if (!cfg.Load())
               {
                  if (verbose)
                     Console.WriteLine("[{0}] Model Runner: Was not possible to load the mail configuration file '{1}'", DateTime.Now, cmdArgs.Parameter("mailcfg"));
               }
               else
               {
                  MailSender ms = new MailSender();

                  string sendTo,
                         header,
                         message;

                  if (e != null)
                  {
                     header = "[ERROR] " + cfg.Root["header", "MohidRun Report"].AsString();
                     sendTo = "sendto.onerror";
                     message = cfg.Root["message", "Mohid Run Report"].AsString() + Environment.NewLine;
                     message += "An exception happened" + e.Message + Environment.NewLine;

                     while (e != null)
                     {
                        message += "  => " + e.Message + Environment.NewLine;
                        e = e.InnerException;
                     }
                  }
                  else
                  {
                     header = "[SUCCESS] " + cfg.Root["header", "MohidRun Report"].AsString();
                     sendTo = "sendto.onsuccess";
                     message = cfg.Root["message", "Mohid Run Report"].AsString();
                  }

                  ms.SetFrom(cfg.Root["from"].AsString(), cfg.Root["display", cfg.Root["from"].AsString()].AsString());
                  ms.User = cfg.Root["user", "*****@*****.**"].AsString();
                  ms.Password = cfg.Root["pass", "MohidOperationalISTMARETEC2011"].AsString();
                  ms.SetMessage(message, header);
                  ms.Host = cfg.Root["host", "smtp.gmail.com"].AsString();
                  ms.Port = cfg.Root["port", 587].AsInt();
                  ms.EnableSSL = cfg.Root["enable.ssl", true].AsBool();

                  foreach (ConfigNode n in cfg.Root.ChildNodes.FindAll(delegate(ConfigNode node) { return (node.Name == sendTo || node.Name == "sendto"); }))
                  {
                     if (!(n["bcc", ""].AsString() == ""))
                        ms.AddBCC(n["bcc"].AsString(), n["display", n["bcc"].AsString()].AsString());
                     else if (!(n["cc", ""].AsString() == ""))
                        ms.AddCC(n["cc"].AsString(), n["display", n["cc"].AsString()].AsString());
                     else
                        ms.AddTo(n["to"].AsString(), n["display", n["to"].AsString()].AsString());
                  }

                  ms.SendMail();
               }
            }
            catch (Exception ex)
            {
               if (verbose)
               {
                  Console.WriteLine("[{0}] Model Runner: Was not possible to send the mail. An EXCEPTION happened. The message returned was:", DateTime.Now);
                  Console.WriteLine("{0}", ex.Message);
               }

               return_value -= 2;
            }
             }

             if (sendSMS)
             {
             }

             return return_value;
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            CmdArgs cmdArgs = null;
             Exception last_exception = null;

             try
             {
            Setup.StandardSetup();
            cmdArgs = new CmdArgs(args);

            //======================================================================================
            //Load configuration
            //======================================================================================
            Config cfg = new Config(cmdArgs.Parameter("cfg"));
            if (!cfg.Load())
            {
               Console.WriteLine("[{0}] Was not possible to load the configuration file '{1}'", DateTime.Now, cmdArgs.Parameter("cfg"));
               return;
            }

            //======================================================================================
            //Execute tasks
            //======================================================================================
            List<ConfigNode> task_list = cfg.Root.ChildNodes.FindAll(delegate(ConfigNode node) { return node.Name == "task.config"; });

            if (task_list != null && task_list.Count > 0)
            {
               Tasks t_engine = new Tasks(task_list);
               if (!t_engine.RunTasks())
               {
                  if (t_engine.SuccessfullTasks == 0)
                     Console.WriteLine("All tasks failed");
                  else if(t_engine.SuccessfullTasks == 1)
                     Console.WriteLine("Only 1 task from a total of " + t_engine.NumberOfTasks + " were successfull");
                  else
                     Console.WriteLine("Only " + t_engine.SuccessfullTasks + " tasks from a total of " + t_engine.NumberOfTasks + " were successfull");

                  last_exception = t_engine.LastException;
               }
            }
            else
            {
               last_exception = new Exception("No task.config block found in configuration.");
            }

            //======================================================================================
            //Send STATUS e-mail if mail.config block exists
            //======================================================================================
            ConfigNode mail_cfg = cfg.Root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == "mail.config"; });
            if (mail_cfg != null)
            {
               MailEngine mail_engine = new MailEngine();

               if (!mail_engine.SendMail(mail_cfg, last_exception))
               {
                  Console.WriteLine("[{0}] Was not possible to send the status e-mail.", DateTime.Now);
                  if ((last_exception = mail_engine.LastException) != null)
                     Console.WriteLine("The message returned was: {0}", last_exception);
                  return;
               }
            }
            else if (last_exception != null)
            {
               throw last_exception;
            }
             }
             catch (Exception ex)
             {
            Console.WriteLine("[{0}] An unexpected exception happened. The message returned was: {1}", DateTime.Now, ex.Message);
            return;
             }
        }
        static void Main(string[] args)
        {
            CmdArgs cmdArgs = new CmdArgs(args);
             Dictionary<String, String> replace_list = new Dictionary<string, string>();
             DateTime end, actual_start, actual_end;

             if (!cmdArgs.HasParameter("cfg"))
             {
            Console.WriteLine("Configuration file was not provided. Use --cfg [file] to provide one.");
            Console.WriteLine("Operation Aborted.");
            return;
             }

             Config cfg = new Config(cmdArgs.Parameter("cfg"));
             if (!cfg.Load())
             {
            Console.WriteLine("Was not possible to load '" + cmdArgs.Parameter("cfg") + "'.");
            if (!string.IsNullOrWhiteSpace(cfg.ExceptionMessage))
            {
               Console.WriteLine("The message returned was:");
               Console.WriteLine(cfg.ExceptionMessage);
               Console.WriteLine("Operation Aborted.");
               return;
            }
             }

             ConfigNode root = cfg.Root;

             int id = root["start.id", 1].AsInt();
             string template = root["template", "FillMatrix.template"].AsString();
             string dateFormat = root["dateFormat.format", "yyyy-MM-dd HH:mm:ss"].AsString();
             actual_start = root["start"].AsDateTime(dateFormat);
             end = root["end"].AsDateTime(dateFormat);
             int interval;
             if (root.NodeData.ContainsKey("interval.days"))
             {
            interval = root["interval.days"].AsInt();
            actual_end = actual_start.AddDays(interval);
             }
             else
             {
            interval = 10;
            actual_end = end;
             }
             string interpolation = root["interpolation.method", "2"].AsString();

             replace_list.Add("<<start>>", actual_start.ToString("yyyy M d H m s"));
             replace_list.Add("<<end>>", actual_end.ToString("yyyy M d H m s"));
             replace_list.Add("<<id>>", id.ToString());
             replace_list.Add("<<interpolation>>", interpolation);

             ExternalApp fillmatrix = new ExternalApp();

             while (actual_end <= end)
             {

            TextFile.Replace(template, "FillMatrix.dat", ref replace_list);

            fillmatrix.CheckSuccessMethod = CheckSuccessMethod.DONOTCHECK;
            fillmatrix.Wait = true;
            fillmatrix.WorkingDirectory = @".\";
            fillmatrix.Executable = @".\fillmatrix.exe";

            try
            {
               fillmatrix.Run();
            }
            catch (Exception ex)
            {
               Console.WriteLine("Erro detectado. Mensagem de erro:");
               Console.WriteLine(ex.Message);
               Console.WriteLine("ID    : {0}", id.ToString());
               Console.WriteLine("Start : {0}", actual_start.ToString());
               Console.WriteLine("End   : {0}", actual_end.ToString());
               Console.WriteLine("");
            }

            id++;
            actual_start = actual_end;
            actual_end = actual_start.AddDays(14);

            if (actual_start < end && actual_end > end)
               actual_end = end;

            replace_list["<<start>>"] = actual_start.ToString("yyyy M d H m s");
            replace_list["<<end>>"] = actual_end.ToString("yyyy M d H m s");
            replace_list["<<id>>"] = id.ToString();
             }
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            OPTamegaScript script = new OPTamegaScript();
             CmdArgs cmdArgs = null;
             Exception e = null;
             bool sendMail = false;
             bool sendSMS = false;
             bool verbose = false;

             try
             {
            Setup.StandartSetup();
            cmdArgs = new CmdArgs(args);

            if (cmdArgs.HasParameter("mailcfg"))
               sendMail = true;

            if (cmdArgs.HasParameter("smscfg"))
               sendSMS = true;

            if (cmdArgs.HasOption("verbose"))
               verbose = true;
             }
             catch (Exception ex)
             {
            Console.WriteLine("Exception raised during initialization: {0}", ex.Message);
            return;
             }

             try
             {
            if (Run(cmdArgs, verbose))
               throw new Exception("Run failed.");
             }
             catch (Exception ex)
             {
            e = ex;
             }

             if (sendMail)
             {
            try
            {
               Config cfg = new Config(cmdArgs.Parameter("mailcfg"));
               if (!cfg.Load())
               {
                  Console.WriteLine("[{0}] Was not possible to load the mail configuration file '{1}'", DateTime.Now, cmdArgs.Parameter("mailcfg"));
               }
               else
               {
                  MailSender ms = new MailSender();

                  string sendTo,
                         header,
                         message;

                  if (e != null)
                  {
                     header = "[ERROR] " + cfg.Root["header", "MohidRun Report"].AsString();
                     sendTo = "sendto.onerror";
                     message = cfg.Root["message", "Mohid Run Report"].AsString() + Environment.NewLine;
                     message += "Exception raised: " + Environment.NewLine;
                     message += e.Message;
                  }
                  else
                  {
                     header = "[SUCCESS] " + cfg.Root["header", "MohidRun Report"].AsString();
                     sendTo = "sendto.onsuccess";
                     message = cfg.Root["message", "Mohid Run Report"].AsString();
                  }

                  ms.SetFrom(cfg.Root["from"].AsString(), cfg.Root["display", cfg.Root["from"].AsString()].AsString());
                  ms.User = cfg.Root["user", "*****@*****.**"].AsString();
                  ms.Password = cfg.Root["pass", "MohidOperationalISTMARETEC2011"].AsString();
                  ms.SetMessage(message, header);
                  ms.Host = cfg.Root["host", "smtp.gmail.com"].AsString();
                  ms.Port = cfg.Root["port", 587].AsInt();
                  ms.EnableSSL = cfg.Root["enable.ssl", true].AsBool();

                  foreach (ConfigNode n in cfg.Root.ChildNodes.FindAll(delegate(ConfigNode node) { return (node.Name == sendTo || node.Name == "sendto"); }))
                  {
                     if (!(n["bcc", ""].AsString() == ""))
                        ms.AddBCC(n["bcc"].AsString(), n["display", n["bcc"].AsString()].AsString());
                     else if (!(n["cc", ""].AsString() == ""))
                        ms.AddCC(n["cc"].AsString(), n["display", n["cc"].AsString()].AsString());
                     else
                        ms.AddTo(n["to"].AsString(), n["display", n["to"].AsString()].AsString());
                  }

                  ms.SendMail();
               }
            }
            catch (Exception ex)
            {
               Console.WriteLine("[{0}] Was not possible to send the mail. An EXCEPTION happened. The message returned was:", DateTime.Now);
               Console.WriteLine("{0}", ex.Message);
            }
             }

             if (sendSMS)
             {
             }
        }
Exemplo n.º 7
0
        static void LoadConfig(CmdArgs args, MohidRunEngineData data)
        {
            data.cfg = new Config();
             Config cfg = data.cfg;

             string configFile;
             if (args.HasParameter("simcfg"))
            configFile = args.Parameter("simcfg");
             else
            configFile = "sim.cfg";

             cfg.ConfigFile.FullPath = configFile;
             if (!cfg.Load())
            throw new Exception("Was not possible to load the configuration file '" + configFile + "'. " + cfg.ExceptionMessage);
        }
Exemplo n.º 8
0
        static int Main(string[] args)
        {
            CmdArgs cmdArgs = null;
             Exception last_exception = null;
             string task_block;

             try
             {
            Setup.StandartSetup();
            cmdArgs = new CmdArgs(args);

            //======================================================================================
            //Load configuration
            //======================================================================================
            Config cfg = new Config(cmdArgs.Parameter("cfg"));
            if (!cfg.Load())
            {
               Console.WriteLine("[{0}] Was not possible to load the configuration file '{1}'", DateTime.Now, cmdArgs.Parameter("cfg"));
               return -1;
            }

            //======================================================================================
            //Check to see if there are a specific name for the task block
            //======================================================================================
            if (cmdArgs.HasParameter("task"))
               task_block = cmdArgs.Parameter("task");
            else
               task_block = "task.config";

            //======================================================================================
            //Execute task
            //======================================================================================
            ConfigNode task_cfg = cfg.Root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == task_block; });
            if (task_cfg != null)
            {
               TaskEngine te = new TaskEngine();
               if (!te.LoadConfig(task_cfg))
               {
                  if ((last_exception = te.LastException) == null)
                     last_exception = new Exception("Unknow error during process of task configuration.");
               }
               if (!te.CreateNewHDF())
               {
                  if ((last_exception = te.LastException) == null)
                     last_exception = new Exception("Unknow error during process of task execution.");
               }
               te.End();
            }
            else
            {
               last_exception = new Exception("No task.config block found in configuration.");
            }

            if (cmdArgs.HasOption("verbose"))
            {
               if (last_exception != null)
                  Console.WriteLine("MohidHDF5Processor FAILED to complete the process.");
               else
                  Console.WriteLine("MohidHDF5Processor SUCCESSFULLY completed the process.");
            }

            //======================================================================================
            //Send STATUS e-mail if mail.config block exists
            //======================================================================================
            ConfigNode mail_cfg = cfg.Root.ChildNodes.Find(delegate(ConfigNode node) { return node.Name == "mail.config"; });
            if (mail_cfg != null)
            {
               MailEngine mail_engine = new MailEngine();

               if (!mail_engine.SendMail(mail_cfg, last_exception))
               {
                  Console.WriteLine("[{0}] Was not possible to send the status e-mail.", DateTime.Now);
                  if ((last_exception = mail_engine.LastException) != null)
                     Console.WriteLine("The message returned was: {0}", last_exception);
                  return -1;
               }
            }
            else if (last_exception != null)
            {
               throw last_exception;
            }
             }
             catch(Exception ex)
             {
            Console.WriteLine("[{0}] An unexpected exception happened. The message returned was: {1}", DateTime.Now, ex.Message);
            return -1;
             }

             return 0;

              //   HDFEngine engine = new HDFEngine();
              //   Exception last_ex = null;

              //   Console.WriteLine("Starting...");

              //   if (!engine.InitializeLibrary())
              //   {
              //      Console.WriteLine("Library start failed.");
              //      if ((last_ex = engine.LastException) != null)
              //         Console.WriteLine("Message: {0}", last_ex.Message);
              //   }

              //   if (!engine.OpenHDF(new FileName(@"E:\Development\Tests\HDF5\basin.evtp.hdf5")))
              //   {
              //      Console.WriteLine("File Open failed.");
              //      if ((last_ex = engine.LastException) != null)
              //         Console.WriteLine("Message: {0}", last_ex.Message);
              //   }

              //   Console.WriteLine("ROOT: '/'");
              //   List<HDFObjectInfo> list = engine.GetTree(null, engine.FileID, "/");
              //   PrintList(list, 0);

              //   Console.WriteLine("");

              //   Console.WriteLine("ROOT: '/Grid/'");
              //   list.Clear();
              //   list = engine.GetTree(null, engine.FileID, "/Grid/");
              //   PrintList(list, 1);

              //   if (!engine.CloseHDF())
              //   {
              //      Console.WriteLine("File Close failed.");
              //      if ((last_ex = engine.LastException) != null)
              //         Console.WriteLine("Message: {0}", last_ex.Message);
              //   }

              //   if (!engine.CloseLibrary())
              //   {
              //      Console.WriteLine("Library close failed.");
              //      if ((last_ex = engine.LastException) != null)
              //         Console.WriteLine("Message: {0}", last_ex.Message);
              //   }

              //   Console.WriteLine("End. Press any key.");
              //   Console.ReadKey();
              //}

              //public static void PrintList(List<HDFObjectInfo> list, int level)
              //{
              //   foreach (HDFObjectInfo oi in list)
              //   {
              //      Console.WriteLine("{0}: {1}", level, oi.Name);
              //      if (oi.Children != null)
              //         PrintList(oi.Children, level + 1);
              //   }
        }
Exemplo n.º 9
0
            protected void LoadConfig(CmdArgs args)
            {
                try
                {
                   data.cfg = new Config();
                   Config cfg = data.cfg;

                   string configFile;
                   if (args.HasParameter("simcfg"))
                  configFile = args.Parameter("simcfg");
                   else
                  configFile = "sim.cfg";

                   if (args.HasParameter("max.iter"))
                  data.maxIterations = int.Parse(args.Parameter("max.iter"));
                   else
                  data.maxIterations = -1;

                   cfg.ConfigFile.FullPath = configFile;
                   if (!cfg.Load())
                  throw new Exception("Was not possible to load the configuration file '" + configFile + "'. " + cfg.ExceptionMessage);

                   ConfigNode root = cfg.Root;

                   data.sim.SimDirectory = root["sim.folder", "sim"].AsFilePath();
                   data.logFileName = root["log.file", data.sim.SimDirectory.Path + "sim.log"].AsFileName();

                   data.RestartFailedRun = root["restart.failed.run", true].AsBool();

                   data.sim.Start = root["sim.start"].AsDateTime(data.dateFormat);
                   data.sim.SimLenght = root["sim.lenght", 14].AsDouble();
                   data.simID = 1;

                   data.sim.CheckRun = root["check.run", true].AsBool();
                   data.sim.Verbose = root["verbose", true].AsBool();
                   data.sim.Wait = root["wait", true].AsBool();
                   data.sim.SuccessString = root["check.this", "successfully terminated"].AsString();

                   data.sim.SetupRunPeriod = root["setup.run.period", false].AsBool();

                   if (data.sim.SetupRunPeriod)
                   {
                  data.sim.EndTAG = root["sim.end.tag", "<<end>>"].AsString();
                  data.sim.StartTAG = root["sim.start.tag", "<<start>>"].AsString();
                   }

                   data.sim.DataDirectory = root["data.folder", data.sim.SimDirectory.Path + "data"].AsFilePath();
                   data.sim.WorkingDirectory = root["working.folder", data.sim.SimDirectory.Path + "exe"].AsFilePath();
                   data.resFolder = root["results.folder", data.sim.SimDirectory.Path + "res"].AsFilePath();
                   data.storeFolder = root["store.folder", data.sim.SimDirectory.Path + "store"].AsFilePath();
                   data.oldFolder = root["old.folder", data.sim.SimDirectory.Path + "old"].AsFilePath();

                   data.sim.SaveOutput = root["save.output", true].AsBool();
                   if (data.sim.SaveOutput)
                   {
                  data.sim.OutputFile = new FileName(data.resFolder.Path + root["output.file", "result.txt"].AsString());
                   }

                   data.sim.Executable = root["mohid.executable", "mohid.exe"].AsFileName();
                   data.sim.CreateInputFiles = root["use.templates", false].AsBool();
                   if (root.NodeData.ContainsKey("sim.end"))
                   {
                  data.useEndOfSimulation = true;
                  data.endOfSimulation = root["sim.end"].AsDateTime(data.dateFormat);
                   }
                   else
                  data.useEndOfSimulation = false;

                   if (!data.useEndOfSimulation && data.maxIterations < 1 && !root["infinite.run", false].AsBool())
                  throw new Exception("'sim.end' keyword and 'max.iter' parameter are missing and 'infinit.run' keyword is missing or set to False.");

                   if (data.sim.SetupRunPeriod && !data.sim.CreateInputFiles)
                  throw new Exception("If 'setup.run.period' is set to True, 'use.templates' also must be set to True.");

                   if (data.sim.CreateInputFiles)
                   {
                  InputFileTemplate newTemplate;
                  List<ConfigNode> itfList = root.ChildNodes.FindAll(FindFirstTemplateInfoBlocks);
                  foreach (ConfigNode ticn in itfList)
                  {
                     newTemplate = new InputFileTemplate(ticn["file"].AsFileName().FullPath,
                                                         (InputFileTemplateType)Enum.Parse(typeof(InputFileTemplateType), ticn["type", "data"].AsString(), true));
                     data.templatesStart.Add(newTemplate);
                  }
                  data.sim.TemplateFilesList = data.templatesStart;

                  data.changeTemplates = root["change.templates", true].AsBool();
                  if (data.changeTemplates)
                  {
                     itfList = root.ChildNodes.FindAll(FindNextTemplateInfoBlocks);
                     foreach (ConfigNode ticn in itfList)
                     {
                        newTemplate = new InputFileTemplate(ticn["file"].AsFileName().FullPath,
                                                            (InputFileTemplateType)Enum.Parse(typeof(InputFileTemplateType), ticn["type", "data"].AsString(), true));
                        data.templatesContinuation.Add(newTemplate);
                     }
                  }
                   }
                }
                catch (Exception ex)
                {
                   throw new Exception("MohidRunEngine.LoadConfig", ex);
                }
            }
Exemplo n.º 10
0
            protected IMohidSim LoadUserInterface(CmdArgs args)
            {
                try
                {
                   FileName interfaceName;
                   data.sim.PreProcessing = OnPreProcessing;

                   if (args.HasParameter("script"))
                  interfaceName = new FileName(args.Parameters["script"]);
                   else
                  return null;

                   if (interfaceName.Extension.ToLower() == "dll") //it's a library
                   {
                  if (!args.HasParameter("class"))
                     return null;

                  string class_name = args.Parameter("class");

                  Assembly ass = Assembly.LoadFrom(interfaceName.FullPath);
                  data.userInterface = (IMohidSim)Activator.CreateInstance(ass.GetType("Mohid." + class_name));
                  return data.userInterface;
                   }
                   else //it's a script
                   {
                  ScriptCompiler sc = new ScriptCompiler();
                  Assembly ass = sc.Compile(interfaceName);
                  data.userInterface = (IMohidSim)sc.FindScriptInterface("IMohidSim", ass);
                  return data.userInterface;
                   }
                }
                catch (Exception ex)
                {
                   throw new Exception("MohidRunEngine.LoadUserInterface", ex);
                }
            }