ASP.NET Tutorial/Data Binding/ExpressionBuilders

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

RandomNumber Expression Builder

using System;
using System.Web.UI;
using System.Web.rupilation;
using System.CodeDom;
using System.ruponentModel;
public class RandomNumberExpressionBuilder : ExpressionBuilder
{
  public static string GetRandomNumber(int lowerLimit, int upperLimit)
  {
    Random rand = new Random();
    int randValue = rand.Next(lowerLimit, upperLimit + 1);
    return randValue.ToString();
  }
  public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, object parsedData,ExpressionBuilderContext context){
    if (!entry.Expression.Contains(","))
    {
      throw new ArgumentException("Must include two numbers separated by a comma.");
    }
    else
    {
      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)){
          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.");
        }
      }
    }
  }
}
File: Web.config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <appSettings/>
  <connectionStrings>
    <add name="Northwind" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI"/>
  </connectionStrings>
  
  <system.web>
   <compilation debug="true">
        <expressionBuilders>
          <add expressionPrefix="RandomNumber" type="RandomNumberExpressionBuilder"/>
        </expressionBuilders>
    </compilation>
    <authentication mode="Windows"/>
  </system.web>
</configuration>