Ejemplo n.º 1
0
        /// <summary>
        /// Returns an engine to the pool so it can be reused
        /// </summary>
        /// <param name="engine">Engine to return</param>
        public virtual void ReturnEngineToPool(IJsEngine engine)
        {
            if (!_metadata.ContainsKey(engine))
            {
                // This engine was from another pool. This could happen if a pool is recycled
                // and replaced with a different one (like what ReactJS.NET does when any
                // loaded files change). Let's just pretend we never saw it.
                engine.Dispose();
                return;
            }

            _metadata[engine].InUse = false;
            var usageCount = _metadata[engine].UsageCount;

            if (_options.MaxUsagesPerEngine > 0 && usageCount >= _options.MaxUsagesPerEngine)
            {
                // Engine has been reused the maximum number of times, recycle it.
                DisposeEngine(engine);
                return;
            }

            // TODO: VroomJs doesn't expose an garbage collection
            //if (
            //    _config.GarbageCollectionInterval > 0 &&
            //    usageCount % _config.GarbageCollectionInterval == 0 &&
            //    engine.SupportsGarbageCollection()
            //)
            //{
            //    engine.CollectGarbage();
            //}

            _availableEngines.Add(engine);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns an engine to the pool so it can be reused
        /// </summary>
        /// <param name="engine">Engine to return</param>
        public virtual void ReturnEngineToPool(IJsEngine engine)
        {
            EngineMetadata metadata;

            if (!_metadata.TryGetValue(engine, out metadata))
            {
                // This engine was from another pool. This could happen if a pool is recycled
                // and replaced with a different one (like what ReactJS.NET does when any
                // loaded files change). Let's just pretend we never saw it.
                engine.Dispose();
                return;
            }

            metadata.InUse = false;
            var usageCount = metadata.UsageCount;

            if (_config.MaxUsagesPerEngine > 0 && usageCount >= _config.MaxUsagesPerEngine)
            {
                // Engine has been reused the maximum number of times, recycle it.
                DisposeEngine(engine);
                return;
            }

            if (
                _config.GarbageCollectionInterval > 0 &&
                usageCount % _config.GarbageCollectionInterval == 0 &&
                engine.SupportsGarbageCollection()
                )
            {
                engine.CollectGarbage();
            }

            _availableEngines.Add(engine);
        }
Ejemplo n.º 3
0
        public static string GetCondition(List <string> constants, List <int> useConstants, string condition, string className)
        {
            GetJsEngineSwitcher();
            return(antiDupCache.GetOrAdd(condition, () =>
            {
                var js = @"var antlr4={};
antlr4.Token={};
antlr4.Token.EOF=-1;
var {3}={};
{3}.EOF = antlr4.Token.EOF;
{0}
var testNums=[{1}];
var result=[];
for(var i=0;i<testNums.length;i++){
    var _la=testNums[i];
    if({2}){
        result.push(_la)
    }
}
outResult=result.join(',');
";
                js = js.Replace("{0}", string.Join("\r\n", constants));
                js = js.Replace("{1}", string.Join(",", useConstants));
                js = js.Replace("{2}", condition);
                js = js.Replace("{3}", className);

                IJsEngine engine = JsEngineSwitcher.Current.CreateEngine(JintJsEngine.EngineName);
                engine.SetVariableValue("outResult", "");
                engine.Evaluate(js);
                var result = engine.GetVariableValue <string>("outResult");
                engine.Dispose();
                return result;
            }));
        }
        /// <summary>
        /// Get the js engine to use
        /// </summary>
        /// <returns></returns>
        private static Func <IJsEngine> GetFactory(IEnumerable <FactoryRegistration> availableFactories)
        {
            var availableEngineFactories = availableFactories
                                           .OrderBy(x => x.Priority)
                                           .Select(x => x.Factory);

            foreach (var engineFactory in availableEngineFactories)
            {
                IJsEngine engine = null;

                try
                {
                    engine = engineFactory();

                    if (EngineIsUsable(engine, true))
                    {
                        return(engineFactory);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    engine?.Dispose();
                }
            }

            throw new Exception("No engine factory could be determined.");
        }
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(IJsEngineSwitcher jsEngineSwitcher)
        {
            string defaultEngineName = jsEngineSwitcher.DefaultEngineName;

            if (!string.IsNullOrWhiteSpace(defaultEngineName))
            {
                var engineFactory = jsEngineSwitcher.EngineFactories.Get(defaultEngineName);
                if (engineFactory != null)
                {
                    return(engineFactory.CreateEngine);
                }
                else
                {
                    throw new ReactEngineNotFoundException(
                              "Could not find a factory that creates an instance of the JavaScript " +
                              "engine with name `" + defaultEngineName + "`.");
                }
            }

            if (jsEngineSwitcher.EngineFactories.Count == 0)
            {
                throw new ReactException("No JS engines were registered. Visit https://reactjs.net/docs for more information.");
            }

            var exceptionMessages = new List <string>();

            foreach (var engineFactory in jsEngineSwitcher.EngineFactories.GetRegisteredFactories())
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory.CreateEngine();
                    if (EngineIsUsable(engine))
                    {
                        // Success! Use this one.
                        return(engineFactory.CreateEngine);
                    }
                }
                catch (JsEngineLoadException ex)
                {
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex.Message));
                    exceptionMessages.Add(ex.Message);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                    exceptionMessages.Add(ex.ToString());
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            throw new ReactEngineNotFoundException("There was an error initializing the registered JS engines. " + string.Join(Environment.NewLine, exceptionMessages));
        }
