Example #1
0
        private PropertySerializeInfo GetPropertySerializationInfo(DotvvmProperty property)
        {
            var binding = GetBinding(property);

            if (binding == null)
            {
                return(new PropertySerializeInfo
                {
                    Property = property,
                    Js = JsonConvert.SerializeObject(GetValue(property), Formatting.None, DefaultViewModelSerializer.CreateDefaultSettings()),
                    IsSerializable = true
                });
            }
            else if (binding is IValueBinding)
            {
                return(new PropertySerializeInfo
                {
                    Property = property,
                    Js = (binding as IValueBinding).GetKnockoutBindingExpression(this),
                    IsSerializable = true
                });
            }
            else
            {
                return(new PropertySerializeInfo {
                    Property = property
                });
            }
        }
        /// <summary>
        /// Gets the value of a specified property.
        /// </summary>
        public virtual object GetValue(DotvvmProperty property, bool inherit = true)
        {
            var value = GetValueRaw(property, inherit);

            if (property.IsBindingProperty)
            {
                return(value);
            }
            while (value is IBinding)
            {
                DotvvmBindableObject control = this;
                // DataContext is always bound to it's parent, setting it right here is a bit faster
                if (property == DataContextProperty)
                {
                    control = control.Parent;
                }
                // handle binding
                if (value is IStaticValueBinding binding)
                {
                    value = binding.Evaluate(control);
                }
                else if (value is ICommandBinding command)
                {
                    value = command.GetCommandDelegate(control);
                }
            }
            return(value);
        }
Example #3
0
        private bool TouchProperty(DotvvmProperty prop, object?value, ref RenderState r)
        {
            if (prop == TextProperty)
            {
                r.Text = value;
            }
            else if (prop == RenderSpanElementProperty)
            {
                r.RenderSpanElement = (bool)EvalPropertyValue(RenderSpanElementProperty, value) !;
            }
#pragma warning disable CS0618
            else if (prop == FormatStringProperty || prop == ValueTypeProperty)
#pragma warning restore CS0618
            {
                r.HasFormattingStuff = true;
            }
            else if (base.TouchProperty(prop, value, ref r.HtmlState))
            {
            }
            else if (DotvvmControl.TouchProperty(prop, value, ref r.BaseState))
            {
            }
            else
            {
                return(false);
            }
            return(true);
        }
        protected internal bool HasBinding <TBinding>(DotvvmProperty property)
            where TBinding : IBinding
        {
            object value;

            return(Properties.TryGetValue(property, out value) && value is TBinding);
        }
        /// <summary>
        /// Gets the value of a specified property.
        /// </summary>
        public virtual object GetValue(DotvvmProperty property, bool inherit = true)
        {
            var value = GetValueRaw(property, inherit);

            if (property.IsBindingProperty)
            {
                return(value);
            }
            while (value is IBinding)
            {
                DotvvmBindableObject control = this;
                if (inherit && !properties.ContainsKey(property))
                {
                    int n;
                    control = GetClosestWithPropertyValue(out n, d => d.properties != null && d.properties.ContainsKey(property));
                }
                if (value is IStaticValueBinding)
                {
                    // handle binding
                    var binding = (IStaticValueBinding)value;
                    value = binding.Evaluate(control, property);
                }
                else if (value is CommandBindingExpression)
                {
                    var binding = (CommandBindingExpression)value;
                    value = binding.GetCommandDelegate(control, property);
                }
            }
            return(value);
        }
        public void EmitSetDotvvmProperty(string controlName, DotvvmProperty property, ExpressionSyntax value)
        {
            UsedAssemblies.Add(property.DeclaringType.Assembly);
            UsedAssemblies.Add(property.PropertyType.Assembly);

            if (property.IsVirtual)
            {
                EmitSetProperty(controlName, property.PropertyInfo.Name, EmitValue(value));
            }
            else
            {
                CurrentStatements.Add(
                    SyntaxFactory.ExpressionStatement(
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.ParseName(property.DescriptorFullName),
                                SyntaxFactory.IdentifierName("SetValue")
                                ),
                            SyntaxFactory.ArgumentList(
                                SyntaxFactory.SeparatedList(
                                    new[] {
                    SyntaxFactory.Argument(SyntaxFactory.IdentifierName(controlName)),
                    SyntaxFactory.Argument(value)
                }
                                    )
                                )
                            )
                        )
                    );
            }
        }
Example #7
0
 protected override void LoadProperties(Dictionary <string, IPropertyDescriptor> result)
 {
     foreach (var property in DotvvmProperty.ResolveProperties(controlType.Type).Concat(DotvvmProperty.GetVirtualProperties(controlType.Type)))
     {
         result.Add(property.Name, property);
     }
 }
