Пример #1
0
        public static string GetDisplayName(this IMPropertyInfo pPropertyInfo, IStringLocalizer L, bool pMarkup = false)
        {
            var displayAttribute = pPropertyInfo.GetCustomAttribute <DisplayAttribute>();

            if (displayAttribute != null)
            {
                var display = displayAttribute.GetName();

                if (displayAttribute.ResourceType == null)
                {
                    display = L[displayAttribute.Name];
                }

                display ??= string.Empty;

                if (pMarkup)
                {
                    return(HttpUtility.HtmlEncode(display).Replace("\n", "<br>"));
                }

                return(display);
            }

            return(pPropertyInfo.Name);
        }
Пример #2
0
        private static Expression <Func <T> > GetValueExpression <T>(IMPropertyInfo pPropertyInfo, object pModel)
        {
            if (pModel is IDictionary <string, object> )
            {
                var fake = new FakePropertyInfo <T>(pPropertyInfo.Name);

                //just create a member expression with random values
                MemberExpression expression = Expression.Property(Expression.Constant(fake), nameof(fake.CanRead));

                Expression constantExpression = Expression.Constant(default(T), typeof(T));

                var constantExpressionValueBaseFields = constantExpression.GetType().BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic);
                var constantExpressionValueFields     = constantExpression.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

                var field = constantExpressionValueBaseFields.Concat(constantExpressionValueFields).First(f => f.FieldType == typeof(object));
                field.SetValue(constantExpression, pModel);

                //set generated constant expression
                var expressionField = expression.GetType().BaseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic).First(f => f.FieldType == typeof(Expression));
                expressionField.SetValue(expression, constantExpression);

                //set fake property type
                var propertyField = expression.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic).First(f => f.FieldType == typeof(PropertyInfo));
                propertyField.SetValue(expression, fake);

                //now we have generated an MemberExpression which has the pModel as value and an FakePropertyInfo with correct type

                return(Expression.Lambda <Func <T> >(expression));
            }
            else
            {
                var propertyholder = pPropertyInfo.GetPropertyHolder(pModel);
                return(Expression.Lambda <Func <T> >(Expression.Property(Expression.Constant(propertyholder), pPropertyInfo.Name)));
            }
        }
        public static MemberExpression GetMemberExpression(this IMPropertyInfo pPropertyInfo, ParameterExpression param)
        {
            MemberExpression propertyExpr = null;

            if (pPropertyInfo.Parent != null)
            {
                var parents = GetParents(pPropertyInfo);

                foreach (var entry in parents)
                {
                    if (propertyExpr == null)
                    {
                        propertyExpr = Expression.Property(param, entry.Name);
                    }
                    else
                    {
                        propertyExpr = Expression.Property(propertyExpr, entry.Name);
                    }
                }

                propertyExpr = Expression.Property(propertyExpr, pPropertyInfo.Name);
            }
            else
            {
                propertyExpr = Expression.Property(param, pPropertyInfo.Name);
            }

            return(propertyExpr);
        }
        public static ICollection <IMPropertyInfo> GetParents(this IMPropertyInfo pPropertyInfo)
        {
            List <IMPropertyInfo> ret = new List <IMPropertyInfo>();

            GetParents(pPropertyInfo, ref ret);
            ret.Reverse();
            return(ret);
        }
Пример #5
0
 internal MFormValueChangedArgs(IMField pField, IMPropertyInfo pPropertyInfo, object pNewValue, T pModel)
 {
     NewValue     = pNewValue;
     Model        = pModel;
     Field        = pField;
     Property     = pPropertyInfo.Name;
     PropertyInfo = pPropertyInfo;
 }
Пример #6
0
        public async Task OnInputValueChanged(IMField pField, IMPropertyInfo pPropertyInfo, object pNewValue)
        {
            ChangedValues.Add(pPropertyInfo);

            if (OnValueChanged.HasDelegate)
            {
                await OnValueChanged.InvokeAsync(new MFormValueChangedArgs <T>(pField, pPropertyInfo, pNewValue, Model));
            }
        }
Пример #7
0
        private static bool IsPropertyHolderNull(IMPropertyInfo pPropertyInfo, object pModel)
        {
            if (pModel is IDictionary <string, object> )
            {
                return(false);
            }

            return(pPropertyInfo.GetPropertyHolder(pModel) == null);
        }
        private static void GetParents(IMPropertyInfo pPropertyInfo, ref List <IMPropertyInfo> pResult)
        {
            if (pPropertyInfo.Parent == null)
            {
                return;
            }

            pResult.Add(pPropertyInfo.Parent);
            GetParents(pPropertyInfo.Parent, ref pResult);
        }
