Welcome to MSDN Blogs Sign in | Join | Help

ASP.NET Dynamic Data Overview

This post is a preview of the up-coming documentation on MSDN. The links in this post will point to the new topics when available.

Please, send us your feedback.

ASP.NET Dynamic Data lets you create extensible data-driven Web applications by inferring at runtime the appearance and behavior of data entities from the database schema and deriving UI behavior from it.

Dynamic Data supports scaffolding, which is a way to automatically generate Web pages for each table in the database. Scaffolding lets you create a functional Web site for viewing and editing data based on the schema of the data. You can easily customize scaffolding elements or create new ones to override the default behavior.

You can also enable dynamic behavior in existing or new Web applications without using scaffolding. In that case, you specify how and when Dynamic Data should infer UI elements from the data source without using scaffolding for the entire Web site.

Dynamic Data Architecture

Dynamic Data obtains data schema information or metadata from a data model that represents database entities as common language runtime (CLR) types.

The following illustration shows the Dynamic Data architecture. The dashed-line boxes represent technologies that are defined in the CLR but that are used by Dynamic Data.

Dynamic Data Architecture

Using Dynamic Data in ASP.NET ApplicationsPage TemplatesEntity TemplatesField TemplatesFilter TemplatesCustom Field TemplatesCustom Page TemplatesPresentation LayerData LayerDL CustomizationLINQ to SQLEntity FrameworkASP.NET Dynamic Data Overview

As the illustration shows, Dynamic Data architecture contains the following layers:

  • Presentation layer, which contains templates such as page, entity, field, and filter templates that are used to create the UI for displaying and editing data entities.

  • Data layer, which contains the data model that represents the database entities as CLR types.

  • Data source mapping layer, which contains elements that are part of the CLR but are used by Dynamic Data. These elements are technologies such as LINQ to SQL and ADO.NET Entity Framework that are used to generate data models.

These layers together provide the scaffolding that lets Dynamic Data generate Web pages for each table in the database.

Presentation Layer Elements

This section provides a quick overview of the Dynamic Data elements that are used to create the UI for displaying and editing data entities. For more information, see ASP.NET Dynamic Data Scaffolding.

Page Templates

Page templates are Web pages that render data from any table in the database. Dynamic Data includes page templates for different views of data, such as listing a table (List view), displaying master/detail tables (Details view), and editing data (Edit view). By default, Dynamic Data uses only a List view page template. When you create a Dynamic Data Web project, Visual Studio adds a DynamicData\PageTemplates folder to the project. This folder contains the default page templates. You can modify the default page templates or create new ones in order to specify how tables are rendered.

Entity Templates

Entity templates are user controls that let you customize the layout for a whole table (that is, for a data row). Entity templates give you better control over table layout than page templates.

When you create a Dynamic Data Web project, Visual Studio adds a DynamicData\EntityTemplates folder to the project. This folder contains the default entity templates. There are templates for display, edit, and insert operations. The default entity templates show data in two columns, using a label for the field name and an appropriate control for the field value.  You can modify default entity templates to change the appearance and behavior of data rows for the whole site.

Entity templates are included in the Details.aspx, Insert.aspx and Update.aspx page templates and any custom pages. Entity templates in turn use field templates to render the actual data.

For more information about how to use entity templates, see the related topics listed in the Dynamic Data Scenarios section.

Field Templates

Field templates are user controls that render the UI for individual data fields. By default, Dynamic Data selects a field template for a field based on the data type of the field. For example, to display Boolean data, Dynamic Data uses the Boolean field template; to display text data, Dynamic Data uses a text field template; and so on. There is typically one field template to display data, and a different template that lets users enter or edit field values.

Dynamic Data selects the appropriate field template to use based on the data field type. When you create a Dynamic Data Web project, Visual Studio adds a DynamicData\FieldTemplates folder to the project. This folder contains the default field templates. You can modify the default field templates or create new ones in order to specify how individual data fields are rendered.

Filter Templates

Filter templates are user controls that render the UI for data filtering, which lets the user choose the table rows to display based on a selected column value. Dynamic Data enables you to use page markup to create the UI for data filtering for a column you identify. If a filter template does not exist for that column type, you can create a custom one and instruct Dynamic Data to use it when it creates the UI. You can also create page markup to let Dynamic Data automatically generate the UI for any column type for which a default filter template exists. By default, Dynamic Data provides Boolean, foreign-key, and enumeration filter templates.

When you create a Dynamic Data Web project, Visual Studio adds a DynamicData\FilterTemplates folder to the project. This folder contains the default filter templates.

Data Layer Elements

ASP.NET Dynamic supports LINQ to SQL and ADO.NET Entity Framework data models. Dynamic Data uses these types to query the database and to perform create, read, update, and delete (CRUD) operations. The data models also provide an easy way to integrate custom data validation and business logic rules.

When you create a new project in Visual Studio 2010, you can select the LINQ to SQL Classes or the ADO.NET Entity Data Model template. This selection determines the type of model that is used by the project. Dynamic Data scaffolding can support only one of the data model type in the same project.

At run time, Dynamic Data automatically extracts metadata information from the data model, such as data field properties. From this information, it infers how to create UI for displaying and editing data. To render the UI, it uses the following information:

  • Information about associations between tables is used to display foreign-key columns and navigate between tables.

  • Data-type information is used to add validation for a data field. For example, null column information can be used to determine whether a data field is required. Length information can be used to restrict the maximum length of user's text input.

Using Dynamic Data

Dynamic Data scaffolding supports the following design options:

  • Create a Web site using scaffolding. You can create a basic Web application that uses ASP.NET Dynamic Data with minimal coding. When scaffolding is enabled, ASP.NET analyzes the data model and generates Web pages dynamically based on the metadata information. These auto-generated Web pages provide CRUD capabilities for each table. For more information, see Walkthrough: Creating a New Dynamic Data Web Site Using Scaffolding.

  • Add dynamic behavior to individual data-bound controls (such as the GridView and ListView controls) in an existing ASP.NET Web site. You can enable Dynamic Data in ASP.NET data-bound controls without using scaffolding and a data model. This enables you to use Dynamic Data features such as run-time datafield validation, in-memory page templates which do not require scaffolding, and System.ComponentModel.DataAnnotations attributes to customize data fields. For more information, see Walkthrough: Using Dynamic Data in ASP.NET Data-Bound Controls.

  • Add Dynamic Data features to an existing or new ASP.NET Web site. You can create a Web site and include Dynamic Data features without using scaffolding. You can also customize the Dynamic Data Web site capabilities. A defining aspect of ASP.NET Dynamic Data is that it can infer at runtime the appearance and behavior of data fields from the database schema. This information is then used in the data-bound controls, with the support of templates, to eliminate the need for repetitive code in the presentation layer. For more information, see Walkthrough: Create a Web Site that Uses Dynamic Data.

For more information about Dynamic Data scenarios, see Using ASP.NET Dynamic Data Content Map.

Customizing Dynamic Data

An important Dynamic Data feature is customization. Customization options can be grouped into the following categories:

  • Customizing general behavior. You can modify how Dynamic Data performs tasks that do not rely on a specific database schema. You make these modifications in the presentation layer and then use them for any number of projects. This type of customization lets you define consistent behavior for any data schema, without redefining the behavior every time that you add or modify a data entity. The customization is performed by modifying the default templates or by creating custom templates to display and interact with the database. For more information, see ASP.NET Dynamic Data Presentation Layer Customization.

  • Customizing schema-specific behavior. You can customize Dynamic Data behavior for individual tables or fields based on the data model or database schema. In this case, the customization is specific to the instance of the data model. For example, you can customize the UI for an individual data field; you can create a custom page template or use entity templates to render an individual table. You can apply custom metadata to specific data fields to modify their appearance and behavior by using the System.ComponentModel.DataAnnotations attributes. You can also customize the behavior of an application, which lets you create custom validation and bind tables or fields in the data model to specific templates. For more information, see ASP.NET Dynamic Data Model Customization.

A Visual Studio project with source code is available at this location: Download LINQ to SQL version.

Dynamic Data Scenarios

The following is a selection of Dynamic Data scenarios with topics that describe them and related examples.

Scenario Topic Description and Examples
Enabling dynamic behavior in data-bound controls in an existing Web site Walkthrough: Using Dynamic Data in ASP.NET Data-Bound Controls This approach is useful if you have an existing Web site and you want to use validation and templates with minimal coding.

A Visual Studio project with source code is available for this scenario: Download LINQ to SQL version.

Customizing appearance and behavior of an individual table How to: Customize Data Field Appearance and Behavior in a Dynamic Data Control This approach lets you customize an individual table. It is a schema specific customization that is performed by creating a custom Web page to render the table.
Customizing appearance and behavior of an individual data field. How to: Customize Data Field Appearance and Behavior in the Data Model This approach is used to customize an individual data field. It is a schema-specific in which you create a custom field template.

See a run-time code example of this feature: Run.

See a video that shows this feature: Watch.

Customizing appearance and behavior associated with a data field type How to: Customize ASP.NET Dynamic Data Default Field Templates

This approach is used to customize a data field type in the whole application. It is a general behavior customization in the presentation layer in which you customize the default field templates.

See a video that shows this feature: Watch.

Customizing appearance and behavior of an individual data field by using a field template that is more specific than the default field template How to: Customize Data Field Appearance and Behavior For Non-Intrinsic Data Types in the Data Model

This approach is used to customize an individual data field . It is a schema specific customization. It is obtained by applying a field template that is more specific than the default template for the field data type. For example, you can mark a text field that contains e-mail addresses as an e-mail type.

 

Customizing the appearance and behavior of an individual table by using a custom page template How to: Customize the Layout of an Individual Table By Using a Custom Page Template This approach is used to customize an individual table. It is a schema specific customization that enables you to use Dynamic Data templates and tailor them to your specific needs
Customizing the appearance and behavior of an individual table by using custom entity templates Walkthrough: Customizing Table layout using Entity Templates

This approach is used to customize an individual table. It is a general behavior customization in which you create custom entity templates. It is an alternative to the custom page template approach and gives you a better control over the table layout.

A Visual Studio project with source code is available at this location: Download 

Customizing data field validation by using a custom validation attribute How to: Customize Data Field Validation in the Data Model Using Custom Attributes

This approach is used to customize the validation of an individual data field. It is a schema specific customization in which you apply a custom validation attribute to the data field in the data model. You use this approach when the available data-validation attributes do not satisfy your requirements.

See a run-time code example of this feature: Run

Customizing data field validation by using attributes, or by customizing method that process field changes, or by customizing the validation event handler How to: Customize Data Field Validation in the Data Model

This approach is used to customize the validation of an individual data field. It is a schema specific customization that is obtained for example by overriding the OnValidate event handler.

Run an online example of this feature: Run

Filtering table rows to display in a child table by using a foreign-key value from a parent table Walkthrough: Filtering Rows in Tables with a Parent-Child Relationship

This approach is used to filter the table rows to display based on a foreign-key value from a parent table.

