コード例 #1
0
        ///<summary>
        /// 구문 분석된 식을 나타내는 개체를 반환합니다.
        ///</summary>
        ///<returns>
        /// 구문 분석한 식을 나타내는 <see cref="T:System.Object" />입니다.
        ///</returns>
        ///<param name="expression">선언적 식의 값입니다.</param>
        ///<param name="propertyType">식에 의해 바인딩된 속성의 형식입니다.</param>
        ///<param name="context">식을 계산하는 데 필요한 컨텍스트 정보입니다.</param>
        ///<exception cref="T:System.Web.HttpException">리소스 식이 없거나 유효하지 않은 경우</exception>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            expression.ShouldNotBeWhiteSpace("expression");

            if (IsDebugEnabled)
            {
                log.Debug("표현식을 파싱합니다... expression=[{0}], propertyType=[{1}], context=[{2}]", expression, propertyType, context);
            }

            string classKey;
            string resourceKey;

            //+ 예 : <%$ ExternalResources : AssemblyName|ResourceFileName, ResourceKey %> 를 파싱한다.
            //
            StringResourceTool.ParseClassKey(expression, ',', out classKey, out resourceKey);
            var field = new ExpressionField(classKey, resourceKey);

            // 실제로 값이 있는지 검사한다.
            if (ResourceProvider.GetObject(field.ClassKey, field.ResourceKey) == null)
            {
                throw new InvalidOperationException("지정한 리소스를 찾을 수 없습니다. resource key=" + field.ResourceKey);
            }

            return(field);
        }
コード例 #2
0
        private static string GetResourceString(HttpContextBase httpContext,
                                                string expression,
                                                string virtualPath,
                                                object[] args)

        {
            ExpressionBuilderContext context = new ExpressionBuilderContext(virtualPath);

            ResourceExpressionBuilder builder = new ResourceExpressionBuilder();

            ResourceExpressionFields fields = (ResourceExpressionFields)builder
                                              .ParseExpression(expression,
                                                               typeof(string), context);


            if (!string.IsNullOrEmpty(fields.ClassKey))
            {
                return(string.Format((string)httpContext.GetGlobalResourceObject(
                                         fields.ClassKey,
                                         fields.ResourceKey,
                                         CultureInfo.CurrentUICulture),
                                     args));
            }


            return(string.Format((string)httpContext.GetLocalResourceObject(
                                     virtualPath,
                                     fields.ResourceKey,
                                     CultureInfo.CurrentUICulture),
                                 args));
        }
コード例 #3
0
        /// <summary>
        /// Parses and validates the expression data and returns a canonical type or member name,
        ///     or throws an exception if the expression is invalid.
        /// </summary>
        /// <param name="expression">
        /// The raw expression to parse.
        /// </param>
        /// <param name="propertyType">
        /// The target property type.
        /// </param>
        /// <param name="context">
        /// Contextual information for the expression builder.
        /// </param>
        /// <returns>
        /// A string representing the target type or member name for binding.
        /// </returns>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            var    parsed     = false;
            string typeName   = null;
            string memberName = null;

            if (!String.IsNullOrEmpty(expression))
            {
                var parts = expression.Split(',');
                if (parts.Length > 0 && parts.Length < 3)
                {
                    switch (parts.Length)
                    {
                    case 1:
                        typeName = parts[0].Trim();
                        break;

                    case 2:
                        typeName   = parts[0].Trim();
                        memberName = parts[1].Trim();
                        break;
                    }

                    parsed = true;
                }
            }

            if (!parsed)
            {
                throw new HttpException($"Invalid Reflect expression - '{expression}'.");
            }

            // now validate the expression fields
            return(ValidateExpression(typeName, memberName));
        }
コード例 #4
0
        /// <summary>
        /// Returns an object that represents the parsed expression.
        /// </summary>
        /// <param name="expression">The value of the declarative expression.</param>
        /// <param name="propertyType">The type of the property bound to by the expression.</param>
        /// <param name="context">Contextual information for the evaluation of the expression.</param>
        /// <returns>An Object that represents the parsed expression</returns>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            var lsr = new LocaleStringResource();

            lsr.ResourceName = expression;
            return(lsr);
        }