Пример #9
0
        public static void ShowNotSupportedType(RenderTreeBuilder pBuilder, IMPropertyInfo pPropertyInfo, object pModel, Guid pId, IMForm pParent)
        {
            var value = pPropertyInfo.GetValue(pModel);

            pBuilder.OpenElement(45, "input");
            pBuilder.AddAttribute(1, "id", pId);
            pBuilder.AddAttribute(2, "Value", value);
            pBuilder.AddAttribute(33, "disabled", string.Empty);
            pBuilder.AddAttribute(33, "class", "m-form-control");
            pBuilder.CloseElement();
        }
Пример #10
0
        protected IMPropertyField GetField(IMPropertyInfo pPropertyInfo)
        {
            return(new MField()
            {
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.

                Attributes = pPropertyInfo.GetAttributes()?.ToArray(),
                Property = pPropertyInfo.Name,
                PropertyType = pPropertyInfo.PropertyType

#pragma warning restore BL0005 // Component parameter should not be set outside of its component.
            });
        }
Пример #11
0
 public void OnInputKeyUp(KeyboardEventArgs pArgs, IMPropertyInfo pPropertyInfo)
 {
     if (pArgs.Key == "Enter" && pPropertyInfo.GetCustomAttribute <TextAreaAttribute>() == null)
     {
         if (ContainerContext == null)
         {
             //value may not be updated
             Task.Delay(10).ContinueWith((a) =>
             {
                 _ = CallLocalSubmit(true);
             });
         }
     }
 }
        public static string GetFullName(this IMPropertyInfo pPropertyInfo)
        {
            var parents = GetParents(pPropertyInfo);

            if (parents.Count <= 0)
            {
                return(pPropertyInfo.Name);
            }

            string ret = string.Join(".", parents.Select(p => p.Name));

            ret += "." + pPropertyInfo.Name;

            return(ret);
        }
Пример #13
0
        public async Task OnInputValueChanged(IMField pField, IMPropertyInfo pPropertyInfo, object pNewValue)
        {
            if (!ChangedValues.Contains(pPropertyInfo))
            {
                ChangedValues.Add(pPropertyInfo);
            }

            if (OnValueChanged.HasDelegate)
            {
                await OnValueChanged.InvokeAsync(new MFormValueChangedArgs <T>(pField, pPropertyInfo, pNewValue, Model));
            }

            if (mEditContext != null && pField is IMPropertyField propertyField)
            {
                mEditContext.NotifyFieldChanged(mEditContext.Field(propertyField.Property));
            }
        }
Пример #14
0
        private void AddInput(RenderTreeBuilder builder2, IMField field, IMPropertyInfo propertyInfo, Guid inpId)
        {
            if (field is IMPropertyField pf)
            {
                if (field is IMComplexField)
                {
                    var appendMethod = typeof(RenderHelper).GetMethod(nameof(RenderHelper.AppendComplexType)).MakeGenericMethod(typeof(T), pf.PropertyType);
                    appendMethod.Invoke(null, new object[] { builder2, propertyInfo, Model, inpId, this, field, MFormGridContext });
                    return;
                }

                bool isInFilterRow = AdditionalAttributes != null && AdditionalAttributes.ContainsKey("data-is-filterrow");

                var method = typeof(RenderHelper).GetMethod(nameof(RenderHelper.AppendInput)).MakeGenericMethod(propertyInfo.PropertyType);
                method.Invoke(null, new object[] { builder2, propertyInfo, Model, inpId, this, isInFilterRow, field });
            }
        }
