TypeAs() public static method

Creates a UnaryExpression that represents an explicit reference or boxing conversion where null is supplied if the conversion fails.
/// or is null.
public static TypeAs ( Expression expression, Type type ) : UnaryExpression
expression Expression An to set the property equal to.
type Type A to set the property equal to.
return UnaryExpression
示例#1
0
        /// <summary>
        ///     Create a lambda to receive a property value
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        private Delegate CreateValueGetter(PropertyInfo property)
        {
            ParameterExpression parameter = Expression.Parameter(GetType(), "i");
            UnaryExpression     cast      = Expression.TypeAs(Expression.Property(parameter, property), typeof(object));

            return(Expression.Lambda(cast, parameter).Compile());
        }
示例#2
0
 private Expression Evaluate(Expression e)
 {
     if (e.NodeType == ExpressionType.Constant || e.NodeType == ExpressionType.Default)
     {
         return e;
     }
     try
     {
         if (e.Type != typeof (void))
         {
             var eval = e.TypeAs(typeof (object));
             var lambda = Expression.Lambda<Func<object>>(eval);
             var func = lambda.Compile();
             return Expression.Constant(func(), e.Type);
         }
         else
         {
             var lambda = Expression.Lambda<Action>(e);
             var action = lambda.Compile();
             action();
             return Expression.Default(typeof (void));
         }
     }
     catch
     {
         // Don't eval if catched something =\
         return base.Visit(e);
     }
 }
        private UnaryExpression UnaryExpression(
            ExpressionType nodeType, System.Type type, JObject obj)
        {
            var operand = this.Prop(obj, "operand", this.Expression);
            var method  = this.Prop(obj, "method", this.Method);

            switch (nodeType)
            {
            case ExpressionType.ArrayLength: return(Expr.ArrayLength(operand));

            case ExpressionType.Convert: return(Expr.Convert(operand, type, method));

            case ExpressionType.ConvertChecked: return(Expr.ConvertChecked(operand, type, method));

            case ExpressionType.Decrement: return(Expr.Decrement(operand, method));

            case ExpressionType.Increment: return(Expr.Increment(operand, method));

            case ExpressionType.IsFalse: return(Expr.IsFalse(operand, method));

            case ExpressionType.IsTrue: return(Expr.IsTrue(operand, method));

            case ExpressionType.Negate: return(Expr.Negate(operand, method));

            case ExpressionType.NegateChecked: return(Expr.NegateChecked(operand, method));

            case ExpressionType.Not: return(Expr.Not(operand, method));

            case ExpressionType.OnesComplement: return(Expr.OnesComplement(operand, method));

            case ExpressionType.PostDecrementAssign: return(Expr.PostDecrementAssign(operand, method));

            case ExpressionType.PostIncrementAssign: return(Expr.PostIncrementAssign(operand, method));

            case ExpressionType.PreDecrementAssign: return(Expr.PreDecrementAssign(operand, method));

            case ExpressionType.PreIncrementAssign: return(Expr.PreIncrementAssign(operand, method));

            case ExpressionType.Quote: return(Expr.Quote(operand));

            case ExpressionType.Throw: return(Expr.Throw(operand, type));

            case ExpressionType.TypeAs: return(Expr.TypeAs(operand, type));

            case ExpressionType.UnaryPlus: return(Expr.UnaryPlus(operand, method));

            case ExpressionType.Unbox: return(Expr.Unbox(operand, type));

            default: throw new NotSupportedException();
            }
        }
示例#4
0
        static GetRectangleFromTextPositionAction GenerateGetRectangleFromTextPositionAction()
        {
            ParameterExpression textViewArgument    = Expression.Parameter(typeof(object), nameof(textViewArgument));
            ParameterExpression textPointerArgument = Expression.Parameter(typeof(TextPointer), nameof(textPointerArgument));

            UnaryExpression      textViewInterface = Expression.TypeAs(textViewArgument, TextViewInterface);
            MethodCallExpression methodCall        = Expression.Call(textViewInterface, GetRectangleFromTextPositionMethod, textPointerArgument);

            var lambda = Expression.Lambda <GetRectangleFromTextPositionAction>(
                body: methodCall,
                parameters: new[] { textViewArgument, textPointerArgument }
                );

            return(lambda.Compile());
        }