A Visual Studio project with source code is available at this location: Download LINQ to SQL version

Walkthrough: Using Dynamic Data in ASP.NET Data-Bound Controls

This approach is useful if you have an existing Web site and you want to use validation and templates with minimal coding.

A Visual Studio project with source code is available for this scenario: Download LINQ to SQL version.

Namespace Reference

 

The following table lists the namespaces that contain the ASP.NET Dynamic Data classes.

Namespace Description
System.ComponentModel.DataAnnotations Provides attribute classes that are used to define metadata for Dynamic Data objects. The classes are used to customize dynamic data behavior.
System.Web.DynamicData Contains classes that provide the core functionality for ASP.NET Dynamic Data. These classes provide extensibility features to customize dynamic data behavior.
System.Web.DynamicData.Design Contains classes that provide design-time support for the classes in the System.Web.DynamicData namespace.

Additional Information

 

Suggestions for additional exploration include the following:

  • Understanding URL routing. For more information, see ASP.NET Routing.

  • Understanding LINQ-to-SQL Object-Relational mapping. For more information, see LINQ to SQL.

  • Understanding the ADO.NET Entity Framework. For more information, see ADO.NET Entity Framework.

Back to top

See Also

Tasks

Walkthrough: Creating a New Dynamic Data Web Site Using Scaffolding

Walkthrough: Create a Web Site that Uses Dynamic Data

Concepts

Using Dynamic Data in ASP.NET Applications

Customizing ASP.NET Dynamic Data

Other Resources

ASP.NET Dynamic Data Scaffolding

Posted by morebits | 0 Comments
Filed under:

Using Simple Bing Search over SOAP Protocol in an ASP.NET Web Application

Introduction

This walkthrough shows how to use a simple Bing search as a Web service in an ASP.NET Web application. The Bing search features are invoked by the ASP.NET Web application using SOAP protocol over HTTP.

You can also use XML and JSON to invoke the service. We'll have related examples at a later time.

This walkthrough shows you how to perform the following tasks:

  • Create a client Web application to interact with BING service.
  • Add the reference to the Bing search service.
  • Perform live search by using Bing SourceTypes.
Bing Service Background

Complex problems such as indexing, relevance logic, and hosting issues such as CPU and storage are solved in transparent way to your application by having the ability to use the BING features as a Web service. This article offers a starting point for adding the service to your application.

Remember that a Web service is a component on a Web server that a client application can call by making HTTP requests across the Web. If you want some good explanation about this subject, see this MSDN article Using ASP.NET Web Services.

By using the Bing search service you can integrate the following features in your application:

  • Retrieve information from the Internet.
  • Add advertisements to your application.
  • Improve and enhance search requests and results.
  • Find location-specific information.
  • Translate terms and blocks of text.

You interact with the Bing Service through the Bing API

Each of the previous feature is associated with one or more Bing API SourceTypes. A SourceType is a source of information accessible using the Bing API.   An overall description of these SourceTypes can be find on MSDN at this location: About the Bing API.

Prerequisites

In order to complete the example in this topic, you need the following:

  • Visual Studio 2008.
  • The ability to send requests using the Simple Object Access Protocol (SOAP) 1.1 and the Hyper Text Transfer Protocol (HTTP 1.1)
  • The ability to parse SOAP and XML

Creating a Web Application

This section shows how to create a Web application that will use the Bing search service.

To create an ASP.NET Web application

  1. Start Visual Studio 2008.
  2. In the File menu, click New, and then click Project.
  3. The New Project dialog box is displayed.
  4. In the left pane, under Project types, expand the Visual C# node then select Web
  5. In the Visual Studio installed templates right pane, select ASP.NET Web Application.
  6. In the Location box enter the name of the folder where you want to keep the Web application. For example, enter the folder name C:\WebApplications\CS\.
  7. In the Name dialog box enter the name of the project. For example, enter the name SoapBasicSearch.
  8. Click OK.
  9. An ASP.NET application is created.

Referencing Bing Search Service

This section shows how to reference the Bing search service. In order to do that, you use a Web service discovery process by which your application locates the service and obtains its description. The process of Web service discovery in Visual Studio involves interrogating a Web site to locate the service description, which is an XML document that uses the Web Services Description Language (WSDL).

When you add a Web reference to a project, Visual Studio generates a proxy class that provides a local representation of the Web service. The proxy enables your application to interface with the Web service. You can access Web service methods by calling the methods in the proxy class. The proxy class handles the communication between your application and the Web service itself.

To reference the Bing Search Service

  1. In Solution Explorer, right-click the project name then click Add Web Reference button.
  2. In the Add Web Reference panel, in the URL box enter the following value: http://api.search.live.net/search.wsdl.
  3. Click GO (represented by a green arrow).
  4. If the process has been successfully a message is displayed saying that "1 Service Found: Search" and the Web reference is: net.live.search.api.
  5. Click the Add Reference button.
  6. A Web References folder is added to the project that contains the reference to the Bing search service API.
  7. Also, the Web.config file is updated to contains address information about the soap.asmx service. The following is an example of the configuration update.
    <applicationSettings>
       <UsingBingService.Properties.Settings>
           <setting name="UsingBingService_net_live_search_api_LiveSearchService"
               serializeAs="String">
               <value>http://api.search.live.net:80/soap.asmx</value>
           </setting>
       </UsingBingService.Properties.Settings>
   </applicationSettings>

Performing Search by Using Bing Service Types

This section shows the code that enables the user to choose the desired Bing ServiceType to perform live search. For simplicity only the types listed in the table shown next are used. Also, the search are “hard-coded” and code used comes from the Code Samples (Bing, Version 2.0) on MSDN: .  

SourceType

Function

Web

Retrieve information from the Internet

 
Selecting the ServiceType to Use
  1. In Solution Explorer , open the default.aspx page. Then add the following markup.
<h2>Using BING Service</h2>
  <ul>
    <li><a href="WebSourceType.aspx" target="_blank">Using the Web SourceType over the SOAP Protocol</a></li> 
  </ul>
 
Create the Code to Interact with the Web ServiceType
  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Web Form.
  3. In the Name box enter WebSourceType.aspx.
  4. Click the Add button.
  5. In the newly created WebSourceType.aspx page enter the following markup and save the file.
<form id="form1" runat="server">
    <div>
        
        <h2>Using the Web SourceType Over the SOAP Protocol</h2>
            
            This example shows how to perform the following tasks:
            
            <ul>
                <li>Set search request basic parameters by using the 
                    <a href="http://msdn.microsoft.com/en-us/library/dd250960.aspx" target="_blank">SearchRequest</a> type.</li>
                <li>Set the Web book request by using the 
                    <a href="http://msdn.microsoft.com/en-us/library/dd250886.aspx" target="_blank">WebRequest</a> type. </li>
                <li>Display the results obtained  from the 
                    <a href="http://msdn.microsoft.com/en-us/library/dd250843.aspx" target="_blank">SearchResponse</a> type. </li>
            </ul>
          
            <h4>See Also </h4>
            <span style="background-color:Yellow">
                <a href="http://msdn.microsoft.com/en-us/library/dd251056.aspx" target="_blank">BING API</a></span>
            <br /> <br />

            <span style="background-color:Yellow">For more information, see 
                <a href="http://blogs.msdn.com/morebits/" target="_blank">Technical Notes</a></span>
            <br /> <br />
            
            <asp:Table ID="WebResultID" BorderWidth="1"    runat="server">  
                <asp:TableHeaderRow BackColor="LightGray">
                    <asp:TableCell ID="hdrID1" BorderStyle="Inset"/>
                </asp:TableHeaderRow>
            </asp:Table>
            
        
    </div>
    </form>
  1. In Solution Explorer , open the code behind file WebSourceType.aspx.cs and add the following code and save the file.
      // Get the search results. Display one result per row.
      private void DisplayResults(SearchResponse response)
      {
          int j = 0; 
          foreach (WebResult result in response.Web.Results)
          {
             
              TableRow tRow = new TableRow();
             
              WebResultID.Rows.Add(tRow);
              TableCell tCell = new TableCell();
              tCell.BorderWidth = Unit.Parse("1");
              if (j % 2 == 0)
                  tCell.BackColor = System.Drawing.Color.Blue;
              else
                  tCell.BackColor = System.Drawing.Color.Tomato;

              tCell.ForeColor = System.Drawing.Color.Yellow;
              tCell.Font.Bold = true;

              System.Text.StringBuilder builder = new System.Text.StringBuilder();
          
              builder.AppendLine(result.Title);
              builder.AppendLine(result.Description);
              builder.AppendLine(result.Url);
              builder.Append("Last Crawled: ");
              builder.AppendLine(result.DateTime);
              j++;

              int i = 0;
              foreach (char c in builder.ToString().ToCharArray())
              {

                  if (c == '\uE000')
                  {
                      // If the current character is the begin highlighting
                      // character (U+E000), change it to a left square bracket.

                      builder[i] = Convert.ToChar("[");


                  }

                  else if (c == '\uE001')
                  {
                      // If the current character is the end highlighting
                      // character (U+E001), change it to a right square bracket.
                      builder[i] = Convert.ToChar("]");
                  }

                  i++;
              }

              tCell.Text = builder.ToString();

              tRow.Cells.Add(tCell);

          }

         
      }

      protected override void OnPreRender(EventArgs e)
      {
          base.OnPreRender(e);
          SearchResponse response = UsingWebSourceType.PerformLiveSearch();
       
          string results = string.Format("Displaying {0} to {1} of {2} results", response.Web.Offset + 1,
                         response.Web.Offset + response.Web.Results.Length, response.Web.Total);

          // Add header information to the table.
          hdrID1.Text = "<div style='color:red; font-weight:bold'>' + "Bing API Version: " + response.Version + "</div>" +
                          "<div style='color:red; font-weight:bold'>' + "Phonebook results for " + response.Query.SearchTerms + "</div>" +
                          "<div style='color:red; font-weight:bold''>' + results + "</div>";
          // Add rows to the table that contain search results.
          DisplayResults(response);

         
      }
 
  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Code File.
  3. In the Name box enter ApiId.cs.
  4. Click the Add button.
  5. In the newly created file enter the following code and save the file.

The following static class enables you to have a single place where to define the AppID.

Remember you need this ID to use the Bing Search Service. For more information, see Getting Started with Bing API, Version 2.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "SoapBasicSearch" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using SoapBasicSearch.net.live.search.api;

namespace SoapBasicSearch
{
    public static class AppID
    {
        // Replace the following string with the AppId you received from the
        // Bing Developer Center.
        public const string Current = "Enter your AppId";
    }
}
  1. In Solution Explorer , right-click the project name then click Add and select New Item.
  2. In the Installed Templates dialog, select Code File.
  3. In the Name box enter UsingWebSourceType.cs.
  4. Click the Add button.
  5. In the newly created file enter the following code and save the file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "SoapBasicSearch" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using SoapBasicSearch.net.live.search.api;

namespace SoapBasicSearch
{
    public static class UsingWebSourceType
    {
        