Example #8
0
        private PropertySerializeInfo GetPropertySerializationInfo(DotvvmProperty property)
        {
            var binding = GetBinding(property);

            if (binding == null)
            {

                return new PropertySerializeInfo
                {
                    Property = property,
                    Js = JsonConvert.SerializeObject(GetValue(property), Formatting.None),
                    IsSerializable = true
                };
            }
            else if (binding is IValueBinding)
            {
                return new PropertySerializeInfo
                {
                    Property = property,
                    Js = (binding as IValueBinding).GetKnockoutBindingExpression(),
                    IsSerializable = true

                };
            }
            else
            {
                return new PropertySerializeInfo { Property = property };
            }
        }
 /// <summary>
 /// Evaluates the binding.
 /// </summary>
 public object Evaluate(DotvvmBindableObject control, DotvvmProperty property, params object[] args)
 {
     var action = GetCommandDelegate(control, property);
     if (action is Command) return (action as Command)();
     if (action is Action) { (action as Action)(); return null; }
     return action.DynamicInvoke(args);
 }
Example #10
0
 public void BindingCompiler_PropertyRegisteredTwiceThrowException()
 {
     Assert.ThrowsException <ArgumentException>(() => {
         MoqComponent.PropertyProperty = DotvvmProperty.Register <object, MoqComponent>(t => t.Property);
         DotvvmProperty.Register <bool, MoqComponent>(t => t.Property);
     });
 }
Example #11
0
        private PropertySerializeInfo GetPropertySerializationInfo(DotvvmProperty property)
        {
            if (ContainsPropertyStaticValue(property))
            {
                JsonSerializerSettings settings = DefaultViewModelSerializer.CreateDefaultSettings();
                settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;

                return(new PropertySerializeInfo {
                    Property = property,
                    Js = JsonConvert.SerializeObject(GetValue(property), Formatting.None, settings),
                    IsSerializable = true
                });
            }
            else if (GetBinding(property) is IValueBinding valueBinding)
            {
                return(new PropertySerializeInfo {
                    Property = property,
                    Js = valueBinding.GetKnockoutBindingExpression(this),
                    IsSerializable = true
                });
            }
            else
            {
                return(new PropertySerializeInfo {
                    Property = property
                });
            }
        }
Example #12
0
 internal object EvalPropertyValue(DotvvmProperty property, object value)
 {
     if (property.IsBindingProperty)
     {
         return(value);
     }
     if (value is IBinding)
     {
         DotvvmBindableObject control = this;
         // DataContext is always bound to it's parent, setting it right here is a bit faster
         if (property == DataContextProperty)
         {
             control = control.Parent;
         }
         // handle binding
         if (value is IStaticValueBinding binding)
         {
             value = binding.Evaluate(control);
         }
         else if (value is ICommandBinding command)
         {
             value = command.GetCommandDelegate(control);
         }
         else
         {
             throw new NotSupportedException($"Cannot evaluate binding {value} of type {value.GetType().Name}.");
         }
     }
     return(value);
 }
        /// <summary>
        /// Emits the set attached property.
        /// </summary>
        public void EmitSetAttachedProperty(string controlName, DotvvmProperty property, object value)
        {
            UsedAssemblies.Add(property.DeclaringType.Assembly);
            UsedAssemblies.Add(property.PropertyType.Assembly);

            CurrentStatements.Add(
                SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName(controlName),
                            SyntaxFactory.IdentifierName("SetValue")
                            ),
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SeparatedList(
                                new[] {
                SyntaxFactory.Argument(
                    SyntaxFactory.MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        ParseTypeName(property.DeclaringType),
                        SyntaxFactory.IdentifierName(property.Name + "Property")
                        )
                    ),
                SyntaxFactory.Argument(
                    EmitValue(value)
                    )
            }
                                )
                            )
                        )
                    )
                );
        }
Example #14
0
 public ExpressionSyntax CreateDotvvmPropertyIdentifier(DotvvmProperty property)
 {
     if (property is GroupedDotvvmProperty)
     {
         var    gprop = (GroupedDotvvmProperty)property;
         string fieldName;
         if (!cachedGroupedDotvvmProperties.TryGetValue(gprop, out fieldName))
         {
             fieldName = $"_staticCachedGroupProperty_{cachedGroupedDotvvmProperties.Count}";
             cachedGroupedDotvvmProperties.Add(gprop, fieldName);
             otherDeclarations.Add(SyntaxFactory.FieldDeclaration(
                                       SyntaxFactory.VariableDeclaration(ParseTypeName(typeof(DotvvmProperty)),
                                                                         SyntaxFactory.SingletonSeparatedList(
                                                                             SyntaxFactory.VariableDeclarator(fieldName)
                                                                             .WithInitializer(SyntaxFactory.EqualsValueClause(
                                                                                                  SyntaxFactory.InvocationExpression(
                                                                                                      SyntaxFactory.ParseName(gprop.PropertyGroup.DeclaringType.FullName + "." + gprop.PropertyGroup.DescriptorField.Name
                                                                                                                              + "." + nameof(DotvvmPropertyGroup.GetDotvvmProperty)),
                                                                                                      SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                                                                                                     SyntaxFactory.Argument(this.EmitStringLiteral(gprop.GroupMemberName))
                                                                                                                                     ))
                                                                                                      )
                                                                                                  ))
                                                                             )
                                                                         )
                                       ));
         }
         return(SyntaxFactory.ParseName(fieldName));
     }
     else
     {
         return(SyntaxFactory.ParseName($"global::{property.DescriptorFullName}"));
     }
 }
