Home > Articles > Home & Office Computing > Microsoft Windows Vista & Home Server

Your Data Everywhere, Part 1: OData Support in Visual Studio LightSwitch

In part 1 of a three-article series, Alessandro Del Sole, author of Microsoft Visual Studio LightSwitch Unleashed, describes a useful addition to LightSwitch: support for Open Data Protocol (OData) data sources. Learn how to work with OData services from your LightSwitch apps.
Like this article? We recommend

This article describes a new, important addition to Visual Studio LightSwitch 2012, which is the support for data sources of type Open Data Protocol (OData). I'll explain how to consume OData services in your LightSwitch applications. In part 2 of this series, I'll show you how to expose LightSwitch data sources as OData services to other clients.

A Brief Introduction to OData

Exposing data through the Web—or, more generally, through a network—is a very common need for business software. Typically this goal is accomplished by exposing data via services that can be consumed by several clients. In this kind of scenario, the problem is that there are many ways (and thus APIs) to expose and consume data. The Open Data Protocol (OData for short) provides a standardized way to query and update data, based on the representational state transfer (REST) approach. Basically, REST-ful services support HTTP requests as well as verbs such as GET, POST, PUT, and DELETE; they also allow querying data via the so-called "query strings."

OData derives from the WCF Data Services; if you've already had a chance to work with this platform, you'll be totally familiar with OData. In a typical scenario, an OData service is hosted on a web server and exposed through the Web or a local network via an .Svc file (that is, WCF). OData exposes XML feeds that can be accessed in many ways, including via LINQ. Figure 1 shows how to query an OData service via an HTTP request directly from the browser.

Figure 1 Querying an OData service via HTTP requests.

Now let's move on to examining how to use OData services in Visual Studio LightSwitch, and how to consume such services as data sources—without writing a single line of code.

OData and LightSwitch

Visual Studio 2012 introduces native support for OData in LightSwitch. More specifically, LightSwitch 2012 allows you to do the following:

  • Consume OData services produced by other people, in order to extend applications with external data
  • Expose any data source used in a LightSwitch application as an OData service, making it possible for other clients to take advantage of your data in the form of an XML feed

With particular regard to the first point above, OData is a new type of external data source to which LightSwitch can connect, joining SQL Server, SQL Azure, SharePoint 2010, and WCF RIA Services. Here's the tremendous benefit: LightSwitch is capable of mapping data from OData services to entities. This fact implies that you'll be able to manage entities—creating queries, handling the business logic, and adding relationships to other tables—even if they're in different data sources. As a LightSwitch developer, you don't need to know what's going on under the hood; you just work with entities in the usual way.

LightSwitch supports both reading and writing data against OData. A lot of public OData services are read-only, so remember that fact if you're attempting to save changes back to a read-only service; a LightSwitch application will show an error message. In part 2 of this series, you'll learn how LightSwitch can expose the intrinsic database and other data sources as OData services to the network; for now, you'll learn how to enhance your applications by consuming existing services.

Choosing Existing OData Services

Lots of producers offer data sets as OData feeds. A variety of OData feeds are available for a plethora of information, such as city crime, transportation, government information, weather conditions, and so on. Two websites offer interesting OData services that you can use in your LightSwitch applications:

  • Windows Azure Data Market. In this cloud-based portal, you can find data sets based on the OData protocol, as well as fully-functional applications offered through the cloud. The Windows Azure Data Market requires signing up with a Windows Live ID. Once signed in, you can find a lot of public data sets. Not all are free; many are paid services, and some producers offer a variety of prices based on the number of transactions.
  • The Windows Azure Data Market is certainly the more professional place for finding OData services, but it requires a Windows Live ID, and the web portal automatically requires switching to the version based on your language. For an example with the Windows Azure Data Market, check out Beth Massi's blog post "Enhance Your LightSwitch Applications with OData."

  • Ecosystem page of the OData Protocol portal. In particular, the Live Services section of the page summarizes available OData services from several producers, as represented in Figure 2.

Figure 2 A list of OData services available in the OData portal.

By clicking the Browse link at the right side of each service listing, you can see the list of entity sets exposed by the OData service as an XML feed, inside your web browser. For this article, you'll consume the Netflix public OData service, in order to create a LightSwitch application that displays a catalog of movies based on certain criteria. Netflix is a web portal where you can rent movies for online streaming; the rental service is not available in all countries, but you can still consume the data service and show the results in LightSwitch. The URL of the Netflix service can be found in the OData Protocol portal. We'll use it shortly.

Consuming the OData Service