コード例 #5
0
        /// <summary>
        /// Gets a resource fields.
        /// </summary>
        /// <param name="expression">The expression.</param>
        /// <param name="virtualPath">The virtual path.</param>
        /// <returns>The resource fields.</returns>
        private static ResourceExpressionFields GetResourceFields(string expression, string virtualPath)
        {
            var context = new ExpressionBuilderContext(virtualPath);
            var builder = new ResourceExpressionBuilder();

            return((ResourceExpressionFields)builder.ParseExpression(expression, typeof(string), context));
        }
コード例 #6
0
        /// <summary>
        /// Returns an object that represents the parsed expression.
        /// </summary>
        /// <param name="expression">The value of the declarative expression.</param>
        /// <param name="propertyType">The type of the property bound to by the expression.</param>
        /// <param name="context">Contextual information for the evaluation of the expression.</param>
        /// <returns>An Object that represents the parsed expression</returns>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            var lsr = new CustomerAction();

            lsr.SystemKeyword = expression;
            return(lsr);
        }
コード例 #7
0
 internal void ParseExpression(ExpressionBuilderContext context)
 {
     if (((this.Expression != null) && (this.ExpressionPrefix != null)) && (this.ExpressionBuilder != null))
     {
         this._parsedExpressionData = this.ExpressionBuilder.ParseExpression(this.Expression, base.Type, context);
     }
 }
    public override CodeExpression GetCodeExpression(
        BoundPropertyEntry entry, object parsedData,
        ExpressionBuilderContext context)
    {
        // entry.Expression is the number string
        // (minus the RandomNumber: prefix).
        if (!entry.Expression.Contains(","))
        {
            throw new ArgumentException("Must include two numbers separated by a comma.");
        }
        else
        {
            // Get the two numbers.
            string[] numbers = entry.Expression.Split(',');

            if (numbers.Length != 2)
            {
                throw new ArgumentException("Only include two numbers.");
            }
            else
            {
                int lowerLimit, upperLimit;
                if (Int32.TryParse(numbers[0], out lowerLimit) &&
                    Int32.TryParse(numbers[1], out upperLimit))
                {
                    // So far all the operations have been performed in
                    // normal code. That's because the two numbers are
                    // specified in the expression, and so they won't
                    // change each time the page is requested.
                    // However, the random number should be allowed to
                    // change each time, so you need to switch to CodeDOM.

                    // Get a reference to the class that has the GetRandomNumber() method.
                    // (It's the class where this code is executing.)
                    CodeTypeReferenceExpression typeRef = new CodeTypeReferenceExpression(this.GetType());

                    // Define the parameters that need to be passed to GetRandomNumber().
                    CodeExpression[] methodParameters = new CodeExpression[2];
                    methodParameters[0] = new CodePrimitiveExpression(lowerLimit);
                    methodParameters[1] = new CodePrimitiveExpression(upperLimit);

                    // Define the code expression that invokes GetRandomNumber().
                    CodeMethodInvokeExpression methodCall = new CodeMethodInvokeExpression(typeRef, "GetRandomNumber", methodParameters);

                    // The commented lines allow you to perform casting.
                    // It's not required in this example (as GetRandomNumber returns a string),
                    // but it's a common expression builder technique.
                    //Type type = entry.DeclaringType;
                    //PropertyDescriptor descriptor = TypeDescriptor.GetProperties(type)[entry.PropertyInfo.Name];
                    //return new CodeCastExpression(descriptor.PropertyType, methodCall);

                    return(methodCall);
                }
                else
                {
                    throw new ArgumentException("Use valid integers.");
                }
            }
        }
    }
コード例 #9
0
        /// <summary>
        /// Gets the code expression.
        /// </summary>
        /// <param name="entry">
        /// The entry.
        /// </param>
        /// <param name="parsedData">
        /// The parsed data.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A CodeExpression.
        /// </returns>
        public override CodeExpression GetCodeExpression(
            BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            var typeName     = BeforeLast(entry.Expression, ".");
            var propertyName = AfterLast(entry.Expression, ".");

            return(new CodePrimitiveExpression(PropertyLength(typeName, propertyName)));
        }
