Exemplo n.º 1
0
    static private string NameImageFile()
    {
        ExperimentSettings _expInstance  = ExperimentSettings.GetInstance();
        string             imageFileName = _expInstance.FileName + "_" + _expInstance.MazeSettings.TrialName + _expInstance.TrialTracker[_expInstance.MazeSettings.TrialName].ToString() + "_";

        if (ExperimentSettings.IsAP() ||
            ExperimentSettings.IsSPT() ||
            ExperimentSettings.IsTP())
        {
            if (_expInstance.MazeSettings.Arrows)
            {
                imageFileName += "Arrows_";
            }
        }
        if (ExperimentSettings.IsCM())
        {
            imageFileName += "Start" + _expInstance.MazeSettings.StartLocationCM + "-";
            if (!string.IsNullOrEmpty(_expInstance.MazeSettings.LandmarkGoalCM))
            {
                imageFileName += "Landmark" + _expInstance.MazeSettings.LandmarkGoalCM;
            }
        }

        imageFileName += "_path.png";

        return(imageFileName);
    }
Exemplo n.º 2
0
        public NeatTrainer(ExperimentSettings experimentSettings, NeatEvolutionAlgorithmParameters evolutionAlgorithmParameters, TrainingGameSettings gameSettings)
        {
            var neuromonPhenomeEvaluator = new NeuromonEvaluator(gameSettings, experimentSettings);
            var neatGenomeParameters = new NeatGenomeParameters();

            _neuromonExperiment = new NeuromonExperiment(experimentSettings, evolutionAlgorithmParameters, neuromonPhenomeEvaluator, neatGenomeParameters);

            _genomeIo = new GenomeIo(_neuromonExperiment);
            _genomeFactory = _neuromonExperiment.CreateGenomeFactory();

            if (experimentSettings.LoadExistingPopulation)
            {
                _genomePopulation = _genomeIo.Read(experimentSettings.ExistingPopulationFilePath);
            }
            else
            {
                // Randomly generate a new population
                _genomePopulation = _genomeFactory.CreateGenomeList(experimentSettings.PopulationSize, 0);
            }

            _genomeIo.CacheChampion(_genomePopulation.OrderByDescending(g => g.EvaluationInfo.Fitness).First());

            _fitnessStagnationDetector = new FitnessStagnationDetector(experimentSettings.StagnationDetectionTriggerValue);

            _desiredFitness = experimentSettings.DesiredFitness;

            _previousGeneration = 0;
            _overallBestFitness = 0.0;
        }
    public static void NameAndCountTrial()
    {
        _instance.MazeSettings.TrialName = _instance.MazeSettings.MazeName.ToString();
        if (ExperimentSettings.IsStudy() && !ExperimentSettings.IsPractice())
        {
            _instance.MazeSettings.TrialName += "_LearnT";
        }

        else if (!ExperimentSettings.IsStudy() && !ExperimentSettings.IsPractice())
        {
            if (!_instance.MazeSettings.Reverse)
            {
                _instance.MazeSettings.TrialName += "_FWDT";
            }
            else
            {
                _instance.MazeSettings.TrialName += "_REVT";
            }
        }

        if (_instance.TrialTracker.ContainsKey(_instance.MazeSettings.TrialName))
        {
            _instance.TrialTracker[_instance.MazeSettings.TrialName] += 1;
        }
        else
        {
            _instance.TrialTracker[_instance.MazeSettings.TrialName] = 1;
        }
    }
Exemplo n.º 4
0
    void Awake()
    {
        if (_instance != null)
        {
            Debug.Log("Instance already exists!");
            Destroy(transform.gameObject);
            return;
        }
        _instance = this;
        checkpointButton.gameObject.SetActive(true);
        resumeFromCheckpointButton.gameObject.SetActive(false);
        //		DoMicTest ();
        //		if(Application.loadedLevel==0)
        //			InitMainMenuLabels ();
        //		CheckGamifiedStatus ();
        //		if (SceneManager.GetActiveScene ().name == "EndMenu") {
        //			AttachSceneController ();


        ChangeFirstEnvironment();
        //		ChangeReevalType ();
        reevalType = ReevalType.Transition;
        InitMainMenuLabels();

        SetConnectionMethod();
        SetSessionDay();
        SetControlDevice();
        SetControlToggle();

//		reevalType = ReevalType.Reward;
//		}
    }