示例#5
0
        private static Exp CreateSubExpression(Exp pe, Type type, string text, FullTextSearchOptions options, bool isQueriable = false)
        {
            var texts = text.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(t => t.Trim().ToLower())
                        .Where(t => t.Length > 0)
                        .ToList();

            var properties = type.GetProperties().AsEnumerable();

            if (isQueriable)
            {
                properties = properties.GetMappedProperties();
            }

            Exp predicateBody = null;

            foreach (var prop in properties)
            {
                //Check if we can use this property in Search
                if (options == null || options.Filter == null || options.Filter.Invoke(prop))
                {
                    var paramExp = Exp.Property(pe, prop);

                    if (prop.PropertyType == typeof(string) || prop.PropertyType == typeof(int) ||
                        prop.PropertyType == typeof(int?))
                    {
                        Exp notNullExp = null;
                        if (prop.PropertyType == typeof(string))
                        {
                            Exp nullConst = Exp.Constant(null, typeof(string));
                            notNullExp = Exp.NotEqual(paramExp, nullConst);
                        }

                        Exp toStringExp = paramExp;
                        //Check if property has int type
                        if (prop.PropertyType == typeof(int?) || prop.PropertyType == typeof(int))
                        {
                            if (!isQueriable)
                            {
                                Exp toNullableIntExp = null;

                                //property should be nullable
                                if (prop.PropertyType == typeof(int))
                                {
                                    toNullableIntExp = Exp.TypeAs(paramExp, typeof(int?));
                                }

                                Exp valueExp = null;
                                if (toNullableIntExp != null)
                                {
                                    notNullExp = Exp.Property(toNullableIntExp, "HasValue");
                                    valueExp   = Exp.Property(toNullableIntExp, "Value");
                                }
                                else
                                {
                                    notNullExp = Exp.Property(paramExp, "HasValue");
                                    valueExp   = Exp.Property(paramExp, "Value");
                                }

                                notNullExp = Exp.Equal(notNullExp, Exp.Constant(true, typeof(bool)));

                                var convertToString = typeof(Convert).GetMethod("ToString", new[] { typeof(int) });
                                toStringExp = Exp.Call(convertToString, valueExp);
                            }
                            else
                            {
                                var convertToString = typeof(Convert).GetMethod("ToString", new[] { typeof(int) });
                                toStringExp = Exp.Call(convertToString, Exp.Convert(paramExp, typeof(int)));
                            }
                        }

                        Exp peLower = Exp.Call(toStringExp, typeof(string).GetMethod("ToLower", System.Type.EmptyTypes));

                        Exp conditionExp = null;
                        foreach (var txt in texts)
                        {
                            var constant    = Exp.Constant(txt, typeof(string));
                            Exp containsExp = Exp.Call(peLower, typeof(string).GetMethod("Contains", new[] { typeof(string) }), constant);
                            if (conditionExp != null)
                            {
                                conditionExp = Exp.OrElse(conditionExp, containsExp);
                            }
                            else
                            {
                                conditionExp = containsExp;
                            }
                        }

                        Exp andExp = (notNullExp != null) ? Exp.AndAlso(notNullExp, conditionExp) : conditionExp;
                        if (predicateBody != null)
                        {
                            predicateBody = Exp.OrElse(predicateBody, andExp);
                        }
                        else
                        {
                            predicateBody = andExp;
                        }
                    }

                    //If this property is't simple and the depth > 0
                    if (options != null && options.Depth != 0 &&
                        !prop.PropertyType.IsSimpleType() && !prop.PropertyType.IsEnumerable())
                    {
                        options.Depth -= 1;
                        var subExp = CreateSubExpression(paramExp, prop.PropertyType, text, options, isQueriable);
                        options.Depth += 1;

                        if (subExp != null)
                        {
                            Exp notNullExp = Exp.NotEqual(paramExp, Exp.Constant(null, typeof(object)));
                            subExp        = Exp.AndAlso(notNullExp, subExp);
                            predicateBody = (predicateBody != null) ? Exp.OrElse(predicateBody, subExp) : subExp;
                        }
                    }
                }
            }

            return(predicateBody);
        }
        static VisualStudio2017StartPage()
        {
            var uiInternalAssembly     = Assembly.Load("Microsoft.VisualStudio.Shell.UI.Internal");
            var shellFrameworkAssembly = Assembly.Load("Microsoft.VisualStudio.Shell.Framework");
            var shell15Assembly        = Assembly.Load("Microsoft.VisualStudio.Shell.15.0");

            // Start_GetTemplateChildInternal
            {
                var startType = uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.Packages.StartPage.Start");

                var frameworkElementParameter     = Expression.Parameter(typeof(object), "frameworkElement");
                var nameParameter                 = Expression.Parameter(typeof(string), "name");
                var getTemplateChildMethodGeneric = startType.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
                                                    .First(
                    m => m.Name == "GetTemplateChild" && m.IsGenericMethodDefinition)
                ;
                var getTemplateChildMethod = getTemplateChildMethodGeneric.MakeGenericMethod(typeof(object));

                Start_GetTemplateChildInternal = Expression.Lambda <Func <object, string, object> >(
                    Expression.Call(Expression.TypeAs(frameworkElementParameter, startType), getTemplateChildMethod,
                                    nameParameter),
                    frameworkElementParameter, nameParameter
                    ).Compile();
            }

            // CodeContainerProviderService_CodeContainerProviders
            {
                var codeContainerProviderServiceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.Services.CodeContainerProviderService");
                var codeContainerProvidersProperty =
                    codeContainerProviderServiceType.GetProperty("CodeContainerProviders",
                                                                 BindingFlags.Instance | BindingFlags.NonPublic);

                var codeContainerProviderServiceParameter = Expression.Parameter(typeof(object), "codeContainerProviderService");

                CodeContainerProviderService_CodeContainerProviders =
                    Expression.Lambda <Func <object, object> >(
                        Expression.Property(Expression.TypeAs(codeContainerProviderServiceParameter, codeContainerProviderServiceType), codeContainerProvidersProperty),
                        codeContainerProviderServiceParameter
                        ).Compile();
            }

            // NewProjectsListViewModel_New
            var newProjectsListViewModelType =
                uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.NewProjectsListViewModel");
            {
                var asyncServiceProviderType = shellFrameworkAssembly.GetType("Microsoft.VisualStudio.Shell.IAsyncServiceProvider");

                var messageDialogInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.StartPage.NewProject.IMessageDialog");
                var messageDialogType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.StartPage.NewProject.MessageDialog");
                var messageDialogConstructor = messageDialogType.GetConstructor(new Type[0]);

                var newProjectTelemetryLoggerInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.Telemetry.INewProjectTelemetryLogger");
                var newProjectTelemetryLoggerType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.Telemetry.NewProjectTelemetryLogger");
                var newProjectTelemetryLoggerConstructor = newProjectTelemetryLoggerType.GetConstructor(new Type[0]);

                var newProjectsListViewModelConstructor =
                    newProjectsListViewModelType.GetConstructor(new[]
                {
                    asyncServiceProviderType,
                    messageDialogInterfaceType,
                    newProjectTelemetryLoggerInterfaceType
                });

                var asyncServiceProviderParameter = Expression.Parameter(typeof(object),
                                                                         "asyncServiceProvider");

                NewProjectsListViewModel_New = Expression.Lambda <Func <object, object> >(
                    Expression.New(newProjectsListViewModelConstructor,
                                   Expression.TypeAs(asyncServiceProviderParameter, asyncServiceProviderType),
                                   Expression.New(messageDialogConstructor),
                                   Expression.New(newProjectTelemetryLoggerConstructor)
                                   ),
                    asyncServiceProviderParameter
                    ).Compile();
            }

            // NewProjectsListViewModel_SetMoreTemplatesTextRemoteSettingIfAvailableAsync
            {
                var viewModelParameter = Expression.Parameter(typeof(object), "viewModel");

                var setMoreTemplatesTextRemoteSettingIfAvailableAsync =
                    newProjectsListViewModelType.GetMethod("SetMoreTemplatesTextRemoteSettingIfAvailableAsync",
                                                           BindingFlags.Instance | BindingFlags.NonPublic);

                NewProjectsListViewModel_SetMoreTemplatesTextRemoteSettingIfAvailableAsync =
                    Expression.Lambda <Func <object, Task> >(
                        Expression.Call(Expression.TypeAs(viewModelParameter, newProjectsListViewModelType),
                                        setMoreTemplatesTextRemoteSettingIfAvailableAsync),
                        viewModelParameter
                        ).Compile();
            }

            // NewProjectsListViewModel_LoadRecentTemplatesAsync
            {
                var viewModelParameter = Expression.Parameter(typeof(object), "viewModel");

                var loadRecentTemplatesAsync = newProjectsListViewModelType.GetMethod("LoadRecentTemplatesAsync",
                                                                                      BindingFlags.Instance | BindingFlags.NonPublic);

                NewProjectsListViewModel_LoadRecentTemplatesAsync = Expression.Lambda <Func <object, Task> >(
                    Expression.Call(Expression.TypeAs(viewModelParameter, newProjectsListViewModelType),
                                    loadRecentTemplatesAsync),
                    viewModelParameter
                    ).Compile();
            }

            // CodeContainerListViewModel_New
            {
                var codeContainerStorageManagerInterfaceType =
                    shellFrameworkAssembly.GetType("Microsoft.VisualStudio.Shell.CodeContainerManagement.ICodeContainerStorageManager");

                var codeContainerStorageManagerFactoryType =
                    shell15Assembly.GetType("Microsoft.VisualStudio.Shell.CodeContainerManagement.CodeContainerStorageManagerFactory");
                var codeContainerStorageManagerFactoryConstructor =
                    codeContainerStorageManagerFactoryType.GetConstructor(new[] { typeof(System.IServiceProvider) });
                var codeContainerStorageManagerFactoryCreate = codeContainerStorageManagerFactoryType.GetMethod(
                    "Create", BindingFlags.Instance | BindingFlags.Public);

                var codeContainerAccessManagerInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.ICodeContainerAccessManager");
                var codeContainerAccessManagerType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.CodeContainerAccessManager");
                var codeContainerAccessManagerConstructor =
                    codeContainerAccessManagerType.GetConstructor(new[] { typeof(System.IServiceProvider) });

                var removalPromptProviderInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.IRemovalPromptProvider");
                var removalPromptProviderType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.RemovalPromptProvider");
                var removalPromptProviderConstructor =
                    removalPromptProviderType.GetConstructor(new[] { typeof(System.IServiceProvider) });

                var codeContainerIconMonikerProviderInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.ICodeContainerIconMonikerProvider");
                var codeContainerIconMonikerProviderType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.CodeContainerIconMonikerProvider");
                var codeContainerIconMonikerProviderConstuctor =
                    codeContainerIconMonikerProviderType.GetConstructor(new[] { typeof(System.IServiceProvider) });

                var timeCategoryProviderInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.ITimeCategoryProvider");
                var timeCategoryProviderType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.TimeCategoryProvider");
                var timeCategoryProviderInstanceProperty = timeCategoryProviderType.GetProperty("Instance",
                                                                                                BindingFlags.Static | BindingFlags.Public);

                var codeContainerTelemetryLoggerInterfaceType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.ICodeContainerTelemetryLogger");
                var codeContainerTelemetryLoggerType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.CodeContainerTelemetryLogger");
                var          codeContainerTelemetryLoggerConstuctor      = codeContainerTelemetryLoggerType.GetConstructors().First();
                var          codeContainerTelemetryLoggerConstuctorParam = codeContainerTelemetryLoggerConstuctor.GetParameters().FirstOrDefault();
                Expression[] newCodeContainerTelemetryLoggerParams;
                if (codeContainerTelemetryLoggerConstuctorParam == null)
                {
                    newCodeContainerTelemetryLoggerParams = new Expression[0];
                }
                else if (codeContainerTelemetryLoggerConstuctorParam.ParameterType.FullName == "Microsoft.VisualStudio.PlatformUI.CodeContainerScenario")
                {
                    var startPageScenario = codeContainerTelemetryLoggerConstuctorParam.ParameterType.GetField("StartPage").GetValue(null);
                    newCodeContainerTelemetryLoggerParams = new Expression[]
                    {
                        Expression.Constant(startPageScenario)
                    };
                }
                else
                {
                    newCodeContainerTelemetryLoggerParams = new Expression[0];
                    Debug.Fail("unclear what parameter is expected, needs update");
                }

                var codeContainerListViewModelType =
                    uiInternalAssembly.GetType("Microsoft.VisualStudio.PlatformUI.CodeContainerListViewModel");
                var codeContainerListViewModelConstructor = codeContainerListViewModelType.GetConstructor(new[]
                {
                    codeContainerStorageManagerInterfaceType,
                    codeContainerAccessManagerInterfaceType,
                    removalPromptProviderInterfaceType,
                    codeContainerIconMonikerProviderInterfaceType,
                    timeCategoryProviderInterfaceType,
                    codeContainerTelemetryLoggerInterfaceType
                });

                var serviceProviderParameter = Expression.Parameter(typeof(System.IServiceProvider), "serviceProvider");

                CodeContainerListViewModel_New = Expression.Lambda <Func <System.IServiceProvider, object> >(
                    Expression.New(codeContainerListViewModelConstructor, // new CodeContainerListViewModel(
                                                                          // new CodeContainerStorageManagerFactory(serviceProvider).Create()
                                   Expression.Call(
                                       Expression.New(codeContainerStorageManagerFactoryConstructor, serviceProviderParameter),
                                       codeContainerStorageManagerFactoryCreate),

                                   // new CodeContainerAccessManager(serviceProvider)
                                   Expression.New(codeContainerAccessManagerConstructor, serviceProviderParameter),

                                   // new RemovalPromptProvider(serviceProvider)
                                   Expression.New(removalPromptProviderConstructor, serviceProviderParameter),

                                   // new CodeContainerIconMonikerProvider(serviceProvider)
                                   Expression.New(codeContainerIconMonikerProviderConstuctor, serviceProviderParameter),

                                   // TimeCategoryProvider.Instance
                                   Expression.Property(null, timeCategoryProviderInstanceProperty),

                                   // new CodeContainerTelemetryLogger()
                                   Expression.New(codeContainerTelemetryLoggerConstuctor, newCodeContainerTelemetryLoggerParams)
                                   ),
                    serviceProviderParameter
                    ).Compile();
            }
        }
示例#7
0
 public static UnaryExpression TypeAs(Expression expression, Type type) => Expression.TypeAs(expression, type);
 public static Expression AsTypeTo(this Expression expression, Type type = null)
 => Expression.TypeAs(expression, type ?? typeof(object));