Beispiel #1
0
        public void ReplaceParentChangesChildrenIfParentDifferentTypes()
        {
            // Arrange
            var bnd = new Binder();

            bnd.PropertyScanner.Add(new ReflectionPropertyScanner());
            bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
            var view = new MockView {
                Control = new MockControl("ViewOrig")
            };
            var vm = new MockViewModel2 {
                Control = new MockControlViewModel("VmOrig")
            };

            _bindings = bnd.Bind(new object[] { vm, view });

            // Act
            view.Control = new MockControl("ViewNew")
            {
                Text = "banaan",
                Size = 11
            };

            // Assert
            Assert.Greater(_bindings.Count(), 0);
            Assert.AreEqual("banaan", vm.Control.Text);
            Assert.AreEqual(11, vm.Control.Size);
        }
Beispiel #2
0
        public void BindDifferentlyDistributedObjectHierarchiesChangeParent()
        {
            // Arrange
            var bnd = new Binder();

            bnd.PropertyScanner.Add(new ReflectionPropertyScanner());
            bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
            var ob1 = new Abcd1();
            var ob2 = new Abcd2();
            var ob3 = new Abcd3();

            _bindings             = bnd.Bind(new object[] { ob1, ob2, ob3 });
            ob2.AaaBee.CeeDee.Eee = "x";

            // Act
            Abcd2.AB oldAaaBee = ob2.AaaBee;
            ob2.AaaBee = new Abcd2.AB
            {
                CeeDee = new Abcd2.CD
                {
                    Eee = "y"
                }
            };


            // Assert
            Assert.Greater(_bindings.Count(), 0);
            Assert.AreEqual("y", ob1.Aaa.Bee.Cee.Dee.Eee);
            Assert.AreEqual("y", ob3.Aaa.BeeCee.Dee.Eee);
            Assert.AreEqual("x", oldAaaBee.CeeDee.Eee);
        }
Beispiel #3
0
        /// <summary>
        /// Returns a <code>SimpleScriptContext</code>.  The <code>SimpleScriptContext</code>:
        /// <br><br>
        /// <ul>
        /// <li>Uses the specified <code>Bindings</code> for its <code>ENGINE_SCOPE</code>
        /// </li>
        /// <li>Uses the <code>Bindings</code> returned by the abstract <code>getGlobalScope</code>
        /// method as its <code>GLOBAL_SCOPE</code>
        /// </li>
        /// <li>Uses the Reader and Writer in the default <code>ScriptContext</code> of this
        /// <code>ScriptEngine</code>
        /// </li>
        /// </ul>
        /// <br><br>
        /// A <code>SimpleScriptContext</code> returned by this method is used to implement eval methods
        /// using the abstract <code>eval(Reader,Bindings)</code> and <code>eval(String,Bindings)</code>
        /// versions.
        /// </summary>
        /// <param name="nn"> Bindings to use for the <code>ENGINE_SCOPE</code> </param>
        /// <returns> The <code>SimpleScriptContext</code> </returns>
        protected internal virtual IScriptContext GetScriptContext(IBindings nn)
        {
            SimpleScriptContext ctxt = new SimpleScriptContext();
            IBindings           gs   = GetBindings(ScriptContext_Fields.GLOBAL_SCOPE);

            if (gs != null)
            {
                ctxt.SetBindings(gs, ScriptContext_Fields.GLOBAL_SCOPE);
            }

            if (nn != null)
            {
                ctxt.SetBindings(nn, ScriptContext_Fields.ENGINE_SCOPE);
            }
            else
            {
                throw new System.NullReferenceException("Engine scope Bindings may not be null.");
            }

            ctxt.SetReader(context.GetReader());
            ctxt.SetWriter(context.GetWriter());
            ctxt.SetErrorWriter(context.GetErrorWriter());

            return(ctxt);
        }
        public void NameBasedBinding()
        {
            var binder = new Binder();

            /* ViewModelClass and ViewClass both have a string property MyProperty,
             * and they both implement INotifyPropertyChanged
             */
            var view = new ViewClass {
                MyProperty = "aaa"
            };
            var viewModel = new ViewModelClass {
                MyProperty = "bbb"
            };

            this._bindings = binder.Bind(viewModel, view);

            //  viewModel.MyProperty is now bound to view.MyProperty.
            //  view.MyProperty will have the value "bbb".

            Assert.AreEqual("bbb", view.MyProperty);

            view.MyProperty = "ccc";      // propagates "ccc" to viewModel.MyProperty

            Assert.AreEqual("ccc", viewModel.MyProperty);

            viewModel.MyProperty = "ddd"; // propagates "ddd" to view.MyProperty

            Assert.AreEqual("ddd", view.MyProperty);
        }