Example #15
0
 protected bool TouchProperty(DotvvmProperty prop, object value, ref RenderState r)
 {
     if (prop == TextProperty)
     {
         r.Text = value;
     }
     else if (prop == RenderSpanElementProperty)
     {
         r.RenderSpanElement = (bool)EvalPropertyValue(RenderSpanElementProperty, value);
     }
     else if (prop == FormatStringProperty || prop == ValueTypeProperty)
     {
         r.HasFormattingStuff = true;
     }
     else if (base.TouchProperty(prop, value, ref r.HtmlState))
     {
     }
     else if (DotvvmControl.TouchProperty(prop, value, ref r.BaseState))
     {
     }
     else
     {
         return(false);
     }
     return(true);
 }
Example #16
0
        private PropertySerializeInfo GetPropertySerializationInfo(DotvvmProperty property)
        {
            var binding = GetBinding(property);

            if (binding == null && !typeof(ITemplate).IsAssignableFrom(property.PropertyType))
            {
                JsonSerializerSettings settings = DefaultViewModelSerializer.CreateDefaultSettings();
                settings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
                return(new PropertySerializeInfo
                {
                    Property = property,
                    Js = JsonConvert.SerializeObject(GetValue(property), Formatting.None, settings),
                    IsSerializable = true
                });
            }
            else if (binding is IValueBinding)
            {
                return(new PropertySerializeInfo
                {
                    Property = property,
                    Js = (binding as IValueBinding).GetKnockoutBindingExpression(this),
                    IsSerializable = true
                });
            }
            else
            {
                return(new PropertySerializeInfo {
                    Property = property
                });
            }
        }
Example #17
0
        public static int FindSlot(DotvvmProperty[] keys, int hashSeed, DotvvmProperty p)
        {
            var l = keys.Length;

            if (l == 4)
            {
                for (int i = 0; i < 4; i++)
                {
                    if (keys[i] == p)
                    {
                        return(i);
                    }
                }
                return(-1);
            }

            var lengthMap = l - 1; // trims the hash to be in bounds of the array
            var hash      = HashCombine(p.GetHashCode(), hashSeed) & lengthMap;

            var i1 = hash & -2; // hash with last bit == 0 (-2 is something like ff...fe because two's complement)
            var i2 = hash | 1;  // hash with last bit == 1

            if (keys[i1] == p)
            {
                return(i1);
            }
            if (keys[i2] == p)
            {
                return(i2);
            }
            return(-1);
        }
Example #18
0
        /// <summary>
        /// Evaluates the specified expression in the context of specified control.
        /// </summary>
        public object Evaluate(ValueBindingExpression expression, DotvvmProperty property, DotvvmBindableControl contextControl)
        {
            var visitor = EvaluateDataContextPath(contextControl);

            // evaluate the final expression
            EvaluateBinding(visitor, expression.Expression, expression.GetViewModelPathExpression(contextControl, property));
            return visitor.Result;
        }
Example #19
0
 public PropertyControlCollectionInsertionInfo(DotvvmProperty dotvvmProperty, StyleOverrideOptions type,
                                               ControlResolverMetadata metadata, IStyle innerControlStyle)
 {
     this.dotvvmProperty    = dotvvmProperty;
     this.Type              = type;
     this.metadata          = metadata;
     this.innerControlStyle = innerControlStyle;
 }
Example #20
0
 /// <summary>
 /// Determines whether it is legal to invoke a command on the specified property.
 /// </summary>
 public bool ValidateCommand(DotvvmProperty targetProperty)
 {
     if (targetProperty == ClickProperty)
     {
         return(Enabled && Visible);
     }
     return(false);
 }
Example #21
0
 /// <summary>
 /// Determines whether it is legal to invoke a command on the specified property.
 /// </summary>
 public bool ValidateCommand(DotvvmProperty targetProperty)
 {
     if (targetProperty == ClickProperty)
     {
         return Enabled && Visible;
     }
     return false;
 }