コード例 #10
0
// ============================================================================
        public override CodeExpression GetCodeExpression(
            BoundPropertyEntry entry,
            object parsedData,
            ExpressionBuilderContext context
            )
        {
            return(new CodeSnippetExpression(entry.Expression));
        }
コード例 #11
0
        // Parse the expression, and store the resulting object
        internal void ParseExpression(ExpressionBuilderContext context)
        {
            if (Expression == null || ExpressionPrefix == null || ExpressionBuilder == null)
            {
                return;
            }

            _parsedExpressionData = ExpressionBuilder.ParseExpression(Expression, Type, context);
        }
コード例 #12
0
 public override System.CodeDom.CodeExpression GetCodeExpression(
     BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     CodeTypeReferenceExpression targetClass =
         new CodeTypeReferenceExpression(typeof(ExpressionBuilderIdentity));
     string targetMethod = "GetIdentity";
     CodeExpression methodParameter =
         new CodePrimitiveExpression(entry.Expression.Trim());
     return new CodeMethodInvokeExpression(
         targetClass, targetMethod, methodParameter);
 }
コード例 #13
0
    //<!--</snippet3>-->

    //<!--<snippet4>-->
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
                                                     object parsedData, ExpressionBuilderContext context)
    {
        Type type1 = entry.DeclaringType;
        PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(type1)[entry.PropertyInfo.Name];

        CodeExpression[] expressionArray1 = new CodeExpression[3];
        expressionArray1[0] = new CodePrimitiveExpression(entry.Expression.Trim());
        expressionArray1[1] = new CodeTypeOfExpression(type1);
        expressionArray1[2] = new CodePrimitiveExpression(entry.Name);
        return(new CodeCastExpression(descriptor1.PropertyType, new CodeMethodInvokeExpression(new
                                                                                               CodeTypeReferenceExpression(base.GetType()), "GetEvalData", expressionArray1)));
    }
コード例 #14
0
        /// <summary>
        /// When overridden in a derived class, returns code that is used during page execution to obtain the evaluated expression.
        /// </summary>
        /// <param name="entry">
        /// The object that represents information about the property bound to by the expression.
        /// </param>
        /// <param name="parsedData">
        /// The object containing parsed data as returned by <see cref="M:System.Web.Compilation.ExpressionBuilder.ParseExpression(System.String,System.Type,System.Web.Compilation.ExpressionBuilderContext)"/>.
        /// </param>
        /// <param name="context">
        /// Contextual information for the evaluation of the expression.
        /// </param>
        /// <returns>
        /// A <see cref="T:System.CodeDom.CodeExpression"/> that is used for property assignment.
        /// </returns>
        public override CodeExpression GetCodeExpression(
            BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            var inputParams = new CodeExpression[]
            {
                new CodePrimitiveExpression(entry.Expression.Trim()), new CodeTypeOfExpression(entry.DeclaringType),
                new CodePrimitiveExpression(entry.PropertyInfo.Name)
            };

            // Return a CodeMethodInvokeExpression that will invoke the GetRequestedValue method using the specified input parameters
            return(new CodeMethodInvokeExpression(
                       new CodeTypeReferenceExpression(this.GetType()), "Instance().GetRequestedValue", inputParams));
        }