Exemplo n.º 5
0
        public ExperimentObserver(StorageCache cache, ExperimentSettings expSettings, BiomeFilter filter,
                                  ScanInterface scanMapInterface, string expid, ModuleScienceExperiment exp = null)
        {
            settings            = expSettings;
            biomeFilter         = filter;
            requireControllable = true;
            if (exp != null)
            {
                rerunnable = exp.rerunnable;
                resettable = exp.resettable;
            }

            if (scanMapInterface == null)
            {
                scanMapInterface = new DefaultScanInterface();
            }

            scanInterface = scanMapInterface;

            experiment = ResearchAndDevelopment.GetExperiment(expid);

            if (experiment == null)
            {
                Log.Error("Failed to get experiment '{0}'", expid);
            }

            storage = cache;
            Rescan();
        }
Exemplo n.º 6
0
        ///////////////////////////////////////////////////////////////////////////////
        // Construction and Initializing methods                                     //
        ///////////////////////////////////////////////////////////////////////////////
        #region CONSTRUCTION

        /// <summary>
        /// Initializes a new instance of the Document class.
        /// </summary>
        public Document()
        {
            activeDocument          = this;
            this.isModified         = false;
            this.experimentSettings = new ExperimentSettings();
            this.selectionState     = new SelectionsState();
        }
        public static Experiment CreateExperimentGO(string expName, ExperimentSettings settings = null)
        {
            var expGO = new GameObject();

            expGO.transform.name   = expName;
            expGO.transform.parent = ExperimentManager.Instance.transform;
            var experimentClass = TypeHelper.GetTypeByName(expName);

            if (experimentClass == null)
            {
                Debug.Log("Experiment of name " + expName + "does not exist");
                return(null);
            }
            var exp = expGO.AddComponent(experimentClass) as Experiment;

            //exp.Settings
            if (exp != null)
            {
                exp.AddSettings(settings);
                //this is here so that logs are created properly
                exp.Name = expName;
                return(exp);
            }
            return(null);
        }
Exemplo n.º 8
0
        public async Task <ExperimentSettings> CreateAsync(ExperimentSettings entity)
        {
            VPLContext.ExperimentSettings.Add(entity);
            await VPLContext.SaveChangesAsync();

            return(entity);
        }
Exemplo n.º 9
0
    void OpenSubmenu()
    {
        // Cursor is disabled coming out of maze scenes
        Cursor.visible   = true;
        Cursor.lockState = CursorLockMode.None;

        // QUESTION: Could this be simplified? Still have to line up the right menu w/ the experiment type selected.
        FirstPanel.SetActive(false);
        if (ExperimentSettings.IsAP())
        {
            APPanel.SetActive(true);
        }
        else if (ExperimentSettings.IsSPT())
        {
            SPTPanel.SetActive(true);
        }
        else if (ExperimentSettings.IsTP())
        {
            TPPanel.SetActive(true);
        }
        else if (ExperimentSettings.IsCM())
        {
            CMPanel.SetActive(true);
        }
    }
Exemplo n.º 10
0
    public void OnTriggerEnter(Collider other)
    {
        Debug.Log("MazeEnd() being called due to maze completion");
        ExperimentSettings _instance = ExperimentSettings.GetInstance();

        _instance.MazeSettings.ReachedEnd = true;
        MazeController.MazeEnd();
    }
 public static ExperimentSettings GetInstance()
 {
     if (_instance == null)
     {
         _instance = new ExperimentSettings();
     }
     return(_instance);
 }