Example #22
0
        private bool ContainsPropertyStaticValue(DotvvmProperty property)
        {
            var binding = GetBinding(property);

            var isValueOrServerSideValueBinding = binding == null || (binding is IStaticValueBinding && !(binding is IValueBinding));

            return(isValueOrServerSideValueBinding && !typeof(ITemplate).IsAssignableFrom(property.PropertyType));
        }
        /// <summary>
        /// Gets the view model path expression.
        /// </summary>
        public override string GetViewModelPathExpression(DotvvmBindableControl control, DotvvmProperty property)
        {
            // find the parent markup control and calculate number of DataContext changes
            int numberOfDataContextChanges;
            var current = control.GetClosestControlBindingTarget(out numberOfDataContextChanges) as DotvvmBindableControl;

            current.EnsureControlHasId();
            return string.Join(".", Enumerable.Range(0, numberOfDataContextChanges).Select(i => "_parent").Concat(new[] { "_controlState_" + current.ID, Expression }));
        }
        /// <summary>
        /// Gets the command binding set to a specified property.
        /// </summary>
        public ICommandBinding GetCommandBinding(DotvvmProperty property, bool inherit = true)
        {
            var binding = GetBinding(property, inherit);

            if (binding != null && !(binding is ICommandBinding))
            {
                throw new DotvvmControlException(this, "CommandBindingExpression was expected!");
            }
            return(binding as ICommandBinding);
        }
Example #25
0
 public PropertyControlCollectionInsertionInfo(DotvvmProperty dotvvmProperty, StyleOverrideOptions type,
                                               ControlResolverMetadata metadata, IStyle innerControlStyle, object[] ctorParameters)
 {
     this.dotvvmProperty    = dotvvmProperty;
     this.Type              = type;
     this.metadata          = metadata;
     this.innerControlStyle = innerControlStyle;
     this.ctorParameters    = ctorParameters;
     this.propertyKind      = DeterminePropertyKind(dotvvmProperty, metadata);
 }
        private string GetJsValue(DotvvmProperty property)
        {
            var valueBinding = GetValueBinding(property);

            if (valueBinding != null)
            {
                return(valueBinding.GetKnockoutBindingExpression());
            }
            return(JsonConvert.SerializeObject(GetValue(property), Formatting.None));
        }
        /// <summary>
        /// Gets the value binding set to a specified property.
        /// </summary>
        public IValueBinding GetValueBinding(DotvvmProperty property, bool inherit = true)
        {
            var binding = GetBinding(property, inherit);

            if (binding != null && !(binding is IStaticValueBinding)) // throw exception on incompatible binding types
            {
                throw new DotvvmControlException(this, "ValueBindingExpression was expected!");
            }
            return(binding as IValueBinding);
        }
        /// <summary>
        /// Translates the expression to client script.
        /// </summary>
        public override string TranslateToClientScript(DotvvmBindableControl control, DotvvmProperty property)
        {
            ValidateExpression(Expression);

            // find the parent markup control and calculate number of DataContext changes
            int numberOfDataContextChanges;
            var current = control.GetClosestControlBindingTarget(out numberOfDataContextChanges) as DotvvmBindableControl;

            current.EnsureControlHasId();
            return string.Join(".", Enumerable.Range(0, numberOfDataContextChanges).Select(i => "$parent").Concat(new[] { "$controlState()", current.ID + "()", Expression }));
        }
Example #29
0
        public T Property <T>(DotvvmProperty property)
            where T : class
        {
            ResolvedPropertySetter s;

            if (Control.Properties.TryGetValue(property, out s))
            {
                return((s as ResolvedPropertyValue)?.Value as T);
            }
            return(null);
        }
 internal static object?TryGeyValue(this DotvvmBindableObject control, DotvvmProperty property)
 {
     try
     {
         return(control.GetValue(property));
     }
     catch
     {
         return(property.DefaultValue);
     }
 }
        public static DotvvmProperty GetDotvvmProperty <TControl, TProperty>(this TControl control, Expression <Func <TControl, TProperty> > prop)
            where TControl : DotvvmBindableObject
        {
            var property = (prop.Body as MemberExpression)?.Member as PropertyInfo;

            if (property == null)
            {
                throw new Exception($"Expression '{prop}' should be property access on the specified control.");
            }
            return(DotvvmProperty.ResolveProperty(property.DeclaringType, property.Name) ?? throw new Exception($"Property '{property.DeclaringType.Name}.{property.Name}' is not a registered DotvvmProperty."));
        }
Example #32
0
 private void SetProperty(string controlName, DotvvmProperty property, ExpressionSyntax value)
 {
     if (property.IsVirtual)
     {
         emitter.EmitSetProperty(controlName, property.PropertyInfo.Name, value);
     }
     else
     {
         emitter.EmitSetValue(controlName, property, value);
     }
 }
 private void SetProperty(string controlName, DotvvmProperty property, ExpressionSyntax value)
 {
     if (property.IsVirtual)
     {
         emitter.EmitSetProperty(controlName, property.PropertyInfo.Name, value);
     }
     else
     {
         emitter.EmitSetValue(controlName, property, value);
     }
 }
