Пример #1
0
 /// <summary>
 /// Called by clicking on the open button of CrypTool
 /// loads a serialized model
 /// </summary>
 /// <param name="fileName"></param>
 public void Open(string fileName)
 {
     try
     {
         New();
         CurrentFile = fileName;
         GuiLogMessage(String.Format(Resources.WorkspaceManagerClass_Open_Loading_Model___0_, fileName), NotificationLevel.Info);
         var persistance = new ModelPersistance();
         persistance.OnGuiLogNotificationOccured += OnGuiLogNotificationOccured;
         WorkspaceModel = persistance.loadModel(fileName, Cryptool.Core.Globals.templateReplacement);
         WorkspaceModel.OnGuiLogNotificationOccured += this.GuiLogNotificationOccured;
         var dispatcherOp = WorkspaceSpaceEditorView.Load(WorkspaceModel);
         HandleTemplateLoadingDispatcher(dispatcherOp, fileName);
         WorkspaceModel.UpdateableView = this.WorkspaceSpaceEditorView;
         this.OnProjectTitleChanged.Invoke(this, System.IO.Path.GetFileName(fileName));
         WorkspaceModel.MyEditor = this;
         WorkspaceModel.UndoRedoManager.ClearStacks();
     }
     catch (Exception ex)
     {
         string s = ex.ToString();
         GuiLogMessage(String.Format(Resources.WorkspaceManagerClass_Open_Could_not_load_Model___0_, s), NotificationLevel.Error);
         if (LoadingErrorOccurred != null)
         {
             LoadingErrorOccurred.Invoke(this, new LoadingErrorEventArgs()
             {
                 Message = s
             });
         }
     }
 }
Пример #2
0
        private static WorkspaceModel GetWorkspaceModel(string fileName)
        {
            var modelLoader = new ModelPersistance();
            var model       = modelLoader.loadModel(Path.Combine(_templateDirectory.FullName, fileName));

            return(model);
        }