        public static SearchResponse PerformLiveSearch()
        {
            // LiveSearchService implements IDisposable.
            using (LiveSearchService service = new LiveSearchService())
            {
                SearchResponse response = new SearchResponse();

                try
                {
                    SearchRequest request = BuildRequest();

                    // Send the request; display the response.
                    response = service.Search(request);

                }
                catch (System.Web.Services.Protocols.SoapException ex)
                {
                    // A SOAP Exception was thrown. Display error details.
                    DisplayErrors(ex.Detail);
                }
                catch (System.Net.WebException ex)
                {
                    // An exception occurred while accessing the network.
                    HttpContext.Current.Response.Write(ex.Message);
                }

                return response;
            }
        }

        static SearchRequest BuildRequest()
        {
            SearchRequest request = new SearchRequest();

            // Common request fields (required)
            request.AppId = AppID.Current;
            request.Query = "msdn blogs";
            request.Sources = new SourceType[] { SourceType.Web };

            // Common request fields (optional)
            request.Version = "2.0";
            request.Market = "en-us";
            request.Adult = AdultOption.Moderate;
            request.AdultSpecified = true;
            request.Options = new SearchOption[]
        {
            SearchOption.EnableHighlighting
        };

            // Web-specific request fields (optional)
            request.Web = new WebRequest();
            request.Web.Count = 10;
            request.Web.CountSpecified = true;
            request.Web.Offset = 0;
            request.Web.OffsetSpecified = true;
            request.Web.Options = new WebSearchOption[]
        {
            WebSearchOption.DisableHostCollapsing,
            WebSearchOption.DisableQueryAlterations
        };

            return request;
        }


        static void DisplayErrors(XmlNode errorDetails)
        {
            // Add the default namespace to the namespace manager.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(
                errorDetails.OwnerDocument.NameTable);
            nsmgr.AddNamespace(
                "api",
                "http://schemas.microsoft.com/LiveSearch/2008/03/Search");

            XmlNodeList errors = errorDetails.SelectNodes(
                "./api:Errors/api:Error",
                nsmgr);

            if (errors != null)
            {
                // Iterate over the list of errors and display error details.
                HttpContext.Current.Response.Write("Errors");
                //Console.WriteLine("Errors:");
                //Console.WriteLine();
                foreach (XmlNode error in errors)
                {
                    foreach (XmlNode detail in error.ChildNodes)
                    {
                        HttpContext.Current.Response.Write(detail.Name + ": " + detail.InnerText);
                        // Console.WriteLine(detail.Name + ": " + detail.InnerText);
                    }

                }
            }
        }
    }
}

Testing Bing Search Service in the Web Application

This section shows the steps to perform to test the application.

  1. Build the Web application.
  2. In Solution Explorer right click on default.aspx.
  3. Click the Using the Web SourceType over the SOAP Protocol link
  4. The Web ServiceType search results are displayed.

We are done.

A complete Visual Studio project is attached next. Please download and play with it.

I appreciate your feedback.

See Also

Bing API, Version 2

Working with Protocols (Bing, Version 2)

Code Samples (Bing, Version 2.0)

Posted by morebits | 5 Comments

Attachment(s): SimpleBingSearch.zip

Walkthrough: Filtering Rows in Tables with a Parent-Child Relationship

[Note:  This document is a preliminary version of a walkthrough that will be released with the Beta 2 version of Visual Studio 2010 and ASP.NET 4.]

Introduction

This walkthrough shows how to filter rows in tables with a parent-child relationship.

Filtering table rows refers to the ability provided to the user to choose (filter) the table rows to display based on a selected column value, it also defines whether data fields are displayed or in what order they are displayed.

This walkthrough illustrates the following tasks:

The example shown in this topic uses tables from the AdventureWorks database. More specifically, it uses the child Product table that contains the foreign-key column ProductCategory defined in the parent table ProductCategories. The relationship between tables is one-to-many that is a single category can contain many products. The following figure shows the relationship between the tables:

filtering

By default, Dynamic Data includes templates that let you perform filtering for Boolean, foreign-key, and enumeration column values. In these templates, filtering is defined declaratively by using the ASP.NET T:System.Web.UI.WebControls.QueryExtender control .

A Visual Studio project with source code is available at this location: Download LINQ to SQL version.

The following figure shows the steps that Dynamic Data performs to filter rows in tables that have a parent-child relationship.

The figure illustrates the following sequence:

ParentChildContext

1. The parent data-bound control passes the user's selected foreign-key to the T:System.Web.UI.WebControls.QueryExtender control.

2. The T:System.Web.UI.WebControls.QueryExtender control uses this foreign-key value to create the query filtering information. It then passes this filtering information to the data source control that fetches child rows.

3. The child data source control passes the filtering query information to the data source provider.

4. The data source provider passes the query to the database.

5. The database returns the filtered table rows.

6. The data source provider sends this data back to the child data source control.

7. This control finally passes the filtered table rows to the child data-bound control for display.

Prerequisites

This walkthrough assumes that you have created a Dynamic Data Web site and that you are using a data context that is based on LINQ to SQL. For more information, see Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding.

Setting the Parent Table for Selecting a Foreign-Key

In this section you will set the parent table for selecting a foreign-key. The setting includes a T:System.Web.UI.WebControls.LinqDataSource control to access the database that contains the parent table. It also includes a T:System.Web.UI.WebControls.GridView control to display the parent table and enable the selection of the foreign-key value.

To set the parent table for selecting a foreign key

8. In Solution Explorer, right-click the project name, and then click Add New Item.

9. Under Installed Templates in the right pane, select Web Form.

In the Name box, enter ParentChild.aspx.

10. Switch to Design modality by clicking on the Design tab.

11. From the Data tab of the Toolbox, add a T:System.Web.DynamicData.DynamicDataManager control to the page.

The T:System.Web.DynamicData.DynamicDataManager control must be included on a page in order to support Dynamic Data for data-bound controls. The markup for the T:System.Web.DynamicData.DynamicDataManager control must precede the markup for any controls that use Dynamic Data. We will register the necessary data-bound controls to be managed in later steps.

12. From the Data tab of the Toolbox, add a T:System.Web.UI.WebControls.LinqDataSource control to the page.

13. From the LinqDataSource Tasks menu click on the Configure Data Source.

14. The Choose a Context Object dialog box is displayed.

15. Choose the context object AdventureWorksLTDataContext.

16. Click the Next button.

17. The Configure Data Selection dialog box is displayed.

18. In the Table drop-down list control, select the parent table ProductCategories.

19. In the Select box leave the box with the asterisk checked. This will select all the rows of the ProductCategories table.

20. Click the Finish button.

21. From the Data group of the Toolbox, add a T:System.Web.UI.WebControls.GridView control to the page. This control is used to display the ProductCategories table data fields.

22. From the GridView Tasks menu in the Choose Data Source drop-down list control, select LinqDataSource1. This is the ID of the data source control created in the previous steps.

23. Enable paging and selection by checking the related check-boxes.

24. Switch to source modality, by clicking the Source tab.

25. For display clarity above the T:System.Web.UI.WebControls.GridView control enter the following markup:

<h2>Parent Table: ProductCategories</h2>

26. In the <Coulmns> tag, delete all the <asp:BoundField> controls.

27. Enable automatic columns generation, set page size, and set the selection index to a category that is not empty. The following example shows how to set these properties.

   <asp:GridView ID="GridView1" runat="server" 
     DataSourceID="LinqDataSource1" 
     AutoGenerateColumns="True"
     PageSize="5" SelectIndex="4"> 
   </asp:GridView>

28. Switch to Design modality by clicking on the Design tab.

29. From the DynamicDataManager Tasks menu, click Register Controls.

30. The DataControlReference Collection Editor is displayed.

31. In the Members pane, click the Add button. A DataControl entry is displayed in the Members box.

32. In the DataControl properties pane in the ControlID drop-down list control box select GridView1.

33. Click OK.

34. Right-click on the page and select View in Browser. The ProductCategories table rows are displayed.

35. Save the ParentChid.aspx file.

Setting the Child Table for Displaying Filtered Rows

In this section you will set the child table for displaying filtered rows. The setting includes a T:System.Web.UI.WebControls.LinqDataSource control to access the database that contains the child table. It also includes a T:System.Web.UI.WebControls.GridView control to display the child table filtered rows.

To set the child table for displaying filtered rows

36. While in the ParentChild.aspx file, switch to Design modality by clicking on the Design tab.

37. From the Data tab of the Toolbox, add a T:System.Web.UI.WebControls.LinqDataSource control to the page.

38. From the LinqDataSource Tasks menu click on the Configure Data Source.

39. The Choose a Context Object dialog box is displayed.

40. In the Choose your context object drop-down list control box, choose the context object AdventureWorksLTDataContext.

41. Click the Next button.

42. The Configure Data Selection dialog box is displayed.

43. In the Table drop-down list control box, select the child table Products.

44. In the Select box leave the box with the asterisk checked. This will select all the rows of the Products table.

45. Click the Finish button.

46. From the Data group of the Toolbox, add a T:System.Web.UI.WebControls.GridView control to the page. This control is used to display the Products table data fields.

48. From the GridView Tasks menu in the Choose Data Source drop-down list control, select LinqDataSource2. This is the ID of the data source control created in the previous steps.

49. Enable paging and selection by checking the related check-boxes.

50. Switch to source modality, by clicking the Source tab.

51. For display clarity above the T:System.Web.UI.WebControls.GridView control enter the following markup:

<h2>Child Table: Products</h2>

52. In the <Coulmns> tag, delete all the <asp:BoundField> controls.

53. Enable automatic columns generation and set page size. The following example shows how to set these properties.

       <asp:GridView ID="GridView2" runat="server" 
         DataSourceID="LinqDataSource2" 
         AutoGenerateColumns="True" PageSize="5"> 
       </asp:GridView>

54. Switch to Design modality by clicking on the Design tab.

55. From the DynamicDataManager Tasks menu, click Register Controls.

56. The DataControlReference Collection Editor is displayed.

57. In the Members pane, click the Add button. A DataControl entry is displayed in the Members box.

58. In the DataControl properties pane in the ControlID drop-down list control box select GridView2.

59. Click OK.

60. Right-click on the page and select View in Browser. The Products table rows are displayed.

61. Save the ParentChid.aspx file.

Set the Child Table Row Filtering

In this final section you will set the child table rows filtering. The T:System.Web.UI.WebControls.QueryExtender control is set in such way to enable child table rows filtering based on the foreign-key selected by the user in the parent table.

To set the child table row filtering

62. In the ParentChild.aspx page, add a T:System.Web.UI.WebControls.QueryExtender control and set its P:System.Web.UI.WebControls.QueryExtender.TargetControlID property to the ID of the data source control that is associated with the child table whose rows you want to filter.

The following example shows the markup for a T:System.Web.UI.WebControls.QueryExtender control that specifies the data source control LinqDataSource2 is associated with the child table.

      <asp:QueryExtender ID="QueryExtenderID" 
         TargetControlID="LinqDataSource2" runat="server" >
       </asp:QueryExtender>

