Comparison of Silverlight lightweight queries

Source: Internet
Author: User

Translated from: infoq, Author: Wu lei.

The essence of information systems is information input, query, computing, storage, and output operations, just as finance is essentially a value exchange across time and space, although the information system has a variety of "derivatives ",
Without information, the form of information is inseparable: structured and unstructured data, and structured data has become a necessity for information systems since the 1990s s, such as database objects and XML tagging.
Data and object objects can all be considered structured data. In particular, the ability to process structured data in enterprise-level applications is often a key indicator of technology selection. We will discuss it in depth in this article.
The Data Query capability of Silverlight.

I mentioned in the article "the importance of Silverlight" That Silverlight integrates with advanced query languages such as LINQ and has a variety of data processing and query methods, allowing developers to have more choices in data processing. Next we will use a case study to learn about the powerful data processing capabilities of Silverlight on the client.

Case demo address: http://space.silverlightchina.net/xpeter/Demo/SLQueryTest.html

Source codeAddress: http://space.silverlightchina.net/xpeter/Demo/code/SLQueryTest.rar

Case requirement description and analysis

Case requirement: "find objects that meet the conditions in a large number of object objects ".

There is only one sentence to describe this requirement, just like the plain words of the demand speaker in the real project. However, behind this sentenceProgramDesigners do a lot of things. First, they need to construct a large amount of object data. What we need to do isEntity classAnd then passData GeneratorClass to produce a large amount of data. Secondly, we need to design and implement the SilverlightQuery ClassFinally, we need to output the result set to the page. By refining nouns, we design the following class diagrams:

After the program starts, the app class constructs a mainpage instance and automatically constructs 0.1 million pieces of customer data. After the data construction is complete, you can search for qualified customers through various query methods.
User records are displayed in the "query result" DataGrid Control. The query time consumption information is displayed in the "query efficiency" text box (in this case, the query condition is that the customer name contains a string by default.
Method ).

Entity class and Generator

The object testmodel is designed based on the customer model, including attributes such as name, gender, birthday, and age.

The datagenerator class of the data generator class uses the createbycnt <t> method to generate data. The data generator is often used in performance testing and penetration testing of large data volumes in enterprise-level development. In this case, it is used to simulate real customer data.

Query Method implementation class

In order to achieve componentized reuse and interface and logic separation, I put the specific implementation of various Silverlight query methods in the queryworker class. Below are several lightweight query methods that Silverlight applies to clients:

      1. Direct Query