Beispiel #5
0
 public ScriptBindings(IList <IResolver> scriptResolvers, IVariableScope variableScope, IBindings wrappedBindings)
 {
     this.scriptResolvers     = scriptResolvers;
     this.variableScope       = variableScope;
     this.wrappedBindings     = wrappedBindings;
     autoStoreScriptVariables = IsAutoStoreScriptVariablesEnabled();
 }
        /// <summary>
        /// Returns the possible ways that a query term can unify with a program term
        /// </summary>
        public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null)
        {
            var simpleUnifier = new SimpleUnifier();
            var freeVariables = new HashSet<ILiteral>();

            // Run the unifier
            var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings);
            if (queryFreeVars == null) return null;

            simpleUnifier.PrepareToRunProgram();

            var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings);
            if (programFreeVars == null) return null;

            freeVariables.UnionWith(queryFreeVars);

            // Retrieve the unified value for the program
            var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query);

            // If the result was valid, return as the one value from this function
            if (result != null)
            {
                var variableBindings = freeVariables.ToDictionary(variable => variable,
                    variable => simpleUnifier.UnifiedValue(variable));

                return new BasicBinding(result, variableBindings);
            }
            else
            {
                return null;
            }
        }
Beispiel #7
0
        /// <summary>
        /// Compiles a literal for unification using a query unifier
        /// </summary>
        /// <returns>
        /// The list of variables in the literal
        /// </returns>
        public static IEnumerable<ILiteral> Compile(this IQueryUnifier unifier, ILiteral literal, IBindings bindings = null)
        {
            if (unifier == null) throw new ArgumentNullException("unifier");
            if (literal == null) throw new ArgumentNullException("literal");

            // Flatten the literal
            var assignments = literal.Flatten().ToList();

            // Bind the variables in order
            var freeVariables = unifier.Bind(assignments);

            // Rebind the assignments if necessary
            if (bindings != null)
            {
                assignments = assignments.BindVariables(bindings).ToList();
            }

            // Compile the result
            if (!unifier.Compile(assignments))
            {
                return null;
            }

            return freeVariables;
        }
Beispiel #8
0
        public void Activate(IBindings bindings)
        {
            int userInput = 1;

            while (userInput != 0)
            {
                //Print the loaded menu
                Console.Clear();
                Console.WriteLine(menuName);
                Console.WriteLine(menuDescription);
                for (int lineCount = 0; lineCount < menuList.Count; lineCount++)
                {
                    Console.WriteLine("  {0}.  {1}", lineCount + 1, menuList[lineCount]);
                }

                //Ensure input is a valid number.
                while (!int.TryParse(Console.ReadLine(), out userInput) || userInput > menuId.Count)
                {
                    Console.WriteLine(errorList[0]);
                }
                if (userInput > 0)
                {
                    bindings.Call(menuId[userInput - 1]);
                    Console.ReadKey();
                }
            }
        }
        public void BindingAcrossObjectBoundaries()
        {
            var binder = new Binder();

            /* ViewModelClass, ViewClass, and ControlClass all implement interface
             * INotifyPropertyChanged.
             */
            var view = new ViewClass()
            {
                MyControl = new ControlClass {
                    Label = "aaa"
                }
            };
            var viewModel = new ViewModelClass {
                MyControlLabel = "bbb"
            };

            this._bindings = binder.Bind(viewModel, view);

            //  viewModel.MyControlLabel is now bound to view.MyControl.Label.
            //  both will have the value "bbb".
            Assert.AreEqual("bbb", ((ControlClass)view.MyControl).Label);

            ((ControlClass)view.MyControl).Label = "ccc";      // propagates "ccc" to viewModel.MyControlLabel

            Assert.AreEqual("ccc", viewModel.MyControlLabel);

            viewModel.MyControlLabel = "ddd";  // propagates "ddd" to view.MyControl.Label

            Assert.AreEqual("ddd", ((ControlClass)view.MyControl).Label);
        }
