Other types of expressions

Source: Internet
Author: User
Tags connectionstrings
Other types of expressions
Data Binding expressions are always wrapped in the <% # And %> characters. ASP. NET 2.0 also adds
Support for different types of expressions, commonly known as $ expressions because they in1_ate
The $ character. Technically, a $ expression is a code sequence that you can add to an. ASPX page
And that will be evaluated by an expression builder when the page is rendered. The expression
Builder processes the expression and replaces it with a string value in the final HTML.
Currently, ASP. NET implements des a built-in expression builder that allows you to extract custom
Application settings and connection string information from the Web. config file. For example, if
You want to retrieve an application setting named appname from the <shortettings> portion of
Web. config file, you can use the following expression:
<Asp: literal runat = "server" text = "<% $ appsettings: appname %>"/>
Several differences exist between $ expressions and data binding expressions:
• Data Binding expressions start with the <% # character sequence, and $ expressions use <% $.
• Unlike data binding expressions, you don't need to call the databind () method to evaluate $
Expressions. Instead, they're always evaluated when the page is rendered.
298 Chapter 9 ■ Data Binding
• Unlike data binding expressions, $ expressions can't be inserted anywhere in a page. Instead,
You need to wrap them in a control tag and use the expression result to set a control property.
That means if you just want to show the result of an expression as ordinary text, you
Need to wrap it in a literal tag (as shown in the previous example). The literal control outputs
Its text to plain, unformatted HTML.
The first part of a $ expression indicates the name of the expression builder. For example,
Appsettings: appname expression works because a dedicated appsettingsexpression builder is
Registered to handle all expressions that begin with your ettings. Similarly, ASP. NET between des
Resourceexpressionbuilder for inserting resources (see chapter 17) and a connectionstring-
Expressionbuilder that retrieves connection information from the <connectionstrings> section
Of the Web. config file. Here's an example that uses the connectionstringexpressionbuilder:
<Asp: literal runat = "server" text = "<% $ connectionstrings: northwind %>"/>
Displaying a connection string isn't that useful. But this technique becomes much more useful
When you combine it with the sqldatasource control you'll examine later in this chapter, in which
Case you can use it to quickly supply a connection string from the Web. config file:
<Asp: sqldatasource connectionstring = "<% $ connectionstrings: northwind %>".../>
Technically, $ expressions don't involve data binding. But they work in a similar way and have
Similar syntax.
Custom expression builders
One of the most innovative features of $ expressions is that you can create your own expression
Builders that plug into this framework. This is a specialized technique that, while neat, isn' t always
Practical. As you'll see, custom $ expressions make the most sense if you're developing a distinct
Feature that you want to induplicate ate into more than one web application.
For example, imagine you want a way to create a custom expression builder that allows you
Insert random numbers. You want to be able to write a tag such as this to show a random number
Between 1 and 6:
<Asp: literal runat = "server" text = "<% $ randomnumber: 1,6%>"/>
Unfortunately, creating a custom expression builder isn't quite as easy as you probably regular CT.
The problem is how the code is compiled. When you compile a page that contains an expression,
The expression evaluating the Code also needs to be compiled with it. However, you don't want
Expression to be evaluated at that point-instead, you want the expression to be reevaluated each
Time the page is requested. To make this possible, your expression builder needs to generate
Generic segment of code that performs the appropriate task.
The technology that enables this is codedom (Code Document Object Model)-a model
For dynamically generating code constructs. Every expression builder extends des a method named
Getcodeexpression () that uses codedom to generate the code needed for the expression. In other
Words, if you want to create a randomnumberexpressionbuilder, you need to create a getcode-
Expression () method that uses codedom to generate a segment of code for calculating random
Numbers. Clearly, it's not that straightforward-and for anything but trivial code, it's quite lengthy.
All expression builders must derive from the base expressionbuilder class (which is found in
The system. Web. Compilation namespace). Here's how you might declare an expression builder
Random Number Generation:
Public class randomnumberexpressionbuilder: expressionbuilder
{...}
Chapter 9 ■ Data Binding 299
To simplify life, it helps to create a static method that performs the task you need (in this case,
Random Number Generation ):
Public static string getrandomnumber (INT lowerlimit, int upperlimit)
{
Random Rand = new random ();
Int randvalue = Rand. Next (lowerlimit, upperlimit + 1 );
Return randvalue. tostring ();
}
The advantage of this approach is that when you use codedom, you simply generate
Single line of code needed to call the getrandomnumber () method (rather than the code needed
To generate the random number ).
Now, you need to override the getcodeexpression () method. This is the method that ASP. NET
Callwhen it finds an expression that's mapped to your expression Builder (while compiling
Page). At this point, you need to examine the expression, verify no errors are present, and then
Generate the code for calculating the expression result (using a codeexpression object from
System. codedom namespace). This dynamically generated piece of code will be executed every
Time the page is requested.
Here's the first part of the getcodeexpression () method:
Public override codeexpression getcodeexpression (boundpropertyentry entry,
Object parseddata, expressionbuildercontext context)
{
// Entry. expression is the number string
// Without the prefix (for example "1, 6 ").
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 stored med in normal code. That's because the two numbers
Are specified in the expression, so they won't change each time the page is requested. However,
Random Number shoshould be allowed to change each time, so now you need to switch to codedom
Create a dynamic segment of code. The basic strategy is to construct a codeexpression that callthe
Static getrandomnumber () method.
300 Chapter 9 ■ Data Binding
Here's the rest of the Code:
...
// Specify the class.
Type type = entry. declaringtype;
Propertydescriptor descriptor =
Typedescriptor. getproperties (type) [entry. propertyinfo. Name];
// Define the parameters.
Codeexpression [] expressionarray = new codeexpression [2];
Expressionarray [0] = new codeprimitiveexpression (lowerlimit );
Expressionarray [1] = new codeprimitiveexpression (upperlimit );
// Define the expression that invokes the method.
Return new codecastexpression (descriptor. propertytype,
New codemethodinvokeexpression (
New codetypereferenceexpression (base. GetType ()),
"Getrandomnumber", expressionarray ));
}
Else
{
Throw new argumentexception ("use valid integers .");
}
}
}
}
Now you can copy this expression builder to the app_code folder (or compile it separately and
Place the DLL assembly in the bin folder ).
Finally, to use this expression builder in a web application, You need to register it in
Web. config file and map it to the prefix you want to use:
<Configuration xmlns = "http://schemas.microsoft.com/.NetConfiguration/v2.0">
<System. Web>
<Compilation DEBUG = "true">
<Expressionbuilders>
<Add expressionprefix = "randomnumber"
Type = "randomnumberexpressionbuilder"/>
</Expressionbuilders>
</Compilation>
...
</System. Web>
</Configuration>
Now you can use expressions such as <% $ randomnumber: 1,6%>. These expressions are
Automatically handled by your custom expression builder, which generates a new random number
In the desired range each time the page runs.
The possibilities for expression builders are intriguing. They enable extends extensibility scenarios,
And third-party tools are sure to take advantage of this feature. However, if you intend to use
An expression in a single web application or in a single web page, you'll find it easier to just use
Data Binding expression that calla custom method in your page. For example, you cocould create
A Data Binding expression like this:
<% # Getrandomnumber (1, 6) %>
Chapter 9 ■ Data Binding 301
And add a matching public or protected method in your page, like this:
Protected string getrandomnumber (INT lowerlimit, int upperlimit)
{...}
Just remember to call page. databind () to evaluate your expression.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.