Example #34
0
 protected virtual ResolvedPropertySetter EmitBinding(Expression expression, DotvvmProperty property, ResolvedBinding originalBidning, ref string errror)
 {
     if (originalBidning == null)
     {
         errror = $"Could not merge constant values to binding '{expression}'."; return(null);
     }
     return(new ResolvedPropertyBinding(property,
                                        new ResolvedBinding(originalBidning.BindingService, originalBidning.Binding.GetProperty <BindingParserOptions>(), originalBidning.DataContextTypeStack, null, expression, property))
     {
         DothtmlNode = originalBidning.DothtmlNode
     });
 }
 public override Type GetChildDataContextType(Type dataContext, DataContextStack controlContextStack, ResolvedControl control, DotvvmProperty dproperty = null)
 {
     var property = DotvvmProperty.ResolveProperty(control.Metadata.Type, PropertyName);
     ResolvedPropertySetter propertyValue;
     if (control.Properties.TryGetValue(property, out propertyValue))
     {
         var binding = propertyValue as ResolvedPropertyBinding;
         if (binding == null) return dataContext;
         return binding.Binding.GetExpression().Type;
     }
     else return dataContext;
 }
Example #36
0
        public StyleBuilder <T> SetControlProperty <TControlType>(DotvvmProperty property, Action <StyleBuilder <TControlType> > styleBuilder = null,
                                                                  StyleOverrideOptions options = StyleOverrideOptions.Overwrite)
        {
            var innerControlStyleBuilder = new StyleBuilder <TControlType>(null, false);

            styleBuilder?.Invoke(innerControlStyleBuilder);

            style.SetProperties[property] = new CompileTimeStyleBase.PropertyControlCollectionInsertionInfo(property, options,
                                                                                                            new ControlResolverMetadata(typeof(TControlType)), innerControlStyleBuilder.GetStyle());

            return(this);
        }
Example #37
0
 public void Add(string name, DotvvmBindableControl control, DotvvmProperty property, Action nullBindingAction)
 {
     var binding = control.GetValueBinding(property);
     if (binding == null)
     {
         nullBindingAction();
     }
     else
     {
         info.Add(new KnockoutBindingInfo() { Name = name, Expression = control.GetValueBinding(property).GetKnockoutBindingExpression() });
     }
 }
Example #38
0
 protected internal string TranslateValueOrBinding(DotvvmProperty property)
 {
     var binding = GetValueBinding(property);
     if (binding == null)
     {
         return JsonConvert.SerializeObject(GetValue(property));
     }
     else
     {
         return "ko.unwrap(" + binding.GetKnockoutBindingExpression() + ")";
     }
 }
Example #39
0
        public static string EvaluateRouteUrl(string routeName, HtmlGenericControl control, DotvvmProperty urlSuffixProperty, IDotvvmRequestContext context)
        {
            var coreUrl = GenerateRouteUrlCore(routeName, control, context) + (control.GetValue(urlSuffixProperty) as string ?? "");

            if ((bool)control.GetValue(Internal.IsSpaPageProperty))
            {
                return "#!/" + coreUrl;
            }
            else
            {
                return context.TranslateVirtualPath(coreUrl);
            }
        }
Example #40
0
 public static void WriteRouteLinkHrefAttribute(string routeName, HtmlGenericControl control, DotvvmProperty urlSuffixProperty, IHtmlWriter writer, IDotvvmRequestContext context)
 {
     if (!control.RenderOnServer)
     {
         var group = new KnockoutBindingGroup();
         group.Add("href", GenerateKnockoutHrefExpression(routeName, control, urlSuffixProperty, context));
         writer.AddKnockoutDataBind("attr", group);
     }
     else
     {
         writer.AddAttribute("href", EvaluateRouteUrl(routeName, control, urlSuffixProperty, context));
     }
 }
Example #41
0
        public static void CopyProperty(DotvvmBindableObject source, DotvvmProperty sourceProperty, DotvvmBindableObject target, DotvvmProperty targetProperty)
        {
            var binding = source.GetValueBinding(sourceProperty);

            if (binding != null)
            {
                target.SetBinding(targetProperty, binding);
            }
            else
            {
                target.SetValue(targetProperty, source.GetValue(sourceProperty));
            }
        }
Example #42
0
        private static string GetUrlSuffixExpression(HtmlGenericControl control, DotvvmProperty urlSuffixProperty)
        {
            var urlSuffixBinding = control.GetValueBinding(urlSuffixProperty);

            if (urlSuffixBinding != null)
            {
                return("(" + urlSuffixBinding.GetKnockoutBindingExpression(control) + ")");
            }
            else
            {
                return(JsonConvert.SerializeObject(control.GetValue(urlSuffixProperty) as string ?? ""));
            }
        }
 // public static Expression GetDataContextExpression(DataContextStack dataContextStack, ResolvedControl control, DotvvmProperty property = null)
 //{
 //    var attributes = control.Metadata.Type.GetCustomAttributes<DataContextChangeAttribute>();
 //    Expression dataContextExpression = Expression.Parameter(dataContextStack.DataContextType, Constants.ThisSpecialBindingProperty);
 //    var paramDataContextExpression = dataContextExpression;
 //    foreach (var attribute in attributes)
 //    {
 //        // TODO: assign to varialbes to reduce multiple calls ?
 //        dataContextExpression = attribute.GetChildDataContextType(dataContextExpression, dataContextStack, control, property);
 //    }
 //    return dataContextExpression == paramDataContextExpression ? null : dataContextExpression;
 //}
 public static Type GetDataContextExpression(DataContextStack dataContextStack, ResolvedControl control, DotvvmProperty property = null)
 {
     var attributes = property == null ? control.Metadata.Type.GetCustomAttributes<DataContextChangeAttribute>() : property.PropertyInfo?.GetCustomAttributes<DataContextChangeAttribute>();
     if (attributes == null) return null;
     var type = dataContextStack.DataContextType;
     var paramDataContextExpression = type;
     foreach (var attribute in attributes)
     {
         // TODO: assign to varialbes to reduce multiple calls ?
         type = attribute.GetChildDataContextType(type, dataContextStack, control, property);
     }
     return type == paramDataContextExpression ? null : type;
 }
