Home > Articles > Programming > Visual Studio

This chapter is from the book

Creating a New Data Source

Tables are primitive data containers. A table represents a series of items of the same type. For example, a table can represent a list of customers or of employees or of cars or of any object that has some properties. Tables are divided into rows and columns. A row represents a single item. For example, if you have a table storing a list of customers, a row represents a single customer in the list. In LightSwitch terminology, a single item is referred to as an entity, and a list of items is called entity collection. Columns represent properties of the elements that the table stores. For example, a customer has a company name, an address, and so on. This information is represented with columns. In LightSwitch terminology, a column is also referred to as a property. Actually, columns also allow you to specify the type of the property (such as date and time, strings, numbers), as detailed later in this section. Continuing with the creation of this application, the first step is to create a new entity that will represent a single person in the contacts list. Do so, and name it Contact. In the LightSwitch Designer, click Create New Table. Doing so opens the Table Designer, as shown in Figure 3.2.

Figure 3.2.

Figure 3.2. The Table Designer shows a new empty entity.

Here you can design your entity by specifying its properties. By default, the focus is on the entity’s title, which is Table1Item. Rename this Contact.

At this point, you can begin designing your new entity by adding properties. Notice that, by default, LightSwitch adds an Id property of type Integer (a type representing integer numbers), which identifies the entity as unique in the table (this is why such a property cannot be edited or removed). Therefore, such a property is an auto-incrementing index that is incremented by one unit each time a new element is added to the table. If you have some experience with other data-access tools such as Microsoft SQL Server or Microsoft Access, you might think of this as an identity field.

Adding Entity Properties

Each property has three requirements: the name, the type, and whether it is required (meaning that the information is mandatory or not). With regard to an entity that represents a contact, the first property you may want to add is the last name. So, click inside the Add Property field under the Name column and type LastName. Remember that property names are alphanumeric combinations of characters and digits and cannot contain blank spaces. If you want to provide some form of separation between words, you can use the underscore (_) character or you can use the so-called camel-case notation, where the words that compose an identifier start with an uppercase letter. LastName is an example of a camel-case identifier. LightSwitch automatically sets labels in the user interface to contain a space between camel-cased words automatically.

After you type the property name, you can press Tab on the keyboard to switch to the Type field. You can see the list of available data types and select a different one by expanding the Type combo box. By default, LightSwitch assigns the String type to each newly added property. Because the last name is actually a string, you can leave unchanged the default selection. Before providing the full list of available data types, let’s focus on the Required field. You mark a property as required when you want to ensure that the user must provide information for that property. In this example, the last name is mandatory because it is the piece of information that allows the identification of a person on our list of contacts, so Required is checked. LightSwitch marks new properties as required by default, so you need to manually unselect the box if specific property information is optional. Figure 3.3 shows the result of the previous addition.

Figure 3.3.

Figure 3.3. The new property has been added to the entity and marked as required.

Each entity can expose different kinds of information. This is accomplished by assigning the most appropriate data type to each property. Before adding more properties to the Contact entity, it is important for you to understand what data types are and what data types Visual Studio LightSwitch offers.

Understanding Data Types

Whatever tasks your application performs, it manipulates data. Data can be of different kinds, such as numbers, strings, dates, or true or false values. When you add a property to an entity, you need to specify its data type to clarify what kind of data that property is going to manipulate. Visual Studio LightSwitch provides some built-in data types that are based on types exposed by the .NET Framework 4.0 and that in most cases are sufficient to satisfy your business needs. Table 3.1 summarizes available data types.

Table 3.1. Available Data Types in Visual Studio LightSwitch

Data Type

Description

Binary

Represents an array of bytes

Boolean

Accepts true or false values

Date

Represents a date without time information

DateTime

Represents a date including time information

Decimal

Represents a decimal number in financial and scientific calculations with large numbers (a range between -79228162514264337593543950335 and 79228162514264337593543950335)

Double

Represents a large floating number (double precision) with a range from -1.79769313486232e308 to 1.79769313486232e308

Email Address

Represents a well-formed email address

Image

Represents an image in the form of binary data

ShortInteger

Represents a numeric value with a range between -32768 and 32767

Integer

Represents a numeric value with a range between -2147483648 and 2147483647

LongInteger

Represents a numeric value with a range between -9223372036854775808 and 9223372036854775807

Money

Represents a monetary value, including the currency symbol and the appropriate punctuation according to the local system culture

Phone Number

Represents a well-formed phone number according to U.S.-supported formats

String

Represents a string

Guid

Represents a globally unique identifier, which is a complex, randomly generated number typically used when you need a unique identifier across different computers and networks