コード例 #15
0
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            var regEx = new Regex(@"^([A-Z])\w+$");

            if (regEx.IsMatch(expression))
            {
                return(ValidateExpression(expression));
            }
            else
            {
                throw new HttpException(String.Format($"Invalid Site Expression expression - '{expression}'."));
            }
        }
        public void EvaluateExpression()
        {
            RouteTable.Routes.Clear();
            RouteTable.Routes.Add(new Route("{foo}-foo", new PageRouteHandler("~/default.aspx")));
            RouteTable.Routes.Add("bar1", new Route("{bar}-foo", new PageRouteHandler("~/bar.aspx")));
            RouteTable.Routes.Add("bar2", new Route("some-{bar}", new PageRouteHandler("~/some-bar.aspx")));

            var    bldr    = new RouteUrlExpressionBuilder();
            var    entry   = CreatePropertyEntry("foo=test", "RouteUrl");
            var    context = new ExpressionBuilderContext(new FakePage());
            object obj     = bldr.EvaluateExpression(null, entry, null, context);

            Assert.AreEqual("/test-foo", obj, "#A1");

            entry = CreatePropertyEntry("bar=test", "RouteUrl");
            obj   = bldr.EvaluateExpression(null, entry, null, context);
            Assert.AreEqual("/test-foo", obj, "#A2-1");

            entry = CreatePropertyEntry("bar=test,routename=bar2", "RouteUrl");
            obj   = bldr.EvaluateExpression(null, entry, null, context);
            Assert.AreEqual("/some-test", obj, "#A2-2");

            entry = CreatePropertyEntry("bar=test,routename=bar1", "RouteUrl");
            obj   = bldr.EvaluateExpression(null, entry, null, context);
            Assert.AreEqual("/test-foo", obj, "#A2-3");

            entry = CreatePropertyEntry("bar=test,routename=noroute", "RouteUrl");
            try
            {
                obj = bldr.EvaluateExpression(null, entry, null, context);
                Assert.Fail("#A3");
            }
            catch (ArgumentException)
            {
                // success
            }

            entry = CreatePropertyEntry("nosuchparam=test", "RouteUrl");
            obj   = bldr.EvaluateExpression(null, entry, null, context);
            Assert.IsNull(obj, "#A4");

            AssertExtensions.Throws <NullReferenceException> (() =>
            {
                bldr.EvaluateExpression(null, null, null, context);
            }, "#A5-1");

            AssertExtensions.Throws <NullReferenceException> (() =>
            {
                bldr.EvaluateExpression(null, entry, null, null);
            }, "#A5-2");
        }
コード例 #17
0
        /// <summary>
        /// Returns an object that represents the parsed expression.
        /// </summary>
        /// <param name="expression">The value of the declarative expression.</param>
        /// <param name="propertyType">The type of the property bound to by the expression.</param>
        /// <param name="context">Contextual information for the evaluation of the expression.</param>
        /// <returns>An Object that represents the parsed expression</returns>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            LocaleStringResource lsr = new LocaleStringResource();

            lsr.ResourceName = expression;
            //try
            //{
            //    lsr.LanguageID = NopContext.Current.WorkingLanguage.LanguageID;
            //}
            //catch (Exception exc)
            //{
            //}
            return(lsr);
        }
コード例 #18
0
	public override CodeExpression GetCodeExpression(
		BoundPropertyEntry entry, object parsedData,
		ExpressionBuilderContext context)
	{
		// entry.Expression is the number string
		// (minus the RandomNumber: prefix).
		if (!entry.Expression.Contains(","))
		{
			throw new ArgumentException("Must include two numbers separated by a comma.");
		}
		else
		{
			// Get the two numbers.
			string[] numbers = entry.Expression.Split(',');

			if (numbers.Length != 2)
			{
				throw new ArgumentException("Only include two numbers.");
			}
			else
			{
				int lowerLimit, upperLimit;
				if (Int32.TryParse(numbers[0], out lowerLimit) &&
					Int32.TryParse(numbers[1], out upperLimit))
				{

					// So far all the operations have been performed in
					// normal code. That's because the two numbers are
					// specified in the expression, and so they won't
					// change each time the page is requested.
					// However, the random number should be allowed to
					// change each time, so you need to switch to CodeDOM.
					Type type = entry.DeclaringType;
					PropertyDescriptor descriptor = TypeDescriptor.GetProperties(type)[entry.PropertyInfo.Name];
					CodeExpression[] expressionArray = new CodeExpression[2];
					expressionArray[0] = new CodePrimitiveExpression(lowerLimit);
					expressionArray[1] = new CodePrimitiveExpression(upperLimit); 
					return new CodeCastExpression(descriptor.PropertyType, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(base.GetType()), "GetRandomNumber", expressionArray));
				}
				else
				{
					throw new ArgumentException("Use valid integers.");
				}

			}
		}
		
	}