Beispiel #10
0
        public void BindObjectsOfDifferentTypesResultsInPropertiesBeingSetOnce()
        {
            // Arrange
            int ob1cnt = 0, ob2cnt = 0;
            var bnd = new Binder();

            bnd.PropertyScanner.Add(new ReflectionPropertyScanner());
            bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
            var ob1 = new NotifyPropertyChangedClass();
            var ob2 = new ClassWithPropertyAndEvents();

            ob1.PropertyChanged += delegate
            {
                ob1cnt++;
            };
            ob2.PropertyChanged += delegate
            {
                ob2cnt++;
            };
            _bindings = bnd.Bind(new object[] { ob1, ob2 });
            ob1cnt    = 0;
            ob2cnt    = 0;

            // Act
            ob2.Property = "a";

            // Assert
            Assert.Greater(_bindings.Count(), 0);
            Assert.AreEqual(1, ob1cnt);
            Assert.AreEqual(1, ob2cnt);
        }
Beispiel #11
0
        /// <summary>
        /// Executes the program stored in the <code>CompiledScript</code> object using
        /// the supplied <code>Bindings</code> of attributes as the <code>ENGINE_SCOPE</code> of the
        /// associated <code>ScriptEngine</code> during script execution.  If bindings is null,
        /// then the effect of calling this method is same as that of eval(getEngine().getContext()).
        /// <para>.
        /// The <code>GLOBAL_SCOPE</code> <code>Bindings</code>, <code>Reader</code> and <code>Writer</code>
        /// associated with the default <code>ScriptContext</code> of the associated <code>ScriptEngine</code> are used.
        ///
        /// </para>
        /// </summary>
        /// <param name="bindings"> The bindings of attributes used for the <code>ENGINE_SCOPE</code>.
        /// </param>
        /// <returns> The return value from the script execution
        /// </returns>
        /// <exception cref="ScriptException"> if an error occurs. </exception>
        public virtual object Eval(IBindings bindings)
        {
            try
            {
                IScriptContext ctxt = GetEngine().GetContext();

                if (bindings != null)
                {
                    SimpleScriptContext tempctxt = new SimpleScriptContext();
                    tempctxt.SetBindings(bindings, ScriptContext_Fields.ENGINE_SCOPE);
                    tempctxt.SetBindings(ctxt.GetBindings(ScriptContext_Fields.GLOBAL_SCOPE), ScriptContext_Fields.GLOBAL_SCOPE);
                    tempctxt.SetWriter(ctxt.GetWriter());
                    tempctxt.SetReader(ctxt.GetReader());
                    tempctxt.SetErrorWriter(ctxt.GetErrorWriter());
                    ctxt = tempctxt;
                }

                return(Eval(ctxt));
            }
            catch (ScriptException ex)
            {
                throw ex;
            }
            catch (System.Exception ex)
            {
                throw new ScriptException(ex);
            }
        }
Beispiel #12
0
        public void BindThreeNotifyPropertyChangedObjects()
        {
            {
                // Arrange
                var bnd = new Binder();
                bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
                var ob1 = new NotifyPropertyChangedClass();
                var ob2 = new NotifyPropertyChangedClass();
                var ob3 = new NotifyPropertyChangedClass();
                _bindings = bnd.Bind(new object[] { ob1, ob2, ob3 });

                // Act
                ob1.Property = "a";

                // Assert
                Assert.Greater(_bindings.Count(), 0);
                Assert.AreEqual("a", ob1.Property);
                Assert.AreEqual("a", ob2.Property);
                Assert.AreEqual("a", ob3.Property);
            }

            {
                // Arrange
                var bnd = new Binder();
                bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
                var ob1 = new NotifyPropertyChangedClass();
                var ob2 = new NotifyPropertyChangedClass();
                var ob3 = new NotifyPropertyChangedClass();
                _bindings = bnd.Bind(new object[] { ob1, ob2, ob3 });

                // Act
                ob2.Property = "a";

                // Assert
                Assert.Greater(_bindings.Count(), 0);
                Assert.AreEqual("a", ob1.Property);
                Assert.AreEqual("a", ob2.Property);
                Assert.AreEqual("a", ob3.Property);
            }

            {
                // Arrange
                var bnd = new Binder();
                bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
                var ob1 = new NotifyPropertyChangedClass();
                var ob2 = new NotifyPropertyChangedClass();
                var ob3 = new NotifyPropertyChangedClass();
                _bindings = bnd.Bind(new object[] { ob1, ob2, ob3 });

                // Act
                ob3.Property = "a";

                // Assert
                Assert.Greater(_bindings.Count(), 0);
                Assert.AreEqual("a", ob1.Property);
                Assert.AreEqual("a", ob2.Property);
                Assert.AreEqual("a", ob3.Property);
            }
        }