Exemplo n.º 12
0
    public void SetDir(ExperimentSettings _expInstance)
    {
        string currentDir = System.IO.Directory.GetCurrentDirectory();
        string newDir     = "reapg" + _expInstance.ParticipantID +
                            "_" + _expInstance.ExperimentType +
                            "_Sess" + _expInstance.Session.ToString();

        _expInstance.FileDir = currentDir + "\\" + newDir + "_" + DateTime.Now.ToString("ddHHmm");
        System.IO.Directory.CreateDirectory(_expInstance.FileDir);
        _expInstance.FileName = _expInstance.FileDir + "\\" + newDir;
    }
        public async Task <IActionResult> PutExperimentSettings([FromBody] ExperimentSettings experimentSettings)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await ExperimentService.UpdateSettingsAsync(experimentSettings);

            return(NoContent());
        }
Exemplo n.º 14
0
    static private List <string> GetExperimentHeader()
    {
        List <string> experimentHeader = new List <string>();

        ExperimentSettings _expInstance = ExperimentSettings.GetInstance();

        experimentHeader.Add("Participant ID: " + _expInstance.ParticipantID);
        experimentHeader.Add("Experimenter Initials: " + _expInstance.ExperimenterInitials);
        experimentHeader.Add("Date: " + _expInstance.Date);
        experimentHeader.Add("Experiment Type: " + _expInstance.ExperimentType);
        return(experimentHeader);
    }
        private int AudibleSelectionGrid(int currentValue, ref ExperimentSettings settings)
        {
            int num = GUILayout.SelectionGrid(currentValue, filterList.ToArray(), 2, GUILayout.ExpandWidth(true));

            if (num == currentValue)
            {
                return(num);
            }
            audio.PlayUI("click1");
            settings.Filter = (ExperimentSettings.FilterMethod)num;
            return(num);
        }
Exemplo n.º 16
0
 /// <summary>
 /// Construct an experiment with the given parameters
 /// </summary>
 public ExperimentProvider(ExperimentSettings settings,
                           StimulusClass stimulusClass1,
                           StimulusClass stimulusClass2,
                           IArrayView <ClassificationScheme> classificationSchemes,
                           IEEGDataSource dataSource)
 {
     this.Settings              = settings;
     this.StimulusClass1        = stimulusClass1;
     this.StimulusClass2        = stimulusClass2;
     this.ClassificationSchemes = classificationSchemes;
     this.DataSource            = dataSource;
 }
        public static ExperimentSettings PopulateExperimentSettings(string expName, string path)
        {
            ExperimentSettings settings = null;

            Type type = ExperimentSettingsType(expName);

            if (type != null)
            {
                settings = ScriptableObject.CreateInstance(type) as ExperimentSettings;
                settings.DeserialiseSettings(path);
            }
            return(settings);
        }
Exemplo n.º 18
0
 public ExperimentService(
     Belsim2020DbContext dbContext,
     ILogger <ExperimentService> logger,
     IMapper mapper,
     ICurrentUserContext userContext,
     IOptions <ExperimentSettings> settings)
 {
     this.dbContext   = dbContext;
     this.logger      = logger;
     this.mapper      = mapper;
     this.userContext = userContext;
     this.options     = settings.Value;
 }
Exemplo n.º 19
0
    private void Start()
    {
        _expInstance = ExperimentSettings.GetInstance();
        _expInstance.MazeSettings = new MazeSettings();

        if (!string.IsNullOrEmpty(_expInstance.ExperimenterInitials))          // if this already exists then we're coming out of a maze
        {
            OpenSubmenu();
        }
        else
        {
            PopulateDropdown();
        }
    }
