Microsoft ADO .NET 4 Step by Step - p 40 ppsx

10 137 0
Microsoft ADO .NET 4 Step by Step - p 40 ppsx

Đang tải... (xem toàn văn)

Thông tin tài liệu

366 Microsoft ADO.NET 4 Step by Step <! This is just the connection string portion of the Web.config file. > <connectionStrings> <add name="StepSampleConnectionString1" connectionString="Data Source=(local)\SQLExpress; Initial Catalog=StepSample;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> The content can vary depending on your database configuration. The actual data binding occurs through the data-enabled features of the Gr idView control. <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CourseID" DataSourceID="SqlDataSource1" EmptyDataText="There are no data records to display."> <Columns> <asp:BoundField DataField="CourseID" HeaderText="CourseID" ReadOnly="True" SortExpression="CourseID" /> <asp:BoundField DataField="CourseName" HeaderText="CourseName" SortExpression="CourseName" /> <asp:CheckBoxField DataField="OfferedFall" HeaderText="OfferedFall" SortExpression="OfferedFall" /> <asp:CheckBoxField DataField="OfferedSpring" HeaderText="OfferedSpring" SortExpression="OfferedSpring" /> <asp:BoundField DataField="CreditHours" HeaderText="CreditHours" SortExpression="CreditHours" /> <asp:BoundField DataField="Prerequisite" HeaderText="Prerequisite" SortExpression="Prerequisite" /> </Columns> </asp:GridView> The control’s DataSourceID references the SqlDataSource instance that will supply the bound data. Within the control’s Columns tag, a collection of asp:BoundField instances and their DataField attributes identify the path needed to locate the display data within the source. The control also includes an EmptyDa taText attribute that adjusts the grid’s content in the running application if the source lacks data records. It’s a surprisingly small amount of code for the functionality it brings to the web page, and it works without adding a single line of custom C# or Visual Basic code. Chapter 21 Binding Data with ADO.NET 367 Summary This chapter introduced some of the data binding options available in different flavors of Visual Studio projects: Windows Forms, Windows Presentation Foundation, and ASP.NET. With little more than wizard-based database configuration followed by some mouse clicks, Visual Studio can generate a working application that displays—or in some cases enables editing of—data from an external source. The samples included in this chapter provide only the most basic examples of what is pos- sible with data-bound controls. If you forgo the simple drag-and-drop methods and use the examples as a starting point for data binding concepts, you can craft complex, interactive ap- plications that depend on the intelligent data-linking features included in most Visual Studio user interface controls. Chapter 21 Quick Reference To Do This Create a simple data-bound Windows Forms application Create a new Windows Forms project. Add a data source to the project that exposes the rel- evant data table(s). Drag a table from the data source to the surface of a form. Create a simple data-bound Windows Presentation Foundation application Create a new WPF application. Add a data source to the project that exposes the relevant data table(s). Drag a table from the data source to the surface of a window. Create a simple data-bound ASP.NET application Create a new ASP.NET application. Ensure that the target database is available in the Server Explorer (or Database Explorer). Drag a table from the Server Explorer (or Database Explorer) to the surface of a page. Chapter 22 Providing RESTful Services with WCF Data Services After completing this chapter, you will be able to:  Create model-based data services  Understand REST and its interaction with a data service  Make database queries using specially constructed URIs The Internet is a disconnected world. Except for brief moments of connectivity, web pages spend most of their time separated from the servers that provide their data. This reality makes it difficult, if not impossible, to implement a traditional client-server or n-tier database application. Instead, some Web-based applications use a new service-oriented model of re- questing and updating data at the server. This chapter introduces some ADO.NET-related technologies that take advantage of this service-focused methodology. WCF Data Services provides a standardized way of exposing Entity Framework (EF) data and other ADO.NET data content to Web-based clients. REST, short for representational state transfer, provides a method of querying and updating data service content using URIs and other standardized Web-based interfaces. Getting to Know the Service Layers Exposing entity data through a service-oriented RESTful interface involves multiple layers of data libraries. Some of them have already been covered in this book, including the Entity Framework modeling layer that provides the core access to the data. WCF Data Services and the REST interface provide two additional layers that make the service-based movement of data to a web client a reality. Introducing WCF Data Services Windows Communication Foundation (WCF) Data Services began its life as ADO.NET Data Services in Microsoft’s version 3.5 update to the .NET Framework and in the accompanying Visual Studio 2008 SP1 release. The library is Microsoft’s implementation of the Open Data Protocol, a Web-based standard for querying and updating data from a wide array of data sources. The Open Data Protocol is sponsored by Microsoft. 370 Note Learn more about the Open Data Protocol and its objectives at the specification’s official web site: www.odata.org. WCF Data Services are ASP.NET services as expressed through a .svc service file in an ASP.NET project. Clients make query and data-update requests by accessing the service using stan- dard HTTP operations. Note In addition to ASP.NET, WCF Data Services can be expressed directly through Microsoft’s Internet Information Services (IIS), through a standalone WCF service, or through any other net- work service that supports the IDataServiceHost interface. This chapter discusses only the ASP.NET service interface. The goal of a WCF Data Service is to present a collection of data, such as an EF model, in a form that can be queried by something as basic as a specially formed web page address. The system has a strong preference for EF conceptual models, making exposure of model data as easy as creating a derived class instance. WCF Data Services uses a set of source providers to express different types of source data. The Entity Framework provider handles EF conceptual models. Services can also expose data from standard .NET objects that implement the IQueryable interface via the Reflection pro- vider. (If a model supports the IUpdatable interface, clients will be able to update source data as well through that same provider.) Custom Data Service Providers let you create late-bound data services that indicate the available data collections as they are accessed. Note This chapter examines only the Entity Framework provider. By default, data exposed by the service is in the form of an Atom Publishing Protocol (AtomPub) XML document. JavaScript Object Notation (JSON) is also supported. Queries of individual scalar properties return data either in a simple XML wrapper (the default) or as plain-text data. All classes involved in setting up WCF Data Services appear in the System.Data.Serv ices namespace. Introducing REST Representational state transfer is a software architecture for managing distributed text and media content in a client-server environment. It documents a standardized interface for re- questing distributed hypermedia content in a stateless manner. Chapter 22 Providing RESTful Services with WCF Data Services 371 The type of content being retrieved is not REST’s concern. Instead, the architecture focuses on the rules and tools used to locate and transfer the content. If you’ve ever browsed the Internet, you are already well versed in REST because the World Wide Web is, with its distrib- uted content and its standardized set of request verbs, the largest implementation of a REST- based (or “RESTful”) system. WCF Data Services—and the Open Data Protocol on which it is based—is a RESTful system. The services you create in ASP.NET can expose a variety of source data, but the interfaces and commands used to access that data are standardized. For the convenience of discussion in this chapter, RESTful refers to the HTTP transport and the constructed URIs or HTTP re- quests that access data from an exposed service. The URIs for REST requests use a syntax that reflects the structure of the data and the query capabilities inherent in an EF model. Data components, such as entity and property names, are added to the URI after the service address. For example, a request to return all entities in the “Customers” entity set might use the following URI: http://example.com/ExampleService.svc/Customers In a more complex example, the following URI returns the ID numbers and totals (in de- scending order) for all of a specific customer’s orders: http://example.com/ExampleService.svc/Customers(3492L)/ OrderEntries?$orderby=OrderTotal desc&$select=ID,OrderTotal Setting Up a Data Service WCF Data Services implementations typically appear as web services and are built as part of an ASP.NET application. You can create a new service based on an Entity Framework model in just a few steps: 1. Create a new ASP.NET web application using either C# or Visual Basic. 2. Add an ADO.NET Entity Data Model to your project and generate the conceptual mod- el from a database. The “Using the Entity Data Model Wizard” section of Chapter 14, “Visualizing Data Models,” walks you through this process. 372 Microsoft ADO.NET 4 Step by Step 3. Add a new WCF Data Service item to your project. This action adds a new class file to your project that derives from System.Data.Services.DataService(Of T). The new file in- cludes some boilerplate code that you can modify to meet the needs of your service. At the very least, you must modify this template to identify the name of your EF entity container (for the “Of T” part of the generic definition). 4. Configure the new data service to indicate which portions of the entity model are avail- able for use by clients. These changes occur in the InitializeService method of the new service class. The method already appears in the generated class code; you just need to customize it. The following exercise exposes an Entity Framework data model as a WCF Data Service. Creating a Data Service from an EF Model: C# Note If you are using Microsoft Visual C# 2010 Express as your development tool, you must download and install Microsoft Visual Web Developer 2010 Express to complete the exercises in this chapter. Visit www.microsoft.com/express to download Express products. 1. Create a new ASP.NET web application project. 2. Add a new ADO.NET Entity Data Model to the project. (See the “Importing Database Tables as Entities” exercise on page 227 in Chapter 14 for step by step instructions.) Name the model file SalesOrder.edmx. When the Entity Data Model Wizard prompts you to store the connection string in the Web.config file, select that option. 3. On the wizard’s Choose Your Database Objects panel, add the Customer, OrderEntry, and StateRegion tables to the model. Set the Model Namespace field to SalesOrderModel. Click Finish to complete the wizard. 4. In the properties for the SalesOrder.edmx model, make sure that the EntityContainerName property is set to SalesOrderEntities. Save and close the model file. 5. Add a new WCF Data Service item to the project, naming it SalesOrder.svc. The new file appears in your project with the following class code already included (comments removed for clarity): public class SalesOrder : DataService< > { public static void InitializeService(DataServiceConfiguration config) { config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } } Chapter 22 Providing RESTful Services with WCF Data Services 373 6. In the initial class definition clause, replace the DataService< > base class definition (and any content contained within the angle brackets) with DataService<SalesOrder Entities>. This change tells the service which Entity Framework model to use as the data source. 7. Add the following statement to the SalesOrder class in the InitializeService method: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead); This line tells the service to allow full read access to all the model’s entities. 8. Run the application. Visual Studio starts the service using its built-in web server. Next, it opens a web browser and points it to the address of the new service. The service re- turns information about the service’s available features in the default AtomPub format. Note Depending on the configuration of your web browser, the XML content might or might not appear in the browser window. Creating a Data Service from an EF Model: Visual Basic Note If you are using Microsoft Visual Basic 2010 Express as your development tool, you must download and install Microsoft Visual Web Developer 2010 Express to complete the exercises in this chapter. Visit www.microsoft.com/express to download Express products. 1. Create a new ASP.NET web application project. 374 Microsoft ADO.NET 4 Step by Step 2. Add a new ADO.NET Entity Data Model to the project. (See the “Importing Database Tables as Entities” exercise on page 227 in Chapter 14 for step-by-step instructions.) Name the model file SalesOrder.edmx. When the Entity Data Model Wizard prompts you to store the connection string in the Web.config file, select that option. 3. On the wizard’s Choose Your Database Objects panel, add the Customer, OrderEntry, and StateRegion tables to the model. Set the Model Namespace field to SalesOrderModel. Click Finish to complete the wizard. 4. In the properties for the SalesOrder.edmx model, make sure that the EntityContainerName property is set to SalesOrderEntities. Save and close the model file. 5. Add a new WCF Data Service item to the project, naming it SalesOrder.svc. The new file appears in your project with the following class code already included (comments removed for clarity): Public Class SalesOrder Inherits DataService(Of [[class name]]) Public Shared Sub InitializeService(ByVal config As DataServiceConfiguration) config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2 End Sub End Class 6. In the Inherits clause of the SalesOrder class definition, replace [[class name]] with SalesOrderEntities. This change tells the service which Entity Framework model to use as the data source. 7. Add the following statement to the SalesOrder class in the InitializeService method: config.SetEntitySetAccessRule("*", EntitySetRights.AllRead) This line tells the service to allow full read access to all of the model’s entities. 8. Run the application. Visual Studio starts the service using its built-in web server. Next, it opens a web browser and points it to the address of the new service. The service re- turns information about the service’s available features in the default AtomPub format. Chapter 22 Providing RESTful Services with WCF Data Services 375 Note Depending on the configuration of your web browser, the XML content might or might not appear in the browser window. Defining Service Rights By default, the WCF Data Service exposes none of the entity sets included in a model for client queries. To access any data, you must configure the data rights available to RESTful callers. This configuration occurs in the derived DataService(Of T) class’ InitializeService method. The service host calls this routine once at startup to determine the features activated for the service. When you add a new WCF Data Service to your project, the InitializeService method already includes one configuration setting, which is updated using the passed-in config parameter, an instance of DataServiceConfiguration. C# config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; Visual Basic config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2 . www .microsoft. com/express to download Express products. 1. Create a new ASP .NET web application project. 3 74 Microsoft ADO. NET 4 Step by Step 2. Add a new ADO. NET Entity Data Model to the project 366 Microsoft ADO. NET 4 Step by Step <! This is just the connection string portion of the Web.config file. > <connectionStrings> <add name="StepSampleConnectionString1". the “Importing Database Tables as Entities” exercise on page 227 in Chapter 14 for step- by -step instructions.) Name the model file SalesOrder.edmx. When the Entity Data Model Wizard prompts you

Ngày đăng: 05/07/2014, 19:20

Tài liệu cùng người dùng

Tài liệu liên quan