63. Add a T:System.Web.DynamicData.ControlFilterExpression object as a child of the T:System.Web.UI.WebControls.QueryExtender control. The following example shows the markup for adding a T:System.Web.DynamicData.ControlFilterExpression object to the control.

     <asp:QueryExtender ID="QueryExtenderID" 
       TargetControlID="LinqDataSource2" runat="server" >
       <asp:ControlFilterExpression />
     </asp:QueryExtender>

64. Set the ControlID property of the T:System.Web.DynamicData.ControlFilterExpression object to the data-bound control associated with the parent table.

65. Set the Column property of the T:System.Web.DynamicData.ControlFilterExpression object to the column in the parent table that is used for filtering. This column represents a foreign key in the child table.

The following example shows the markup for a

T:System.Web.DynamicData.ControlFilterExpression object that points to a data-bound control and a foreign-key associated with the parent table.

       <asp:QueryExtender ID="QueryExtenderID" 
         TargetControlID="LinqDataSource2" runat="server" >
         <asp:ControlFilterExpression ControlID="GridView1"
           Column="ProductCategory" />
       </asp:QueryExtender>

66. Save the file.

67. In Solution Explorer, right-click the ParentChild.aspx page and then select View in Browser.

68. In the ProductCategories parent table select a category.

Dynamic Data filters the Products table rows based on the category that you selected.

See Also

Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding

Posted by morebits | 0 Comments

Walkthrough: Using BING Service over SOAP Protocol in a Console Application

Introduction

This walkthrough shows how to use the BING features as a Web service in a client console application. This service, that we'll call BING Service, is invoked by the client console application using SOAP protocol over HTTP. You can also use XML and JSON to invoke the service. We'll have related examples at a later time.

BING Service Background

Complex problems such as indexing, relevance logic, and hosting issues such as CPU and storage are solved in transparent way to your application by having the ability to use the BING features as a Web service. This article offers a starting point for adding the service to your application.

Remember that a Web service is a component on a Web server that a client application can call by making HTTP requests across the Web. If you want some good explanation about this subject, see this MSDN article Using ASP.NET Web Services.

By using the service you can integrate the following features in your application:

  • Retrieve information from the Internet.
  • Add advertisements to your application.
  • Improve and enhance search requests and results.
  • Find location-specific information.
  • Translate terms and blocks of text.

You interact with the BING Service through the BING API

Each of the previous feature is associated with one or more Bing API SourceTypes. A SourceType is a source of information accessible via the BING API.   An overall description of these SourceTypes can be find on MSDN at this location: About the Bing API.

Prerequisites

In order to complete the example in this topic, you need the following:

  • Visual Studio 2010.
  • The ability to send requests using the Simple Object Access Protocol (SOAP) 1.1 and the Hyper Text Transfer Protocol (HTTP 1.1)
  • The ability to parse SOAP and XML

Creating a Console Application

This section shows how to create a console application that will use the BING Service.

To create a console application

  1. Start Visual Studio.
  2. In the File menu, click New, and then click Project.
  3. The New Project dialog box is displayed.
  4. Under Installed Templates, in the left pane, select Visual C# (or Visual Basic).
  5. Then select Windows.
  6. In the right pane, select Console Application.
  7. In the Location box enter the name of the folder where you want to keep the Web application. For example, enter the folder name C:\CS\SOAP\ConsoleApplications
  8. In the Name box enter the name of the project. For example, enter the name UsingBingAPI.
  9. Click OK.
  10. A console application is created. Rename the file Program.cs to UsingBingAPI.cs.

Adding a Web Reference to BING Service

This section shows how to add a Web reference to the BING Service. In order to do that, you use a Web service discovery process by which the client application locates the service and obtains its description. The process of Web service discovery in Visual Studio involves interrogating a Web site to locate the service description, which is an XML document that uses the Web Services Description Language (WSDL).

When you add a Web reference to a project, Visual Studio generates a proxy class that provides a local representation of the Web service, which allows the client code to interface with the Web service. You can access Web service methods by calling the methods in the proxy class. The proxy class handles the communication between the client application and the Web service itself.

To add a Web reference to BING Service

  1. In Solution Explorer , right-click the project name, and then click Add Service Reference  button.
  2. In the Add Service Reference dialog box, click the Advanced...  button.
  3. In the Service Reference Settings  dialog box, click the Add Web Reference... button.
  4. In the URL  box enter the following value: http://api.search.live.net/search.wsdl.
  5. Click GO .
  6. If the process has been added successfully a message is displayed saying that "1 Service Found: Search" and the Web reference is: net.live.search.api.
  7. Click Add Reference... button.
  8. A Web References folder is added to the project that contains the reference to the live search service.
  9. Also, the app.config file is created and added to the project. This file contains address information about the soap.asmx service.

 

Adding Code to the Console Application to Interact with BING Service

This section shows the code that provides an interactive menu that enables the user to choose the desired BING service type. Also it shows the code that enables the application to interact with the BING service types. For simplicity only the following types are provided:

SourceType Function
Web Retrieve information from the Internet
InstantAnswer Retrieve information from the Internet
Phonebook Find location specific information

 

To create the user dialog

This section shows how to create the code to provide an interactive menu that enables the user to choose the desired BING service type.

  1. In Solution Explorer , open the file  UsingBingAPI.cs. and add the code shown next.

The code provides an interactive menu that enables the user to choose the desired BING service type among the three listed before.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UsingBingAPI
{
    #region ApplicationMain

    class ApplicationMain
    {
        // Display user's menu.
        public static void UserMenu()
        {
            StringBuilder buffer = new StringBuilder();

            buffer.AppendLine("Please, make your selection.");
            buffer.AppendLine("1    -- Using Web SourceType.");
            buffer.AppendLine("2    -- Using InstantAnswer SourceType.");
            buffer.AppendLine("3    -- Using Phonebook SourceType.");
            buffer.AppendLine("?    -- Display help.");
            buffer.AppendLine("Q,q  -- Exit the application.");

            Console.Write(buffer.ToString());
        }

        // Obtain user's input and provide
        // feedback.
        static void Main(string[] args)
        {
            // Define user selection string.
            string selection;

            // Get user selection.
            while (true)
            {

                UserMenu();
                Console.Write("> ");
                selection = Console.ReadLine();
                if (selection != string.Empty)
                    break;
            }

            while (selection.ToLower() != "q")
            {
                // Process user's input.
                switch (selection)
                {
                    case "1":
                        // Demonstrate the use of the
                        // Web SourceType over the SOAP Protocol.
                        WebSample.WebType();
                        break;

                    case "2":
                        // Demonstrate the use of the
                        // InstantAnswer SourceType over the SOAP Protocol.
                        InstantAnswerFlightStatusSample.Flight();
                        break;

                    case "3":
                        // Demonstrate the use of the
                        // Phonebook SourceType over the SOAP Protocol.
                        PhonebookSample.Phone();
                        break;

                    default:
                        UserMenu();
                        break;
                }
                Console.Write("> ");
                selection = Console.ReadLine();
            }
        }
    }
    #endregion ApplicationMain
}

To create the code to use with BING Service Web Type

This section shows how to create the code that enable the application to use BING Service Web type. For more information, see  WebRequest Class, WebResponse Class and WebResult Class. Remember that you need to obtain your AppID and assign it to the AppId constant string, in the code shown next. You obtain the AppID from the BING Developer Center.

  1. In Solution Explorer , create the file  WebSample.cs. and add the code shown next. The code demonstrates the use of the Web SourceType over the SOAP Protocol.
  2. Save and close the file.
using System;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "UsingBingAPI" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using UsingBingAPI.net.live.search.api;

// Bing API 2.1 code sample demonstrating the use of the
// Web SourceType over the SOAP Protocol.
static class WebSample
{
    // Replace the following string with the AppId you received from the
    // Bing Developer Center.
    const string AppId = "Enter your AppID";

    static public void WebType()
    {
        // LiveSearchService implements IDisposable.
        using (LiveSearchService service = new LiveSearchService())
        {
            try
            {
                SearchRequest request = BuildRequest();

                // Send the request; display the response.
                SearchResponse response = service.Search(request);
                DisplayResponse(response);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // A SOAP Exception was thrown. Display error details.
                DisplayErrors(ex.Detail);
            }
            catch (System.Net.WebException ex)
            {
                // An exception occurred while accessing the network.
                Console.WriteLine(ex.Message);
            }
        }
    }

    static SearchRequest BuildRequest()
    {
        SearchRequest request = new SearchRequest();

        // Common request fields (required)
        request.AppId = AppId;
        request.Query = "msdn blogs";
        request.Sources = new SourceType[] { SourceType.Web };

        // Common request fields (optional)
        request.Version = "2.0";
        request.Market = "en-us";
        request.Adult = AdultOption.Moderate;
        request.AdultSpecified = true;
        request.Options = new SearchOption[]
        {
            SearchOption.EnableHighlighting
        };

        // Web-specific request fields (optional)
        request.Web = new WebRequest();
        request.Web.Count = 10;
        request.Web.CountSpecified = true;
        request.Web.Offset = 0;
        request.Web.OffsetSpecified = true;
        request.Web.Options = new WebSearchOption[]
        {
            WebSearchOption.DisableHostCollapsing,
            WebSearchOption.DisableQueryAlterations
        };

        return request;
    }

    static void DisplayResponse(SearchResponse response)
    {
        // Display the results header.
        Console.WriteLine("Bing API Version " + response.Version);
        Console.WriteLine("Web results for " + response.Query.SearchTerms);
        Console.WriteLine(
            "Displaying {0} to {1} of {2} results",
            response.Web.Offset + 1,
            response.Web.Offset + response.Web.Results.Length,
            response.Web.Total);
        Console.WriteLine();

        // Display the Web results.
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        foreach (WebResult result in response.Web.Results)
        {
            builder.Length = 0;
            builder.AppendLine(result.Title);
            builder.AppendLine(result.Description);
            builder.AppendLine(result.Url);
            builder.Append("Last Crawled: ");
            builder.AppendLine(result.DateTime);

            DisplayTextWithHighlighting(builder.ToString());
            Console.WriteLine();
        }
    }

    static void DisplayTextWithHighlighting(string text)
    {
        // Write text to the standard output stream, changing the console
        // foreground color as highlighting characters are encountered.
        foreach (char c in text.ToCharArray())
        {
            if (c == '\uE000')
            {
                // If the current character is the begin highlighting
                // character (U+E000), change the console foreground color
                // to green.
                Console.ForegroundColor = ConsoleColor.Green;
            }
            else if (c == '\uE001')
            {
                // If the current character is the end highlighting
                // character (U+E001), revert the console foreground color
                // to gray.
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            else
            {
                Console.Write(c);
            }
        }
    }

    static void DisplayErrors(XmlNode errorDetails)
    {
        // Add the default namespace to the namespace manager.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(
            errorDetails.OwnerDocument.NameTable);
        nsmgr.AddNamespace(
            "api",
            "http://schemas.microsoft.com/LiveSearch/2008/03/Search");

        XmlNodeList errors = errorDetails.SelectNodes(
            "./api:Errors/api:Error",
            nsmgr);

        if (errors != null)
        {
            // Iterate over the list of errors and display error details.
            Console.WriteLine("Errors:");
            Console.WriteLine();
            foreach (XmlNode error in errors)
            {   
                foreach (XmlNode detail in error.ChildNodes)
                {
                    Console.WriteLine(detail.Name + ": " + detail.InnerText);
                }

                Console.WriteLine();
            }
        }
    }
}

 

