Microsoft Visual Studio LightSwitch Business Application Development A jump-start guide to application development with Microsoft's Visual Studio LightSwitch
Jayaram Krishnaswamy
professional expertise distilled
P U B L I S H I N G BIRMINGHAM - MUMBAI
Microsoft Visual Studio LightSwitch Business Application Development Copyright © 2011 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2011
Production Reference: 1050911
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-849682-86-2 www.packtpub.com
Cover Image by David Gimenez (
[email protected])
Credits Author Jayaram Krishnaswamy Reviewers Mohit Chakraborty
Project Coordinator Zainab Bagasrawala Indexer Hemangini Bari
Mihail Alexandrov Mateev Proofreader Acquisition Editor
Jacqui McGhee
Dhwani Devater Graphics Development Editor
Nilesh Mohite
Dhwani Devater Production Coordinator Technical Editors
Melwyn D'sa
Mohd. Sahil Prashant Macha Sakina Kaydawala Copy Editor Kriti Sharma
Cover Work Melwyn D'sa
About the Author Jayaram Krishnaswamy studied at the Indian Institute of Science in Bangalore
India and Madras University in India and taught at the Indian Institute of Technology in Madras. He went to Japan on the basis of Japanese Ministry of Education Research scholarship to complete his PhD in Electrical Engineering from Nagoya University. He was a Post-Doctoral Fellow at Sydney University in Australia; a Government of India Senior Scientific Officer at the Indian Institute of Science in Bangalore and Indian Institute of Technology at Kanpur; a Visiting Scientist at the Eindhoven Institute of Technology in the Netherlands; a Visiting Professor of Physics at the Federal University in Brazil; an Associate Research Scientist at a government laboratory in Sao Jose dos Campos in Sao Paulo, Brazil; a visiting scientist at the National Research Council in Ottawa, Canada before coming to the USA in 1985. He has also taught and worked at the Colorado State University in Fort Collins and North Carolina State University in Raleigh, North Carolina. He worked with the Northrop Grumman Corporation on a number of projects related to high energy electron accelerators / Free Electron Lasers. These projects were undertaken at the Brookhaven National Laboratory in Long Island, NY and in the Physics Department at Princeton University, NJ. He has over 80 publications in refereed and non-refereed publications and eight issued patents. He is fluent in Japanese and Portuguese and lives in Plainsboro, New Jersey, USA. He is also an affiliate of the IEEE Computer Society and a Member of the American Physical Society.
He has been working in IT-related fields since 1997. He was once a Microsoft Certified Trainer in Networking and a Siebel Certified developer. He has worked with several IT related companies, such as the Butler International in their Siebel practice; with several IBM sub-contractors and smaller companies. Presently he is active in writing technical articles in the IT field to many online sites such as CodeProject.com, APSFree.com, DevShed.com, DevArticles.com, OfficeUsers.org, ASPAlliance.com, Egghead Café, SSWUG.org, Packt Article Network, databasedev. co.uk, cimaware.com, and many others. Between 2006 and 2010 he wrote more than 400 articles mostly related to database and web related technologies covering Microsoft, Oracle, Sybase, ColdFusion, Sun and other vendor products. He has also written two Microsoft Business Intelligence related books for Packt and a book on Microsoft SQL Azure. He regularly writes to his four blogs on Blogger; http://hodentek.blogspot.com; http://hodentekHelp.blogspot.com; http:// hodentekMSSS.blogspot.com; and http://hodentekMobile.blogspot.com. He recently received Microsoft's Microsoft Community Contributor award for 2011.
Acknowledgement I would like to thank Packt Publishing for giving me this opportunity to write a book for the fourth time and for their continuing encouragement. Dhwani Devater, the Senior Acquisition Editor for enterprise books, and my early contact for this book was most helpful and without her guidance and meticulous editing, this book would not have been possible. I am most grateful for her advice which she gave generously every step of the way. I would like to thank Zainab Bagasrawala, the Project Coordinator, for having monitored the flow of correspondence successfully and for her timely reminders. I also would like to thank Dhwani Devater the Development Editor for this book for her valuable input and pointers which have added great value to the book. I would also like to thank the technical editors, Mohd. Sahil, Prashant Macha, and Sakina Kaydawala, in addition to many others at Packt. I also would like to thank Priya Mukherjee, the Project Manager at Packt for guiding me through the contract process, the very first step in writing this book. I thank my son for reading through the initial chapters and making suggestions and picking out errors. I sincerely thank the reviewers, Mihail Mateev (http://blogs.infragistics.com/ blogs/mihail_mateev/default.aspx) of Infragistics a major third-party developer for LightSwitch, and Mohit Chakraborty (http://social.msdn.microsoft.com/ Profile/mohit%20chakraborty?type=forum) of Microsoft. Their close association with LightSwitch and their deep knowledge of this product has enormously added value to my book that I can only humbly and sincerely acknowledge. Their pointed questions; their thorough reading of the manuscript; their corrections and well directed advice has made portions of this book more readable and clear. I'm appreciative of the efforts they have put in for this book. I would like to thank my parents who would have shared my joy. I thank my brothers (Gopal and Vijay) and sisters, and the whole-hearted support of our Subbagiri family. I cannot sufficiently thank my wife Michiko Fukumoto, my son Krishna Jayaram and his wife Jannet Jayaram for their continuous encouragement.
Last but not the least I would like to thank Microsoft Corporation for making available evaluation software and allowing me to participate in their various events live as well as on the Web. I am most indebted to the MSDN forums, especially Visual Studio LightSwitch and Extensibility forums and their moderators ,both Microsoft and otherwise, and the various forum participants from whom I have received unstinted support.
About the Reviewers Mihail Mateev is a senior software development engineer in Infragistics Inc. He
worked as a Software developer and team leader on WPF and Silverlight Line of Business production lines of the company. Now he works like a Technical evangelist in the Infragistics. Mihail is also a consultant for the products of Infragistics, related to Visual Studio LightSwitch . Mihail worked in various areas related to technology with Microsoft: Silverlight, WPF, Windows Phone 7, Visual Studio LightSwitch, WCF RIA Services, MS SQL Server and Windows Azure. Mihail did presentations for .Net and Silverlight user groups in Bulgaria. He has experience with GIS system over .Net framework. He worked for more than five years in ESRI Bulgaria as a Software developer and a trainer. For several years Mihail lectures about Geographic Information Systems in the Sofia University "St. Kliment Ohridski", Faculty of Mathematics and Informatics. Mihail is also a lecturer of Computer Systems in the University of the Architecture, Civil Engineering and Geodesy in Sofia at Computer Aided Engineering Department. Mihail holds Master's degrees in Structural Engineering and Applied Mathematics and Informatics. Over the past ten years, Mihail has written articles for Bulgarian Computer World magazine and blogs about .Net technologies. He is a contributor to "Professional Silverlight 4 (Willey)" and a reviewer of "Developing Business Applications with Visual Studio LightSwitch" (PACKT Publishing).
Thanks to Jason Beres—VP of Product Management, Community, and Evangelism at Infragistics, who proposed the possibility to starting of deal with LightSwitch. Thanks to Matt Van Horn (former Sr. Consultant at Infragistics, now a Sr. Consultant with Capax Global), who helped me to get into detail in LightSwitch shells. Thanks to Dean Guida—CEO and President of Infragistics, who gave me the opportunity to work for Infragistics and become consultant for LightSwitch-related products.
Mohit Chakraborty is a developer in the Visual Studio LightSwitch team. His work primarily focuses on the project system, build, and debugging experience and the extensibility system. Before joining the current team he worked on developing Microsoft's Backup and recovery solution called Data Protection Manager. Before that he worked for Trilogy India where he worked on a Business Intelligence solution for the auto industry. Mohit has done his M.Tech. in Computer Science from the Indian Institute of Technology, Madras in 2004. Dedicated to my late father to whom I owe everything. His life is an inspiration to all.
www.PacktPub.com Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at
[email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe? •
Fully searchable across every book published by Packt
•
Copy and paste, print and bookmark content
•
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Table of Contents Preface Chapter 1: Getting Started with Microsoft LightSwitch
1 9
What is Visual Studio LightSwitch and who is the target audience? Basic architecture of a VSLS application The VSLS designers Installing Microsoft LightSwitch Installing on Windows 7
9 12 12 15 15
Installing on Windows XP Installing the databases used in the book Downloading the samples Installing the databases on SQL Express 2008 Summary References
19 21 22 22 24 24
Installation problems and remedies
Chapter 2: Microsoft LightSwitch IDE and Architecture Visual Studio LightSwitch Beta 2 application architecture Presentation tier Logic tier Data Access Service and Data storage Business logic Hosting Process Visual Studio LightSwitch Beta 2 IDE The Start page The Main menu Exploring the LightSwitch Project Creating a new project Project File View of the application
19
25
25 26 29 29 30 31 31 31 35 39 39 42
47
Table of Contents
Summary References
Chapter 3: Accessing Data from a VSLS Application WCF RIA service Components of a WCF RIA service Creating data entities in LightSwitch applications Creating a table (or entity) in a LightSwitch application Data types in Microsoft LightSwitch Salesman table Creating data entities using an external data source Review of business-related Northwind database tables Attaching to external data Accessing data on a database Accessing data on SharePoint 2010 Accessing data from a WCF RIA Service
Summary References
Chapter 4: Screens in VSLS application Screens, data, and visual presentation Microsoft LightSwitch screens New Data Screen Creating a screen Binding screen to data source Screen properties Displaying the screen
51 51
53
54 55 57 58 61 62 65 65 66
67 86 87
90 91
93
94 95 96
96 98 102 103
Search Data Screen
108
List and Details Screen Creating a screen from scratch
115 117
Export to Excel functionality
126
Testing the functionality Can you add or modify the data in the Search Data Screen?
Create an unbound Search Data Screen Add a group Add a data item Add an AutoCompleteBox Display and test combo-box
112 113
117 118 119 120 123
Disabling Export to Excel
128
Customizing a screen at runtime Summary References
128 132 132
Chapter 5: Working with Entities
135
Entities in Microsoft LightSwitch Entity Designer
135 136
[ ii ]
Table of Contents
Creating data entities: adding, deleting, and modifying fields
138
Adding a computed field
144
Entity field validation
149
How are the code pages organized in the project? Relationships between entities in LightSwitch Relationships between tables (entities) from an attached source
161 161 164
Choice list Setting up a default e-mail domain Entering Money field Setting up Phone Properties (formatting) Computed value using the Edit Method
138 140 142 143 146
Built-in validation Custom Validation
What is the workaround? How to establish a many-to-many relationship?
Summary References
Chapter 6: Querying and Filtering Data Querying in LightSwitch Querying a Single Entity Filtering and sorting the data Filtering the data Sorting the list Queries using a parameter
Querying multiple entities AutoCompleteBox to set the parameter value Static spans Querying a query Summary References
Chapter 7: Writing Code in Microsoft LightSwitch Getting started with writing code Why do you write code? Where to write the code? How you write code? Data Model and Screens in LightSwitch Writing and testing code targeting the entity Inserting default values in the entity Inserting data into an entity by code Validating entity Writing and testing screen-related code Entering default values using code with screens [ iii ]
150 155
170 172
173 174
175
175 178 179
180 186 188
193 199 206 208 210 211
213
214 215 215 216 216 217 217 221 225 226 227
Table of Contents
Overriding default behavior Accessing screen elements Writing custom queries using code A simple query with code Query with selection and sorting Query with text search Data from related tables Finding records by navigation Using a query to add data Summary References
Chapter 8: Authentication and Authorization in Microsoft LightSwitch Authentication schemes Access permission Permissions with Forms authentication
Creating screen Permissions with Forms authentication Where is the permission saved? Permission to a button Permission to query Permitting a user to run a query Permission to a query based on another query Permission to Entity
232 233 235 236 239 240 240 243 244 246 246
247
248 249 250
250 256 256 262 262 264 265
Permissions with Windows authentication
268
Associating Permissions with roles Permission elevation of server code
272 273
LightSwitch Project with Windows Authentication User testing the WindowsAuthenticationVB
Elevating the permission example
User Management Summary References
Chapter 9: Deploying LightSwitch Applications
Publishing and maintaining a two-tier desktop application Installing the application Running the application Adding users Publishing updates to the application Deploying the application to another computer Removing the application
[ iv ]
269 272
274
276 280 280
283
285 292 294 296 297 298 298
Table of Contents
Publishing to Web Where do you publish to? Certificate-backed deployment Publishing a three-tier application Publishing a three-tier application with Forms Authentication Displaying the application Publishing a three-tier application with Windows Authentication Publishing application to Windows Azure Creating the application to be deployed to Windows Azure Obtaining the subscription to Windows Azure and configuring the hosting site Preparing the application for Forms Authentication and deployment to Windows Azure Publishing to Windows Azure hosting site Creating a package for publication Summary About using project download from the Packt site Reference
Chapter 10: Troubleshooting, Debugging, Custom Controls, and Extensions Troubleshooting Debugging LightSwitch applications LightSwitch Debug Menu Adding custom controls to LightSwitch Creating a User Control Extensions Theme extension using CookBook recipe Setting up the right environment Creating a theme extension Installing the extension Using the extension Changing the design of the theme
Summary References
299 299 299 300 300 304 306 308 308 309 311 311 320 321 321 322
325
325 326 326 336 337 341 345
345 345 352 354 355
358 358
Index
359
[]
Preface Microsoft Visual Studio LightSwitch (VSLS in this book and more popularly known as the LightSwitch) is a rapid application development (RAD) tool distilled from many of the mature Microsoft technologies, such as ASP.NET, Framework Silverlight WCF RIA, ADO.NET, MVVM, WPF to name a few. It can be standalone or, used as an add-in for the higher versions of Visual Studio such as, Visual Studio Professional and Visual Studio Ultimate. Microsoft Access enjoyed great popularity because of its attractive feature of being both a database as well as a frontend user interface. However, over the years, it had to contend with a number of data access technologies, such as DAO, RDO, and ADO. Moreover, Microsoft did not quite make up its mind to present it for web-facing applications. Later on, some features were added to deploy the application to the Web through data access pages with a limited support for scripting. Being file based, there were issues of security. Being primarily developed for desktop there were some issues of scalability. Microsoft Visual FoxPro was more suited for the Web with better data access and command-line support but enjoyed a limited following. VSLS has not only the same attractive features of Microsoft Access and Microsoft Visual FoxPro but many more. It is by far the best RAD tool, making it accessible to the non-programmer type with limited skills either in programming or, in databases. It also opens its IDE for the developers and third parties with its extensibility features based on the Microsoft Extensibility Framework (MEF). It is based on a more robust Entity Framework Model, capable of accessing not only relational data from SQL Servers, but also from WCF RIA Services and SharePoint sources, providing the developer the capability to modify certain properties while the program is running; providing a solid security based on ASP.NET database; deploying the application to not only desktop but also for the Internet as well as the Windows Azure Cloud. While the above features are some of the easily noticeable features, there are many others coming from the underpinning technology of MVVM, intellisense support, a well-formulated LightSwitch API, and so on. The capability of wrapping up other unsupported data sources with a WCF RIA wrapper opens up unlimited opportunities. Because the VSLS applications can be hosted on the Windows Azure Platform, the scalability is almost a non-issue.
Preface
One of the nicest features of VSLS is its capability to deploy to desktop, Web or, Windows Azure directly from the IDE. For deployment, you can use the wizards that guide you or, the IDE creates scripts for you to run on the computer. When the out-of-browser feature of Silverlight applications surfaced with SilverLight 3.0, little did I realize that it was going to play such an important role and commented somewhat adversely, 'What use is this out-of-browser application?,' (http:// aspalliance.com/1844_DoubleAnimation_Basics_with_Silverlight_ Application.3). It turned out, it is this feature that makes deployment to the
desktop possible. Developing an application in VSLS and deploying to any of the topologies mentioned before is a great feature that is hard to beat. You don't have to do ASP.NET for Web and Windows Forms for the desktop, you just develop the application with VSLS—you have killed the proverbial birds with one stone. In naming the project initially Kitty Hawk, Microsoft team that developed the product perhaps gazed into the crystal ball and saw the product reaching out to touch the clouds as it literally did. Everything is very nice, what about the downside? Well, there will be a slight problem if you are coming from the Windows Forms or, ASP.NET technologies. You do not have the same design surface you had with the these technologies. You cannot drag and drop components and set their properties, align them easily, and move them on the canvas freely on the design surface as your whim and fancy dictates. Its design surface is totally different as you will see in the book and begin to learn designing LightSwitch applications. Once you get used to it, you will start seeing it in a more favorable light. The extensibility points available to you are many and the third parties have jumped in to add a lot of extensions that you can use to get the look, feel, and functionality you want. Another thing you often hear in the forums is the lack of support for directly migrating an application developed in Microsoft Access to VSLS. Well, this may become possible in future versions of VSLS. VSLS also does not support leveraging data access technologies such as ODBC and OLEDB that many application developers are comfortable with and used in the past. This book has been written twice over (Beta 1 and Beta 2) and an appendix has been added to cover the RTM changes. It was a difficult writing assignment for the author because the change from Beta1 to Beta 2 was drastic. The examples created for Beta 1 could not be used with Beta 2 or the RTM. Moreover, there were changes to object names and more feature changes. Fortunately, for the author and other authors on this subject, the change from Beta 2 to RTM was minimal. The applications built using Beta 2 compiled and performed easily with the RTM. The book is therefore completely ready for the RTM.
[]
Preface
The book did not take the path of starting with a single application built using VSLS and developing the content. This was deliberate for two reasons. First, there were examples of complete applications (some of them simple, others more complex) already available on line to the readers. Second, it was desired to write a book that readers could use to start learning from scratch, how to carry out the tasks; from building tables to creating screens; from writing queries to leveraging extensibility features; from creating security features to deploying to different topologies to name only a few. The author hopes he has been successful. Most of the project downloads are both in C# and VB and are fully tested. The readers may, however, have to make changes to connect to their data sources. As with any book, the readers may find errors and omissions. The author alone takes complete responsibility for these and absolves the reviewers and the editors who have done an excellent job.
What this book covers
In Chapter 1, Getting started with Microsoft LightSwitch, you will get a basic understanding of what this software is about; how to install the software and how to install the necessary database(s) to work with the software. In Chapter 2, Microsoft LightSwitch IDE and Architecture, the architectural features of Visual Studio LightSwitch application including the underpinning .NET Framework reference as well as the details of the platform IDE are covered. In Chapter 3, Accessing Data from a VSLS Application, you will be able to connect to the major SQL Server versions which form the underlying data of this data layer as well as connect to data available from a WCF RIA Service. In Chapter 4, Screens in VSLS Application, you will learn the different screens that are available in Microsoft LightSwitch and bind them to the various data sources we connected to in Chapter 3. You will be seeing more of the screens in other chapters as well but here you will be getting the first taste of what they can do and how they are configured without writing any code. In Chapter 5, Working with Entities, we will cover all aspects of entities used in VSLS projects. Entities consist of fields, some of which are no different from their counterparts in SQL Servers and some are specific to the program. This chapter covers the full range of data types used in defining entities. Entity fields once defined can also be modified and can even be deleted.
[]
Preface
In Chapter 6, Querying and Filtering data, in overview of querying in Microsoft LightSwitch is described to lay a basis for the various querying scenarios described in the rest of the chapter. Querying data for displaying data in Microsoft LightSwitch from single entities as well as multiple entities using the built-in user interface, the query designer is described. In Chapter 7, Writing Code in Microsoft LightSwitch, we will be looking at writing code to the event-driven programming model that you find in Microsoft LightSwitch codes targeting entities, screens and queries, these are described with some examples. In Chapter 8, Authentication and Authorization in Microsoft LightSwitch, the most important aspect of any business application, namely security is discussed in detail. Both Forms authentication and Windows authentication are described in detail. Creating Access permissions, users and roles that use those permissions are described with examples. In Chapter 9, Deploying LightSwitch Applications, the importance of delivering the developed application to end users, namely the deployment or publishing of the project is described with complete examples. Deployment to desktop, internet and the Windows Azure platform are described in an easy to follow step-by-step process. In Chapter 10, Troubleshooting, Debugging, Custom Controls, and Extensions, are discussed the troubleshooting and debugging and the problems one may come across during installation. Also described are the creation of custom controls and extensions. By way of example creating a custom theme is described in detail.
What you need for this book
Some prior knowledge of Visual Studio suite of products will be helpful, but not absolutely necessary. Knowledge of relational databases as well as tables, as used in SQL Servers will be useful. WCF RIA Services and SharePoint Lists would be advantageous.
Who this book is for
This book is for developers who are beginning to use Visual Studio LightSwitch. Small business houses should be able get a jump start on using LightSwitch. The book does not assume prior knowledge of Visual Studio LightSwitch but exposure to SQL Server, Silverlight, and Microsoft IDEs such as Visual Studio (any version) will be of great help. The book should be useful to both Visual Basic and C# programmers. []
Preface
In addition to small businesses, this book will be useful to libraries, schools, departmental applications, and to those who might be writing applications to be hosted on desktop, internet and Windows Azure platforms.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: " We start off with a project which has an entity called Employees and a SearchEmployee screen." A block of code is set as follows: Namespace LightSwitchApplication Public Class Application Private Sub SearchEmployees_CanRun(ByRef result As Boolean) ' Set result to the desired field value End Sub End Class End Namespace
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: " The Edit Menu item is just like any other Edit item in Microsoft products." Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. []
Preface
To send us general feedback, simply send an e-mail to
[email protected], and mention the book title via the subject of your message. If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail
[email protected]. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book on, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www. packtpub.com/support, selecting your book, clicking on the let us know link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
[]
Preface
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at
[email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at
[email protected] if you are having a problem with any aspect of the book, and we will do our best to address it.
[]
Getting Started with Microsoft LightSwitch This chapter begins with explanations as to what makes this software so important and places it in the context of the Visual Studio suite of products. This chapter also aims to help the reader install the required items on the user's computer. It also deals with installing the necessary sample database or databases that will be used together with the LightSwitch applications, as well as other infrastructural details. Topics to be covered: •
What is Visual Studio LightSwitch and who is the target audience?
•
Installing Microsoft LightSwitch
•
Installing the databases used in the book
After this chapter, the reader would have a basic understanding of what this software is about, how to install the software, and how to install the necessary database(s) to work with the software.
What is Visual Studio LightSwitch and who is the target audience?
Microsoft Visual Studio LightSwitch (will be called VSLS from here on) is the most recent offering in the Visual Studio suite of products that provides a fast and easy means to create professional-quality line-of-business applications for the three important application genres: the desktop, web, and cloud. However, it is to be noted that in Beta 1, hosting the LightSwitch application on Windows Azure was not supported and in Beta 2, it is supported.
Getting Started with Microsoft LightSwitch
There has been some debate as to the target audience for this product, but from the developments that the product has undergone from Beta 1 to Beta 2, it is easy to see that it should appeal to a larger group than was initially intended. The extension points and the fact that VSLS applications can be deployed to Windows Azure will now appeal to a larger group than was initially envisaged. It should appeal to small businesses that have minimal developer support to bigger departmental applications; to software vendors that would build upon VSLS's core capabilities using its extensibility features; to businesses that may want to migrate their legacy Microsoft Access-based applications to the Cloud. With future enhancements to the product, it may even be possible to move Visual FoxPro applications. VSLS takes off where Microsoft Access left off. Microsoft's MS Access program became a workhorse for many small businesses and for developing departmental applications in larger businesses, and remained a favorite of these communities for a very long time. This enormous appeal was due to the fact that the program could readily adopt to line-of-business applications with its easy-to-understand object model, support for graphic user interface, support for user management, integration with SQL Servers, support for various export/import tools, and finally its ability to create web-facing applications with Data Access Pages. Yet, Microsoft Access, being file-based, always had security-related issues, as well as a limit on the number of connected users issues. It was not intended for web facing applications, though DAC improved this situation. With the beginning of SharePoint products, Microsoft abandoned its support for DAC. VSLS may be deemed a much more powerful product due to its capability of creating applications by drawing upon the full power of the .NET Programming technology, its tight integration with SQL Servers including the latest implementation of SQL Server for the Microsoft Azure Cloud platform (the SQL Azure), its most recent framework (SilverLight 4.0) support, and its built-in capability to deploy applications to many different topologies. In fact, this was the first time a single application could be built once and deployed to different topologies. In the past, it was either for Windows or the Web, but not for both. Little did the author suspect that the "out-of-browser" execution of the Silverlight application would have such profound implications (http://aspalliance. com/1844_DoubleAnimation_Basics_with_Silverlight_Application). Microsoft LightSwitch Version 1.0 is expected to be released by the end of 2011, but is guaranteed to be compatible with SilverLight 4.0 (http://social.msdn.
microsoft.com/Forums/en-US/lightswitchgeneral/thread/db9c4f49-8e4340a2-93bc-40b597e8a5df).
[ 10 ]
Chapter 1
The line-of-business abstraction is taken to a level where the user needs to be concerned only with data sources and the "screens" that a business is most likely to be concerned with, as the "screens"in the application, represent the patterns common to most of the applications such as search, update, insert, and so on. Most other programs design applications with much more complexity, and much less flexibility and security. VSLS actually leveraged and abstracted the common patterns in business applications. While the Betas provide one such pattern through their default screens; developers and third parties can build custom screens to address their line of business. VSLS in its release version will be a full-service Integrated Development Environment (IDE), well suited to develop line-of-business applications using Microsoft's latest .NET Framework 4.0 technology. Unlike the other products in the suite, such as Visual Studio Professional and higher versions, Microsoft LightSwitch is targeted at developers and first-time users with limited exposure to Visual Studio programming models, and the plethora of application types that can be handled with Visual Studio. Microsoft LightSwitch is really for those who want to develop applications quickly and easily, without writing even a line of code. However, if a user needs customization, he or she may yet have to write an additional code, and the original assertion that no code needs to be written maybe bit of a stretch. In order to support custom programming, VSLS does support writing code by providing support to many events that are natural in any application. In addition, one can custom program using the extensive library that can be referenced. Extensions further provide for features built by more experienced developers or third-party vendors. For these and other custom code, Microsoft LightSwitch alone is not enough. It will require at least Visual Studio Professional in Beta2. However in the release version, VSLS may completely cover all aspects of programmability without needing to install higher versions of Visual Studio. Microsoft LightSwitch can cover the whole spectrum of developers from novices to experts. Already since its release, many such programs have been written by advanced developers as seen in the forums (http://social.msdn.microsoft. com/Forums/en-US/lightswitchgeneral/threads) and programs developed by third parties (http://blogs.infragistics.com/blogs/jason_beres/
archive/2010/08/05/infragistics-microsoft-lightswitch-awesome.aspx).
You can purchase Microsoft LightSwitch 2011 from: http://www.microsoft.com/visualstudio/en-us/lightswitch/buy. There are
three different purchase options. A single user can buy it for $199 and save $100 . Beta 1 and Beta 2 versions are available free of cost.
[ 11 ]
Getting Started with Microsoft LightSwitch
Basic architecture of a VSLS application
What is VSLS and how does it work? Microsoft LightSwitch is model-centric rather than driven by code. The application model is at the heart of a Microsoft LightSwitch application. The application model is built using the application blocks. Entities are built from EntityTypes and queries derive from entities. Screens consist of controls. The built-in designers use these blocks to create the application; picking entities and binding them with the desired screens. The run time gets this model moving by loading the application, retrieving the data, overseeing and running the logic that binds the screens with data, and a host of other activities.
The VSLS designers
It is the built-in designers that give the flexibility to the application developers in choosing data, and tailoring their displays and user interface. The designers work with the blocks described in this section. Model is at the heart of a lightSwitch application Entities *Queries
Screens *Controls
*Queries
*Controls
Data
GUI
Application Model EntityTypes are basic building blocks of entities
As mentioned earlier, VSLS is specifically meant for line-of-business applications and EntityType is its basic unit. For example, as shown in the next screenshot, Customer described by its various constituents, is an example of Entity Type, and so is Order. The Customer has a Key Property as well in relation to the other entity Order; it has a Navigational Property shown by the line joining the two. Additionally, although not shown explicitly in the screenshot, there is also a Computed Property that you see as one of its menu items. It is not mandatory for an entity to have navigational or computed properties. The data source NorthwindData is a container of these entities. The entity designer is where you define a new entity or bring one by attaching it to the data from an external source.
[ 12 ]
Chapter 1
The query designer shown in the next screenshot is where you design a query after choosing an entity on which it is based. A query based on another query is also allowed. A query has the same data as in an entity, but only some selected version of it. That is, it has the data that is filtered and sorted based on some criteria that you can set in the designer.
[ 13 ]
Getting Started with Microsoft LightSwitch
The Screen designer shown in the next screenshot is where a screen is designed. The IDE binds the data to the screen when you bind the entity to the screen to expose the entity to a user. These screens are pre-built to address common business scenarios, but with extensions it will be possible to build custom screens. However, one can start with an unbound screen (shown in the next screenshot) and bring in entity data or query data to the screen using hooks (Add Data Item…) in the Screen designer.
If you become conversant with using these designers, then you will be able to build applications effortlessly, as the screens, the queries, and the entities are tightly bound by the IDE. After designing the application in the IDE, it is the run time that executes the program to achieve the design objectives and display results to the user. The run time is based on many other Microsoft technologies, such as Model View ViewModel (MVVM), SilverLight, WCF Data Services, and so on, that utilize the best practices to provide a secure and extensible application which can be hosted on both the desktop and Web; a hitherto unavailable feat in a single application. A user can indeed work with the IDE to create applications without a full understanding of the behind-thescene workings of these sophisticated technologies. However, to create something that is not built-in, it will be necessary to have an understanding of the above technologies to some extent. Applications can be written without a line of code just by using the built-in features. However, run time can also draw upon the Application Programming Interfaces (APIs) to write code against events that an application would raise, such as an entity getting updated, a screen element getting displayed, or a validation being checked, and so on. The extensibility points available in the IDE provides for more advanced customization. In the next section, the preliminary tasks necessary for working through the rest of the book will be described.
[ 14 ]
Chapter 1
Installing Microsoft LightSwitch
Microsoft LightSwitch program vs_vslsweb.exe (3.3MB, version Beta 2, Date Published: 3/7/2011) may be downloaded from the location: http://www.
microsoft.com/downloads/en/details.aspx?FamilyID=CFF6C4EF-A29A-4C829A59-8A3BBB65EC3D and saved to a location of your choice. The saved file can be
used to install the program later.
The following are the system requirements: •
Supported Operating Systems: Windows 7; Windows Server 2003 R2 (32-Bit x86) or above, Windows Server 2003 R2 x64 editions, Windows Server 2003 Service Pack 1 or above, Windows Server 2008, Windows Vista, Windows XP Service Pack 2 or above.
•
Supported Architectures: °
x86
°
x64 (Windows 32 on Windows 64 bit)
The following are the hardware requirements: •
A computer with a 1.6GHz or faster processor
•
1024MB RAM (1.5GB if running on a virtual machine)
•
3GB of available hard-disk space
•
5400 RPM hard drive
•
DirectX 9 capable video card running at 1024 x 768 or higher-resolution display
This book was developed using the (x32) Windows 7 Ultimate OS on an ASPIRE notebook computer. Describing the installation of the product will be limited to Windows 7 and Windows XP, although it can be installed on many more operating systems both x32 and x64. As some of the would-be users (non-programmer, hobbyist, junior developer, and so on) will be using either Windows XP or Windows 7, installing on these OSs will be described in the following sections.
Installing on Windows 7
Installation on Windows 7 and on Windows XP is carried out similarly except that there could be some individual differences as well as problems that some may encounter.
[ 15 ]
Getting Started with Microsoft LightSwitch
1. Download the Microsoft VSLS from the link mentioned earlier: (http://www.microsoft.com/visualstudio/en-us/lightswitch). You can either purchase a single individual user's or developer's copy or download a trial version from: http://www.microsoft. com/visualstudio/en-us/lightswitch/try
2. Double-click on the executable vs_vslsweb.exe in the download location shown in the next screenshot:
3. This displays the Welcome to Setup page of Microsoft Visual Studio LightSwitch Beta Edition Setup window, as shown in the next screenshot:
Read the EULA before you click on Install Now. [ 16 ]
Chapter 1
4. Click on Install Now. The installation starts downloading the needed files that may vary depending on the computer on which they are installed. The VSLS server software is downloaded as shown in the next screenshot:
This is followed by the VSLS Beta Edition program as shown in the next screenshot:
[ 17 ]
Getting Started with Microsoft LightSwitch
These are the only components that are downloaded assuming you have Silverlight 4.0 on your computer and the other components (http://
social.msdn.microsoft.com/Forums/en-US/lightswitchgeneral/ thread/7ca9ddf6-27da-487d-8383-d8dad3a612ca). If Silverlight 4.0 is
not installed, the above installation will install Silverlight 4.0.
If you have an older build of Silverlight 4.0 Visual Studio LightSwitch, install a newer version of Silverlight - 4.0.50630.0. This could be an issue with some Silverlight projects that you did before. It is recommended to download the latest public build of Silverlight 4: 4.0.50917.0. You can find it here: Silverlight Tools 4 (http://go.microsoft.com/fwlink/ ?LinkID=177428 and Silverlight Runtime: http://go.microsoft. com/fwlink/?LinkID=149156).
3. Click on Close after the download is complete. This starts the installation and at its conclusion you will get the window shown in the next screenshot. Now you are ready to start using VSLS. This whole process took less than half an hour on the computer used.
[ 18 ]
Chapter 1
Installation problems and remedies
It may not be possible to describe all problems and their remedies, but some of them encountered while developing the material for this book will be described. The VSLS team has come up with a comprehensive list of the components that should be present for successful installation: problems and fixes (http://social.msdn.
microsoft.com/Forums/en-US/lightswitchgeneral/thread/7ca9ddf6-27da487d-8383-d8dad3a612ca). You may experience varying degrees of difficulty,
especially if you have the beta and CTP versions of some Microsoft programs. In one of the earlier installations on this computer, when one of the components was absent, installation did not succeed till the required component was installed. For details, review the link: http://hodentek.blogspot.com/search?updated-max=2010-0829T20%3A29%3A00-07%3A00.
In case you are unable to install for some reason, you should take a look at the installation log files: dd_VSMsiLLogXXXX.txt or dd_error_vs_vslscore_100. txt to identify where your installation might have gone wrong. To find this and related files, go to the Logs sub-folder in the installation folder: \Microsoft Visual Studio LightSwitch Beta Edition – ENU\Logs. Some of these files could run to a couple of thousand pages. If there are no errors, the error file will be empty.
Installing on Windows XP
While this section describes the installation of Beta 2 on Windows XP, the information will still be useful for installing Microsoft LightSwitch 2011. You will still need Windows (x32) SP with SP3. Review the link at: http://www.microsoft. com/visualstudio/en-us/lightswitch/overview/system-requirements for more information. Installing on Windows XP is no different from installing on Windows 7, except that you need to note the following, and in case you find these indicated programs on your computer, do what is required, as indicated. Please note that: At a minimum, you should have Windows XP with (Service Pack) SP 2. On the computer used for this book, SP3 was installed. Beta of WCF RIA Services, if present, should be removed. Beta 2 of MS .NET Framework 4 client, if present, should be removed. Also note that before you remove Beta 2 of MS .NET Framework 4 client, you should remove .NET framework 4 extended Beta 2, if you have it. These betas were removed from the author's computer before installing LightSwitch. [ 19 ]
Getting Started with Microsoft LightSwitch
It is preferable to have SQL Server 2008 Express (or higher up to SQL Server 2008 R2 Enterprise), as well as the recently released free edition, the SQL Server Express 2008 R2 (http://www.microsoft.com/downloads/en/details.
aspx?FamilyID=967225eb-207b-4950-91df-eeb5f35a80ee&displaylang=en) on the computer, as it is used by VSLS applications. According to the answer found in the forum (http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/549c7dd9-0919-473d-a841-81dbc53f23c5), VSLS installation should install SQL Server 2008 Express, if it is not already present. It is assumed you have the necessary .NET Framework (.NET 3.5) to install SQL Server 2008 Express 2008. On the author's computer, SQL Server 2008 Express was already present. In addition, Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (Intel X86) Enterprise evaluation edition was also present.
In case SQL Server is not installed for any reason, the following link describes the three flavors of SQL Express that you can install on your computer and the links to their download sites: http://hodentek.blogspot.com/2009/01/sql-server-208-express-editionwhich.html
All you need to do is to double-click on the vs_vslsweb.exe file to start the download and installation process. Follow the installation wizard instructions and the wizard steps may not be the same as in the case of Windows 7, as the installed programs on Windows XP SP 3 may be different from those on Windows 7. For example, the installation displayed the next screenshot when the download and installation process started:
[ 20 ]
Chapter 1
This download will continue until all the following items are downloaded and installed on the computer: •
VC 9 and VC10 runtime (x86 or x64)
•
MS .NET F 4.0
•
MS .Net Framework 4.0 Multi-targeting pack
•
SQL Server 2008 R2 Management Objects
•
MS Help Viewer 1.0
•
TFS Object Model (x86)
•
MSWeb deployment tool (x86)
•
Silverlight 4 SDK
•
WCF RIA Services
•
Microsoft Visual Studio LightSwitch Beta Server
•
Microsoft Visual Studio LightSwitch Beta Edition
The installer verifies the already-installed components and installs the programs that are not present on the computer. For a comprehensive list of programs installed, follow this link: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/7ca9ddf6-27da-487d-8383-d8dad3a612ca. It has a list of most of the installation-related troubleshooting information as well. After downloading and installing the files, Visual Studio LightSwitch Beta 2 will be installed without any problem, although the whole process takes nearly two hours (with an average download speed of 185 kbps on the Wi-Fi connection, compared to under half an hour on Windows 7).
Installing the databases used in the book As the book will be using Northwind and Adventure Works databases whenever a database on the SQL Server 2008 Express is used, these databases will be required to work with the book. The following section describes where to obtain the sample databases, as well as bringing them to the SQL Server 2008 Express installed on the computer. By default, the server installation does not contain sample databases.
[ 21 ]
Getting Started with Microsoft LightSwitch
Downloading the samples
Download sites depend on how long the databases have been in use, as the earlier databases were smaller and the more recent ones are larger. •
Download the SQL Server 2000 Sample DBS, as well as Microsoft Sample Databases from the CodePlex site: http://sqlserversamples.codeplex.com/#databases
•
Download SQL Server 2000 databases Northwind and Pubs from: http://code.msdn.microsoft.com/northwind/
•
For SQL 2005 (top right of the URL) and SQL Server 2008 R2 databases, follow this URL: http://msftdbprodsamples.codeplex.com/releases/view/37109
Installing the databases on SQL Express 2008 The installation of databases on SQL Server 2008 requires attaching the database MDF and LDF files to the server. This process is described in the following blog:
http://hodentekmsss.blogspot.com/2010/05/using-sample-databases-withsql-server.html, where an Adventure Works database is installed on an instance
of SQL Server 2008 R2.
However, with the sample files download from http://code.msdn.microsoft. com/northwind, which provides a ZIP file, the process is even simpler if you follow these indicated steps: 1. Download SQL2000.Sample.Databases.(Northwind, pubs).zip, a 1.2MB file from: http://code.msdn.microsoft.com/northwind/Release/ ProjectReleases.aspx?ReleaseId=1401 The file contains both the Northwind and the pubs database-related files. You will find both the MDF and LDF files for these databases, as well as the install scripts instnwnd.sql and instpubs.sql files. Make sure you read the ReadME_SQL2000SampleDbScripts.html file for further guidance.
2. Extract the files from the ZIP to a location of your choice. 3. Connect to the SQL Server Express in the Microsoft SQL Server Management Studio. 4. Right-click on the databases node and choose Create a new database. [ 22 ]
Chapter 1
5. Create a new database Northwind in SQL Server 2008 Express. 6. Expand the Database node and right-click on the master database node and choose New Query. 7. In the Management Studio's menu, click on File | Open | File...; browse and locate the instnwnd.sql script file mentioned earlier. 8. The installation script gets copied to the query window. 9. Do a syntax check and execute the query by clicking on the Menu icon. 10. The script is executed very quickly and you have the Northwind database in SQL Server 2008 Express. 11. After the query is run, you must be able to find the Northwind database in your SQL Server 2008 Express as shown:
In a similar manner or using the method suggested earlier in the author's blog, the Adventure Works database can also be installed on the server.
[ 23 ]
Getting Started with Microsoft LightSwitch
Summary
The chapter describes some of the basic architectural features of VSLS for designing VSLS applications. Features that differentiate this product from other programs are also described. After describing the hardware and software requirements for installing VSLS, the download and install process is described for both Windows 7 and Windows XP. Downloading and installing the sample databases, which are used with this software, is also described.
References
Here are some of the resources that will help in your understanding of VSLS Applications: •
Microsoft LightSwitch site at: http://www.microsoft.com/visualstudio/en-us/lightswitch
•
Microsoft Documentation of Microsoft LightSwitch is found at: http://msdn.microsoft.com/en-us/library/ff851953.aspx
•
About a dozen videos describing VSLS Applications on MSDN are at: http://msdn.microsoft.com/en-us/lightswitch/gg604823
•
Microsoft LightSwitch Forum (General) is where most of the issues, problems, and workarounds are posted: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/threads
•
Video introducing VSLS can be found at: http://channel9.msdn.com/Blogs/Dan/Jay-Schmelzer-IntroducingVisual-Studio-LightSwitch
[ 24 ]
Microsoft LightSwitch IDE and Architecture This chapter covers the architectural features of Visual Studio LightSwitch application including the underpinning .NET Framework reference, as well as the details of the platform IDE. Topics to be covered: •
Visual Studio LightSwitch Beta 2 application architecture
•
Visual Studio LightSwitch Beta 2 IDE
•
Exploring the LightSwitch Project
Visual Studio LightSwitch Beta 2 application architecture
In the previous chapter we looked at the model, the building blocks, and the designers. And in this section, we will look at how they are integrated. Microsoft LightSwitch is built with long-term integrity in mind and it comprises three distinct tiers housed in the LightSwitch Shell (the interface the user encounters on launching the application): the Presentation, logic, and the data storage; as shown in the next image. Out of the box there is a default shell, but by using extension points, it is possible to customize the shell to the user's requirements. Chapter 10, Deployment of LS Applications, describes the extension points that provide customization.
Microsoft LightSwitch IDE and Architecture
The basic structure of a VSLS application is very simple, as shown:
While this structure appears to be simple (to be appreciated by non-programmers and hobbyists), it hides a complex organization of several of the most recent Microsoft technologies as we shall see in this chapter. The Presentation tier is where the user interacts and visualizes data. The main concern of this tier is to provide the screens and controls to enable the user to do just this. The Logic tier takes care of the logical operations needed to support all kinds of data manipulation, process client requests, and provide a medium that can address the validity of client requests. This feature shields the direct access to data to prevent invalid entries. The Data Storage tier is to ensure, store, and persist application data. It must be appreciated that the application is driven by data no matter what tier is involved. It is possible to create an application with no data, but such an application would not be very useful. The VSLS IDE allows developers to access all these tiers in a very intuitive manner.
Presentation tier
Silverlight 4.0 is chosen for the presentation tier that supports running the application on a desktop (out-of-the-browser implementation), or hosting it on a browser. Support of WCF RIA Services Client and Office automation are other features. The Presentation tier (or Client) has the user interface and consists of the shell: the screens and the controls.
[ 26 ]
Chapter 2
The Shell takes care of common tasks such as logging in, launching, and activating screens. The shell is also responsible for theming, which provides for visual attributes of the application on top of what is provided by Silverlight. The Screens are the principal parts of the user interface. During the design time, the model of a screen consists of ContentItem building blocks, as shown in the next screenshot for a typical screen(in this case, a Search screen) in the design stage.
The screen is designed on the Model View ViewModel (MVVM) pattern. At runtime, the screen appears as rendered in the browser shown in the next image. ContentItems in the design go over to Content Objects.
[ 27 ]
Microsoft LightSwitch IDE and Architecture
The Content Objects are laid out dynamically without any user interaction so that a lot of manual work in designing the UI (such as sizing, aligning, layout, and so on) is eliminated. However, the downside is that the structure is fixed, unless a custom layout is designed by the developer, as discussed in the forums. One interesting aspect of this strategy is that the developer can make changes to the design at run time by accessing the ContentItems using the Design Screen hook on the displayed screen, as shown in the previous screenshot. The window that is accessed by this button is shown in the next image:
Observe that the Contact Name content object is removed (by deleting the Contact Name in the left pane) from the screen display on the right. This can be saved or cancelled to retain or cancel changes. Because the Screen ContentItems are bound to data, this screen manipulation is dynamic and saves a lot of developer time in not requiring him to go back and make changes to the UI.
[ 28 ]
Chapter 2
Logic tier
The Logic tier leverages WCF RIA Domain Services with ASP.NET 4.0. The processes in this tier can be hosted in three ways presently: hosted locally on the user's machine, on an IIS Server, or on the cloud as a Windows Azure Web role. However, in Beta 1, the cloud hosting is not supported. Also, the new OData services can be tied to the logic layer.
Data Access Service and Data storage
Data used in VSLS Application comes from two sources: one internal, called Application Data, and the other from external data. The Application Data is stored in an intrinsic database (a local SQL Express database). The route to data from the application to the stored data is shown schematically in the next image. VSLS Application Data Source 1
Data ......... Source 2
DWS1
DWS2 .........
LS API Data VS Database Dev Tool (TS Data) SQL Compact Edition
Application Data (Intrinsic Database) SQL Express (at design time)
External Data SQL Server 2005 and sbove sharepoint MySql- Connector 6.3.6 Oracle 11g WCF RIA Data Services
The Data Storage tier utilizes storage of data in SQL Servers (includes SQL Server Express) or in SQL Azure instances using ADO.NET Entity Framework. It can consume data from SharePoint's 2010 Lists using WCF Data services with ODATA Protocol, and custom-built WCF RIA Domain Services using an in-memory WCF Data Service. It can also use data from other vendor products such as Oracle and MySQL, for which .NET providers that support Entity Framework are available. However, when such products are used, the Application may not support all the features available for the supported data sources.
[ 29 ]
Microsoft LightSwitch IDE and Architecture
The IDE orchestrates this architecture superbly by its minimalist design of the project templates, giving access to the tiers in an intuitive way. The Shell of the IDE takes care of the hosting and theming; the "Screens" take care of the visual presentation, setting up an intuitive and visually appealing layout, bringing in chosen data and binding it to the visual elements with which the user interacts; and the Data Workspace (DWS in the previous image) via "Data Sources" allows all needed elements that deal with data such as entities, their relationships, queries, and data updates. Each Data Source creates a data workspace as shown schematically. The VSLS application screen depends on the Control blocks to visualize or edit a particular kind of data type, such as a String (ContactName, for example) or Integer (CustomerID, for example). VSLS has many built-in controls as we shall see in the book, but one can also bring in custom controls as described in Chapter 10.
Business logic
Business logic can be associated with screens and entities, or even one of its commands. The business logic comes in several ways: •
Dynamically evaluated Computed Properties that evaluate the returned value from an entity
•
Validation rules for checking both screens and entities
•
Read-Only rules for both screens and entities
•
Can_Execute rule to find if a command can execute (for command buttons, queries, and so on)
The Details property in the VSLS API gives access to the business rules. We will look at some of these details in the rest of this chapter. In the Client, VSLS renders the Screen and EntityType building blocks as screen object and entity object at runtime. A typical screen object (say, Customer) has the task to search or add a new customer or modify. To accomplish this, these screens have logic to load and make sure that the information added is valid. After this, they have a logic to save. The screen's workflow can also be manipulated by user-defined screen commands. In an Entity object, which is a copy of business, data-related rules are built-in or encapsulated; for example, data validation, data default, and so on. As long as the clients and entities are tied in the service tier, business logic such as validation is checked on both tiers.
[ 30 ]
Chapter 2
Hosting Process
By design, a VSLS application can be run as a desktop application. For this case, the application is designed to leverage the out-of-browser installation (see http://aspalliance.com/1844_DoubleAnimation_Basics_with_ Silverlight_Application.3 for an example) and the startup process is designed to ensure that the process truly runs as an out-of-browser, leveraging the sllauncher.exe program. This is the default of an application. As the desktop applications are designed to operate under elevated security considerations, the access to resources on the desktop and access to Office from within the screen is possible. Hence, "Export to Excel" becomes effective for applications targeted at deployment to the desktop. For browser hosting, all that is needed is that the OS should support Silverlight 4.0. The process runs in a sandbox and therefore the resources on the computer cannot be accessed. The Office Automation feature discussed above is not possible and Windows file system access is restricted. Any information to be persisted should be explicitly saved; an action that LightSwitch handles by design. The hosting of VSLS Applications is discussed with examples in Chapter 9, Using extensions with VSLS Applications.
Visual Studio LightSwitch Beta 2 IDE
As a developer, knowing the development environment is of utmost importance. In this section, we take a look at the VSLS IDE to become familiar with all the details that can be accessed in the user interface. All controls will be accessible only for a fully developed application, and in this section, we shall look at what is available when you just start working with the IDE.
The Start page
The resources available here are the most up-to-date and you should really start from here. We explore by following the given steps: 1. Click on Start | All Programs and then click on the Microsoft Visual Studio 2010 folder.
[ 31 ]
Microsoft LightSwitch IDE and Architecture
2. Right-click on the displayed application shortcut Microsoft Visual Studio 2010 and from the displayed menu, click on Run as administrator, (although it's not necessary to run as administrator it provides for easier management) as shown:
3. Click on Yes on the User Account Control message box, agreeing to run devenv.exe. The Microsoft LightSwitch user interface's Start Page is displayed as shown. Note that the program is running under the control of the administrator and it is assumed that no other Visual Studio product is installed.
[ 32 ]
Chapter 2
The displayed page may look different if you already have other Visual Studio versions installed on your computer.
The interface consists of project navigation on the left. If you have already created some projects, they appear under Recent Projects and you may also choose to remove them from display. There are two projects on this computer, but they were created in Beta 1. Applications created using Beta 1 are not supported in Beta 2.
Here you can also create a new project, or open an existing project by clicking the corresponding links New Project… or Open Project….
[ 33 ]
Microsoft LightSwitch IDE and Architecture
The Get Started and Latest News tabs adjacent to Recent Projects allow you to get introduced to the Microsoft LightSwitch, interact with the user community, and access resources and download LightSwitch extensions to enhance capabilities. The Introduction to LightSwitch link provides these very useful options: •
LightSwitch Overview The details are available at this link: http://msdn.microsoft.com/en-us/library/ff851953.aspx
•
Create your first LightSwitch Application Details four easy steps to create a contact management application and run it: http://msdn.microsoft.com/en-us/library/ff852059.aspx
•
Tour of the development environment This takes you to the following link, which describes the development environment: http://msdn.microsoft.com/en-us/library/ee256724.aspx
The reader should follow through each of these links and review the available information. The Community and Learning Resources link provides access to community resources, such as: •
LightSwitch Developer Center
•
LightSwitch Forums
•
LightSwitch Team Blog
•
LightSwitch Samples and Tutorials
This is very useful and you must become acquainted with these resources. Most of the problems that you may encounter may have been discussed in the forums. You may get useful insight and working experience with the samples and learn about breaking news and other helpful hints by reading the blogs. Presently, when you click on the Launch Extensions Manager link from the link Download LightSwitch Extensions, a description of what Extension Manager is, appears with a link to launch the Extension Manager. When you click this link, the Extension Manager window will be displayed as shown. Presently, there are no installed extensions available, but you can get them from the Gallery. Extensions are very useful if one needs to customize the line-of-business application.
[ 34 ]
Chapter 2
The Latest News tabbed page displays the URL of the RSS feed to which you can subscribe, as shown:
The Main menu
Like in all Microsoft products, this is where most of the activities from creating a project to building and running a project are accomplished.
[ 35 ]
Microsoft LightSwitch IDE and Architecture
The File menu item allows you to carry out a number of tasks as shown:
For LightSwitch applications, the relevant file menu items are for creating or opening an existing project. You can also have your project under Source Control using the drop-down menu item. The Edit menu item is just like any other Edit item in Microsoft products. The View menu item provides access to other parts of the IDE, such as the various windows that are accessible to the designers and the various Toolbars shown that users can enable or disable according to their choice. The View menu item also provides access to the two explorers besides the other items. We will look at some of the commonly-used ones in the book.
[ 36 ]
Chapter 2
The Debug menu item will be described while creating and running a project. In Chapter 10, Deployment of LS Applications, we will look at the Debug menu in some detail. The Tools menu item supports a number of activities including access to the configurable options for this IDE. Most of these items are common to the other Visual Studio IDE.
[ 37 ]
Microsoft LightSwitch IDE and Architecture
The Extension Manager… link launches the extension manager and the Import and Export Settings… link displays the window shown in the next screenshot:
This is an important wizard, especially when you are working with multiple settings. The default is the LightSwitch default. The Options… drop-down menu item allows you to customize the IDE and display the Options window as shown:
[ 38 ]
Chapter 2
A more detailed description of the Visual Studio IDE (at that time, the current version was VS 2005) may be found in the author's book, at: https://www.packtpub.com/sql-server-integrationservices-visual-studio-2005/book, published by Packt Publishers.
The IDE displays only contextual windows appropriate for the task. We will look at some of the windows and their features after creating a project.
Exploring the LightSwitch Project
Microsoft LightSwitch IDE has LightSwitch-related templates that can be used to create LightSwitch applications. The best way to explore the features is to create a project and explore the template-created files and folders, configuration details, project structure, project dependencies, and so on. In the following discussion, a LightSwitch project is created to describe some of these features. Although not completely described, it is assumed that some data is accessible and that some screens have been created. In the coming chapters, the reader will be creating the data as well as the screens for the example application in this book.
Creating a new project
Creating a new project is very similar to creating a project in other versions of Visual Studio. As described earlier, we can create a project, or open an existing project, from the file menu. •
Click on File | New Project… and the New Project window is displayed as shown:
[ 39 ]
Microsoft LightSwitch IDE and Architecture
There are only two Installed Templates for LightSwitch: LightSwitch Application (Visual Basic) and LightSwitch Application (C#). The VSLS team is likely to add other project types in the RTM version. Each of these creates a blank LightSwitch application in the language chosen. The application comes up with a default name, Application 1. Also note that if you are using source control, you may add this to the source control. And, you can browse and point to a different location for the project files: 1. Click on LightSwitch Application (Visual Basic). 2. Change the default name to something different and click on OK. Here the application name is TestApplication. The following Silverlight Project window may pop up as shown. Clicking the link takes you to the website where you can download and save the file. After saving the file, double-click on the Silverlight_Developer.exe (8.2MB) file and follow the instructions. It may take a while to install, after which you need to refresh your browser for the installation to be effective. It is possible that this file might have been dropped during a system restore operation on this computer and may not happen on your installation.
Make sure your version of Silverlight 4.0 is as shown. It may have if you have older versions. VSLS installs the Developer package as well.
[ 40 ]
Chapter 2
3. After this, it may take a little while, and the project gets created with four panes as shown in the following screenshot:
It has just four panes: Solution Explorer, the application designer in this case, TestApplication Designer, the Properties window, and the Error List. The TestApplication Designer is the design pane where you can either Create new table, which can be used as a source of data, or you can Attach an external database. Because most applications will be data centric, this is the most appropriate starting point. The project folder is simplicity itself. It has three items: Property of the application, Data Sources used in the application, and Screens that display the data from the data sources to the users. By right-clicking the Data Sources folder, you can Add Data Source… or Add Table. We will see how to do these tasks in the next chapter, Accessing Data from a VSLS Application. In a similar manner, when you right click on the Screens folder, you can Add Screen… or Edit Screen Navigation. Chapter 5, Screens in VSLS Application, describes adding screens and hooking them up with data.
[ 41 ]
Microsoft LightSwitch IDE and Architecture
While the Project folder appears deceptively simple, FileView of the project can be accessed from the project's toolbar, as shown. We will look at FileView a little later in this chapter.
Project
The project node in the Solution Explorer has its own sub-menus, as shown in the following image: 1. Right-click the project TestApplication in the Solution Explorer. The drop-down menu displayed shows various actions that you can take while working with this project, as shown. Again, this is on a computer on which no other Visual Studio product but LightSwitch is installed.
This is also quite similar to other Visual Studio products. Here, you can add data source(s) as well as screen(s). You can build, rebuild, clean, and deploy (publish) projects.
[ 42 ]
Chapter 2
2. Click on Properties in the drop-down menu. The project's properties page opens in the TestApplication Designer as shown:
3. The chosen application name appears in the General tabbed page. In this page, you can select graphic images for the logo as well as the application. The visual themes and shell can be chosen from their drop-down. However, in Beta 2, there are only the default choices. The drop-down choice Culture provides for using many languages besides English. For example, some of the screen menu items get their screen details in the language chosen (Japanese) here, as shown. As seen here, there are two screenshots present in the application.
[ 43 ]
Microsoft LightSwitch IDE and Architecture
The Extensions tabbed page shows only the extension being chosen for Beta, the Microsoft LightSwitch Extensions Version 1.0, which supports the VSLS specific datatypes like Phone, Email, and so on, in addition to the default shell, theme, and the like. In Chapter 10, Troubleshooting, Debugging, Custom Controls, and Extensions you will learn how to create and add an extension. The Screen Navigation tabbed page shows how you can navigate through the screens. Herein, two screens based on one table have been created to show the particulars of this tabbed page. In fact, there are two screens added to this application: CreateNewTable1Item and SearchTable1Item. Here you can use the up/down buttons shown as icons on the right-hand side to change the order of the screen in the menu, when the project is run. You just need to highlight the screen and use the up /down button. You can also set which screen to display at the start up, using the Set button at the bottom of the page after highlighting the screen.
The Screen Navigation page can also be used for renaming or deleting the screen as well as writing code to the CanRun () method, as shown here:
[ 44 ]
Chapter 2
In the Screen Navigation page, you can also display tasks related to administration, such as Users and Roles. If the application access is set for anonymous access, there are no administration tasks in the displayed application as shown in the image on the left-hand side, the one on the right is for access when Windows Authentication is set (using the next-tabbed page Access Control) for access.
The Access Control tabbed page provides the means to authenticate users and authorize the authenticated users; that is, manage permissions to whole or part of the application as shown in the next image. This page also defines the permissions granted for debugging.
[ 45 ]
Microsoft LightSwitch IDE and Architecture
Do not enable authentication allows access to anyone and this access control is similar to anonymous access in IIS. Use Windows authentication provides access to windows users and groups. This is suitable for intranet or corporate domain-hosted applications, where access is handled by Windows servers and all windows users can access the application. In Beta 2, the Windows Authentication option Allow any authenticated Windows user was added. For users who want to access the application using the Internet and who do not belong to the Windows Domain, Forms authentication is recommended as users must provide the username/password, which will be checked against the information stored in a database. At the bottom of the Access Control page is a grid that is provided to define authorization. Permissions are the same as authorization rules. As shown in the grid, there is a built-in permission that controls whether someone can access the security administration screen. We will look at how permissions are set up in Chapter 7, Writing Code in Microsoft LightSwitch, when we look at creating applications for desktop, web, and cloud. Since access control exerts its control on screen navigation as well as data access, we will also look at these aspects in Chapter 3, Accessing Data from a VSLS Application to Chapter 5, Working with Entities as well. The Application Type tabbed page displays choices for the type of application and deployment options that are available to VSLS applications, as shown in the next image:
[ 46 ]
Chapter 2
As mentioned earlier, it leverages the out of browser mode and runs on the desktop. The default application type is a desktop client designed for two-tier deployment. The application services are run on the user's machine. In the case of the Web, the application can be hosted on IIS or the Windows Azure platform. In Chapter 9, Deploying LightSwitch Applications, we will look at the details of deployment (publishing).
File View of the application
The default view of the application is the Logical View consisting of Data Sources and Screens, together with the application properties as shown. Here, there are two screens based on some Application Data.
[ 47 ]
Microsoft LightSwitch IDE and Architecture
We have seen earlier how to access the FileView. 1. Click on the drop-down handle and click on File View. The File View of the application is displayed as shown with all the nodes expanded.
The application files are divided into groups related to Client, Common, Data, Server. The node Common has elements common to both Client and Server. The ApplicationDefinition.lsml file, which is common to the groups, is an XML file as shown in the next image. It is the LightSwitch markup and the user is not supposed to modify this page as it may leave the application in an unstable state. Future versions may have a different structure. 2. Right-click on this file and select View Code to view the file contents as shown:
[ 48 ]
Chapter 2
In Beta 2, the web application can be deployed to the Windows Azure cloud and hence the last two files (ServiceConfiguration.cscfg and ServiceDefinition.csdef) in the File View were added, to aid in deploying the application to the Windows Azure. We will see deploying a VSLS Application in Chapter 9, Deploying LightSwitch Applications. While customizing the application, you can add an item to the Client, Server, or Common node by right-clicking on the node which pops up in the menu as shown:
[ 49 ]
Microsoft LightSwitch IDE and Architecture
The Add, Add Reference…, and Add Service Reference… adds the chosen item or items to the node chosen. With these menu items, you can add a variety of templates and assembly references to get additional functionality depending on your requirements, such as: •
ADO.NET EntityObject Generator
•
ADO.NET Self-tracking Entity Generator
•
Class File
•
Silverlight related files and Resource Dictionary
•
Text files
•
Authentication Domain Service
•
Domain Service Class
•
ADO.NET Entity Data Model
In Chapter 10, Troubleshooting, Debugging, Custom Controls, and Extensions, we look at creating a theme extension where you will be adding files to the FileView. The App.Config file shown in the next screenshot displays the application configuration.
[ 50 ]
Chapter 2
The takes care of the authentication and authorization items and generally there is no need to modify this file. It is in the IDE that you can make changes to the settings. The node uses the SQL Express database and supports Multiple Result Sets. In developing simple applications, one needs to write almost no code and the developer may not need to access some of the more involved interfaces discussed, other than Data Sources, Screens, and Application properties. However, for more complicated situations, one may need to dig deeper into the object model.
Summary
In this chapter, a brief review of the LightSwitch architecture is presented. User interface of the standalone (in the sense of not being part of a higher version, such as Visual Studio Professional or Visual Studio Premium) LightSwitch Beta 2 is described. While only a small part of the IDE features are presented in this chapter, the features related to Data Sources, Screens, hosting topologies, and so on, will be described in appropriate places. The next chapter describes how to create application data, how to connect to this data and data from external databases, presently limited to SQL Servers and other sources.
References
1. This article nicely summarizes the architecture. Much of the content in this chapter is based on this article: http://www.code-magazine.com/article.aspx?quickid=1103051&page =2.
2. A comparison of VSLS and VS 2010 Professional is found here: http://www.microsoft.com/visualstudio/en-us/lightswitch/lightswitch-compare.
3. A four-part article discussing the details of VSLS: http://blogs.msdn.com/b/lightswitch/archive/2010/08/06/theanatomy-of-a-lightswitch-application-overview.aspx.
[ 51 ]
Accessing data from a VSLS Application Microsoft LightSwitch, being a data-centric program even in Beta version, is well positioned to connect to a variety of data sources. Presently it can only connect to SQL servers, SharePoint lists, and WCF RIA services. in the next version promise connection to more sources. Also, with its base in the Entity model, it is not only just for relational data, but also for data from other sources. In the Beta 2 version of VSLS, applications can access data from table(s) created in the VSLS IDE or they can connect to an external data source. In this chapter, we take a look at both of these options in more detail. We cover the following topics: •
Creating Application Data in the IDE
•
Connecting to external data
After reviewing this chapter, the reader will be able to connect to the prevalent SQL server versions and the forthcoming version, which will form the underlying data of its data layer, as well as connect to the data available from a WCF RIA service. Connecting to SharePoint lists is described in this book, though a complete example is not given as a Windows 7 (x32) machine, on which this book is based, does not support SharePoint 2010 (Windows 7(x64) does support). In order to understand how VSLS applications can be created using WCF RIA services, you need to understand a significant number of new technologies. It is outside the scope of this book to describe WCF RIA services, but a brief description follows in the next section. However, this chapter describes the mechanics of connecting to such an existing service. In a practical sense, these services may be created by third parties or developers with required skills.
Accessing Data from a VSLS Application
WCF RIA service
One of the objections that was directed against Microsoft LightSwitch Beta 1 was the fact that the program targeted non-programmers. Clearly, it would be difficult to rationalize that a non-programmer would understand Silverlight, Windows Communication Foundation and Domain Services, which are all necessary ingredients for creating such a service, in addition to .NET Framework classes. However, if such a service is somehow created, either by a brave non-programmer or someone who is well versed in such programs, then it will be relatively easy to consume the service using Microsoft LightSwitch. In retrospect, it is reasonable to understand why non-programmers were targeted. Over the years, Microsoft resorted to a variety of ways to connect to data on servers starting from ODBC to ADO.NET data services (after laying the foundations for the DotNet Framework). In simple terms, one could use HTTP to access data exposed as a web service through the Entity Data Model objects, which expose data provided by ADO.NET data services. The following article by the author shows how one may connect to data on a server using ADO.NET data servies using the Entity Data Model: http://www.packtpub.com/article/data-access-with-ado-dot-net-dataservices. Microsoft's Silverlight is typical of a Rich Internet Application (RIA) As
described in Chapter 1, Getting Started with Microsoft LightSwitch Silverlight is the technology behind Microsoft LightSwitch. How does RIA come into the picture? RIA Services can facilitate n-tier (presentation, logic, and data access) development with a RIA Services client application. RIA Services add tools to Visual Studio 2010 that enable the communication between the Client and Server projects in a single solution by generating the code from the middle tier. The following link provides details of WCF RIA services: http://msdn. microsoft.com/en-us/library/ee707344%28v=vs.91%29.aspx. We saw earlier that one of the data source options was WCF RIA service. Here, WCF stands for Windows Communication Foundation that is used to create a domain service on the server and generates a code made available to the client. The Rich Internet Application will consume the code working with the data on the client side. When this Silverlight Business application is built, a dynamic link library (dll) will be created. The Microsoft LightSwitch Application will use this dll to consume the service. While the Silverlight Business Application can consume the service in a Silverlight web application, the service can also be consumed by a LightSwitch application.
[ 54 ]
Chapter 3
Components of a WCF RIA service
We start off with the assumption that a WCF RIA service is available (in the references section, links to articles creating such services are available) and describes the steps needed to create a WCF RIA service. This service needs to be created in an external project using another Visual Studio product, such as Visual Studio Professional. Microsoft LightSwitch installed alone, comes with only LightSwitch projects in Beta 2, and if a suitable template is available in the MSDN Gallery, it may be added to the IDE to create the service in the IDE. Although the steps as to how such a service is created in detail are not described, the components of a WCF RIA service will be described so as to point out to the reader some of the features of a Silverlight Business Application. In a departmental VSLS application, where the WCF RIA service is on a server, the application needs access to the assemblies (dll) created by the service. This service can be on an external resource (in the present case, the VSLS application on a Windows XP machine accessed the service on a Windows 7(x32) platform over a Wi-Fi network) or available on the computer. The Silverlight Business Application when actually created has two projects, as shown in the following screenshot:
The HRApp Silverlight application has a folder/file structure as shown in the next screenshot:
[ 55 ]
Accessing Data from a VSLS Application
The MainPage.xaml is a Silverlight page with placeholders for the various Views including those created by the user in addition to the ones created by the application template as shown:
The MainPage.xaml is the one that is behind the rendering of the aspx and html pages in the web server application, as shown in the next screenshot. You can get a more detailed explanation of page navigation at: http://hodentek.blogspot.com/2009/12/navigation-in-xaml-browserapplications.html
[ 56 ]
Chapter 3
The data connection to the web application is via an ADO.NET Entity Data Model which, in the present case, is sourcing out of an AdventureWorks database on a SQL Server Express 2008. The Domain Service mentioned earlier creates OrganizationService.vb and OrganizationService.metadata.vb, which may be understood as equivalents of a web service exposing data in earlier Visual Studio versions. AuthenticationService and the UserRegistration Service are created by the template. When the project is built, the data classes are available in the generated code for the Silverlight application. In essence, HrApp.web.dll is the one that will be used (consumed) by the Microsoft LightSwitch Application. Before moving on to the next section, an example of the page displaying the Employees table in AdventureWorks database is shown in the following screenshot, which is essentially HrApp.TestPage.aspx.
Creating data entities in LightSwitch applications
Microsoft LightSwitch is order-made for displaying and manipulating business data. Data required for the application can be created in the Microsoft LightSwitch IDE, or existing data can be used by connecting to the external data source. In the following section, we will look at how to create application data by creating a table in the IDE. We will also look at creating entities from an external source.
[ 57 ]
Accessing Data from a VSLS Application
Creating a table (or entity) in a LightSwitch application
It is very easy to create a table in a LightSwitch application as it is custom-made for such an activity. In this book, the words "Tables" and "Entities" are used interchangeably with tables being used in the context of a database while entities are used in the context of business objects (review the following link to know the differences between Tables and Entities: http://social.msdn.microsoft. com/Forums/en-US/lightswitchgeneral/thread/b021d830-7fd0-436b8c79-10593d3e0622/). Entities cover a larger range of data than Tables, as any
set of objects that have business logic and can be related in some way embracing Microsoft's Entity Data Model are known as entities. Also, even non-programmers would know what tables are, but not entities. We saw in Chapter 2, Microsoft LightSwitch IDE and Architecture that LightSwitch data uses the Entity Data Provider. Now for the nuts and bolts of creating a table using LightSwitch, follow along the indicated steps: 1. Start Microsoft LightSwitch from its shortcut and click on File | New Project… to open the New Project window. 2. In the New Project window displayed, highlight LightSwitch Application (Visual Basic) and rename Application 1 to a name of your choice (Here, it is NewHire, as shown in the following screenshot). Depending on user preference, the C# option can also be used and both these project templates have the same capabilities. However, once the project type is chosen, it cannot be changed. You can change the directory for the project files using the Browse… button as well as add to source control. Here the defaults are accepted. 3. Click on OK. The NewHire project gets created after a while. The application designer NewHire Designer is displayed. As we saw in the previous chapter, there are two options to work with data. You can work with data by choosing Create new table or you can choose Attach to external data in the NewHire Designer window. Here we will be creating a new table:
[ 58 ]
Chapter 3
4. Click on Create new table. A new item Table1Items gets added to the Data Sources node (although not immediately— depends on your machine resources) and a table Table1Item with columns and rows gets added to the NewHire Designer pane as shown. The table properties window displays properties of the table, such as whether it is searchable or not, its display name, and so on. You can create a table starting from any of the following: clicking on Add Table in the drop-down list of Project menu, right-clicking on Data Sources node, creating a new Table link in the NewHire Designer, and right-clicking on NewHire project in Solution Explorer.
The table created has just one column, a unique identifier (see the tool tip). The table designer is multi-functional, as you can see from the tabs on the NewHire Designer* window. You literally get access to the rest of the required elements of an application. The table item is Table1Item but in the Solution Explorer, it is the pluralized version (one may wonder what if the language is not English). You can change the name of the table in two ways: you can directly type the name in NewHire Designer to replace Table1Item, or in the table properties window in the General node, change the name: Table1Item. Here, the Salesman is used for the table name. [ 59 ]
Accessing Data from a VSLS Application
Note that the table is created (as shown in the next screenshot), which has just one default column Id, which is Required with a data type Int32 and is the primary key pk. Also, in a LightSwitch application, there is no equivalent of composite key that one may find in SQL Server databases (review the discussions at: http://social.
msdn.microsoft.com/Forums/en-US/lightswitchgeneral/thread/705b0c7765b7-4cb8-9e8c-55da3e8ebb9c and at: http://social.msdn.microsoft. com/Forums/en-US/lightswitchgeneral/thread/c0b88194-a16e-4aa7-9f5505758598ebb8).
Note however, that when you attach to an external database, you could have the existing composite keys brought into LightSwitch IDE. The Salesman table (entity) is designed in a manner very similar to how a table is designed in SQL Server Management Studio (SSMS), although the interface does not have the same details as a table designer in SSMS. Click on the box just below Id in Salesman table, where the text is displayed and type in FirstName. In the adjacent column, click on the drop-down handle to reveal a pick list as shown:
You see a number of data types supported in LightSwitch from where you can choose one appropriate for the column. Here, String data type is appropriate for FirstName. Because a name is necessary for a new hire, you can accept the default property as being required. This successfully creates a column in the Salesman table. If you want to delete the property for some reason, you make a right-click on the left of FirstName and from the drop-menu, click on Delete. [ 60 ]
Chapter 3
Note that in the above image, the list is scrolled down and the following items are not shown: Date, Boolean, and Binary.
Data types in Microsoft LightSwitch
As seen in the drop-down list, there are a number of data types that are supported in this version of VSLS. There are data types such as Short Integer, Integer, Long Integer, and so on, which are easily recognized (as they are also used in SQL Server). There are also new data types such as EmailAddress, PhoneNumber, and many others) implemented like custom data types. The following image captured from the IDE's help file shows more details about the supported data types. In a future version, it appears that more will be supported (Spatial Data Types?). Using extensions discussed in Chapter 10, Troubleshooting, Debeugging, Custom Controls, and Extensions it is also possible to create custom data types.
Because VSLS is really built for business applications, the VSLS specific business data types such as PhoneNumber, Money, Image, and EmailAddress will be extremely useful as they appear very frequently in business applications and these data types have built-in validation provided by the IDE. We will learn about data validation in the Chapter 5, Working with Entities. [ 61 ]
Accessing Data from a VSLS Application
Salesman table
In the previous section, we started the NewHire project and created a Salesman table. At present, we only have two columns in the table: Id and FirstName. We will go ahead and complete the design of the table with more information about the Salesman. The table is completed as described in the previous step by adding the column values shown in the next paragraph and setting all their Required property to false. •
LastName
String
Not required
•
Address
String
Not required
•
HireDate
Date
Not required
•
BirthDate
Date
Not required
•
Email
EmailAddress
•
Phone
PhoneNumber
Not required
•
StartSalary
Money
Not required
Not required
Notice that there is a fair amount of flexibility in developing the table. You can insert a column (that is, a Property in a chosen location by right-clicking the column and choosing Insert New Property) at the chosen location as shown. You can also move up or down the columns, as well as insert a new property, or establish a relationship with another entity.
[ 62 ]
Chapter 3
This will add Property1 between BirthDate and Email. Also, using the Move Up and Move Down choices, the columns can be rearranged. Property1 can be changed in the Properties window for the column. The completed table should appear as shown in the next screenshot:
The Required property has been set to Not required by not checking the checkbox for most columns. It's just for convenience in this case that it is set to Not required, but in a realistic application, some properties must be present for entries to be valid. For example, in the case of a bank account, the account name and account number may both be required. For the above table, therefore, data can be added without worrying whether data is available or not. However, if the data is entered in any column, its data type should be the same as (or convertible to) the one specified in the table design. The data entered into the table will be validated by the program including those of the business types. While the above represents the Business Types in VSLS, the following image shows how it is persisted in the data layer. This screenshot was obtained by attaching the ApplicationData.mdf (ApplicationData.ldf) file, which is created whenever a table is created in VSLS using the SQL Server Management Studio.
[ 63 ]
Accessing Data from a VSLS Application
As explained in the previous chapter, application data (the one created by the process described in this section) creates database files, MDF and LDF, which are used by the IDE wherein users can add data; work with it testing the CRUD operations, but when the application is deployed, only the meta data of the table created in the IDE goes into the deployed database (which bears the name of the project by default), and the data that was entered in the IDE does not get into the deployment. The path of the MDF file shown is only for the IDE during development. The deployment target is the SQL Express installed when VSLS is installed.
Note that each data type in the table maps to a SQL Server data type. Also, note that though no authentication information has been used so far (except that it is a default client or server with Anonymous access), the membership database is created by default. Presently, the authentication/permission-related database has only meta data. Another thing to note is that FirstName, LastName, Address, EmailAddress, and PhoneNumber are all of nvarchar (255) type.
[ 64 ]
Chapter 3
After creating the table, one needs to populate the database with values for various "Salesman" (Salesmen) who are hired by the company. We will populate the Salesman table in the next chapter.
Creating data entities using an external data source
Microsoft LightSwitch is order-made for displaying and manipulating business data. As a large number of applications still use Microsoft Access and it is likely that many will upgrade to Microsoft LightSwitch, our discussions will be more productive and easy to understand if we can use some of the business models used in Microsoft Access. With this in mind, we will be using the Northwind database, which is perhaps most familiar to the users as it gives an example database in MS Access as well as several versions of SQL Servers.
Review of business-related Northwind database tables
Here, before we describe how VSLS handles data, we take a look at three of the business-related tables in the Northwind database that we are going to use in the present discussions. The next screenshot shows the three tables: Orders, Products, and Order Details in the Northwind database:
[ 65 ]
Accessing Data from a VSLS Application
Each one of the tables has information related to the particular entity and the Order Details table is used to relate Orders* to Products*. In order to relate the tables, the Order Details* table has a composite key, that is, the Order Details table has a primary key consisting of both OrderID and ProductID. You may line up the tables in the preceding fashion creating a New Database Diagram in SQL Server Management Studio, or using the Relationships window in Microsoft Access in most versions. As shown presently, you have tables by themselves unrelated, but you can establish relationships between them as Orders and Order Details can be related by OrderID, Products, and Order Details by ProductID. The next screenshot shows relationships established between the three tables. The Order Details has a composite primary key and has foreign keys for the two other tables.
Attaching to external data
As we saw earlier, when a new VSLS application is created, the project template creates the project folder, as well as displays the designer panel, where a table can be created, or the application can be attached to external data. In the following, we will create a VSLS project that will attach to an external data: 1. Create a VSLS project using the Visual Basic template or Visual C#, naming it Nwind (here, the Visual Basic template is used). The Nwind project gets created displaying Nwind Designer. [ 66 ]
Chapter 3
2. Click on Attach to external Data Source in Nwind Designer. The Attach Data Source Wizard window is displayed as shown:
3. As seen here, there are three types of data sources to which you can get attached: °
The Database option lets you connect to database objects in a database
°
The SharePoint option lets you use lists returned by a SharePoint 2010 site
°
The WCF RIA Service option lets you import entities to be used by your application by consuming a WCF RIA Assembly
In order to use the SharePoint option, you must be able to connect to a SharePoint site, which needs to run on a Windows Server. Review system requirements to run SharePoint at http://technet.microsoft.com/en-us/library/cc288751. aspx. As this book is based on Windows 7 Ultimate OS on a 32-bit Intel machine, the SharePoint option will not be described with an example as it cannot be created on this machine. However, links and related information will be provided. It may be noted that though there are many public sites that are hosted on SharePoint, they need special configuration to be accessed by VSLS applications.
Accessing data on a database
In this section, we look at accessing data using the option Database in the Attach to Database Wizard, which you saw earlier:
[ 67 ]
Accessing Data from a VSLS Application
1. Click on the Database icon to highlight it and click on Next. The Connection Properties window is displayed, as shown with all the default settings. Again, like in many Microsoft programs, there is usually more than one way to accomplish a task. You can connect to an external data source by different means as we did for creating a table. You can do it from Project Menu, the Project node in Solution Explorer, the TestApplication Designer, or the Data Sources node in Solution Explorer.
Let us explore the options in this Beta 2.
[ 68 ]
Chapter 3
2. Click on Change.... The Change Data Source screen is displayed.
In the RTM, this figure will be slightly different. It will show Microsoft SQL Server and Microsoft SQL Server Compact 4.0. Steps to follow may also need to be followed keeping this in mind.
The Description clearly says that you can connect to Microsoft SQL Server 2005 or above, or to Microsoft SQL Azure using the .NET Framework Data Provider for SQL Azure. 3. Click on in the Data source: of the Change Data Source window. There appears to be no other data source through which one can connect to a VSLS Application. 4. Click on the handle of Data provider: combo-box to display the other possible data providers.
[ 69 ]
Accessing Data from a VSLS Application
The other data provider, the .NET Framework Data Provider for Microsoft SQL Server Compact 3.5 is displayed. 5. Click on the highlighted option to choose Microsoft SQL Server Compact 3.5. The Description now clearly says that you could connect to Microsoft SQL Server Compact 3.5.
The databases that one can connect to from a VSLS application natively in Beta 2 are: •
Microsoft SQL Server 2005 and above
•
Microsoft SQL Azure Server on the Windows Azure Platform
•
The Microsoft SQL Server Compact 4.0
However, it should be noted that while one can connect to SQL Server Compact 4.0(3.5), developing applications using this data source in VSLS is not supported. As we saw in the previous chapter, VSLS applications can be developed for those third-party products that support Entity Framework. Presently, MySQL and Oracle 11g can be used. Note that for other providers to appear in the previous window, appropriate Entity Framework supporting providers must be registered in the machine.config file. This will be explained in a later section. In order to use the other third-party source versions that do not support Entity Framework, one can create a WCF Data Service, which can be consumed by VSLS.
[ 70 ]
Chapter 3
Connecting SQL Server 2005 and above
In this case, you can use the Connection Properties window we saw earlier or highlight Microsoft SQL Server in the Change Data Source we saw earlier, which takes you back to the Connection Properties window. In the following, it is assumed that you have a Microsoft SQL Server Installed on the computer. On the computer used for this book, there are a number of Microsoft SQL Servers (Enterprise SQL Server 2008 R2, SQL Express, SQL Server Express 2008 R2, Denali (SQL Express 2011 in Beta), and so on, which can be accessed by the drop-down handle for Server name). Each of the servers has many databases as shown here for the SQL Express Server. This server has been installed with Windows Authentication (if the server is installed for SQL Server authentication, then UserName/Password will be needed, and these fields become enabled for this selection): 1. Choose the database from the drop-down, which should display all the databases if the server name and authentication information are correct as shown:
[ 71 ]
Accessing Data from a VSLS Application
2. Click on (for example) Northwind in the drop-down. Northwind is entered into the Select or enter a database name field. 3. Click on Test Connection. You should get a Microsoft Visual Studio message: Test connection succeeded. 4. Click on OK. The Choose your Database Objects page of the Attach Data Source Wizard is displayed after a little while. The Which database objects do you want to import? pane will display all the Tables and Views as shown in the next screenshot (the Views are hidden in this screenshot, where both the nodes are expanded; also, only few tables are shown). Note that when you use WCF RIA Services, you can also bring in stored procedures.
[ 72 ]
Chapter 3
In the previous screenshot, you would choose table(s) and view(s) that you would use in your VSLS application. You choose them by placing checkmarks (click inside the squares by the side of the tables or views in the check box). The screenshot also shows that three of the tables, Orders, Order Details, and Products, have been chosen. These three tables will be included in the data source with the name NorthwindData. Here, it was renamed to NwindData by replacing the default name. 5. Click on Finish. The Wizard exits and you will be returned to the VSLS application in the IDE as shown:
NwindData joins the Data Sources node in the Solution Explorer with the three tables chosen in the previous step. The three tables will be added to the Nwind Designer-tabbed page, correctly displaying the relationships that exist between these tables. With the Order_Details table, the Product, and Order tables have a one-to-many relationship.
[ 73 ]
Accessing Data from a VSLS Application
The Order_Details table with five columns and a composite key (OrderID and ProductID) now has two more rows, which establish the same relationship in the Entity Designer in addition to OrderID and ProductID rows.
Updating the data source
We see that there are three tables in the data source. The data source can be updated by right-clicking on the node NwindData and choosing Refresh Data Source. This will take you back to the Choose your Database Objects page of the wizard, where you can modify your selections. You can add more tables or remove a table by unchecking in the data connection wizard. This is a general procedure to modify entities in VSLS applications. In a similar manner, it should be possible to connect to SQL Servers 2005 and above.
Connecting to SQL Server 2011 (in CTP1)
Let us see what happens if we try to connect to SQL Server 2011 (which is presently in CTP1 with the name Denali) Recently, Denali CTP3 was released. Download link for CTP3 is in Appendix A of the book, which may be accessed on the Packt's site. HODENTEK3\ALASKA (SQL Server 2011) is a named instance; your server name could be different if you have the server installed), to which a Northwind Database data has been copied and given a new name NorthAlaska. It is installed for Windows Authentication. Using the Test Connection button, you can verify that the connection succeeds.
[ 74 ]
Chapter 3
The next screenshot shows the tables that you can access after connecting to the database:
[ 75 ]
Accessing Data from a VSLS Application
When you click on Finish, you may get a warning as shown in the next screenshot:
This is because the tables we chose earlier did not have primary keys (the Export-Import wizard used in data transfer did not bring in the primary keys). This warning is not only specific to SQL Servers but for other databases as well. When you click on Continue, you will have added a data source NorthAlaskaData to the VSLS application. However, the tables are not connected in the IDE as there are no relationships in the Denali's NorthAlaska database. We will discuss connecting these key-less tables in a later chapter.
Connecting to SQL Azure
If you recall, SQL Azure is really SQL Server 2008 R2 hosted in the cloud (I strongly recommend my book: http://hodentekmsss.blogspot.com/2010/12/ regarding-my-book-on-sql-azure.html), and connecting to it and working with it is very easy. All you need to do is to copy the connection string from the SQL Azure portal and use it in the Connection Properties window. You must also remember that SQL Azure admits only SQL Server authentication, which means you must be armed with Username and Password to connect to it. Because it is not an on-site SQL server, you must also connect to a database on the server. The next Connection Properties window shows the various items you need to set while connecting to SQL Azure (the screenshot shows a connection being established to the author's SQL Azure instance on Windows Azure Platform).
[ 76 ]
Chapter 3
Here is the ADO.NET connection string copied from the SQL Azure portal (http://sql.azure.com). Server=tcp: XXXXXXXXXX.database.windows.net; Database=master; User ID=mysorian@xxxxxxxxxx; Password=myPassword; Trusted_Connection=False; Encrypt=True; Here is the Connection Properties window, you will need to connect to SQL Azure database (presently the above account has only the master database to keep the cost down; the author has not created any other databases). The items highlighted in the connection string are used in this window. The server name XXXXXXXXX is masking the server name of the provisioned SQL Azure Server.
[ 77 ]
Accessing Data from a VSLS Application
Using this connection, you can get to the tables and views on SQL Azure, as shown in the next screenshot:
Here, only one of the Views, firewall_rules (sys), has been chosen for the data source. By entering default name masterData and by clicking on Finish , you can add this data source to the Data Sources node after displaying the warning that the table's or view's master.sys.firewall_rules does not have a PrimaryKey defined. This is OK because views are not supposed to have keys.
Connecting to SQL Server 2008 R2 Express
This is the latest free edition, well integrated with the free Visual Studio product, the Visual Studio 2010 Express. SQL Server Express 2008 R (58.17 MB) can be downloaded from: http://www.filehippo.com/download_sql_server_express/. It can be installed just like the more recent versions of the SQL Server (there is a comprehensive chapter on installing more recent SQL Servers in my book at: http://www.packtpub.com/learning-sql-server-2008-reporting-services/ book?mid=010409ofvkyp
Using this, creating a data source in VSLS is no different from the others previously mentioned and follows the same lines. [ 78 ]
Chapter 3
Connecting to SQL Server Compact
The future applications on the Internet will be mostly accessed using mobile devices. They do operate mostly in the disconnected mode due to various reasons, such as network availability, nature of business (for example, a travelling salesman connecting back to his HQ for data refresh, and the like), and so on. Microsoft has tied up the mobile data access to its database on the cloud using robust synchronization technology. VSLS applications can very well be the frontends for these mobile databases. From Beta 2 to RTM some changes have been made with regards to connectivity to SQL Server Compact. The Connectivity in Beta 2 was to SQL Server Compact 3.5, and in the RTM, it is to the version 4.0. This difference will not have any effect on how you connect to SQL Server Compact from a VSLS Application. You may download version 4.0 from here, http://www.microsoft. com/sqlserver/2005/en/us/compact.aspx and install it. To get most out of SQL Server Compact please review the following link: http://hodentekmsss. blogspot.com/2010/07/sql-server-compact-35-basics-you-must.html.
If you do not have SQL Server Compact 3.5, you may download and install it from: http://www.microsoft.com/sqlserver/2005/en/us/compact.aspx. The author strongly recommends reading the two articles in the previous link. Although not seen here, the IDE may also support SQL Server Compact 4.0 as there is an entry for it in the machine.config file.
RTM was not released when this was written.
You saw in the beginning that the Connection Properties page guides you to connect to a .NET Framework SQL Server Compact 3.5 provider. We will be using this window to establish a connection. The same procedure can be used to connect to SQL Server Compact 4.0 in the RTM.
[ 79 ]
Accessing Data from a VSLS Application
When you dismiss the Change Data Source window after choosing the above provider, the Connection Properties window appears as shown here. Notice that the Data source (provider) is now Microsoft SQL Server Compact 3.5. This data can originate from your computer or it can be from a connected source through ActiveSync—the robust synchronization technology mentioned earlier.
1. Click on Browse… after navigating to the screen. The following Select SQL Server Compact 3.5 Database file screen is displayed, where you look for a compact database server file on your machine. The wizard is cleverly set up so that it takes you directly to the sample compact database, Northwind.sdf (that gets installed when you install the Microsoft SQL Server Compact 3.5).
[ 80 ]
Chapter 3
2. Click on Northwind.sdf. The file path information gets entered into the Connection Properties window. 3. Click on Test Connection. The Test connection succeeded message is displayed. 4. Click on OK on both screens. The Choose your Database Objects screen is displayed, as shown in the next screenshot:
Note that in Compact 3.5, only tables are supported. 5. Choose the table(s) you need (here, Customers and Orders); change the Data Source Name: to something simpler. 6. Here, Data Source Name is chosen as NorthCompact.
7. Click on Finish. The NorthCompact data source will be added to the Data Sources node in the Solution Explorer.
[ 81 ]
Accessing Data from a VSLS Application
The IDE has enough flexibility to bring as many, or as few of the data sources and their objects, as needed. It is possible to bring a large number of tables without any problem. Note, however, that you will not be able to create a VSLS with this source; at least not in this version, as we shall see later trying to display data on the SQL Server Compact 3.5(or 4.0).
Connecting to databases on MySQL
As previously mentioned, it is possible to connect to MySQL and Oracle 11g by using the .NET Providers supplied by the vendors that support Entity Framework. Here, we look at connecting to MySQL using the MySQL 6.3.6 connector.
Getting the connector
At first, you need to download and install the connector. The connector may be downloaded from the following link: http://www.mysql.com/downloads/mirror.php?id=402376
This download file, mysql-connector-net-6.3.6.msi (106MB) when run, modifies the machine.config file for VS 2010 and VS 2008 versions of Visual Studio. The connector when installed, modifies the machine.config file so that the following XML fragment is added to the node, enabling the Connection Wizard in Visual studio 2010 to display MySQL, as we shall see presently.
Connecting to a database on MySQL
The connection will be made to an existing database testmove on the resident MySQL Server. It will be instructive to read all of my MySQL-related articles at: http://hodentek.blogspot.com/search?q=MySQL as the database we are connecting to has been documented in some of them. While connecting to MySQL, the choice is to connect to an external database. This brings up the Connection Wizard, which by default uses the SQL Server (SQL Client) as we saw in an earlier section. When you change this to look for other options, the following window is displayed.
[ 82 ]
Chapter 3
You will notice that .NET Framework Data Provider for MySQL has been added after installing the connector. When you click on OK, you will get to the next screen where you need to authenticate yourself, as shown in the following screenshot:
[ 83 ]
Accessing Data from a VSLS Application
Choosing testmove database and clicking on OK should bring up the screen where database objects (Tables and Views) are displayed. However, in the present case, the following window is displayed:
The Connector will allow you to connect and create a Data Source but it does not provide access to the tables or views. It is possible to add data to this Data Source from the IDE. It may be noted that the testmove MySQL database has several tables, none of which have a primary key column. However, when a table with a primary key exists, it gets displayed in the IDE and the table object is correctly modeled in the designer. However, a View is displayed if the underlying table has a primary key, as shown in the following screenshot:
[ 84 ]
Chapter 3
Clicking on Finish adds the table to the Entity Designer and a node testmove to the Data Sources, as shown in the next screenshot. The Solution Explorer shows all the data sources created so far, including the testmove database on MySQL.
[ 85 ]
Accessing Data from a VSLS Application
Accessing data on SharePoint 2010
Microsoft SharePoint 2010 is supported but requires to be configured for supporting WCF RIA Services. Lists and Relationships can be accessed, but not Attachments and Transactions. Data is obtained from SharePoint using the DataService Context as the provider, which depends on System.Data.Services.Client. DataServiceContext in System.Data.Services.Client.dll. Once you get DataService Context, it will be very easy to access data. In a VSLS application, you do not even need to code as the wizard makes it easy to reference the site and get the list you want to include in the application. In doing so, LightSwitch uses the Entity Framework ObjectContext to talk to the SharePoint through the ODATA feed using SharePoint's DataService Context mentioned earlier. The whole of under-the-hood processing is transparent to the end user. SharePoint 2010 is not supported on Windows 7 (x32), but if you have a Windows 7 (x64) platform, you could get an evaluation copy from: http://technet. microsoft.com/en-us/evalcenter/ee388573. Make sure you read the requirements. Please refer to the link just mentioned for other platforms as well. Accessing data from a SharePoint site is described in Microsoft Documentation listed in the References section. If you do try to access a service from Windows 7 (x32), the following screenshot is displayed:
[ 86 ]
Chapter 3
Accessing data from a WCF RIA Service
In this section, we will look at a data source created in VSLS application that accesses data from a WCF RIA Service. 1. Bring up Attach Data Source Wizard, as described earlier, and highlight WCF RIA Service in the Choose a Data Source Type page. 2. Read the note in the previous screenshot and click on Next. The Choose a WCF Ria Service page of the wizard is displayed:
The Microsoft LightSwitch created WCF RIA Service classes are shown (you get this free from the template). Note that you may not see these in Beta 2. Now, we add a reference to the HRApp application described in the previous section. 3. Click on Add Reference. 4. The Add Reference window is displayed. The HrApp project is in another location (this project was created using Visual Studio Express 2010, a free Microsoft download). The Hr.Web.dll is created in another project (in this example, it was created using Visual Studio 2010 Express free edition).
[ 87 ]
Accessing Data from a VSLS Application
5. Click on Browse and locate dll as shown:
On this computer, it was created in the HrApp project directory at: %Users%\Visual Studio 2010\Projects\HRApp\HRApp.Web\bin
6. Click on HrApp.Web.dll and click on OK. The list of WCF RIA Services available gets updated, as shown in the next screenshot:
[ 88 ]
Chapter 3
7. Highlight HrApp.OrganizationService and Click on Next. The Select Data Source Objects page of the wizard is displayed as shown:
The reason we see three Entities is because we had chosen three tables to be included in the HrApp WCF RIA Services application. 8. Place check mark for Employee in the Entities node and click on Finish. (Here, OrganizationServiceData was chosen for Data Source Name: by replacing the default). You will get a security message depending on how the WCF RIA Service was created. 9. Override the warning and click Continue. In a more secure application, do heed the warning and take the necessary steps. OrganizationServiceData gets added to the Data Sources node of the Nwind Application. It is not altogether clear why all fields are associated with a key symbol.
[ 89 ]
Accessing Data from a VSLS Application
In this chapter, we created a number of data sources by either using the Database option, or the WCF RIA Service option. The data can used in the screens (subject of next chapter) using these, as shown in the following screenshot:
Summary
In this chapter, we reviewed all the data connection options available so far in a Microsoft LightSwitch application, except accessing data from a SharePoint list. Specifically, we learnt how to connect to the SQL Servers on site, in the cloud, on a mobile device, and also how to connect to the next-in-line version SQL Server 2011 with the code name "Denali". Connecting to MySQL besides SQL servers is also described. In the next chapter, Screens in VSLS Applications, we will be using the data from these sources and binding them to the various 'Business screens' that the UI provides in developing business applications.
[ 90 ]
Chapter 3
References
1. Important MSDN Blog's article that completely describes data access in VSLS Applications: http://blogs.msdn.com/b/lightswitch/archive/2010/11/30/anatomyof-a-lightswitch-application-part-4-data-access-and-storage2.aspx
2. VSLS Applications connecting to data from various sources are discussed at: http://msdn.microsoft.com/en-us/library/ff852017.aspx
3. Guidelines for Creating WCF RIA Services for LightSwitch are discussed at: http://msdn.microsoft.com/en-us/library/gg589479.aspx
4. Examples of VSLS Applications consuming WCF RIA Services are at the following links. All are full examples including how to create such a service: °
http://blogs.msdn.com/b/lightswitch/archive/2011/04/08/ how-do-i-display-a-chart-built-on-aggregated-data-ericerhardt.aspx
°
http://blogs.infragistics.com/blogs/mihail_mateev/ archive/2011/01/21/using-visual-studio-lightswitchapplications-with-wcf-ria-services.aspx
°
http://www.paulspatterson.com/technology/lightswitch/ microsoft-lightswitch-odata/
5. VSLS Application with SharePoint 2010. A brief summary of a SharePoint site link: °
http://blogs.msdn.com/b/uksharepoint/archive/2010/04/05/ introducing-site-directory-for-sharepoint-2010.aspx
°
http://www.wictorwilen.se/Post/How-to-create-aSharePoint-2010-application-using-Visual-Studio-2010LightSwitch.aspx
A full application connecting to SharePoint 2010 is described at: http://blogs.msdn.com/b/lightswitch/archive/2011/02/01/ extending-a-lightswitch-application-with-sharepoint-datarobert-green.aspx
[ 91 ]
Screens in VSLS application While data is at the heart of the business application, the screens provide a window to this data. It is, therefore, not unusual for businesses to ask a developer to show them how the screens (windows) look and function when the application is finished. Windows (screens) started with the object oriented C++ technology based on Microsoft Foundation Classes (MFC) but real show time and large-scale adoption started with Microsoft Visual Basic and the event-driven programming model. This was superseded by the Windows Forms developed with the birth of the Microsoft .NET Framework that wrapped up the Windows API in managed code. The next development began with .NET 3.0, (now .NET 4.0) and the Windows Presentation Foundation (WPF). WPF with its object-declarative programming, although superior to binary object representation, presented a steep learning curve. WPF allowed not only object declaration but also object binding in a variety of ways. Microsoft LightSwitch represents a quantum leap and inherits this rich and most recent development in programming. Screens in VSLS are the equivalents of Windows Forms with just one difference, they are equivalent only after the application is run and screens are displayed. At design time there is no resemblance; there is an UI design interface in Windows Forms where you can drag and drop objects (controls) but none in VSLS. However, Microsoft LightSwitch provides a pre-set number of controls with their positions pre-designed for each type of screen (each screen being a representative of a business-related activity such as search, display, insert, and so on). In addition, the facility to add or remove controls from the pre-set suite is also supported. The events that these screens evoke can be linked to code that runs to accomplish developer's logic or, satisfy a custom need.
Screens in VSLS application
In this chapter, we will learn the different screens that are available in Microsoft LightSwitch Beta 1 and bind them to the various data sources we got connected to in Chapter 3, Accessing Data from a VSLS Application. We will be seeing more of the screens in other chapters as well but here you will be getting the first taste of what they can do and how they are configured without writing any code.
Screens, data, and visual presentation
VSLS application screens are independent of one another and represent a complete independent unit of work. The screens open in a tabbed arrangement of screens at runtime and the shell keeps track of the active screen. The first screen you create will always come up first, but in the case of multiple screens you can determine which of them should be active to start with using the Screen Navigation node in the Project Properties. The Screens in a VSLS application follow the MVVM (http://en.wikipedia. org/wiki/MVVM) pattern. The screen object is the model that encapsulates the data
and business logic; the screen layout defines a tree of view models that define the logical layout of the screen. The Visual tree is what is being presented consisting of Silverlight controls that are data-bound to the view models in the layout. Screen object (Data & Logic) is the business object of a VSLS application. It is all data and no graphic interface. It can have data (scalar/entity), parameters (scalar values), query results, and so on. Although all of these are not seen in this chapter, you will see examples of all of these in the rest of the book. In the designer's screen, it is on the left. Each screen has its own copy of entity and the copies are not shared. The Screen Layout shows how the controls that display the content are laid out. There is a direct relationship between each of the controls in the Screen layout to the Visual tree seen in the presentation. These controls may be discrete controls or container of controls (Group). When a screen is created, the LightSwitch runtime builds the content dynamically (Visual tree) based on what the designer has arranged in the screen layout. The screen layout is arranged initially by the choice of template. It is, however, possible to start with an unbound screen and customize the layout. Screen data management is handled by the data work space (dws) by tracking the local copy of the entity and the relationships if multiple entities are used by the screen. The dws fetches data from the data service (supplied by the data source you add to the application). If there is more than one data source, it aggregates data from each of the data services.
[ 94 ]
Chapter 4
A schematic of the architectural details of the client copied from the URL here: (http://blogs.msdn.com/b/lightswitch/archive/2010/08/09/the-anatomyof-a-lightswitch-application-series-part-2-the-presentation-tier. aspx) is that which was described earlier. Shell Hosting
Screens
Shell UI
Data &Logic
Theming
Visual
Data Workspace
Layout
Entities
Relationships
Queries
Update
Microsoft LightSwitch screens
The screens in Microsoft LightSwitch Beta 2 (listed here) cover a majority of business needs, especially those of small businesses. In RTM also, you find the same screens appearing in slightly different order than in Beta 2: •
New Data Screen
•
Search Data Screen
•
Details Screen
•
Editable Grid Screen
•
List and Details Screen
The data for these screens by default uses all the data in the data source but it is also possible to create screens based on queries against the data source. At runtime, the screen is displayed in the browser and if there is no screen created at design time, the browser displays a blank screen with just the Save and Refresh buttons disabled. In addition to these out-of-the box templates, it is also possible to create custom screens using extensions and screens created by third parties. In the following section, we will be looking at the default.
[ 95 ]
Screens in VSLS application
Specifically, we will be looking at some of the general features of the screens using two of the above screens available in Microsoft LightSwitch. In the present chapter, we will look at the following: •
New Data Screen
•
Search Data Screen
•
Creating a screen from scratch
•
Export to Excel functionality
•
Customizing screens at runtime
New Data Screen
There are occasions in business when you may want to add fresh data to an empty table, or add data to an existing table. In the previous chapter in the NewHire project, we created a Salesman table. We will populate the table using the New Data Screen. This table has several different data types some of which are required. We will add a couple of rows of data to this table. Start Microsoft LightSwitch from its shortcut and open the NewHire Project created previously as shown (partial view shown in the image).
At this point, you may want to consider how you plan to manage the project. There are three ways you can configure the project for deployment. Project deployment is described in Chapter 9, Deploying LightSwitch Applications.
Creating a screen
We started with describing how a New Data Screen is created. The reason for this is that this type of screen is made for inserting data into the Application Database. In the following we will create a screen. The screens we create for the application are part of a screen collection and will be under the Screens node. [ 96 ]
Chapter 4
1. Right-click on the Screens node as shown.
2. Click on Add Screen…. The Add New Screen window is displayed as shown with the first screen in the collection as shown. In this case, it is the Details Screen.
[ 97 ]
Screens in VSLS application
3. Now click on New Data Screen. The New Data Screen template appears as shown in Add New Screen window.
Binding screen to data source
Using this screen you can create a new data record (a new row of data) and you can also add child records for a parent. We will consider adding child records later. Click on the handle for Screen Data and you would see Salesman as the only data source. 1. Click on Salesman in the drop-down list. 2. Now the screen is bound to Salesman entity. 3. Click on OK. 4. The update region of Add New Screen window appears as shown.
[ 98 ]
Chapter 4
Because there is only one table we are populating we can remove the check mark for Salesman Details. 5. Clear the check mark for Salesman Details and click on OK. 6. The CreateNewSalesman screen will be added to the Screens folder (you may choose a custom name if you want to). At the same time, the columns from the entities will be displayed as well as the tree view of the controls that will be available on the screen. This choice is made by Microsoft LightSwitch by default. You can change this in many ways as we shall see later.
[ 99 ]
Screens in VSLS application
The middle panel of the IDE shows how the screen is designed. The Create New Salesman is the screen that will be displayed. The screen has a Screen Command Bar consisting of Save and Refresh buttons by default. You may add other buttons using this middle panel. We will see how this is done later. The rows of data corresponding to the Salesman Property are arranged as a list here (appear in a grid in the displayed browser) and its has its own Command Bar which is empty by default. You can add command buttons to this Command Bar and program the buttons you add (using this middle panel). The various columns of the Salesman appear below this Command Bar. The arrangement of the columns follow the same way they appear in the entity. Associated with each field is an icon representative of the data that is present. The Microsoft LightSwitch specific data types of the columns Email, Phone, StartingSalary and HeadShot have their own specific editors (modify) or viewers (read only) as shown here for the Email field by expanding the Email control in the screen layout.
You can add more controls to the Screen Command Bar as well as Command Bar under the Rows Layout by clicking the plus (+) sign on the +ADD drop-down button. You may need to first click the Command Bar which displays the Command Bar as a node and then click the (+) sign.
[ 100 ]
Chapter 4
The Rows Layout which is presently a vertical stack of the controls has all the column headings. There are different ways data can be displayed in the Screen Content Layout. These options which can be seen by clicking the drop-down handle are shown in the next image.
By scrolling up, you will see that there is one more option, the Address Editor. In addition to the controls provided by Microsoft LightSwitch you have the option to use a Custom Control, a control designed by the user or by referencing to the .NET library where the control is found. Creating and using a custom control in a VSLS Application is described in Chapter 10, Troubleshooting, Debugging, Custom Controls, and Extensions with an example. For the purposes of the following, we will assume the Rows Layout (the default) which arranges the controls in a vertical arrangement when the screen is displayed. From the above discussion, we can see that there is no equivalent of a design view of the screen (similar to what is seen in Visual Basic or WinForm). This is a major difference that the user will find difficult to adjust to. After creating a screen if you make changes to the ordering of the entity fields it will not be reflected in the Screen Layout. You will have to delete the screen and create a new screen.
[ 101 ]
Screens in VSLS application
Screen properties
The Properties window of the Screen Layout and the controls you find in a Screen provide a means to design these elements. The Properties windows of most controls are organized with all elements having the same nodes: General, Appearance, and Sizing. The next screenshot shows how much control you can have on the screen design (the image is a composite showing expanded views of all the nodes).
This screen is for the default Rows Layout and you can choose to change the display name, choose only read-only controls, allow for horizontal-scrolling, make changes to the alignment; make changes to some geometrical sizes, and so on. The controls in a screen also follow similar organizational patterns. However, the controls may have control specific properties. For example, if you were to look at the properties of Email you may get to choose a default e-mail editor; choosing the Headshot may allow you to adjust how it may accommodated on the page by letting you choose its stretch as shown:
[ 102 ]
Chapter 4
Displaying the screen
Most of the work is done by LightSwitch, namely, the data binding to these visual elements and all that is needed is to run the program. 1. Click on NewHire project in Solution Explorer and click on F5. The project builds, a blank screen appears followed by a Loading… message and a little later the CreateNewSalesman window is displayed as shown. This page is served by the LightSwitch Server NewHire which you will find in the control tray at the bottom of the screen (you can, if you need to, stop the screen from the LightSwitch server icon in the control tray). Note however, the Windows Security pops up a modal window (this did not happen in Beta 1 and there has been many discussions related to this behavior in the forum, see: http://social.msdn.microsoft.com/Forums/ en-US/lightswitchgeneral/thread/cb543510-fe9e-4da9941c-44c470ffbce5. It is interesting to note that although the program is launched with administrative privileges, the IDE does not recognize and comes up with this screen. The procedure in this book is to just enter the administrator's credentials (the computer name is Hodentek3, and in your case it could be different). This note is irrelevant in the case of RTM.
The Screen Command Bar with Save and Refresh buttons; the CreateNewSalesman vertical stack of controls and the Menu displaying the CreateNewSalesman screen as one of its Tasks, are all seen. In addition, the Design Screen control element is also displayed, which can be clicked to make custom changes to the screen. We will see this customization later. The Save button must be clicked after the data entry if you want the data to persist. The Refresh button refreshes the screen.
[ 103 ]
Screens in VSLS application
There is only one screen in the project and therefore you see only one screen in the Menu which is a screen navigation element.
When you click on any clear region of the Create New Salesman screen, the First Name control is highlighted and you can start entering the information in the same way you would enter information in a windows form. Because we chose all entities to be optional you may skip elements if you want to. 2. Enter the data you want to populate the Salesman entity and click on Save in the Screen Command Bar.
[ 104 ]
Chapter 4
In the example here, the data in the following will be inserted into the Salesman entity. First Name
Last Name
Address
Hire Date
Birth Date
Email
Phone Number
Starting Salary
Headshot*
John
Doe
1 Cypress Ave.,
Jan 22, 1990
Dec 21, 1960
[email protected]
609-555-9999
$40,000
C:\Users\jay \Desktop\ LightSwitchBook
Edison, NJ 08550
Mary
Doe
2 Columbia Ave., Washington D.C
\Chapter04\ man2.png Mar 25, 2005
Mar 22, 1965
[email protected]
202-999-5555
$50,000
C:\Users\jay \Desktop\ LightSwitchBook\ Chapter04\ woman2.png
Images used here are taken from: http://www.free-clipart-pictures.net/beach_clipart.html
There are two options to enter data, either to enter the date directly, or using the Calendar control. It's almost free-form input and you can type in January 22, 1990 or, even 1/22/1990. The display will be in conformity of the location (in USA) but will appear as 1/22/1990. Even if you make a mistake of the locale and enter 22/1/1990 (as in Japanese language entries) it will correct itself (that's smart!). Of course, you can click on the Calendar icon and make your entries. To enter the date using the Calendar control, click on the Calendar icon to bring up the Calendar as shown where you can use the GUI to enter the date.
3. Next when you come to entering email you will get a window displayed bracketing the entry in red if you just stop after typing in jdoe.
[ 105 ]
Screens in VSLS application
You will immediately see something wrong with the data you entered. The star at the beginning of CreateNewSaleman tab has turned red and there is a red rectangle covering jdoe. Also, there is a validation message. You would get a more detailed message if you were to click on the indicated position. Although, you did not violate the underlying data type (string) you violated the Microsoft LightSwitch specific data type. This is a nice feature that ensures correct data entry. The next image is displayed when you want to find the details and you will know that you need to enter the full e-mail address to proceed further. You can also provision a default value for the e-mail address.
After entering the e-mail address, you will be entering the telephone number and when you come to this control you can enter the phone number and formatting mistakes you make (entering, for example, 609-2751205 will be correctly displayed as (609)-275-1205) will be automatically corrected. Also you may click on the down handle ↓and a data entry screen will be displayed as shown.
Note however, that the display may correctly show (as in the case of entering 609-2751205) but when it comes to saving, it may throw up an error. Always check your entry and make sure it is correct.
For John Doe's number in the US, you would enter as shown in the next screenshot. The following entries will be made; Country Code: 1; Area Code: 609; Local Number: 555-9999; and no entry for Extension.
[ 106 ]
Chapter 4
The Country Code is optional and defaults to the locale and the extension will be added to the telephone number after a # sign. Also note that while entering the number validation errors may show up that will disappear after you complete the entry. When you leave this control after entering these, you will go the next entry point, the Currency. Depending on the locale which is default US, the currency symbol will be added to the number you type in. Also formatting will be added. For example, if you type in 40000, it will be displayed as $40,000.00. While entering the image information you will have the assistance of GUI which helps in loading the image from your file location. For this you hit the → green arrow key indicated by the tool tip text 'Load Image' which opens up a dialog which allows you to browse your file system to find the image. If you need to remove a loaded image you can click on the X icon next to it. When you choose the image with PNG or JPG extensions (in this case, the image of PNG extension) and close the dialog—the image will be added to the screen. As to the size of the image, you may have to work on the available size of the image and the image properties so that you can create an aesthetically appealing screen. You must save the data entered, and in case you close the screen without saving, you will get a message to that effect. 4. Click on Save. The data gets saved and the screen tab now shows John – Salesman as shown. You will not get a message that the screen data is saved.
[ 107 ]
Screens in VSLS application
In order to enter the data for Mary Doe, you need to hit the CreateNewSalesman in the Menu on the left-hand side when a new input screen is displayed by the side of the existing tab. However, if you close out and run the program again, you get a single tabbed page for creating a new salesman record. The validation that came up for e-mail will also come up for the other data types as well whenever the data is entered. This is one of the nice features of Microsoft LightSwitch. There may be many other kinds of logic needed in data entry screens besides simple validation. How are they handled? For example, the date of birth can be a restraint, the hire date cannot be later than birth date, and so on. For this, one has to write some code. We will see this in a later chapter. The data that is saved using the screen enters a database file which may be found by entering the following at a command prompt: cd %userprofile%\documents\Visual Studio 2010\Projects\Beta2 \NewHire\NewHire\Bin\data
The database files are: ApplicationDatabase.mdf and ApplicationDatabase_log.
ldf.
In the following section, we will see how the Search Data Screen functions and some of its details.
Search Data Screen
Search is one of the major activities of any business. It's so important that Google relies on it for its very existence. Enterprises resort to this activity on a second-to-second basis for all business activities from HR to Financial. Microsoft LightSwitch realizes the importance of this and has provided a Search Data Screen. For this example, although we can use the data we inserted into the Salesman entity in the previous section, we will use one of the other data sources created in the Nwind project, the NwindData. In the NewHire project, create a data source using the Northwind database on SQL Server Express bringing in the tables Customers, Employees, Orders, OrderDetails, and Products. Here, we follow the steps to create the screen and verify its functionality. 1. Start Microsoft LightSwitch from its shortcut and open the NewHire Project created previously (Chapter 3, Accessing Data from a VSLS Application). As in the previous example, we will be using the same project properties as in the previous section New Data Screen (steps 2 to 4). 2. Right-click on the Screens node and choose to Add Screen…from the dropdown menu. [ 108 ]
Chapter 4
3. In the Add New Screen window displayed, click on Search Data Screen. 4. It is not bound to any data as yet and using the drop-down handle of Search Data you can bind it to one of the sources shown here.
Here, the Customers table is chosen. Click on OK on Add New Screen window.
[ 109 ]
Screens in VSLS application
The SearchCustomers is displayed as shown.
The Screen Content Layout is shown. Note that if you look at the properties of the Data Grid Row in the screen layout you would see that all controls on the Data Grid are read-only, a default for a search screen as you will not be making any modifications. 5. Build the project. Now you are ready to test the functionality. 6. Click on F5 (on the keyboard after highlighting the NewHire project in the IDE) to run the project. The program runs and after a while you will see the Loading… message followed by the display shown next (Hereafter, it is assumed that if the Windows Security login shows up you would enter the required credentials):
[ 110 ]
Chapter 4
The screen shows all the customers in the Northwind database's Customer table. The listing of the customers has the following properties that are very easy to verify: •
The list can be sorted on any column.
•
The columns can be rearranged by clicking on the column header and moving to a new location either to the left or right.
•
The column widths can be changed by dragging the divider between columns.
•
The Customers column items are actively linked and when clicked they bring up the customer details as shown here for customer ALFIKI:
[ 111 ]
Screens in VSLS application
You may close the window for the customer ALFKI by hitting the X on the tabbed page. The reason the link exists is because if you look at the ID property of the Customer table—you will see the following screenshot displayed showing that it is a link.
Testing the functionality
Using the Search button, you can search the database after which you can use the hyperlinked element to get the details of the searched item. 1. Enter Madrid in the Search box at the top of the screen box and click on the search icon. 2. After some processing, the following window is displayed by the program.
[ 112 ]
Chapter 4
To get back to the original screen, click on the close (X) icon in the search box. 3. Verify that you can search anywhere (any field) in the database.
Can you add or modify the data in the Search Data Screen?
As reviewed in the previous section, we can search the screen very easily. Usually, Search Data Screens are not used for adding data. But can we modify the data in a VSLS application–typically add, update, delete, and so on. This is indeed possible by adding appropriate buttons to the Data Grid control that displays the search data. In order to demonstrate how this could be done, we will start off with the SearchCustomers screen: 1. Expand the Command Bar node under the DataGrid. In the expanded list click on the + sign to display another drop-down list as shown:
2. Choose any of the buttons. Here AddNew and AddAndEditNew are chosen because we are going to look at Add functionality only. The Screen Layout is modified as shown displaying the new buttons:
[ 113 ]
Screens in VSLS application
3. Click on F5 to run the program. The screen is displayed as shown after some processing.
Note that + and +… buttons have been added to the SearchCustomers screen which enables you to add a new customer into the data grid row directly or using a data entry form. 4. Click +… button. 5. A data entry form for entering Customer information is displayed as shown. This form will be empty before any data is added. The required columns are shown in bold, this means you must enter data (to reduce the size of the graphic, several fields are omitted in the screenshot).
6. Fill in the details as shown (only required data is entered) and click on OK. 7. The data you added enters the displayed screen. 8. Click on Refresh in the SearchCustomers screen. This brings up the Unsaved Changes message box giving you an opportunity to either save the changes or discard them. 9. Click on Yes to save the data. 10. The data gets saved to the database, in this case the Northwind | Customer table on SQL server Express 2008 as shown by the SELECT query in the SQL Server Management Studio. [ 114 ]
Chapter 4
The next time you refresh the data in the search data screen, the new data appears in its correct sorted position. If you choose Add instead of Add… button, you will not get the data grid but you can enter the data to the row of the grid directly. In Beta 2, there appears to be a bug. The last row gets opened for data entry, but you are prevented from entering the data.
Although this looks like magic, the DataGrid screen in the most recent versions of Visual Studio had this functionality of adding buttons for adding, updating, and modifying data. It has become so much simpler in LightSwitch. While entering data what if there is already an entry with the same CustomerID? The LightSwitch IDE clearly flags it as a validation error as shown here:
List and Details screen
We have seen the usage of the Search Screen and New Data Screen for entering data into the entities. We will be learning about editing data in the entities using Edit Data Screen in the coming chapters. Here, we will consider the other important screen templates: the Details Screen, and the List and Details screen templates. These templates are accessed in the same way as other screen templates studied earlier.
[ 115 ]
Screens in VSLS application
The Details Screen is different from other screens as it is not displayed independently in the navigation menu by itself but is launched from the other screens. The Details screen shows a single entity and its children, if any. The List and Details screen displays a list and for the chosen item in the list displays its details. Let us say, if a product in a product list is chosen, the details screen shows the details of the product. In order to see how the screen works, follow these steps: 1. Create a project and bring in Orders, Products and Order Details entities from the Northwind database on SQL Server Express. These tables (entities) are related as discussed in the chapter on entities. 2. Create a screen using the List and Details template and when you click on the handle for screen data you will see the three tables. When you pick NorthwindData.Products as the data source you will see the drop-down list shown here. The Product Details are added by default, but you can choose to add the Product OrderDetails by choosing the checkbox:
The corresponding Screen layout if you choose the default is as shown here.
[ 116 ]
Chapter 4
This screen in the display would show a list of products in one column and the details of the products in the other column. However, when you include the Product Order Details (by placing a check mark in the checkbox), then the List and Details screen will also display related information about Order Details for any chosen product in the Product List. The screen layout (ProductsListDetail1) will be as shown.
This in the display would show a list of products; a product detail for a product chosen in the Product list and also an Order detail for the Product chosen. Please download this project and review the above.
Creating a screen from scratch
Although you can design a screen by just using the Add Screen… menu item and then binding it to the data source, you could start with an empty screen and design as you go. One of the reasons for this could be that you may need only a group of controls; a client may like a different layout arrangement and so on.
Create an unbound Search Data Screen
In the following steps, we will design a Search Data Screen type screen which was described earlier. In the same project NewHire, we create a new screen, NewSearch for searching the data. 1. Start Microsoft LightSwitch from its shortcut and open the NewHire Project created previously. 2. Click Add Screen… in the Solution Explorer. 3. Choose the Search Data Screen and provide the name NewSearch.
[ 117 ]
Screens in VSLS application
The screen name should be a valid identifier. It cannot be the same name as the entity. Screen name should be just one word with no white space. A red underline indicates an invalid identifier.
4. Accept the default value none in the Screen Data field and click on OK. 5. The NewHire Designer* window is displayed with just the controls (Save, Refresh and Close) for an as yet unbound datasource. The NewSearch screen is added to the Screens node of the project as shown. 6. The Screen Content Layout contains the minimal default components which gives us a free canvas to place the controls.
Add a group
We will add group which will have an AutoCompleteBox. The AutoCompleteBox is a new addition in Beta 2 and a replacement for the Combo-box in Beta1. 1. Click Rows Layout and Add Group. By default it adds a Group as shown.
2. Click on the drop-down of the Group and change it to Modal as shown in the next image.
[ 118 ]
Chapter 4
Add a data item
We will add a data item for this group. This data comes from the entity. 1. Click on Add Data Item from the screen menu while you are on the Group (Group is highlighted) you created. 2. The Add Data Item is displayed. 3. There are three main options and we could add any of them. We will look at other options later in the book. Here we will pick the Local Property and for its type we choose the Salesman from the drop-down and for the name choose to keep the default Property1. Property1 gets its data from the entity. Click on OK. You get a warning in red if you try to leave this empty or choose an invalid entry.
[ 119 ]
Screens in VSLS application
4. This adds all the fields of the Property1 to the designer as shown.
Add an AutoCompleteBox
In the following, we add an AutoCompleteBox control which provides the functionality of a combo-box. 1. Now click on the plus (+) sign directly below the Modal Window to display the following drop-down list.
2. Choose Property1.
[ 120 ]
Chapter 4
3. The Screen Layout changes as shown in the next image.
4. Drag and drop Property1 from the left side of the Screen Layout and drop it just below the Modal Window as shown.
5. The Screen Layout changes to the image shown here.
[ 121 ]
Screens in VSLS application
6. Change Property1 to Rows Layout using the drop-down handle as shown choosing it from the drop-down.
The Screen Layout changes are as shown in the following image:
[ 122 ]
Chapter 4
What you have achieved so far is to arrange an AutoCompleteBox and a Rows Layout bound to the entity inside a group. 7. Make sure you highlight and review the properties of the AutoCompleteBox. Also make sure both the RowsLayout and the AutoCompleteBox are bound to the entity.
Display and test combo-box
Let us see how this screen appears when displayed to review what we have accomplished so far. 1. Click on F5 to run the program and click NewSearch screen in the menu. The screen will appear with Group control on it. 2. Click on the Group control. 3. The Contents of the group are displayed as shown here:
4. Click on the drop-down handle for Property1.
[ 123 ]
Screens in VSLS application
5. After some processing the following is displayed.
As explained earlier the FirstName in the Salesman entity are John and Mary. However if you need to make LastName in the search all you need to do is to change the first field in the Salesman entity to LastName instead of FirstName as shown here. This can be done by holding down on LastName with the mouse and pushing it up to replace FirstName (FirstName will now appear below LastName).
Another way to replace the default of Summary is to choose the item to be searched in the Summary property of the Salesman entity as shown.
[ 124 ]
Chapter 4
1. Choose Mary or John. Here Mary is chosen. 2. The details of Mary are populated as shown.
[ 125 ]
Screens in VSLS application
The clear and browse icons should not really show in this view. Probably they will not show in the production version.
Export to Excel functionality
Microsoft LightSwitch has the built-in functionality to export its data records if available on a screen to Microsoft Excel 2010/MS Excel 2007. This is a very useful activity because once the data is brought into Excel it can be used in a variety of ways such as, •
Create reports using SSRS
•
Integrate with other data sources using SSIS
•
Export it as XML files, ASCII files so on.
•
Create charts and use pivot tables so on.
•
Export data from SQL Azure
VSLS Application can be integrated with other Office products using COM automation. For an example of how this is done follow this link here; http:// blogs.msdn.com/b/bethmassi/archive/2010/09/10/using-microsoft-wordto-create-reports-for-lightswitch-or-silverlight.aspx.
The author highly recommends his books on SSIS (https://www.packtpub. com/sql-server-integration-services-visual-studio-2005/book), SSRS; (https://www.packtpub.com/learning-sql-server-2008-reportingservices/book), SQL Azure; (https://www.packtpub.com/microsoft-sqlazure-enterprise-application-development/book) and the links to many of the articles for charting and use of pivot tables on his blog, http://hodentek. blogspot.com wherein all of the above are described in minute detail. Exporting to Excel in Microsoft LightSwitch requires just one click on the Export to Excel button on the screen. Nothing can be simpler than this! 1. Click on F5 after highlighting the NewHire Project and bring up the Search Customers screen as shown.
[ 126 ]
Chapter 4
2. The Search Customers screen is displayed with all the rows of data as shown (only a part of the screen is shown here as the full screen is available in the previous section). 3. Click the Export to Excel button on this screen. That is all there is to it. After all the processing is completed you will be led directly to the exported data in an Excel file as shown here (only a portion is cropped from the original). There will be no other messages. If Excel is not available it will return an error message.
Of course, the hyperlink information in the CustomerID column is not a part of the export. By default it is Sheet 1 of the workbook file renamed Customers. Some of the other features of this functionality you may want to note are: •
If you do not see the Export to Excel button on a screen then it means that data is not meant to be exported. You do not see this control if it is not a desktop application.
•
Since we have used the default application type, access to local files to read/ write is supported and hence you are able to export to local file system. If you choose the type that does not allow access to local files then exporting to excel is not available.
[ 127 ]
Screens in VSLS application
•
You can disable the export to excel functionality if you choose to and in which case the Export to Excel button will be absent on the screen.
Disabling Export to Excel
You need to get to the Screen Content Layout to carry out this activity. 1. Click Search Customers in the NewHire project. 2. The NewHire Designer is displayed displaying the Screen Content Layout. 3. Scroll down the Properties of the DataGrid so that the Disable exporting data to Excel checkbox appears as shown.
4. Place a check mark for Disable exporting data to Excel. 5. Click on F5 to run the application and verify that the Export to Excel button is not showing.
Customizing a screen at runtime
This is an interesting feature of Microsoft LightSwitch and is of great value to developers. You might have observed in the displayed screen a control at the very top right–the Design Screen, shown in the next image. This can be clicked to open an interface to customize the screen. After customizing, if you choose to save and return to the displayed screen you will notice the changes you have made are displayed. That means you can modify a screen both at design time as well as while the application is still running. For the developers this is a great feature as they do not have stop the program; make changes to the design; run the program to check and so on. [ 128 ]
Chapter 4
1. Click on F5 and display the Search Customers screen. 2. Click Design Screen button at the top-right corner of the screen. You may need to toggle it if it is not displayed. The Customization Mode window is displayed as shown:
This window displays the tree structure of the screen layout on the left and the top- right pane displays a preview of the screen when displayed; the bottom-right pane shows the properties of the element chosen on the left (presently SearchCustomers). It also has Save and Cancel buttons. In the following step you will change some properties and the save the changes. 1. Click on CompanyName label on the left and change it to My Company (Display Name:) in its Properties. Change Customer ID to display My Customer. Click on Save.
[ 129 ]
Screens in VSLS application
2. The display in the browser immediately changes as shown here:
The changes are persisted and when you run the program again, for example, these changes will be displayed. They persist in the exported file as well.
We saw only changes made to a label in the tree structure. According to documentation you can make the following changes. •
Add a button to the screen
•
Add a group to the screen
•
Delete an item from the screen
•
Move the fields on the screen
•
Reset the layout of fields on the screen to their default value
•
Change the labels for items on the screen
•
Change the controls for items on the screen
[ 130 ]
Chapter 4
You can also use the icons to the left of the Screen Content Layout tree in the Customization Mode window to make the changes. Some of the above changes made are shown in the next image where many of the columns were removed by using the Delete icon on the left of the Screen Content Layout tree. The link My Customer was de-linked and so on.
The Customization mode is interactive and the Preview on the right is updated as changes are made in the Screen layout. However, Customization mode does not have the full functionality of the designer.
[ 131 ]
Screens in VSLS application
Summary
This chapter introduced Screens in Microsoft LightSwitch IDE and described the differences between these screens and forms (equivalents of screens) in Visual Studio Windows programs. Two of the screens, one that takes care of entering new data and the other used for searching a database entity were described in detail. Modifying the search screen for data modification and designing a screen starting from scratch were also described in detail. Microsoft LightSwitch connection to Office applications via Microsoft Excel and screen modification while the application is running using Customization Mode were also described. The interaction of screens with data to enforce business rules, altering the screens with code and so on, are described in Chapter 7, Writing Code in Microsoft LightSwitch. In the next chapter, we will look at data sources that have multiple entities as well as using some of the other business activity related screens.
References
1. Screens as part of the Presentation tier, from which the book has derived much of its discussion is described here: http://blogs.msdn.com/b/lightswitch/archive/2010/08/09/theanatomy-of-a-lightswitch-application-series-part-2-thepresentation-tier.aspx.
2. Learn from "How to…" videos with no video longer than 30 minutes here: http://msdn.microsoft.com/en-us/lightswitch/gg604823.
3. For Bug fixes in Beta 2, you may want to check out here: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/8afbdd52-34bc-4958-813c-fa9f10795dd8.
4. For explanation for AllowMultipleInstances property, check: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/ff06ff65-60cc-4a8b-b3a3-85c9718c0d98.
[ 132 ]
Chapter 4
5. For more information on Beta 1 and Beta 2 incompatibility: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/6e7a9dbd-60cc-4aa1-9574-9e5ad5498a54.
6. Download the LightSwitch Extensions cookbook if you want to change the features not available out-of-the box. Some examples are also shown in Chapter 10, Troubleshooting, Debugging, Custom Controls and Extensions: http://blogs.msdn.com/b/lightswitch/archive/2011/03/16/ lightswitch-beta-2-extensibility-cookbook.aspx.
[ 133 ]
Working with Entities Data is at the heart of Microsoft LightSwitch applications. If there is no data then there is nothing much to do with LightSwitch. The data as we saw in the previous chapter can be created within the IDE or, it may reside in an external source. Microsoft LightSwitch uses Microsoft's Entity Framework in the background although it connects to data sources which at present are limited to relational data; from WCF RIA Services or SharePoint lists.
Entities in Microsoft LightSwitch
Although LightSwitch depends on the Entity Framework for its data, it does not support importing entity models created outside of the LightSwitch IDE (using the EDMX file created in Visual Studio using the ADO.NET entity model support, see for example, http://www.packtpub.com/article/data-access-with-ado-dotnet-data-services). In LightSwitch, the whole process of data mapping takes place via the IDE and generates the entity model when a data is attached or created in the IDE. This is then embedded in the LSML file we described in Chapter 2, Microsoft LightSwitch IDE and Architecture. It is possible that support for externally created entities may be provided in future versions. This chapter covers all aspects of entities used in VSLS projects. Entities consist of fields some of which are no different from their counterparts in SQL Servers and some are specific to the program. This chapter covers the full range of data types used in defining entities. Entity fields once defined, can also be modified and can even be deleted. The LightSwitch IDE also allows adding fields. It is seldom that a single entity represents the whole business and it may require two or more entities. Microsoft LightSwitch supports defining relationships between and modifying them as well as recognizing existing relationships in external sources.
Working with Entities
Topics to be covered in this chapter are: •
Entity Designer
•
Creating data entities: add, delete, and modify fields
•
Adding a computed field
•
Entity field validation
•
How are code pages organized in the project?
•
Relationships between entities in LightSwitch
•
Relationship between tables (entities) from an attached source
This chapter should help the reader to work with entities with confidence and test data validation skills.
Entity Designer
Everything you need to do with entities can be carried out in the Entity Designer. Entity Designer is the window (or panel) in which you display the entities, be it from an externally attached data source or, one created using the Create new table in the project. When you create a table in a VSLS application, the Entity Designer menu will be displayed in the Project Designer panel as shown.
However, when you highlight an entity in a data source from an externally attached database, the menu item for creating a New Table will be disabled. The Entity Designer has menu items which can add a relationship; add a computed property; add a query; add a screen that utilizes the entity; add a new table; attach to an external data source; and allow you to write code from the Entity Designer. After creating new items using the above, you can then modify them by accessing the item you created, be it a relationship, a computed property, or any other item. In this chapter, we will look at all of these in more detail. [ 136 ]
Chapter 5
The Microsoft Visual Studio suite of products has the facility to carry out the same task in a number of ways. Microsoft LightSwitch is no exception. For example, once an entity is created you could also access the fields or the entity itself to carry out some of the above tasks without using the menu. Solution Explorer is another place where you can carry out some of the above tasks as we have seen in earlier chapters. When an entity is created in the Microsoft LightSwitch IDE, a default entity is created with just one field, the Id field of type Int32 which cannot be null (the required property is checked) but is displayed by default. You can change this property if you do not want to display it. Another change you can make is to add a description. Using the link in the entity you can add more properties (fields or, the same as columns of a table in a relational database). For each of the properties you add you must specify a data type by choosing one of the available types and also indicate whether it is a required property or not. In Chapter 4, Screens in VSLS Application, this is how the Salesman entity was created in the NewHire Project. Entities usually have a collection of fields of various data types as in the Salesman entity. Each user-created property has a Properties panel which has the following three nodes: •
General
•
Appearance
•
Validation
In the General node, you find properties such as Name, Is Searchable, Is Computed, and what to show when no value is provided for the property you have accessed. If you want the property to be the one that is computed you spawn the Edit Method by using the Is Computed choice that opens up a text panel where you can write appropriate code. We will learn more about it later in the chapter. In this node, you can also set up a Choice List for a field which may have a few choices to choose from. In Appearance, you can change the way entity fields are displayed, add a description of the field, or choose to display it or not on a screen (for example, you may want to hide the Id property as it is not necessary to show it). In some cases, you can have additional information as to the format, as in the case of Phone and Date, Microsoft LightSwitch specific extension data types. In the LightSwitch IDE, the data types and all property values are saved in the Settings file and these can be exported using (Tools | Import and Export Settings…) to an XML file with the date stamp as in Exported-2011-08-23.vssettings . In Beta 2 it was named slightly differently as in CurrentSettings-2011-05-28.vssettings. Validation is the node in which you set up the validation rules. We will learn more about it in a later section of the chapter. [ 137 ]
Working with Entities
Creating data entities: adding, deleting, and modifying fields
In Chapter 3, Accessing Data from a VSLS Application details of creating a data entity were described in detail. We also learnt how fields can be added, rearranged, modified and deleted. These tasks need nothing more than bringing up a pop-up pick list wherein you select a task. For example, making a right-click on the left-hand side of HireDate in the Salesman entity brings up this pop-up menu where you can choose the task you want to perform.
We have covered some but not all of the entity-related items in earlier chapters. We will cover the field properties that were not covered but are very important while entering data in this chapter.
Choice list
Most businesses have to display choices they have for the customer. For example, a business may sell a variety of products defined by the product type. An employee may be married, single, divorced, and so on. Company personnel may have set of categories such as Manager, Supervisor, and so on. We will illustrate the use of choice list with a simple example: 1. Create a new project NewHire5vb project with the Salesman table as in the previous chapter (alternately use the same project); highlight the Salesman entity in the Solution Explorer and add a new field with the name Sex setting its type to Boolean and making it a required property.
[ 138 ]
Chapter 5
2. Move it up (right-click in the field and choose) and place it below the LastName as shown next:
3. Click on Choice List in the Properties window. 4. The Choice List window is displayed. Add two entries (First, enter in the Value column and then the Display Name Column) as shown next. Add display names as shown; M for Male and F for Female). The link in the previous image gets an additional red delete icon should you choose to delete it for some reason.
When you choose Choice List in the designer you will be accessing the EnumDataTypeAttribute class, see http://msdn.microsoft.com/en-us/ library/gg589479.aspx#Applying
5. Create a screen with the name CreateNewSalesPerson. This will use the entity with the added Sex column.
[ 139 ]
Working with Entities
6. Click on F5 and in the displayed screen click on CreateNewSalesPerson in the navigation menu. Initially, the value Male shows up by default and when you click on the drop-down handle, the screen is displayed as shown.
Note that the required fields are highlighted in the screen. Now, when we enter information for a sales person we can choose to include whether the person is male or female using the drop-down choice. Also note that Boolean false is the default.
Setting up a default e-mail domain
EmailAddress is a Microsoft LightSwitch specific data type. It makes perfect business sense to set up a default domain in case a domain is not specified while entering the data. This is very useful and reduces finger work for the person entering the intranet data. Microsoft LightSwitch makes it very easy to add a default. We will add a domian mysorian for the Email field of Salesman entity: 1. Click on the Email field (of type EmailAddress) and type in mysorian.com in the textbox below Default Email Domain in its Properties window in the General node. Any other domain of your choice is also suitable. Also note that you can set other properties as well for the e-mail. In an Intranet situation, probably searching by e-mail may not be necessary.
[ 140 ]
Chapter 5
2. Build the project and Click on F5. 3. In the CreateNewSalesPerson screen, observe that as soon as you finish typing in jay in the Email field and leave that field by stepping out, @ mysorian.com will be immediately added. This does not depend on whether or not the e-mail field is required. E-mail can be the first thing you enter because all fields are set to Not Required.
4. Enter a few more fields such as First Name, Last Name, Sex, and so on. Hit Save menu item to save all screen data. 5. The data gets saved. Sometimes you may get the error shown in the next image. This is because you might have made some changes and did not build the project. In some cases, use Clean and Rebuild from the project node. In this case exit out of the browser, build the project, and run the screen again.
6. Now close the screen and create a new Search Data Screen called Search Sales Person with the Salesman as the entity for the screen.
[ 141 ]
Working with Entities
7. Click on F5. Observe that e-mail has correctly entered (Email field was moved right next to LastName from its default position by dragging).
Entering Money field
In entering a value in the money field to display a monetary value, Microsoft LightSwitch offers excellent support by LightSwitch specific data type, Money. The attributes of Money can be set in the Properties window. When a monetary value is displayed one often sees $1500, $1500.75, or $1,500.75. Also, depending on the locale the symbol used for the currency can change. If you need to display one, more, or all properties of money representation, make use of the information in the next table. A value of 1500.75 will be displayed variously depending on your choices. Property
Description
Example (highlighted part)
Currency Symbol
Symbol of monetary value
$1,500.75
Decimal digits
Decimal digits to display
$1,500.75
Is Formatted
Formatted with all attributes
$1,500.75
Is Grouped
Display digit grouping
$1,500.75
Symbol Mode
To select whether or not display currency symbol, choose the drop-down
Choices are: No Currency Symbol: 1,500.75 Currency symbol: $1,500.75 ISO Currency Symbol: USD1,500.75
[ 142 ]
Chapter 5
These changes are only possible in the design mode (not in Customization Mode).
Setting up Phone Properties (formatting)
Telephone number is another Microsoft LightSwitch extension item that can take different formats. This has become even more complicated because of VOIP and the increasing use of mobile phones. Also, the local dialing requirement may vary from country to country. The international Telephone Calling Code (which is the same as International Direct Dialing (IDD)) is shown as under (sometimes mobile numbers do not use area code). Review the link at: http://en.wikipedia.org/wiki/ International_call for more information. International Access Code - Country Code - Area Code - Local Subscriber Number
When you click on the Phone field of an entity, you can access the Phone Properties window as shown (look in the General section): 1. Click on the Phone field of the Salesman entity in NewHire5VB project to display the Phone properties as shown.
2. Click on Phone Number Formats link.
[ 143 ]
Working with Entities
3. The Phone Number Formats window is displayed where the format to display and to validate are configured. Here, you can test and set your formatting.
The formats supported are as explained in the above window where a number entered without breaks validates with format and displays with the format as shown in the previous screenshot.
Adding a computed field
Often it may be required to display information in an entity which may be a combination of other fields in the entity. One common example is to display the full name (computed property is a string) of a person when the fields in the entity are last name and first name. In the following example, we will use the NewHire5VB project with the Salesman entity. To this entity, we will add a computed field. We will add a new field which is a combination of the FirstName and LastName.
[ 144 ]
Chapter 5
1. Click on and add an item FullName as shown:
This is the Name of the computed property we will be adding. 2. Click on the area left of FullName to bring up its Properties as shown:
3. Place a check mark for the Is Computed check box.
[ 145 ]
Working with Entities
The Properties window is updated as shown. A new link Edit Method will be generated. Note that it is not searchable any more.
Also, the FullName in the entity gets a new icon added as shown indicating that it is a computed property. The tool tip shows that this is not stored in the database but is used only for display and business logic. For the same reason, you can neither make it a required field nor sort using this field.
The computed property only affects the business logic. Assuming we had a screen, for example a Search Data Screen using the entity without this computed property, adding this property will not affect the screen which was based on an entity without this property. The screens which used the entity without this computer property will not show this in display. You have to recreate the screens with the entity containing the computed property.
Computed value using the Edit Method
We will now create the method that computes the computed field and makes it available for screens such as the previous to display the computed value. 1. In the FullName property window shown earlier click on the Edit Method. Read the tool-tip message, "Code to calculate the value of the computed property". The code editor window brings up Salesman.vb code behind the entity shown next. [ 146 ]
Chapter 5 Namespace LightSwitchApplication Public Class Salesman Private Sub FullName_Compute(ByRef result As String) ' Set result to the desired field value End Sub End Class End Namespace
The FullName_Compute procedure when executed produces a result. The annotation in green is very helpful, the user is asked to set the result to a desired field value. This means you need to equate result to a combination of FirstName and LastName field names of the entity which is coded as shown. Make sure you use the intellisense drop-down in the code editor as shown.
The line of code that will be added to display the FullName is shown here. result = FirstName + " " + LastName
Now let us check the SalesmanSearch screen to verify that the computed value is displayed.
[ 147 ]
Working with Entities
2. Bring up the SearchSalesmanFullName (you need to create a new search screen which uses the entity with the added computed field, here called as SearchSalesmanFullName) screen as shown clicking on F5.
Now the Summary property is correctly reflected in the screen to display the Full_Name field of the entity in the SearchSalesman screen. What if one of FirstName or LastName is a required field (presently both are not required fields)? In this case, the Salesman column will only show the required field (say, LastName) if you did not enter a value for the other field (FirstName). Of course, we can clean up the screen by removing the LastName in the above screen. Note that the Export to Excel button exports the above screen. Some attributes of FullName can be modified in Design Screen control which allows you to make changes while the application is running. There are many other examples of computed property such as the cost (computed property is of type money) of an object computed from the fields that represent the number of articles sold and the price of the article or conversion schemes converting from one system of units to another, or calculating quantities using the existing field values. This next image shows the Edit Method for each of the added fields in an entity representing a rectangular box with dimensions length, width, and height to display other computed items such as area, volume, of machinable parcel dimension (used by USPS). Namespace LightSwitchApplication Public Class PostalParcel Private Sub BaseArea_Compute(ByRef result As String) ' Set result to the desired field value result = Length * Width End Sub Private Sub Volume_Compute(ByRef result As String) ' Set result to the desired field value result = BaseArea * Height [ 148 ]
Chapter 5 'alternately result=Length*width*Height End Sub Private Sub MachinableParcel_Compute(ByRef result As String) ' Set result to the desired field value result = Length + 2 * (Width + Height) End Sub End Class End Namespace
This is displayed in a New Data Screen called Configure Box as shown. As you begin to add the dimensions of the box, the calculated values begin to appear in the labels at the bottom of the screen.
In the above example, you could also bring in the conversion factors based on the locale (British or Metric). The computed field(s) you add depends on the nature of your data and your requirements and are not limited to a certain data type. Also, note that although the dimensions are displayed in textboxes, the computed properties are displayed as labels.
Entity field validation
Data entry validation is an essential feature of enterprise business as it is at the core of having reliable, correct data in a format that is standardized across the business. In the early days of computer-related data entries, which used a more or less free format entry of data, data corruption was rampant. Depending on the training and knowledge of the person entering data there was wide variation. Simple date entry, for example, can have so many variants that it is impossible for the data not to be corrupted during manual entry even assuming the entry was made in a single geographical location.
[ 149 ]
Working with Entities
Users of Microsoft Access and Microsoft Excel are quite conversant with validation in these products that have choice wizards to help in establishing validation of the entered data. Visual Studio (remember the validation controls) from the very beginning attacked this problem with varying degrees of success in UI design, but in Microsoft LightSwitch validation has really reached a high degree of maturity and seems to have reached its peak in abstraction. Validation works because the entries are checked against validation rules. First of all, validation rules can be established for all core objects like screens, entities, and the Data Service. This means validation can be made at the client level, server level, or both. The validation code is shared (some of them) by both the client and server and finds itself in the Common folder of the project. The validation rules for entities validate entity properties and entities. Each entity property can specify more than one rule and these rules are all checked when the entity is changed and are accessible from the entity designer. Validation of screens works the same way, the properties and the screen data can both be covered by validation rules. DataService validation rules come into play just before data is committed to storage and therefore runs only on the server. As to types of validation there are two—one for which you do not need to write any code as it is predefined and checked automatically. The other is code based (VB or C#), which must be coded by a developer based on the line of business. This is often called the business logic (for example, no employee can work for more than 40 hours a week which assumes a time sheet to be present for all workers).
Built-in validation
The validation rules available in Microsoft LightSwitch are shown in the following table taken from Microsoft documentation and these depend on the data type as shown in the Applies to column. The constraint (validation rule) is checked and if it is violated during data entry it is flagged with a conspicuous message. Validation Rule
Description
Applies to
Is Required
Specifies whether the field must have a value. If a value is required, select this checkbox. Checks the presence of a field.
Binary, Boolean, DateTime, Decimal, Double, EmailAddress, Image, Int16, Int32, Int64, Money, PhoneNumber, String
Maximum Length
Specifies the maximum length of the field in characters. Checks the length of a field.
Binary, EmailAddress, Image, PhoneNumber, String
[ 150 ]
Chapter 5
Validation Rule
Description
Applies to
Maximum Value
Specifies the maximum value of the field.
DateTime, Decimal, Double, Int16, Int32, Int64, Money
Minimum Value
Specifies the minimum value of the field.
DateTime, Decimal, Double, Int16, Int32, Int64, Money
Precision
Specifies the maximum number of digits for the value of the field. This includes digits both left of and right of the decimal point.
Decimal, Money
Scale
Specifies the maximum number of digits to the right of the decimal point for the value of the field.
Decimal, Money
These validation rules can be set in the Validation node of the entity field's property window as shown here in for data type String. The validation rules (constraints) are declared in the property of the entity. One only needs to look at the Properties window for other field types.
[ 151 ]
Working with Entities
This next one shows the Validation node property in the Properties window for data type Money.
The values shown for the maximum string length (255) is a default. Others with the same 255 defaults are address, e-mail, and phone. 1. For the FirstName field of Salesman entity, set the maximum length of string to 6; for the Starting Salary set a value of 0 and for the Email field a value of 5. 2. Click on F5 and bring up the CreateNewSalesPerson screen. 3. For FirstName field enter Clementine (10 letters) and for the Email field enter Clementine. 4. The screen changes to the one shown in the next image.
[ 152 ]
Chapter 5
Because our entry violated the validation rules, the errors were generated. It is interesting to note that the FullName does not care for the violation of underlying data. 5. Continue and enter -6000 for the Starting Salary. 6. The display appears as shown in the next screenshot:
The error messages are unambiguous. The entries violated all the rules. Note that immediately below the tab CreateNewSalesmanFullName, the error summary list is produced which can be expanded by clicking on the handle to view the details. 7. Click on Save in the screen menu at the top. [ 153 ]
Working with Entities
8. You get an "Unable to save data" error asking you to correct the data entry and try to save again. These changes made to entities for data validation get persisted to the database as shown here. In order to get this view, the Application data files were copied over to a location where they can be attached to another server.
Unique Index
In Beta 2, a new element was introduced in the General tab of the Properties window of the entity fields, which is: Include in Unique Index (see section on Declarative Unique Constraints at http://msdn.microsoft.com/en-us/ lightswitch/gg699332). This is also true in the RTM. When you choose this option for a number of fields then those fields as a combination should have to be unique as seen in this SalesWoman example. In this example there are two fields FirstName and LastName for both of which a check mark was placed on the checkbox for Include in Unique Index and a data entry screen CreateNewSalesWoman was created to test. This is for checking Unique Check Constraint. This error was produced when you attempt to insert the same combination of FirstName and LastName while entering data (Mary Doe, in this case).
[ 154 ]
Chapter 5
This option cannot be applied to Computed fields and fields with data type Image but are supported for the other Microsoft LightSwitch specific data types Email, Phone and Money.
Custom Validation
While the built-in validation is defined declaratively at design time using the property of the entity field one needs to write code for custom validation.
Where to write the code
The Microsoft IDE provides good support through the various events that occur while running an application. The property to any of the fields has a link to the related field entity event code template as seen when you click on this link. In the SalesWoman entity, in the NewHire5VB Project, click on the Email field in the entity designer. 1. In the Properties window of the entity field Email, click on the link Custom Validation. 2. This opens the code page SalesWoman.vb with the following code: Namespace LightSwitchApplication Public Class SalesWoman Private Sub Email_Validate(results As EntityValidationResultsBuilder) ' results.AddPropertyError("") End Sub End Class End Namespace [ 155 ]
Working with Entities
You notice that only one of the properties AddPropertyError (String) is used in the above code and you can use the others shown in the next paragraph as well. The EntityValidationResultsBuilder class taken from the Object Browser has all these members. These can be used in writing the custom code.
Another way to start writing code is to use the entity designer. 3. Click on Email field in the NewHire5VB project's SalesWoman entity designer and click on the Write Code menu item in the entity designer. Click on the handle for Write Code. The drop-down menu shown in the next image is displayed.
[ 156 ]
Chapter 5
This drop-down menu item is a common location for all codes written in Microsoft LightSwitch. 4. Click on Email_Validate in the drop-down under Write Code. 5. This will place your cursor in the place where you need to write code in the Email_Validate method shown earlier. Because we started with the VB.NET template of the Microsoft LightSwitch project our codes will also be in VB.NET. You cannot mix the two languages in the IDE. Here is the same Email_Validate event that is created in a C# project with the same entity as salesman (it is called SharpSalesman entity in a NewHireSharp C# project with all fields set as not required). using Microsoft.LightSwitch; namespace NewHireSharp { public partial class SharpSalesman
partial void Email_Validate(EntityValidationResultsBuilder results) [ 157 ]
Working with Entities { // results.AddPropertyError(""); } } }
After testing for validation, should it fail, you display the error using the AddPropertyError() method.
Custom code
The best practice is to use whatever validation provided in the IDE and write code for something that is not readily available. In this section you will see a simple example of writing custom code for the described validation requirement. Let us say, in the SalesWoman entity of our NewHire5VB project we have the following validation requirement for some of the fields: •
FirstName entered should have its first letter capitalized
•
LastName is a required field with not less than 4 characters
•
The HireDate cannot be less than the BirthDate
Note that the second requirement can be set in the Properties window of LastName. Because we started with all fields not required for SharpSalesman with default values we are writing the code. 1. As described in the previous section, we can highlight each of the fields for which we need to write validation code and access the field's Validate method by either clicking the Custom Validation link or the Write Code drop-down menu. By doing so, all the validate methods will be created in the tabbed page for SalesWoman.vb as shown: Namespace LightSwitchApplication Public Class SalesWoman Private Sub LastName_Validate(results As EntityValidationResultsBuilder) Dim Ln As New String(LastName) If Ln.Length < 4 Then results.AddPropertyError("Must enter a value with not less than 4 characters") End If End Sub Private Sub FirstName_Validate(results As EntityValidationResultsBuilder) [ 158 ]
Chapter 5 Dim fn As New String(FirstName, 0, 0) If Not (RegularExpressions.Regex.IsMatch(fn, "[A-Z]")) Then results.AddPropertyError("First letter should be capitalized") End If End Sub Private Sub HireDate_Validate(results As EntityValidationResultsBuilder) If HireDate < BirthDate Then results.AddPropertyError("You have to be born before you are hired") End If End Sub End Class End Namespace
The FirstName_Validate will test the entered value to verify that it is entered and that the first letter is capitalized. If it fails this test, it will show the validation text shown as an argument for the results.AddPropertyError(). Note that it uses regular expressions pattern to discover the case of the first letter entered. For this code to work, you need to add the following Imports statement at the beginning of the code. Imports System.String Imports System.Text.RegularExpressions.Regex
The LastName_Validate will test the entered value to verify that it is entered (not null) and that its length greater than four characters. Note that it has to first test for the null verification. In order for the Length property to be evaluated for the String you need to Import System.String. The BirthDate_Validate will test for the silly condition (happened in practice in a legacy application) that one has to be born before one can be hired. Note that data corruption is present even these days of data corruption awareness, http://
hodentek.blogspot.com/2011/08/on-errors-and-mistakes-both-public-and. html.
No code was written for Email_Validate specifically.
[ 159 ]
Working with Entities
Test custom code
In order to test the validation code, create a CreateNewSalesWoman1 screen as described previously. The result of inserting values that violate all of the previous validation rules is shown in the next image. There is no difference between built-in validation and custom validation as far as how the validation error messages are concerned. You get a summary at the top of the screen and individual errors at the location they are flagged.
Hovering over the right top edge of the decorated boxes brings up the tool tip message (as shown for BirthDate). Expanding the summary by clicking on the drop-down displays the following:
We will see more validation examples in the chapter on Writing Code in Microsoft LightSwitch.
[ 160 ]
Chapter 5
How are the code pages organized in the project?
In this chapter, we wrote code to carry out Validation and compute a new property from the other existing properties. Now all these code pages are organized under the Common node of the Project as shown here.
Relationships between entities in LightSwitch
In Chapter 3, Accessing Data from a VSLS Application the different kinds of data sources that can be presently used in Microsoft LightSwitch Beta 1 were described. Also, creating a table (Entity) in the LightSwitch IDE was also described. The difference between a table and an entity was described in terms of relational data and business-related data using a model. This difference is best seen when you have multiple tables (entities). The next screenshot shows the relational features of two tables stored in a SQL Server Database. Each table is complete by itself and contains all the related attributes and follows the standard practice of relational data model. The Orders table has everything related to an order and similarly the Customers table has everything related to Customers and there is nothing about Orders in the Customers table. The Orders table does have a field, the CustomerID to identify a customer's order.
[ 161 ]
Working with Entities
Similarly, looking at the Customers table by itself does not give any information about the order. It is the application that makes use of the relational model to extract these relationships by using the SQL language and writing queries.
However, when the same two tables are imported into Microsoft LightSwitch, the program correctly identifies this existing relationships as shown in the NwindData Designer you encountered in Chapter 3 , Accessing Data from a VSLS Application.
[ 162 ]
Chapter 5
Note that at the bottom of the Customer1 (there is a Customer in another data source and hence Customer1) entity, there is a name Orders and its type is OrdersCollection. This is not a data type but it is added by the entity model, the behind-the-scenes model for Microsoft LightSwitch. What this means for practical purposes is that when you create a screen for the Customer1 entity, you could also access all his orders (OrdersCollection). In the Orders entity however, you only see Customer at the bottom as shown and not a CustomerCollection. Similarly, in the Order entity, you know which customer placed the order.
In earlier versions of Microsoft Studio, you had to write code to discover these relationships in order to develop applications. Here it comes with no effort from you. This is big leap in application development made possible by the introduction of the entity model.
[ 163 ]
Working with Entities
The Entity designer shown in the previous screenshot gives you access to know the details about these relationships. Just right click on the line connecting the two entities and choose Edit Relationship… to display the following screenshot:
This relationship aids the navigation from one entity to the other. As shown, a customer can have many orders but the order can only have one customer. Although we chose to edit the relationship, the various controls that can be used to edit are greyed out. This is because it is attached to an existing relational database (the SQL Server Express 2008 in this case). This means any modification you want to make should be made in the database.
Relationships between tables (entities) from an attached source
In the previous section, we saw how LightSwitch recognizes the underlying relationship between tables in an attached Data source. What if such relationships are missing and how do we establish the relationships?
[ 164 ]
Chapter 5
Let us assume that the Customers and Orders tables in the Northwind database have no keys. For example, in the new R2D2 Data source, created using the database into which the Northwind database tables were copied, there are no primary or foreign keys as shown:
Let us now create a data source in NewHire5VB by attaching to the FromSQLXpress database on the R2D2 SQL Server (download details were provided in Chapter 3) shown. Because the FromSQLXpress database tables shown do not have keys, the tables used for the Data source will appear without any relationships as shown here in the LightSwitch IDE.
[ 165 ]
Working with Entities
Because there is no underlying relationship in the attached database, the relationship was not automatically recognized by the IDE (compare this to the earlier case when such relationship existed in the attached database). Now we can establish a relationship between the Customers and Orders tables by clicking the Add Relationship… button (Ctrl+Shift+R). This button adds a relationship for the showing item, in this case Customer1. 1. Click on Add Relationship… in the NewHire5VB Designer*. The Add New Relationship window appears as shown:
The screenshot explains it all. Something needs to be selected for both sides of a relationship because only one table is displayed and the To column of the window is empty.
[ 166 ]
Chapter 5
2. Click on the handle in the To column of the row Name. A drop-down list is displayed as shown next:
There are multiple databases with some having the same table names and the IDE assigns a number to the table. For example, customer comes from NwindData data source and Customer1 comes from R2D2Data data source.
[ 167 ]
Working with Entities
3. Click on Order1. The Add New Relationship window changes to the one shown in the next image:
To proceed further we need to answer the question, Which Properties on Order are shared by Customer? However, we know that a customer can have many orders. We adjust the multiplicity in the relationship by using the appropriate drop-down handles as shown.
[ 168 ]
Chapter 5
Using "many" as the choice we get the following. Note that one-to-one relationships are not supported in LightSwitch.
[ 169 ]
Working with Entities
The error message clearly shows that if the two tables are in the same Datasource (container) one cannot establish a relationship.
What is the workaround?
Let us go back and create another datasource R2D2_2Data containing the Orders table from the FromSQLExpress database.
Now start with Customers entity in R2D2Data and bring up the Add New Relationship window. Use drop-down handles in the window to arrange the relationship as shown (follow same steps as before).
[ 170 ]
Chapter 5
In the bottom table, answer the question by using the drop-down handle for 'Order' and choose CustomerID. Right click on CompanyName and delete to display the following:
[ 171 ]
Working with Entities
Click on OK and now you have established a relationship as shown.
The broken connection between Customer and Order represents that they are in different containers.
How to establish a many-to-many relationship?
You can extend the above procedure to create a many-to-many relationship. Create separate data containers for Orders, Products, Order_Details as shown in this project folder image (only partial view is shown).
[ 172 ]
Chapter 5
Start with Order_Details in R2D2Data_4 and establish a relationship with Orders in R2D2_2Data. Now with Order_Details in R2D2Data_4, establish a relationship with R2D2Data_3 Products. This will establish a many-to-many relationship between Orders and Products as shown in the next screenshot:
Summary
In this section, we reviewed the various aspects of entities used in Microsoft LightSwitch applications or projects. We now know how to create, edit, and update entity properties. We also learnt special properties of great utility in data entry such as the Microsoft specific data types Email, Money and Phone. Creating computed fields; validating entered values using both in-built and custom methods; and creating relationships where more than one entity is present was also studied. We also learnt how to establish one-to-many and many-to-many relationships between entities in different containers. In the next chapter, we will study how to write queries to filter and fine tune the data that we need to display.
[ 173 ]
Working with Entities
References
1. The Anatomy of a LightSwitch Application Part 3 – the Logic Tier: http://ria.feedables.com/story/6410312/The-Anatomy-of-aLightSwitch-Application-Part-3-%EF%BF%BD%E2%82%AC-the-LogicTier
2. Related to data container implication in LightSwitch: http://connect.microsoft.com/VisualStudio/feedback/ details/588113/lightswitch-allow-data-relationships-to-bedefined-within-the-same-container
3. Validating Collections of Entities: http://blogs.msdn.com/b/bethmassi/archive/2010/08/31/ validating-collections-of-entities-sets-of-data-in-lightswitch. aspx
4. Regarding Declarative Unique Constraints: http://msdn.microsoft.com/en-sg/lightswitch/gg699332
5. Difference between an entity and a SQL server table: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/b021d830-7fd0-436b-8c79-10593d3e0622
6. Self-Populating tables: http://tejana.wordpress.com/2011/05/15/microsoft-lightswitchentity-names-and-properties-self-populating-tables/
7. Regular expression syntax http://www.regular-expressions.info/reference.html
[ 174 ]
Querying and Filtering Data A Query is a question you pose to the database so as to retrieve a specific piece of information in the database. The querying in LightSwitch can be best understood by looking at how it is structured. The following section (abridged for the sole purpose of what is being discussed in this chapter) is a gist of the article by the LightSwitch team which you may review at: http://blogs.msdn.com/b/lightswitch/ archive/2010/08/26/the-anatomy-of-a-lightswitch-application-part3-the-logic-tier.aspx. Querying in LightSwitch can be carried out using the
built-in Query Designer but more advanced querying can be carried out using code. This chapter describes the use of the built-in Query Designer in the IDE to query the entities in the data sources.
Querying in LightSwitch
The logic tier of LightSwitch basically starts with a data service that encapsulates all the access to the data source. This tier can host any number of data services exposed as endpoints at the service boundary as seen for example in Chapter 3, Accessing Data from an VSLS Application. Each data service exposes a number of queryable entity sets with operations for querying entities and an operation for submitting changes; add, update, and delete. An entity set contains entities of the same entity type. All operations take place with entity sets whether they are intended for fetching or for making changes to them. If you think of an entity set as an analogue of SQL table you will not be wrong. Just like you take information out of the table, make changes to it and return it to the table, you do likewise with entity sets.
Querying and Filtering Data
The following figure is based on the one you may review on the link mentioned earlier and schematically summarizes the architectural details: Data Service Analogous to db, WCF RIA SVC etc
Queryable Entity Sets Analogous to tables Entity 1
All
Single
Entity 2
Active
...etc.
Save
Operations
Each entity set has a default All and Single as shown in the entity Category. All entity sets have a Save operation that saves the changes.
[ 176 ]
Chapter 6
As defined, the entity sets are queryable and therefore query operations on these sets are allowed and supported. A query (query operation) requests an entity set(s) with optional filtering and sorting as shown, for example, in a simple, filtered, and sorted query on the Category entity.
Queries can be parameterized with one or more parameters returning single or multiple results (result sets). In addition to the defaults (for example, Category*(SELECT All) and Category), additional filtering and sorting predicates can be defined. Although queries are based on LINQ, all of the IQueryable LINQ operations are not supported. The query passes through the following steps (the pipeline) before the results are returned. (This is directly copied from the link mentioned earlier. The readers are urged to review the contents of the link.) •
Pre-processing
•
CanExecute—called to determine if this operation may be called or not
•
Executing—called before the query is processed
•
Pre-process query expression—builds up the final query expression
•
Execution—LightSwitch passes the query expression to the data provider for execution
•
Post-processing
•
Executed—after the query is processed but before returning the results
•
ExecuteFailed—if the query operation failed [ 177 ]
Querying and Filtering Data
In this chapter, we will review the following: •
Querying a Single Entity
•
Querying Multiple Entities
In the next chapter, we will review how events are handled along this pipeline.
Querying a Single Entity
We will start off creating a Visual Studio LightSwitch project LSQueries6 using the Visual Basic Template as shown (the same can be carried out with a C# template). We will attach this application to the SQL Server Express server's Northwind database and bring in the Products (table) entity. This process has been described in earlier chapters.
We will create a screen EditableProductList which brings up all the data in the Products entity as shown in the previous screenshot.
[ 178 ]
Chapter 6
.
The above screen was created using the Editable Grid Screen template as shown next with the source of data being the Products entity.
We see that the EditableProductList screen is displaying all columns including those discontinued items and it is editable as seen by the controls on the displayed screen. This is equivalent to the SQL query, Select * from Products as far as display is concerned.
Filtering and sorting the data
Often you do not need all the columns but only a few columns of importance for your immediate needs, which besides being sufficient, enormously reduces the cost of running a query. What do you do to achieve this? Of course, you filter the data by posing a query to the entity. [ 179 ]
Querying and Filtering Data
Let us now say, we want products listing ProductID, ProductName excluding the discontinued items. We also need the list sorted. In SQL Syntax, this reduces to: SELECT [Product List].ProductID, [Product List].ProductName FROM Products AS [Product List] WHERE ((([Product List].Discontinued) =0)) ORDER BY [Product List].ProductName;
This is a typical filtering of data followed by sorting the filtered data.
Filtering the data
In LightSwitch, this filtering is carried out as shown in the following steps: 1. Click on Query menu item in the LSQueries Designer as shown:
The Designer (short for Query Designer) pops-up as shown and the following changes are made in the IDE: A default Query1 gets added to the Products entity on which it is based as shown; the Query1 property window is displayed and the Query Designer window is displayed. Query1 can be renamed in its Properties window (this will be renamed as Product List). The query target is the Products table and the return type is Product.
[ 180 ]
Chapter 6
As you can see Microsoft has provided all the necessary basic querying in this designer. If the query has to be changed to something more complicated, the Edit Additional Query Code link can be clicked to access the ProductListDataService as shown:
[ 181 ]
Querying and Filtering Data
Well, this is not a SQL Query but a LINQ Query working in the IDE. We know that entities are not just for relational data and this makes perfect sense because of the known advantages of LINQ for queries (review the following link: http://msdn.microsoft.com/en-us/library/bb425822.aspx). One of those main advantages is that you can write the query inVB or C#, and the DataContext, the main player takes it to SQL and runs queries that SQL Databases understand. It's more like a language translation for queries with many more advantages than the one mentioned. We will be looking at this in the next chapter but in what follows we will look at the basic tools available for querying in the Query Designer. Let us now come back to creating the SQL Query we started with, using LightSwitch. 2. Hover over Add Filter to review what this will do as shown: This control will add a new filter condition. Note that Query1 has been renamed (right-click on Query1 and choose Rename) to ProductList.
3. Click on the Add Filter button. The Filter area changes to display the following:
[ 182 ]
Chapter 6
The first field in the entity will come up by default as shown for the filtered field for the 'Where' clause. The GUI is helping to build up "Where CategoryID=" . However, as you can see from the composite screenshot (four screens were integrated to create this screenshot) built from using all the drop-down options that you can indeed filter any of the columns and choose any of the built-in criteria. Depending on the choice, you can also add parameter(s) with this UI.
4. For the particular SQL Query we started with, choose the drop-down as shown.
Notice that LightSwitch was intelligent enough to get the right data type of value for the Boolean field Discontinued. You also have an icon (in red, left of Where) to click on should you desire to delete the query.
[ 183 ]
Querying and Filtering Data
5. Add a Search Data Screen using the previous query as the source by providing the following information to the screen designer (associating the ProductList query for the Screen Data).
This screen when displayed shows all products not discontinued as shown. The Discontinued column has been dragged to the position shown in the displayed screen.
Selecting the columns to display
It is seldom necessary to show all the columns in a row of data for the entity. Getting all the columns may also impact the resources. We may therefore need to select only a few columns to display. What we will be doing in this section could have been done earlier as well. We will use the Customization Screen to remove columns; we do not need to show (this can be done in the screen designer also, as discussed in the previous chapter). Note that the Query Designer is not built to select the columns and it will return the whole set of columns. This feature is quite different from all the rest of Microsoft's Query Designers over the years. You can select the columns you need to display either in the Customization mode while the program is running, or in the Screen Layout by deleting the elements you do not need (review discussions [ 184 ]
Chapter 6
at: http://social.msdn.microsoft.com/Forums/en-US/lightswitchgeneral/ thread/0795502a-513c-458f-9f63-bf9b06b68b12). 1. Click on Customization Screen at top-right and delete all the rows except ProductID, and Product so that the Customization Mode screen appears as shown.
2. Click on Save. The changes you made will take effect and the SearchProduct screen will appear as shown:
[ 185 ]
Querying and Filtering Data
Sorting the list
It is always important to display to the user a sorted list, either alphabetically or in some other way depending on the data type we need to display. Sorting makes it easy to get to the item you want quickly. The list you see does not seem to be sorted whereas the SQL Query has the Order By Clause and orders' Product Name according to the default ordering. Well, LightSwitch can be used to sort the query we created earlier. We will see how in the next section: 1. Create a query exactly as before called SortedProductList. 2. Click on the + sign by the side of Sort in the designer, which adds an expression developer GUI as shown:
3. Click on the drop-down handle for the fields and pick ProductName from the list. 4. Build the project. 5. Add a Search Data Screen called Search Sorted Product List and remove all the unwanted columns as before. 6. Click on F5 to display the screen. 7. Verify that the list is sorted with the Product Name alphabetically as shown.
[ 186 ]
Chapter 6
Also note that you can sort on multiple columns as well as add more complex criteria for selection as shown next:
Note however, the sorting on two columns (the above image) does not result in the desired result due to a known bug in Beta 2. This is fixed in the RTM according to what is reported in the LightSwitch forums; (http://social.msdn.microsoft. com/Forums/is/lightswitchgeneral/thread/47c28477-403a-45cd-aa4067d36eb1b6d7). [ 187 ]
Querying and Filtering Data
Queries using a parameter
At times even the previous filtering is not good enough and you want to fine tune your query (search) even more. Let us say in the previous filtered data we know that the products' unit price ranges over a wide range. We may want to look at only those products which are above a certain value. How is this done? Users familiar with Microsoft Access know how to find a solution to the above problem, that is, by using a parametric query. The next snippet which is a SQLView of a parametric query shows that you create a placeholder in the SQL Statement, for say, the ProductName. At runtime, Access will ask you for a ProductName and if you provide one it will show all the columns for that product. SELECT * FROM Products WHERE (((Products.ProductName)=[ProductName:]));
In SQL Server, you could write a stored procedure; (http://msdn.microsoft. com/en-us/library/aa174792%28v=sql.80%29.aspx) such as the one shown next which when executed with a parameter can show this kind of information. If you have never worked with stored procedures you can find a simple explanation at:
http://hodentekhelp.blogspot.com/2011/06/what-is-stored-procedure. html.The following code when executed in the query window of SQL Server Express will create the stored procedure. In this case, you first declare a parameter (@uprice
in this example) and in order to execute the stored procedure you need to supply a value for that parameter. Use Northwind go Create proc PriceFix @uprice money as select ProductId, Productname from Products where Discontinued=0 and UnitPrice >@uprice order by ProductName asc
This stored procedure is executed with the following statement, for example to find the selected items which are not discontinued and whose unit price is more than $45: Exec PriceFix 45.0—Here you are providing a value for @uprice=45
[ 188 ]
Chapter 6
The result of running query returns this the following set. It returns multiple values because there are many products that comply with the statement in the stored procedure. ProductId ProductName 18 Carnarvon Tigers 38 Côte de Blaye 43 Ipoh Coffee 51 Manjimup Dried Apples 59 Raclette Courdavault 20 Sir Rodney's Marmalade 62 Tarte au sucre
This kind of querying is carried out by creating a parameterized query in LightSwitch. The final result is as shown in the next screenshot. This is the same result as shown above.
To achieve this kind of screen to display those products whose price is greater than $45.00 the following abbreviated steps must be followed.
[ 189 ]
Querying and Filtering Data
1. Create a query ListByPrice as shown in the next image. This is a development of the sorted list with the additional information about the parameter Uprice. Uprice is the parameter of type Money and you are using it in the Filter criterion in addition to the Discontinued column set to False. The filter regions and the corresponding SQL they follow are shown alongside. It should not be construed that the stored procedure is being used in the screen. It is just a conceptual mapping.
In the above case, you can add a parameter first and then use it in the Filter criterion, or you start from Filter criterion, add a new parameter and set its value from the default Decimal to Money. 2. As shown in this first step, add a new parameter.
3. Create a Select Data Screen with no screen data (here it is called SearchProductListByPrice).
[ 190 ]
Chapter 6
4. Click on Add Data Item to bring up the Add Data Item window as shown:
5. In the Add Data Item window choose Queries and in the list choose ProductListData.ListbyPrice. The default name of the screen item becomes ListbyPrice.
[ 191 ]
Querying and Filtering Data
6. Click on OK on the Add Data Item window. The screen appears as shown next:
7. Click and drag ListbyPrice on the left-hand side of the screen and drop it just below the Rows Layout at the location shown.
The screen changes to the following as shown. The parameter is correctly identified as of data type Money and gets added to the screen menu.
[ 192 ]
Chapter 6
The control for Unit Price is the default Money Editor which can be changed to a Text Box or Money Viewer. 8. Keep the default control. 9. Click on F5. 10. The screen gets displayed with the Unit Price textbox with a value of 0 and you can enter any value you like. Here, a value of 45 was entered and the grid filled up with the rows that satisfy the criterion. 11. The screen is now displayed for the selected parameter value as shown next:
Querying multiple entities
Microsoft LightSwitch makes it easy to query multiple entities and with queries you can fine tune the results using multiple parameters.
[ 193 ]
Querying and Filtering Data
In the following, we will be considering the Orders and the Shippers tables from the Northwind database shown next:
What we would like to achieve is to fashion a query in LightSwitch which finds orders later than a specified date (OrderDate) carried by a specified shipping company (CompanyName). In the previous example, we created a single parameter and here we extend it to two parameters, OrderDate and CompanyName. The following stored procedure in SQL Server 2008 would produce the rows that satisfy the above conditions: Use Northwind Go Create Procedure ByDateAndShprName @ordDate datetime, @shprName nvarchar(30) as SELECT Orders.OrderID, Orders.CustomerID, Orders. EmployeeID,Orders.OrderDate, Orders.RequiredDate, Orders.ShippedDate,Orders.ShipVia, Orders.Freight, Orders.ShipName, Orders.ShipAddress, Shippers.ShipperID, Shippers.CompanyName, Shippers.Phone FROM Orders INNER JOIN Shippers ON Orders.ShipVia = Shippers.ShipperID where Orders.OrderDate > @OrdDate and Shippers.CompanyName=@ shprName
The stored procedure ByDateAndShprName can be executed by providing the two parameters (variables), @OrdDate and @shprName, as shown below. Exec ByDateAndShprName '5/1/1998 12:00:00','United Package' [ 194 ]
Chapter 6
The result returned by the previous command is shown next copied from the SQL Server Management Studio (only first few columns are shown):
The same result can be achieved in LightSwitch using two parameters after attaching these two tables to the LightSwitch application. As the details of creating screens and queries have been described in detail, only some details specific to the present section are described. Note that the mm-dd-yyyy appears in the result reversed yyyy-mm-dd. 1. Create a Microsoft LightSwitch application (VB or C#). Here project Using Combo6 was created. 2. Attach a database using SQL Server 2008 Express and bring the two tables, Orders and Shippers, to create two entities, Order and Shipper, as shown in the next screenshot:
[ 195 ]
Querying and Filtering Data
Create a query as shown in the next image:
Here the query is called ByDate. Note that the CompanyName in the Shippers table is distinct. The completed query with two parameters appears as shown:
[ 196 ]
Chapter 6
3. Create a new screen (click on Add Screen in the query designer shown in the previous screenshot) and choose the Editable Grid Screen template. Here the screen created is named EditableGridByDate. 4. Click on Add Data Item… and add the query NorthwindData.ByDate. The designer changes as shown next:
5. Click on OrderDate parameter on the left-hand side navigation of the screen and drag and drop it just below the Screen Command Bar as shown.
6. In a similar manner, drag and drop the query parameter CompanyName below the OrderDate of the earlier step. This will display as two controls for two parameters on the screen.
[ 197 ]
Querying and Filtering Data
7. Hold with mouse, drag and drop ByDate below the CompanyName you added in the previous step. The completed screen design should appear as shown (some fields are not shown in the display):
The previous image shows two parameters. The DataGrid rows show the rows returned by the query. As is, this screen would return no data if the parameters were not specified. The OrderDate defaults to Current Date. 8. Click on F5 to display the screen as shown:
9. Enter the date 5/1/1998 directly. 10. Enter United Package in the CompanyName textbox and click on the Refresh button on the previous screen.
[ 198 ]
Chapter 6
The screen is displayed as shown here (how do I know what to enter? I had a peek at the Shippers table beforehand).
The above screen is an editable screen and you should be able to add, delete, and edit the fields and they should update the fields in the backend database when you save the data. Also note that the LightSwitch application returned 11 rows of data while the stored procedure in SQL Server returned 10 rows. This may look weird but SQL Server date time refers to PM but Microsoft LightSwitch order date is datetime data type with AM. Entering PM instead of AM returns the correct number of rows.
AutoCompleteBox to set the parameter value
In the previous example if you did not know apriori (upfront) the parameter value to type in you would not be able to display the screen. One way would be to bring all the available parameter values into a control like a combo-box (drop-down) from which you only need to choose one. Beta 1 had a combo-box control that was removed in Beta 2( also in the release version) and a Auto Complete Box was provided in the IDE. In the present example, the parameter CompanyName has only a couple of values and the following steps show how you may replace the text box for CompanyName with an AutoCompleteBox control and then use some code to transfer the text in the AutoCompleteBox to the query parameter box to enter the CompanyName. 1. Using the same project UsingCombo create a screen with the Search Data Screen template based on the ByDate query (In ByDate query in the query designer, click on Add Screen…). Here the screen is named SearchByDate_CName.
[ 199 ]
Querying and Filtering Data
2. Click on Add Data Item in the screen designer; in the Add Data Item displayed click on Queries and choose ByDate in the list, accept the default name ByDate and click on OK. The designer screen appears as shown:
3. Hold, drag, and drop OrderDate between Rows Layout and the Screen Command Bar (a blue line shows up while you do this) which inserts the Data Picker (default) control below the Screen Command Bar as before. 4. Hold, drag, and drop ByDate below the label CompanyName. A DataGrid will be added to the screen as shown:
5. Click on Add Data Item… one more time, bring up the Add Data Item window, and choose items as shown in the next screenshot (click on drop-down handle of Type: and pick Northwind.Shipper). Note you are adding a Local Property
[ 200 ]
Chapter 6
6. Click on OK accepting the default name Property1. This adds the Property1 to the View Model as shown:
[ 201 ]
Querying and Filtering Data
7. Hold, drag, and drop Property1 below the Date Picker control as shown in this screenshot:
The Summary element for Property1 is added as shown:
[ 202 ]
Chapter 6
8. Hold CompanyName on the left; drag and drop it below Property1 as shown:
If we run the application by hitting F5 we will see a screen as shown.
The Property1 Auto Complete Box will function as a Combo box, but this value will not enter the Company Name parameter entry box for the By Date query. At this point, we add a little code to facilitate this.
[ 203 ]
Querying and Filtering Data
9. Add a button to the Property1 command bar as shown by clicking on New Button, which brings up a window where you provide a name (here, CopyFields) for the method and click on OK.
The button gets added. 10. Right-click on the button and pick Edit Execute Code from the drop-down. This opens the code editor page with the template code shown: Namespace LightSwitchApplication Public Class SearchByDate_CName Private Sub CopyFields_Execute() ' Write your code here. End Sub End Class End Namespace
In the procedure, insert the following code: Private Sub CopyFields_Execute() ' Write your code here. Dim x As New String(Me.Property1.ToString) Me.CompanyName = x End Sub
When the button is clicked, the text in the Property1 box will be copied to the parameter input box. We could use other controls, or the event from the Auto Complete Box also.
[ 204 ]
Chapter 6
The same code in C# is shown in the next image and the project is available for download at Packt's website.
11. Build the project and hit F5. Click on the handle for Property1 and choose the Company Name as shown:
[ 205 ]
Querying and Filtering Data
12. Enter the data directly in Order Date and click on the Copy Fields button. 13. The data grid gets populated by the query response as shown in the next screenshot:
Note however, that the query is based on existing entities and if the entity set is updated, say by adding a related entity (not necessarily changing the query), the query will become invalid.
Static spans
This is a new feature added in Beta 2, which confers the ability to include or exclude the related data when the query is executed. This task of including or excluding the records from the related entities is carried out in the design view of the UI. For example a new entity, Customers was added to the existing entities (Orders and Shippers) in the previous example. As noted earlier Search By Date CName query became invalid. A new screen, based on the same query ByDate was created (here as Search Test). Now, the parametric query result is working as it should. However, since Customers is related to Orders, the query brings in results for Customers as well as what's seen in the next screenshot:
[ 206 ]
Chapter 6
This may take more round trips to the server and this unwanted field in the display can be excluded by using the static spans. In order to do this, you will have to use the Edit Query link in the View Model (Screen designer) shown next:
[ 207 ]
Querying and Filtering Data
When you click on this Edit Query link the following screen is presented.
The new link Manage Included Data is used to include / exclude data from being displayed from related entities as shown here (click on the link).
The default is Auto for all of them which may make the query run slower. You can choose to exclude by making a choice here. Test the options and verify in the displayed screen.
Querying a query
In the previous sections, we saw queries using an entity set as a source. It is also possible to base a query using another query (also known as composed query) as a source. Users of Microsoft Access may have carried out refinements of the original query by using their queries as a source. This is also possible in Microsoft LightSwitch.
[ 208 ]
Chapter 6
However, you would start with a VSLS application which has an entity(s) and a query based on them defined. The following shows the ByDate query of the previous example.
1. Right click on Orders or Shippers and from the drop-down box choose to add a query. The following screen shows up:
This gives the choice where we can choose either the Orders entity as the source or the ByDate query as the source.
[ 209 ]
Querying and Filtering Data
2. Choose ByDate by clicking it. The Query1 is displayed as shown. You will notice that the parameters from the previous query are in the display.
You can further refine it by adding more criterion or other search options.
Summary
A brief overview of querying in Microsoft LightSwitch was described to lay a basis for the various querying scenarios described in the rest of the chapter. Querying data for displaying data in Microsoft LightSwitch from single entities as well as multiple entities was described using the built-in user interface, the query designer. Filtering, sorting, and the use of parameters (one or more) were described as well the use of auto complete box in search operations. Querying an existing query is also described. In the next chapter, the support for writing code in Microsoft LightSwitch will be described covering examples from entities, queries, screens, and so on.
[ 210 ]
Chapter 6
References
1. Query designer in LightSwitch: http://msdn.microsoft.com/en-us/library/ee256724.aspx
2. Creating and using a query in LightSwitch: http://www.paulspatterson.com/technology/lightswitch/microsoftlightswitch-creating-and-using-a-query/
3. How to create composed and scalar queries (Ravi Eda): http://blogs.msdn.com/b/lightswitch/archive/2011/04/18/how-tocreate-composed-and-scalar-queries-ravi-eda.aspx
4. What is new in Beta 2 (regarding static span): http://msdn.microsoft.com/en-us/lightswitch/gg699332
5. List detail and query: http://connect.microsoft.com/site1231/feedback/details/667262/ listdetail-show-records-out-of-query-in-lightswitch-beta-2
6. Selecting a few columns: http://social.msdn.microsoft.com/Forums/en/lightswitchgeneral/ thread/0795502a-513c-458f-9f63-bf9b06b68b12
[ 211 ]
Writing Code in Microsoft LightSwitch Writing code is what delights programmers. For non-programmers writing code is more of a challenge and not very palatable as they are not used to writing code. Microsoft from the very beginning even as far back as VB5 dedicated a lot of effort to make it easier for non-programmers to use its software such as VB and MS Access. It is these programs that attracted a large clientele. In Microsoft LightSwitch, this is taken to the next step in abstraction. Things are simplified even more. Most of the simple business applications can indeed be written without a line of code and still be robust with all features of validation, security, and so on. What is more, it can even support deploying the application to a number of topologies. The following summarizes how you did it before and how you do it in LightSwitch: •
Connect to a data source writing code (in LightSwitch, it takes only a few clicks).
•
Creating the GUI using the parts available in the Toolbox (in LightSwitch, screens are prebuilt). Only the controls you add are custom-built.
•
Write code for your business application (all screens wired to data during design). Use LINQ (Language Integrated Query).
•
Deployment needed more coding and use of other programs (in LightSwitch, it is built into the IDE).
In order to provide easy-to-use programming support, Microsoft LightSwitch has made it easier to write code using the built-in event-driven code templates that are appropriately matched to the program flow. Microsoft did not forget the developer either and has provided enough structural access to the code for the developers; more importantly, third-party software vendors can bring in the functionality that's absent in the bare bones program. This extensibility feature, which is in a very nascent state is deemed to grow as the software reaches its production stature.
Writing Code in Microsoft LightSwitch
In this chapter, we will be looking at writing code to the event-driven programming model that one finds in Microsoft LightSwitch. This chapter covers the following: •
Getting started with writing code
•
Writing and testing entity-related code
•
Writing and testing query-related code
•
Writing and testing screen-related code
Getting started with writing code
These are some general notions you should have before writing code. You have to know why, where, and how you write code. •
You want to write code because there is something that you want to do that is not present in the out-of-the-box program.
•
You write code in the event-generated methods such as adding an entity, validating a field, displaying a screen, and so on.
•
You have a choice of either VB or C# to write the code. At the very outset, you must choose VB or C# as the language for the application. Once in the project you cannot mix languages.
•
You write code to address entities, queries, screens, and other data and security-related tasks. A good percentage of all written code will be to the events raised by what is happening in the program.
•
The code window where you write code for entities/queries will be different from the one you write for a screen.
The code editor window supports intellisense technology that gives contextual help in writing code without which it is practically impossible to write code. If you have used any of the recent Visual Studio projects you would have experienced the utility of intellisense. It is strongly recommended that you pause while writing code and get intellisense support at appropriate places. Here is a link to see how and in what way intellisense makes your programming life easy (all editions of Visual Studio): http://msdn.microsoft.com/en-us/library/hcw1s69b%28v=VS.100%29.aspx
It is also important to make use of the Object Browser in the IDE, which gives a comprehensive class listing with details. Help that can be accessed from the IDE starts a Help Agent (Microsoft Help Viewer 1.1–Catalog VS_100_EN_US ) which starts a Visual Studio Help web page from the localhost.
[ 214 ]
Chapter 7
Why do you write code?
Although Microsoft LightSwitch is purported to be capable of being used by non-programmers and hobbyists there are situations where you do need to write code. To cite just one example, you may want to display a calculated value using two or more fields in an expression with some constants and LightSwitch does not provide a way of doing this other than the custom code. We have already seen some examples of code in earlier chapters; it is sufficient to say that there is a need to write code in some cases.
Where to write the code?
As to where you write the code, there are links and drop-down menus in the LightSwitch IDE, which give access to the Code Editor window where you write the code. You will be learning where to write the code in the rest of the chapter in different sections. There are many events in the lifetime of an entity (a screen, or some custom object that can be targeted by code) and VSLS has covered most of the events as you can see in the next image. Additionally, you can access the User Code folder in the file view of the project where you can add your custom files. The next image shows up a few major locations where you will begin practicing your code writing skills.
[ 215 ]
Writing Code in Microsoft LightSwitch
How you write code?
This really depends on you and your business requirements. In the sections to follow, there are a number of examples where you may want to write code. Code you write can target an entity, a screen or a query and may make use of all the referenced .NET classes. In what follows some of the events to which you can write code are broadly divided according how the code is targeted.
Data Model and Screens in LightSwitch
This image taken from MSDN documentation shows the various members of the data model generated in the Microsoft LightSwitch IDE. Application
Data Workspace Data Source Query Method
Entity Set
Property
Entity
Entity Collection
Related Entity
Related Entity Collection
In the Data WorkSpace which is directly under the top-level application you find the Data Source. When you create a table or attach an external database you will be creating this data source. The various data sources you connect to create data sources in the IDE which belongs to the Data Sources node. Under the data source will appear the entities which may consist of related entities. Entities have properties that you access in the designer. Queries are created from entities and they have their own methods. Queries coming under the entities are also part of the data source. You will see in this chapter that intellisense helps you enormously in navigating through these objects and it is well worth understanding how intellisense works. It is one of the most useful tools that you will often resort to, the other being the Object Explorer. Both the Entity Set and the Query Method in the above scheme get the data. Entity Set may also contain the security-related objects and there are different entity sets. Security-related entity objects will be treated in the next chapter. LINQ (Language Integrated Query) is well suited for working with queries. This is one place users coming for the first time to LightSwitch may find it most difficult. LightSwitch does not support all of LINQ's power and supports it partially. Other reasons users will [ 216 ]
Chapter 7
find it difficult is because of the lack of resources applied to LightSwitch directly, although the amount of LINQ information available otherwise is truly extensive. The LINQPAD, LINQER references you find in the references section are useful tools in understanding LINQ, but because LightSwitch supports LINQ to a restricted extent these tools may not be of immediate use although adequate for learning purposes . While creating screen, to use the data from entities or queries you use the screen designer. This designer uses in the background the Model View ViewModel (MVVM), a Microsoft-developed program-architectural pattern. The user does not need to understand this pattern for most of his experience with LightSwitch but it helps a lot if custom coding is called for. The model is used behind the scenes and the user will only reap the benefits of this scheme. The View is the screen layout you find in the screen designer you have seen in the previous chapters and the View Model is the data that is coming from the entities or the queries to the screen either through the screen designer templates or manually added to the screen as seen in some examples using the Add Data Item Control in the screen designer.
Writing and testing code targeting the entity
In order to write code to target the entity you should be in the entity designer of the application. Here we will attach to an external database; bring in some entities to the IDE and write code.
Inserting default values in the entity
The code we write addresses the business requirement that certain columns need to be filled with default values while making a data entry and we want the code to provide the defaults. 1. Create a MSLS VB Project (herein LS_Data2). 2. Attach database Northwind on SQL Express 2008. Northwind database is available in several versions of MS Access and SQL Servers. Because of their widespread use Microsoft has made available these files in several locations as you have seen in Chapter 1, Getting Started with Microsoft LightSwitch You may also access the SQL Server 2000 from: http://archive.msdn.microsoft.com/northwind/Release/ ProjectReleases.aspx?ReleaseId=1401.
[ 217 ]
Writing Code in Microsoft LightSwitch
3. Bring in entities Shippers and Suppliers to the entity designer. 4. Click on Supplier entity in the designer and click on Write Code menu item as shown:
5. Click on Supplier_Inserting (in the General Methods item) in the drop-down menu to display the code template. Supplier_Inserting is called just before data is inserted into the data store and therefore runs on the server. 6. Type in the code as shown. Make sure you make full use of intellisense.
[ 218 ]
Chapter 7
Using the code shown next we will set the default value for the ContactTitle as "Generalist" as shown in the following snippet. Note that the code is written in the NorthwindDataService.vb file. Namespace LightSwitchApplication Public Class NorthwindDataService Private Sub Suppliers_Inserting(entity As Supplier) If entity.ContactTitle = Nothing Then entity.ContactTitle = "Generalist" End If End Sub End Class End Namespace
End Sub
When you add a new row to the Supplier entity and save using the Save menu item on the screen, this default will be added to the new row you are inserting. The following is the code in C# (review the project download at Packt's website): using System; using System.Collections.Generic; [ 219 ]
Writing Code in Microsoft LightSwitch using System.Linq; using System.Text; using Microsoft.LightSwitch; using Microsoft.LightSwitch.Security.Server; namespace LightSwitchApplication { public partial class NorthwindDataService { partial void Suppliers_Inserting(Supplier entity) { if (entity.ContactTitle==null) { entity.ContactTitle = "Generalist"; } } } }
7. Create an Editable Grid Screen using Suppliers for data source. 8. Click on F5 to display the screen, the EditableSupplierGrid screen. 9. Click on the green + icon for Add... in the EditableSupplierGrid screen to bring up the Add New Supplier dialog as shown (shown partially).
10. Add values for CompanyName (required item), a few other fields (here ContactName and City) if you like but leave the ContactTitle empty as shown:
[ 220 ]
Chapter 7
11. Click on OK. The screen gets updated as shown next. It is still not committed to the server. Values of two of the fields in the new row inserted by the screen are, Hodentek and Jay. 12. Click on Save. The data is updated on the server and the SupplierID changes from 0 to a new value and the ContactTitle for the added row now gets the value Generalist as shown in the following screenshot. You may be wondering why the ID is not 30. The reason is it has been edited many times.
In the above operation we used the default behavior of the Add... button on the screen which brings up dialog for entering data. This behavior can be overridden by writing the custom code as we will see later. The next image shows the File View of the project and you will note that the code page is in the UserCode of the Server.
Inserting data into an entity by code
You can write custom code to insert data into an entity using code. The following example uses the Shippers entity from the Shippers table of Northwind database on SQL Server 2008. Presently, the project LS_Data2 is attached to this data source. Two custom commands will be added to enter the data:
[ 221 ]
Writing Code in Microsoft LightSwitch
1. Create a Search screen with a Search Data Screen template not attached to any data source. 2. In the Search screen add a new data items (Add Data Item | Query | NorthwindData. Shippers) which is the data in the Shippers entity. 3. Add two Buttons button and Button1 to the command bar under the data grid by clicking on the New Button drop-down menu as shown.
4. Add the following code (Shipper.vb) to the Button and Button1 execute ( right-click on the button in the screen layout and pick Edit Execute code) methods. Namespace LS_Data2 Public Class Search 'This is better in that you type in the values for Company Name and Phone 'Not good if you have many fields. Private Sub Button_Execute () 'Write your code here. Dim newshp As Shipper = New Shipper () newshp.CompanyName = ShowInputBox ("Enter Company Name", "CompanyName") newshp.Phone = ShowInputBox ("Enter Phone Number", "Phone") Save () End Sub 'This will create a new shipper record with hard coded values Private Sub Button1_Execute () 'Write your code here. Dim newshpr As Shipper = New Shipper With newshpr .CompanyName = "Everest Agencies" [ 222 ]
Chapter 7 .Phone = "555-9876" End With End Sub End Class
The following is the code in C# (review the project download at Packt's website) for Shipper.cs: using using using using using using using using using
System; System.Linq; System.IO; System.IO.IsolatedStorage; System.Collections.Generic; Microsoft.LightSwitch; Microsoft.LightSwitch.Framework.Client; Microsoft.LightSwitch.Presentation; Microsoft.LightSwitch.Presentation.Extensions;
namespace LightSwitchApplication { public partial class Search { partial void Button_Execute() { // Write your code here. Shipper shpr = new Shipper(); shpr.CompanyName = this.ShowInputBox("Enter CompanyName", "CompanyName"); shpr.Phone = this.ShowInputBox("Enter Phone Number", "Phone"); } partial void Button1_Execute() { // Write your code here. Shipper shpr2 = new Shipper(); shpr2.CompanyName = "Everest Agencies_2"; shpr2.Phone = "999-5555"; } } }
[ 223 ]
Writing Code in Microsoft LightSwitch
Notice that Button1 can only add a hard-coded shipper whereas Button will display an InputBox() dialog where you can enter the values. You can find reference to ShowInputBox() in the Object Browser as the following method: Microsoft.LightSwitch.Presentation. Extensions.ScreenExtensions.ShowInputBox (thisMicrosoftLightSwitch.Client.IScreenObject,System. String,System.String,System.String)
1. Click on Button1 on the grid with the screen displayed. Accept to save the changes and click on Refresh. Verify that the data is entered. 2. Click on Button on the grid with the screen displayed. An InputBox with CompanyName as title is displayed. Type in a company name. Here it is Himalaya. 3. Click on OK on the InputBox. 4. A new InputBox appears with Phone as the title requiring a phone number. Type in a phone number (here 521-52120) and click on OK. The screen is displayed. 5. Click on Refresh on the screen and verify that the data has been entered. Verify on the server in SSMS.
[ 224 ]
Chapter 7
Validating entity
You have already come across validation in Chapter 4, Screens in VSLS Application and you can write custom code to validate the entity. Let us say in the above Shippers entity, the business rule says there cannot be more than five shippers that the company can use. They can limit the entry by counting the existing vendors and restrict it to five. 1. For validation, you need to be in the entity and click on Write Code, which displays this menu as shown next:
2. Click on Shippers_Validate and insert the code as shown below: Private Sub Shippers_Validate(ByVal entity As Shipper, ByVal results As EntitySetValidationResultsBuilder) If Shippers.GetQuery.Execute.Count > 5 Then results.AddEntityError("Only 5 vendors are allowed") End If End Sub
When the count exceeds 5, the data entered will not be saved.
[ 225 ]
Writing Code in Microsoft LightSwitch
The same code in C# is as shown in the next screenshot:
Naturally, you will test this in a screen using the New Data Template named CreateNewShipper01 The following image shows the display of a validation error while trying to save an entry that exceeded the set count.
Writing and testing screen-related code
As mentioned previously, the code can be written targeting Entity, Query, Screen, and so on. Here, we will look at a couple of examples of code targeting the screens.
[ 226 ]
Chapter 7
Entering default values using code with screens
Just as in the previous section, the code can be written targeting the screen to provide default values when no values are provided during data entry. We will use the same project as in the previous section: 1. Bring up the Screen designer by double clicking on the EditableSupplierGrid screen in the Screen node of the Solution Explorer. 2. Highlight Rows Layout | Editable Suppliers Grid and click on Write Code to reveal the drop-down menu, as shown in the next screenshot:
3. Click on the EditableSuppliersGrid_Saving menu item to open the code page as shown
[ 227 ]
Writing Code in Microsoft LightSwitch
4. Under the Write Code here commented line, insert the code as shown next. Note that the code page is now displaying EditableSuppliersGrid.vb. This procedure is called just before the screen is saved and it runs on the client. It is the client validating the entry and all of the data is validated before being saved to the database.
The extra ShowMessageBoxes () were added to monitor the screen when it is running and are not needed. Detailed debugging information can be obtained by choosing to add a Toggle Breakpoint to the line as shown (for this, you can highlight the line and from the menu item Debug's drop-down list, click on ToggleBreakpoint or click to the left of the green line along the line you want to have the code to break). Add a breakpoint for the two lines as shown:
[ 228 ]
Chapter 7
As seen in the code we are choosing to add the default values to Country and PostalCode fields of the entity. Me in the code refers to the screen and the rest of the items are related to the screen controls. 1. Build and run the program hitting F5. 2. Click +…. in the screen to open the dialog Add New Supplier which adds an item to the list. 3. Insert a few items (Acme, John, and New York) and make sure the CompanyName field is not empty. Also make sure you are keeping the ContactTitle, Country and PostalCode fields empty. The SupplierID should be showing 0 as the data is not yet saved. 4. Click on OK. The items, Acme, John, and New York, get added to the screen as shown. Note that the Contact Title, Country, and Postal Code are empty.
5. Click on Save. The screen data is going to be saved to the data source. In this process, it hits the first breakpoint as shown:
[ 229 ]
Writing Code in Microsoft LightSwitch
6. You can right-click on the yellow arrow to display the above drop-down menu, which allows you do a number of things. 7. The following image shows the 'PostalCode' being changed at the Toggle Breakpoint we inserted earlier (you have to come to the End If line to see this by stepping into (F8) the code twice).
8. Step through (using Step Into (F8)) the code and click on OK for the MessageBoxes that may show up. When the code has completely run the following is displayed after hitting the Refresh on the screen menu:
The default values USA, Generalist, and PostalCode were added as shown with Generalist at the entity level and USA and PostalCode via code in the screen file.
[ 230 ]
Chapter 7
If you need the code in C#, cut and paste the code shown in the next paragraph into your application's EditableSuppliersGrid.cs page. using System; using System.Linq; using System.IO; using System.IO.IsolatedStorage; using System.Collections.Generic; using Microsoft.LightSwitch; using Microsoft.LightSwitch.Framework.Client; using Microsoft.LightSwitch.Presentation; using Microsoft.LightSwitch.Presentation.Extensions; namespace LightSwitchApplication { public partial class EditableSuppliersGrid { partial void EditableSuppliersGrid_Saving(ref bool handled) { // Write your code here. if (this.Suppliers.SelectedItem.PostalCode == null) { this.Suppliers.SelectedItem.PostalCode = "555-1212"; } if (this.Suppliers.SelectedItem.Country == null) { this.Suppliers.SelectedItem.Country = "USA"; } } } }
Writing custom code in some business cases may be very useful. For example, EmailAddress property is a data type in Microsoft LightSwitch for which you can set a default Email Domain, but you could write your own default code after setting the Email data type to be string. In many Intranet applications, e-mail addresses are given to employees with some combination of their first name and last name with the Company's e-mail domain name. This can be easily implemented in Microsoft LightSwitch.
[ 231 ]
Writing Code in Microsoft LightSwitch
Overriding default behavior
The default behavior of the Add..., Edit..., Delete..., and Update... buttons of the Command Bar can all be overridden and custom code can be written. Default Add...
Code when overridden gridAddAndEditNew_Execute()
Edit...
gridEditSelected_Execute()
Delete...
gridDeleteSelected_Execute()
Refresh...
gridRefresh_Execute()
Each of these are also paired with _CanExecute() (a consequence of Microsoft LightSwitch being built according to the Model View ViewModel(MVVM)) pattern as shown here for the overridden Refresh button): Private Sub gridRefresh_CanExecute (ByRef result As Boolean) 'Write your code here. End Sub Private Sub gridRefresh_Execute () 'Write your code here. End Sub
You can opt to override, for example the +... button as shown in the next image:
If you choose to do so, the screen displayed will be different than if you had not chosen to override. Using the above code, (when you click on +..., you will not be presented with a dialog as when it is not overridden) you add the values for the fields on the last row (which is empty and write enabled as shown here) and then click on the +... button.
[ 232 ]
Chapter 7
Accessing screen elements
There may be times when you want to access and modify properties of some screen elements. You should use the FindControl and FindControlInCollection methods of the screen. The syntax for these are as follows: FindControl(ByVal screen As Microsoft.LightSwitch.Client. IScreenObject, ByVal controlName) As String FindControlInCollection(ByVal screen As Microsoft.LightSwitch. Client.IScreenObject, ByVal controlName As String, ByVal rowData As Microsoft.LightSwitch.IEntityObject)
Make sure you review this in the ObjectBrowser as shown in the next image.
The difference between FindControl and FindControlInCollection depends on where the control is located in a screen. If it is not part of a collection then you can use the FindControl () and if the control is in a Collection (such as a Grid or a List) [ 233 ]
Writing Code in Microsoft LightSwitch
then you should use the FindControlInCollection ().
With reference to the above, you will use the FindControl() to find if the Test button you added is Visible and the display name of the CompanyName (field name in the entity) in the EditableShippersGrid screen using the following code. Note that the display name of the field CompanyName has been changed to MyCompany. ShowMessageBox(FindControl("Test").IsVisible.ToString) ShowMessageBox(FindControlInCollection("CompanyName", Suppliers.SelectedItem).DisplayName.ToString)
The first message box displays False and the second message box displays My Company. Modifications to the screen can be implemented if we can access the controls. In this next snippet you will see how you can set the visibility of a control: If FindControlInCollection("CompanyName", Suppliers.SelectedItem). IsVisible = True Then FindControlInCollection("CompanyName", Suppliers. SelectedItem).IsVisible = False End If
When you select the line you added and choose to edit and change one of the fields and try to save, the display will appear as shown.
[ 234 ]
Chapter 7
You can see that Acme which was the company name has become invisible. If you are starting with a VSLS application using the C# template you may use the following code to find how the FindControl() and FindControlInCollection() works. bool Cntrlstrg =this.FindControl("Test").IsVisible; this.ShowMessageBox(Convert.ToString(Cntrlstrg)); string Cntrlstrg2 = this.FindControl("CompanyName"). DisplayName; this.ShowMessageBox(Cntrlstrg2); }
Of course, this gets into the same EditableSuppliersGrid_Saving(ref bool handled) procedure used earlier. Download and review the project LSData_ 7CSharp from Packt's website.
Writing custom queries using code
The Query Designer in VSLS can do excellent filtering and sorting, but with some limitations, and it can also work with parameters. However, it has no means to support choosing certain columns, use aggregate functions, use other clauses such as group by, and any other logic not handled by the GUI. However, Query Designer code can be further fine tuned using custom code. In the following section, we look at a number of queries written using codes. Queries in MSLS as described in earlier chapter depend on LINQ. LINQ queries are not the same as SQL queries although there is some resemblance especially when used with relational data.
[ 235 ]
Writing Code in Microsoft LightSwitch
A simple query with code
This example is very simple and can even be implemented in the designer but shows the basics of writing code. The query in this section just returns one row that satisfies a given condition. 1. Create a VSLS project using a VB template or C# template Here Linq_7. 2. Attach to an external database. In this case, it is attached to Northwind on SQL Server Express. 3. Bring in the entities Categories and Customers, Orders, and Products. 4. Create three queries as shown in the following (only Query1 is shown in the Linq_7 Designer):
Query2 and Query3 are also similar except that they are queries to the Customers entity. In design view, all three queries appear the same (no filtering, no sorting, and no parameters). 5. In the Properties window of Query1 click on Edit Additional Query Code. The code page opens with a stub for the Query1_PreprocessQuery () procedure which returns query. The reference returned is from System.Linq.IQueryable.
[ 236 ]
Chapter 7
6. Type in the following statement for the query in NorthwindDataService.vb as shown: Namespace LightSwitchApplication Public Class NorthwindDataService Private Sub Query1_PreprocessQuery(ByRef _ query As System.Linq.IQueryable(Of LightSwitchApplication.Category)) query = From c In query Where c.CategoryName = "Beverages" End Sub End Class End Namespace
7. Create a blank Search Data Screen based screen SearchQuery1. The screen gets added to the Screens node in Solution Explorer. 8. Add a data item and choose NorthwindData.Query1 for the source as shown:
[ 237 ]
Writing Code in Microsoft LightSwitch
9. Drag and drop Query1 under the RowsLayout as shown (this task was described in Chapter 4, Screens in VSLS Application):
10. Build and click on F5. The SearchQuery1 screen displays as shown:
If you are wondering why this search screen looks like an edit screen, it is because we started with a blank screen and dragged and dropped the NorthwindData. Query1 whereas you could also create a Search screen while designing the screen by attaching to NorthwindData | Query1 as shown next:
[ 238 ]
Chapter 7
Query with selection and sorting
The query in this example does the filtering and sorting with code. It is similar to the previous query but adds the sorting. It returns more than one row depending on the filter condition. Follow all the steps as mentioned before to displaying the screen, but for the code use the following in Query2_PreprocessQuery();. Private Sub Query3_PreprocessQuery (ByRef query As System.Linq. IQueryable(Of Linq01.Customer)) query = From c In query Where c.City = "London" Order By c.CompanyName End Sub
For the Customer entity in Northwind you would get the following displayed:
In the place of Order By clause, you can use others shown in this intellisense drop-down menu.
[ 239 ]
Writing Code in Microsoft LightSwitch
Query with text search
The following example shows that you could have a query that filters out records containing a particular piece of text (string) in a field. In SQL server, the same procedure would need full text searching enabled. Follow all the steps as above up to and displaying the screen, but for the code use Private Sub Query3_PreprocessQuery(ByRef query _ As System.Linq.IQueryable(Of LightSwitchApplication.Customer)) query = From c In query Where c.CompanyName.Contains ("La ") Select c End Sub
Build and click on F5. The screen gets displayed as shown:
Data from related tables
It is often necessary to search for records from related tables in a relational database such as SQL Server. In SQL Server, you would be using Join between the tables in a SQL query to find the child records for a given parent record. For example, the Customers and Orders tables have a one-to-many relationship with each customer capable of having many orders. 1. Create a screen based on the Search Data Screen template with no attached data source. Here the screen is called just Search. 2. Open the View Model and View of the Search screen. 3. This will be empty except for the Close, Refresh, and Save buttons. Add two data items (use Add Data Item) of the type Query. Pick the queries Customers and Orders one after another from this Add Data Item window shown in this image: [ 240 ]
Chapter 7
Your design area of Search screen would appear as shown in the following screenshot:
The Customers and Orders were added to the View Model when you added the data items in the previous step (shown on the left). 4. Drag and drop Customers below the RowsLayout so that is the screen layout. 5. Expand the Command Bar node and add a button (named as Find Orders). 6. In the panel on the left of the screen designer click Add Orders to the Customers data. [ 241 ]
Writing Code in Microsoft LightSwitch
7. In the menu of this screen click on Write Code at the extreme-right of the menu bar and click on FindOrders_Execute (here display name of Button is set as Find Orders). The code page that opens inserts the code as shown here (complete page is shown with insertion). Option Infer On Imports System.Linq Namespace LightSwitchApplication Public Class Search Private Sub FindOrders_Execute() ' Write your code here. Dim q = From c In Customers From o In Orders Where (o.Customer.CustomerID = c.CustomerID) ShowMessageBox(q.Count) q.ToList() 'Dim output As New System.Text.StringBuilder For Each x In q Dim strg As String = "" For i = 0 To 14 strg = strg + q.ElementAt(i).c.CompanyName strg = strg + "," + q.ElementAt(i).o.OrderDate. ToString strg = strg + "," + q.ElementAt(i).o.OrderID. ToString + vbCrLf Next i ShowMessageBox(strg) Next End Sub End Class End Namespace
Option Infer On is necessary for the LINQ query to work. System.Linq was added
since it was not found in the Client's references. You do get the help of intellisense for this code.
[ 242 ]
Chapter 7
This joins the Customers and Orders table for the shown condition. The components of the variable q are then decomposed using the For Each… statement to access the members. Actually, there is only one element in this that satisfies the condition shown in the next screenshot.
You can easily modify the code to get other fields in Customers or Orders. Please follow this link for an alternative way of doing the same: http://social.msdn.
microsoft.com/Forums/en-US/lightswitchgeneral/thread/3ee965fb-d1cc4858-b3aa-2097900a7afc.
Finding records by navigation
When entities are related such as in the case of Customers and Orders typical of Master / Slave (perhaps politically incorrect but legacy terminology) or Parent/ Child relationships, you can use the LINQ's way of going from one to other as shown in the following example. 1. Create a query, Query5, and make no change in the Query Designer. 2. Click on Edit Additional Query Code in the property window of the Query5. 3. In the code page that opens insert the following code: Private Sub Query5_PreprocessQuery(ByRef query As System.Linq. IQueryable(Of LightSwitchApplication.Order)) query = query.Where(Function(o) o.Customer.City = "Berlin") [ 243 ]
Writing Code in Microsoft LightSwitch query = query.OrderBy(Function(o) o.Customer.City) End Sub
This query filters the Orders entity with the customer's city as a criterion. The second query orders the first query according to the ascending order of customer's city. 4. Now create a screen SearchQuery5 using Query5 as the source of data. 5. Build and hit F5. The following screen is displayed:
Using a query to add data
We have seen a number of examples of displaying row(s) of data. We also inserted data into the entity using code targeting the entity designer. It is equally possible to add data to the entity collection using a query populating a screen. 1. Create a query Query6 using the Customer table in Northwind along the same lines as before (no need to filter, sort, or add parameter.) 2. Create an empty screen EditableGrid based on the Editable Grid Screen template. 3. Add the query collection to the RowsLayout in the view of the screen along the same line as before. 4. Expand the Command Bar node in the screen designer (View) and right-click on the Add… button to view the code page.
[ 244 ]
Chapter 7
This opens the code page with the following method: Namespace LightSwitchApplication Public Class EditableGrid Private Sub CustomersAddAndEditNew_CanExecute (ByRef result As Boolean)
End Sub Private Sub CustomersAddAndEditNew_Execute()
End Sub End Class End Namespace
You could write your code if you wanted to override its default behavior. Insert the following code in the Private Sub CUstomersAddAndEditNew_Execute() 'Write your code here. Dim customer As New Customer customer.CustomerID = "JAMES" customer.CompanyName = "Jamies" customer.City = "Manchester" customer.Country = "United Kingdom" End Sub
5. Click on F5 and bring up the screen. 6. When you click the + button on the Command Bar of the displayed screen you will have added the new customer to the database.
[ 245 ]
Writing Code in Microsoft LightSwitch
Summary
In this chapter, some general aspects of writing code in LightSwitch were described. Codes targeting entities, screens, and queries were described with some examples. This is in no way complete as there are many aspects of writing code not considered. For example, code targeting security issues were not described. They will be described in the next chapter. While testing the code in a single-user environment can provide an adequate description of how the code works; it is only in a multi-user environment the full potential of the code must be evaluated. Perhaps LINQ-related programming is the most difficult part for the user and it is recommended that the user reviews some of the references given just before. In the next chapter, we will look at authentication and authorization in LightSwitch. We will also look at writing code targeting the application security.
References
1. Writing code for data-related objects http://msdn.microsoft.com/en-us/library/gg445195.aspx
2. About Model View ViewModel: http://en.wikipedia.org/wiki/Model_View_ViewModel
3. Using code with data-related tasks: http://msdn.microsoft.com/en-us/library/ff851990.aspx
4. LINQ in MSDN documentation: http://msdn.microsoft.com/en-us/library/bb397910.aspx
5. LINQPAD download link. Useful tool to learn LINQ: http://www.linqpad.net/
6. LINQER – evaluation copy download here: http://www.sqltolinq.com/
[ 246 ]
Authentication and Authorization in Microsoft LightSwitch Application security is a must-have feature for all businesses. Microsoft LightSwitch has sufficient built-in security features to support both authentication and authorization. Authentication uniquely and unambiguously identifies the user while authorization determines what an authenticated user can and cannot perform in the application. Additionally during development, there is a provision to test the security feature without exiting the IDE which speeds up the development process. Microsoft LightSwitch authentication and authorization is built on familiar Microsoft technologies used in various products and therefore presents an easier learning curve or very little extra learning for those who are already familiar. The application level security scheme in Microsoft LightSwitch is an extension of the ASP.NET security which utilizes membership and roles supported by Profile provider APIs. Users accessing the application should first be authenticated. Microsoft LightSwitch has two options for authentication—namely Windows authentication and Forms authentication. As the name implies, Windows authentication system will work with a high degree of security where all users are located in a Windows domain or inside an intranet system. Microsoft LightSwitch supports users for application with roles and permissions. The user management is administered by the application administrator at runtime via administrative screens built in the application. Access to these screens at design time requires debug permission for security administrator. Application administrator can also create users, create access permissions, and provide roles to users at design time as well, but these will not be present at the runtime.
Authentication and Authorization in Microsoft LightSwitch
In this chapter, we will be looking at the following: •
Authentication schemes
•
Access Permission
•
User Management
Authentication schemes
By default, for a new project created in Microsoft LightSwitch, authorization is not enabled, as shown in the following screenshot. Here we can see the application designer with its Access Control tab displayed in its default state for the VSLS Application named TestAccessUI.
In all the previous chapters, this (default) has been the case. However, for your application to operate with high security, authentication has to be enabled for which you have the two choices. Authentication is only the first part of creating an application which is secure. You are either authenticated or unauthenticated (similar to anonymous user). In case you are authenticated you belong to one of these: •
Windows authentication: Uses Application user's Windows credentials
•
Forms authentication: Uses application user's login (username and password) which is checked against stored user's credentials [ 248 ]
Chapter 8
Choosing an authentication scheme is easily carried out while you are in the Access Control tab of the designer. For Forms authentication, click on the radio button Use Forms authentication and for Windows authentication use the other radio button.
Access permission
This is where permissions are created, which describes how and what parts of an application the users are permitted to access. These permissions are assigned to roles and the authenticated users can take on roles. When these users log into the application, they can and cannot take actions in the application, depending on the permissions they have. Microsoft LightSwitch registers the users in its security database which is an extension of the aspnet.db with some additional related tables for taking care of roles and permissions as shown in the next image. The right side of the image shows the security database used in ASP.NET applications where the four tables shown are used in managing users. The security in a VSLS application may be considered as an extension of the above idea and is shown in the left side of the image. In addition to user management, the database also contains information on Roles and the Users who are assigned to roles by the application. This database is created by the application and uses the Project name created in the VSLS application as the name of the database.
The LightSwitch Security database is created in the application and stored internally. During the deployment of the application, the database is attached to a resident SQL Express database (only the Metadata). The preceding database is the Security database of an application AdvEntity in the local SQL Express server.
[ 249 ]
Authentication and Authorization in Microsoft LightSwitch
Permissions with Forms authentication
Permission determines what an authenticated user can and cannot do in an application. Some users are allowed to just view some screens and only the data they are allowed to see; some may be permitted to insert into the application data, and some others can make updates to the tables and so on. The Security Administrator of the application makes all these security decisions and assigns them to users by creating roles that are endowed with permissions. The first step in creating permissions is to create a permission object. Permission objects can be created for screens, commands, data entities, and queries. Once created, the objects can be referenced in code by the Can methods such as: CanRun .
Creating screen Permissions with Forms authentication
In this section, we will see how a permission, which allows users to see a screen, is created. We start off with a project which has an entity called Employees and a SearchEmployee screen. The Access Control where permissions are created is an easy-to-use interface. It can be used to create any number of permissions with the name of your choice. Permissions can also be deleted as easily. 1. Choose Forms authentication. 2. Click in the just below the permission called SecurityAdministration as shown in the image in this step. Type in the following: Name: Can_View_Employees (it is assumed you have a screen named Employees). Display Name: View Employees. Description: Allow access to Employees screen. Your Access Control tab appears as the following screenshot:
[ 250 ]
Chapter 8
Now, we will restrict users who can view the Search Employees screen which happens to be the only screen in this application to start with as follows: 3. Click on Screen Navigation tab in the previous window. The tabbed page appears as shown:
4. Make sure you read everything on this window. This application has just one screen which also happens to be the Startup Screen, the screen that is displayed as soon as your browser is displayed. If you have multiple screens, you can choose any of the screens to be the startup screen using the Set or Clear buttons on this page after highlighting the screen you choose to start up with. Search Employees is the only task in this application. The administration of this application is via Users and Roles although nothing is defined as yet. The elements in a node can be shifted up or down using the up and down buttons on the right. The Users and Roles are under the screen Administration which only the application administrator will be allowed to see and take actions. If needed, you can also create new groups using the Add Group control. The screen displaying Users | Roles of the Administration | Users will be visible to the Administrator | Users if the checkbox Granted for debug has a check mark as shown:
[ 251 ]
Authentication and Authorization in Microsoft LightSwitch
Screen Navigation also allows including adding screens, changing the Startup screen if you had had multiple screens, and so on. 5. Right-click on the SearchEmployees task as shown in the next screenshot:
Here you have the options to remove, rename, or write code for SearchEmployees_CanRun. 6. Click on the Edit SearchEmployees_CanRun drop-down. The code page opens with this template procedure where you need to write the code (here the project name is FormsAuthetication): Namespace LightSwitchApplication Public Class Application Private Sub SearchEmployees_CanRun(ByRef result As Boolean) ' Set result to the desired field value End Sub End Class End Namespace
The code you write will be just under the commented line and the code will determine who can view the SearchEmployee screen. Insert the following code: Private Sub SearchEmployees_CanRun(ByRef result As Boolean) ' Set result to the desired field value If Current.User.HasPermission(Can_View_Employees) Then result = True Else result = False End If End Sub
[ 252 ]
Chapter 8
Make sure you do not type the code all at once (do not cut and paste) but do it word by word pausing each time so that intellisense will bring up the drop-down menu (as shown at an intermediate state):
Note that the code is in the Application class and runs every time the application is run. Now that the code is written, you need to test if it works. This has to be tested to verify that the user who is permitted, can view the table and the user who is not, should not see the screen. For this you need to set up what is called debug permission. This is easily done in the Application Designer's Access tab as seen earlier. 7. Just place a check mark in the Granted for Debug check box for the selected permission (in this case Can_View_Employees) as shown. It is shown as checked in an earlier image also. To uncheck, click again in the check box as shown in the following screenshot:
[ 253 ]
Authentication and Authorization in Microsoft LightSwitch
Since the permission for debugging is granted when you click on F5, the screen should get displayed. In the design environment, the program creates a TestUser which has the debug permission and allows testing permissions. When you uncheck this and try to run by clicking F5, the application runs but the Search Employee screen will not be displayed. What you see is an empty screen shown here where the current user is shown at the bottom-right, the previously mentioned Test User.
For testing in the IDE, LightSwitch creates a current user called Test User
Using code, you could discover everything about the User as shown in the next snippet written to the SearchEmployee_Activated() event. For C# version, please see the Authen8_CSharp project on the Packt website.
[ 254 ]
Chapter 8
In working with the project, you may run into some timeout errors as shown here. In the next screenshot there is a connection-related timeout. The solution is to refresh the data source before you build the application:
You may also get timeout in the request handling as shown here and the application may not work. You may have to rerun the application to succeed. Some of these errors may not show up in the final version:
[ 255 ]
Authentication and Authorization in Microsoft LightSwitch
Where is the permission saved?
The permission with its name and other details will be saved in the ApplicationDefinition.lsml file as shown here:
Permission to a button
Buttons execute commands and can be placed on a screen in the design phase. The next screenshot shows how a button is added to the screen menu. The display name of the button represents the method it executes. Click +Add to open the drop-down menu as shown in the following screenshot:
[ 256 ]
Chapter 8
Click on New Button… which displays the Add Button window:
Replace the default name Method with a custom name. Here, the name Test1 is used. Another way to add the button to the screen command bar is to click the +Add Layout Item on the screen layout (Test0 was added as shown in the next image). You can add a button to any of the following locations on the screen as shown in the next screenshot. The Control Type of the button is shown in parenthesis: Screen Command Bar: Default (Shell Button) Data Grid | Command Bar: Default (Collection Button) Data Grid Row | Command Bar: Default (Button)
[ 257 ]
Authentication and Authorization in Microsoft LightSwitch
All these buttons have the same two methods, Execute Code and CanExecute. Buttons are used to issue commands and controlling who can execute the code invoked by this code is security based. Data entry staff may be given permission to add data for example and Managers may be permitted to delete. If you do not want to permit staff to delete some entry, the best way is to not allow the employee to see that the delete button is disabled or not seen in the first place. These user actions are orchestrated by the permissions in a VSLS application. The preceding UI gets rendered as shown in the next screenshot:
You can begin writing code to the various methods by right-clicking on the method on the screen layout as shown:
[ 258 ]
Chapter 8
Each of the methods you add has editable codes, Execute Code and CanExecute Code. While the Execute Code runs the method you want to run, the CanExecute Code which is an access control method, runs ahead of it and checks if it is secure to run the Execute code. Depending on what is permitted in the CanExecute code, the Execute Code will be run. The Execute and CanExecute are built into the model which is based on the Model View View Model (MVVM) design pattern (Review the images here: http://www.bing.com/images/search?q=MVVM+architecture&q pvt=MVVM+architecture&FORM=IGRE). 1. In understanding MVVM in the context of LightSwitch, the following well written article is highly recommended: http://openlightgroup.net/Blog/ tabid/58/EntryId/89/Silverlight-View-Model-Style-An-OverlySimplified-Explanation.aspx. After you add a table or get connected to an external data source you are building the model and when you add a data item to a screen (UI) or use a template of a screen using the data source, you are creating a View Model, which appears on the left side of your screen designer. The controls necessary to access the view model are laid out in the view (the screen layout). The commands, which can be thought of as methods are also part of object to data binding which is a core concept of MVVM. The commands (buttons or methods) are bound to the view model that invokes events. Microsoft LightSwitch provides the framework for working with the commands (just search for ICommand in the Object Browser to see the details). The object browser really shows how a command is implemented in LightSwitch.
2. In this section we look at a simple example that tests the permission with a simple logic. Create a screen (using the Editable Grid Screen template) for displaying Employee's table from the Northwind database on SQL Server 2008 Express. 3. Using Add Layout Item place a button on the Screen Command Bar with a display name (Method) Click me. Place a check mark for the Is Visible check box if it is unchecked. 4. Right-click on the button and click to add the two methods Edit CanExecute code and Edit Execute code to open the following code templates. 5. The code page of the screen opens with the following codes: Public Class SearchEmployees Private Sub ClickMe_Execute() ' Write your code here. End Sub Private Sub ClickMe_CanExecute(ByRef result As Boolean) [ 259 ]
Authentication and Authorization in Microsoft LightSwitch ' Write your code here. End Sub End Class
Note that the _CanExecute () method returns a Boolean with the name result. 6. Insert the following code as shown here: Private Sub ClickMe_Execute() ' Write your code here. ShowMessageBox("ClickMe button is clicked") End Sub Private Sub ClickMe_CanExecute(ByRef result As Boolean) ' Write your code here. result = True End Sub
7. Click on F5 to display the EditableEmployeeGrid screen and notice that the Click me button on the screen menu is enabled. Click on the button and verify as shown here:
8. Change the code to return a false in the _CanExecute() method as shown and verify that the button is disabled when you run it by hitting (debug) F5. Namespace LightSwitchApplication Public Class EditableEmployeesGrid Private Sub ClickMe_Execute()
[ 260 ]
Chapter 8 ' Write your code here. ShowMessageBox("ClickMe button is clicked") End Sub Private Sub ClickMe_CanExecute(ByRef result As Boolean) ' Write your code here. result = False End Sub End Class End Namespace
In the following screenshot you will see that the ClickMe button is disabled:
If you place a breakpoint in the _CanExecute () method you will observe that the breakpoint is hit as soon as you try to display the screen. The _CanExecute () method is used for reasons of security to make sure the permitted user with certain permission can click on the button to respond. The following code can be used to check this situation (place a second button ClickMe2 in the screen Command Bar). Private Sub ClickMe2_CanExecute(ByRef result As Boolean) ' Write your code here. If Application.User.HasPermission(Permissions.Can_View_ Employees) Then result = True Else result = False End If End Sub
On the other hand, you can prevent the user with the Can_View_Employees permission by turning around and changing the logic in the preceding code. In either case, to test it in the IDE you need to provide (not provide) debug permissions as described earlier. [ 261 ]
Authentication and Authorization in Microsoft LightSwitch
Permission to query
Permission to run a query is controlled by how you code the Query _CanExecute () method. You can access the code you can write by clicking on the Write Code menu on the Query designer as shown. The query filters the entity, based on the condition shown in the filter:
As you see in the next screenshot there are many query-related methods and Query_CanExecute () runs on the server and is called prior to query execution.
Permitting a user to run a query
A user cannot display a screen if the screen is based on a query for which he has no permission. In this case we can write code in the query's _CanExecute () method as shown here. In order to see how this works, you should create a Query1 as shown in the previous screenshot using the Employees entity. In the Application's Property page, you should create a permission with the following settings: Access Control tab: Use Forms Authentication Name of permission: CannotView_Employees Display name: Cannot see Employees Description: Employees screen cannot be accessed Granted for Debug: Checked Namespace LightSwitchApplication Public Class NorthwindDataService Private Sub Query1_CanExecute(ByRef result As Boolean) If Application.User.HasPermission(Permissions.CannotView_ Employees) Then [ 262 ]
Chapter 8 result = False Else result = True End If End Sub End Class End Namespace
When you display a screen based on this query, the preceding code will be run and since the current user has no permission to run the query, the screen would not display but comes up with an error message as shown in the following screenshot:
Here we have a query called Query1 which shows everything in the Employees entity where the country is 'USA'. The screen Search Query1 is based on this query for which the preceding code was written. However, in Beta 1, the error message was different but more informative as shown in the next screenshot:
[ 263 ]
Authentication and Authorization in Microsoft LightSwitch
Permission to a query based on another query
Since it is possible to create a query based on another query, we will examine how permission gets verified when you run the query based on another query. 1. Based on the previous query, create another query, Query2 as shown here (this is done from the entity screen's Query menu item):
2. Add a filter where the FirstName is set to Nancy.
3. Create a screen SearchQueryEmployee2 using the Search Data Screen template with Query2 as the source. The Search Query1 screen will display all the Employees in 'USA' and the SearchQueryEmployee2 screen just shows the record for the employee whose first name is Nancy. 4. Click on Write Code menu on Query2 editor (the previous screen) and click on Query2_CanExecute(). [ 264 ]
Chapter 8
5. The NorthwindDataService.vb code page opens where you wrote the Query1_CanExecute() code. 6. Insert the following code in Query2_CanExecute(). Private Sub Query2_CanExecute(ByRef result As Boolean) If Application.User.HasPermission(Permissions.Can_ View_Employees) Then result = True Else result = False End If End Sub
7. Create the SearchQuery2 screen based on Search Data Screen template using Query2. 8. Click F5 or Click on Debug from the main menu. 9. You can verify from the screens that querying the query is yielding the expected result.
Bug in querying a query
Since Query2 is derived from Query1, it would be natural to assume that if Query1 is not evaluated, Query2 would not be . This bug appears to persist in Beta 2 (also in the release version) as you can verify by inverting the logic in Can_Execute() for which Query1 will fail, but you can verify that Query 2 still executes. Compare SearchQuery1 and SearchQueryEmployee2 screens in the Authen8 Project. This bug appears to persist in Beta 2 as you can verify by inverting the logic in
CanExecute() for which Query1 will fail, but you can verify that Query 2 still executes. Query2 appears to be just another query derived from the entity. In this sense it is not a query based on another query. The reason for this is that the Query2 gets its permission from the Application and not from whether Query1 executes
or not.
It should be noted that any Query execution result will depend on how the permissions are set in the Application's property page.
Permission to Entity
In order to access the hook to writing code for entities, you should be in the entity designer window. You can write code for several of the Create, Read, Update, and Delete (CRUD) operations—the basic requirement of persisted storage as well as saving the data. All these codes run on the server.
[ 265 ]
Authentication and Authorization in Microsoft LightSwitch
Click Write Code with the entity displayed to display the menu for choosing the Access Control Methods for which you want to write the code as shown:
The drop-down list gives access to writing code for the four EntitySet access control methods, namely _CanDelete, _CanInsert, _CanRead, and _CanUpdate methods as well as the pre-processing SaveChanges_CanExecute() method. However, each data source you have in your project will have its own data service and the security of the entity will be governed by the code you write in the data service as you see from the two similar _CanDelete() methods. The first one for a TestAppDatas_CanDelete() for the TestAppDatas if you have, in addition to the Employees entity an Application Data, a table created in the project called TestAppData. This code is for the TestAppData entity's _CanDelete() as shown here, Public Class ApplicationDataService Private Sub TestAppDatas_CanDelete(ByRef result As Boolean) End Sub
Whereas for the Employee entity's _CanDelete() method the following code is used:
[ 266 ]
Chapter 8
The code that you write in the _CanDelete depends on whether or not you are allowing someone to carry out a task such as those involved with CRUD operations. In order to look at how this works, let us create a screen EditableEmployeesScreen based on the Editable Grid Screen template. By default the Editable Employees Grid screen will be displayed as shown in the next screenshot. You can carry out the edit operations by clicking on the icons. If you hover over the icon, you will see a pop-up displaying information as to what the icon does when clicked.
Let us assume that we do not want this permission to include Edit or Delete operations for the user. We want to make sure that the user with this permission can neither delete nor edit an entity. We can do so by inserting the following code as shown: Private Sub Employees_CanDelete(ByRef result As Boolean) If Application.User.HasPermission(Permissions.Can_View_ Employees) Then [ 267 ]
Authentication and Authorization in Microsoft LightSwitch result = False Else result = True End If End Sub Private Sub Employees_CanUpdate(ByRef result As Boolean) If Application.User.HasPermission(Permissions.Can_View_ Employees) Then result = False Else result = True End If End Sub End Class
When the screen is displayed as shown in the screenshot, the Delete and Edit buttons are disabled for the user who has the Can_View_Employees permission:
Permissions with Windows authentication
In Windows authentication, the credentials for logging on to the computer (or the domain in a server set up) are used by the application to authenticate the user. You need to provide the credentials only once while accessing the computer. LightSwitch users can be users added by an application administrator in the running application or they can be authenticated Windows users.
[ 268 ]
Chapter 8
If a user has to access resources on the computer he or she should be authenticated. The computer administrator can set up the user in the computer management (Control Panel | System and Security | Administrative Tools | Computer Management | Local Users and Groups | Users as shown in the screenshot. Here a user LS_User has been created as shown. His password will be created at the same time.
For this user to access resources on SQL Server Express with Windows Authentication he or she must have login rights to the database on the server. Usually this login can be created by the SQL Server Administrator in the SQL Server Management Studio (SSMS).
LightSwitch Project with Windows Authentication
When Windows authetication is chosen, Microsoft LightSwitch application uses the credentials used by Windows for authenticating its users. Now we create a LightSwitch application with administrator's privileges (run as Administrator from program shortcut). 1. Start LightSwitch program as administrator. 2. Create a LightSwitch VB Project to use Windows Authentication (here the project name is AuthenWindows8). 3. Connect to SQL Server 2008 and attach the Northwind database to get the Products entity. 4. Create a screen EditableProductsGrid based on Editable Data Grid screen template.
[ 269 ]
Authentication and Authorization in Microsoft LightSwitch
5. Configure the application to be authenticated by Windows authentication in the same manner as seen earlier for Forms authentication or, as shown next:
6. Verify that the screen can be displayed. 7. Write codes for the CanDelete, CanInsert, and CanUpdate methods of the Products entity as in the previous section (results of all these are set to FALSE when the permission is set as in the application). If you are not sure, download the projects AuthenWindows8 or AuthenWindows8_CSharp project from the Packt website. This scenario is also present in the Permission Elevation of server code section. Note that you need not go back to the Write Code drop-down handle to pick the code, you can do it directly in the code window as shown in the next screenshot:
[ 270 ]
Chapter 8
8. When you run the application, you would get a display as shown:
Clearly the Update permission returns false for each of the Edit, Insert, and Delete operations and these buttons are grayed out.
[ 271 ]
Authentication and Authorization in Microsoft LightSwitch
User testing the WindowsAuthenticationVB
Although debug permission allows us to test in the Microsoft LS IDE without stepping out of it, we will test here with a user login. When the application is published, you could test it as well from the deployed application (this is the usual way). 1. Login as user (LS_User and use the password that you created earlier while creating the Windows user in Computer Management). 2. Open LightSwitch and open the project created earlier (since this is the only project with Windows Authentication, this is the only project you see in the LightSwitch IDE). 3. If your login is correctly configured, you should be able to retrieve objects and display the EditableProductsGrid screen as shown here:
Associating Permissions with roles
Roles are associated with permissions and the user who is assigned a role can have those permissions. While the permissions are created in the designer, associating roles with permissions or, assigning users to roles is carried out in the running application by an application administrator or, one who has the administrator's permissions. The Users or Roles created in the IDE are for testing purposes. When the application is deployed, the Users or Roles created in the IDE will not be present in the access control (security) database. After an application is deployed, the database administrator can run a query to find the roles and permissions in the RolePermissions table as shown in the next screenshot for a deployed application called ThreeTierForms.
[ 272 ]
Chapter 8
Permission elevation of server code
Elevating permission of server code was added in Beta 2. This is an override of what has been set in the design. Permission elevation is a temporary power (permission given to a user to assume higher permission than he is usually permitted to) given to a user to assign himself other permissions only effective during the save operation. This is therefore a temporary transient set of permissions he can have to address the following business requirements: User may need to carry out other operations which are not permitted to him normally. Trying to give this user all these permissions on a permanent basis defeats the security basis of the business and also trying to temporarily provide a substitute user with higher permission will have logistic problem as resources have to be added. LighSwitch application can elevate the permissions of the current user during the save operation by the following API's as seen in the Object Browser: Public Shared Function AddPermissions(user As Microsoft.LightSwitch. Security.IUser, ParamArray permissionIds() As String) As System. IDisposable Member of Microsoft.LightSwitch.Security.Server.UserExtensions
[ 273 ]
Authentication and Authorization in Microsoft LightSwitch
As seen in the API call, he can assume an array of permissions. And in C # this is as follows: Microsoft.LightSwitch.Security.Server.UserExtensions. AddPermissions(this Microsoft.LightSwitch.Security.IUser, params System.String[])
In addition to adding permissions you can also remove permissions as seen in this Object Browser code for VB.NET. Public Shared Function RemovePermissions(user As Microsoft. LightSwitch.Security.IUser, ParamArray permissionIds() As String) As System.IDisposable Member of Microsoft.LightSwitch.Security.Server.UserExtensions
And in C # this is, Microsoft.LightSwitch.Security.Server.UserExtensions. RemovePermissions(this Microsoft.LightSwitch.Security.IUser, System. Collections.Generic.IEnumerable)
Elevating the permission example
We consider the scenario of a user who has no permission to Insert, Edit, or Remove from a database using a screen, based on the Editable Grid screen template. Using the following code, you disallow the user to carry out the preceding operations who does not have these permissions. Private Sub Shippers_CanUpdate(ByRef result As Boolean) If Application.Current.User.HasPermission(Permissions. CanUpdate) Then result = True Else result = False End If End Sub Private Sub Shippers_CanInsert(ByRef result As Boolean) If Application.Current.User.HasPermission(Permissions. CanInsert) Then result = True Else result = False End If End Sub
[ 274 ]
Chapter 8 Private Sub Shippers_CanDelete(ByRef result As Boolean) If Application.Current.User.HasPermission(Permissions. CanDelete) Then result = True Else result = False End If End Sub
The user (the Test User in debug) who has the following application access permissions shown in the next screenshot can only Insert but can neither Edit nor Remove.
Now suddenly your staff member who would have modified the table content using the Update permission is unavailable and you want the person with the preceding permission (Insert) to take care of a single edit in the table. Let's say you want him to change the telephone number of the supplier with the SupplierID=1 as the supplier has moved to another location. Normally the preceding user cannot handle this because in his screen the Edit button is disabled as shown. The display shows the data from the Shippers table in the Northwind in an Editable Grid screen.
[ 275 ]
Authentication and Authorization in Microsoft LightSwitch
This is where the Permission Elevation comes in. Since the user can insert data, he injects a bit of code into the procedure during saving the data to the server, that is, he intercepts the Save pipe-line (it is instructive to see the DataService.vb or DataService.cs code in the projects) and injects the code as shown here: Private Sub Shippers_Inserting(entity As Shipper) If Application.Current.User.HasPermission (Permissions.CanUpdate) Then Application.Current.User.AddPermissions (Permissions.CanUpdate) Dim tel = (From s In Me.DataWorkspace.NorthwindData. Shippers Where s.Phone = "503-555-9831" Select s).FirstOrDefault tel.Phone = "203-123-5897" End If End Sub
The code determines if the user has a certain specific permission and if he does not possess that permission, the needed permission gets added in the highlighted API call. As you can see this is just a one-time use during the save operation. Since this is an override of the procedure when the user clicks on the Insert button, the dialog for inserting data will be presented and after making the insert operation, the inserted data gets added to the screen. Now the user hits the Save button and the preceding code enters the action and updates the value of the Phone field for the supplier. As you can see from the API, it is a user extension. A more elaborate example is provided in the reference section. The code for the preceding in C # as well as the full project can be downloaded from the Packt website.
User Management
User management is carried out in a running application using the administrative screen which is visible to the administrator of the application. A running application is a deployed application. Microsoft LightSwitch has the capability to deploy the application to both desktop; the web, and the Windows Azure Cloud. This ability of the application created once which can be deployed to desktop and/or web, is one of its very attractive features. While deployment is described in greater detail in the next chapter, a brief description is provided here to wrap up the access permissions and how they figure in the actual running applications. Readers are encouraged to look up the references at the end of the chapter if they need to review deployment options.
[ 276 ]
Chapter 8
User management works the same way in both modes of authentication and is processed only after the user is authenticated. In the case of Forms Authentication, the user details (user name, password, his role, and role's permission) are saved in the asp.net database described previously. In the case of Windows authentication, while users are authenticated using the Windows users' database, their permission and role membership are stored in the asp.net database. The following image shows the administration screen of an application called Admit which is configured for forms authentication. By default the administrator's name will be present to start with and after logging in as an administrator (provided at the time of deployment) he can add users and provide them with username/password. The administrator also creates Role(s) that can have permission(s) and assign the user to the role. The process roughly follows the following steps: 1. In the Users screen create the user, using the Add button (not visible in the image) which enables the details to be typed in on the right side (at this point the role is not configured). 2. In the Roles screen, the administrator creates a role which is in this case Reader who has the View Search Screen permission as shown.
[ 277 ]
Authentication and Authorization in Microsoft LightSwitch
3. After creating the role, the administrator assigns the role to the user as seen in the bottom of the screenshot:
In this manner the administrator first creates the user Jay2 Krish2 and provides him with password and saves the Users screen. Then the administrator moves into the Roles screen and creates the role Reader (using the Add button) and assigns him to have the View Search Screen permission and saves the Roles screen. Finally the administrator returns to the Users screen and assigns the role Reader to user Jay2 Krish2. In the deployed application when the user clicks to run the program, he will be presented with a login screen which requires the username and password as shown here:
[ 278 ]
Chapter 8
The adminsitrator logs in with his credentials supplied at the time of publishing and using the administrator's screen, he creates other users. In the case of Windows authentication depending on his login credentials, the application can be accessed by the administrator and using the administrator's screen he creates users with the condition that they are also Windows Users. In Beta 2, any Windows user will be able to access the application if the application is created to support it as we saw in the beginning (this was also true in Beta2). With the support for any Windows user being able to access the application, however results in the following situation in the design phase of the application: Assuming Windows authentication and making the choice to support all Windows users restricts the application administrator to be able to add only Windows users (using the choice allow any windows users) he will not be able to add a user while designing the application who is not as seen in the following screenshot where this situation is encountered.
[ 279 ]
Authentication and Authorization in Microsoft LightSwitch
We will be looking at User Management in greater detail in the next chapter as most of the management will be carried out in the deployed application. In the case of deployment to the Windows Azure Platform, the access control database will be created in SQL Azure.
Summary
In this chapter, we considered the security-related features in Microsoft LightSwitch. It has built-in support for authentication and authorization. We considered in detail the process of writing code for checking the permissions created in an application created with forms authentication for the permitted objects, screens, entities, queries, and commands. Windows authentication was described briefly. Permission elevation, a feature added in Beta 2, was described with a simple example. User management in LightSwitch application was also described briefly. The interesting feature of checking permissions without stepping out of the IDE was also described. In the next chapter, the deployment of LightSwitch applications to different network topologies will be described.
References
1. LightSwitch Security: http://msdn.microsoft.com/en-us/library/gg481776.aspx
2. Describes how security is implemented in LightSwitch: http://blogs.msdn.com/b/bethmassi/archive/2010/10/06/ implementing-security-in-a-lightswitch-application.aspx
3. Authentication features in LightSwitch and User Management: http://blogs.msdn.com/b/mthalman/archive/2010/08/23/authentication-features-in-visual-studio-lightswitch.aspx
4. Security in role-based application example: http://community.infragistics.com/blogs/mihail_mateev/ archive/2010/10/11/implementing-security-in-a-role-basedlightswitch-applications.aspx
5. MVVM in LightSwitch: http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/24/ This-Is-How-LightSwitch-Does-MVVM.aspx
[ 280 ]
Chapter 8
6. An end-to-end example with domain user implementation: http://www.codeproject.com/KB/silverlight/DNNThingsForSale.aspx ?msg=3938322#xx3938322xx
7. Creating a role-based application: http://msdn.microsoft.com/en-us/library/ff851957.aspx
8. Deploying LightSwitch applications: http://msdn.microsoft.com/en-us/library/ff872288.aspx
[ 281 ]
Deploying LightSwitch Applications After an application is developed and tested it is time to give it to the end users by deploying it suitably so that users can download and install it. Deployment of an application is a relatively difficult process if you consider the diverse technological schemes the user may be constrained to, such as operating system, network topology, platform hardware constraints, software constraints, and many other factors. Microsoft LightSwitch handles both publishing and packaging by the built-in Publish wizard (this was true in Beta 2 as well). This wizard can be called up from within the LightSwitch program after an application is built and tested. In publishing to the cloud Microsoft LightSwitch, the application is deployed to Windows Azure with the data hosted in SQL Azure (this was true in Beta 2 as well). Also, it is now possible for any of the Windows-authenticated users to access an application with Windows authentication without being explicitly added in the application.
Deploying LightSwitch Applications
In addressing the topologies of the servers and clients Microsoft LightSwitch has the following options summarized in the next screenshot (Right-click on Project to pick up Properties and click Application Type tabbed page in the application designer):
Clearly, the three-tier applications can be accessed by Windows' clients such as web browsers to access the Internet. •
A two-tier traditional-type client / server topology wherein the applications run on the end-user's Window's desktop (laptop) while the database and server components run either on the same machine or on a networked computer.
•
A three-tier deployment scheme wherein the application runs on the end-user's Windows desktop (laptop) or on a web browser while the database and server components runs on an Internet Information Services(IIS) server or on Windows Azure, the Microsoft Cloud Platform.
In this chapter, we will consider in detail the following: •
Publish and maintain a two-tier desktop application
•
Publishing to web
•
Publishing a three-tier application [ 284 ]
Chapter 9
•
Publishing the application to Windows Azure
•
Creating a package for publication
It must be noted that the web server, the database server, and the LightSwitch IDE are all on the same Windows 7 machine for these examples.
Publishing and maintaining a two-tier desktop application
Microsoft LightSwitch program has a built-in wizard that takes care of publishing LightSwitch applications after they are built and tested. The program also supports updating the application as well as uninstalling the applications. Herein the steps to publish a desktop (laptop) application are described. We take an application using existing forms authentication created as described in Chapter 8, Authentication and Authorization in Microsoft LightSwitch and publish it as a desktop application. 1. Create the LightSwitch application you want to deploy. 2. Right-click on the application and click on Publish… from the drop-down menu. 3. The LightSwitch Publish Application Wizard appears as shown in the following screenshot:
[ 285 ]
Deploying LightSwitch Applications
We follow the wizard's steps by clicking on the Next button each time it is displayed and enter pertinent and required information. For now, we assume that the application will be published as a desktop application. 4. Accept the default, Desktop and click on Next. 5. The Application Services page of the wizard appears as shown. Herein we make a decision about the topology of deployment:
6. Assume the default to publish on the end user's machine (in this case on the same Windows 7 machine on which the application was created). This machine has the Microsoft LightSwitch program as well as the SQL Server 2008 Express used by the LightSwitch application installed. Click on Next.
[ 286 ]
Chapter 9
7. The Specify Publishing Preference page of the wizard appears as shown:
There are two choices. Publishing directly (assumed for this section) to the database now will install everything needed to the database while the other option will Create a script file to install and configure the database used by the application.
8. Choose the default as shown. Click on Next. The LightSwitch Application Data – SQL Database Connection page of the wizard appears as shown with some connections (both administration and user instance) to the resident SQL Express server:
[ 287 ]
Deploying LightSwitch Applications
9. Click on Create Database Login…. The login screen appears as shown where you enter the administrator's login information. Make sure the password has the allowed and required characters and length. As the same interface may be used with Windows Azure, you may need to follow the acceptable password for Windows Azure. For this example, a password such as $12xyZ23$ was used. Review this link for details regarding acceptable passwords: http://social.
msdn.microsoft.com/Forums/en-US/lightswitchgeneral/thread/ 560a65d7-64e2-4080-9caf-117cf01a8d35/#fb3165ee-8d1c-464e-ab477d9771c0b448.
10. Enter password and click on Create. The password information from the previous screen gets entered into the one shown before that. 11. Click on Next. The Application Administrator page appears as shown wherein you need to enter the credentials for the application's administrator:
[ 288 ]
Chapter 9
12. Click on Next after entering the information. The Install Prerequisites page appears wherein you may have to make a choice of any additional dependencies to install. Herein accept the defaults and click on Next. 13. The Other Connection Information page appears as shown. This is where the data used in the LightSwitch application is originating from (a SQL Server Express database).
14. Click on Next. Signing a XAP file using a test certificate: Using a certificate for signing the XAP (*.xap) file assures the end user that the program is safe to install and that it has not been tampered with. In this section, a test certificate is used and there are two other methods in case you are distributing the application to your clients.
[ 289 ]
Deploying LightSwitch Applications
15. This brings up the Specify a Certificate page of the wizard with three choices as shown. Read why a certificate is needed (follow the link in the window). As security is an important issue for Internet facing applications, a certificate from a trusted authority [Certificate Authority (CA)] is the most appropriate choice. It may be noted that Windows Azure also needs SSL certificates for deploying to the Azure cloud services:
You could use a certificate stored in the computer's store; browse for one (with extension .cer) or to test locally—use a test certificate (this certificate will have a limited lifetime but good enough for testing). A certificate can also be created manually using the MakeCert.exe program on Microsoft SDK as shown in this link: (http://hodentekhelp.blogspot. com/2011/06/how-to-create-certificate-that-can-be.html) 16. Click on the Create a test certificate… button. 17. This brings up a Create Test Certificate window wherein you need to enter a password. 18. Click on OK. The Issued to:, Issued By:, Expiration date fields in the previous image get values and if you need additional information, click the suggested link which brings up the Microsoft Help Viewer 1.1 - Catalog VS_100_EN-US.
[ 290 ]
Chapter 9
Here is an image showing the details of one of the test certificates created in LS:
19. In order to get a certificate from a trusted certification authority (CA), you should get a Code Signing Certificate from the CA. This is a digital certificate and you will have to pay for it depending on how long you want to use it. There are many CAs such as VeriSign, DigiCode, and so on. Please see the references at the end of the chapter. Here is a link to a how-to obtain a certificate post: http://hodentekhelp.blogspot.com/2011/06/how-toobtain-code-signing-certificate.html.
[ 291 ]
Deploying LightSwitch Applications
20. Click on Next. The Publish Summary page displaying the details of the publication and the version number is displayed as shown in the following screenshot:
21. Click on Publish. After some processing the application gets published. The Publish folder may be found in the application's folder if the defaults were accepted at the time of publication (see the Specify Publishing Preference page of the wizard in the beginning).
Installing the application
Once an application is published, you need to install the application before it can used. The steps to install are described in this section. 1. In the application folder, locate the setup.exe file in the Publish folder (the default folder is [LightSwitch Project folder]\Publish) (herein C:\ Users\jay\Documents\Visual Studio 2010\Projects\Beta2) as shown:
[ 292 ]
Chapter 9
2. Double-click on setup.exe file which begins the installation. You will see an Application Install – Security Warning dialog displayed. 3. Click on Install. You will see an Installing window showing the progress of the installation. When the installation is completed your application pops up and an application shortcut is added to the desktop as shown:
The program also gets added to the installed list of programs in the Programs and Features list in the Control Panel. The security database with the database name (same as application name) will be applied to the SQL Express as shown next:
[ 293 ]
Deploying LightSwitch Applications
Note that the Security database which has the same name as the application's project name, has security-related data as well as tables (entities) created in the application. The next image shows a SQL Express database of a VSLS application (but not the data (tables) from SQL Server) with two data sources one from an attached SQL Server database and the other being a table Tests created in the application:
However, you will notice only the administrator of the application is recorded in the database and none of the users/roles that you might have added during design as seen in the two queries. After you login as administrator, you can create users and assign them with roles as discussed in Chapter 8, Authentication and Authorization in Microsoft LightSwitch.
Running the application
Now that the application is installed it is time to test the application. The following steps will run the application: 1. Double-click on the application shortcut installed in the All Programs shown earlier.
[ 294 ]
Chapter 9
Some client/server conversation takes place-after which the application is displayed as shown together with the Windows Security's modal window dialog. The next three steps are not needed (will be needed in Beta2 if you are still using) in the Microsoft LightSwitch 2011 as the Windows Security’s modal window dialog will not be displayed. This Window Security pop-up is a known issue. Review this link: http://social.msdn.microsoft.com/Forums/en-US/ lightswitchgeneral/thread/cb543510-fe9e-4da9941c-44c470ffbce5.
2. Switch to Use another account and enter the credentials of the Computer Owner (this will be different in your case):
3. Click on OK after entering the credentials. The Forms authentication credential input page appears.
[ 295 ]
Deploying LightSwitch Applications
4. Enter the information you entered earlier while publishing (see Application Administrator page of the Publish wizard) and click on Log In. The application is displayed with the user administration as shown:
Adding users
Users with forms authentication can be added by the administrator in this screen by: •
Creating a user in the Users page wherein the User Name, Full Name, and Passwords are provided. This page is saved using the Save button.
•
In the Roles page, a role name is provided and this role will be attached to a permission, and saved using the Save button.
•
Again back in the Users page, the role is assigned to a chosen User and saved using the Save button.
This administrative page is very much like the List and Details screen that you can create in LightSwitch. After creating these users, the users can get into the application and carry out such activities as are permitted for their roles. The buttons View screen and No View Screens in the preceding screenshot were created to test the command execution permissions described in a previous chapter. The Who Is button displays the current logged-in user (current user was tester during design phase of the application).
[ 296 ]
Chapter 9
Publishing updates to the application
You can go back to Microsoft LightSwitch IDE, make modifications as you see fit and then re-publish the application. Second time around you do not need to go through all the steps of the publishing wizard and in fact it takes you to the last step which requires you to just click on the Publish button in the last step. In case you want to make some changes you can go back with the Previous button. Each time you publish the minor version of the application changes by 1 (1.0.0.0 becomes 1.0.1.0). When you run Publish again this window is displayed and all you need to do is click on Publish.
You can also change the language of the application by changing it in the Project Designer's Culture item in the application's General Properties tab in its properties page as shown:
[ 297 ]
Deploying LightSwitch Applications
This setting gets reflected in the application as shown in the displayed page (Culture changed to Japanese):
Deploying the application to another computer
The other computer must be running Windows OS with a SQL Server whose version is 2005 and above and satisfy the requirements for Visual Studio LightSwitch Beta2. Just follow the instructions in the install.htm page of the Publish folder.
Removing the application
The Application can be uninstalled from the control panel's Add / Remove program.
[ 298 ]
Chapter 9
Publishing to Web
The Web application runs on the browser and has no access to the user's computer programs. For the web application, the applications services can be hosted on: •
Local machine
•
IIS Server (local or web hosting company)
•
Windows Azure
Desktop (laptop) applications can be published to: •
Local machine
•
IIS Server
Where do you publish to?
There are two options for publishing. It can be published directly to a remote server or using the zip file of the project created in the Publish folder which can be installed on the server by importing the zip file into the website using the IIS Management Console. •
Create a package (a MS Deploy package that can be deployed manually or using Microsoft Web Deployment Tool) on a disk that can be deployed to a configured server
•
Publish directly to a remote server
Certificate-backed deployment
You need a certificate to deploy the application to make sure that the end user can use it and he/she can make sure it is safe to deploy. Assurance that software is in no-way tampered between the time the author wrote the program and the time it is deployed is very important. This assurance is provided by the certificate. Please review links to the Code Signing resources in the Reference section. Publishing creates a file with XAP extension and a certificate is needed to sign this file. There are three options: •
Create a test certificate that you can immediately use (for testing)
•
Browse for a certificate and look for a certificate (a .cer file) from a third party (from CA)
•
Select a certificate from this computer's store (all certificates on the computer)
[ 299 ]
Deploying LightSwitch Applications
Publishing a three-tier application
Before you start publishing make sure you have the following installed on your computer especially, if you have used earlier versions of any of these: •
Microsoft Visual Studio LightSwitch Beta 2 - ENU
•
Microsoft Visual Studio LightSwitch Beta 2 Deployment Prerequisites
•
Microsoft Visual Studio 2010 Service Pack 1
•
Microsoft SQL Server 2008 R2 Management Objects
These should be installed when you run the Microsoft LightSwitch Beta 2. However, depending on the state of the computer some of these softwares may not get installed correctly. Sometimes you may need to uninstall and install them again. Most of these (which are up-to-date) can be installed by running the Web Platform Installer which can be located at: http://www.microsoft.com/web/downloads/ platform.aspx. All of the above are applicable if you are still using Beta 2. If you are using the Release Version (Microsoft LightSwitch 2010) then you will have realized by this time that you need to completely remove Beta 2 before you install Microsoft LightSwitch 2011.
Publishing a three-tier application with Forms Authentication In this section, we describe publishing an application configured for Forms Authentication to the IIS 7 server on the same machine. This provides access to the intranet clients:
1. Create a LS application which gets its entity (entities) from a table on a SQL Server database as described earlier. Herein, the ThreeTierForms application gets it data from a recently released SQL Express 2008 R2 to which a table from the Northwind database has been copied over. 2. In the Designer's page, click on Application Type tab and choose the option Web for Client and for Application Server choose to host the application on an IIS Server. 3. Make sure you have an IIS 7 running on the computer if you are publishing to IIS on the local machine. On Windows 7 Ultimate used for this book, the IIS 7 is installed and running. [ 300 ]
Chapter 9
If it is not running, you should start the following services on the machine: °
World Wide Web Publishing Service
°
Web Management Service It is also possible to directly publish to another computer running IIS and store the publishing-related files in the local machine. In this case, the website will be created on the remote server and it should have the prerequisites to host the LightSwitch application. Read How to: Deploy 3-tier application in Microsoft Help-Viewer 1.1 (F1).
4. Create a Search screen based on the entity (it is the Supplier's table from the Northwind database) 5. In the Access Control tab of the Designer, choose the Forms Authentication option. 6. Click on F5 and make sure the application runs and that you can access the screen. 7. Right-click on the application and pick Publish… The Welcome to the LightSwitch Publish Wizard page appears as shown.
8. In the Client Configuration tabbed page, select Web if it is not already chosen. 9. Click on Next.
[ 301 ]
Deploying LightSwitch Applications
10. In the Application Services page, choose the default. This will be, IIS Server with the IIS Server has the LightSwitch Deployment Prerequisites installed option checked. 11. Click on Next. The Publish Output page appears as shown:
12. Choose to remotely publish and enter the Service URL as shown. The Site/ Application is picked up by the program. Note that you need the Microsoft Web Deployment Tool (http://www.iis. net/download/WebDeploy) service. 13. Click on Next. The Database Connection's page appears as shown where the administrator and user connection are present. 14. For specifying the User Connection, click on Create Database Login. The login page appears.
[ 302 ]
Chapter 9
15. Enter the login name and a password. The SQL Express must be configured for SQL Server Authentication as shown in the following screenshot:
16. Confirm the password and click on Create. 17. In the Authentication Page that comes up next, choose to create the Application Administrator's User Name, Full Name, and Password similar to the way you created them for the two-tier application earlier. 18. Click on Next. The Other Connection Information page appears, you makes changes to the database connection using the ellipsis button. Here the default from the application is accepted. Herein Hodentek3\R2D2 is a SQL Server Express 2008 R2 and the FromSQLExpress database has just one table dbo.Suppliers from a Northwind database on another server copied over:
[ 303 ]
Deploying LightSwitch Applications
19. Click on Next and choose a test certificate as in the case of two-tier deployment. 20. Click on Next to review the Summary page. 21. Click on Publish. After some processing, the application gets published to the IIS's default website if you have not specified any other site.
Displaying the application
Deployment related files are also available in the application folder. Project Folder\ Publish as shown here: (C:\Users\jay\Documents\Visual Studio 2010\ Projects\Beta2\ThreeTierForms\ThreeTierForms)
The needed files are hosted on the IIS 7 server as seen in the next screenshot. These can be hosted on IIS 5.1 that you find on some versions of Windows XP.
[ 304 ]
Chapter 9
The .xap file, ThreeTierForms.Client.xap is in the Web folder and it is displayed using a Silverlight control as seen in this snippet chopped from the default.html page:
[ 305 ]
Deploying LightSwitch Applications
The page with the login form is displayed when you browse the default.html page from the IIS default site (the browser must have the Silverlight add-in installed). Clicking on Log In after entering the User Name and Password displays the web page as shown next:
Publishing a three-tier application with Windows Authentication
This is very similar to the previous exercise, except that the authentication choice is made as shown in the following screenshot for a project named ThreeTierWin:
[ 306 ]
Chapter 9
If you have published a three-tier application in Beta2, the same can be opened in Microsoft LightSwitch 2011, and after following the guide lines at the end of this chapter, you can re-publish again without any problems. Please review items related to Chapter 9 in the Appendix A. This can be downloaded from the Packt site. In Beta 2, the second choice that allows access to any authenticated Windows User was added. However, you can also add USERS/ROLES in the running application. The publication starts off by clicking the Publish button as in the previous case and proceeds pretty much along the same lines except that you will be asked to provide login information. You should see the authentication you have chosen in the summary page before the application is published. When the application is published, you can access the application from browsing the default.htm page, as shown next, which requires authentication. Any authenticated user is able to access:
[ 307 ]
Deploying LightSwitch Applications
This can now be accessed by any user of the machine. If a Windows Domain user accesses, he may have already entered this information.
Publishing application to Windows Azure
This is a new addition to LS in Beta 2, which was promised in Beta 1. In addition to desktop and Web, publishing to Windows Azure was strategically important to Microsoft and it came as no surprise that this was promised in Beta 1. This will be of interest to not only departmental applications but also to users who want to make applications available on the Internet with the three outstanding business advantages: Terms Of Availability (TOA), Total Cost Of Ownership (TCO), and Time To Value (TTV). If you are new to Cloud Platforms, read this article "State of Cloud Applications and Platforms: The Cloud Adopters' View", B.Narasimhan and R.Nichols, COMPUTER, IEEE Computer Society, March 2011, Pages 24-28. In this section, deploying a LS application created in the Beta2 program to an existing Windows Azure hosting site is described. The following are the basic steps in deploying the application to Windows Azure: 1. Creating the application to be deployed to Windows Azure. 2. Obtaining the subscription to Windows Azure and configure the hosting site. 3. Preparing the application for Forms Authentication and deployment to Windows Azure. 4. Publishing to Windows Azure hosting site using the wizard in LS IDE.
Creating the application to be deployed to Windows Azure
As we will be using data coming from a SQL Azure to be used by a LightSwitch application hosted on Windows Azure, we need to create our data or have access to data on SQL Azure. The necessary steps are described in the following points. 1. Create a LS application with data coming from a SQL Azure database as described in: http://www.packtpub.com/article/microsoft-azure. 2. Create a search screen based on the entity(ies). In this section, a database RoundObject on the SQL Azure has been used to create the Search screen. The application when run, displays the screen. It is empty but editable.
[ 308 ]
Chapter 9
In the following section, the procedure to obtain subscription to Windows Azure is described.
Obtaining the subscription to Windows Azure and configuring the hosting site In early 2010, Microsoft Windows Azure Platform went into production and has seen many enhancements. The early portal has been replaced by a new portal for accessing the services. If you are new to Windows Azure, please visit this link: http://www.microsoft.com/windowsazure/windowsazure/ and get a free subscription.
In this section, it is assumed that you have a subscription that allows you to use the Windows Azure services. The author's book deals extensively with the practical aspects of Windows Azure in general and SQL Azure in particular: (https://www.
packtpub.com/microsoft-sql-azure-enterprise-application-development/ book) and is highly recommended. The author's Windows Azure subscription
details are shown in the following screenshot (new portal). The old portal is still available here: https://sql.azure.com/ProjectViewer.aspx.
[ 309 ]
Deploying LightSwitch Applications
With reference to the subscription the following are important: •
Subscription ID needed in deploying
•
Hosting site: This is where the LS application is hosted (Use URL to access)
•
Storage Account: Some deployment-related info is stored
•
SQL Azure instance: The application user database is created here
The Production / Staging slots of the hosting site are shown in the following screenshot as displayed in the old portal. The DeployToAzure LS application created in the previous section will be deployed to the Staging slot of the hosting site:
[ 310 ]
Chapter 9
Preparing the application for Forms Authentication and deployment to Windows Azure
Windows Azure deployed applications are meant for Internet access and therefore Forms Authentication where username/password are stored on a database with the administrator creating users and roles as described in Chapter 8, Authentication and Authorization in Microsoft LightSwitch is most appropriate. This will be a three-tier web application hosted on the Windows Azure's Staging slot which can be promoted to production with the click of a mouse. Configuring the application for Forms Authentication was explained earlier and in the Application Type tabbed page of DeployToAzure Designer, choose Web for the Client and for Application Server choose Host Application Services using Windows Azure. The choices made in this screen prepare the ground for deploying the application to Windows Azure.
Publishing to Windows Azure hosting site The application will now be published to Windows Azure: 1. Click on Publish…. The Welcome to the LightSwitch Publish Wizard screen appears pointing to the Client Configuration. 2. Choose Web and click on Next at the bottom of the screen. The Application Services page of the wizard appears with three options. 3. Choose Windows Azure and click on Next (note that although these choices were made earlier the user has to go through these steps again. Perhaps this will be improved in the release version).
[ 311 ]
Deploying LightSwitch Applications
The Connect to Windows Azure page is displayed as shown. Herein two pieces of information are necessary: the Subscription ID that you can obtain once you have a subscription (review the screen related to subscription shown earlier). The other information is the certificate necessary to identify the project to Windows Azure which can be generated from this screen:
The Subscription ID is shown partially masked. In the present example, although some certificates are uploaded a new certificate will be created using the drop-down shown next:
[ 312 ]
Chapter 9
4. Click on . The New Management Certificate window appears as shown:
5. Type in a friendly name and click on OK. Herein, TestDeploy was used. Click on OK. The certificate generated is entered as shown here. Friendly name is indeed easier to remember!
In place of a Microsoft LightSwitch created certificate, a Code Signing Certificate from a CA can also be used. For Software distribution, a Code Signing Certificate from a CA is recommended. To protect applications published to the Windows Azure you may need to use SSL certificates.
[ 313 ]
Deploying LightSwitch Applications
6. As directed in the previous screenshots, click on Copy Path. The copied path pasted on a text editor such as Notepad is: C:\Users\jay\AppData\Local\ Temp\flmbjm5u.cer. 7. Go to the Windows Azure Portal (http://Windows.Azure.com). This shows the author's site:
You need to have a subscription to carry out any of these tasks as discussed earlier.
8. Click on Manage My API Certificates. This opens the user interface to upload a file displayed as shown:
9. Browse and locate the file with extension:.cer (C:\Users\jay\AppData\ Local\Temp\flmbjm5u.cer) and click on Upload. The certificate gets added to the subscription's list of installed certificates as shown with a CN Name:
[ 314 ]
Chapter 9
10. Now in the LS IDE, click on Next to move on to the Azure Service Configuration. The Select the Azure Service and Storage page of the wizard appears as shown. Note that before this page is displayed you will see a series of messages appear while establishing a connection to Windows Azure.
11. Use the refresh buttons and drop-down handles to access the Service, Storage, and Environment. This task produces the following display for the author's Azure account. If the subscription is right and the connection is established these should appear in the drop-down menus:
[ 315 ]
Deploying LightSwitch Applications
12. Click on Next and move on to the Security Settings page of the wizard as shown. Make sure you read the information on this page:
13. Use the drop-down to pull up the certificates as shown and choose the one you created earlier or create a new one. 14. Choose to . The New Self-signed Certificate window is displayed as shown:
15. Fill in the fields and save it to a location of your choice. Here TestMar26.pfx was saved to a location on the hard drive. [ 316 ]
Chapter 9
16. Click on OK to save this page and click on the Upload a PFX file… button. Upload a PFX file to the window that appears. 17. Browse and locate the PFX file you saved earlier, enter the password you used and click on OK. 18. Click on Next to move on to the Database Connections page. This page is for the Administrator and User databases. The LightSwitch Application Data – SQL Database Connection page is displayed as shown:
19. To specify administrator connection click on the ellipsis (…) button. 20. The window appears as shown. Enter the details of the SQL Azure server instant details (review Chapter 3, Accessing Data from a VSLS Application). Provide a name for the database (here it is the same as the project). Use the Server Principals credentials. The Test button may not work as the database is not yet present. 21. Click on OK. The same information appears for the User window below as well. But change the login by clicking on Create Database Login…. 22. The Create Database Login window appears. 23. The following info was used: User name: oliver and Password: #$olive23$#.
[ 317 ]
Deploying LightSwitch Applications
24. Click on Create. 25. Click on Next to move on to Forms Authentication dialog where you must provide a username and password for the Administrator. The Forms authentication admin info window appears as shown. This is very similar to the earlier two-tier deployment with forms authentication. 26. After filling in the information, click on Next. Here the following was used: °
User Name: Admin
°
Full Name: Admin LS
°
Password: $12nimda34$
Note that these passwords are acceptable in length and mix of characters. 27. Click on Next to open the page as shown. Read the information on this page. A hosted Windows Azure project can obtain data from the SQL Azure in the same datacenter under some conditions. As to what these conditions are, please read the SQL Azure documentation.
28. Click on Next and in the Specify a Certificate page leave the checkbox unchecked (choose not to create a certificate). Click on Next. 29. The Summary page appears with some deployment information such as version, server, and so on. 30. Click on Publish. The program starts cranking, but even in this Beta the processing is very slow, much slower than deploying to IIS. If everything is quite right the publishing process succeeds and if there is already an application hosted on the Staging site it gets deleted and the LightSwitch application gets hosted as seen next: [ 318 ]
Chapter 9
The following screenshot shows the administrator's screen displayed in the browser:
[ 319 ]
Deploying LightSwitch Applications
When you access the staging site URL you will see There is a problem with this website's security certificate message in IE 9. This is because the certificate is not trusted. Click on Continue to this website link. This will then display the Login forms page. In Mozilla you will get This connection is untrusted. Click on I understand the risks. In the Add Security Exception window displayed, click on Confirm Security Exception.
Creating a package for publication
After creating an application and verifying it works in the IDE, proceed with the deployment. These are the steps in the deployment: 1. Client configuration: Choose Desktop. 2. Application Server configuration: Choose Local. 3. Publish Out: Choose Create a package on disc. What should the website be named? TestAzure (defaults to project name). Where should the package be created: Defaults to Publish folder (project's sub-folder) folder location on hard drive: C:\Users\jay\Documents\Visual Studio 2010\Projects\Beta2\TestAzure\TestAzure\Publish\. 4. Generate a new database called: (Defaults to project name) 5. Authentication: Yes, Create Application Admin at this time. 6. Specify a Certificate. 7. Enter a password for new file ClientGenerated_TemporaryKey.pfx Sample password: $%12a$. 8. Go to next step after reviewing the certificate information 9. Summary: This will have the following information: °
Application Name: TestAzure
°
Application Version: 1.0.0.0
°
Client Configuration: Desktop
°
Application Server: IIS Server
[ 320 ]
Chapter 9
°
Authentication: Forms Authentication
°
Database: New Database
10. Click on Publish. Result after publishing: This creates a TestAzure.zip file in the Publish sub-folder of the project. Follow the instructions as described in the following link: http://msdn.microsoft.com/en-us/library/gg615263.aspx.
In order to install this you need to have the Web Deployment Tool installed on the IIS 7 which will provide access to the Import Application Package wizard that helps you through the installation.
Summary
This chapter described in detail the various options the users have in deploying their applications to the desktop, the Internet Information Services server and the Windows Azure platform. This enables both desktop and browser-based access to LS applications. The examples covers both Windows and Forms-based Authentication schemes. In order to deploy to Windows Azure, the user must have a subscription to the service and there are subscriptions available for evaluation (as to the details please visit Microsoft's Azure website). As the Azure platform is targeted in this Beta, the passwords must follow the requirements for Azure platform access. Readers should download and read the Appendix A written mostly to allay the concerns of the reader regarding using projects created in Beta 2. Most of the Beta 2 created projects have been recompiled and tested in Microsoft LightSwitch 2011. In the next chapter, trouble shooting LS applications, extensions, Custom Controls and latest developments, and so on will be covered.
About using project download from the Packt site The deployment scenarios in this chapter were written at the time of Beta2. These projects would still compile and work. However, when it comes to deployment you may have to carry out the following after bringing up the project in the VSLS 2010 IDE:
[ 321 ]
Deploying LightSwitch Applications
1. If there is an external database you are connecting to make sure the data source is refreshed. 2. Build and debug (F5) the project. 3. Publish again as the test certificate may be stale. Create a new Administrator password.
Reference
1. Deploying LightSwitch Applications: http://msdn.microsoft.com/en-us/library/ff872288.aspx
2. Deployment Options, a video briefing: http://msdn.microsoft.com/en-us/lightswitch/gg274326
3. Publishing to Windows Azure: http://blogs.msdn.com/b/lightswitch/archive/2011/03/18/step-bystep-how-to-publish-to-windows-azure-andy-kung.aspx
4. Deploying three-tier LightSwitch Applications for browser clients: http://blogs.infragistics.com/blogs/mihail_mateev/ archive/2010/10/09/deploying-browser-client-3-tierapplications-with-visual-studio-lightswitch.aspx
5. Code signing: http://en.wikipedia.org/wiki/Code_signing
6. Introduction to code signing: http://msdn.microsoft.com/en-us/library/ms537361.aspx
7. Acquire a Code Signing Certificate: http://technet.microsoft.com/en-us/library/cc732597%28WS.10%29. aspx
8. Signing and Checking Code with Authenticode: http://msdn.microsoft.com/en-us/library/ms537364%28v=vs.85%29. aspx
9. VeriSign code signing certificate: http://www.verisign.com/code-signing/
[ 322 ]
Chapter 9
10. DigiCode Software signing: http://www.digi-sign.com/digi-code
11. What is MakeCert.exe and how to use it with LightSwitch? http://hodentekHelp.blogspot.com
12. Windows Azure Services: http://www.microsoft.com/windowsazure/
13. Microsoft SQL Azure Enterprise Application Development, the chapter on deployment (cloud-to-cloud): https://www.packtpub.com/microsoft-sql-azure-enterpriseapplication-development/book
14. Web Deployment Tool: http://www.iis.net/download/WebDeploy
[ 323 ]
Troubleshooting, Debugging, Custom Controls, and Extensions In this chapter, we look at a number of items that did not fit into the theme of previous chapters. This includes some of the content that became available after the release of Beta 2. There are no breaking changes from Beta 2 to Microsoft LightSwitch 2011. Some of these items are nonetheless very important for applications as they fulfill a need that is not available in the IDE. The following topics are considered in this chapter: •
Troubleshooting
•
Debugging
•
Adding custom controls to LightSwitch
•
Extensions
Troubleshooting
Troubleshooting is an exercise that starts right from the time you download or install software and continues till it is deployed and used. Troubleshooting is a reality of any software and the vendors build-in enough documentation and support to carry out this all important task.
Troubleshooting, Debugging, Custom Controls, and Extensions
Problems encountered in installing and running applications have been documented based on user experiences and the LightSwitch team's responses and suggested workarounds. Please refer to this post: http://social.msdn.microsoft.com/
Forums/en-US/lightswitchgeneral/thread/7ca9ddf6-27da-487d-8383d8dad3a612ca in the LightSwitch forum which also happens to be the source for
any future undocumented problems and workaround. Since LightSwitch Beta2 download also downloads and installs a number of needed components, pay close attention to the last item in the preceding post which lists all necessary software and their versions. If any of those items are missing, the installation may have a problem. On Windows 7 OS (32-bit) some of the problems encountered during installation are also available here: http://hodentek.blogspot.com/search?q=LightSwitch.
Also make sure you read the release notes that accompany the download as known issues with the software are described. If you face problem related to SQL Express while building your project which happens sometimes due to SLQ Express corruption, review the following link: http://hodentek.blogspot.com/2011/07/installing-microsoftlightswitch-rtm.html
Debugging LightSwitch applications
Often errors creep into code and finding the errors and fixing them is the task handled by debugging. Most programs have a debug mode where you halt a program at a location and see what is happening. The Help file that you can access from Microsoft LightSwitch has a section completely devoted to debugging. This information closely follows the online article Debugging Tools in Microsoft LightSwitch available here: http://msdn.microsoft.com/en-us/library/ff851983.aspx. Most of the items in the Debug menu are common to most editions of Visual Studio and can be used in LightSwitch as well. The following section describes the menu items in the Debug menu.
LightSwitch Debug Menu
The Debug menu shown here is the starting point for debugging LightSwitch applications and the process of debugging starts when you hit F5.
[ 326 ]
Chapter 10
The Windows menu item Debug gives access to the three basic windows—Immediate Window, Output window, and Breakpoints window shown here useful in reviewing the debug operation. These windows must be familiar to users who have used other Visual Studio products.
The Start Debugging (F5) is the item you hit when you run the application in the debug mode. Step Into (F8) and Step Over (Shift+F8) are items you use when the program stops at a breakpoint. These are all familiar menu items that we have seen earlier in the book.
[ 327 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
The Exceptions menu items brings up a window showing available support for possible exceptions. You have the choice for customizing your application at debug time using the following window:
Some of these are chosen by default, as shown here for the Managed Debugging Assistants, which you might have encountered in the other chapters.
[ 328 ]
Chapter 10
In the next section of the Debug menu, you will find the Toggle Breakpoint, New Breakpoint, and Delete All Breakpoints. We have also seen the use of these in earlier chapters. The New Breakpoint (Cntrl+B) brings up its own window as shown here where you can specify where the breakpoint will occur in a function:
The DataTips, Watch window, and the QuickWatch dialog box tools are available in all editions of Visual Studio. These tools are well suited to debugging LightSwitch programs as well. The following example shows some of the tools as applied to a program which has some problems. The query in LINQ used in most of the Microsoft LightSwitch queries is not evaluated when it is created or declared. It's only when the query is used or executed, it is evaluated and will have a value. Query execution in LINQ can be immediate or deferred: http://msdn.microsoft.com/en-us/library/bb384667. aspx#Y11300. In this section, we will be looking at one such query. 1. Create a query TeatQry in a LightSwitch project attaching external data to create a Customers entity from Northwind database on an existing SQL Server Express. 2. In the query's Properties window, click on Edit Additional Query Code link and open the code editor window which opens the template for the Preprocess_Query() method.
[ 329 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
3. Another way, as described in the chapter on queries, is to access the code page from the Write Code menu in the query Editor as shown here:
Insert the code shown in the Preprocess_Query () to query the Customer's entity. Namespace LightSwitchApplication Public Class NorthwindDataService Private Sub TestQry_PreprocessQuery(ByRef _ query As System.Linq.IQueryable(Of LightSwitchApplication.Customer)) query = From c In Customers Order By c.City Select c.CompanyName, c.ContactName End Sub End Class End Namespace
The code builds in VB (comes up with immediate errors in C#) but there are errors in the code. The query is not evaluated when it is created, but only when it is used. We will create a screen based on Search Data Screen. [ 330 ]
Chapter 10
4. Create the screen SearchTestQry using the TestQry as the source. 5. Highlight query in the preceding code and from the Debug menu click on Toggle Breakpoint. The code page immediately shows that something is not quite right as shown here:
We have seen how this LINQ query works in the chapter on queries. The underlined element with the wiggly blue underline is the one with the problem. It should be changed to query. This is easily changed from the intellisense drop-down after the word 'In'. This will insert a breakpoint for the query. However, if the query has a problem, an exception will be thrown at which point DataTips window and/or Watch windows may be added. We assume that Customer is not changed to query as yet.
[ 331 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
6. Click Debug | Start Debugging (F5). The program begins to run and when the program hits the breakpoint, the following is displayed if you hover on query. The following screenshot shows the expanded query variable to show the details. This is the DataTips window described earlier. If you need to see the code hidden by the expanded DataTip window, hold down the Ctrl key and the DataTip becomes transparent. When you move away from the query the DataTip window disappears. You can keep the DataTip to remain till you desire to close it by clicking on the 'pin' icon. The next image is displaying the expanded +query.
Note that before the breakpoint is reached there is an exclamation icon added to the breakpoint and when it is reached, there is an arrow inside the toggle breakpoint.
[ 332 ]
Chapter 10
Right-click query in the preceding code which opens up a menu as shown:
From here, you can access a number of tools such as Add Watch, QuickWatch, Pin to Source; many other breakpoint related options; stepping into specific portions of the code, and so on. Click on Debug | Continue. The program throws an argument unhandled exception (Common Language Runtime System exception) message as shown in the following screenshot:
[ 333 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
The reason for the previous message is that the LINQ in LightSwitch does not support returning individual fields. It returns the whole set. Instead of specifying the individual fields we need to select the whole set. Now after making the correction, if you debug once again, you will see that the program throws another exception (InvalidCastException) and this following message:
This is because we have not changed Customers to query. Once we do this, we get to display the screen. Note that, even after changing this, if there are loading errors the query may not return results, in which case you may try to run the query again. Microsoft Help Viewer 1.1 shipped with Microsoft LightSwitch Beta2 which is accessed from Help | View Help provides the complete documentation available at this time. While previously debugging managed code was described, problems may also arise in deployed applications such as problems communicating with the server. Microsoft LightSwitch debugs both the SL-based client runtime code and the server code that runs on the local test server during F5. The Help documentation details enabling diagnostics in LightSwitch deployed applications. Please refer to the section How to: Enable diagnostics in Help File 1.1. In the previous section, we looked at debugging CLR code using the built-in Visual Studio tools available in LightSwitch Beta 2. Here we review debugging the SilverLight applications. The following URL provides a starting point Debugging, error handling, and exceptions in SilverLight applications: http://msdn. microsoft.com/en-us/library/cc838261%28v=vs.95%29.aspx. An overview of debugging SilverLight applications is available here: http://msdn.microsoft. com/en-us/library/cc838267(VS.95).aspx. Microsoft LightSwitch desktop application is an out-of-browser SilverLight application and the debugging of out-of-browser applications as outlined here should be used: [ 334 ]
Chapter 10
http://msdn.microsoft.com/enus/library/dd550721(v=vs.95). aspx#debugging_outofbrowser_applications. Since Microsoft LightSwitch is
a Silverlight 4.0 application, you have command-line support for debugging outof-browser applications using the sllauncher.exe. The file Sllauncher.exe can be found here: C:\Program Files\Microsoft SilverLight. The arguments to be passed to Sllauncher.exe are shown in the following screenshot:
With this executable, you can run an XAP file in an out-of-browser window as if it has already been installed. After this you need to attach a debugger to this window process. The messages from sllauncher.exe are available from this resource: http://blogs.msdn.com/b/silverlight_sdk/archive/2010/04/10/ sllauncher-error-messages.aspx
For attaching a debugger in the IDE, you must have installed Visual Studio 2010 SP1. Alternately, if you have Visual Studio 2008 Professional or above installed, you could "Attach a debugger" to a process after opening a project in the IDE. However, you may try using the command-line program devenv.exe. Look up the help file for this command on your computer as shown here. This is just a suggestion as the author has not used this method: C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE> devenv /?
[ 335 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
In the help file, you will find the command-line to attach the process to the debugger as shown in the next screenshot:
Adding custom controls to LightSwitch
Earlier we have seen that LightSwitch comes with a number of controls routinely used in various business applications such as buttons; text boxes; list boxes, and so on. However, it is also possible to bring in user controls that can be added to the LightSwitch screens for enhanced experience. In order to use user controls in LightSwitch, it will be necessary to install Silverlight 4 tools that contain all the necessary library files. The Silverlight tools can be downloaded from here: http://silverlight.codeplex.com/releases/ view/43528. Get both the Silverlight_4_Toolkit_April_2010.msi and the Silverlight 4 Toolkit April 2010.zip. Depending on what you are going to use, you should have all the necessary files. Install the msi file and unzip the zip file. Since it is downloaded from a web location, you may get a message as shown: "This assembly may have been downloaded from the Web. If an assembly has been downloaded from the Web, it is flagged by Windows as being a Web file, even if it resides on the local computer. This may prevent it from being used in your project. You can change this designation by changing the file properties. Only unblock assemblies that you trust. See: http://go.microsoft.com/fwlink/ ?LinkId=179545." [ 336 ]
Chapter 10
As suggested in the preceding link, you need to unblock the files that you are going to use in LightSwitch application. In this section, a simple example of bringing in a user control and incorporating it into a LightSwitch screen will be described.
Creating a User Control
In here we will create a User Control, using Windows Presentation Foundation (WPF). We create a XAML file for the control. Since we will not be doing any data binding for the control, we will use a project without data for now. For details of SilverLight controls please refer to this link: http://weblogs.asp.net/scottgu/
pages/silverlight-tutorial-part-6-using-user-controls-to-implementmaster-detail-scenarios.aspx
1. Create a LightSwitch application with or without connecting to a data source. We will be adding a user control to the application. In the file view of the application, right-click the Client node and add a new item as shown:
2. In the Add | New Item… window, add the Text1.txt file, but rename it as TestCntrl.xaml. We will be adding a xaml file to the Client. This file will have just some text and a picture to keep it simple.
[ 337 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
3. Click and open the TestCntrl.xaml file and add the code as shown in the following screenshot. 4. This screenshot shows both the code and its rendering in design (after adding a picture and some text described in the next few steps):
5. Right-click the Client and click Existing Item…. 6. Browse and find a suitable image (the one shown here was an image file on the computer). With these added, the Client node appears as shown:
[ 338 ]
Chapter 10
7. Add a reference to the System.Windows.Controls.Toolkit by right-clicking the Client's References node and locating the previous assembly. 8. Build the application. 9. Create an empty screen, based on Search Data screen. 10. Right-click Search as shown in the Search screen.
11. Click Add Custom Control….
[ 339 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
12. The Add Custom Control window is displayed as shown (node is expanded in the following screenshot):
13. Click TestCntrl in the window and click OK. 14. This user control will be available in the screen layout of the Search screen as shown:
[ 340 ]
Chapter 10
15. Build and display the Search screen as shown here.
While the previous procedure described adding a non-database-bound user control, the same procedure may be used for controls binding to data. For example, for binding a Chart Control to data derived from a WCF RIA Data, please follow this link: http://
blogs.msdn.com/b/lightswitch/archive/2011/04/08/how-do-i-display-achart-built-on-aggregated-data-eric-erhardt.aspx. A similar example using data bound to a pie-chart user control is found here: http://community.visualbasic.it/alessandroenglish/archive/2010/11/26/37377.aspx
Extensions
Extensions provide means to implement features which are not found in the out-of-the box Microsoft LightSwitch Product. The point to extensibility is that this is a much needed item if one wants to do things that are not possible in the vanilla Microsoft LightSwitch IDE. Users in the forums complained about lack of customization from screens to controls, and from data types to themes. The answers to these complaints lie in the extensions that you can create for the application. Extensibility is to build upon what exists in the Visual Studio eco-systems like bringing in a SilverLight control and bind it to a VSLS application. There is whole lot of information on SilverLight controls and there are already many ways of bringing data into VSLS application and extensibility brings these together in a more productive manner. In short, the VSLS IDE can leverage objects built using SilverLight very easily and there is no need to create separate controls for VSLS. [ 341 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
The following are some of the points to keep in mind while creating extensions or using extensions developed by third-party: •
Microsoft Extensibility Framework (MEF) is the basis for LightSwitch Extensions and provides a model-based architecture. Extensions combine .NET/SilverLight assemblies and are packaged together. These packages are used by the Visual Studio application.
•
Multiple extensions can be combined in a solution.
•
Extensions can be part of design time experience, run time experience or both.
•
Extensions are added at design time.
•
At design time the control extension is added in the same way built-in controls are added independent of the type of extension.
•
Extensions built by third-parties are available in the Visual Studio Gallery (http://visualstudiogallery.msdn.microsoft.com/) can be consumed by the application. The central point to bring in the extension is via the Gallery. Third-party extensions may need separate licenses. Review this link for the recent extensions as of this writing, http://hodentek.blogspot. com/2011/07/expanding-universe-of-microsoft-visual.html.
•
You install Extensions using Tools | Extension Manager...
Once you add-in the extension, they will appear in the Extension tab of the Project Property as shown here:
[ 342 ]
Chapter 10
The Blank Extension is the one created in the example in this chapter. The Document Toolkit for LightSwitch is created by a third-party (First Floor Software, see, http://firstfloorsoftware.com/blog/document-toolkit-forlightswitch-rtm/) which allows you to view different kinds of document formats (DOC, PDF, and so on) and the LightSwitch Utilities (Filter Control for VSLS). The Excel Importer for LightSwitch extension can be downloaded from here: http://code.msdn.microsoft.com/Excel-Importer-for-Visual-61dd4a90. Implementing extensions requires at least Visual Studio 2010 Professional version installed. In the preparation of this section an evaluation version was used. Implementing extensions is primarily targeted at developers with experience and third-party vendors and would require considerable experience which may be beyond novice users (the most targeted by audience for LightSwitch). Make sure to watch this extensibility video here: http://www.microsoft.com/showcase/en/us/ details/cb5280af-3156-487f-8aa1-d4727294cec3. The documentation for the extensibility of LightSwitch applications came in the form of a recipe which may be downloaded here which will be hereafter referred to as the CookBook, http://blogs.msdn.com/b/lightswitch/archive/2011/03/16/ lightswitch-beta-2-extensibility-cookbook.aspx. This CookBook provides templates and guidance for implementing extensions to Microsoft LightSwitch. One of the suggestions made for those who are interested in creating extensions was not to start from an application of type VSIX, but to use the templates presented in the cookbook. The Theme extension described in the next section is entirely drawn from the suggested recipe. The reason Theme extension is described here is because it is the easiest way to create and demonstrate the various steps involved in creating an extension. Here is a quote from the CookBook that describes to some extent how the extensions fit in with existing Microsoft technology: "LightSwitch uses the Microsoft Extensibility Framework (MEF) which allows a developer to build a LightSwitch application using a model centric architecture approach. Extensions are a combination of .NET/Silverlight assemblies and metadata that are packaged together and consumed by a Visual Studio LightSwitch application. Extensions can provide a design or runtime experience, or both, depending on the extension type."
[ 343 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
There are several changes needed to implement extensions in Microsoft LightSwitch applications which is shown in the next image taken from the Cookbook.
The preceding image shows various folders that you will find in a VSLS application. The text associated with a each of the elements clearly states how they interact with the Framework. For example, if you need to change the displayed UI's appearance, you need to work with WPF-based resource dictionary. But on the other hand, if you want to debug, you need the SilverLight-based resource dictionary as we see in the theme extension example. We also see that this resource is to be provided to the Client and hence a Client class is used. Extensions are created by developers and third-party vendors. You create an extension using the project template available in Visual Studio (New Project | Extensibility (templates)). However, in the next section, the BlankExtension. zip template is downloaded from the same URL as the Cookbook here: http://
download.microsoft.com/download/9/6/3/96358FFC-4CB5-4E7E-967BE5738000672D/BlankExtension.zip. These templates appropriately package all
that is required by the various components (in the File View) of LightSwitch needed to create extensions. The ZIP file consists of the following:
[ 344 ]
Chapter 10
The types of extensions that can be developed using CookBook templates are as follows: •
Shell
•
Theme
•
Control
•
Custom Data Source
•
Business Type
•
Screen Template
In the next section, we look at implementing a Theme extension of a LightSwitch application.
Theme extension using CookBook recipe
Make sure you read the CookBook in its entirety before you work on extensions. In order to implement the theme extension, you need to download the BlankExtension.zip file mentioned earlier.
Setting up the right environment You need the following: •
Visual Studio 2010 Professional or higher version
•
Visual Studio 2010 Service Pack 1
•
Visual Studio 2010 SDK
•
Visual Studio LightSwitch
•
LightSwitch Blank Extension Solution
Unzip the downloaded file to a location of your choice.
Creating a theme extension
In this section, we create a theme extension which when used in a LightSwitch application provides a theme other than the default theme.
[ 345 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
1. Open the solution file in LightSwitch with Administrator rights. The Blank Solution appears as shown:
2. Click open the BlankPresentation.lsml file and add the as shown: [ 346 ]
Chapter 10
Herein, a has been added with a display name and a description. Since this is a resource that the extension will be using, it needs to be properly referenced in the IDE. This should find its place in the Blank_Resources.resx file shown in the next screenshot:
Presently it has no resource but a default String1 as shown here:
1. Modify the previous extension by adding theme-related items in the model fragment. Type in exactly as shown here in the following screenshot:
[ 347 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
Next, we need to modify the BlankModule.cs file so as to address the theme programmatically. Presently this file has nothing except references to the BlankExtension as shown here:
2. Modify the code as shown in the next screenshot adding theme-related item. 3. The theme class and version numbers are referenced in the module.
[ 348 ]
Chapter 10
So far we made modifications to the Blank.Common project that affects both client and server. Since theme affects the visual appearance of the client, we will make changes to the Blank.Client project shown in its default as shown here:
1. Add a folder Themes to the Blank.Client and a folder within the Themes folder named MyTheme. MyTheme is the folder where the theme that we are going to create is added.
2. Add a class file class1.cs to MyTheme folder. 3. Change class1.cs to MyTheme.cs using the following code: This is the default Class1.cs file: using using using using using using using using using using
System; System.Net; System.Windows; System.Windows.Controls; System.Windows.Documents; System.Windows.Ink; System.Windows.Input; System.Windows.Media; System.Windows.Media.Animation; System.Windows.Shapes;
[ 349 ]
Troubleshooting, Debugging, Custom Controls, and Extensions namespace Blank.Themes.MyTheme { public class MyTheme { } }
Replace the above after renaming it MyTheme.cs and the code shown next. This is MyTheme.cs: using using using using
System; Microsoft.LightSwitch.Theming; System.ComponentModel.Composition; Blank;
namespace Blank.Themes.MyTheme { [Export(typeof(ITheme))] [Theme(BlankModule.MyTheme.GlobalName, BlankModule.MyTheme. Version)] public class MyTheme : ITheme { public string Id { get { return BlankModule.MyTheme.GlobalName; } } public string Version { get { return BlankModule.MyTheme.Version; } } public Uri ColorAndFontScheme { get { return new Uri(@"/Blank.Client;component/Themes/ MyTheme/MyThemeVisualPalette.xaml", UriKind.Relative); } } } }
[ 350 ]
Chapter 10
You may get an error message as shown here:
If you now build the project, this error goes away. 4. Add a Silverlight.Resource Dictionary file from installed Silverlight template files and rename it MyThemeVisualPalette.xaml. This is the SilverLight file:
5. Add the following code: Replace the preceding code with the content of Theme10.doc as described in the document from the Packt website download for Chapter 10, Troubleshooting, Debugging, Custom Controls, and Extensions. The following two changes were made to the preceding default document to alter some color changes to the background for the navigation shell and navigation: [ 351 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
The Blank.Client now appears as shown:
6. Build the project and the extension will be created which will be found in the project directory (C:\Users\jay\Documents\Visual Studio 2010\ Projects\Beta2\BlankExtension\Blank.Vsix\bin\Release) as shown: 7. Blank.Vsix.vsix is the final extension file.
Installing the extension
After creating the extension, it must be installed. It can be locally installed or installed on another machine if the necessary files are taken to another machine. In this section, we will see how it is installed. Besides this method, there are other ways to install as well. Please refer to the CookBook. 1. Double-click on the Blank.Vsix.vsix file to launch the extension installer as shown:
[ 352 ]
Chapter 10
2. Click Install. The extension gets installed as shown in the Extension Manager screen which can be accessed from Tools | Extension Manager….
Note that you may disable and uninstall from the extension manager window. Once it is in the IDE it can be used.
[ 353 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
Using the extension
We will see how this is used in a LightSwitch application in this section. 1. Create a LightSwitch application project. Herein TestTheme2 project. Open the TestTheme2 Designer as shown:
2. Verify that your Blank Extension is available in the list of Extensions and the Use in new projects is enabled. 3. Click on General Properties to display the page.
4. If MyTheme is not chosen, choose it from the drop-down list. 5. Build and run the program and bring up the screen as shown.
[ 354 ]
Chapter 10
6. The theme will be applied to all screens:
Note that the changes we made to the XAML file are reflected in the screen. Without the extension we would have the shell designed for the default theme.
Changing the design of the theme
Changes can be made to the XAML file and the BlankExtension project must be rebuilt. In order to implement the changes, the existing extension must be removed and the modified extension installed before the changes become effective. Also note, if your Visual Studio is open, when you installed the extension, you need to restart Visual Studio instance to make the extension available. It is also possible to circumvent this process by starting an experimental instance of the LightSwitch program as detailed in this section. This was suggested by Justin Anderson in this following post: http://social.msdn.microsoft.com/Forums/
en-US/lsextensibility/thread/6a9828a7-5c6b-44ac-9251-c0fb7c9f12a0/ #7db0b982-4a36-42f5-b029-a7dab1052d1e.
1. Make some changes to the XAML file (highlighted colors replaced the default values).
[ 355 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
2. The following changes were made:
3. Build the project. 4. Bring up the Properties page of the Blank.Vsix project and change the Debug options as shown:
By using these options, you will be starting another instance of the program when you hit F5 and in the externally-launched program the changes you made will be visible although you have not yet installed the version after the changes. This would make the build process somewhat slower.
[ 356 ]
Chapter 10
5. Set Blank.Vsix as the start-up project and hit F5. 6. An Experimental Instance is launched as shown. The BlankExtension is also running and is shown behind the Experimental Instance.
7. Create a new project TestTheme3 and verify that the theme is MyTheme. 8. Build and run the project. 9. The screen with the changes appears as shown. The Ribbon color is clearly pink but the changes to the Tab are barely seen:
[ 357 ]
Troubleshooting, Debugging, Custom Controls, and Extensions
Summary
This chapter described Troubleshooting, Custom Controls, and Extensions. Starting from installation to runtime trouble can surface at any point. Most of the tools supported in the Visual Studio LightSwitch IDE are described in some detail. Some references to troubleshooting connectivity and installation are given but are by no means exhaustive. Adding spice to the application and creating something not available in the IDE are always on the wish list. Custom Controls and extensions provide points of departure to provide what is not available. It is also a source of great creativity for the developers.
References
1. This is the link where you find the latest news and examples related to Microsoft LightSwitch: http://blogs.msdn.com/b/lightswitch/
2. Downloading Beta2, demos, videos are found here: http://msdn.microsoft.com/en-US/lightswitch
3. The forum is where you can interact and find information from other LightSwitch users, interested parties, and Microsoft LightSwitch team members. There are two forums—one is general and the other for extensions: http://social.msdn.microsoft.com/Forums/en-us/category/ vslightswitch
4. Many of the important resources for LightSwitch are found here including walkthroughs, end-to-end examples, articles, and so on: http://social.msdn.microsoft.com/Search/en-US?query=codeplex%20 and%20Lightswitch&ac=3
5. For those who follow and learn from videos this is the best: http://blogs.msdn.com/b/bethmassi/archive/2009/07/01/new-howdo-i-video-series-released.aspx
[ 358 ]
Index Symbols
C
_CanDelete method 266 _CanExecute () method 260 _CanInsert method 266 _CanRead method 266 _CanUpdate method 266
Can_View_Employees permission 268 CanExecute Code 259 choice list, data entities about 139 CreateNewSalesPerson 139, 140 display name column 139 selecting 139 value column 139 code, targeting entity data, inserting in entity by code 221-224 default values, inserting in entity 217-221 entity, validating 225, 226 writing 217 code, writing examples 216 general notions 214 in Code Editor window 215 need for 215 Code editor window 214 code pages organizing 161 components, WCF RIA service 55 computed field, entities adding 144-146 edit method used 146-149 connector downloading 82 custom controls adding, to LightSwitch 336 Customers entity 170 customization mode, Microsoft LightSwitch screens 128
A AddPropertyError () method 158 ADO.NET connection 77 ADO.NET Entity Data Model 57 ADO.NET Entity Framework 29 ADO.NET entity model support 135 application security 247 architecture, VSLS 12 Authen8_CSharp project 254 authentication schemes about 248, 249 Forms authentication 248 Windows authentication 248 AutoCompleteBox using, for setting parameter value 199-206
B built-in validation, entity field validation about 150 validation rules 151 validation rules, setting up 151-154 business logic, VSLS Beta 2 application architecture 30
custom queries data, inserting 244, 245 data, searching from related tables 240-243 query with selection and sorting, with code 239 query with text search 240 records, finding by navigation 243 simple query 236-238 writing, code used 235 custom validation, entity field validation about 155 code, writing 155-158 custom code 158, 159 custom code, testing 160
D data accessing, from WCF RIA Service 87-89 accessing, on database 67-70 accessing, on SharePoint 2010 86 filtering 180-184 data, accessing on database connector, downloading 82 connector, installing 82 SQL Azure, connecting to 76-78 SQL Server 2005, connecting to 71-74 SQL Server 2008 R2 Express, connecting to 78 SQL Server 2011 (in CTP1), connecting to 74-76 SQL Server Compact, connecting to 79-81 MySQL databases, connecting to 82 Data Access Service, VSLS Beta 2 application architecture 29 databases installing 21 installing, on SQL Express 2008 22, 23 samples, downloading 22 data entities choice list 138 creating 57, 138 creating, external data source used 65 default e-mail domain, setting up 140, 141 fields, adding 138 fields, deleting 138 fields, modifying 138
money field, entering 142 Northwind database tables, review 65, 66 phone properties, setting up 143, 144 data model about 216 DataWorkSpace 216 DataSource Entity Set 216 Query Method 216 Data Storage tier, VSLS Beta 2 application architecture 29 DataTips 329 data types, VSLS applications 61 DataWorkSpace DataSource 216 debugging, LightSwitch applications about 326 debug menu 326 debug menu, VSLS Beta 2 IDE 37 debug permission 253 default e-mail domain, data entities setting up 140, 141
E Editable Grid Screen template 179 edit menu, VSLS Beta 2 IDE 36 entities, VSLS about 135 code pages, organizing 161 computed field, adding 144-146 data entities, creating 138 Entity Designer 136 entity field validation 149 properties panel 137 relational features 161 relationships, establishing from attached source 164-170 Entity Designer about 136 Entity Designer menu 136 example 137 menu items 136 Entity Designer menu 136, 137 entity field validation about 149 built-in validation 150
[ 360 ]
custom validation 155 DataService validation rules 150 types 150 validation rules, establishing 150 EntityValidationResultsBuilder class 156 Execute Code 259 extensions about 341 business type 345 changes, implementing 343 control 345 custom data source 345 implementing 343, 344 screen template 345 shell 345 theme 345 theme extension 343 types 345 Extension tab about 342 Blank Extension 343 external data attaching to 66, 67
F file menu, VSLS Beta 2 IDE 36 File View, LightSwitch Project accessing 48 ApplicationDefinition.lsml file 48 client node 48 common node 48 data node 48 server node 48 FromSQLXpress database tables 165
H HRApp Silverlight application 55
I installation VSLS 15 intellisense technology about 214 reference link 214
L LightSwitch applications deployment application, publishing to Windows Azure 308 package, creating for publication 320, 321 three-tier application, publishing 300 two-tier desktop application, publishing 285, 286 web application 299 LightSwitch debug menu about 326 delete all breakpoints 329 exceptions 328 new breakpoint 329 start debugging menu 327 step into 327 step over 327 toggle breakpoint 329 windows menu 327 LightSwitch Project creating 39-41 exploring 39 project node 42 properties page, TestApplication Designer 43 TestApplication Designer 41 LightSwitch Project, TestApplication Designer Access Control tabbed page 45 Application Type tabbed page 46, 47 Do not enable authentication, Access Control tabbed page 46 Extensions tabbed page 44 Forms authentication, Access Control tabbed page 46 General tabbed page 43 Screen Navigation tabbed page 44, 45 Use Windows authentication, Access Control tabbed page 46 LINQ (Language Integrated Query) 216 LINQER 217 LINQPAD 217 LINQ query executing 329-335
[ 361 ]
list and details screen about 115 screen layout 116 working 116 Logic tier, VSLS Beta 2 application architecture 29 LS application, publishing to Windows Azure about 308 creating 308 hosting site, configuring 309, 310 preparing, for deployment to Windows Azure 311 preparing, for Forms Authentication 311 publishing, on hosting site 311-318 subscription to Windows Azure, obtaining 309, 310 LSQueries Designer 180
M main menu, VSLS Beta 2 IDE about 35 debug menu 37 edit menu 36 options drop-down menu 38 tools menu 37 view menu 36 many-to-many relationship, entities establishing 172, 173 Microsoft Extensibility Framework (MEF) 342, 343 Microsoft LightSwitch Beta2 screens 95 Microsoft LightSwitch screens. See also screens about 95 creating, from scratch 117 customizing, at run time 128-131 exporting, to Excel 126, 127 export to Excel, disabling 128 general features 96 list and details screen 115 new data screen 96 search data screen 108 Microsoft Visual Studio LightSwitch. See VSLS
Model View ViewModel (MVVM) 217 money field, data entities entering 142 properties 142 MSLS VB Project creating 217 multiple entities, querying about 194-199 AutoCompleteBox, for setting parameter value 199-206 static spans, using 206, 208 MySQL databases connecting to 82-85 MyThemeVisualPalette.xaml 351
N new data screen about 96 binding, to data source 98-101 creating 96, 97 displaying 103-108 screen properties 102 New Data Screen template 98 Northwind database tables review 65, 66 NwindData data source 167
O Object Browser 214 ODATA Protocol 29
P package creating, for publication 320 permission elevation 273 permissions about 249 associating, with roles 272 permission example, elevating 274-276 permission of serve code, elevating 273 permissions, with Form authentication about 250 bug, in query 265 button, adding 256-261 creating 250-255 [ 362 ]
entity 265-268 query, creating based on another query 264, 265 query, running 262 saving 256 user permission, to run query 262, 263 permissions, with Windows authentication about 268, 269 LightSwitch Project 269- 271 WindowsAuthenticationVB, user testing 272 phone properties, data entities formatting 143 setting up 143, 144 Preprocess_Query() method 330 Presentation tier, VSLS Beta 2 application architecture about 27 ContentItems 27 Content Objects 28 screens 27 shell 27 properties panel, entities appearance node 137 validation node 137
Q queries execution 177 parameterizing 177 post-processing 177 pre-processing 177 querying 208, 210 Query_CanExecute () 262 Query1_CanExecute() code 265 Query Designer about 175 architecture 176 query operations 177 query execution, in LINQ 329 querying, VSLS about 175 architectural details 176 multiple entities, querying 193-199 query, querying 208, 210
single entity, querying 178, 179 query operations 177 QuickWatch dialog box tool 329
R R2D2 SQL Server 165 relationships, between entities establishing 161-164 establishing, from attached source 164-170 many-to-many relationship, establishing 172, 173 workaround 170-172 Rich Internet Application (RIA) 54
S Salesman.vb code 146 Salesman entity 137 Salesman Property, new data screen about 100 Address Editor 101 Command Bar 100 Custom Control 101 Rows Layout 101 Screen Command Bar 100 Screen Content Layout 101 SaveChanges_CanExecute() method 266 screen, creating from scratch about 117 AutoCompleteBox, adding 120-123 combo-box, displaying 123-126 combo-box, testing 123-126 data item, adding 119, 120 group, adding 118 unbound search data screen, creating 117, 118 screen-related code default behaviour, overriding 232 default values, entering using codes with screens 227-231 screen elements, accessing 233-235 writing 226 screen data management 94 screen layout 94 screen object 94 screen properties, new data screen 102
[ 363 ]
screens. See also Microsoft LightSwitch screens about 93 architectural details 95 MVVM pattern 94 screen data management 94 screen layout 94 screen object 94 search data screen about 108 creating 108-111 data, modifying 113-115 functionality, testing 112, 113 SearchEmployee_Activated() event 254 SharePoint 2010 data, accessing on 86 Silverlight application URL 10 Silverlight Business Application about 55 features 55 MainPage.xaml 56 single entity, querying about 178, 179 columns, selecting for displaying 184, 185 data, filtering 179-184 list, sorting 186, 187 parameter used 189-193 process 178 SQL Azure about 76 connecting to 76-78 SQL Express 2008 databases, installing 22, 23 SQL Server 2005 connecting 71-74 data source, updating 74 SQL Server 2008 R2 Express connecting to 78 SQL Server 2011 (in CTP1) connecting to 74-76 SQL Server Compact connecting to 79-81 SQL Server Management Studio (SSMS) 269 start menu, VSLS Beta 2 IDE about 31-33
Community and Learning Resources link 34 Get Started and Latest News tabs 34 Introduction to LightSwitch link 34 Latest News tabbed page 35 static spans about 206 using, in querying 206-208 System.Windows.Controls.Toolkit 339
T table, VSLS applications creating 58, 59 salesman table 60 TestAppDatas_CanDelete() 266 TestApplication Designer, LightSwitch Project Access Control tabbed page 45 Application Type tabbed page 46, 47 Do not enable authentication, Access Control tabbed page 46 Extensions tabbed page 44 Forms authentication, Access Control tabbed page 46 General tabbed page 43 Screen Navigation tabbed page 44, 45 Use Windows authentication, Access Control tabbed page 46 TestCntrl.xaml file 338 theme extension about 345 Cook Book recipe used 345 creating 345-351 design, changing 355-357 environment, setting up 345 installing 352, 353 using 354 three-tier application displaying 304-306 publishing 300 publishing, with Forms authentication 300-304 publishing, with Windows authentication 306-308 tools menu, VSLS Beta 2 IDE 37 troubleshooting 325 [ 364 ]
two-tier desktop application deploying, to another computer 298 installing 292-294 maintaining 285-292 publishing 285-292 removing 298 running 294, 296 updates, publishing 297 users, adding 296
U user control creating 337-341 user management 276-280
V view menu, VSLS Beta 2 IDE 36 VSLS about 9 access permission 249 application security 247 architecture 12 authentication 247 authentication schemes 248 authorization 247 Beta 2 application architecture 25 Beta 2 IDE 31 code, writing 213, 214 custom controls, adding 336 databases, installing 21 data model and screens 216 entities 135 extensions 341, 342 features 9, 10 hardware requirements 15 installation issues, troubleshooting 19 installing 15 installing, on Windows 7 15-18 installing, on Windows XP 19, 21 items, downloading 21 querying 175 screens 93 system requirements 15 target audience 10 troubleshooting 325 user control, creating 337-341
user management 276-280 VSLS applications data entities, creating 57 data entities, creating using external data source 65 data types 61 debugging 326 external data, attaching to 66, 67 File View 47 publishing, to Windows Azure 308 reference links 24 salesman table, creating 60-65 table, creating 58-60 VSLS application screens 94 VSLS Beta 2 application architecture about 25 business logic 30 Data Access Service 29 Data Storage tier 26, 30 hosting process 31 Logic tier 26, 29 Presentation tier 26 VSLS Beta 2 IDE about 31 main menu 35, 36 start page 31-33 VSLS designers about 12 query designer 13 Screen designer 14
W Watch window 329 WCF RIA Domain Services 29 WCF RIA Service about 54 components 55 data, accessing on 87, 89 web application certificate-backed deployment 299 publishing 299 Windows 7 VSLS, installing 15-18 Windows Presentation Foundation (WPF) 337 Windows XP VSLS, installing 19, 20 [ 365 ]
Thank you for buying
Microsoft Visual Studio LightSwitch Business Application Development About Packt Publishing
Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions. Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done. Packt books are more specific and less general than the IT books you have seen in the past. Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't. Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike. For more information, please visit our website: www.packtpub.com.
About Packt Enterprise
In 2010, Packt launched two new brands, Packt Enterprise and Packt Open Source, in order to continue its focus on specialization. This book is part of the Packt Enterprise brand, home to books published on enterprise software – software created by major vendors, including (but not limited to) IBM, Microsoft and Oracle, often for use in other corporations. Its titles will offer information relevant to a range of users of this software, including administrators, developers, architects, and end users.
Writing for Packt
We welcome all inquiries from people who are interested in authoring. Book proposals should be sent to
[email protected]. If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you.
We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise.
Microsoft Visio 2010 Business Process Diagramming and Validation ISBN: 978-1-84968-014-1
Paperback: 344 pages
Create custom Validation Rules for structured diagrams and increase the accuracy of your business information with Visio 2010 Premium Edition 1.
Optimize your business information visualization by mastering out-of-the-box, structured diagram functionality with features like the Basic and Cross-Functional Flowcharts
2.
Create and analyze custom Validation Rules for structured diagrams using Visio Premium
Microsoft SharePoint 2010 End User Guide: Business Performance Enhancement ISBN: 978-1-84968-066-0
Paperback: 424 pages
A from-the-trenches tutorial filled with hints, tips, and real world best practices for applying SharePoint 2010 to your business 1.
Designed to offer applicable, no-coding solutions to dramatically enhance the performance of your business
2.
Excel at SharePoint intranet functionality to have the most impact on you and your team
3.
Drastically enhance your End user SharePoint functionality experience
Please check www.PacktPub.com for information on our titles