Пример #15
0
        private static async Task InvokeValueChanged(IMForm pParent, IMPropertyInfo pPropertyInfo, IMField pField, object pModel, object pNewValue)
        {
            lock (pModel)
            {
                if (pPropertyInfo.GetCustomAttribute <DateAttribute>() != null)
                {
                    var dateTime = pNewValue as DateTime?;

                    if (dateTime != null && dateTime.Value.Kind == DateTimeKind.Unspecified)
                    {
                        pNewValue = DateTime.SpecifyKind(dateTime.Value, DateTimeKind.Utc);
                    }
                }

                pPropertyInfo.SetValue(pModel, pNewValue);
            }

            await pParent.OnInputValueChanged(pField, pPropertyInfo, pNewValue);
        }
        public virtual string FormatPropertyColumnValue(IMGridPropertyColumn pColumn, IMPropertyInfo pPropertyInfo, T pRow)
        {
            object value = pPropertyInfo.GetValue(pRow);

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

            if (pColumn.StringFormat != null)
            {
                return(String.Format(pColumn.StringFormat, value));
            }

            Type pType = Nullable.GetUnderlyingType(pPropertyInfo.PropertyType) ?? pPropertyInfo.PropertyType;

            if (pType == typeof(bool))
            {
                return((bool)value ? L["True"] : L["False"]);
            }

            if (pType.IsEnum)
            {
                return(((Enum)value).ToName());
            }

            if (pType == typeof(DateTime)) //TODO
            {
                if (HasAttribute(pColumn, pPropertyInfo, typeof(TimeAttribute)))
                {
                    return(((DateTime)value).ToString("HH:mm"));
                }

                if (HasAttribute(pColumn, pPropertyInfo, typeof(DateTimeAttribute)))
                {
                    return(((DateTime)value).ToString("yyyy-MM-ddTHH:mm"));
                }

                return(((DateTime)value).ToString("yyyy-MM-dd"));
            }

            return(value.ToString());
        }
 protected bool HasAttribute(IMGridPropertyColumn pColumn, IMPropertyInfo pPropertyInfo, Type pType)
 {
     return(pPropertyInfo.GetCustomAttribute(pType) != null || (pColumn.Attributes != null && pColumn.Attributes.Any(a => a.GetType() == pType)));
 }
        public virtual string FormatPropertyColumnValue(IMGridPropertyColumn pColumn, IMPropertyInfo pPropertyInfo, T pRow)
        {
            object value = pPropertyInfo.GetValue(pRow);

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

            if (pColumn.StringFormat != null)
            {
                return(string.Format(pColumn.StringFormat, value));
            }

            if (pPropertyInfo.PropertyType == null)
            {
                throw new ArgumentException($"{nameof(pPropertyInfo.PropertyType)} of column {pColumn.Identifier} is null, please specify it");
            }

            Type pType = Nullable.GetUnderlyingType(pPropertyInfo.PropertyType) ?? pPropertyInfo.PropertyType;

            if (pType == typeof(bool))
            {
                return((bool)value ? L["True"] : L["False"]);
            }

            if (pType.IsEnum)
            {
                return(((Enum)value).ToName());
            }

            if (pType == typeof(DateTime))
            {
                if (HasAttribute(pColumn, pPropertyInfo, typeof(TimeAttribute)))
                {
                    return(string.Format("{0:t}", ((DateTime)value)));
                }

                if (HasAttribute(pColumn, pPropertyInfo, typeof(DateTimeAttribute)))
                {
                    return(string.Format("{0:g}", ((DateTime)value)));
                }

                return(string.Format("{0:d}", ((DateTime)value)));
            }

            return(value.ToString());
        }