Ejemplo n.º 6
0
 public virtual void TearDown()
 {
     if (_jsEngine != null)
     {
         _jsEngine.Dispose();
         _jsEngine = null;
     }
 }
 public override void Dispose()
 {
     if (_engine.SupportsGarbageCollection)
     {
         _engine.CollectGarbage();
     }
     _engine.Dispose();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Disposes the specified engine.
        /// </summary>
        /// <param name="engine">Engine to dispose</param>
        /// <param name="repopulateEngines">
        /// If <c>true</c>, a new engine will be created to replace the disposed engine
        /// </param>
        public virtual void DisposeEngine(IJsEngine engine, bool repopulateEngines = true)
        {
            engine.Dispose();
            _metadata.Remove(engine);

            if (repopulateEngines)
            {
                // Ensure we still have at least the minimum number of engines.
                PopulateEngines();
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Destroys object
 /// </summary>
 public void Dispose()
 {
     if (_disposedFlag.Set())
     {
         if (_jsEngine != null)
         {
             _jsEngine.Dispose();
             _jsEngine = null;
         }
     }
 }
Ejemplo n.º 10
0
 public override void Dispose()
 {
     if (_engine.SupportsGarbageCollection)
     {
         try {
             _engine.CollectGarbage();
         } catch (Exception) {
             Context.Debug(() => "Error collecting js garbage");
         }
     }
     _engine.Dispose();
 }
Ejemplo n.º 11
0
        public void Dispose()
        {
            if (!_disposed)
            {
                _disposed = true;

                if (_jsEngine != null)
                {
                    _jsEngine.Dispose();
                    _jsEngine = null;
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Destroys object
        /// </summary>
        public void Dispose()
        {
            if (_disposedFlag.Set())
            {
                if (_jsEngine != null)
                {
                    _jsEngine.RemoveVariable(COUNTRY_STATISTICS_SERVICE_VARIABLE_NAME);

                    _jsEngine.Dispose();
                    _jsEngine = null;
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(JsEngineSwitcher jsEngineSwitcher, bool allowMsie)
        {
            EnsureJsEnginesRegistered(jsEngineSwitcher, allowMsie);
            foreach (var engineFactory in jsEngineSwitcher.EngineFactories)
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory.CreateEngine();
                    if (EngineIsUsable(engine, allowMsie))
                    {
                        // Success! Use this one.
                        return(engineFactory.CreateEngine);
                    }
                }
                catch (Exception ex)
                {
                    // This engine threw an exception, try the next one
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            // Epic fail, none of the engines worked. Nothing we can do now.
            // Throw an error relevant to the engine they should be able to use.
#if NET40
            if (JavaScriptEngineUtils.EnvironmentSupportsClearScript())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <V8JsEngine, ClearScriptV8InitialisationException>(
                    ex => new ClearScriptV8InitialisationException(ex)
                    );
            }
#endif
#if NET40 || NETSTANDARD1_6
            if (JavaScriptEngineUtils.EnvironmentSupportsVroomJs())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <VroomJsEngine, VroomJsInitialisationException>(
                    ex => new VroomJsInitialisationException(ex.Message)
                    );
            }
#endif
            throw new ReactEngineNotFoundException();
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(IEnumerable <Registration> availableFactories)
        {
            var availableEngineFactories = availableFactories
                                           .OrderBy(x => x.Priority)
                                           .Select(x => x.Factory);

            foreach (var engineFactory in availableEngineFactories)
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory();
                    // Perform a sanity test to ensure this engine is usable
                    if (engine.Evaluate <int>("1 + 1") == 2)
                    {
                        // Success! Use this one.
                        return(engineFactory);
                    }
                }
                catch (Exception ex)
                {
                    // This engine threw an exception, try the next one
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            // Epic fail, none of the engines worked. Nothing we can do now.
            // Throw an error relevant to the engine they should be able to use.
            if (JavaScriptEngineUtils.EnvironmentSupportsClearScript())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <V8JsEngine, ClearScriptV8InitialisationException>(
                    ex => new ClearScriptV8InitialisationException(ex.Message)
                    );
            }
            else if (JavaScriptEngineUtils.EnvironmentSupportsVroomJs())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <VroomJsEngine, VroomJsInitialisationException>(
                    ex => new VroomJsInitialisationException(ex.Message)
                    );
            }
            throw new ReactEngineNotFoundException();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Destroys object
        /// </summary>
        public void Dispose()
        {
            if (_disposedFlag.Set())
            {
                if (_jsEngine != null)
                {
                    _jsEngine.RemoveVariable(VIRTUAL_FILE_MANAGER_VARIABLE_NAME);

                    _jsEngine.Dispose();
                    _jsEngine = null;
                }

                _virtualFileManager = null;
            }
        }
Ejemplo n.º 16
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }
            _disposed = true;

            if (_jsEngine == null)
            {
                return;
            }
            _jsEngine.Dispose();
            _jsEngine = null;
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Destroys object
        /// </summary>
        public void Dispose()
        {
            if (_disposedFlag.Set())
            {
                if (_jsEngine != null)
                {
                    _jsEngine.RemoveVariable(FILE_MANAGER_VARIABLE_NAME);

                    _jsEngine.Dispose();
                    _jsEngine = null;
                }

                _jsonSerializer         = null;
                _options                = null;
                _fileManager            = null;
                _createJsEngineInstance = null;
            }
        }
        public JsEvaluationViewModel Evaluate(JsEvaluationViewModel model)
        {
            IJsEngine engine = null;
            var       result = new JsEvaluationResultViewModel();

            try
            {
                engine       = _engineSwitcher.CreateEngine(model.EngineName);
                result.Value = engine.Evaluate <string>(model.Expression);
            }
            catch (JsEngineLoadException e)
            {
                var error = GetJsEvaluationErrorFromException(e);
                result.Errors.Add(error);
            }
            catch (JsRuntimeException e)
            {
                var error = GetJsEvaluationErrorFromException(e);
                error.LineNumber     = e.LineNumber;
                error.ColumnNumber   = e.ColumnNumber;
                error.SourceFragment = e.SourceFragment;

                result.Errors.Add(error);
            }
            finally
            {
                if (engine != null)
                {
                    engine.Dispose();
                }
            }

            model.Result = result;

            return(model);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(IEnumerable <Registration> availableFactories)
        {
            var availableEngineFactories = availableFactories
                                           .OrderBy(x => x.Priority)
                                           .Select(x => x.Factory);

            foreach (var engineFactory in availableEngineFactories)
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory();
                    // Perform a sanity test to ensure this engine is usable
                    if (engine.Evaluate <int>("1 + 1") == 2)
                    {
                        // Success! Use this one.
                        return(engineFactory);
                    }
                }
                catch (Exception ex)
                {
                    // This engine threw an exception, try the next one
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            // Epic fail, none of the engines worked. Nothing we can do now.
            throw new ReactException("No usable JavaScript engine found :(");
        }
Ejemplo n.º 20
0
		/// <summary>
		/// Returns an engine to the pool so it can be reused
		/// </summary>
		/// <param name="engine">Engine to return</param>
		public virtual void ReturnEngineToPool(IJsEngine engine)
		{
			if (!_metadata.ContainsKey(engine))
			{
				// This engine was from another pool. This could happen if a pool is recycled
				// and replaced with a different one (like what ReactJS.NET does when any 
				// loaded files change). Let's just pretend we never saw it.
				engine.Dispose();
				return;
			}

			_metadata[engine].InUse = false;
			var usageCount = _metadata[engine].UsageCount;
            if (_config.MaxUsagesPerEngine > 0 && usageCount >= _config.MaxUsagesPerEngine)
			{
				// Engine has been reused the maximum number of times, recycle it.
				DisposeEngine(engine);
				return;
			}

			if (
				_config.GarbageCollectionInterval > 0 && 
				usageCount % _config.GarbageCollectionInterval == 0 &&
				engine.SupportsGarbageCollection()
			)
			{
				engine.CollectGarbage();
			}

			_availableEngines.Add(engine);
		}
Ejemplo n.º 21
0
 public override void Release()
 {
     isdisposed = true;
     js.Dispose();
 }
Ejemplo n.º 22
0
 public void Dispose()
 {
     CheckDisposed();
     _engine.Dispose();
     _disposed = true;
 }
Ejemplo n.º 23
0
 public void Dispose()
 {
     _engine?.Dispose();
 }
Ejemplo n.º 24
0
        /// <summary>
        /// Gets a factory for the most appropriate JavaScript engine for the current environment.
        /// The first functioning JavaScript engine with the lowest priority will be used.
        /// </summary>
        /// <returns>Function to create JavaScript engine</returns>
        private static Func <IJsEngine> GetFactory(IJsEngineSwitcher jsEngineSwitcher, bool allowMsie)
        {
            EnsureJsEnginesRegistered(jsEngineSwitcher, allowMsie);

            string defaultEngineName = jsEngineSwitcher.DefaultEngineName;

            if (!string.IsNullOrWhiteSpace(defaultEngineName))
            {
                var engineFactory = jsEngineSwitcher.EngineFactories.Get(defaultEngineName);
                if (engineFactory != null)
                {
                    return(engineFactory.CreateEngine);
                }
                else
                {
                    throw new ReactEngineNotFoundException(
                              "Could not find a factory that creates an instance of the JavaScript " +
                              "engine with name `" + defaultEngineName + "`.");
                }
            }

            foreach (var engineFactory in jsEngineSwitcher.EngineFactories)
            {
                IJsEngine engine = null;
                try
                {
                    engine = engineFactory.CreateEngine();
                    if (EngineIsUsable(engine, allowMsie))
                    {
                        // Success! Use this one.
                        return(engineFactory.CreateEngine);
                    }
                }
                catch (Exception ex)
                {
                    // This engine threw an exception, try the next one
                    Trace.WriteLine(string.Format("Error initialising {0}: {1}", engineFactory, ex));
                }
                finally
                {
                    if (engine != null)
                    {
                        engine.Dispose();
                    }
                }
            }

            // Epic fail, none of the engines worked. Nothing we can do now.
            // Throw an error relevant to the engine they should be able to use.
#if NET45
            if (JavaScriptEngineUtils.EnvironmentSupportsClearScript())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <V8JsEngine, ClearScriptV8InitialisationException>(
                    ex => new ClearScriptV8InitialisationException(ex)
                    );
            }
#endif
            if (JavaScriptEngineUtils.EnvironmentSupportsVroomJs())
            {
                JavaScriptEngineUtils.EnsureEngineFunctional <VroomJsEngine, VroomJsInitialisationException>(
                    ex => new VroomJsInitialisationException(ex.Message)
                    );
            }

            throw new ReactEngineNotFoundException();
        }
Ejemplo n.º 25
0
 public void Dispose()
 {
     javascriptEngine?.Dispose();
 }
Ejemplo n.º 26
0
		/// <summary>
		/// Disposes the specified engine.
		/// </summary>
		/// <param name="engine">Engine to dispose</param>
		/// <param name="repopulateEngines">
		/// If <c>true</c>, a new engine will be created to replace the disposed engine
		/// </param>
		public virtual void DisposeEngine(IJsEngine engine, bool repopulateEngines = true)
		{
			engine.Dispose();
			_metadata.Remove(engine);
			Interlocked.Decrement(ref _engineCount);

			if (repopulateEngines)
			{
				// Ensure we still have at least the minimum number of engines.
				PopulateEngines();
			}
		}