コード例 #19
0
        ///<summary>
        /// 리소스 파일에서 값을 반환합니다.
        ///</summary>
        ///
        ///<returns>
        /// 구문 분석한 식과 관련된 <see cref="T:System.Object" />입니다. 구문 분석한 식은 클래스 이름과 리소스 키를 포함합니다.
        ///</returns>
        ///
        ///<param name="target">
        /// 식이 포함된 개체입니다.
        /// </param>
        ///<param name="entry">
        /// 식에 의해 바인딩된 속성에 대한 정보를 나타내는 개체입니다.
        /// </param>
        ///<param name="parsedData">
        /// <see cref="ParseExpression"/> 메서드에 의해 반환된 구문 분석한 데이터가 들어 있는 개체입니다.
        ///</param>
        ///<param name="context">
        /// 식을 계산하는 데 필요한 컨텍스트 정보입니다.
        ///</param>
        public override object EvaluateExpression(object target,
                                                  BoundPropertyEntry entry,
                                                  object parsedData,
                                                  ExpressionBuilderContext context)
        {
            if (IsDebugEnabled)
            {
                log.Debug("표현식을 평가합니다... target=[{0}], entry=[{1}], parsedData=[{2}], context=[{3}]", target, entry, parsedData, context);
            }

            var field = parsedData as ExpressionField;

            Guard.Assert(field != null, "파싱된 정보가 ExpressionField 형식이 아닙니다. parseData=[{0}]", parsedData);

            return(ResourceProvider.GetObject(field.ClassKey, field.ResourceKey));
        }
コード例 #20
0
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
        object parsedData, ExpressionBuilderContext context)
    {
        // entry.Expression - строка с числом 
        // без префикса (например: "1,6").
        if (!entry.Expression.Contains(","))
        {
            throw new ArgumentException(" Должны быть указаны два числа, разделенные запятой");
        }
        else
        {
            // Получить два числа
            string[] numbers = entry.Expression.Split(',');

            if (numbers.Length != 2)
            {
                throw new ArgumentException("Должны быть указаны два числа");
            }
            else
            {
                int min, max;
                if (Int32.TryParse(numbers[0], out min) &&
                    Int32.TryParse(numbers[1], out max))
                {

                    // Получить ссылку на класс, имеющий метод GetRandomNumber(). 
                    // (Это класс, где данный код выполняется.)
                    CodeTypeReferenceExpression typeRef = new CodeTypeReferenceExpression(this.GetType());

                    // Определить параметры для GetRandomNumber().
                    CodeExpression[] methodParameters = new CodeExpression[2];
                    methodParameters[0] = new CodePrimitiveExpression(min);
                    methodParameters[1] = new CodePrimitiveExpression(max);

                    // Вернуть выражение привязки вызвав метод GetRandomNumber()
                    CodeMethodInvokeExpression methodCall = new CodeMethodInvokeExpression(
                        typeRef, "GetRandomNumber", methodParameters);
                    return methodCall;
                }
                else
                {
                    throw new ArgumentException("Должны использоваться допустимые целые числа");
                }

            }
        }
    }