To create the code to use with BING Service InstantAnswer Type

This section shows how to create the code that enable the application to use BING Service InstantAnswer type. For more information, see InstantAnswerResponse Class and InstantAnswerResult Class.

Remember that you need to obtain your AppID and assign it to the AppId constant string, in the code shown next. You obtain the AppID from the BING Developer Center.

  1. In Solution Explorer , create the file  InstantAnswerFlightStatusSample.cs. and add the code shown next. The code demonstrates the use of the InstantAnswer SourceType that returns FlightStatus results over the SOAP Protocol.
  2. Save and close the file.
using System;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "UsingBingAPI" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using UsingBingAPI.net.live.search.api;

// Bing API 2.2 code sample demonstrating the use of the
// InstantAnswer SourceType to return FlightStatus results over the SOAP Protocol.
static class InstantAnswerFlightStatusSample
{
    // Replace the following string with the AppId you received from the
    // Bing Developer Center.
    const string AppId = "Enter your AppID";

    static public void Flight()
    {
        // LiveSearchService implements IDisposable.
        using (LiveSearchService service = new LiveSearchService())
        {
            try
            {
                SearchRequest request = BuildRequest();

                // Send the request; display the response.
                SearchResponse response = service.Search(request);
                DisplayResponse(response);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // A SOAP Exception was thrown. Display error details.
                DisplayErrors(ex.Detail);
            }
            catch (System.Net.WebException ex)
            {
                // An exception occurred while accessing the network.
                Console.WriteLine(ex.Message);
            }
        }
    }

    static SearchRequest BuildRequest()
    {
        SearchRequest request = new SearchRequest();

        // Common request fields (required)
        request.AppId = AppId;
        request.Query = "CO234";
        request.Sources = new SourceType[] { SourceType.InstantAnswer };

        // Common request fields (optional)
        request.Version = "2.2";
        request.Market = "en-us";
        return request;
    }

    static void DisplayResponse(SearchResponse response)
    {
        // Display the results header.
        Console.WriteLine("Bing API Version " + response.Version);
        Console.WriteLine(
            "InstantAnswer results for \"" + response.Query.SearchTerms + "\" query");
        Console.WriteLine();

        // Display the InstantAnswer results.
        foreach (InstantAnswerResult result in response.InstantAnswer.Results)
        {
            Console.WriteLine(
                "Title: " + result.Title);
            Console.WriteLine(
                "ClickThroughUrl: " + result.ClickThroughUrl);
            Console.WriteLine(
                "URL: " + result.Url);
            Console.WriteLine(
                System.Environment.NewLine + "InstantAnswerSpecificData for FlightStatus");
            DisplayInstantAnswerSpecificData(result.InstantAnswerSpecificData);
            Console.WriteLine();          
        }
    }

    static void DisplayInstantAnswerSpecificData(string data)
    {
        // Load the InstantAnswer-specific data into an XmlDocument.
        XmlDocument document = new XmlDocument();
        document.Load(new System.IO.StringReader(data));

        // Add the FlightStatus namespace to the namespace manager.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(
            document.NameTable);
        nsmgr.AddNamespace(
            "fls",
            "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element/flightstatus");

        string flightName = document.DocumentElement.SelectSingleNode(
    "./fls:FlightName",
    nsmgr).InnerText;

        Console.WriteLine(
            "Flight: " + flightName);

        string statusString = document.DocumentElement.SelectSingleNode(
            "./fls:StatusString",
            nsmgr).InnerText;

        Console.WriteLine(
            "Status: " + statusString);

        string originAirportName = document.DocumentElement.SelectSingleNode(
    "./fls:OriginAirport/fls:Name",
    nsmgr).InnerText;

        Console.WriteLine(
            "From: " + originAirportName);


        string destinationAirportName = document.DocumentElement.SelectSingleNode(
    "./fls:DestinationAirport/fls:Name",
    nsmgr).InnerText;

        Console.WriteLine(
            "To: " + destinationAirportName);



        string scheduledDeparture = document.DocumentElement.SelectSingleNode(
    "./fls:ScheduledDeparture",
    nsmgr).InnerText;

        Console.WriteLine(
            "Scheduled Departure: " + scheduledDeparture);


        string scheduledArrival = document.DocumentElement.SelectSingleNode(
    "./fls:ScheduledArrival",
    nsmgr).InnerText;

        Console.WriteLine(
            "Scheduled Arrival: " + scheduledArrival);

    }

    static void DisplayErrors(XmlNode errorDetails)
    {
        // Add the default namespace to the namespace manager.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(
            errorDetails.OwnerDocument.NameTable);
        nsmgr.AddNamespace(
            "api",
            "http://schemas.microsoft.com/LiveSearch/2008/03/Search");

        XmlNodeList errors = errorDetails.SelectNodes(
            "./api:Errors/api:Error",
            nsmgr);

        if (errors != null)
        {
            // Iterate over the list of errors and display error details.
            Console.WriteLine("Errors:");
            Console.WriteLine();
            foreach (XmlNode error in errors)
            {
                foreach (XmlNode detail in error.ChildNodes)
                {
                    Console.WriteLine(detail.Name + ": " + detail.InnerText);
                }
                Console.WriteLine();
            }
        }
    }
}

 

To create the code to use with BING Service Phonebook Type

This section shows how to create the code that enable the application to use BING Service Phonebooktype. For more information, see  PhonebookRequest Class, PhonebookResponse Class and PhonebookResult Class.

Remember that you need to obtain your AppID and assign it to the AppId constant string, in the code shown next. You obtain the AppID from the BING Developer Center.

  1. In Solution Explorer , create the file PhonebookSample.cs. and add the code shown next. The code demonstrates the use of the Phonebook SourceType over the SOAP Protocol.
  2. Save and close the file.
using System;
using System.Xml;

// This using directive assumes that the project's default namespace is
// "UsingBingAPI" and the name of the Bing API web reference is
// "net.live.search.api". Modify this using directive as necessary.
using UsingBingAPI.net.live.search.api;

// Bing API 2.0 code sample demonstrating the use of the
// Phonebook SourceType over the SOAP Protocol.
static class PhonebookSample
{
    // Replace the following string with the AppId you received from the
    // Bing Developer Center.
    const string AppId = "Enter your AppID";

    static public void Phone()
    {
        // LiveSearchService implements IDisposable.
        using (LiveSearchService service = new LiveSearchService())
        {
            try
            {
                SearchRequest request = BuildRequest();

                // Send the request; display the response.
                SearchResponse response = service.Search(request);
                DisplayResponse(response);
            }
            catch (System.Web.Services.Protocols.SoapException ex)
            {
                // A SOAP Exception was thrown. Display error details.
                DisplayErrors(ex.Detail);
            }
            catch (System.Net.WebException ex)
            {
                // An exception occurred while accessing the network.
                Console.WriteLine(ex.Message);
            }
        }
    }

    static SearchRequest BuildRequest()
    {
        SearchRequest request = new SearchRequest();

        // Common request fields (required)
        request.AppId = AppId;
        request.Query = "microsoft offices";
        request.Sources = new SourceType[] { SourceType.Phonebook };

        // Common request fields (optional)
        request.Version = "2.0";
        request.Market = "en-us";
        request.UILanguage = "en";
        request.Latitude = 47.603450;
        request.LatitudeSpecified = true;
        request.Longitude = -122.329696;
        request.LongitudeSpecified = true;
        request.Radius = 10.0;
        request.RadiusSpecified = true;
        request.Options = new SearchOption[]
        {
            SearchOption.EnableHighlighting
        };

        // Phonebook-specific request fields (optional)
        request.Phonebook = new PhonebookRequest();
        request.Phonebook.Count = 10;
        request.Phonebook.CountSpecified = true;
        request.Phonebook.Offset = 0;
        request.Phonebook.OffsetSpecified = true;
        request.Phonebook.FileType = "YP";
        request.Phonebook.SortBy = PhonebookSortOption.Distance;
        request.Phonebook.SortBySpecified = true;

        return request;
    }

    static void DisplayResponse(SearchResponse response)
    {
        // Display the results header.
        Console.WriteLine("Bing API Version " + response.Version);
        Console.WriteLine(
            "Phonebook results for " + response.Query.SearchTerms);
        Console.WriteLine(
            "Displaying {0} to {1} of {2} results",
            response.Phonebook.Offset + 1,
            response.Phonebook.Offset + response.Phonebook.Results.Length,
            response.Phonebook.Total);
        Console.WriteLine();

        // Display the Phonebook results.
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        foreach (PhonebookResult result in response.Phonebook.Results)
        {
            builder.Length = 0;
            builder.AppendLine(result.Business);
            builder.AppendLine(result.Address);
            builder.Append(result.City);
            builder.Append(", ");
            builder.AppendLine(result.StateOrProvince);
            builder.AppendLine(result.PhoneNumber);
            builder.Append("Average Rating: ");
            builder.AppendLine(result.UserRating.ToString());

            DisplayTextWithHighlighting(builder.ToString());
            Console.WriteLine();
        }
    }

    static void DisplayTextWithHighlighting(string text)
    {
        // Write text to the standard output stream, changing the console
        // foreground color as highlighting characters are encountered.
        foreach (char c in text.ToCharArray())
        {
            if (c == '\uE000')
            {
                // If the current character is the begin highlighting
                // character (U+E000), change the console foreground color
                // to green.
                Console.ForegroundColor = ConsoleColor.Green;
            }
            else if (c == '\uE001')
            {
                // If the current character is the end highlighting
                // character (U+E001), revert the console foreground color
                // to gray.
                Console.ForegroundColor = ConsoleColor.Gray;
            }
            else
            {
                Console.Write(c);
            }
        }
    }

    static void DisplayErrors(XmlNode errorDetails)
    {
        // Add the default namespace to the namespace manager.
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(
            errorDetails.OwnerDocument.NameTable);
        nsmgr.AddNamespace(
            "api",
            "http://schemas.microsoft.com/LiveSearch/2008/03/Search");

        XmlNodeList errors = errorDetails.SelectNodes(
            "./api:Errors/api:Error",
            nsmgr);

        if (errors != null)
        {
            // Iterate over the list of errors and display error details.
            Console.WriteLine("Errors:");
            Console.WriteLine();
            foreach (XmlNode error in errors)
            {   
                foreach (XmlNode detail in error.ChildNodes)
                {
                    Console.WriteLine(detail.Name + ": " + detail.InnerText);
                }

                Console.WriteLine();
            }
        }
    }
}

 