Example #44
0
 private static string GetUrlSuffixExpression(HtmlGenericControl control, DotvvmProperty urlSuffixProperty)
 {
     var urlSuffixBinding = control.GetValueBinding(urlSuffixProperty);
     string urlSuffix;
     if (urlSuffixBinding != null)
     {
         urlSuffix = urlSuffixBinding.GetKnockoutBindingExpression();
     }
     else
     {
         urlSuffix = JsonConvert.SerializeObject(control.GetValue(urlSuffixProperty) as string ?? "");
     }
     return urlSuffix;
 }
Example #45
0
        public static string GenerateKnockoutHrefExpression(string routeName, HtmlGenericControl control, DotvvmProperty urlSuffixProperty, IDotvvmRequestContext context)
        {
            var link = GenerateRouteLinkCore(routeName, control, context);

            var urlSuffix = GetUrlSuffixExpression(control, urlSuffixProperty);
            if ((bool)control.GetValue(Internal.IsSpaPageProperty))
            {
                return $"'#!/' + {link} + {urlSuffix}";
            }
            else
            {
                return $"'{context.TranslateVirtualPath("~/")}' + {link} + {urlSuffix}";
            }
        }
Example #46
0
        private static void AddValidatedValue(IHtmlWriter writer, IDotvvmRequestContext context, DotvvmProperty prop, DotvvmControl control)
        {
            writer.AddKnockoutDataBind("dotvvmValidation", control, ValueProperty);

            // render options
            var bindingGroup = new KnockoutBindingGroup();
            foreach (var property in ValidationOptionProperties)
            {
                var javascriptName = KnockoutHelper.ConvertToCamelCase(property.Name);
                var optionValue = control.GetValue(property);
                if (!object.Equals(optionValue, property.DefaultValue))
                {
                    bindingGroup.Add(javascriptName, JsonConvert.SerializeObject(optionValue));
                }
            }
            writer.AddKnockoutDataBind("dotvvmValidationOptions", bindingGroup);
        }