Пример #19
0
        public static void AppendInput <T>(RenderTreeBuilder pBuilder, IMPropertyInfo pPropertyInfo, object pModel, Guid pId, IMForm pParent, bool pIsInFilterRow, IMField pField)
        {
            try
            {
                if (!IsTypeSupported(typeof(T)) || IsPropertyHolderNull(pPropertyInfo, pModel))
                {
                    ShowNotSupportedType(pBuilder, pPropertyInfo, pModel, pId, pParent);
                    return;
                }

                T    value = (T)(pPropertyInfo.GetValue(pModel) ?? default(T));
                Type tType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

                bool isReadOnly = pPropertyInfo.IsReadOnly || pPropertyInfo.GetCustomAttribute(typeof(ReadOnlyAttribute)) != null;

                if (mNumberTypes.Contains(tType))
                {
                    pBuilder.OpenComponent <InputNumber <T> >(0);
                }
                else if (tType == typeof(DateTime) || tType == typeof(DateTimeOffset))
                {
                    if (pPropertyInfo.GetCustomAttribute(typeof(TimeAttribute)) != null)
                    {
                        pBuilder.OpenComponent <InputTime <T> >(0);
                    }
                    else if (pPropertyInfo.GetCustomAttribute(typeof(DateTimeAttribute)) != null)
                    {
                        pBuilder.OpenComponent <InputDateTime <T> >(0);
                    }
                    else
                    {
                        pBuilder.OpenComponent <InputDate <T> >(0);
                    }
                }
                else if (typeof(T) == typeof(bool))
                {
                    pBuilder.OpenComponent <MInputCheckbox>(0);
                }
                else if (typeof(T) == typeof(bool?))
                {
                    pBuilder.OpenComponent <MSelect <T> >(0);
                    if (pIsInFilterRow)
                    {
                        pBuilder.AddAttribute(10, "NullValueDescription", "\u200b");
                    }
                }
                else if (tType == typeof(Guid))
                {
                    pBuilder.OpenComponent <InputGuid <T> >(0);
                }
                else if (tType.IsEnum)
                {
                    pBuilder.OpenComponent <MSelect <T> >(0);
                    if (pIsInFilterRow)
                    {
                        pBuilder.AddAttribute(10, "NullValueDescription", "\u200b");
                    }
                }
                else
                {
                    if (pPropertyInfo.GetCustomAttribute(typeof(TextAreaAttribute)) != null)
                    {
                        pBuilder.OpenComponent <InputTextArea>(0);
                    }
                    else
                    {
                        pBuilder.OpenComponent <InputText>(0);
                    }
                }

                if (pPropertyInfo.GetCustomAttribute(typeof(PasswordAttribute)) != null)
                {
                    pBuilder.AddAttribute(33, "type", "password");
                }

                if (pField.AdditionalAttributes != null)
                {
                    pBuilder.AddMultipleAttributes(17, pField.AdditionalAttributes
                                                   .Where(a => a.Key != Extensions.MFORM_IN_TABLE_ROW_TD_STYLE_ATTRIBUTE)
                                                   .Where(a => a.Key != nameof(IMGridColumn))
                                                   .ToDictionary(a => a.Key, a => a.Value));
                }

                pBuilder.AddAttribute(1, "id", pId);
                pBuilder.AddAttribute(2, "Value", value);

                pBuilder.AddAttribute(23, "ValueChanged", RuntimeHelpers.CreateInferredEventCallback <T>(pParent, async __value =>
                {
                    pPropertyInfo.SetValue(pModel, __value);
                    await pParent.OnInputValueChanged(pField, pPropertyInfo, __value);
                }, value));

                pBuilder.AddAttribute(23, "onkeyup", EventCallback.Factory.Create <KeyboardEventArgs>(pParent, (a) =>
                {
                    pParent.OnInputKeyUp(a);
                }));

                var valueExpression = GetValueExpression <T>(pPropertyInfo, pModel);

                pBuilder.AddAttribute(4, "ValueExpression", valueExpression);

                string cssClass = "m-form-control";

                if (isReadOnly)
                {
                    pBuilder.AddAttribute(33, "disabled", string.Empty);
                    pBuilder.AddAttribute(33, "IsDisabled", true);
                }

                pBuilder.AddAttribute(10, "class", cssClass);

                if (typeof(T) == typeof(bool?))
                {
                    IEnumerable <bool?> options = new bool?[] { true, false };
                    pBuilder.AddAttribute(10, "Options", options);
                }

                pBuilder.CloseComponent();

                if (pParent.EnableValidation)
                {
                    pBuilder.OpenComponent <ValidationMessage <T> >(60);
                    pBuilder.AddAttribute(61, "For", valueExpression);
                    pBuilder.CloseComponent();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
Пример #20
0
        private static IMPropertyInfo GetMPropertyInfo(Type pObjectType, string pProperty, IMPropertyInfo pParent)
        {
            if (pProperty.Contains('.'))
            {
                var properties = pProperty.Split('.');

                if (properties.Length < 2)
                {
                    throw new ArgumentException($"{nameof(pProperty)} not valid: " + pProperty);
                }

                var parentProperty = GetPropertyInfo(pObjectType, properties.First());

                string childProperties = string.Join(".", properties.Skip(1));

                var parent = new MPropertyInfo(parentProperty, pParent);

                var childPropType = parentProperty.PropertyType.GetProperty(properties.Skip(1).First());

                return(GetIMPropertyInfo(parentProperty.PropertyType, childProperties, childPropType.PropertyType, parent));
            }

            PropertyInfo pi = GetPropertyInfo(pObjectType, pProperty);

            if (pi == null)
            {
                throw new InvalidOperationException(pObjectType + " does not have property " + pProperty);
            }

            return(new MPropertyInfo(pi, pParent));
        }
Пример #21
0
        private static IMPropertyInfo GetMPropertyExpandoInfo(Type pObjectType, string pProperty, Type pPropertyType, IMPropertyInfo pParent)
        {
            if (pProperty.Contains('.'))
            {
                var properties = pProperty.Split('.');

                if (properties.Length < 2)
                {
                    throw new ArgumentException($"{nameof(pProperty)} not valid: " + pProperty);
                }

                var parent = new MPropertyExpandoInfo(properties.First(), null, pParent);

                string childProperties = string.Join(".", properties.Skip(1));

                return(GetIMPropertyInfo(pObjectType, childProperties, pPropertyType, parent));
            }

            return(new MPropertyExpandoInfo(pProperty, pPropertyType, pParent));
        }
Пример #22
0
#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
        public async Task RestoreGridState <T>(MGrid <T> pGrid)
        {
            try
            {
                var state = await mPersistService.GetValueAsync <MGridState>(pGrid);

                if (state == null)
                {
                    return;
                }

                pGrid.SelectRow(state.SelectedRow);

                if (pGrid.Pager != null)
                {
                    if (state.Page != null)
                    {
                        pGrid.Pager.CurrentPage = Math.Max(1, state.Page.Value);
                    }
                    if (state.PageSize != null)
                    {
                        pGrid.Pager.PageSize = Math.Max(1, state.PageSize.Value);
                    }
                }

                pGrid.FilterInstructions = state.FilterState.Select(filterState =>
                {
                    var column = pGrid.ColumnsList.FirstOrDefault(c => c.Identifier == filterState.ColumnIdentifier);

                    if (column == null || !(column is IMGridPropertyColumn propc))
                    {
                        return(null);
                    }

                    IMPropertyInfo pi = pGrid.PropertyInfos[propc];

                    object value = null;

                    if (filterState.ReferencedId != null && column.GetType().Name == typeof(MGridComplexPropertyColumn <object, object>).Name)
                    {
                        value = GetReferencedValue(pGrid, column, propc.PropertyType, filterState.ReferencedId);
                    }
                    else
                    {
                        var jsone = filterState.Value as JsonElement?;

                        try
                        {
                            value = jsone?.ToObject(pi.PropertyType);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }

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

                    return(new FilterInstruction()
                    {
                        Value = value,
                        GridColumn = column,
                        PropertyInfo = pi
                    });
                }).Where(f => f != null).ToList();

                pGrid.SortInstructions = state.SorterState.Select(s =>
                {
                    var column = pGrid.ColumnsList.FirstOrDefault(c => c.Identifier == s.ColumnIdentifier);

                    if (column == null || !(column is IMGridPropertyColumn propc))
                    {
                        return(null);
                    }

                    IMPropertyInfo pi = pGrid.PropertyInfos[propc];

                    return(new SortInstruction()
                    {
                        GridColumn = propc,
                        Direction = s.Direction,
                        Index = s.Index,
                        PropertyInfo = pi,
                        Comparer = column.GetComparer()
                    });
                }).Where(s => s != null).ToList();

                await pGrid.SetFilterRowVisible(state.IsFilterRowVisible);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }
        }
Пример #23
0
        public static IMPropertyInfo GetIMPropertyInfo(Type pObjectType, string pProperty, Type pPropertyType, IMPropertyInfo pParent = null)
        {
            if (typeof(IDictionary <string, object>).IsAssignableFrom(pObjectType))
            {
                return(GetMPropertyExpandoInfo(pObjectType, pProperty, pPropertyType, pParent));
            }

            return(GetMPropertyInfo(pObjectType, pProperty, pParent));
        }
        public static Expression GetMemberExpression(this IMPropertyInfo pPropertyInfo, ParameterExpression param)
        {
            if (typeof(IDictionary <string, object>).IsAssignableFrom(param.Type))
            {
                if (pPropertyInfo.Parent != null)
                {
                    throw new System.NotImplementedException();
                }

                var p = Expression.Convert(param, typeof(IDictionary <string, object>));

                var expKey = Expression.Constant(pPropertyInfo.Name);

                var containsMi = typeof(IDictionary <string, object>).GetMethod("ContainsKey");

                var exprContains = Expression.Call(p, containsMi, expKey);

                var exprGet = Expression.Property(p, "Item", expKey);

                Expression expGetConvert;

                if (pPropertyInfo.PropertyType == typeof(string))
                {
                    expGetConvert = Expression.Call(exprGet, "ToString", Type.EmptyTypes);
                }
                else
                {
                    expGetConvert = Expression.Convert(exprGet, pPropertyInfo.PropertyType);
                }

                var ifnull = Expression.Condition(exprContains, expGetConvert, Expression.Default(pPropertyInfo.PropertyType));

                return(ifnull);
            }

            MemberExpression propertyExpr = null;

            if (pPropertyInfo.Parent != null)
            {
                var parents = GetParents(pPropertyInfo);

                foreach (var entry in parents)
                {
                    if (propertyExpr == null)
                    {
                        propertyExpr = Expression.Property(param, entry.Name);
                    }
                    else
                    {
                        propertyExpr = Expression.Property(propertyExpr, entry.Name);
                    }
                }

                propertyExpr = Expression.Property(propertyExpr, pPropertyInfo.Name);
            }
            else
            {
                propertyExpr = Expression.Property(param, pPropertyInfo.Name);
            }

            return(propertyExpr);
        }
Пример #25
0
        public static void AppendComplexType <T, TProperty>(RenderTreeBuilder pBuilder, IMPropertyInfo pPropertyInfo, T pModel, Guid pId, IMForm pParent, MComplexPropertyField <TProperty> pComplexField,
                                                            MFormGridContext pGridContext)
        {
            if (pComplexField.Template == null)
            {
                ShowNotSupportedType(pBuilder, pPropertyInfo, pModel, pId);
                return;
            }

            TProperty value = (TProperty)pPropertyInfo.GetValue(pModel);

            var context = new MComplexPropertyFieldContext <TProperty>
            {
                Row              = pModel,
                InputId          = pId.ToString(),
                FormId           = pParent.Id.ToString(),
                Form             = pParent,
                Value            = value,
                MFormGridContext = pGridContext,

                ValueChanged = RuntimeHelpers.CreateInferredEventCallback <TProperty>(pParent, async __value =>
                {
                    pPropertyInfo.SetValue(pModel, __value);
                    await pParent.OnInputValueChanged(pComplexField, pPropertyInfo, __value);
                }, value),

                ValueExpression = GetValueExpression <TProperty>(pPropertyInfo, pModel)
            };

            pBuilder.AddContent(263, pComplexField.Template?.Invoke(context));

            if (pParent.EnableValidation)
            {
                pBuilder.OpenComponent <ValidationMessage <TProperty> >(236);
                pBuilder.AddAttribute(237, "For", context.ValueExpression);
                pBuilder.CloseComponent();
            }
        }
Пример #26
0
        public static void AppendInput <T>(RenderTreeBuilder pBuilder, IMPropertyInfo pPropertyInfo, object pModel, Guid pId, IMForm pParent, bool pIsInFilterRow, IMField pField, bool pUpdateOnInput)
        {
            try
            {
                if (!IsTypeSupported(typeof(T)) || IsPropertyHolderNull(pPropertyInfo, pModel))
                {
                    ShowNotSupportedType(pBuilder, pPropertyInfo, pModel, pId);
                    return;
                }

                T   value = default(T);
                var val   = pPropertyInfo.GetValue(pModel);

                if (val != null)
                {
                    value = (T)ReflectionHelper.ChangeType(val, typeof(T));
                }

                Type tType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);

                bool isReadOnly = pPropertyInfo.IsReadOnly || pPropertyInfo.GetCustomAttribute <ReadOnlyAttribute>() != null;

                var restrictValues = pPropertyInfo.GetCustomAttribute <RestrictValuesAttribute>();

                if (typeof(T) == typeof(bool?) || tType.IsEnum || restrictValues != null)
                {
                    pBuilder.OpenComponent <MSelect <T> >(0);
                    if (pIsInFilterRow)
                    {
                        pBuilder.AddAttribute(10, "NullValueDescription", "\u200b");
                    }
                }
                else if (mNumberTypes.Contains(tType))
                {
                    if (pUpdateOnInput)
                    {
                        pBuilder.OpenComponent <InputNumberOnInput <T> >(0);
                    }
                    else
                    {
                        pBuilder.OpenComponent <InputNumber <T> >(0);
                    }
                }
                else if (tType == typeof(DateTime) || tType == typeof(DateTimeOffset))
                {
                    if (pPropertyInfo.GetCustomAttribute <TimeAttribute>() != null)
                    {
                        pBuilder.OpenComponent <InputTime <T> >(0);
                    }
                    else if (pPropertyInfo.GetCustomAttribute <DateTimeAttribute>() != null)
                    {
                        pBuilder.OpenComponent <InputDateTime <T> >(0);
                    }
                    else
                    {
                        pBuilder.OpenComponent <InputDate <T> >(0);
                    }
                }
                else if (typeof(T) == typeof(bool))
                {
                    pBuilder.OpenComponent <MInputCheckbox>(0);
                }
                else if (tType == typeof(Guid))
                {
                    pBuilder.OpenComponent <InputGuid <T> >(0);
                }
                else if (tType == typeof(Type))
                {
                    pBuilder.OpenComponent <InputType>(0);
                }
                else
                {
                    if (pPropertyInfo.GetCustomAttribute <TextAreaAttribute>() != null)
                    {
                        pBuilder.OpenComponent <InputTextArea>(0);
                    }
                    else
                    {
                        pBuilder.OpenComponent <InputText>(0);
                    }
                }

                if (pPropertyInfo.GetCustomAttribute <PasswordAttribute>() != null)
                {
                    pBuilder.AddAttribute(33, "type", "password");
                }

                if (pField.AdditionalAttributes != null)
                {
                    pBuilder.AddMultipleAttributes(17, pField.AdditionalAttributes
                                                   .Where(a => a.Key != Extensions.MFORM_IN_TABLE_ROW_TD_STYLE_ATTRIBUTE)
                                                   .Where(a => a.Key != nameof(IMGridColumn))
                                                   .ToDictionary(a => a.Key, a => a.Value));
                }

                //      pBuilder.SetUpdatesAttributeName(pPropertyInfo.Name);

                pBuilder.AddAttribute(1, "id", pId);
                pBuilder.AddAttribute(2, "Value", value);

                pBuilder.AddAttribute(129, "form", pParent.Id);

                pBuilder.AddAttribute(23, "ValueChanged", RuntimeHelpers.CreateInferredEventCallback <T>(pParent, async __value =>
                {
                    await InvokeValueChanged(pParent, pPropertyInfo, pField, pModel, __value);
                }, value));

                if (pUpdateOnInput && !mNumberTypes.Contains(tType))
                {
                    pBuilder.AddAttribute(23, "oninput", EventCallback.Factory.Create <ChangeEventArgs>(pParent, async a =>
                    {
                        object value = a.Value;
                        value        = ReflectionHelper.ChangeType(value, typeof(T)); //maybe the TryParseValueFromString method of the input is better?
                        await InvokeValueChanged(pParent, pPropertyInfo, pField, pModel, value);
                    }));
                }

                pBuilder.AddAttribute(23, "onkeyup", EventCallback.Factory.Create <KeyboardEventArgs>(pParent, (a) =>
                {
                    pParent.OnInputKeyUp(a, pPropertyInfo);
                }));

                var valueExpression = GetValueExpression <T>(pPropertyInfo, pModel);

                pBuilder.AddAttribute(4, "ValueExpression", valueExpression);

                string cssClass = "m-form-control";

                if (isReadOnly)
                {
                    pBuilder.AddAttribute(33, "disabled", string.Empty);
                    pBuilder.AddAttribute(33, "IsDisabled", true);
                }

                pBuilder.AddAttribute(10, "class", cssClass);
                // pBuilder.SetUpdatesAttributeName(pPropertyInfo.Name); <- new code generator will add this, but I don't know why

                if (restrictValues != null)
                {
                    foreach (var allowedValue in restrictValues.AllowedValues)
                    {
                        if (typeof(T) != typeof(string) && !typeof(T).IsAssignableFrom(allowedValue.GetType()))
                        {
                            throw new Exception($"Allowed value {allowedValue} does not implement property type {typeof(T).AssemblyQualifiedName}");
                        }
                    }

                    IEnumerable <T> options;

                    if (typeof(T) == typeof(string))
                    {
                        options = restrictValues.AllowedValues.Select(v => (T)(object)v.ToString()).ToArray();
                    }
                    else
                    {
                        options = restrictValues.AllowedValues.Cast <T>().ToArray();
                    }

                    pBuilder.AddAttribute(10, "Options", options);
                }
                else if (typeof(T) == typeof(bool?))
                {
                    IEnumerable <bool?> options = new bool?[] { true, false };
                    pBuilder.AddAttribute(10, "Options", options);
                }

                pBuilder.CloseComponent();

                if (pParent.EnableValidation)
                {
                    pBuilder.OpenComponent <ValidationMessage <T> >(60);
                    pBuilder.AddAttribute(61, "For", valueExpression);
                    pBuilder.CloseComponent();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw;
            }
        }
Пример #27
0
        private static IOrderedQueryable <TSource> PerformOperation(IQueryable <TSource> source, IMPropertyInfo pField, MethodInfo mi, object pComparer)
        {
            if (typeof(IDictionary <string, object>).IsAssignableFrom(typeof(TSource)))
            {
                Expression <Func <TSource, object> > keySelector = v => ((IDictionary <string, object>)v)[pField.Name];
                var method2 = mi.MakeGenericMethod(new[] { typeof(TSource), typeof(object) });

                if (pComparer == null)
                {
                    return((IOrderedQueryable <TSource>)method2.Invoke(null, new object[] { source, keySelector }));
                }

                return((IOrderedQueryable <TSource>)method2.Invoke(null, new object[] { source, keySelector, pComparer }));
            }

            var param  = Expression.Parameter(typeof(TSource), "p");
            var prop   = pField.GetMemberExpression(param);
            var exp    = Expression.Lambda(prop, param);
            var method = mi.MakeGenericMethod(new[] { typeof(TSource), prop.Type });

            if (pComparer == null)
            {
                return((IOrderedQueryable <TSource>)method.Invoke(null, new object[] { source, exp }));
            }

            return((IOrderedQueryable <TSource>)method.Invoke(null, new object[] { source, exp, pComparer }));
        }
Пример #28
0
        private static Cell GetPropertyColumnCell <T>(IMGridObjectFormatter <T> pFormatter, T rowData, IMGridPropertyColumn popcolumn, IMPropertyInfo iprop)
        {
            Cell cell;

            if (iprop.PropertyType == typeof(DateTime) || iprop.PropertyType == typeof(DateTime?))
            {
                var datetime = iprop.GetValue(rowData) as DateTime?;
                cell = CreateDateCell(datetime);
            }
            else if (iprop.PropertyType == typeof(int) || iprop.PropertyType == typeof(int?))
            {
                var    value    = iprop.GetValue(rowData) as int?;
                string strvalue = value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;
                cell = CreateNumberCell(strvalue);
            }
            else if (iprop.PropertyType == typeof(long) || iprop.PropertyType == typeof(long?))
            {
                var    value    = iprop.GetValue(rowData) as long?;
                string strvalue = value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;
                cell = CreateNumberCell(strvalue);
            }
            else if (iprop.PropertyType == typeof(float) || iprop.PropertyType == typeof(float?))
            {
                var    value    = iprop.GetValue(rowData) as float?;
                string strvalue = value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;
                cell = CreateNumberCell(strvalue);
            }
            else if (iprop.PropertyType == typeof(double) || iprop.PropertyType == typeof(double?))
            {
                var    value    = iprop.GetValue(rowData) as double?;
                string strvalue = value.HasValue ? value.Value.ToString(CultureInfo.InvariantCulture) : string.Empty;
                cell = CreateNumberCell(strvalue);
            }
            else
            {
                string cellValue = pFormatter.FormatPropertyColumnValue(popcolumn, iprop, rowData);
                cell = CreateTextCell(cellValue ?? string.Empty);
            }

            return(cell);
        }
Пример #29
0
        private static IOrderedQueryable <TSource> PerformOperation(IQueryable <TSource> source, IMPropertyInfo pField, MethodInfo mi, object pComparer)
        {
            var param  = Expression.Parameter(typeof(TSource), "p");
            var prop   = pField.GetMemberExpression(param);
            var exp    = Expression.Lambda(prop, param);
            var method = mi.MakeGenericMethod(new[] { typeof(TSource), prop.Type });

            if (pComparer == null)
            {
                return((IOrderedQueryable <TSource>)method.Invoke(null, new object[] { source, exp }));
            }

            return((IOrderedQueryable <TSource>)method.Invoke(null, new object[] { source, exp, pComparer }));
        }
Пример #30
0
        public static void AppendComplexType <T, TProperty>(RenderTreeBuilder pBuilder, IMPropertyInfo pPropertyInfo, T pModel, Guid pId, IMForm pParent, MComplexPropertyField <T, TProperty> pComplexField,
                                                            MFormGridContext pGridContext)
        {
            if (pComplexField.Template == null)
            {
                ShowNotSupportedType(pBuilder, pPropertyInfo, pModel, pId, pParent);
                return;
            }

            MComplexPropertyFieldContext <TProperty> context = new MComplexPropertyFieldContext <TProperty>();

            TProperty value = (TProperty)pPropertyInfo.GetValue(pModel);

#pragma warning disable BL0005 // Component parameter should not be set outside of its component.
            context.Row              = pModel;
            context.InputId          = pId;
            context.Value            = value;
            context.MFormGridContext = pGridContext;

            context.ValueChanged = RuntimeHelpers.CreateInferredEventCallback <TProperty>(pParent, async __value =>
            {
                pPropertyInfo.SetValue(pModel, __value);
                await pParent.OnInputValueChanged(pComplexField, pPropertyInfo, __value);
            }, value);

            context.ValueExpression = GetValueExpression <TProperty>(pPropertyInfo, pModel);

#pragma warning restore BL0005 // Component parameter should not be set outside of its component.

            pBuilder.AddContent(42, pComplexField.Template?.Invoke(context));
        }