Exemplo n.º 20
0
        /// <summary>
        /// Load experiment settings from settings file given in parameters.
        /// </summary>
        /// <param name="filePath">A <see cref="string"/> with the path
        /// and filename to the settings file.</param>
        /// <param name="splash">The loading document splash screens background worker,
        /// needed for interrupting splash when SQL connection fails.</param>
        /// <returns><strong>True</strong>,if successful, otherwise
        /// <strong>false</strong>.</returns>
        public bool LoadSettingsFromFile(string filePath, BackgroundWorker splash)
        {
            try
            {
                this.experimentSettings = ExperimentSettings.Deserialize(filePath);

                // If deserialization succeeded update possible copied experiment folders
                // references.
                if (this.experimentSettings != null)
                {
                    string filename  = Path.GetFileNameWithoutExtension(filePath);
                    string directory = Path.GetDirectoryName(filePath);

                    // Setup document path and name
                    this.experimentSettings.DocumentPath = directory;

                    // Set path properties of slideshow elements
                    this.experimentSettings.SlideShow.UpdateExperimentPathOfResources(
                        this.experimentSettings.SlideResourcesPath);

                    // Write version information
                    if (!this.experimentSettings.UpdateVersion())
                    {
                        return(false);
                    }

                    this.experimentSettings.Name = filename;

                    // Check if database file is correct located in the connection string
                    // abort if user aborts.
                    if (!this.experimentSettings.CheckDatabasePath())
                    {
                        return(false);
                    }

                    return(true);
                }
            }
            catch (WarningException)
            {
                // This is the case when the user cancels the upgrading
                return(false);
            }
            catch (Exception ex)
            {
                ExceptionMethods.HandleException(ex);
            }

            return(false);
        }
Exemplo n.º 21
0
    public static void ConfigureExperiment(ushort newWordsSeen, ushort newSessionNumber, IronPython.Runtime.List newWords = null)
    {
        wordsSeen = newWordsSeen;
        session   = newSessionNumber;
        settings  = FRExperimentSettings.GetSettingsByName(UnityEPL.GetExperimentName());
        bool isEvenNumberSession = newSessionNumber % 2 == 0;
        bool isTwoParter         = settings.isTwoParter;

        if (words == null)
        {
            SetWords(settings.wordListGenerator.GenerateListsAndWriteWordpool(settings.numberOfLists, settings.wordsPerList, settings.isCategoryPool, isTwoParter, isEvenNumberSession, UnityEPL.GetParticipants()[0]));
        }
        SaveState();
    }
Exemplo n.º 22
0
    private void OnTriggerEnter(Collider other)
    {
        ExperimentSettings _expInstance = ExperimentSettings.GetInstance();

        if (_expInstance.MazeSettings.Rotate || _expInstance.MazeSettings.Pause)
        {
            Debug.Log(gameObject.transform.position);
            MazeController.cornerTransform = gameObject.transform;
            gameObject.SetActive(false);
            //Debug.Log(gameObject.ToString());
            MazeController.onCorner    = cornerNum;
            MazeController.cornerEvent = true;
        }
    }
        public async Task <IActionResult> PostExperimentSettings([FromBody] ExperimentSettings experimentSettings)
        {
            experimentSettings.LogicalName = "experiment_settings";
            experimentSettings.CreatedOn   = DateTime.Now;
            experimentSettings.Experiment  = await ExperimentRepository.GetByIdAsync(experimentSettings.ExperimentId);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            experimentSettings = await ExperimentService.CreateSettingsAsync(experimentSettings);

            return(CreatedAtAction("GetExperimentSettings", new { id = experimentSettings.Id }, experimentSettings));
        }