Beispiel #13
0
 /// <summary>
 /// Creates a new instance using the specified <code>Bindings</code> as the
 /// <code>ENGINE_SCOPE</code> <code>Bindings</code> in the protected <code>context</code> field.
 /// </summary>
 /// <param name="n"> The specified <code>Bindings</code>. </param>
 /// <exception cref="NullPointerException"> if n is null. </exception>
 public AbstractScriptEngine(IBindings n) : this()
 {
     if (n == null)
     {
         throw new System.NullReferenceException("n is null");
     }
     context.SetBindings(n, ScriptContext_Fields.ENGINE_SCOPE);
 }
 public IBindings GetKeyBindings()
 {
     if (bindings == null)
     {
         bindings = ConfigurationRepository.KeyboardBindings;
     }
     return(bindings);
 }
Beispiel #15
0
        public OptionsProcessor(ILogger <OptionsProcessor> log, IBindings bindings, IFileReader fileReader)
        {
            _log        = log;
            _bindings   = bindings;
            _fileReader = fileReader;

            _cache = new ConcurrentDictionary <string, string>();
        }
Beispiel #16
0
        /// <summary>
        /// Sets the specified value with the specified key in the <code>ENGINE_SCOPE</code>
        /// <code>Bindings</code> of the protected <code>context</code> field.
        /// </summary>
        /// <param name="key"> The specified key. </param>
        /// <param name="value"> The specified value.
        /// </param>
        /// <exception cref="NullPointerException"> if key is null. </exception>
        /// <exception cref="IllegalArgumentException"> if key is empty. </exception>
        public virtual void Put(string key, object value)
        {
            IBindings nn = GetBindings(ScriptContext_Fields.ENGINE_SCOPE);

            if (nn != null)
            {
                nn.Put(key, value);
            }
        }
Beispiel #17
0
        /// <summary>
        /// execute a given script in the environment
        /// </summary>
        /// <param name="script"> the <seealso cref="ExecutableScript"/> to execute </param>
        /// <param name="scope"> the scope in which to execute the script </param>
        /// <returns> the result of the script evaluation </returns>
        public virtual object Execute(ExecutableScript script, IVariableScope scope)
        {
            // get script engine
            IScriptEngine scriptEngine = scriptingEngines.GetScriptEngineForLanguage(script.Language);

            // create bindings
            IBindings bindings = scriptingEngines.CreateBindings(scriptEngine, scope);

            return(Execute(script, scope, bindings, scriptEngine));
        }
Beispiel #18
0
 public SimpleScriptContext()
 {
     engineScope = new SimpleBindings();
     globalScope = null;
     //reader = new StreamReader(); // new InputStreamReader(System.in);
     //writer = new PrintWriter(System.out, true);
     //errorWriter = new PrintWriter(System.err, true);
     reader      = new MemoryStream();
     writer      = new MemoryStream();
     errorWriter = new MemoryStream();
 }
Beispiel #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Emulator"/> class with the specified <see cref="IBindings"/>
        /// instance.
        /// </summary>
        internal Emulator(UnicornArch arch, UnicornMode mode, IBindings bindings)
        {
            _arch      = arch;
            _mode      = mode;
            _registers = new Registers(this);
            _memory    = new Memory(this);
            _hooks     = new Hooks(this);

            Bindings = bindings;
            Bindings.Open(arch, mode, ref _handle);
        }
Beispiel #20
0
        /// <summary>
        /// Gets the value for the specified key in the <code>ENGINE_SCOPE</code> of the
        /// protected <code>context</code> field.
        /// </summary>
        /// <returns> The value for the specified key.
        /// </returns>
        /// <exception cref="NullPointerException"> if key is null. </exception>
        /// <exception cref="IllegalArgumentException"> if key is empty. </exception>
        public virtual object Get(string key)
        {
            IBindings nn = GetBindings(ScriptContext_Fields.ENGINE_SCOPE);

            if (nn != null)
            {
                return(nn.Get(key));
            }

            return(null);
        }
