Exemplo n.º 1
0
        private void DoRebind()
        {
            // removing possible previous bindings for formatting validation results as colors (would not be needed if elements were always IValidatingObject instances)
            if (formatColorBinding != null)
            {
                tbIntPropList.DataBindings.Remove(intPropColorBinding);
                tbStringPropList.DataBindings.Remove(stringPropColorBinding);
                tbIntPropList.BackColor       = SystemColors.Window;
                tbStringPropList.BackColor    = SystemColors.Window;
                tbIntPropCurrent.BackColor    = SystemColors.Window;
                tbStringPropCurrent.BackColor = SystemColors.Window;
                commandBindings.Remove(formatColorBinding);
                formatColorBinding = null;
            }

            // the actual rebind
            IList testList = viewModel.TestList;

            listBindingSource.SuspendBinding();
            listBindingSource.DataSource = testList;
            listBindingSource.ResumeBinding();
            errorProvider.UpdateBinding();

            // bindings for TextBox.BackColor (could be in the constructor if elements were always IValidatingObject instances but WinForms is not tolerant for invalid property names)
            if (testList.Cast <ITestObject>().FirstOrDefault() is IValidatingObject)
            {
                intPropColorBinding    = new Binding(nameof(TextBox.BackColor), listBindingSource, nameof(IValidatingObject.ValidationResults), true, DataSourceUpdateMode.Never);
                stringPropColorBinding = new Binding(nameof(TextBox.BackColor), listBindingSource, nameof(IValidatingObject.ValidationResults), true, DataSourceUpdateMode.Never);
                formatColorBinding     = commandBindings.Add <ConvertEventArgs>(OnFormatColor)
                                         .AddSource(intPropColorBinding, nameof(Binding.Format))
                                         .AddSource(stringPropColorBinding, nameof(Binding.Format));
                tbIntPropList.DataBindings.Add(intPropColorBinding);
                tbStringPropList.DataBindings.Add(stringPropColorBinding);
            }
        }
Exemplo n.º 2
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, RenderContext context, DotvvmControl control,
                                                          bool useWindowSetTimeout = false, bool?returnValue = false, bool isOnChange = false)
        {
            var uniqueControlId = "";

            if (expression is ControlCommandBindingExpression)
            {
                var target = (DotvvmControl)control.GetClosestControlBindingTarget();
                target.EnsureControlHasId();
                uniqueControlId = target.ID;
            }

            var arguments = new List <string>()
            {
                "'" + context.CurrentPageArea + "'",
                "this",
                "[" + String.Join(", ", GetContextPath(control).Reverse().Select(p => '"' + p + '"')) + "]",
                "'" + uniqueControlId + "'",
                useWindowSetTimeout ? "true" : "false",
                JsonConvert.SerializeObject(GetValidationTargetExpression(control)),
                "null",
                GetPostBackHandlersScript(control, propertyName)
            };

            // return the script
            var condition       = isOnChange ? "if (!dotvvm.isViewModelUpdating) " : null;
            var returnStatement = returnValue != null?string.Format(";return {0};", returnValue.ToString().ToLower()) : "";

            // call the function returned from binding js with runtime arguments
            var postBackCall = String.Format("{0}({1})", expression.GetCommandJavascript(), String.Join(", ", arguments));

            return(condition + postBackCall + returnStatement);
        }
Exemplo n.º 3
0
 public virtual void Stop(object key)
 {
     if (key is ICommand && activeSequences.ContainsKey(key as ICommand))
     {
         removeSequence(key as ICommand);
     }
     else
     {
         ICommandBinding binding = GetBinding(key) as ICommandBinding;
         if (binding != null)
         {
             if (activeSequences.ContainsValue(binding))
             {
                 foreach (KeyValuePair <ICommand, ICommandBinding> sequence in activeSequences)
                 {
                     if (sequence.Value == binding)
                     {
                         ICommand command = sequence.Key;
                         removeSequence(command);
                     }
                 }
             }
         }
     }
 }