The goal of the sample application is to display a list of movies available on Netflix, including information such as available formats, awards, and so on. Let's get started.

  1. Begin by creating a new LightSwitch application in Visual Studio 2012. When the project is ready, click Attach to External Data Source. The Attach Data Source Wizard displays a new item called OData Service, as shown in Figure 3. Select this item and then click Next.
  2. Figure 3 The new OData Service connection option.

  3. The next step requires entering the OData service address and specifying credentials, as demonstrated in Figure 4. Enter the Netflix OData service address in the OData Source Address box. Notice that you can flag the "Attach to this data source as read-only" checkbox if you want to use the service only for reading information (or if you know in advance that it's a read-only service.) In the Login Information group, select None. (The OData service of Netflix doesn't require authentication.)
  4. Figure 4 Establishing a connection to an OData service.

  5. When ready, click the Test Connection button to test the connection against a particular entity before going on to the next step of this procedure. For example, in the Test Connection dialog, select the Titles entity and then click Test. If the connection succeeds, you'll be prompted with a confirmation message, as shown in Figure 5.
  6. Figure 5 Testing the connection to the OData service.

  7. The next step is selecting which entity sets exposed by the OData service will be used in LightSwitch. For this example, select all the available entities, as shown in Figure 6, to demonstrate how LightSwitch can also handle relationships. (Notice that LightSwitch automatically proposes a name for the new data source, based on the data service's name.)
  8. Figure 6 Selecting entity sets.

  9. Click Finish. A warning message appears, informing you that some custom data types in the service are not supported by LightSwitch, and therefore columns of that type will not be imported. In this particular case, the Netflix service also has many-to-many relationships that aren't supported and won't be mapped. Accept the LightSwitch warning by clicking Continue in the warning dialog.
  10. In order to understand how you're going to use the new data source, double-click the Titles table in Solution Explorer. Figure 7 shows how the Table Designer appears at this point.

    Figure 7 The Table designer shows how entities have been mapped to the service entity sets.

It's easy to see how LightSwitch has been able to generate a new entity for each kind of information exposed by the service, mapping data types and required properties correctly. At this point, you can choose different data types for a more precise mapping; for example, changing DateTime to Date. Also, notice how LightSwitch correctly recognizes one-to-many relationships, making them visible in the designer. You can manage entities and relationships exactly as you're used to doing with other kinds of data sources.

As an example of manipulation, and since we want to show the list of available movies, let's change the Summary property in the Title entity. By default, the Summary property is the Id property, but it's more appropriate to change it to the name of the movie for this example. Follow these steps:

  1. Make sure that the Title entity is open in the Table Designer.
  2. Click Title.
  3. In the Properties window, expand the Summary property drop-down box and select Name.
  4. At this point, we can add a new List and Details screen, demonstrating how easy it is to display information from the OData service—including entities with relationships. In Solution Explorer, right-click Screens and choose Add Screen. In the Add New Screen dialog, under Additional Data to Include, select Title AudioFormats, Title Awards, and Title ScreenFormats (see Figure 8). The Title Details checkbox should be selected by default; if not, be sure to select it.
  5. Figure 8 Creating a new List and Details screen.

  6. After the new screen has been added to the project, simply run the application. On the left side of the screen is the list of available movies, based on the specified Summary property. On the right side of the screen are the details for the highlighted movie, including related information such as awards and available formats (see Figure 9).
  7. Figure 9 The sample application shows data from the OData service.

Creating Queries

The full data set returns the complete list of movies from Netflix, which can be too much. Imagine that you want to display only movies released after 2005 that have been rated by viewers. In Solution Explorer, right-click the Titles table and select Add Query. When the Query Designer appears, call the new query FilteredTitles and specify filters to reproduce those in Figure 10.

Figure 10 Designing a query over the OData service.

The ReleaseYear property is of type Integer, so it's possible to make comparisons with math operators. Notice that the query also implements sorting based on the DateModified property. If you add a new List and Details screen based on the new query and run the application again, the result will show only movies released since the beginning of 2006 that have been rated by viewers (see Figure 11).

Figure 11 The application shows the result of a query.

This just confirms the fact that you can manage a data set coming from OData in the same way you manage data from other data sources.

Free Services with Read/Write Support

LightSwitch has complete control over OData feeds, which means that the runtime can certainly save back and update data to the service, if it supports update operations. Since LightSwitch provides a unified model for accessing different data sources, including OData, the runtime automatically implements whatever is necessary to handle this kind of operation for you. In other words, you won't have to write any code (except for custom business logic) to implement saving and updating operations—LightSwitch does it all for you. The OData Protocol portal offers a free live service that you can use for testing and that supports reading and writing data, which is the Read-Write OData Sample Service. Please read the usage information in the OData portal carefully before consuming it in your LightSwitch application, and remember that it's only for testing purposes.

Conclusion

The upcoming OData support in Visual Studio LightSwitch is a huge benefit because it allows you to integrate your own data with feeds produced by other people. This capability gives you the opportunity to create powerful applications that can offer information created, updated, and maintained by others—without having to change the way you manage either the data or the business logic.

References

Following is a list of useful references that you can check out to learn more about the OData protocol:

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020