Пример #3
0
        /// <summary>
        /// This method analyses a given cwm file and returns all parameters
        /// </summary>
        /// <param name="cwm_file"></param>
        private void DiscoverCWMFile(string cwm_file)
        {
            try
            {
                UpdateAppDomain();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while updating AppDomain: {0}", ex.Message);
                Environment.Exit(-4);
            }

            ModelPersistance modelPersistance = new ModelPersistance();

            try
            {
                _workspaceModel = modelPersistance.loadModel(cwm_file, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured during loading of cwm file: {0}", ex.Message);
                Environment.Exit(0);
            }
            DiscoverWorkspaceModel(cwm_file);
        }
Пример #4
0
 private byte[] SerializeWorkspace()
 {
     using (var stream = new MemoryStream())
         using (var streamWriter = new StreamWriter(stream))
         {
             var persistantModel = new ModelPersistance().GetPersistantModel(WorkspaceModel);
             XMLSerialization.XMLSerialization.Serialize(persistantModel, streamWriter, true);
             return(stream.ToArray());
         }
 }
Пример #5
0
 public static byte[] Serialize(WorkspaceModel workspaceModel)
 {
     using (var stream = new MemoryStream())
         using (var streamWriter = new StreamWriter(stream))
         {
             var persistantModel = new ModelPersistance().GetPersistantModel(workspaceModel);
             XMLSerialization.XMLSerialization.Serialize(persistantModel, streamWriter, true);
             var serialize = Compress(stream.ToArray());
             return(serialize);
         }
 }
Пример #6
0
        private void LoadAndCheckTemplate(string file, Dictionary <string, List <KeyValuePair <string, object> > > pluginProperties)
        {
            var modelLoader = new ModelPersistance();

            modelLoader.OnGuiLogNotificationOccured += (sender, args) => LogHandler(args.NotificationLevel, file);

            var model = modelLoader.loadModel(Path.Combine(_templateDirectory.FullName, file), false);

            model.OnGuiLogNotificationOccured += (sender, args) => LogHandler(args.NotificationLevel, file);

            /*
             * foreach (PluginModel pluginModel in model.GetAllPluginModels())
             * {
             *  pluginModel.Plugin.Initialize();
             * }
             */

            //iterate over all plugins which properties should be set and check them:
            foreach (var pluginSetting in pluginProperties)
            {
                KeyValuePair <string, List <KeyValuePair <string, object> > > setting = pluginSetting;
                int count = 0;
                foreach (var plugin in model.GetAllPluginModels().Where(x => x.GetName() == setting.Key))
                {
                    count++;

                    foreach (var property in pluginSetting.Value)
                    {
                        try
                        {
                            if (!WizardControl.SetPluginProperty(new PluginPropertyValue()
                            {
                                PluginName = setting.Key, PropertyName = property.Key, Value = property.Value
                            }, plugin))
                            {
                                PropertyFail(file, pluginSetting, property);
                            }
                        }
                        catch (Exception ex)
                        {
                            PropertyFail(file, pluginSetting, property);
                        }
                    }
                }

                if (count == 0)
                {
                    Assert.Fail(string.Format("Plugin with name {0} does not exist in template {1}!", setting.Key, file));
                }
            }
        }
Пример #7
0
 /// <summary>
 /// Called by clicking on the save button of CrypTool
 /// serializes the current model
 /// </summary>
 /// <param name="fileName"></param>
 public void Save(string fileName)
 {
     try
     {
         GuiLogMessage(String.Format(Resources.WorkspaceManagerClass_Save_Saving_Model___0_, fileName), NotificationLevel.Info);
         var persistance = new ModelPersistance();
         persistance.OnGuiLogNotificationOccured += OnGuiLogNotificationOccured;
         persistance.saveModel(this.WorkspaceModel, fileName);
         CurrentFile = fileName;
         this.OnProjectTitleChanged.Invoke(this, System.IO.Path.GetFileName(fileName));
     }
     catch (Exception ex)
     {
         GuiLogMessage(String.Format(Resources.WorkspaceManagerClass_Save_Could_not_save_Model___0_, ex.ToString()), NotificationLevel.Error);
     }
 }
Пример #8
0
        private static StreamWriter Save(WorkspaceModel model)
        {
            var persistance = new ModelPersistance();
            var pmod        = persistance.GetPersistantModel(model);

            MemoryStream ms     = new MemoryStream();
            StreamWriter writer = null;

            try
            {
                writer = new StreamWriter(ms, Encoding.UTF8);
                XMLSerialization.XMLSerialization.Serialize(pmod, writer);
                return(writer);
            }
            catch (Exception e)
            {
                throw new NullReferenceException();
            }
        }
Пример #9
0
 private static WorkspaceModel Open(StreamWriter writer)
 {
     try
     {
         var persistance = new ModelPersistance();
         var wp          = persistance.loadModel(writer);
         return(wp);
     }
     catch (Exception)
     {
         throw new NullReferenceException();
     }
     finally
     {
         if (writer != null)
         {
             writer.Close();
         }
     }
 }
Пример #10
0
        public static void GenerateStatisticsFromTemplate(string templateDir)
        {
            var modelLoader = new ModelPersistance();

            foreach (var file in Directory.GetFiles(templateDir, "*.cwm", SearchOption.AllDirectories))
            {
                var templateFile = new FileInfo(file);
                if (templateFile.Name.StartsWith("."))
                {
                    continue;
                }

                try
                {
                    using (var model = modelLoader.loadModel(templateFile.FullName))
                    {
                        //Analyse model connections:
                        foreach (var pluginModel in model.GetAllPluginModels())
                        {
                            foreach (var inputConnector in pluginModel.GetInputConnectors())
                            {
                                AnalyseConnectorUsage(inputConnector);
                            }
                            foreach (var outputConnector in pluginModel.GetOutputConnectors())
                            {
                                AnalyseConnectorUsage(outputConnector);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Error loading model... Just ignore
                }
            }
        }
Пример #11
0
        /// <summary>
        /// Starts the execution of the defined workspace
        /// 1) Parses the commandline parameters
        /// 2) Creates CT2 model and execution engine
        /// 3) Starts execution
        /// 4) Gives data as defined by user to the model
        /// 5) Retrieves results for output and outputs these
        /// 6) [terminates]
        /// </summary>
        /// <param name="args"></param>
        public void Start(string[] args)
        {
            _startTime = DateTime.Now;

            //Step 0: Set locale to English
            var cultureInfo = new CultureInfo("en-us", false);

            CultureInfo.CurrentCulture              = cultureInfo;
            CultureInfo.CurrentUICulture            = cultureInfo;
            CultureInfo.DefaultThreadCurrentCulture = cultureInfo;

            //Step 1: Check, if Help needed
            if (ArgsHelper.GetShowHelp(args))
            {
                Environment.Exit(0);
            }

            //Step 2: Get cwm_file to open
            string cwm_file = ArgsHelper.GetCWMFileName(args);

            if (cwm_file == null)
            {
                Console.WriteLine("Please specify a cwm file using -cwm=filename");
                Environment.Exit(-1);
            }
            if (!File.Exists(cwm_file))
            {
                Console.WriteLine("Specified cwm file \"{0}\" does not exist", cwm_file);
                Environment.Exit(-2);
            }

            //Step 3: Get additional parameters
            _verbose = ArgsHelper.CheckVerboseMode(args);
            try
            {
                _timeout = ArgsHelper.GetTimeout(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(-2);
            }
            try
            {
                _loglevel = ArgsHelper.GetLoglevel(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(-2);
            }
            try
            {
                _terminationType = ArgsHelper.GetTerminationType(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(-2);
            }
            try
            {
                _jsonoutput = ArgsHelper.CheckJsonOutput(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Environment.Exit(-2);
            }

            //Step 4: Check, if discover mode was selected
            if (ArgsHelper.CheckDiscoverMode(args))
            {
                DiscoverCWMFile(cwm_file);
                Environment.Exit(0);
            }

            //Step 5: Get input parameters
            List <Parameter> inputParameters = null;

            try
            {
                inputParameters = ArgsHelper.GetInputParameters(args);
                if (_verbose)
                {
                    foreach (var param in inputParameters)
                    {
                        Console.WriteLine("Input parameter given: " + param);
                    }
                }
            }
            catch (InvalidParameterException ipex)
            {
                Console.WriteLine(ipex.Message);
                Environment.Exit(-3);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while parsing parameters: {0}", ex.Message);
                Environment.Exit(-3);
            }

            //Step 6: Get output parameters
            List <Parameter> outputParameters = null;

            try
            {
                outputParameters = ArgsHelper.GetOutputParameters(args);
                if (_verbose)
                {
                    foreach (var param in inputParameters)
                    {
                        Console.WriteLine("Output parameter given: " + param);
                    }
                }
            }
            catch (InvalidParameterException ipex)
            {
                Console.WriteLine(ipex.Message);
                Environment.Exit(-3);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while parsing parameters: {0}", ex.Message);
                Environment.Exit(-3);
            }

            //Step 7: Update application domain. This allows loading additional .net assemblies
            try
            {
                UpdateAppDomain();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while updating AppDomain: {0}", ex.Message);
                Environment.Exit(-4);
            }

            //Step 8: Load cwm file and create model
            try
            {
                ModelPersistance modelPersistance = new ModelPersistance();
                _workspaceModel = modelPersistance.loadModel(cwm_file, true);

                foreach (var pluginModel in _workspaceModel.GetAllPluginModels())
                {
                    pluginModel.Plugin.OnGuiLogNotificationOccured += OnGuiLogNotificationOccured;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while loading model from cwm file: {0}", ex.Message);
                Environment.Exit(-5);
            }

            //Step 9: Set input parameters
            foreach (var param in inputParameters)
            {
                string name  = param.Name;
                bool   found = false;
                foreach (var component in _workspaceModel.GetAllPluginModels())
                {
                    //we also memorize here the name of each plugin
                    if (!_pluginNames.ContainsKey(component.Plugin))
                    {
                        _pluginNames.Add(component.Plugin, component.GetName());
                    }

                    if (component.GetName().ToLower().Equals(param.Name.ToLower()))
                    {
                        if (component.PluginType.FullName.Equals("CrypTool.TextInput.TextInput"))
                        {
                            var settings     = component.Plugin.Settings;
                            var textProperty = settings.GetType().GetProperty("Text");

                            if (param.ParameterType == ParameterType.Text || param.ParameterType == ParameterType.Number)
                            {
                                textProperty.SetValue(settings, param.Value);
                            }
                            else if (param.ParameterType == ParameterType.File)
                            {
                                try
                                {
                                    if (!File.Exists(param.Value))
                                    {
                                        Console.WriteLine("Input file does not exist: {0}", param.Value);
                                        Environment.Exit(-7);
                                    }
                                    var value = File.ReadAllText(param.Value);
                                    textProperty.SetValue(settings, value);
                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine("Exception occured while reading file {0}: {0}", param.Value, ex.Message);
                                    Environment.Exit(-7);
                                }
                            }
                            //we need to call initialize to get the new text to the ui of the TextInput component
                            //otherwise, it will output the value retrieved by deserialization
                            component.Plugin.Initialize();
                            found = true;
                        }
                    }
                }
                if (!found)
                {
                    Console.WriteLine("Component for setting input parameter not found: {0}", param);
                    Environment.Exit(-7);
                }
            }

            //Step 10: Set output parameters
            foreach (var param in outputParameters)
            {
                string name  = param.Name;
                bool   found = false;
                foreach (var component in _workspaceModel.GetAllPluginModels())
                {
                    if (component.GetName().ToLower().Equals(param.Name.ToLower()))
                    {
                        if (component.PluginType.FullName.Equals("TextOutput.TextOutput"))
                        {
                            component.Plugin.PropertyChanged += Plugin_PropertyChanged;
                            found = true;
                        }
                    }
                }
                if (!found)
                {
                    Console.WriteLine("TextOutput for setting output parameter not found: {0}", param);
                    Environment.Exit(-7);
                }
            }

            //Step 11: add OnPluginProgressChanged handlers
            foreach (var plugin in _workspaceModel.GetAllPluginModels())
            {
                plugin.Plugin.OnPluginProgressChanged += OnPluginProgressChanged;
            }

            //Step 12: Create execution engine
            try
            {
                _engine = new ExecutionEngine(null);
                _engine.OnGuiLogNotificationOccured += OnGuiLogNotificationOccured;
                _engine.Execute(_workspaceModel, false);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception occured while executing model: {0}", ex.Message);
                Environment.Exit(-7);
            }

            //Step 13: Start execution in a dedicated thread
            DateTime endTime = DateTime.Now.AddSeconds(_timeout);
            Thread   t       = new Thread(() =>
            {
                CultureInfo.CurrentCulture = new CultureInfo("en-Us", false);
                while (_engine.IsRunning())
                {
                    Thread.Sleep(100);
                    if (_engine.IsRunning() && _timeout < int.MaxValue && DateTime.Now >= endTime)
                    {
                        Console.WriteLine("Timeout ({0} seconds) reached. Kill process hard now", _timeout);
                        Environment.Exit(-8);
                    }
                }
                if (_verbose)
                {
                    Console.WriteLine("Execution engine stopped. Terminate now");
                    Console.WriteLine("Total execution took: {0}", DateTime.Now - _startTime);
                }
                Environment.Exit(0);
            });

            t.Start();
        }