Exemplo n.º 24
0
        public async Task <ExperimentSettings> UpdateSettingsAsync(ExperimentSettings entity)
        {
            var newExperimentSettings = await ExperimentSettingsRepository.GetByExperimentAsync(entity.ExperimentId);

            newExperimentSettings.Axis        = entity.Axis;
            newExperimentSettings.Friction    = entity.Friction;
            newExperimentSettings.Restitution = entity.Restitution;
            newExperimentSettings.Walls       = entity.Walls;
            newExperimentSettings.Gravity     = entity.Gravity;
            newExperimentSettings.Size        = entity.Size;

            var experimentSettings = await ExperimentSettingsRepository.UpdateAsync(newExperimentSettings);

            return(experimentSettings);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Save experiment settings to settings file given in parameters.
        /// </summary>
        /// <param name="filePath">A <see cref="string"/> with the path
        /// and filename to the settings file.</param>
        /// <returns><strong>True</strong>,if successful, otherwise
        /// <strong>false</strong>.</returns>
        public bool SaveSettingsToFile(string filePath)
        {
            try
            {
                if (ExperimentSettings.Serialize(this.experimentSettings, filePath))
                {
                    return(true);
                }
            }
            catch (Exception ex)
            {
                ExceptionMethods.HandleException(ex);
            }

            return(false);
        }
Exemplo n.º 26
0
        private void OnStart()
        {
            if (MeasurementManager.CurrentExperiment == null)
            {
                var settings =
                    new ExperimentSettings(
                        TimeSpan.FromMilliseconds(ExperimentSettings.SamplingIntervalMilliseconds),
                        IsDeltaOnly);
                MeasurementManager.CreateExperiment(settings);
            }
            else
            {
                MeasurementManager.CurrentExperiment.Settings.SamplingInterval = TimeSpan.FromMilliseconds(ExperimentSettings.SamplingIntervalMilliseconds);
            }

            MeasurementManager.Start();
        }
Exemplo n.º 27
0
        public NeuromonExperiment(ExperimentSettings experimentSettings, NeatEvolutionAlgorithmParameters evolutionAlgorithmParameters, IPhenomeEvaluator<IBlackBox> neuromonPhenomeEvaluator, NeatGenomeParameters genomeParameters)
        {
            Name = experimentSettings.ExperimentName;
            Description = experimentSettings.Description;
            InputCount = experimentSettings.InputCount;
            OutputCount = experimentSettings.OutputCount;
            DefaultPopulationSize = experimentSettings.PopulationSize;

            _neuromonPhenomeEvaluator = neuromonPhenomeEvaluator;
            _complexityRegulationStrategy = experimentSettings.ComplexityRegulationStrategy;
            _complexityThreshold = experimentSettings.ComplexityThreshold;

            // Removed from .xml configuration. TODO: Possibly make configurable via json config
            _networkActivationScheme = NetworkActivationScheme.CreateCyclicFixedTimestepsScheme(1);

            NeatEvolutionAlgorithmParameters = evolutionAlgorithmParameters;
            NeatGenomeParameters = genomeParameters;
        }
Exemplo n.º 28
0
    static private List <string> GetExperimentInfo()
    {
        List <string>      experimentInfo = new List <string>();
        ExperimentSettings _expInstance   = ExperimentSettings.GetInstance();


        experimentInfo.Add(_expInstance.MazeSettings.TrialName + _expInstance.TrialTracker[_expInstance.MazeSettings.TrialName].ToString());
        experimentInfo.Add("Maze: " + _expInstance.MazeSettings.MazeName.ToString());
        experimentInfo.Add("Trial Number: " + _expInstance.TrialTracker[_expInstance.MazeSettings.TrialName].ToString());
        experimentInfo.Add("Experiment Type: " + _expInstance.ExperimentType);


        if (ExperimentSettings.IsAP() ||
            ExperimentSettings.IsSPT() ||
            ExperimentSettings.IsTP())
        {
            experimentInfo.Add("Arrows: " + _expInstance.MazeSettings.Arrows.ToString());
        }

        if (ExperimentSettings.IsCM())
        {
            experimentInfo.Add("CM Start Location: " + _expInstance.MazeSettings.StartLocationCM);
            if (!string.IsNullOrEmpty(_expInstance.MazeSettings.StartLocationCM))
            {
                experimentInfo.Add("CM Landmark:" + _expInstance.MazeSettings.LandmarkGoalCM);
            }
        }

        experimentInfo.Add("Distance: " + totalDistance);
        experimentInfo.Add("Time: " + totalTime);
        experimentInfo.Add("Avg. Velocity: " + avgVelocity);
        if (_expInstance.MazeSettings.ReachedEnd && _expInstance.MazeSettings.MazeName != MazeNameEnum.JP)
        {
            experimentInfo.Add("Reached End: " + _expInstance.MazeSettings.ReachedEnd.ToString());
        }
        else if (!_expInstance.MazeSettings.ReachedEnd && _expInstance.MazeSettings.MazeName != MazeNameEnum.JP)
        {
            experimentInfo.Add("Reached End: False, manual exit");
        }
        experimentInfo.Add("\r\n");


        return(experimentInfo);
    }
Exemplo n.º 29
0
        ///////////////////////////////////////////////////////////////////////////////
        // Public methods                                                            //
        ///////////////////////////////////////////////////////////////////////////////
        #region PUBLICMETHODS

        /// <summary>
        /// Destruction. Clear member fields and close database connections.
        /// </summary>
        public void CleanUp()
        {
            //SqlConnection connectionString = new SqlConnection(Document.ActiveDocument.ExperimentSettings.ServerConnectionString);
            //ServerConnection connection = new ServerConnection(connectionString);
            //Server sqlServer = new Server(connection);
            try
            {
                //// If there are open connections set offline and online to kill all
                //// active connections, they are not used anymore.
                //int connections = sqlServer.GetActiveDBConnectionCount(Document.ActiveDocument.ExperimentSettings.Name);
                //if (connections > 0)
                //{
                //  string query = "ALTER DATABASE \"" + Document.ActiveDocument.ExperimentSettings.Name +
                //   "\" SET OFFLINE WITH ROLLBACK IMMEDIATE;";
                //  Queries.ExecuteSQLCommand(query);
                //  query = "ALTER DATABASE \"" + Document.ActiveDocument.ExperimentSettings.Name +
                //    "\" SET ONLINE;";
                //  Queries.ExecuteSQLCommand(query);
                //}

                // Close database connection
                if (this.dataSet != null)
                {
                    this.dataSet.Dispose();
                }

                //// Detach database from user instance
                //if (sqlServer.Databases.Contains(Document.ActiveDocument.ExperimentSettings.Name))
                //{
                //  sqlServer.DetachDatabase(Document.ActiveDocument.ExperimentSettings.Name, true);
                //}
            }
            catch (Exception ex)
            {
                ExceptionMethods.HandleException(ex);
            }

            activeDocument          = null;
            this.isModified         = false;
            this.experimentSettings = null;
            this.selectionState     = null;
        }
Exemplo n.º 30
0
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.E) && !hasEnded)
        {
            MazeEnd();
            SceneManager.LoadScene(0);
        }

        else if (Input.GetKeyDown(KeyCode.E) && hasEnded)
        {
            SceneManager.LoadScene(0);
        }

        if (Input.GetKeyDown("space") && !hasStarted)
        {
            ExperimentSettings.NameAndCountTrial();

            if (_expInstance.MazeSettings.MultiIntro)
            {
                StartCoroutine(MultiPicIntro());
            }
            else if (_expInstance.MazeSettings.SingleIntro)
            {
                StartCoroutine(SinglePicIntro());
            }
            else
            {
                StartCoroutine(WaitAndStart());
                InvokeRepeating("TrackPathEverySecond", 2.0f, 1.0f);
                controller.enabled = true;
            }
        }

        // Trial has begun, do the following:
        if (hasStarted && !hasEnded)
        {
            currentPos     = subjectInstance.transform.position;
            totalDistance += Vector3.Distance(currentPos, lastPos);
            totalTime     += Time.deltaTime;
            lastPos        = currentPos;
        }
    }