Example #47
0
 public static void AddKnockoutDataBind(this IHtmlWriter writer, string name, DotvvmControl control, DotvvmProperty property, Action nullBindingAction = null,
     string valueUpdate = null, bool renderEvenInServerRenderingMode = false, bool setValueBack = false)
 {
     var expression = control.GetValueBinding(property);
     if (expression != null && (!control.RenderOnServer || renderEvenInServerRenderingMode))
     {
         writer.AddAttribute("data-bind", name + ": " + expression.GetKnockoutBindingExpression(), true, ", ");
         if (valueUpdate != null)
         {
             writer.AddAttribute("data-bind", "valueUpdate: '" + valueUpdate + "'", true, ", ");
         }
     }
     else
     {
         if (nullBindingAction != null) nullBindingAction();
         if (setValueBack && expression != null) control.SetValue(property, expression.Evaluate(control, property));
     }
 }
        /// <summary>
        /// Evaluates the specified expression.
        /// </summary>
        public override object Evaluate(DotvvmBindableControl control, DotvvmProperty property)
        {
            ValidateExpression(Expression);

            // find the parent markup control and calculate number of DataContext changes
            int numberOfDataContextChanges;
            var current = control.GetClosestControlBindingTarget(out numberOfDataContextChanges) as DotvvmBindableControl;

            if (current == null || !current.RequiresControlState)
            {
                throw new Exception("The {controlState: ...} binding can only be used in a markup control that supports ControlState!");    // TODO: exception handling
            }
            else
            {
                object value;
                return current.ControlState.TryGetValue(Expression, out value) ? value : DefaultValue;
            }
        }
        /// <summary>
        /// Evaluates the binding.
        /// </summary>
        public object Evaluate(Controls.DotvvmBindableControl control, DotvvmProperty property)
        {
            if (Delegate != null) return Delegate(new object[0], null);

            if (!OriginalString.Contains("."))
            {
                throw new Exception("Invalid resource name! Use Namespace.ResourceType.ResourceKey!");
            }

            // parse expression
            var lastDotPosition = OriginalString.LastIndexOf(".");
            var resourceType = OriginalString.Substring(0, lastDotPosition);
            var resourceKey = OriginalString.Substring(lastDotPosition + 1);

            // find the resource manager
            var resourceManager = cachedResourceManagers.GetOrAdd(resourceType, GetResourceManager);

            // return the value
            return resourceManager.GetString(resourceKey);
        }
        public override object Evaluate(DotvvmBindableControl control, DotvvmProperty property)
        {
            // I can execute the delegate, or find the property and get its value
            // TODO: whats better ??
            return ExecDelegate(control, property != DotvvmBindableControl.DataContextProperty, setRootControl: true);


            //// find the parent markup control and calculate number of DataContext changes
            //int numberOfDataContextChanges;
            //var current = control.GetClosestControlBindingTarget(out numberOfDataContextChanges);

            //// get the property
            //var sourceProperty = DotvvmProperty.ResolveProperty(current.GetType(), OriginalString);
            //if (sourceProperty == null)
            //{
            //    throw new Exception(string.Format("The markup control of type '{0}' does not have a property '{1}'!", current.GetType(), ExpressionTree));        // TODO: exception handling
            //}

            //// check whether the property contains binding
            //if (current is DotvvmBindableControl)
            //{
            //    var originalBinding = ((DotvvmBindableControl)current).GetBinding(sourceProperty);
            //    if (originalBinding != null && originalBinding.GetType() == typeof(ValueBindingExpression))
            //    {
            //        // ValueBindingExpression must be modified to be evaluated against the original DataContext
            //        return new ValueBindingExpression(string.Join(".",
            //            Enumerable.Repeat("$parent", numberOfDataContextChanges)
            //            .Concat(new[] { originalBinding.OriginalString })));
            //    }
            //    else if (originalBinding != null)
            //    {
            //        return originalBinding;
            //    }
            //}

            //// otherwise evaluate on server
            //return current.GetValue(sourceProperty);
        }
        /// <summary>
        /// Emits the set attached property.
        /// </summary>
        public void EmitSetAttachedProperty(string controlName, DotvvmProperty property, object value)
        {
            UsedAssemblies.Add(property.DeclaringType.Assembly);
            UsedAssemblies.Add(property.PropertyType.Assembly);

            CurrentStatements.Add(
                SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName(controlName),
                            SyntaxFactory.IdentifierName("SetValue")
                        ),
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SeparatedList(
                                new[] {
                                    SyntaxFactory.Argument(
                                        SyntaxFactory.MemberAccessExpression(
                                            SyntaxKind.SimpleMemberAccessExpression,
                                            ParseTypeName(property.DeclaringType),
                                            SyntaxFactory.IdentifierName(property.Name + "Property")
                                        )
                                    ),
                                    SyntaxFactory.Argument(
                                        EmitValue(value)
                                    )
                                }
                            )
                        )
                    )
                )
            );
        }
        public string EmitEnsureCollectionInitialized(string parentName, DotvvmProperty property)
        {
            UsedAssemblies.Add(property.PropertyType.Assembly);

            if (property.IsVirtual)
            {
                StatementSyntax initializer;
                if (property.PropertyInfo.SetMethod != null)
                {
                    initializer = SyntaxFactory.ExpressionStatement(
                            SyntaxFactory.AssignmentExpression(
                                SyntaxKind.SimpleAssignmentExpression,
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(parentName),
                                    SyntaxFactory.IdentifierName(property.Name)
                                ),
                                SyntaxFactory.ObjectCreationExpression(ParseTypeName(property.PropertyType))
                                    .WithArgumentList(
                                        SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new ArgumentSyntax[] { }))
                                    )
                            )
                        );
                }
                else
                {
                    initializer = SyntaxFactory.ThrowStatement(
                        CreateObjectExpression(typeof(InvalidOperationException),
                            new[] { EmitStringLiteral($"Property '{ property.FullName }' can't be used as control collection since it is not initialized and does not have setter available for automatic initialization") }
                        )
                    );
                }
                CurrentStatements.Add(
                    SyntaxFactory.IfStatement(
                        SyntaxFactory.BinaryExpression(
                            SyntaxKind.EqualsExpression,
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.IdentifierName(parentName),
                                SyntaxFactory.IdentifierName(property.Name)
                            ),
                            SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
                        ),
                        initializer
                    )
                );

                return EmitCreateVariable(
                    SyntaxFactory.MemberAccessExpression(
                        SyntaxKind.SimpleMemberAccessExpression,
                        SyntaxFactory.IdentifierName(parentName),
                        SyntaxFactory.IdentifierName(property.Name)
                    )
                );
            }
            else
            {
                CurrentStatements.Add(
                    SyntaxFactory.IfStatement(
                        SyntaxFactory.BinaryExpression(
                            SyntaxKind.EqualsExpression,
                            SyntaxFactory.InvocationExpression(
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(parentName),
                                    SyntaxFactory.IdentifierName("GetValue")
                                ),
                                SyntaxFactory.ArgumentList(
                                    SyntaxFactory.SeparatedList(new[]
                                    {
                                        SyntaxFactory.Argument(SyntaxFactory.ParseName(property.DescriptorFullName))
                                    })
                                )
                            ),
                            SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
                        ),
                        SyntaxFactory.ExpressionStatement(
                            SyntaxFactory.InvocationExpression(
                                SyntaxFactory.MemberAccessExpression(
                                    SyntaxKind.SimpleMemberAccessExpression,
                                    SyntaxFactory.IdentifierName(parentName),
                                    SyntaxFactory.IdentifierName("SetValue")
                                ),
                                SyntaxFactory.ArgumentList(
                                    SyntaxFactory.SeparatedList(new[]
                                    {
                                        SyntaxFactory.Argument(SyntaxFactory.ParseName(property.DescriptorFullName)),
                                        SyntaxFactory.Argument(
                                            SyntaxFactory.ObjectCreationExpression(ParseTypeName(property.PropertyType))
                                                .WithArgumentList(
                                                    SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(new ArgumentSyntax[] { }))
                                                )
                                        )
                                    })
                                )
                            )
                        )
                    )
                );
                return EmitCreateVariable(
                    SyntaxFactory.CastExpression(
                        ParseTypeName(property.PropertyType),
                        SyntaxFactory.InvocationExpression(
                            SyntaxFactory.MemberAccessExpression(
                                SyntaxKind.SimpleMemberAccessExpression,
                                SyntaxFactory.IdentifierName(parentName),
                                SyntaxFactory.IdentifierName("GetValue")
                            ),
                            SyntaxFactory.ArgumentList(
                                SyntaxFactory.SeparatedList(new[]
                                {
                                    SyntaxFactory.Argument(SyntaxFactory.ParseName(property.DescriptorFullName))
                                })
                            )
                        )
                    )
                );
            }
        }
        /// <summary>
        /// Emits the set DotvvmProperty statement.
        /// </summary>
        public void EmitSetValue(string controlName, DotvvmProperty property, ExpressionSyntax valueSyntax)
        {
            UsedAssemblies.Add(property.DeclaringType.Assembly);
            UsedAssemblies.Add(property.PropertyType.Assembly);

            CurrentStatements.Add(
                SyntaxFactory.ExpressionStatement(
                    SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.IdentifierName(controlName),
                            SyntaxFactory.IdentifierName("SetValue")
                        ),
                        SyntaxFactory.ArgumentList(
                            SyntaxFactory.SeparatedList(new[]
                            {
                                SyntaxFactory.Argument(SyntaxFactory.ParseName(property.DescriptorFullName)),
                                SyntaxFactory.Argument(valueSyntax)
                            })
                        )
                    )
                )
            );
        }