コード例 #21
0
        /// <summary>
        /// Validates an DBResource expression by attempting to access resources for the expression. Page parsing will fail if the resource cannot be found.
        /// NB! Expressions are parsed at design time, and prior to compilation
        /// TODO HES Skip DB look-up to avoid DB access to be required
        /// </summary>
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "DBResourceExpressionBuilder.ParseExpression({0}, {1}, {2})", expression, propertyType, context));

            if (string.IsNullOrEmpty(expression))
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Resource.Expression_TooFewParameters, expression));
            }

            DBResourceExpressionFields fields = null;
            string classKey    = null;
            string resourceKey = null;

            string[] expParams = expression.Split(new char[] { ',' });
            if (expParams.Length > 2)
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Resource.Expression_TooManyParameters, expression));
            }
            if (expParams.Length == 1)
            {
                classKey = context.VirtualPath;

                string vp = context.VirtualPath.Remove(0, 1);
                classKey    = vp.Remove(0, vp.IndexOf('/') + 1);
                resourceKey = expParams[0].Trim();
                //throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Resource.Expression_TooFewParameters, expression));
            }
            else
            {
                classKey    = expParams[0].Trim();
                resourceKey = expParams[1].Trim();
            }

            fields = new DBResourceExpressionFields(classKey, resourceKey);

            DBResourceExpressionBuilder.EnsureResourceProviderFactory();
            IResourceProvider rp = DBResourceExpressionBuilder.s_resourceProviderFactory.CreateGlobalResourceProvider(fields.ClassKey);

            object res = rp.GetObject(fields.ResourceKey, CultureInfo.InvariantCulture);

            if (res == null)
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Resource.RM_ResourceNotFound, fields.ResourceKey));
            }
            return(fields);
        }
コード例 #22
0
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
                                                         object parsedData, ExpressionBuilderContext context)
        {
            var componentType   = entry.DeclaringType;
            var expressionArray = new CodeExpression[3]
            {
                new CodePrimitiveExpression(entry.Expression.Trim()),
                new CodeTypeOfExpression(componentType),
                new CodePrimitiveExpression(entry.Name)
            };

            var descriptor = TypeDescriptor.GetProperties(componentType)
                             [entry.PropertyInfo.Name];

            return(new CodeCastExpression(descriptor.PropertyType,
                                          new CodeMethodInvokeExpression(
                                              new CodeTypeReferenceExpression(GetType()),
                                              "GetCdnUrl", expressionArray)));
        }
コード例 #23
0
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "ExternalResourceExpressionBuilder.ParseExpression({0}, {1}, {2})", expression, propertyType, context));

            if (string.IsNullOrEmpty(expression))
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Localization.ResourceExpressionTooFewParameters, expression));
            }

            ExternalResourceExpressionFields fields = null;
            string classKey    = null;
            string resourceKey = null;

            var expParams = expression.Split(new char[] { ',' });

            if (expParams.Length > 2)
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Localization.ResourceExpressionTooManyParameters, expression));
            }
            if (expParams.Length == 1)
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Localization.ResourceExpressionTooFewParameters, expression));
            }
            else
            {
                classKey    = expParams[0].Trim();
                resourceKey = expParams[1].Trim();
            }

            fields = new ExternalResourceExpressionFields(classKey, resourceKey);

            EnsureResourceProviderFactory();
            var rp = s_resourceProviderFactory.CreateGlobalResourceProvider(fields.ClassKey);

            var res = rp.GetObject(fields.ResourceKey, CultureInfo.InvariantCulture);

            if (res == null)
            {
                throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentUICulture, Properties.Localization.ResourceNotFound, fields.ResourceKey));
            }
            return(fields);
        }