Exemplo n.º 31
0
        private static void RunExperiment(ExperimentSettings settings)
        {
            try
            {
                GlobalVariables.Dimensions    = settings.Dimensions;
                GlobalVariables.GrowCondition = new GrowCondition(
                    settings.MaxDecisionTreeHeight, settings.MaxAttributeUsage, settings.MinLeafSize);

                dataStorage = new DataStorage(
                    settings.LearnFilePath, settings.ValidationFilePath, settings.TestFilePath);

                LearnDecisionTree();

                CalculateStatistics(settings);
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong.");
            }
        }
Exemplo n.º 32
0
    void Start()
    {
        _expInstance = ExperimentSettings.GetInstance();
        InitMaze();
        totalDistance      = 0;
        totalTime          = 0;
        path               = new List <string>();
        hasEnded           = false;
        hasStarted         = false;
        picCounter         = 0;
        grabAndFaceForward = false;
        subjectInstance    = GameObject.FindWithTag("Player");
        controller         = subjectInstance.GetComponent <UnityStandardAssets.Characters.FirstPerson.FirstPersonController>();
        controller.enabled = false;
        lastPos            = subjectInstance.transform.position;
        currentPos         = subjectInstance.transform.position;
        GameObject _goTransform = new GameObject();

        cornerTransform = _goTransform.transform;
    }