Using the appropriate data type is very important because it makes data manipulation easier, provides the right mapping against the back-end database, and in most cases can save system resources. As an example, instead of using a String to represent a date, you use the Date type. This is useful (other than natural) because SQL Server has a corresponding data type and the .NET Framework provides specific objects for working with dates if you need to write custom code. The same consideration applies to numbers, Boolean values, and binary data.

The Concept of Business Data Types

In Table 3.1, you might have noticed something new in the LightSwitch approach to data types. In contrast to other development tools and technologies, including .NET Framework 4 and Visual Studio 2010, LightSwitch introduces the concept of business data types. For example, suppose you want to add a property to an entity for inserting or displaying monetary information. Before LightSwitch, this was accomplished by using the Decimal data type, which can display decimal numbers and is therefore the most appropriate .NET type in this scenario. This is correct but has some limitations: For example, you must write some code to add the currency symbol or format the information according to the local system culture. Next, consider email addresses. Developers usually represent email addresses with the String data type but they have to implement their own validation logic to ensure that the string is a well-formed email address. The same is true for phone numbers. This approach makes sense in a general-purpose development environment such as Visual Studio 2010. But Visual Studio LightSwitch is a specialized environment focusing on business applications, so the LightSwitch team at Microsoft introduced four new data types, specifically to solve business problems:

  • Money, a data type for displaying currency information that provides the appropriate currency symbol and culture information according to the user’s system regional settings.
  • Image, which allows storing and returning an image in the form of binary data.
  • Email Address, which accepts only valid email addresses and implements validation logic that throws errors if the supplied email address is not well formed.
  • Phone Number, which accepts only valid phone numbers and which implements validation logic that throws errors in case the supplied phone number is not well formed. This data type can be customized to accept phone numbers in a format different from the default one, built specifically for the United States.

If you think that any data-centric applications must validate the user input to ensure that the entered data is valid, business data types can save you a lot of time, especially because you do not need to write the validation logic: LightSwitch does it for you. You will get a visual sensation of the power of business data types in this chapter when you run the application and test the validation functionalities. In addition, Visual Studio LightSwitch provides an extensibility point where you can add custom business types, as described in Chapter 19, “LightSwitch Extensibility: Data and Extension Deployment.” Now you know everything important about data types in LightSwitch and are ready to complete the design of the Contact entity by adding specialized properties.

Building a Complete Entity

So far, the Contact entity exposes only the LastName property, so it needs to be extended with additional properties that complete the single contact information. Table 3.2 shows the list of new properties (and their data type) that are added to the entity. You add properties by clicking inside the Add Property field and specifying types from the drop-down Type combo box, as you learned earlier.

Table 3.2. Properties That Complete the Contact Entity

Property Name

Type

FirstName

String

Age

Integer

Address

String

City

String

Country

String

PostalCode

String

Email

Email Address

HomePhone

Phone Number

OfficePhone

Phone Number

MobilePhone

Phone Number

Picture

Image

JobRole

String

None of the new properties is required because the entity already provides two ways to identify a contact as unique: the Id property and the LastName property. After you complete adding properties, the Contact entity looks like Figure 3.4.

Figure 3.4.

Figure 3.4. The Contact entity has been completed.

The Contact entity represents a single contact, but Visual Studio LightSwitch also generates a Contacts table that represents a list of items of type Contact. If you open Solution Explorer and expand the Data Sources node, you can see how such a table is visible, as demonstrated in Figure 3.5. If you name your entities with words from the English language, LightSwitch automatically pluralizes the entity’s name when generating the table, thus providing the appropriate name for the new table.

Figure 3.5.

Figure 3.5. The new Contacts table is visible in Solution Explorer.

Now that you have successfully created a new entity and a table for storing a list of entities, you might wonder where data is stored by your application. This is briefly explained in the next subsection and is revisited in Chapter 12, “Dissecting a LightSwitch Application.”

Data Storage

LightSwitch applications use the Microsoft SQL Server database engine to store their data. In fact, one of the prerequisites when you install LightSwitch is the presence on your development machine of SQL Server Express Edition. Supported versions are 2005, 2008, and 2008 R2. When you create an application, Visual Studio LightSwitch creates a SQL Server database for the application itself, also known as the intrinsic database, naming such a database ApplicationDatabase.mdf. This is the physical storage for your data until you run the application on the development machine. When you deploy the application to a web server or a networked computer, you also need to deploy the database. You can decide to export the current database and attach it to the running instance of Microsoft SQL Server, and its name is replaced with the name of the application (for example, ContactsManager.mdf). Alternatively, you can let the deployment process build and attach to SQL Server a brand-new database with a different name, but you can also publish the database in the cloud by deploying it to your SQL Azure storage. LightSwitch can perform these tasks for you, especially if you use the one-click deployment systems covered in Chapter 10, “Deploying LightSwitch Applications.” For now, you just need to know that data is stored into ApplicationDatabase.mdf, which is located in the %ProjectFolder%\Bin\Data folder.

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