Beispiel #21
0
        public void Activate(IBindings bindings)
        {
            int  choice  = 0;
            bool running = true;

            while (running != false)
            {
                Console.Clear();

                Console.WriteLine(titel + "\n");

                Console.WriteLine(explain + "\n");

                // print alle menuerne
                for (int i = 0; i < menu.GetLength(0); i++)
                {
                    Console.WriteLine((i + 1) + ". " + menu[i, 0] + "\n");
                }

                string input = Console.ReadLine();


                if (input.ToLower() == "0")
                {
                    running = false;
                }
                else if (int.TryParse(input, out choice))
                {
                    choice -= 1;
                    //kald bindings klassen
                    if (choice < menu.GetLength(0))
                    {
                        bindings.Call(menu[choice, 1]);
                    }
                    else
                    {
                        Console.WriteLine("The number you put in is too high, choose one from the description");
                    }
                }

                else if (input.Length <= 0)
                {
                    Console.WriteLine("Please enter a number");
                }
                else
                {
                    Console.WriteLine("that is not a number, please enter a number ");
                }

                Console.ReadLine();
            }
        }
        public IBindings CreateBindings(IVariableScope variableScope, IBindings engineBindings)
        {
            List <IResolver> scriptResolvers = new List <IResolver>();

            foreach (IResolverFactory scriptResolverFactory in resolverFactories)
            {
                IResolver resolver = scriptResolverFactory.CreateResolver(variableScope);
                if (resolver != null)
                {
                    scriptResolvers.Add(resolver);
                }
            }
            return(new ScriptBindings(scriptResolvers, variableScope, engineBindings));
        }
Beispiel #23
0
        public virtual object Execute(ExecutableScript script, IVariableScope scope, IBindings bindings, IScriptEngine scriptEngine)
        {
            string scriptLanguage = script.Language;
            // first, evaluate the env scripts (if any)
            IList <ExecutableScript> envScripts = getEnvScripts(scriptLanguage);

            foreach (ExecutableScript envScript in envScripts)
            {
                envScript.Execute(scriptEngine, scope, bindings);
            }

            // next evaluate the actual script
            return(script.Execute(scriptEngine, scope, bindings));
        }
Beispiel #24
0
 /// <summary>
 /// Sets the <code>Bindings</code> with the corresponding scope value in the
 /// <code>context</code> field.
 /// </summary>
 /// <param name="bindings"> The specified <code>Bindings</code>. </param>
 /// <param name="scope"> The specified scope.
 /// </param>
 /// <exception cref="IllegalArgumentException"> if the value of scope is
 /// invalid for the type the <code>context</code> field. </exception>
 /// <exception cref="NullPointerException"> if the bindings is null and the scope is
 /// <code>ScriptContext.ENGINE_SCOPE</code> </exception>
 public virtual void SetBindings(IBindings bindings, int scope)
 {
     if (scope == ScriptContext_Fields.GLOBAL_SCOPE)
     {
         context.SetBindings(bindings, ScriptContext_Fields.GLOBAL_SCOPE);
     }
     else if (scope == ScriptContext_Fields.ENGINE_SCOPE)
     {
         context.SetBindings(bindings, ScriptContext_Fields.ENGINE_SCOPE);
     }
     else
     {
         throw new System.ArgumentException("Invalid scope value.");
     }
 }
 protected virtual object EvaluateScript(IScriptEngine engine, IBindings bindings)
 {
     try
     {
         log.debugEvaluatingNonCompiledScript(scriptSource);
         return(engine.Eval(scriptSource, bindings));
     }
     catch (ScriptException e)
     {
         if (e.InnerException is BpmnError)
         {
             throw (BpmnError)e.InnerException;
         }
         throw new ScriptEvaluationException("Unable to evaluate script: " + e.Message, e);
     }
 }