Exemplo n.º 33
0
        public static Settings GetSettings(string experimentID)
        {
            Settings settings = GetSettings();
            ExperimentSettings expSettings = null;
            if (experimentID != null)
            {
                if (string.IsNullOrWhiteSpace(experimentID))
                {
                    throw new ArgumentException("experimentID", "Experiment ID cannot be whitespace.");
                }

                if (!s_experimentSettings.TryGetValue(experimentID, out expSettings))
                {
                    expSettings = new ExperimentSettings(s_appSettings, experimentID);
                    s_experimentSettings.Add(experimentID, expSettings);
                }
            }

            settings.m_experimentSettings = expSettings;

            return settings;
        }
Exemplo n.º 34
0
        //private void ReadVersion1(XPathNavigator nav)
        //{
        //    var iter = nav.SelectSingleNode("/Settings/GlobalLogLevels");
        //    if (iter == null)
        //        throw new XmlSchemaException("Settings elements does not match the required elements for this version.");
        //    else if (iter.Value != "null")
        //    {
        //        XmlReader pathReader = iter.ReadSubtree();
        //        pathReader.MoveToContent();
        //        pathReader.Read();
        //        XmlSerializer serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(SerializableDictionary<LogLevel, GlobalLogLevelSetting>), null);
        //        var logLevels = (SerializableDictionary<LogLevel, GlobalLogLevelSetting>)serializer.Deserialize(pathReader);

        //        foreach (KeyValuePair<LogLevel, GlobalLogLevelSetting> pair in logLevels)
        //        {
        //            m_globalLogLevelSettingLookup[pair.Key].IsEnabled = pair.Value.IsEnabled;
        //            m_globalLogLevelSettingLookup[pair.Key].IsLocked = pair.Value.IsLocked;
        //        }
        //    }

        //    iter = nav.SelectSingleNode("/Settings/MainWindowData");
        //    if (iter == null)
        //        throw new XmlSchemaException("Settings elements does not match the required elements for this version.");
        //    else if (!string.IsNullOrEmpty(iter.Value) && iter.Value != "null")
        //    {
        //        XmlReader pathReader = iter.ReadSubtree();
        //        //pathReader.MoveToContent();
        //        //pathReader.Read();
        //        XmlSerializer serializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(MainWindowData), null);
        //        MainWindowRect = (MainWindowData)serializer.Deserialize(pathReader);
        //    }
        //}

        //private void ReadVersion2(XPathNavigator nav)
        //{
        //    // Version 1 data hasn't changed.
        //    ReadVersion1(nav);
        //}

        private static void ReadVersion3(XPathNavigator nav)
        {
            var child = nav.SelectSingleNode("/Settings/ApplicationSettings");

            s_appSettings.ReadXml(child);

            List<ExperimentSettings> settings = new List<ExperimentSettings>();
            var nodeIterator = nav.Select("/Settings/ExperimentSettings");
            while (nodeIterator.MoveNext())
            {
                ExperimentSettings newSettings = new ExperimentSettings(s_appSettings, null);
                newSettings.ReadXml(nodeIterator.Current);

                settings.Add(newSettings);
            }

            var nonExpiredSettings = settings.Where((o) => 
            {
                return (DateTime.Now - o.LastOpened) < s_appSettings.ExperimentSettingsTTL;
            });

            foreach(ExperimentSettings expSetting in nonExpiredSettings)
            {
                s_experimentSettings.Add(expSetting.ExperimentID, expSetting);
            }
        }