コード例 #24
0
        public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
        {
            if (string.IsNullOrEmpty(expression))
            {
                throw new ArgumentException("Too few parameters");
            }

            ResourceExpressionFields fields = null;
            string classKey    = null;
            string resourceKey = null;

            string[] expParams = expression.Split(new char[] { ',' });
            if (expParams.Length > 2)
            {
                throw new ArgumentException("Too many parameters");
            }
            if (expParams.Length == 1)
            {
                throw new ArgumentException("Too few parameters");
            }
            else
            {
                classKey    = expParams[0].Trim();
                resourceKey = expParams[1].Trim();
            }

            fields = new ResourceExpressionFields(classKey, resourceKey);

            EnsureResourceProviderFactory();
            IResourceProvider rp = _resourceProviderFactory.CreateGlobalResourceProvider(fields.ClassKey);

            object res = rp.GetObject(fields.ResourceKey, CultureInfo.InvariantCulture);

            if (res == null)
            {
                throw new ArgumentException("Resource not found");
            }
            return(fields);
        }
        public void GetCodeExpression()
        {
            var            bldr    = new RouteUrlExpressionBuilder();
            var            entry   = CreatePropertyEntry("foo=test", "RouteUrl");
            var            context = new ExpressionBuilderContext(new FakePage());
            CodeExpression expr;

            AssertExtensions.Throws <NullReferenceException> (() =>
            {
                expr = bldr.GetCodeExpression(null, "data", context);
            }, "#A1-1");

            expr = bldr.GetCodeExpression(entry, null, context);
            Assert.IsNotNull(expr, "#A2");

            expr = bldr.GetCodeExpression(entry, "data", null);
            Assert.IsNotNull(expr, "#A3");

            expr = bldr.GetCodeExpression(entry, null, null);
            Assert.IsNotNull(expr, "#A4-1");
            Assert.AreEqual(typeof(CodeMethodInvokeExpression), expr.GetType(), "#A4-2");

            var invoke = expr as CodeMethodInvokeExpression;

            Assert.AreEqual(typeof(CodeTypeReferenceExpression), invoke.Method.TargetObject.GetType(), "#A4-3");

            var tref = invoke.Method.TargetObject as CodeTypeReferenceExpression;

            Assert.AreEqual("System.Web.Compilation.RouteUrlExpressionBuilder", tref.Type.BaseType, "#A4-4");
            Assert.AreEqual("GetRouteUrl", invoke.Method.MethodName, "#A4-5");

            Assert.AreEqual(2, invoke.Parameters.Count, "#A5-1");
            Assert.AreEqual(typeof(CodeThisReferenceExpression), invoke.Parameters [0].GetType(), "#A5-2");
            Assert.AreEqual(typeof(CodePrimitiveExpression), invoke.Parameters [1].GetType(), "#A5-3");

            var pex = invoke.Parameters [1] as CodePrimitiveExpression;

            Assert.AreEqual("foo=test", pex.Value, "#A5-4");
        }
コード例 #26
0
 public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     if (!entry.Expression.Contains(","))
     {
         throw new ArgumentException(
         "Must include two numbers separated by a comma.");
     }
     else
     {
         // Get the two numbers.
         string[] numbers = entry.Expression.Split(',');
         if (numbers.Length != 2)
         {
             throw new ArgumentException("Only include two numbers.");
         }
         else
         {
             int lowerLimit, upperLimit;
             if (Int32.TryParse(numbers[0], out lowerLimit) &&
             Int32.TryParse(numbers[1], out upperLimit))
             {
                 // Get a reference to the class that has the
                 // GetRandomNumber() method.
                 // (It's the class where this code is executing.)
                 CodeTypeReferenceExpression typeRef = new
                 CodeTypeReferenceExpression(this.GetType());
                 CodeExpression[] methodParameters = new CodeExpression[2];
                 methodParameters[0] = new CodePrimitiveExpression(lowerLimit);
                 methodParameters[1] = new CodePrimitiveExpression(upperLimit);
                 return new CodeMethodInvokeExpression(typeRef, "GetRandomNumber", methodParameters);
             }
             else
             {
                 throw new ArgumentException("Use valid integers.");
             }
         }
     }
 }
コード例 #27
0
        ///<summary>
        /// 페이지 실행 중에 계산할 코드 식을 반환합니다.
        /// </summary>
        ///<returns>
        /// 메서드를 호출하는 <see cref="T:System.CodeDom.CodeExpression" />입니다.
        ///</returns>
        ///<param name="entry">개체의 속성 이름입니다.</param>
        ///<param name="parsedData">식의 구문 분석된 값입니다.</param>
        ///<param name="context">컨트롤 또는 페이지에 대한 속성입니다.</param>
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData,
                                                         ExpressionBuilderContext context)
        {
            var field = parsedData as ExpressionField;

            field.ShouldNotBeNull("filed");

            if (IsDebugEnabled)
            {
                log.Debug("Get code expression for NO Compiled ASP.NET page. entry=[{0}], parsedData=[{1}], context=[{2}]", entry,
                          parsedData, context);
            }

            // GetGlobalResourceObject를 호출한다.
            //
            return
                (new CodeMethodInvokeExpression(
                     new CodeTypeReferenceExpression(typeof(WebResourceExpressionBuilder)),
                     "GetGlobalResourceObject",
                     new CodePrimitiveExpression(field.ClassKey),
                     new CodePrimitiveExpression(field.ResourceKey)
                     ));
        }