Exemplo n.º 4
0
        virtual public void ReactTo(object trigger, object data)
        {
            if (data is IPoolable)
            {
                (data as IPoolable).Retain();
            }
            ICommandBinding binding = GetBinding(trigger) as ICommandBinding;

            if (binding != null)
            {
                if (binding.isSequence)
                {
                    next(binding, data, 0);
                }
                else
                {
                    object[] values = binding.value as object[];
                    int      aa     = values.Length + 1;
                    for (int a = 0; a < aa; a++)
                    {
                        next(binding, data, a);
                    }
                }
            }
        }
Exemplo n.º 5
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, PostbackScriptOptions options)
        {
            object uniqueControlId = null;

            if (expression is ControlCommandBindingExpression)
            {
                var target = (DotvvmControl)control.GetClosestControlBindingTarget();
                uniqueControlId = target.GetDotvvmUniqueId();
            }

            var arguments = new List <string>()
            {
                "'root'",
                options.ElementAccessor,
                "[" + String.Join(", ", GetContextPath(control).Reverse().Select(p => '"' + p + '"')) + "]",
                (uniqueControlId is IValueBinding ? "{ expr: " + JsonConvert.ToString(((IValueBinding)uniqueControlId).GetKnockoutBindingExpression(), '\'', StringEscapeHandling.Default) + "}" : "'" + (string)uniqueControlId + "'"),
                options.UseWindowSetTimeout ? "true" : "false",
                JsonConvert.SerializeObject(GetValidationTargetExpression(control)),
                "null",
                GetPostBackHandlersScript(control, propertyName)
            };

            // return the script
            var condition       = options.IsOnChange ? "if (!dotvvm.isViewModelUpdating) " : null;
            var returnStatement = options.ReturnValue != null ? $";return {options.ReturnValue.ToString().ToLower()};" : "";

            // call the function returned from binding js with runtime arguments
            var postBackCall = $"{expression.GetCommandJavascript()}({String.Join(", ", arguments)})";

            return(condition + postBackCall + returnStatement);
        }
Exemplo n.º 6
0
        public void TestRuntimeSequenceCommandBinding()
        {
            string jsonInjectorString = "[{\"Bind\":\"strange.unittests.ISimpleInterface\",\"To\":\"strange.unittests.SimpleInterfaceImplementer\", \"Options\":\"ToSingleton\"}]";

            injectionBinder.ConsumeBindings(jsonInjectorString);

            string jsonCommandString = "[{\"Bind\":\"TestEvent\",\"To\":[\"strange.unittests.CommandWithInjection\",\"strange.unittests.CommandWithExecute\",\"strange.unittests.CommandThatThrows\"],\"Options\":\"InSequence\"}]";

            commandBinder.ConsumeBindings(jsonCommandString);

            ICommandBinding binding = commandBinder.GetBinding("TestEvent") as ICommandBinding;

            Assert.IsTrue(binding.isSequence);

            TestDelegate testDelegate = delegate
            {
                commandBinder.ReactTo("TestEvent");
            };

            //That the exception is thrown demonstrates that the last command ran
            NotImplementedException ex = Assert.Throws <NotImplementedException> (testDelegate);

            Assert.NotNull(ex);

            ISimpleInterface instance = injectionBinder.GetInstance <ISimpleInterface>() as ISimpleInterface;

            Assert.AreEqual(100, instance.intValue);
        }
Exemplo n.º 7
0
    /// <summary>
    /// Working multy layer StrangeIOC binding
    /// </summary>
    /// <typeparam name="Signal"></typeparam>
    /// <typeparam name="Command"></typeparam>
    /// <param name="once"></param>
    /// <returns></returns>
    public virtual ICommandBinding BindCommand <Signal, Command>(bool once = false, bool replace = false)
    {
        ICommandBinding binding = null;

        try
        {
            binding = commandBinder.GetBinding <Signal>();
        }
        catch (InjectionException)
        {
            //Workaround
            //Couldn't find Binding, strange throws error. why? I don't know
            //No "ContainsBinding" method yet
        }

        if (binding != null && replace)
        {
            commandBinder.Unbind(injectionBinder.GetInstance <Signal>());
            binding = null;
        }

        if (binding == null)
        {
            binding = commandBinder.Bind <Signal>().To <Command>();
        }
        else
        {
            binding = binding.To <Command>();
        }
        if (once)
        {
            binding = binding.Once();
        }
        return(binding);
    }