Example #54
0
 public ResolvedPropertyControl(DotvvmProperty property, ResolvedControl control)
     : base(property)
 {
     Control = control;
 }
 public ResolvedPropertyTemplate(DotvvmProperty property, List<ResolvedControl> content)
     : base(property)
 {
     Content = content;
 }
 public override object Evaluate(DotvvmBindableControl control, DotvvmProperty property)
 {
     return ExecDelegate(control, true, true);
 }
 //public override Expression GetChildDataContextType(Expression dataContext, DataContextStack controlContextStack, ResolvedControl control, DotvvmProperty property = null)
 //{
 //    return ExpressionUtils.Indexer(dataContext, controlContextStack.GetNextParameter(typeof(int)));
 //}
 public override Type GetChildDataContextType(Type dataContext, DataContextStack controlContextStack, ResolvedControl control, DotvvmProperty property = null)
 {
     return ReflectionUtils.GetEnumerableType(dataContext);
 }
Example #58
0
 public ResolvedPropertySetter(DotvvmProperty property)
 {
     Property = property;
 }
 public override Delegate GetCommandDelegate(DotvvmBindableObject control, DotvvmProperty property)
 {
     throw new NotImplementedException();
 }
Example #60
0
        /// <summary>
        /// Evaluates the PropertyInfo for the expression.
        /// </summary>
        public PropertyInfo EvaluateProperty(ValueBindingExpression expression, DotvvmProperty property, DotvvmBindableControl control, out object target)
        {
            var visitor = EvaluateDataContextPath(control);
            target = visitor.Result;

            // evaluate the final expression
            var node = ParseBinding(expression.Expression);
            string propertyName = null;
            if (node is IdentifierNameSyntax)
            {
                propertyName = ((IdentifierNameSyntax)node).ToString();
            }
            else if (node is MemberAccessExpressionSyntax)
            {
                target = visitor.Visit(((MemberAccessExpressionSyntax)node).Expression);
                propertyName = ((MemberAccessExpressionSyntax)node).Name.ToString();
            }

            if (propertyName != null && !visitor.IsSpecialPropertyName(propertyName))
            {
                var propertyInfo = target.GetType().GetProperty(propertyName);
                if (propertyInfo != null)
                {
                    return propertyInfo;
                }
            }
            throw new NotSupportedException(string.Format("Cannot update the source of the binding '{0}'!", expression.Expression));
        }