コード例 #28
0
        private static string GetResourceString(HttpContextBase httpContext, string expression, string virtualPath, object[] args)
        {
            var context = new ExpressionBuilderContext(virtualPath);
            var builder = new ResourceExpressionBuilder();
            var fields  = (ResourceExpressionFields)builder.ParseExpression("LanguageResource, " + expression, typeof(string), context);

            string text;

            if (!string.IsNullOrEmpty(fields.ClassKey))
            {
                text = (string)httpContext.GetGlobalResourceObject(fields.ClassKey, fields.ResourceKey, CultureInfo.CurrentUICulture);
            }
            else
            {
                text = (string)httpContext.GetLocalResourceObject(virtualPath, fields.ResourceKey, CultureInfo.CurrentUICulture);
            }

            if (String.IsNullOrEmpty(text))
            {
                return(String.Empty);
            }

            return(String.Format(text, args));
        }
コード例 #29
0
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            CodeTypeReferenceExpression targetClass = new CodeTypeReferenceExpression(typeof(PxImageExpressionBuilder));
            const string   targetMethod             = "GetImagePath";
            CodeExpression methodParameter          = new CodePrimitiveExpression(entry.Expression.Trim());

            return(new CodeMethodInvokeExpression(targetClass, targetMethod, methodParameter));
        }
コード例 #30
0
 public override System.CodeDom.CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData,
         ExpressionBuilderContext context)
 {
     return new CodeCastExpression("Int64",
         new CodePrimitiveExpression(parsedData));
 }
	public virtual object EvaluateExpression(object target, System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {}
	public virtual System.CodeDom.CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) {}
	// Methods
	public virtual object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context) {}
コード例 #34
0
 public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
 {
     return expression;
 }
コード例 #35
0
 public override object ParseExpression(string expression, Type propertyType, ExpressionBuilderContext context)
 {
     return(new StringsExpressionEditorSheet(expression, null));
 }
コード例 #36
0
        public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            StringsExpressionEditorSheet stringsExpressionEditorSheet = (StringsExpressionEditorSheet)parsedData;

            return(new CodeMethodInvokeExpression(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(stringsExpressionEditorSheet.Group.StringsType), stringsExpressionEditorSheet.StringID), "ToString", new CodeExpression[0]));
        }
コード例 #37
0
        public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
        {
            StringsExpressionEditorSheet stringsExpressionEditorSheet = (StringsExpressionEditorSheet)parsedData;

            return(stringsExpressionEditorSheet.Evaluate());
        }
コード例 #38
0
 public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     return(new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression(typeof(ComponentExpressionBuilder)),
                "GetComponent",
                new CodePrimitiveExpression(entry.Expression.Trim()),
                new CodeTypeOfExpression(new CodeTypeReference(entry.PropertyInfo.PropertyType))));
 }
コード例 #39
0
 public override CodeExpression GetCodeExpression(System.Web.UI.BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     return(new CodeMethodInvokeExpression(
                new CodeTypeReferenceExpression(typeof(LabelExpressionBuilder)),
                "GetLabel",
                new CodePrimitiveExpression(entry.Expression.Trim()),
                new CodePrimitiveExpression(context.VirtualPath)));
 }
コード例 #40
0
 public override object EvaluateExpression(object target, BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
 {
     return GetEvalData(entry.Expression);
 }
コード例 #41
0
    public override System.CodeDom.CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context)
    {
        CodeExpression[] expressionArray1 = new CodeExpression[1] { new CodePrimitiveExpression(entry.Expression.Trim()) };

        return new CodeMethodInvokeExpression(new CodeTypeReferenceExpression(base.GetType()), "GetEvalData", expressionArray1);
    }