Exemplo n.º 8
0
 void DefaultUpdateTargetAction(ICommandBinding binding)
 {
     if (binding.Trigger != null)
     {
         var parameter = binding.Parameter;
         binding.Trigger.SetEnabled(binding.Command.CanExecute(parameter));
     }
 }
Exemplo n.º 9
0
 void DefaultUpdateTargetAction(ICommandBinding binding)
 {
     if (binding.Target != null)
     {
         var parameter = GetParameter(binding.Target.Owner, EventArgs.Empty);
         binding.Target.SetEnabled(binding.Source.CanExecute(parameter));
     }
 }
Exemplo n.º 10
0
        virtual protected ICommand invokeCommand(Type cmd, ICommandBinding binding, object data, int depth)
        {
            ICommand command = createCommand(cmd, data);

            command.sequenceId = depth;
            trackCommand(command, binding);
            executeCommand(command);
            return(command);
        }
Exemplo n.º 11
0
        public static string GenerateClientPostBackExpression(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
        {
            var target          = (DotvvmControl?)control.GetClosestControlBindingTarget();
            var uniqueControlId = target?.GetDotvvmUniqueId();

            string getContextPath(DotvvmBindableObject?current)
            {
                var result = new List <string>();

                while (current != null)
                {
                    var pathFragment = current.GetDataContextPathFragment();
                    if (pathFragment != null)
                    {
                        result.Add(JsonConvert.ToString(pathFragment));
                    }
                    current = current.Parent;
                }
                result.Reverse();
                return("[" + string.Join(",", result) + "]");
            }

            string getHandlerScript()
            {
                if (!options.AllowPostbackHandlers)
                {
                    return("[]");
                }
                // turn validation off for static commands
                var validationPath = expression is StaticCommandBindingExpression ? null : GetValidationTargetExpression(control);

                return(GetPostBackHandlersScript(control, propertyName,
                                                 // validation handler
                                                 validationPath == null ? null :
                                                 validationPath == RootValidationTargetExpression ? "\"validate-root\"" :
                                                 validationPath == "$data" ? "\"validate-this\"" :
                                                 $"[\"validate\", {{path:{JsonConvert.ToString(validationPath)}}}]",

                                                 // use window.setTimeout
                                                 options.UseWindowSetTimeout ? "\"timeout\"" : null,

                                                 options.IsOnChange ? "\"suppressOnUpdating\"" : null,

                                                 GenerateConcurrencyModeHandler(propertyName, control)
                                                 ));
            }

            string?generatedPostbackHandlers = null;

            var adjustedExpression = expression.GetParametrizedCommandJavascript(control);
            // when the expression changes the dataContext, we need to override the default knockout context fo the command binding.
            var knockoutContext = options.KoContext ?? (
                // adjustedExpression != expression.CommandJavascript ?
                new CodeParameterAssignment(new ParametrizedCode.Builder {
                "ko.contextFor(", options.ElementAccessor.Code !, ")"
            }.Build(OperatorPrecedence.Max))
Exemplo n.º 12
0
            private void InitEnabledSync()
            {
                if (commandState == null || !(source is UIElement element))
                {
                    return;
                }

                // Creating a CommandState.Enabled -> UIElement.IsEnabled binding
                syncEnabledBinding = commandState.CreatePropertyBinding(nameof(commandState.Enabled), nameof(element.IsEnabled), element);
            }
        /// <summary>Unbind by Signal Type</summary>
        /// <exception cref="InjectionException">If there is no binding for this type.</exception>
        public override void Unbind <T>()
        {
            ICommandBinding binding = (ICommandBinding)injectionBinder.GetBinding(typeof(T));

            if (binding != null)
            {
                T signal = (T)injectionBinder.GetInstance(typeof(T));
                Unbind(signal, null);
            }
        }
Exemplo n.º 14
0
    public virtual ICommandBinding BindCommand <Command>(object key, bool once = false)
    {
        ICommandBinding binding = commandBinder.Bind(key).To <Command>();

        if (once)
        {
            binding = binding.Once();
        }
        return(binding);
    }
        protected override ICommand invokeCommand(Type cmd, ICommandBinding binding, object data, int depth)
        {
            IBaseSignal signal  = (IBaseSignal)binding.key;
            ICommand    command = createCommandForSignal(cmd, data, signal.GetTypes());          //Special signal-only command creation

            command.sequenceId = depth;
            trackCommand(command, binding);
            executeCommand(command);
            return(command);
        }
Exemplo n.º 16
0
        public static ICommandBinding BindCommand <T, TCommand> (object name = null)
        {
            ICommandBinding binding = Context.commandBinder.Bind <T> ().To <TCommand> ();

            if (name != null)
            {
                binding.ToName(name);
            }
            return(binding);
        }
Exemplo n.º 17
0
 private void trackCommand(ICommand command, ICommandBinding binding)
 {
     if (binding.isSequence)
     {
         activeSequences [command] = binding;
     }
     else
     {
         activeCommands.Add(command);
     }
 }
Exemplo n.º 18
0
    public static ICommandBinding SafeBind <T>(this ICommandBinder _this)
    {
        ICommandBinding binding = _this.GetBinding <T>();

        if (binding != null)
        {
            return(binding);
        }

        return(_this.Bind <T>());
    }
Exemplo n.º 19
0
 protected void trackCommand(ICommand command, ICommandBinding binding)
 {
     if (binding.isSequence)
     {
         activeSequences.Add(command, binding);
     }
     else
     {
         activeCommands.Add(command);
     }
 }
Exemplo n.º 20
0
        virtual protected void invokeCommand(Type cmd, ICommandBinding binding, object data, int depth)
        {
            ICommand command = createCommand(cmd, data);

            trackCommand(command);
            executeCommand(command);
            if (binding.isOneOff)
            {
                Unbind(binding);
            }
            ReleaseCommand(command);
        }
 public static DotvvmControl GetContents(
     [DefaultValue(null)] ValueOrBinding <string> text,
     [DefaultValue(null)] ITemplate contentTemplate,
     ICommandBinding click,
     [DefaultValue(ButtonAppearance.Neutral)] ButtonAppearance appearance
     )
 {
     return(new HtmlGenericControl("fluent-button")
            .WithAttribute("appearance", appearance.ToString().ToLower())
            .WithProperty(Events.ClickProperty, click)
            .WithInnerTextOrContent(text, contentTemplate));
 }
Exemplo n.º 22
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
        {
            var expr = GenerateClientPostBackExpression(propertyName, expression, control, options);

            if (options.ReturnValue == false)
            {
                return(expr + ";event.stopPropagation();return false;");
            }
            else
            {
                return(expr);
            }
        }
Exemplo n.º 23
0
        public static string GenerateClientPostBackExpression(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
        {
            var target          = (DotvvmControl)control.GetClosestControlBindingTarget();
            var uniqueControlId = target?.GetDotvvmUniqueId();

            string getHandlerScript()
            {
                // turn validation off for static commands
                var validationPath = expression is StaticCommandBindingExpression ? null : GetValidationTargetExpression(control);

                return(GetPostBackHandlersScript(control, propertyName,
                                                 // validation handler
                                                 validationPath == null ? null :
                                                 validationPath == RootValidationTargetExpression ? "\"validate-root\"" :
                                                 validationPath == "$data" ? "\"validate-this\"" :
                                                 $"[\"validate\", {{path:{JsonConvert.ToString(validationPath)}}}]",

                                                 // use window.setTimeout
                                                 options.UseWindowSetTimeout ? "\"timeout\"" : null,

                                                 options.IsOnChange ? "\"suppressOnUpdating\"" : null,

                                                 GenerateConcurrencyModeHandler(control)
                                                 ));
            }

            string generatedPostbackHandlers = null;

            var call = expression.GetParametrizedCommandJavascript(control).ToString(p =>
                                                                                     p == CommandBindingExpression.ViewModelNameParameter ? new CodeParameterAssignment("\"root\"", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.SenderElementParameter ? options.ElementAccessor :
                                                                                     p == CommandBindingExpression.CurrentPathParameter ? new CodeParameterAssignment(
                                                                                         "[" + String.Join(", ", GetContextPath(control).Reverse().Select(JavascriptCompilationHelper.CompileConstant)) + "]",
                                                                                         OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.ControlUniqueIdParameter ? new CodeParameterAssignment(
                                                                                         (uniqueControlId is IValueBinding ? "{ expr: " + JsonConvert.ToString(((IValueBinding)uniqueControlId).GetKnockoutBindingExpression(control)) + "}" : '"' + (string)uniqueControlId + '"'), OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.OptionalKnockoutContextParameter ? options.KoContext ?? new CodeParameterAssignment("null", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.CommandArgumentsParameter ? options.CommandArgs ?? new CodeParameterAssignment("undefined", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.PostbackHandlersParameter ? new CodeParameterAssignment(generatedPostbackHandlers ?? (generatedPostbackHandlers = getHandlerScript()), OperatorPrecedence.Max) :
                                                                                     default(CodeParameterAssignment)
                                                                                     );

            if (generatedPostbackHandlers == null)
            {
                return($"dotvvm.applyPostbackHandlers(function(){{return {call}}}.bind(this),{options.ElementAccessor.Code.ToString(e => default(CodeParameterAssignment))},{getHandlerScript()})");
            }
            else
            {
                return(call);
            }
        }
Exemplo n.º 24
0
        private void UpdateCurrentView()
        {
            // We remove the earlier binding if any, which releases it subscription automatically.
            if (currentItemChangedBinding != null)
            {
                commandBindings.Remove(currentItemChangedBinding);
            }

            currentView = CollectionViewSource.GetDefaultView(viewModel.TestList);

            // currentView.CurrentChanged -> OnTestListCurrentChangedCommand
            currentItemChangedBinding = commandBindings.Add <EventArgs>(OnTestListCurrentChangedCommand)
                                        .AddSource(currentView, nameof(currentView.CurrentChanged));
        }
Exemplo n.º 25
0
        virtual public void ReactTo(object trigger, object data)
        {
            ICommandBinding binding = GetBinding(trigger) as ICommandBinding;

            if (binding != null)
            {
                object[] values = binding.value as object[];
                int      aa     = values.Length;
                for (int a = 0; a < aa; a++)
                {
                    Type cmd = values [a] as Type;
                    invokeCommand(cmd, binding, data, 0);
                }
            }
        }
Exemplo n.º 26
0
            /// <summary>
            /// Creates a new instance of EventAdapter class.
            /// </summary>
            /// <param name="commandName">The unique command name to create an event adapter for.</param>
            public EventAdapter(string commandName)
            {
                /* get presentation service */
                IPresentationService presentation = Engine.GetService(typeof(IPresentationService)) as IPresentationService;

                if (presentation != null)
                {
                    this.binding = presentation.CreateBinding(commandName);

                    if (this.binding != null)
                    {
                        /* attach to binding */
                        this.binding.Executed += new EventHandler<EventArgs<ICommand>>(OnExecuted);
                    }
                }
            }
Exemplo n.º 27
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, PostbackScriptOptions options)
        {
            object uniqueControlId = null;
            var    target          = (DotvvmControl)control.GetClosestControlBindingTarget();

            uniqueControlId = target?.GetDotvvmUniqueId();

            var arguments = new List <string>()
            {
                "'root'",
                options.ElementAccessor,
                "[" + string.Join(", ", GetContextPath(control).Reverse().Select(p => '"' + p + '"')) + "]",
                (uniqueControlId is IValueBinding ? "{ expr: " + JsonConvert.ToString(((IValueBinding)uniqueControlId).GetKnockoutBindingExpression(), '\'', StringEscapeHandling.Default) + "}" : "'" + (string)uniqueControlId + "'"),
                options.UseWindowSetTimeout ? "true" : "false",
                JsonConvert.SerializeObject(GetValidationTargetExpression(control)),
                "null",
                GetPostBackHandlersScript(control, propertyName)
            };

            // return the script
            var returnStatement = options.ReturnValue != null ? $";return {options.ReturnValue.ToString().ToLower()};" : "";

            if (expression is StaticCommandBindingExpression)
            {
                if (arguments.Last() != "null" && arguments.Last() != "[]")
                {
                    throw new NotSupportedException($"PostBack.Handlers are not supported for staticCommand binding");
                }
                // static command only requires the first argument
                arguments.RemoveRange(1, arguments.Count - 1);
            }

            // call the function returned from binding js with runtime arguments
            var postBackCall = $"{expression.GetCommandJavascript()}({string.Join(", ", arguments)})";

            if (options.UseWindowSetTimeout && expression is StaticCommandBindingExpression)
            {
                postBackCall = "setTimeout(function(){" + postBackCall + "}.bind(this),0)";
            }

            if (options.IsOnChange)
            {
                postBackCall = $"if(!dotvvm.isViewModelUpdating){{{postBackCall}}}";
            }

            return(postBackCall + returnStatement);
        }
Exemplo n.º 28
0
 private void next(ICommandBinding binding, object data, int depth)
 {
     object[] values = binding.value as object[];
     if (depth < values.Length)
     {
         Type     cmd     = values [depth] as Type;
         ICommand command = invokeCommand(cmd, binding, data, depth);
         ReleaseCommand(command);
     }
     else
     {
         if (binding.isOneOff)
         {
             Unbind(binding);
         }
     }
 }
Exemplo n.º 29
0
 public void ReleaseCommand(ICommand command)
 {
     if (command.retain == false)
     {
         if (activeCommands.Contains(command))
         {
             activeCommands.Remove(command);
         }
         else if (activeSequences.ContainsKey(command))
         {
             ICommandBinding binding = activeSequences [command];
             object          data    = command.data;
             activeSequences.Remove(command);
             next(binding, data, command.sequenceId + 1);
         }
     }
 }
Exemplo n.º 30
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmBindableObject control, PostbackScriptOptions options)
        {
            var target          = (DotvvmControl)control.GetClosestControlBindingTarget();
            var uniqueControlId = target?.GetDotvvmUniqueId();

            // return the script
            string returnStatement;

            if (options.ReturnValue == false)
            {
                returnStatement = ";event.stopPropagation();return false;";
            }
            else
            {
                returnStatement = "";
            }

            string generatedPostbackHanlders = null;

            var call = expression.GetParametrizedCommandJavascript(control).ToString(p =>
                                                                                     p == CommandBindingExpression.ViewModelNameParameter ? new CodeParameterAssignment("'root'", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.SenderElementParameter ? options.ElementAccessor :
                                                                                     p == CommandBindingExpression.CurrentPathParameter ? new CodeParameterAssignment(
                                                                                         "[" + String.Join(", ", GetContextPath(control).Reverse().Select(JavascriptCompilationHelper.CompileConstant)) + "]",
                                                                                         OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.ControlUniqueIdParameter ? new CodeParameterAssignment(
                                                                                         (uniqueControlId is IValueBinding ? "{ expr: " + JsonConvert.ToString(((IValueBinding)uniqueControlId).GetKnockoutBindingExpression(control), '\'', StringEscapeHandling.Default) + "}" : "'" + (string)uniqueControlId + "'"), OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.UseObjectSetTimeoutParameter ? new CodeParameterAssignment(options.UseWindowSetTimeout ? "true" : "false", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.ValidationPathParameter ? CodeParameterAssignment.FromExpression(new JsLiteral(GetValidationTargetExpression(control))) :
                                                                                     p == CommandBindingExpression.OptionalKnockoutContextParameter ? options.KoContext ?? new CodeParameterAssignment("null", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.CommandArgumentsParameter ? options.CommandArgs ?? new CodeParameterAssignment("undefined", OperatorPrecedence.Max) :
                                                                                     p == CommandBindingExpression.PostbackHandlersParameter ? new CodeParameterAssignment(generatedPostbackHanlders ?? (generatedPostbackHanlders = GetPostBackHandlersScript(control, propertyName)), OperatorPrecedence.Max) :
                                                                                     default(CodeParameterAssignment)
                                                                                     );

            if (generatedPostbackHanlders == null)
            {
                call = $"dotvvm.applyPostbackHandlers(function(){{return {call}}}.bind(this),{options.ElementAccessor.Code.ToString(e => default(CodeParameterAssignment))},{GetPostBackHandlersScript(control, propertyName)})";
            }
            if (options.IsOnChange)
            {
                call = "if(!dotvvm.isViewModelUpdating){" + call + "}";
            }
            return(call + returnStatement);
        }
Exemplo n.º 31
0
        public void TestOnce()
        {
            //CommandWithInjection requires an ISimpleInterface
            injectionBinder.Bind <ISimpleInterface>().To <SimpleInterfaceImplementer> ().ToSingleton();

            //Bind the trigger to the command
            commandBinder.Bind(SomeEnum.ONE).To <CommandWithInjection>().Once();

            ICommandBinding binding = commandBinder.GetBinding(SomeEnum.ONE) as ICommandBinding;

            Assert.IsNotNull(binding);

            commandBinder.ReactTo(SomeEnum.ONE);

            ICommandBinding binding2 = commandBinder.GetBinding(SomeEnum.ONE) as ICommandBinding;

            Assert.IsNull(binding2);
        }
Exemplo n.º 32
0
		public void AddBinding(ICommandBinding binding)
		{
			this.Bindings.Add(binding);
		}
Exemplo n.º 33
0
        /// <summary>
        /// Initializes component.
        /// </summary>
        protected override void OnInitializeComponent()
        {
            IElementService elements = this.GetElementService();

            /* create an empty square by default if not set */
            if (elements != null)
            {
                if (this.square == null)
                {
                    this.square = elements.CreateEmptySquare();
                }
            }

            /* attach to commands */
            this.enterBinding = this.CreateBinding(GameCommands.SquareMapItem.Enter);

            if (this.enterBinding != null)
            {
                this.enterBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnSquareMapItemEnterCommandExecuted);
            }

            this.leaveBinding = this.CreateBinding(GameCommands.SquareMapItem.Leave);

            if (this.leaveBinding != null)
            {
                this.leaveBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnSquareMapItemLeaveCommandExecuted);
            }

            this.fixBinding = this.CreateBinding(GameCommands.SquareMapItem.Fix);

            if (this.fixBinding != null)
            {
                this.fixBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnSquareMapItemFixCommandExecuted);
            }

            this.fixCompleteBinding = this.CreateBinding(GameCommands.SquareMapItem.FixComplete);

            if (this.fixCompleteBinding != null)
            {
                this.fixCompleteBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnSquareMapItemFixCompleteCommandExecuted);
            }

            base.OnInitializeComponent();
        }
Exemplo n.º 34
0
        public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, PostbackScriptOptions options)
        {
            object uniqueControlId = null;
            if (expression is ControlCommandBindingExpression)
            {
                var target = (DotvvmControl)control.GetClosestControlBindingTarget();
                uniqueControlId = target.GetDotvvmUniqueId() as string;
            }

            var arguments = new List<string>()
            {
                "'root'",
                options.ElementAccessor,
                "[" + String.Join(", ", GetContextPath(control).Reverse().Select(p => '"' + p + '"')) + "]",
                (uniqueControlId is IValueBinding ? ((IValueBinding)uniqueControlId).GetKnockoutBindingExpression() : "'" + (string) uniqueControlId + "'"),
                options.UseWindowSetTimeout ? "true" : "false",
                JsonConvert.SerializeObject(GetValidationTargetExpression(control)),
                "null",
                GetPostBackHandlersScript(control, propertyName)
            };

            // return the script
            var condition = options.IsOnChange ? "if (!dotvvm.isViewModelUpdating) " : null;
            var returnStatement = options.ReturnValue != null ? $";return {options.ReturnValue.ToString().ToLower()};" : "";

            // call the function returned from binding js with runtime arguments
            var postBackCall = $"{expression.GetCommandJavascript()}({String.Join(", ", arguments)})";
            return condition + postBackCall + returnStatement;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Initializes component.
        /// </summary>
        protected override void OnInitializeComponent()
        {
            /* attach to commands with bindings */
            this.floodCompleteBinding = this.CreateBinding(GameCommands.Pipe.FloodComplete);

            if (this.floodCompleteBinding != null)
            {
                this.floodCompleteBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnFloodComplete);
            }

            this.floodAbortBinding = this.CreateBinding(GameCommands.Pipe.FloodAbort);

            if (this.floodAbortBinding != null)
            {
                this.floodAbortBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnFloodAbort);
            }

            base.OnInitializeComponent();
        }
Exemplo n.º 36
0
		public void RemoveBinding(ICommandBinding binding)
		{
			this.Bindings.Remove(binding);
		}
Exemplo n.º 37
0
 public static string GenerateClientPostBackScript(string propertyName, ICommandBinding expression, DotvvmControl control, bool useWindowSetTimeout = false,
     bool? returnValue = false, bool isOnChange = false, string elementAccessor = "this")
 {
     return GenerateClientPostBackScript(propertyName, expression, control, new PostbackScriptOptions(useWindowSetTimeout, returnValue, isOnChange, elementAccessor));
 }
Exemplo n.º 38
0
        /// <summary>
        /// Initializes component.
        /// </summary>
        protected override void OnInitializeComponent()
        {
            /* create flow */
            this.flow = new GameFlow();

            /* first get element service to create member objects */
            IElementService elements = this.GetElementService();

            if (elements != null)
            {
                this.countDown = elements.CreateCountDown();

                this.pipeQueue = elements.CreatePipeQueue();
                this.squareMap = elements.CreateSquareMap();

                this.squareMap.ActiveItemChanged += new EventHandler<EventArgs<ISquareMapItemElement>>(OnSquareMapActiveItemChanged);
            }

            /* second get game service and initialize bindings */
            IGameService game = this.GetGameService();

            if (game != null)
            {
                this.startBinding = game.CreateBinding(GameCommands.Game.Start);
                if (this.startBinding != null)
                {
                    this.startBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnGameStart);
                }

                this.presentCompleteBinding = game.CreateBinding(GameCommands.Game.PresentComplete);
                if (this.presentCompleteBinding != null)
                {
                    this.presentCompleteBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnGamePresentComplete);
                }

                this.readyToPlayCompleteBinding = game.CreateBinding(GameCommands.Game.ReadyToPlayComplete);
                if (this.readyToPlayCompleteBinding != null)
                {
                    this.readyToPlayCompleteBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnGameReadyToPlayComplete);
                }

                this.playAgainCompleteBinding = game.CreateBinding(GameCommands.Game.PlayAgainComplete);
                if (this.playAgainCompleteBinding != null)
                {
                    this.playAgainCompleteBinding.Executed += new EventHandler<EventArgs<ICommand>>(OnGamePlayAgainComplete);
                }
            }

            /* call base to finalize */
            base.OnInitializeComponent();
        }