Testing the Console Application

This section shows the steps to perform to test the application.

  1. Build the application.
  2. In a command Window go to the folder where the UsingBingAPI.exe file is located. Most likely the Debug folder.
  3. Execute the following command: >UsingBingApi.
  4. A dialog is displayed.
  5. Make a selection as suggested by the dialog.
  6. The selected BING service type is invoked and the related results shown.

We are done.

A complete Visual Studio project is attached next. Please download and play with it.

I appreciate your feedback.

See Also

Bing API, Version 2

Working with Protocols (Bing, Version 2)

Working with SourceTypes (Bing, Version 2)

Posted by morebits | 0 Comments

Attachment(s): UsingBingAPI.zip

Walkthrough: Filtering Table Rows in Dynamic Data

Introduction

This walkthrough shows how to use the Dynamic Data filter templates to create the UI that enables you to choose a column value for selecting (filtering) table rows to display. By default, Dynamic Data includes templates that let you specify filtering for Boolean column values and for foreign-key column values.

In this walkthrough you will build an application that displays filtered rows from tables contained by the AdventureWorksLT sample database, in the following ways:

  • Filter table rows using a foreign key. You will create the page markup to let Dynamic Data generate the UI and perform row filtering in the Products table by using the foreign-key column values from the ProductCategories table. You use this approach when you want to filter rows for a specific column type for which Dynamic Data provides a default filter template. (If you want to support filtering for a column type for which Dynamic Data does not provide a default filter template, you need to create a custom filter template.)
  • Filter table rows using default filter templates. You create the page markup to let Dynamic Data automatically generate the UI and perform row filtering in the Products table by using the foreign-key column values from the ProductCategories table, for the column types for which default filter templates exist. By default, Dynamic Data can create the UI for Boolean and foreign-key columns.
  • Test data filtering. This lets you make sure that Dynamic Data table row filtering capabilities have been integrated in the Web site.

A Visual Studio project with source code is available to accompany this topic: Download.

Prerequisites

In order to build the application and run the examples in this topic, you need the following:

  • A Dynamic Data Web site or a Dynamic Data Web application. You must perform this step to create the AdventureWorksLTDataContext data context and the data model classes to access the tables used in this walkthrough. This walkthrough assumes that you have created the Web site and that you are using a data context that is based on LINQ to SQL. For more information, see Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding1564aef2-9103-436a-9806-c8ad7abd616a.
  • The AdventureWorksLT sample database. For more information, see How to: Connect to the AdventureWorksLT Database with an .MDF File.

Filtering Table Rows Using a Foreign Key

This section shows how to create a Web page that let the user filter table rows by using a foreign key. The page contains a T:System.Web.UI.WebControls.LinqDataSource control to interact with the database and a T:System.Web.UI.WebControls.GridView control to display the filtered table rows. The page uses the LINQ to SQL database model, as illustrated in the topic Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding1564aef2-9103-436a-9806-c8ad7abd616a.

To filter table rows using a foreign key

1. In Solution Explorer, right-click the project name, and then select Add New Item.

2. Under Visual Studio installed templates, select Web Form.

In the Name box, enter ForeignKeyTableRowFiltering.aspx.

3. Add a T:System.Web.DynamicData.DynamicDataManager control to the page, as shown in the following example:

<body>
    <form id="form1" runat="server">
        <asp:DynamicDataManager  ID="DynamicDataManager1" runat="server">
            
        </asp:DynamicDataManager>
    </form> 
</body> 

The T:System.Web.DynamicData.DynamicDataManager control must be included on a page in order to support Dynamic Data controls. The markup for the T:System.Web.DynamicData.DynamicDataManager control must precede the markup for any controls that use Dynamic Data.

4. From the Data tab of the Toolbox, add a T:System.Web.UI.WebControls.LinqDataSource control to the page, as shown in the following example:

<form id="form1" runat="server">
    <
asp:LinqDataSource ID="LinqDataSource1" runat="server"/>
 
</form>

5. Set the T:System.Web.UI.WebControls.LinqDataSource control's P:System.Web.UI.WebControls.LinqDataSource.TableName property to the database table to access (Products), as shown in the following example:

<asp:LinqDataSource ID="LinqDataSource1"  TableName="Products" runat="server"/>

 

6. Set the P:System.Web.UI.WebControls.LinqDataSource.ContextTypeName property to the data context class (AdventureWorksLTDataContext), as shown in the following example:

<asp:LinqDataSource ID="LinqDataSource1"  runat="server"

   TableName="Products" ContextTypeName="AdventureWorksLTDataContext"/>

7. From the Data tab of the Toolbox, add a T:System.Web.UI.WebControls.GridView control to the page.

This control will display the Products table data fields. Set the P:System.Web.UI.WebControls.DataBoundControl.DataSourceID property to the ID of the T:System.Web.UI.WebControls.LinqDataSource control, as shown in the following example:

<form id="form2" runat="server">
    <asp:GridView ID="GridView1" runat="server"
        DataSourceID="LinqDataSource1">
    </asp:GridView>
</form>

8. Set the T:System.Web.UI.WebControls.GridView control's P:System.Web.UI.WebControls.GridView.AutoGenerateColumns property to false, as shown in the following example:

<asp:GridView ID="GridView1" runat="server"
    DataSourceID="LinqDataSource1" AutoGenerateColumns="false">
</asp:GridView>

This disables the automatic generation of columns that are based on the database table. Instead you will use a DynamicField controls to populate the T:System.Web.UI.WebControls.GridView control.

9. Optionally, set the T:System.Web.UI.WebControls.GridView control's P:System.Web.UI.WebControls.GridView.AllowPaging and P:System.Web.UI.WebControls.GridView.AllowSorting properties to true, as shown in the following example:

<asp:GridView ID="GridView1" runat="server"
    DataSourceID="LinqDataSource1" AutoGenerateColumns="false"
    AllowPaging="true" AllowSorting="true">
</asp:GridView>

10. Add DynamicField controls to the P:System.Web.UI.WebControls.GridView.Columns property and set their P:System.Web.DynamicData.DynamicField.DataField properties to "ProductCategory", "Name", "Color", and "Size".

DynamicField controls use ASP.NET Dynamic Data to read data from the data model and to format it by using the appropriate field templates. The following example shows the markup for the Columns property and the DynamicField controls:

<asp:GridView ID="GridView1" runat="server"
    DataSourceID="LinqDataSource1" AutoGenerateColumns="false"
    AllowPaging="true" AllowSorting="true">
    <Columns>
        <asp:DynamicField DataField="ProductCategory" />
        <asp:DynamicField DataField="Name" />
        <asp:DynamicField DataField="Color" />
        <asp:DynamicField DataField="Size" />
    </Columns>
</asp:GridView>

11. Register the T:System.Web.UI.WebControls.GridView control with the T:System.Web.DynamicData.DynamicDataManager control, as shown in the following example:

<asp:DynamicDataManager  ID="DynamicDataManager1" runat="server">
    <DataControls>
        <asp:DataControlReference ControlID="GridView1" />
    </DataControls>
</asp:DynamicDataManager>

12. In the markup above the data-bound control, add a T:System.Web.DynamicData.DynamicFilter control to the page and set the DataField property of the to ProductCategory.

This is the name of the column to use to for table row filtering. The following example shows the markup for the T:System.Web.DynamicData.DynamicFilter control.

<asp:DynamicFilter ID="DynamicFilter1" 
   DataField="ProductCategory" runat="server" />

Dynamic Data throws an T:System.InvalidOperationException error if the column type does not have an associated filter template.

13. In the markup above the T:System.Web.DynamicData.DynamicFilter control, add a T:System.Web.UI.WebControls.Label control, as shown in the following example:

<asp:Label ID="Label1" runat="server" 
  Text="ProductCategory "/>

You will use this Label control to display the name of the column that is used for filtering.

14. Add a T:System.Web.UI.WebControls.QueryExtender control to the page and set the TargetControlID property to the identifiier of the data source control that you want to extend, as shown in the following example:

<asp:QueryExtender ID="QueryExtender1" 
    TargetControlID="LinqDataSource1" runat="server">
</asp:QueryExtender>

The T:System.Web.UI.WebControls.QueryExtender control extends a data source control's capabilities by letting you configure data filtering through declarative syntax, as shown in the next steps.

15. Add a T:System.Web.DynamicData.DynamicFilterExpression object as a child of the T:System.Web.UI.WebControls.QueryExtender control. Set the ControlID property of the T:System.Web.DynamicData.DynamicFilterExpression object to the identifier of the T:System.Web.DynamicData.DynamicFilter control, as shown in the following example:

<asp:QueryExtender ID="QueryExtender1" 
    TargetControlID="LinqDataSource1" runat="server">
    <asp:DynamicFilterExpression ControlID="DynamicFilter1" />
</asp:QueryExtender>

16. Save and close the file.

In Solution Explorer, right-click the ForeignKeyTableRowFiltering.aspx page and then select View in Browser.

The page displays the columns from the Products and the UI for filtering the products by category.

17. In the Product Category drop-down control, select a category.

Dynamic Data filters the products that are displayed, based on the category that you selected.

18. Close the ForeignKeyTableRowFiltering.aspx page.

Filtering Table Rows Using Default Filter Templates

This section shows how to create a Web page that lets the user filter table rows for the column types for which default filter templates exist. The page contains a T:System.Web.UI.WebControls.LinqDataSource control to interact with the database and a T:System.Web.UI.WebControls.GridView control to display the filtered table rows. The page uses the LINQ to SQL database model, as illustrated in the Walkthrough: Creating a New Dynamic Data Web Site using Scaffolding1564aef2-9103-436a-9806-c8ad7abd616a.

To filter table rows using default filter templates

19. As a shortcut, instead of recreating a new page, in Solution Explorer right-click the ForeignKeyTableRowFiltering.aspx file and then select Copy.

20. Right-click the project folder and then select Paste.

21. Right click the Copy of ForeignKeyTableRowFiltering.aspx page and then select Rename.

22. Rename the file DefaultTableRowFiltering.aspx.

23. Open the DefaultTableRowFiltering.aspx file.

24. Add one more DynamicField control to the P:System.Web.UI.WebControls.GridView.Columns property and set the P:System.Web.DynamicData.DynamicField.DataField property to "ProductModel".

The ProductModel and the ProductCategory columns are the two foreign keys for which Dynamic Data automatically create a UI to filter table rows. The following example shows the markup for the GridView control after you add the new DynamicField control.

<asp:GridView ID="GridView1" runat="server"
    DataSourceID="LinqDataSource1" AutoGenerateColumns="false"
    AllowPaging="true" AllowSorting="true">
    <Columns>
        <asp:DynamicField DataField="ProductCategory" />
        <asp:DynamicField DataField="ProductModel" />
        <asp:DynamicField DataField="Name" />
        <asp:DynamicField DataField="Color" />
        <asp:DynamicField DataField="Size" />
   </Columns>
</asp:GridView>

