Professional Visual Basic 2010 and .neT 4 phần 5 pps

133 345 0
Professional Visual Basic 2010 and .neT 4 phần 5 pps

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

When the minimum distance has been determined, the Send(SqlDataRecord) method of the SqlPipe class is used to write the data to the output stream, returning it to the calling function. The CopyRow function is used to create the SqlDataRecord to return. The fi rst step in creating a SqlDataRecord is to defi ne the columns of data. The constructor for the SqlDataRecord requires an array of SqlMetaData objects that defi ne each column. The preceding code uses the List generic collection to make defi ning this array easier. Once the columns are defi ned, the data returned from the GetValues method is used to populate the columns of the new SqlDataRecord . Exposing Web Services from SQL Server Another feature of SQL Server is the capability to expose Web services directly from the server. This means there is no requirement for IIS on the server, as the requests are received and processed by SQL Server. You defi ne what ports will be used to host the Web service. The structure of the Web service is defi ned based on the parameters and return data of the function or stored procedure you use as the source of the Web service. Exposing Web services directly from SQL Server is supported only on the Standard and higher editions. The Express and Compact editions do not support creating Web services in this manner. When you are architecting a scenario and plan to expose Web services from SQL Server, keep in mind at least one important question: Why do you think you need to expose this database functionality outside of the SQL Server? It ’ s not a trivial question. It means that you plan on hanging data off of the server, possibly for public access. That ’ s a potentially dangerous scenario not to be taken lightly. Most of the scenarios for which it makes sense to provide Web services directly from a SQL Server involve systems entirely behind a fi rewall, where Web services are used as the conduit between departments (typical A2A integration). This would be useful if the target departments were using another platform or database, or where security considerations prevented them from directly accessing the SQL Server. Following is the basic syntax of the CREATE ENDPOINT command. Although both AS HTTP and AS TCP are shown, only one can occur per CREATE ENDPOINT c o m m a n d . CREATE ENDPOINT endPointName [ AUTHORIZATION login ] STATE = { STARTED | STOPPED | DISABLED } AS HTTP ( PATH = 'url', AUTHENTICATION =( { BASIC | DIGEST | INTEGRATED | NTLM | KERBEROS } [ ,. . .n ] ), PORTS = ( { CLEAR | SSL} [ ,. . . n ] ) [ SITE = {'*' | '+' | 'webSite' },] [, CLEAR_PORT = clearPort ] [, SSL_PORT = SSLPort ] [, AUTH_REALM = { 'realm' | NONE } ] [, DEFAULT_LOGON_DOMAIN = { 'domain' | NONE } ] [, COMPRESSION = { ENABLED | DISABLED } ] ) AS TCP ( LISTENER_PORT = listenerPort [ , LISTENER_IP = ALL | ( < 4-part-ip > | < ip_address_v6 > ) ] ) FOR SOAP( [ { WEBMETHOD [ 'namespace' .] 'method_alias' ( NAME = 'database.owner.name' [ , SCHEMA = { NONE | STANDARD | DEFAULT } ] [ , FORMAT = { ALL_RESULTS | ROWSETS_ONLY } ] ) } [ ,. . .n ] ] [ BATCHES = { ENABLED | DISABLED } ] CLR Integration in SQL Server ❘ 489 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 490 ❘ CHAPTER 12 woRkiNG witH sQl sERVER [ , WSDL = { NONE | DEFAULT | 'sp_name' } ] [ , SESSIONS = { ENABLED | DISABLED } ] [ , LOGIN_TYPE = { MIXED | WINDOWS } ] [ , SESSION_TIMEOUT = timeoutInterval | NEVER ] [ , DATABASE = { 'database_name' | DEFAULT } [ , NAMESPACE = { 'namespace' | DEFAULT } ] [ , SCHEMA = { NONE | STANDARD } ] [ , CHARACTER_SET = { SQL | XML }] [ , HEADER_LIMIT = int ] ) The main points to consider when creating an endpoint are as follows: What stored procedure or function (or UDF) will you be exposing as a Web service? This is identified ➤ in the WebMethod clause. There may be multiple Web methods exposed from a single endpoint. If so, each will have a separate WebMethod parameter listing. This parameter identifies the database object you will expose, and allows you to give it a new name. What authentication will clients need to use? Typically, if your clients are part of the same network, ➤ then you use integrated or NTLM authentication. If clients are coming across the Internet or from non-Windows, then you may want to use Kerberos, Digest, or Basic authentication. What network port will the service use? The two basic options when creating an HTTP endpoint are ➤ CLEAR (using HTTP, typically on port 80) or SSL (using HTTPS, typically on port 443). Generally, use SSL if the data transmitted requires security, and you are using public networks. Note that Internet Information Services (IIS) and other Web servers also use these ports. If you have both IIS and SQL Server on the same machine, you should alternate ports (using CLEAR_PORT or SSL_PORT) for your HTTP endpoints. When creating TCP endpoints, select a LISTENER_PORT that is unused on your server. HTTP offers the broadest reach and largest number of possible clients, while TCP offers better performance. If you are making the Web service available over the Internet, you would generally use HTTP and TCP within the firewall, where you can control the number and type of clients. To continue our example, you can make the procGetClosestStoreWithStock procedure available as a Web service using the following code: CREATE ENDPOINT store_endpoint STATE = STARTED AS HTTP( PATH = '/footsore', AUTHENTICATION = (INTEGRATED), PORTS = (CLEAR), CLEAR_PORT = 8888, SITE = 'localhost' ) FOR SOAP( WEBMETHOD 'GetNearestStore' (name = 'fooStore.dbo.procGetClosestStoreWithStock'), WSDL = DEFAULT, SCHEMA = STANDARD, DATABASE = 'fooStore', NAMESPACE = 'http://fooStore.com/webmethods' ); Endpoints are created within the master database, as they are part of the larger SQL Server system, and not stored within each database. The endpoint defined in the preceding code creates a SOAP wrapper around the procGetClosestStoreWithStock stored procedure, making it available as GetNearestStore. Integrated security is used, which means that any users need network credentials on the SQL Server. If this service were available over the Internet, you might use Digest or Basic instead. As the server is also running IIS, this example moved the port for the service to 8888. Once the service has been created you can create clients based on the WSDL of the service. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Accessing the Web Service SQL Server makes some of the work easier when hosting Web services. The WSDL for the service is automatically generated. Many SOAP tools, such as Visual Studio, enable the creation of wrapper classes based on the WSDL for the service. The WSDL for a SQL Server Web service may be a little daunting when you first see it, as it’s quite lengthy. This is primarily because the WSDL includes definitions for the various SQL Server data types as well as for the Web services you create. Figure 12-30 shows part of the WSDL, the part created for the procGetClosestStoreWithStock procedure. You can view this WSDL by including the query ?WSDL to the end of the URL for the Web Service. FIGURE 1230 As you can see from the WSDL, two main structures are defined: GetNearestStore and GetNearestStoreResponse. The GetNearestStore document is what is sent to the Web service. It includes definitions of each of the columns sent, along with the expected data types and sizes. GetNearestStoreResponse is the return document. In the preceding sample, you can see that it is of type SqlResultStream. This type, also defined in the WSDL, is the tabular data stream returned from SQL Server. It consists of the return value from the stored procedure and any result sets of data. This will be converted to an Object array by the SOAP wrapper classes. You can then convert these data blocks to other types. When creating a Web service, it’s a good idea to create a simple form that can be used to test the service. Add a new Windows Forms Application project to the solution (or create a new Project/Solution). Select the Add Service Reference command from the Solution Explorer. Click the Advanced button on the Add Service Reference dialog and select Add Web Reference. From the Add Web Reference dialog, select the fooStore service (see Figure 12-31). CLR Integration in SQL Server ❘ 491 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 492 ❘ CHAPTER 12 woRkiNG witH sQl sERVER Once you have the connection to the Web service, you’re ready to begin laying out the fields of the test form. Most of the fields are TextBox controls, with the exception of the Product ComboBox and the DataGridView on the bottom. The Table 12-8 describes the properties set on the controls: FIGURE 1231 TABLE 128: Control Properties CONTROL PROPERTY VALUE TextBox Name StreetField TextBox Name CityField TextBox Name StateField MaxLength 2 TextBox Name ZipField ComboBox Name ProductList TextBox Name QuantityField Button Name GetNearestStoreButton Text &Get NearestStore DataGridView Name ResultGrid AllowUserToAddRows False AllowUserToDeleteRows False ReadOnly True Organize the controls on the form in any way you find aesthetically pleasing. Figure 12-32 shows one example. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com The code for the test form is as follows: Imports System.Data Imports System.Data.SqlClient Public Class MainForm Private Sub GetNearestStoreButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetNearestStoreButton.Click Using svc As New fooStore.store_endpoint Dim result() As Object Dim data As New DataSet svc.Credentials = System.Net.CredentialCache.DefaultCredentials result = svc.GetNearestStore(Me.StreetField.Text, Me.CityField.Text, Me.StateField.Text, Me.ZipField.Text, CInt(Me.ProductList.SelectedValue), CInt(Me.QuantityField.Text)) If result IsNot Nothing Then data = DirectCast(result(0), DataSet) Me.ResultGrid.DataSource = data.Tables(0) End If End Using End Sub Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds As New DataSet Using conn As New SqlConnection(My.Settings.FooStoreConnectionString) Using da As New SqlDataAdapter("SELECT id, Name FROM PRODUCTS", conn) da.Fill(ds) With Me.ProductList .DataSource = ds.Tables(0) .ValueMember = "id" .DisplayMember = "Name" End With End Using End Using End Sub End Class Code snippet from FooStore FIGURE 1232 CLR Integration in SQL Server ❘ 493 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 494 ❘ CHAPTER 12 woRkiNG witH sQl sERVER The test form consists of two methods. The Load method is used to retrieve the data that populates the product drop-down. The call to the Web service takes place in the Button click event. This method calls the Web service wrapper, passing in the values entered on the form. Recall that the Web service returns two result sets: the data and the return value. Run the test application. Enter an address close to one of the stores, and select a product and quantity you know to be available. Click the Get Nearest Store button. After a brief delay, the store’s address should appear (see Figure 12-33). Try again with a larger quantity or different product so that another store is returned. Depending on the stock available at each of the store locations, the nearest store may not be all that near. SQL Server 2008 Features Now that you’ve expended the effort to create your own geospatial data type, it’s time to tell you that you wasted your time. SQL Server 2008 includes a number of new data types, including two geospatial data types: geometry and geography. The geometry type is designed for smaller areas, when the curvature of the Earth is not significant, whereas the geography type is “curve aware.” There are a couple of benefits to using these types over creating your own. First, they are much more fully designed than the type you created earlier in this chapter. The geography data type includes a number of standard methods defined by the Open Geospatial Consortium. This standard ensures that your code is portable across multiple implementations. In the case of distance, this can be calculated using the STDistance method (all of the methods defined in the standard begin with “ST”). The geospatial types include methods for defining areas, calculating distances and areas, indicating whether areas intersect, and many others. Second, and probably more important, these types are defined within the Microsoft.SqlServer.Types namespace. As Microsoft created this namespace, they could do a little bit of “cheating” behind the scenes. This namespace does not require you to enable SQL CLR on your server to use them. This means you don’t need to do any additional configuration, and that a potential security hole is not activated. Converting the FooStore application to use the new types is relatively easy. First, you can change the data type of the GeoLocation column from the Location type created earlier to geography (see Figure 12-34). You should drop the table and recreate this, as the internal representation of the data in the column does not match the new data type. The second major change is that you no longer need the calculations behind the Distance method of the location object. This (rather ugly) calculation is encapsulated within the STDistance method, which takes a geography type and returns the distance as a SqlDouble. FIGURE 1233 FIGURE 1234 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com WCF DATA SERVICES In the previous two chapters, you have seen two of the major data access methods in the .NET Framework: “classic” ADO.NET and the Entity Framework. Deciding when to use one over the other depends on whether you’re working on new code versus existing code, and/or your desire to work with the latest and greatest technologies. In both cases, however, you can choose to access your data using either types specifically designed for each data access technology or your own types. Either way, it is assumed that you’re working on a network, and you can expect a .NET class at the other end. WCF Data Services (formerly ADO.NET Data Services) attempts to change that model. Rather than take a traditional .NET or network model to your data access, WCF Data Services (DS) provides a REST model for your data. REST REST, or REpresentational State Transfer, is an application model first defined by Roy Fielding in his doctoral thesis. While you may have never heard of Roy Fielding in the past, you likely use one of his creations daily; he was one of the principal authors of the HTTP specification. In his thesis, he described a way to create applications that “work the way the Internet works”: Every piece of data (or resource) is uniquely identified by some address within the system. ➤ You use a consistent interface for accessing these resources. ➤ You process these resources through representations of the resources, in known data formats. ➤ The entire system is stateless. ➤ Applying these principals to the Internet, you can see how they work in action: Every Web page is defined using a unique URL (Uniform Resource Locator). ➤ The HTTP protocol defines a number of verbs that may be used to act on those URLs. While ➤ the two most commonly used verbs are GET and POST, many others are available (e.g., PUT and DELETE). When you request a specific resource, you receive the content along with the MIME type of that ➤ content. HTTP is very stateless (as many new ASP.NET developers painfully discover). ➤ WCF Data Services provides this mechanism for working with your data. It adds an additional layer to your applications that enables you to manipulate an Entity Framework model (or other data, as you’ll see below) using this RESTful model: Each query, record, or field within your database can be uniquely identified using a URL, such as ➤ http://example.com/PubsService.svc/authors(‘172-32-1176’ ) You use the same HTTP verbs to access your data ( ➤ GET to retrieve an item, POST to insert new records, PUT to update them, and DELETE to delete them). When requesting data, you receive it in Atom or JSON format. ➤ The entire system remains stateless, typically with optimistic concurrency when changing records. ➤ Atom and JSON As described above, the data returned by Data Services is in the form of either Atom or JSON. These are both standard data formats: Atom (an official IETF standard – RFC 4287), while JSON (JavaScript Object Notation) is really just using JavaScript’s object definition syntax. WCF Data Services ❘ 495 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 496 ❘ CHAPTER 12 woRkiNG witH sQl sERVER FIGURE 1235 FIGURE 1236 Atom is an XML format that was initially proposed as a “better RSS,” but it has grown into a flexible format for defining objects of any syntax. Figure 12-35 shows an example of this format. The <content> element holds the actual data, while the rest of the XML is used to provide metadata (data about the data). The root element of Atom is either a <feed> node, or an <entry> node. Feed elements are used to contain multiple entry elements, whereas an entry element represents a single item. JSON is a subset of JavaScript that has become a popular syntax for passing data across the Internet (see Figure 12-36). It is a very concise format for describing data. Individual objects are wrapped in braces ({}); and within an object, the properties are defined using name:value pairs, each in quotes. Collections are defined by wrapping the child objects with brackets ([]). The benefit of JSON over Atom is this conciseness. For the single author shown in Figures 12-35 and 12-36, the JSON version is 459 bytes, whereas the Atom format is 1,300 bytes. Obviously, the more objects you have here, the more the XML format would increase this difference. Conversely, the Atom format retains more information about the record than the bare-bones JSON format. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com WCF Data Services ❘ 497 Exposing Data Using WCF Data Services WCF Data Services is a specialized WCF library that converts the HTTP requests to some provider. Currently, DS supports the Entity Framework as well as custom objects. Adding DS support to a project containing an Entity Framework model is as simple as adding a new WCF Data Service class to the project (see Figure 12-37). This adds a new class to the project that represents the actual service: Imports System.Data.Services Imports System.Linq Imports System.ServiceModel.Web Public Class PubsService ' TODO: replace [[class name]] with your data class name Inherits DataService(Of [[class name]]) ' This method is called only once to initialize service-wide policies. Public Shared Sub InitializeService(ByVal config As IDataServiceConfiguration) ' TODO: set rules to indicate which entity sets ' and service operations are visible, updatable, etc. ' Examples: ' config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead) ' config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All) End Sub End Class Code snippet from SimpleDataService FIGURE 1237 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 498 ❘ CHAPTER 12 woRkiNG witH sQl sERVER As shown in the preceding code, you must perform a number of steps before the project will compile. First, you need to identify the class providing the data. Second, by default, DS does not allow any data access. You need to explicitly identify the objects that may be queried, and what users may do with them. When exposing an Entity Framework model, the class is your entities. You can apply multiple security rules, depending on how you have separated the entities in your model. Alternately, you can take the easy route and expose all the objects in your model, as shown in the following code: Public Class PubsService Inherits DataService(Of PubsEntities) ' This method is called only once to initialize service-wide policies. Public Shared Sub InitializeService(ByVal config As IDataServiceConfiguration) config.SetEntitySetAccessRule("*", EntitySetRights.All) config.UseVerboseErrors = True End Sub End Class Once you have configured your data service, you can browse to the service to view the available resources (see Figure 12-38). FIGURE 1238 Each of the collections returned represents an additional query you can perform. Figure 12-39 shows the results of querying the authors table. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... T-SQL and Visual Basic While the implications of having your database run Visual Basic code can be a little unnerving, the benefits you receive in terms of flexibility and power may be just what you need in some applications Visual Basic provides several tools that are not normally available when working with T-SQL, such as access to the NET Framework’s classes While you should only use Visual Basic. .. solution, locate any services, and dynamically create a host for that service Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 5 24 ❘  Chapter 13   SERVICES (XML/WCF) Figure 13-8 This is a great feature of Visual Studio 2010, as it recognizes and supports the developer who needs to implement and test a WCF Service Instead of needing that production URL, which you would need to track,... Figure 12 -40 ) Figure 12 -40 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 50 2  ❘  Chapter 12   Working with SQL Server Just as with other WCF services, adding the service reference creates a client-side proxy of your service You can then query the objects directly, and DS creates the appropriate URL from your LINQ query You first instantiate a context to your service, and then... /authors/ ?$orderby=state,city&$top =4& $skip =4 would return the second set of four authors $expand When querying for data that includes child data (e.g., order detail rows when retrieving orders), $expand returns the child data as well $filter Enables you to more flexibly query the data This includes a number of operations for comparison, string, date and mathematical functions, and more Some example queries... be described with this XML document, and any application that understands XML (or SOAP) over the assigned protocol (such as HTTP) can access the object That’s because the parameters you type after the function name are passed via XML to the Web service, and because SOAP is an open standard Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 51 2  ❘  Chapter 13   SERVICES (XML/WCF)... identify it as part of the DataContract Working with the WS-* Protocols WCF understands and can work with the full set of WS-* specifications, and these specifications can be enabled to create messages that meet defined ways of dealing with security, reliability, and transactions A few of these protocols and an understanding of how messages are managed are important enough to take a closer look at their... the data service As the resulting data is in standard data formats, you should be able to work with the data, even on non -.NET clients The following code shows a simple console application that queries the PubsDataService to retrieve and display a list of the authors, sorted by state and city The client could be an ASP.NET application, using jQuery or ASP.NET AJAX to retrieve the data, a Silverlight... in a stateless, distributed way Software as a service was born Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Introduction to Services  ❘  50 9 Over the next decade, low-level protocols supported by network systems and the Internet became a staple in applications, with SMTP and FTP providing file and information transfer among distributed servers Remote procedure calls (RPCs)... World Wide Web The problems are wire format, protocol, and discovery The solution is a standards-based, loosely coupled method invocation protocol with a huge catalog Microsoft, IBM, and Ariba set out in 1999 to create just that, and generated the RFC for Web services Web Services A Web service is a means of exposing application logic or data via standard protocols such as XML or SOAP (Simple Object Access... services is quick and easy The data schema is human readable Any programming language can participate ➤➤ Interoperable — Because the Web services all conform to the same standards, and use common communication protocols, they are not concerned about the technology of the application calling them In basic terms, a Web service is an interface with an XML document describing all of the methods and properties . HTTPS, typically on port 44 3). Generally, use SSL if the data transmitted requires security, and you are using public networks. Note that Internet Information Services (IIS) and other Web servers. on a network, and you can expect a .NET class at the other end. WCF Data Services (formerly ADO .NET Data Services) attempts to change that model. Rather than take a traditional .NET or network. between T-SQL and Visual Basic. While the implications of having your database run Visual Basic code can be a little unnerving, the benefits you receive in terms of flexibility and power may be

Ngày đăng: 12/08/2014, 23:23

Mục lục

  • WroxBooks

    • Professional Visual Basic 2010 and .NET 4

      • Contents

      • Introduction

      • Part I: Language Constructs and Environment

        • Chapter 1: Visual Studio 2010

          • Visual Studio 2010: Express through Ultimate

          • Visual Basic Keywords and Syntax

          • Project ProVB_VS2010

          • Enhancing a Sample Application

          • Useful Features of Visual Studio 2010

          • Summary

          • Chapter 2: Objects and Visual Basic

            • Object-Oriented Terminology

            • Working With Visual Basic Types

            • Commands: Conditional

            • Value Types (Structures)

            • Reference Types (Classes)

            • Parameter Passing

            • Variable Scope

            • Working with Objects

            • Data Type Conversions

            • Creating Classes

            • Advanced Concepts

            • Summary

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

  • Đang cập nhật ...

Tài liệu liên quan