Beispiel #26
0
        /// <summary>
        /// Substitutes any variable assignments with their bindings
        /// </summary>
        public static IEnumerable<IAssignmentLiteral> BindVariables(this IEnumerable<IAssignmentLiteral> withVariables, IBindings bindings)
        {
            var result = new List<IAssignmentLiteral>();
            var extras = new List<IAssignmentLiteral>();

            // Run through the assignments
            foreach (var assignment in withVariables)
            {
                if (assignment.Value.UnificationKey == null)
                {
                    // Value is a variable (unifies with everything)
                    var boundTo = bindings.GetValueForVariable(assignment.Value);
                    if (boundTo != null)
                    {
                        // Flatten the bound value
                        var flattened = boundTo.Flatten().ToArray();

                        // Assign the target value of the bound value to the original value location
                        // Ie, here we have Xn = V and the first value of flattened describes the value of V
                        // in the form Xm = a(...)
                        // Substitute Xn = a(...) in the assignment list
                        // Value of V after resolution can be updated by reading Xn after resolution
                        var first = (IAssignmentLiteral) flattened[0].RebuildWithParameters(new[] { assignment.Variable, flattened[0].Value });
                        result.Add(first);

                        // Add in any extra variables generated by flattening
                        extras.AddRange(flattened.Skip(1));
                    }
                    else
                    {
                        // Variable is unbound
                        result.Add(assignment);
                    }
                }
                else
                {
                    result.Add(assignment);
                }
            }

            // Remove any extra items to generate the final result
            var eliminator = new AssignmentEliminator(result.Concat(extras));
            eliminator.Eliminate();
            return eliminator.Assignments;
        }
Beispiel #27
0
        public void BindReflectedObjects()
        {
            // Arrange
            var bnd = new Binder();

            bnd.PropertyScanner.Add(new ReflectionPropertyScanner());
            bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
            var ob1 = new ClassWithPropertyAndEvents();
            var ob2 = new ClassWithPropertyAndEvents();

            _bindings = bnd.Bind(new object[] { ob1, ob2 });

            // Act
            ob2.Property = "a";

            // Assert
            Assert.Greater(_bindings.Count(), 0);
            Assert.AreEqual("a", ob1.Property);
        }
        public void Tldr()
        {
            var viewModel = new ViewModelClass();
            var view      = new ViewClass();

            /* Create binder */
            var binder = new Binder();

            /* Establish bindings.
             * Store the bindings in this._bindings to make sure it is not garbage collected.
             * This is typically done when the view appears (*not* when it is created!)
             */
            this._bindings = binder.Bind(viewModel, view);

            /* Destroy bindings.
             * Typically when the view disappears.
             */
            this._bindings.Dispose();
            this._bindings = null;
        }
Beispiel #29
0
        /// <summary>
        /// Sets a <code>Bindings</code> of attributes for the given scope.  If the value
        /// of scope is <code>ENGINE_SCOPE</code> the given <code>Bindings</code> replaces the
        /// <code>engineScope</code> field.  If the value
        /// of scope is <code>GLOBAL_SCOPE</code> the given <code>Bindings</code> replaces the
        /// <code>globalScope</code> field.
        /// </summary>
        /// <param name="bindings"> The <code>Bindings</code> of attributes to set. </param>
        /// <param name="scope"> The value of the scope in which the attributes are set.
        /// </param>
        /// <exception cref="IllegalArgumentException"> if scope is invalid. </exception>
        /// <exception cref="NullPointerException"> if the value of scope is <code>ENGINE_SCOPE</code> and
        /// the specified <code>Bindings</code> is null. </exception>
        public virtual void SetBindings(IBindings bindings, int scope)
        {
            switch (scope)
            {
            case ScriptContext_Fields.ENGINE_SCOPE:
                if (bindings == null)
                {
                    throw new System.NullReferenceException("Engine scope cannot be null.");
                }
                engineScope = bindings;
                break;

            case ScriptContext_Fields.GLOBAL_SCOPE:
                globalScope = bindings;
                break;

            default:
                throw new System.ArgumentException("Invalid scope value.");
            }
        }