You can use the for or foreach loop to directly search for the object set, locate the records whose names contain the input characters, and add them to the result set. This method is applicable to most applications that specify search criteria during development.CodeAs follows:

 
Publicvoid directquery (string querystr, list <testmodel> data, reflist <Object> result) {foreach (VAR t in data) {If (T. name. contains (querystr) {result. add (t) ;}// the notification is complete. Find invokequerycomplete (eventargs. empty );}
      1. Reflection Query Method

When the entity attributes in the search condition need to be determined at run time, the direct search method is not flexible enough. Therefore, you need to use the C # reflection method to obtain the object attributes specified at run time.
Propertyinfo, and then use the getvalue method to check whether the property value meets the requirements for containing incoming characters. The code for implementing reflectquery in this case is as follows:

Publicvoid reflectquery (string querystr, list <testmodel> data, reflist <Object> result) {// obtain the specified property information propertyinfo vpropertyinfo = typeof (testmodel ). getproperty ("name"); foreach (VAR t in data) {// determines whether the property value meets the search condition if (vpropertyinfo. getvalue (T, null ). tostring (). contains (querystr) {result. add (t) ;}// the notification is complete. Find invokequerycomplete (eventargs. empty );}
      1. LINQ Query Method

LINQ is a proprietary declarative language in the. NET Framework. developers can use this SQL-like language to quickly build data logic, avoiding the complexity of the original object-oriented operations.
Cheng, I believe that the expressions in the LINQ language are divided into three levels: the first level is a LINQ expression similar to SQL; the second level is a Lambda expression; the third level is based on
Expression Tree of the expression class, which is the innermost layer of LINQ and is also the core of the dynamic implementation of LINQ. The code for implementing linqquery in this case is as follows:

Publicvoid linqquery (string querystr, list <testmodel> data, reflist <Object> result) {// defines the delayed execution of the LINQ query expression var linqquery = from T in data where T. name. contains (querystr) Select t; // The tolist method executes the query and returns result = linqquery. cast <Object> (). tolist (); // notification completion lookup invokequerycomplete (eventargs. empty );}

If lambda expressions are used, Data. Where (t =>
T. Name. Contains (querystr) filter conditions, consistent with the meaning of the directly written query expression. The two query methods described later are actually different implementations of LINQ.
But it is more flexible than writing an expression directly.

      1. Expression Tree Query Method

Compared with the LINQ query method, Expression Tree query is more complex but more flexible. The expression tree can be used to dynamically construct query statements at runtime. It is also the basis for implementing dynamic LINQ. Let's take a look at the code of the Expression Tree query implementation method expressionquery in this case:

Publicvoid expressionquery (string querystr, list <testmodel> data, reflist <Object> result) {iqueryable <testmodel> custs = data. asqueryable (); // construct the parameter expression it parameterexpression it = expression. parameter (typeof (testmodel), "it"); // construct the constant expression of the querystr character to be filtered expression funparam = expression. constant (querystr); // obtain the name attribute information of the IT parameter to implement the lambda expression: it. name expression name = expression. property (it, typeof (testmodel ). getproperty ("name"); // obtain the contains method information of the string class methodinfo containsfun = typeof (string ). getmethod ("contains", newtype [1] {typeof (string)}); // call the contains method to implement the lambda expression: it. name. contains (querystr) Expression Filter = expression. call (name, containsfun, newexpression [1] {funparam}); // construct a Lambda expression: It => it. name. contains (querystr) expression Pred = expression. lambda (filter, it); // call the where method to implement the lambda expression: custs. where (IT => it. name. contains (querystr) expression expr = expression. call (typeof (queryable), "where", newtype [] {typeof (testmodel)}, expression. constant (custs), Pred); // the query iqueryable <testmodel> query = custs. provider. createquery <testmodel> (expr); // call the getenumerator method of the query interface to obtain the inumerator enumerator = query. getenumerator (); // call the movenext method of the iterator to execute the query result while (enumerator. movenext () {var o = enumerator. current; result. add (o);} // notification completion lookup invokequerycomplete (eventargs. empty );}

This may cause readers to wonder why the query that can be completed with only one line of code should be written in such a complicated way? Looking back at the Code, it is not difficult to find the parameters used in the query.
Numbers, attributes, and methods are all "passed in" expressions in the form of strings, which enables dynamic query during runtime. In fact, the execution of expression-defined statements is completed at runtime, which is equivalent
The eval method similar to Javascript is to call the interpreter again at runtime to explain and execute the input string.
State.

      1. Dynamic LINQ Query Method

In fact, developers do not need to design complex expression trees to implement dynamic queries. From. Net 3.5 onwards, Microsoft provides a dynamic LINQ Query Class Library dynamic.
Query
Library. With this class library, developers can pass in the where method as a string Lambda expression as a parameter. Of course, the cost of this operation is the syntax security risk of passing in the string. Zheng
Because of this, Microsoft has not preset the dynamic LINQ Query Class Library to the Silverlight basic class library. Considering this is of great significance to real-world development, the author independently encapsulates the dynamic LINQ box
And provides a dynamic LINQ statement input box with the smart sensing function. This allows you to write a LINQ query statement while the Silverlight application is running and dynamically execute the query.

In this case, the dynamiclinqquery code of dynamic LINQ is as follows:

Publicvoid dynamiclinqquery (string querystr, list <testmodel> data, reflist <Object> result) {try {var qtms = data. asqueryable (); // pass the input query statement directly to the where method var dynamicquery = qtms. where (querystr); Result = dynamicquery. cast <Object> (). tolist ();} catch (exception e) // syntax risks exist in the dynamic where clause {// error _ errormessage = "your query statement encountered the following problems:" + E. message; invokequeryerror (eventargs. empty);} // find the notification completed by invokequerycomplete (eventargs. empty );}

Now all the methods of the query class are ready. Now you need to call the query method on the UI Layer and display the query results.

Query call and result feedback

Since all query methods have a unified input parameter structure, the call is almost the same, here, I will take dynamic LINQ query as an example to introduce the code implementation of query calls and result feedback at the UI Layer.

In this case, the mainpage of the UI Layer undertakes all interaction tasks, and the page contains a search class instance queryworker. Because the Search Class asynchronously triggers the completion event after the search task is completed, you need to delegate the queryworker query completion event when constructing the mainpage. The Code is as follows:

Queryworker. onquerycomplete + = (sender1, E1) => dispatcher. begininvoke (queryworker_onquerycomplete );

After loading the page, click the query button and the event will be uniformly delegated to the doquery method:

 
Btndlinq. Click + = newroutedeventhandler (doquery );

In the doquery method, different query methods are called Based on Different buttons. The calling code for dynamic LINQ query is as follows:

 
Querystr = isiquery. words; queryworker. dynamiclinqquery (querystr, testdata, ref queryresults );

After the queryworker instance completes the dynamic query, it will trigger a notification event to call back and forth the preceding method queryworker_onquerycomplete. This method records the time consumed and displays the result in the DataGrid Control. The Code is as follows:

Void queryworker_onquerycomplete () {long usetime = environment. tickcount-starttickcount; TBR. TEXT = "->" + String. format ("in the {0} million data records, {1} found {2} records, time: {3} millisecond \ n", testdata. count/10000.0, currquery, queryresults. count, usetime) + TBR. text. replace ("->", ""); tbrscnt. TEXT = string. format ("{0} records in total", queryresults. count); DG. itemssource = queryresults ;}

Although you only need to specify the data source in the DataGrid data binding, you also need to translate the data in the page definition. For example, the Gender in this case exists in the data instance in the form of code.
, But it is displayed as an image in the DataGrid. This is exactly the conversion between the datagridtemplatecolumn and the bound data in the template column provided by Silverlight.
Converter converter is implemented. I will not introduce it here. You can study the source code of this case on your own.

Silverlight query performance comparison

It compares the performance of millions of data records under the same query conditions. The test platform is a common 2G dual-core notebook with win7 operating system and ie9 browser. From the results, in addition to efficiency comparison
Low reflection mode. Other query methods can query millions of data in 0.3 seconds, which has good performance. The Expression Tree query method only takes 218 milliseconds, which is the most efficient. This is because the Expression Tree
It is already the core layer of LINQ and does not need to be converted too much, so it is faster to execute. What's even more gratifying is that even the most flexible dynamic LINQ is not significant in terms of performance loss
It is completely feasible to use dynamic LINQ in Silverlight enterprise applications. In fact, I often use dynamic LINQ in my current projects to implement complex queries, or even rule-based
.

Silverlight query performance Outlook

At the recent mix11 conference, Microsoft had demonstrated the powerful 3D rendering capability and richer commercial application support of silverlight5, but did not show the extended version of LINQ.
In fact, more Silverlight enterprise-level application developers hope to add parallel frameworks similar to Plinq in future versions, so that they can use parallel computing to further improve the query efficiency of clients.
Rate. I believe that Windows Phone 7 and windows
8. These Microsoft Core Competitiveness products use Silverlight as the presentation layer technology of "thin UI". It is not too long for parallel frameworks to be put into the Silverlight basic framework.

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.