25. In the markup before the data-bound control, replace the T:System.Web.DynamicData.DynamicFilter control and the T:System.Web.UI.WebControls.Label control with a T:System.Web.DynamicData.QueryableFilterRepeater control, as shown in the following example.

<asp:QueryableFilterRepeater ID="FilterRepeater1" runat="server">
</asp:QueryableFilterRepeater>

 

26. In the ItemTemplate element of the T:System.Web.DynamicData.QueryableFilterRepeater control, add a T:System.Web.DynamicData.DynamicFilter control, as shown in the following example:

<asp:QueryableFilterRepeater ID="FilterRepeater1" runat="server">
    <ItemTemplate>
        <asp:DynamicFilter ID="DynamicFilter" runat="server" />
    </ItemTemplate>
</asp:QueryableFilterRepeater>

The T:System.Web.DynamicData.DynamicFilter control automatically generates a T:System.Web.UI.WebControls.DropDownList control for each column type that has a related default filter template. By default, only Boolean and foreign-key columns have filter templates. The T:System.Web.UI.WebControls.DropDownList control enables the user to select the column value for filtering the table rows.

27. Add a T:System.Web.UI.WebControls.Label control before the T:System.Web.DynamicData.DynamicFilter control.

Dynamic Data uses the Label control to display a name for any column that can be used for data filtering.

The following example shows the markup for a T:System.Web.UI.WebControls.Label that displays the names of the columns to use for data filtering.

<asp:QueryableFilterRepeater ID="FilterRepeater1" runat="server">
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" 
            Text='<%# Eval("DisplayName") %> '/>
        <asp:DynamicFilter ID="DynamicFilter" runat="server" />
    </ItemTemplate>
</asp:QueryableFilterRepeater>

28. In the T:System.Web.UI.WebControls.QueryExtender control, set the T:System.Web.DynamicData.DynamicFilterExpression ControlID property to the ID of the T:System.Web.DynamicData.QueryableFilterRepeater control, as shown in the following example:

<asp:QueryExtender ID="QueryExtender1" runat="server" 
    TargetControlID="LinqDataSource1">
    <asp:DynamicFilterExpression ControlID="FilterRepeater1" />
</asp:QueryExtender>

29. Save and close the file.

30. In Solution Explorer, right-click the DefaultTableRowFiltering.aspx page and then select View in Browser.

The page displays the defined Products columns and the UI for filtering the products by category and by model.

31. In the ProductCategory drop-down control, select a category.

Dynamic Data filters the products displayed based on the category you selected.

32. In the ProductModel drop-down control, select a model.

Dynamic Data filters the products displayed based on the model you selected.

33. Close the browser.

Testing Table Row Filtering

You can now test and compare the table row filtering pages that you just created. This lets you make sure that Dynamic Data filtering capabilities have been integrated in the Web site and compare the methods used. You can interact with the database and verify that the application works as expected.

To test and compare table row filtering

34. In Solution Explorer, right-click the ForeignKeyTableRowFiltering.aspx page and then select View in Browser.

The page displays the defined Products columns and the UI for filtering the products by category. Notice that this is the column that you specifically configured to create the UI for table row filtering.

35. Close the ForeignKeyTableRowFiltering.aspx page.

36. In Solution Explorer, right-click the DefaultTableRowFiltering.aspx page and then select View in Browser.

The page displays the defined Products columns and the UI for filtering the products by category and by model. Notice that Dynamic Data has automatically created a UI for category and model filtering. This shows how you can use declarative syntax to instruct Dynamic Data to generate the UI and table row filtering for all the column types for which a default filter template exists.

37. Close the browser.

Next Steps

This walkthrough has illustrated the basic principles of how to add data filtering to an ASP.NET Dynamic Data Web site. You have seen how to enable data filtering using a specific column or automatically. You might want to experiment with additional features. Suggestions for additional exploration include the following:

See Also

How to: Filter Data Using Values from a Parent Table in Dynamic Data.

How to: Filter Table Rows Using Foreign Key in Dynamic Data

How to: Filter Table Rows Using Default Filter Templates in Dynamic Data

ASP.NET Dynamic Data Overview

Posted by morebits | 3 Comments
Filed under:

Customize Table Rows Filtering in Dynamic Data

Introduction

ASP.NET Dynamic Data enables you to use page markup to filter the table rows to display and provides the UI that enables the user to enter the values needed for custom row filtering. Dynamic Data will infer the filter template for creating the UI based on the column type. By default, Boolean and foreign-key columns are used for filtering.

Custom filtering requires the following steps:

  1. Define table row filtering. Add a System.Web.DynamicData.DynamicFilter control and configure it for the desired filtering column. This allows for creating the UI that enables the user to perform table row filtering.
  2. Define data source filtering information. Add a System.Web.UI.WebControls.QueryExtender and configure it to reference the System.Web.DynamicData.DynamicFilter control. This allows for passing filtering information to the data source control on the page.

This lets you perform data filtering by using simple page markup without requiring knowledge of the data source control and of the database query details.

Multiple System.Web.DynamicData.DynamicFilter  controls can be used to allow for multiple filtering criteria.

The following figure shows the process that Dynamic Data elements follow in order to implement filtering.

These are the steps followed:

  1. The System.Web.DynamicData.DynamicFilter  control passes the user's selected value to the System.Web.UI.WebControls.QueryExtender control.
  2. The System.Web.UI.WebControls.QueryExtender control uses the value to create the query filtering information. Then it passes this information to the data source control.
  3. The data source control passes the filtering query information to the data source provider.
  4. The data source provider passes the query to the database.
  5. The database returns the filtered table rows.
  6. The data source provider sends this data back to the data source control.
  7. This control finally passes the filtered table rows to the data-bound control for display.

Dynamic Data Table Rows Filtering Elements

QueryTablesDefaultFilterTemplates

Procedures

To define table row filtering

  1. In Visual Studio, in a Dynamic Data Web site, create or open an ASP.NET Web page. The procedure assumes that a data source control to access the database and a related data-bound control to display the tables exist.
  2. Add a System.Web.DynamicData.DynamicFilter  control to the page. Set the DataField property to the name of the column that is used to filter the rows from the table. The following example shows the markup for a System.Web.DynamicData.DynamicFilter control that specifies the name of the column to use for data filtering.
<asp:DynamicFilter ID="CategoryFilterID" DataField="ProductCategory"   runat="server"/>

Dynamic Data will infer the filter template to use based on the column type. It will throw a System.InvalidOperationException if the column type does not have an associated default filter template.

To define data source filtering information

  1. Add a System.Web.UI.WebControls.QueryExtender control to the page. Set the TargetControlID property to the ID of the data source control that you want to extend. The following example shows the markup for a System.Web.UI.WebControls.QueryExtender control that points to the extended data source control. 
  2. <asp:QueryExtender ID="QueryExtenderID" TargetControlID="GridDataSource" runat="server"/></asp:QueryExtender>

  3. Add a System.Web.UI.WebControls.DynamicFilterExpression object as a child of the System.Web.UI.WebControls.QueryExtende control
  4. Set the System.Web.UI.WebControls.DynamicFilterExpression ControlID property to the identifier of the System.Web.DynamicData.DynamicFilter control.The following example shows the markup for a System.Web.UI.WebControls.QueryExtende control that includes the filter to use for querying the database.

<asp:QueryExtender ID="QueryExtenderID" TargetControlID="GridDataSource" runat="server"/>

    <asp:DynamicFilterExpression ID="CategoryFilterID"/>

</asp:QueryExtender>

Example

The following example uses the ForeignKey.ascx filter template to create a System.Web.UI.WebControls.DropDownList control for the Products foreign key column ProductCategory. When the user selects a value from this control, the example displays only those Products table rows that contain that value.

Refer to the attached files.

Note:

  • Dynamic Data defaults to the Boolean filter template. You do not need to specify it. The example just shows how to apply a filter template to a specific data field, if you need to.
  • The aspX prefix is temporary for this preview. It will change to asp in the final release.

Compiling the Code

This example requires the following:

  • A Dynamic Data Web site or a Dynamic Data Web application.
  • The AdventureWorksLT sample database. ·
  • A data context object that is registered in the Global.asax file.
Posted by morebits | 1 Comments
Filed under:

Attachment(s): CustomizeTableRowFiltering_VB.zip

Configuration API: Using System.Configuration.ConfigurationManager

Summary: This post shows a console application that uses the ConfigurationManager class. The code example extends what is already in the current documentation to demonstrate the use of this class. The example has been built using Microsoft Visual Studio 2008 and the .NET Framework 3.5.

The ConfigurationManager class enables a Web or Windows application to access machine, application, and user configuration files. The  name and location of the configuration files depend on whether you are working with a Web application or a Windows console application. For more information, see Application Configuration Files.

 

You can use this example to build a console application by simply replacing the program file in a console project. For information about how to build a console application, see How to: Create a Console Application.

Note   To compile this example, you must add a reference to the System.Configuration assembly to the  project.

 

 

The example works with a custom configuration section that stores color information for the background and foreground of the console window. The custom configuration section lets you do the following:

  • Create custom information to store in several configuration files, such as the configuration file for roaming users and the default application configuration file that applies to all users.
  • Specify what configuration file and where in the configuration hierarchy the section can be stored or overridden.

     

The example contains the classes described next and shown in the following picture:

ConfigurationManagerSample

  • ConsoleSection. This class defines a custom section that the application uses to create custom configuration sections at the specified level in the configuration hierarchy (that is, in the appropriate configuration files). This enables users who have sufficient access rights to make changes to the configuration files.
  • ConsoleElement. This class is used by CustomSection. This element stores background and foreground colors that the application applies to the console window. The console color information is stored in different configuration files. The values used to define colors depend on which file the color settings are stored in.
  • UsingConfigurationManager. This class is the example core class and is used by the application to exercise the main ConfigurationManager capabilities. It performs the following tasks:

·         Gets the roaming configuration file associated with the application.

 

·         Gets the application configuration file associated with the application.

 

·         Accesses a specified configuration file through mapping.

·         Accesses the machine configuration file through mapping.

·         Reads a specified configuration section.

·         Reads the connectionStrings section.

·         Reads or writes the appSettings section.

 

  • ApplicationMain. This class contains the application Main function and is used to obtain user's input and to provide feedback. It exercises the ConfigurationManager by calling its methods, based on the user's selection.

For a complete example, see the attached files. 

We look forward to your comments and feedback.

 

 

Posted by morebits | 1 Comments
Filed under:

Attachment(s): ConfigurationManager.zip

Querying a Table By a Data Key in Dynamic Data

Summary: Query a child table using a column from a parent table. A simpler example of this would be if the column belongs to the same table. This topic uses two tables related by a parent-child relationship. The parent table contains the data key that is the foreign key in the child table. See the following picture.

ForeignKey

A query is built based on the values assigned to the foreign key. The selection of the values for querying the data source is performed in a source data-bound control. The results of the query are shown in a target data-bound control.

Under the Hood

The following picture shows the main elements involved during querying (filtering).

Data Key Filtering Elements

Procedural Steps