Beispiel #30
0
        protected internal virtual object EvaluateScriptExpression(string expressionLanguage,
                                                                   IVariableContext variableContext, string expressionText,
                                                                   ICachedCompiledScriptSupport cachedCompiledScriptSupport)
        {
            IScriptEngine scriptEngine = GetScriptEngineForName(expressionLanguage);
            // wrap script engine bindings + variable context and pass enhanced
            // bindings to the script engine.
            IBindings bindings = VariableContextScriptBindings.Wrap(scriptEngine.CreateBindings(), variableContext);

            bindings.Put("variableContext", variableContext);

            try
            {
                if (scriptEngine is ICompilable)
                {
                    CompiledScript compiledScript = cachedCompiledScriptSupport.GetCachedCompiledScript();
                    if (compiledScript == null)
                    {
                        lock (cachedCompiledScriptSupport)
                        {
                            compiledScript = cachedCompiledScriptSupport.GetCachedCompiledScript();

                            if (compiledScript == null)
                            {
                                ICompilable compilableScriptEngine = (ICompilable)scriptEngine;
                                compiledScript = compilableScriptEngine.Compile(expressionText);

                                cachedCompiledScriptSupport.CacheCompiledScript(compiledScript);
                            }
                        }
                    }

                    return(compiledScript.Eval(bindings));
                }
                return(scriptEngine.Eval(expressionText, bindings));
            }
            catch (ScriptException e)
            {
                throw Log.unableToEvaluateExpression(expressionText, scriptEngine.GetFactory().LanguageName, e);
            }
        }
        public void BindSpecialPropertyOnExtensionsWithNotifyPropertyChanged()
        {
            // Arrange
            var bnd = new Binder();
            var customExtensionsScanner = new TypeExtensionsScanner(bnd.PropertyScanner);

            customExtensionsScanner.AdapterRegistry.Register <MockViewExtensions>();
            bnd.PropertyScanner.Add(new NotifyPropertyChangedPropertyScanner());
            bnd.PropertyScanner.Add(customExtensionsScanner);
            var ob1 = new MockView();
            var ob2 = new MockViewModel();

            _bindings = bnd.Bind(new object[] { ob1, ob2 });

            // Act
            ob2.SpecialProperty = 666;

            // Assert
            Assert.Greater(_bindings.Count(), 0);
            Assert.AreEqual(666, ob1.GetSpecialProperty());
        }
Beispiel #32
0
        /// <summary>
        /// Returns the possible ways that a query term can unify with a program term
        /// </summary>
        public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null)
        {
            var simpleUnifier = new SimpleUnifier();
            var freeVariables = new HashSet <ILiteral>();

            // Run the unifier
            var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings);

            if (queryFreeVars == null)
            {
                return(null);
            }

            simpleUnifier.PrepareToRunProgram();

            var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings);

            if (programFreeVars == null)
            {
                return(null);
            }

            freeVariables.UnionWith(queryFreeVars);

            // Retrieve the unified value for the program
            var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query);

            // If the result was valid, return as the one value from this function
            if (result != null)
            {
                var variableBindings = freeVariables.ToDictionary(variable => variable,
                                                                  variable => simpleUnifier.UnifiedValue(variable));

                return(new BasicBinding(result, variableBindings));
            }
            else
            {
                return(null);
            }
        }
        public void DynamicRebinding()
        {
            var binder = new Binder();

            /* ViewModelClass, ViewClass, ControlModelClass, ControlClass and TextControlClass all
             * implement interface INotifyPropertyChanged.
             */
            var view = new ViewClass()
            {
                MyControl = new ControlClass {
                    Label = "aaa"
                }
            };
            var viewModel = new ViewModelClass()
            {
                MyControl = new ControlModelClass {
                    Label = "bbb", Text = "ccc"
                }
            };

            this._bindings = binder.Bind(viewModel, view);

            //  viewModel.MyControl.Label is now bound to view.MyControl.Label.
            //  Both will have the value "bbb".
            //  viewModel.MyControl.Text is not bound to anything and will have its original value ("ccc")

            Assert.AreEqual("bbb", ((ControlClass)view.MyControl).Label);
            Assert.AreEqual("ccc", viewModel.MyControl.Text);

            view.MyControl = new TextControlClass {
                Text = "ddd"
            };

            // viewModel.MyControl.Text gets *rebound* to view.MyControl.Text.
            // Both will now have value "ddd".
            // viewModel.MyControl.Label will still have value "bbb".

            Assert.AreEqual("bbb", viewModel.MyControl.Label);
            Assert.AreEqual("ddd", viewModel.MyControl.Text);
        }
Beispiel #34
0
 public BasicQueryResult(bool succeeded, IBindings bindings)
 {
     _success = succeeded;
     _bindings = bindings;
 }