To query a table by a data key, you must perform the following steps:

Setting the Source Data-Bound Control

  • In a page, declare the source data-bound control to display the data from the Categories  parent table. Sets its DataSourceID property to point to the data source control that queries the table. The following example shows how to do it:
    <asp:GridView ID="SourceGridView" DataSourceID="GridDataSource"   runat="server">
    .........
    </asp:GridView>
  • Declare the data source control that queries the Categories  parent table. The following example shows how to do it:
<aspX:LinqDataSource ID="GridDataSource"  runat="server" EnableDelete="true" 
               EnableUpdate="true" ContextTypeName="DynamicDataProject.NorthwindDataContext"
               TableName="Categories">
</aspX:LinqDataSource>

Setting the Target Data-Bound Control

  • Declare the target data-bound control to display the data from the Products child table. Sets its DataSourceID property to point to the data source control that queries the table. The following example shows how to do it:
    <asp:GridView ID="TargetGridView"  DataSourceID="DetailsDataSource" runat="server">
    .........
    </asp:GridView>
  • Declare the data source control that queries the Products child table. The following example shows how to do it:
<aspX:LinqDataSource ID="DetailsDataSource"  runat="server" EnableDelete="true" 
               EnableUpdate="true" ContextTypeName="DynamicDataProject.NorthwindDataContext"
               TableName="Products">
</aspX:LinqDataSource>

Setting the Query

  • Declare the <asp:QueryExtender> control. Sets its TargetControlID property to point to the data source control that queries the Products child table.
  • Declare the <asp:ControlFilterExpression> as a child of the <asp:QueryExtender> control.   Sets its ControlID property to point to the source data-bound control. Sets its Column property to point to the Category column in the Categories parent table. This enables you to filter products based on category values.   The following example shows how to do it:
<aspX:QueryExtender TargetControlID="DetailsDataSource" runat="server">
    <asp:ControlFilterExpression  ControlD="SourceGridView"  Column="Category" />
</aspX:QueryExtender>

Note:

  • The aspX prefix is temporary for the current Dynamic Data preview. It will change to asp in the final release.

For a complete example, see the attached files.

Posted by morebits | 3 Comments

Attachment(s): QueryProductsByDataKey.zip

Querying a Table By a Foreign Key using Dynamic Data Filter

Summary: This post shows how to query a child table using a column from a parent table in dynamic data filtering.  It shows how to use the ForeignKey filter template to query the products using the Category data field. The ForeignKey filter template is specified declaratively. This is because it must override the MultiForeignKey template specified in the partial class or data model. 

Note: You specify the filter template in the data model when you want to apply it globally to your application. You specify it in a page when you want to apply it just to that page. 

The ForeignKey filter template displays a drop-down list. This enables the user to select a category when displaying the products. By default all the categories are selected so that all the products are displayed. The ForeignKey filter template enables the selection of only one category at the time. By contrast, the MultiForeignKey filter template enables the selection of multiple categories.
The Category data field, to which the filter is applied, represents a foreign key (FK). As consequence, the ForeignKey filter obtains its selection values from the Category table.

The following are the key steps to filter the products by Category:

  • Declare the filter template to reference. You do this using the <asp:DynamicFilter> control as follows:
<asp:DynamicFilter  runat="server" ID="CategoryFilterID"  Filter="ForeignKey"
    DataField="Category" OnFilterChanged="OnFilterSelectedIndexChanged" />
  • Add the <asp:DynamicFilterExpression> as an element of the <asp:QueryExtender> control. Set its ControlID property to point to the previously declared  filter as follows:
<aspX:QueryExtender ID="QueryExtender1" TargetControlID="GridDataSource" runat="server">
      <asp:DynamicFilterExpression ControlID="CategoryFilterID" />
</aspX:QueryExtender>

For a complete example, see the attached files.

Analyzing the Dynamic Data 4.0 Preview

Introduction

What: Create your own project, called DynamicDataProject, that mimics the SampleProject shipped with ASP.NET Dynamic Data 4.0 Preview available on CodePlex.

Why: The objective is to analyze the new Dynamic Data features and build gradually complex samples that exercise those features. In the process I will highlight the main elements that you must know to understand the new features. At least that's what I hope to accomplish. You will be the judges.

Our software engineers did an excellent job in creating a set of projects to show the new Dynamic Data 4.0 features. For my own education, I decided to start from scratch by recreating these projects and adding my own examples that I will share in subsequent posts. Because I found this exercise very helpful, I decided to start sharing this information with you as I progress.

Overview

The Dynamic Data 4.0 Preview contains Web projects that illustrate the next generation of Dynamic Data features including:

  • A Web site that uses scaffolding and interacts with the database using both Linq to Sql and Entity Framework models.
  • A new Dynamic Data filter model that enables the developers to apply templates to pages just like field templates, including custom filters. This model will be supported by a new QueryExtender control that simplifies common data filtering operations. This control provides a rich ASP.NET declarative query syntax that makes it easy to do things like search data for text or have filters based on ranges.
  • Support for Database constructs such as inheritance for Entity Framework and Linq to SQL; many to many relationships in Entity Framework.
  • New Entity Templates which allow finer control over how an object is displayed and edited.
  • Attributes for controlling the filters appearance and order.
  • A BusinessLogicDataSource control that uses a data provider model which enables the developers to build their own custom business logic.
  • A datasource control for ADO.NET Data Services that works with ASP.NET and an ADO.NET Data Service Provider for Dynamic Data.

DynamicDataProject

As I said before, I am going to build the DynamicDataProject from the ground up. I will then use it to host my own examples. The project will show the use of the following features:

  • A Web site that uses scaffolding and interacts with the database using both Linq to Sql and Entity Framework models.
  • A new Dynamic Data filter model that enables the developers to apply templates to pages just like field templates, including custom filters. This model will be supported by a new QueryExtender control that simplifies common data filtering operations. This control provides a rich ASP.NET declarative query syntax that makes it easy to do things like search data for text or have filters based on ranges.
  • Support for Database constructs such as inheritance for Entity Framework and Linq to SQL; many to many relationships in Entity Framework.
  • New Entity Templates which allow finer control over how an object is displayed and edited.

The following is the project file organization:

dynamicdataproject

Create the DynamicDataProject

The following are the steps to create the project.

  • In Visual Studio create a new project.
  • Select Web as the project type.
  • Select the Dynamic Data Web Application template.
  • In the Name box enter DynamicDataProject.

Reference the new Dynamic Data Assemblies

To use the new Dynamic Data features you must access the assemblies containing the new types which are not part of the product yet. Enabling the use of these types is achieved by adding the new DLLs to the project and modifying the Web.config file as shown next.

Adding DLLs Referemce

The following are the steps you must perform.

  • Download Dynamic Data 4.0 Preview from Codeplex.
  • Install the downloaded software.
  • From the bin folder in the SampleProject copy the following DLLs into the bin folder of your DynamicDataProject project:
    • Microsoft.Web.Extensions.dll
    • System.ComponentModel.DataAnnotations.dll
    • System.Web.DynamicData.dll
    • AjaxControlToolkit.dll
  • In the Solution Explorer of the DynamicDataProject project right click on the References folder and select Add Reference.
  • Select the Browse tab and navigate to the DynamicDataProject bin folder.
  • Add the DLLs. Remember to remove the old version of the DLLs first.

Modify Web.config File

The following are the steps you must perform. If you have issues, look at the web.config file in the downloaded SampleProject.

  • Add the System.Data.Entity entry to the <assembly> element.
  • In the <controls> element change the previously added DLLs' version number to 99.0.0.0. Also add the AjaxControlToolkit entry to define the ajaxToolkit tag prefix.
  • In the <dependentAssembly> element, add the System.ComponentModel.DataAnnotations and System.Web.DynamicData. This is to allow binding redirect from the older to the 99.0.0.0 DLL’s version.

Add the Database and Create Related Models

The database is a key element in a Dynamic Data Web site. The following steps describe how to add the Northwind database to your site.

  • Copy the Northwind.mdf file from the downloaded project to the DynamicDataProject App_Data folder.
  • Add the database models. The models contain the classes that are mapped to Nowthwind relational objects that enable Dynamic Data to access the underlying database.

For more information on this topic, see  Walkthrough: Creating a New ASP.NET Dynamic Data Web Site Using Scaffolding.

 

Modify Global.asax

You must modify the Global.asax file to allow the use of multiple modelsby copying over the changes from the SampleProject/Global.asax. For more information, see David’s post Using Dynamic Data with multiple databases.

Notice the following:

  • The RegisterRoutes method has been modified to allow registration of data context for both LinqToSQL and Entity Framework. It calls the RegisterModelRoutes to initialize page templates routing accordingly.
  • The RegisterModelRoutes method has been modified to use the flag useSeperatePages to select one of the following page display modes:
    • Combined-page mode, where the List, Detail, Insert, and Update tasks are performed by using the same page.
    • Separate-page mode, where the List, Detail, Insert, and Update tasks are performed by using separate pages.

Modify the DynamicData Folder

The DynamicData folder created by Visual Studio when you selected the Dynamic Data Web Application template contains elements that are no longer valid. Keep the Images folder, the FilterUserControl.ascx and GridViewPager.ascx controls. Delete all the other folders.

Modify Project Root Directory

You must modify the project root directory as described next.

Copy Infrastructure Elements

Copy the following files from the downloaded SampleProject:

  • Default.aspx. This file has been modified to display both models.
  • Site.css. It contains the styles used by the site.
  • Site.master. It contains the master page used by the site.
  • AutocompleteFilter.asmx. This service is needed by the Autocomplete.ascx filter.
  • AutocompleteStyle.css. It contains the styles used during auto complete.
  • AjaxToolKit.css. It contains the styles used by the Ajax toolkit controls.
  • NorthwindPartials.cs. It contains the partial classes that enable you to apply custom metadata information.
  • DynamicDataL2S folder. Copy the SampleProject/DynamicDataL2S folder to your Web site root directory. The DynamicDataL2S folder contains the templates needed by Dynamic Data to function. It also contains the new entity templates and filters in the related folders. The DynamicDataL2S elements apply to the Linq to Sql model.
  • DynamicDataEF folder. Copy the SampleProject/DynamicDataEF folder to your Web site root directory. This folder contains the templates needed by Dynamic Data to function. It also contains the new entity templates folder. The DynamicDataEF elements apply to the Entity Framework model.
Copy Samples

Copy the following sample folders from the downloaded SampleProject:

  • EntityTemplateSamples folder. Copy the SampleProject/ EntityTemplateSamples folder to your Web site root directory. This folder contains the pages/samples that show how to use the templates.
  • FitlerSamples folder. Copy the SampleProject/ FitlerSamples folder to your Web site root directory. This folder contains samples showing how to use the filters.

Add MySamples Folder

This folder contains my examples that exercise the new Dynamic Data features. Refer to these related posts:

Posted by morebits | 1 Comments

Welcome

Welcome to my "technical notes" blog.
Posted by morebits | 2 Comments
Filed under:
 
Page view tracker