• Beth Massi - Sharing the goodness that is VB

    LightSwitch Screen Tips: Scrollbars and Splitters

    • 0 Comments

    Often times in business applications we have a lot of information to present on a screen, and depending on the user’s screen resolution that information may scroll off the page. Visual Studio LightSwitch’s screen templates are set to automatically apply a vertical scrollbar to screens when this happens, however, sometimes we rather allow the user to resize sections of the screen how they see fit. It’s common in screen design to use splitter controls to do this. Splitters are a useful UI feature where the width or height of a control on the screen can be modified to show more or less information. In this post I’ll show you how you can enable splitter controls to appear in LightSwitch as well as control how scrollbars behave.

    Create Your Screen

    First create a screen with all the information you want to display. For this example I will use the ContactDetails screens we created in the Address Book Sample. In this example, Contacts have many Addresses, PhoneNumbers and EmailAddresses. By default, LightSwitch will place the Contact fields at the top of the screen with a Tab Control of three DataGrids representing the children.

    Here is what the screen looks like:

    image

    And here is the content tree for the screen:

    image

    Scrollbars in LightSwitch

    Imagine that over time our contacts get more and more email addresses, phone numbers, and/or addresses. If the user’s screen resolution is low (or the size of the application shell is not maximized) then LightSwitch will place a vertical scrollbar on the screen by default (I added the green box for clarity ;-))

    image

    This is controlled by selecting the topmost Rows Layout and under the Appearance properties you will see “Vertical Scroll Enabled” checked. Notice there is also a “Horizontal Scroll Enabled” property you can use to enable horizontal scrollbars when needed. All group controls in LightSwitch have these properties (i.e. Rows Layout, Columns Layout, Table Layout)

    image

    Leaving this checked however, means that the user cannot see all the email addresses and the First & Last name fields at the same time. There are a couple things we can do here. One is we can disable vertical scroll of the screen. Once we do that LightSwitch will automatically place the scrollbar into the grid itself instead.

    image

    But what if we aren’t using a DataGrid (or list control) below the list of fields? Or what if we want the user to choose how many rows they need to view at a time? In those cases, we can allow the user to resize the panels of information using a splitter.

    Adding a Horizontal Splitter

    In order to provide this functionality, we can place a splitter between the list of fields at the top and the tab control below. While the application is running in debug mode, click the “Design Screen” at the top-right of the shell to open Customization Mode. Select the nested Rows Layout control for Contact and under the sizing properties you will see a check box “Is Row Resizable”.

    image

    Check that and then click Save to save your changes. You will now see a splitter control that you can use to resize the top and bottom panels.

    image

    In this case you probably also want to set a minimum and maximum height of this Rows Layout panel so that the user doesn’t use the splitter to wipe the grid completely off the screen. Right now if you take and drag the splitter off the screen, the grid will completely disappear. In order to stop this, you can set the MinHeight and MaxHeight properties. You can enable a scroll bar to appear in the top panel when needed by checking “Vertical Scroll Enabled” as well.

    image

    Adding Vertical Splitters

    You can also add vertical splitters in a similar way. Instead of displaying DataGrids in separate tabs, say we want to display them side-by-side. Open customization mode again and change the Tabs Layout to a Columns Layout.

    image

    Then select each DataGrid and in the Sizing properties, check “Is Column Resizable”.

    image

    Now you can resize all of the columns containing the DataGrids. The DataGrids will automatically put a horizontal scrollbar at the bottom so users can see all the fields as necessary.

    image

    Another Example

    Splitters and scrollbars really start helping you out when you have sections of information and/or commands that you want to allow the user to resize. Here I modified the Contoso Construction example to allow resizing of the tab control of commands on the left and the information on the right.

    image 

    Wrap Up

    There are a lot of things you can do with the LightSwitch Screen designer in order to provide completely customized layouts. Controlling scrollbars and adding splitters is just another way you can achieve what you want. For more tips and tricks on customizing screens see:

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    LightSwitch Community & Content Rollup–January 2012

    • 3 Comments

    Last Fall I started posting a rollup of interesting community happenings, content, samples and extensions popping up around Visual Studio LightSwitch. If you missed those rollups you can check them out here:

    Looks like folks took a few well-deserved days to ramp back into the groove after the holidays (including myself). But there were still a lot of awesome things around LightSwitch this month, especially the number of submissions The Code Project had in the LightSwitch Star Contest. A lot of really interesting applications and some great case studies for LightSwitch as well as some for Azure. Check them out…

    “LightSwitch Star” Contest

    “LightSwitch Star” Contest on CodeProject

    In November The Code Project launched the “LightSwitch Star” contest. They’re looking for apps that show off the most productivity in a business as well as apps that use extensions in a unique, innovative way. Prizes are given away each month. Soon they will announce the January winners as well as the two grand prize winners of an ASUS U31SD-DH31 Laptop!

    Check out all the submission we had in January and make sure to log onto Code Project and vote for your favorites. Here’s a breakdown of the 13 apps that were submitted in January (see all 34 apps that have been submitted here). There are some very creative “business apps” here – like a campaign manager for Dungeons & Dragons!

    There are a lot of really interesting real-world LightSwitch production applications that were submitted. Some departmental apps, a few personal apps, some enterprise apps as well as a couple start-up companies. There are also some great case studies here for Azure, in particular:

    Developer Center Updates

    Learn Page Updates

    In December I kicked off a series aimed at beginner developers just getting started with LightSwitch and was featured in the MSDN Flash Newsletter. In January we updated the Learn page of the Developer Center to feature this series and it’s been getting some great traffic!

    image

    I also released the completed source code for the sample we build in the series: Beginning LightSwitch - Address Book Sample

    How Do I Videos – Learning Made Easier

    We also updated all the How Do I video pages to show the sequential list of videos so that you can easily get to the previous and next videos in the series. This makes it a lot easier to navigate through the over 20 videos in the correct order. Just click into any video page like this one and you will see the video navigator at the bottom of the page.

    image

    Notable Content this Month

    Here’s some more of the fun things the team and community released in January.

    Extensions released in January (see all 73 of them here!):

    The team also released a control extension sample that you can learn from. Check out the announcement on the team blog:  Many-to-Many Control Released!

    Build your own extensions by visiting the LightSwitch Extensibility page on the LightSwitch Developer Center.

    Team Articles:
    Community Articles:
    Presentations:
    Samples (see all of them here):
    LightSwitch Team Community Sites

    The Visual Studio LightSwitch Facebook Page has been increasing in activity thanks to you all. Become a fan! Have fun and interact with us on our wall. Check out the cool stories and resources.

    Also here are some other places you can find the LightSwitch team:

    LightSwitch MSDN Forums
    LightSwitch Developer Center
    LightSwitch Team Blog
    LightSwitch on Twitter (@VSLightSwitch, #VisualStudio #LightSwitch)

    Join Us!

    The community has been using the hash tag #LightSwitch on twitter when posting stuff so it’s easier for me to catch it (although this is a common English word so you may end up with a few weird ones ;-)). Join the conversation! And if I missed anything please add a comment to the bottom of this post and let us know!

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Calling Web Services to Validate Data in Visual Studio LightSwitch

    • 1 Comments

    Very often in business applications we need to validate data through another service. I’m not talking about validating the format of data entered – this is very simple to do in LightSwitch -- I’m talking about validating the meaning of the data. For instance, you may need to validate not just the format of an email address (which LightSwitch handles automatically for you) but you also want to verify that the email address is real. Another common example is physical Address validation in order to make sure that a postal address is real before you send packages to it.

    In this post I’m going to show you how you can call web services when validating LightSwitch data. I’m going to use the Address Book sample and implement an Address validator that calls a service to verify the data.

    Where Do We Call the Service?

    In Visual Studio LightSwitch there are a few places where you can place code to validate entities. There are Property_Validate methods and there are Entity_Validate methods. Property_Validate methods run first on the client and then on the server and are good for checking the format of data entered, doing any comparisons to other properties, or manipulating the data based on conditions stored in the entity itself or its related entities. Usually you want to put your validation code here so that users get immediate feedback of any errors before the data is submitted to the server. These methods are contained on the entity classes themselves. (For more detailed information on the LightSwitch Validation Framework see: Overview of Data Validation in LightSwitch Applications)

    The Entity_Validate methods only run on the server and are contained in the ApplicationDataService class. This is the perfect place to call an external validation service because it avoids having clients calling external services directly -- instead the LightSwitch middle-tier makes the call. This gives you finer control over your network traffic. Client applications may only be allowed to connect to your intranet internally but you can allow external traffic to the server managing the external connection in one place.

    Calling Web Services

    There are a lot of services out there for validating all sorts of data and each service has a different set of requirements. Typically I prefer REST-ful services so that you can make a simple http request (GET) and get some data back. However, you can also add service references like ASMX and WCF services as well. It’s all going to depend on the service you use so you’ll need to refer to their specific documentation.

    To add a service reference to a LightSwitch application, first flip to File View in the Solution Explorer, right-click on the Server project and then select Add Service Reference…

    image

    Enter the service URL and the service proxy classes will be generated for you. You can then call these from server code you write on the ApplicationDataService just like you would in any other application that has a service reference. In the case of calling REST-ful services that return XML feeds, you can simply construct the URL to call and examine the results. Let’s see how to do that.

    Address Book Example

    In this sample we have an Address table where we want to validate the physical address when the data is saved. There are a few address validator services out there to choose from that I could find, but for this example I chose to sign up for a free trial of an address validation service from ServiceObjects. They’ve got some nice, simple APIs and support REST web requests. Once you sign up they give you a License Key that you need to pass into the service.

    A sample request looks like this:

    http://trial.serviceobjects.com/av/AddressValidate.asmx/ValidateAddress?Address=One+Microsoft+Way&Address2=&City=Redmond&State=WA&PostalCode=98052&LicenseKey=12345

    Which gives you back the result:

    <?xml version="1.0" encoding="UTF-8"?>
    <Address xmlns="http://www.serviceobjects.com/"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Address>1 Microsoft Way</Address>
        <City>Redmond</City>
        <State>WA</State>
        <Zip>98052-8300</Zip>
        <Address2/>
        <BarcodeDigits>980528300997</BarcodeDigits>
        <CarrierRoute>C012</CarrierRoute>
        <CongressCode>08</CongressCode>
        <CountyCode>033</CountyCode>
        <CountyName>King</CountyName>
        <Fragment/>
      </Address>

    If you enter a bogus address or forget to specify the City+State or PostalCode then you will get an error result:

    <?xml version="1.0" encoding="UTF-8"?>
    <Address xmlns="http://www.serviceobjects.com/"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Error>
        <Desc>Please input either zip code or both city and state.</Desc>
        <Number>2</Number>
        <Location/>
      </Error>
    </Address>
    

    So in order to interact with this service we’ll first need to add some assembly references to the Server project. Right-click on the Server project (like shown above) and select “Add Reference” and import System.Web and System.Xml.Linq.

    image

    Next, flip back to Logical View and open the Address entity in the Data Designer. Drop down the Write Code button to access the Addresses_Validate method. (You could also just open the Server\UserCode\ApplicationDataService code file if you are in File View).

    image

    First we need to import some namespaces as well as the default XML namespace that is returned in the response. (For more information on XML in Visual Basic please see: Overview of LINQ to XML in Visual Basic and articles here on my blog.) Then we can construct the URL based on the entity’s Address properties and query the result XML for either errors or the corrected address. If we find an error, we tell LightSwitch to display the validation result to the user on the screen.

    Imports System.Xml.Linq
    Imports System.Web.HttpUtility
    Imports <xmlns="http://www.serviceobjects.com/">
    
    Namespace LightSwitchApplication
      Public Class ApplicationDataService
    
        Private Sub Addresses_Validate(entity As Address, results As EntitySetValidationResultsBuilder)
          Dim isValid = False
          Dim errorDesc = ""
    
          'Construct the URL to call the web service
          Dim url = String.Format("http://trial.serviceobjects.com/av/AddressValidate.asmx/ValidateAddress?" &
                                  "Address={0}&Address2={1}&City={2}&State={3}&PostalCode={4}&LicenseKey={5}",
                                  UrlEncode(entity.Address1),
                                  UrlEncode(entity.Address2),
                                  UrlEncode(entity.City),
                                  UrlEncode(entity.State),
                                  UrlEncode(entity.ZIP),
                                  "12345")
    
          Try
              'Call the service and load the XML result 
    Dim
    addressData = XElement.Load(url) 'Check for errors first Dim err = addressData...<Error> If err.Any Then errorDesc = err.<Desc>.Value Else 'Fill in corrected address values returned from service entity.Address1 = addressData.<Address>.Value entity.Address2 = addressData.<Address2>.Value entity.City = addressData.<City>.Value entity.State = addressData.<State>.Value entity.ZIP = addressData.<Zip>.Value isValid = True End If Catch ex As Exception Trace.TraceError(ex) End Try If Not (isValid) Then results.AddEntityError("This is not a valid US address. " & errorDesc) End If End Sub End Class End Namespace

    Run it!

    Now that I’ve got this code implemented let’s enter some addresses on our contact screen. Here I’ve entered three addresses, the first two are legal and the last one is not. Also notice that I’ve only specified partial addresses.

    image

    If I try to save this screen, an error will be returned from the service on the last row. LightSwitch won’t let us save until the address is fixed.

    image

    If I delete the bogus address and save again, you will see that the other addresses were verified and all the fields are updated with complete address information.

    image

    Wrap Up

    I hope this gives you a good idea on how to implement web service calls into the LightSwitch validation pipeline. Even though each service you use will have different requirements on how to call them and what they return, the LightSwitch validation pipeline gives you the necessary hooks to implement complex entity validation easily.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Beginning LightSwitch–Address Book Sample

    • 1 Comments

    Some folks have been asking for this so I just released the completed Address Book sample that you build step-by-step in the Beginning LightSwitch Article Series.

    Download Sample Download the Address Book Sample

    Read the Series

    Are you completely new to LightSwitch and software development? Read this entry-level article series to get started with the most important concepts you need to build any LightSwitch application.

    More Information

    Visit the LightSwitch Developer Center to download LightSwitch and get started learning.

    Download Visual Studio LightSwitch

    Watch the instructional LightSwitch "How Do I?" videos

    Get essential trainingGet essential training

    Ask questions in the LightSwitch forums

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Using Different Edit Screens Based on Record Types (Table Inheritance)

    • 5 Comments

    I had a reader ask a question this week on how to use Visual Studio LightSwitch to open different Edit Detail screens based on the “type” of record. This is a very common thing to do especially for data models that use table inheritance (or sub-tables). For instance say we are building an application for a pet store to manage their inventory of animals. We need to collect shared properties of all the animals in an Animal table but we also want to set up table inheritance to Fish, Cat and Dog tables which collect specific properties of those types of animals. When a user selects an animal on a search screen, we need to display a screen that lets them work with the correct data from the specific table. LightSwitch provides a “Show as Link” on labels which automatically opens up the default details screen for that entity, but in our case we could have multiple screens. There are also a few techniques you need to know when dealing with these types of relationships in LightSwitch, particularly around the insert pipeline. In this post I will show you how you can achieve this functionality.

    Create The Data Model

    First let’s start by creating a simple inheritance data model for the pet store. We will build an Animal table that collects general properties of any animal in the store. Then we will build Cat, Dog and Fish tables to collect specific properties of those types of animals. The relationship between the Animal table and the others will be a ‘one to zero or one’ relationship.

    For this example, the Animal table has two required properties, Name and Type. Type is a Choice List with the static values “Cat”, “Dog”, “Fish” to correspond to the type of record the animal is. We will use this to drive what records are inserted into which specific table as well as use it to determine which screens to display.

    image

    Next, create the Cat, Dog and Fish tables to collect properties specific to these types of animals.

    image

    Finally, set up the relationships from Animal to these tables as a “one to zero or one” relationship with a delete behavior of “Cascade Delete”.

    image

    Our data model now looks like this.

    image

    Create the Screens

    Next we’ll need to enter new animals into the system. Create a New Data Screen and select Animal as the screen data. When you do this, LightSwitch will include all the one-to-one related tables as fields on the screen. However, we only want to require the user to enter the general Animal properties on this screen. Once they save, we will direct them to the correct Cat, Dog or Fish detail screen. So first delete all the items in the content tree of the Screen Designer except for Name and Type.

    image

    Next, create an Edit Details Screen and select the Animal screen data again. Name the screen CatDetail and uncheck “Use as Default Details Screen”.

    image

    Again you will see that LightSwitch reads these special relationships and adds all the fields from all four tables to the screen. We will need to make some changes. First, change the “Type” from an Auto Complete box to a Label. Once the user has entered the type of animal on the New Data screen, it cannot be changed. Next, delete all the fields related to Dog and Fish from the screen.

    image

    Repeat the same process to create the DogDetail and FishDetail screens, removing the fields from the screen that do not belong.

    Finally, add a Search Data Screen and select the Animal as the screen data again. Select the “Name” content item and in the properties window uncheck “Show as Link”.

    image

    Instead of using the built-in “Show as Link” functionality, we need to create our own command. We can put commands anywhere on the screen and we can show them as buttons or links. (For more information see: “I Command You!” - LightSwitch Screen Commands Tips & Tricks) For instance we could put an edit button on the screen command bar, the grid command bar, or even in the row itself. Let’s add a command into the row itself.

    Right-click on the Data Grid Row Command Bar in the content tree and select “Add Button…”. Create a new method called “Edit”.

    image

    We want to show the command as a link instead of a button so select the button in the content tree and change it to a link.

    image

    Write the Code

    Now we need to write some code to pull this all together. Right-click on the button we just created and select “Edit Execute Code” to open the code editor. Here we will check what type of animal we have to open the corresponding screen.

    Private Sub Edit_Execute()
        If Me.Animals.SelectedItem IsNot Nothing Then
            Select Case Me.Animals.SelectedItem.Type
                Case "Cat"
                    Me.Application.ShowCatDetail(Me.Animals.SelectedItem.Id)
                Case "Dog"
                    Me.Application.ShowDogDetail(Me.Animals.SelectedItem.Id)
                Case "Fish"
                    Me.Application.ShowFishDetail(Me.Animals.SelectedItem.Id)
            End Select
        End If
    End Sub

    Next we need to write similar code on the New Data screen so that it opens the correct detail screen after the user saves a new animal record. Open the CreateNewAnimal screen and in the upper right drop down the “Write Code” button and select the CreateNewAnimal_Saved method. First comment out the call to ShowDefaultScreen and then write code to determine which screen we need to show instead:

    Private Sub CreateNewAnimal_Saved()
        Me.Close(False)
        'Application.Current.ShowDefaultScreen(Me.AnimalProperty)
    
        Select Case Me.AnimalProperty.Type
            Case "Cat"
                Me.Application.ShowCatDetail(Me.AnimalProperty.Id)
            Case "Dog"
                Me.Application.ShowDogDetail(Me.AnimalProperty.Id)
            Case "Fish"
                Me.Application.ShowFishDetail(Me.AnimalProperty.Id)
        End Select
    End Sub

    Finally, we need to implement a business rule on Animal in the save pipeline. This rule is important so that a new record is added to the correct table based on the animal’s type. That way after the user saves the CreateNewAnimal screen, a record will be written to the correct table and the detail screen will open and allow the user to edit the specific fields in the Cat, Dog or Fish table. Double-click on Animals in the Solution Explorer under the Data Sources/ApplicationData node to open the Data Designer. Drop down the Write Code button and select the Animals_Inserting method and write this code:

    Private Sub Animals_Inserting(entity As Animal)
        Select Case entity.Type
            Case "Cat"
                If entity.Cat Is Nothing Then
                    entity.Cat = New Cat()
                End If
            Case "Dog"
                If entity.Dog Is Nothing Then
                    entity.Dog = New Dog()
                End If
            Case "Fish"
                If entity.Fish Is Nothing Then
                    entity.Fish = New Fish()
                End If
        End Select
    End Sub

    Run it!

    Enter new animals on the Create New Animal screen and when you click Save, the correct detail screen will open allowing you to enter more specific details based on the type of animal.

    image

    On our search screen, we can click the Edit link on any of the rows and it will open to the correct details screen as well.

    image

    Wrap Up

    I hope this post answered the reader’s question on how to open different detail screens depending on the record’s type. All it takes is implementing your own command. I also touched on one to one relationships and how to set up basic table inheritance. I encourage you to experiment more with this type of relationship. They come in particularly handy when you need to extend external data sources with additional properties or when you need to set up inheritance hierarchies. The trick is to get a record inserted into the right table when you insert the master / parent record. I’ll expand on a couple other techniques in a future post.

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Creating Cascading Drop Down Lists in Visual Studio LightSwitch

    • 8 Comments

    A common technique on data entry screens is using one “drop down list” (called an auto-complete box in LightSwitch) as a filter into the next. This limits the amount of choices that need to be brought down and guides the user into easily locating values. This technique is also useful if you have cascading filtered lists where the first selection filters data in the second, which filters data in the next, and so forth. LightSwitch makes this easy to do using parameterized queries and parameter binding. In this post let’s take a look a couple common scenarios.

    Cascading Lists based on Multiple Tables

    Let’s take an example where we have a table of States and a child table of Cities. Cities are then selected on Customers when entering them into the system. So we have one-to-many relationships between State and Cities and City and Customers. Our data model looks like this:

    image

    When the user is entering new customers we don’t want to display thousands of cities in the dropdown to choose from. Although the users can use the auto-complete box feature to locate a city, bringing down all these records affects performance. It’s better to either use a Modal Window Picker search dialog (like I showed in this article) or present the list of States first and then filter the list of Cities down based on that selection.

    First we need to create a couple queries. The first will simply sort the list of States so that they show up in alphabetical order in the list. Right-click on the States table in the Solution Explorer and Add Query to open the Query Designer. Create a query called “SortedStates” that sorts on the state’s Name Ascending:

    image

    Next create a query called “CitiesByState” by right-clicking on the Cities table in the Solution Explorer and selecting Add Query again. This time we will create a parameterized query: Where the State.Id property is equal to a new parameter called Id. The Query Designer should now look like this:

    image

    Now create the Customer Detail Screen like normal. Right-click on the Screens node and select “Add Screen…”, select the Edit Details Screen template then choose Customers for the screen data. The Screen Designer opens and all the fields in the Customer entity will be in the content tree. The City field is displayed as an auto-complete box.

    image

    Next we’ll need to add a data item to our screen for tracking the selected State. We will use this value to determine the filter on the City list so that users only see cities in the selected state. Click “Add Data Item” and add a Local Property of type State called SelectedState.

    image

    Next, drag the SelectedState over onto the content tree above the City. LightSwitch will automatically create an auto-complete box control for you.

    image

    Since we want to display the states sorted, next add the SortedStates query to the screen. Click “Add Data Item” again, this time select Query and choose SortedStates.

    image

    Then select the SelectedState auto-complete box in the content tree and on the Properties window, set the Choices property to SortedStates.

    image

    Next, add the CitiesByState query to the screen and set that as the Choices property of the Cities auto-complete box. Again, click “Add Data Item” and choose the CitiesByState query.

    image

    Then select the Cities auto-complete box and set the Choices property to this query.

    image

    Lastly we need to hook up the parameter binding. Select the Id parameter of the CitiesByState query and in the properties window set the Parameter Binding to SelectedState.Id. Once you do this a grey arrow on the left side will indicate the binding.

    image

    Once you set the value of a query parameter, LightSwitch will automatically execute the query for you so you don’t need to write any code for this. Hit F5 and see what you get. Notice that the Cities drop down list is empty until you select a State at which point it feeds the CitiesByState query and executes it. Also notice that if you make a city selection and then change the state, the selection is still displayed correctly, it doesn’t disappear. Just keep in mind that anytime a user changes the state, the city query is re-executed against the server.

    image

    One additional thing that you might want to do is to initially display the state to which the city belongs. As it is, the Selected State comes up blank when the screen is opened. This is because it is bound to a screen property which is not backed by data. However we can easily set the initial value of the SelectedState in code. Back in the Screen Designer drop down the “Write Code” button at the top right and select the InitializeDataWorkspace method and write the following:

    Private Sub CustomerDetail_InitializeDataWorkspace(saveChangesTo As List(Of Microsoft.LightSwitch.IDataService))
        ' Write your code here.
        If Me.Customer.City IsNot Nothing Then
            Me.SelectedState = Me.Customer.City.State
        End If
    End Sub

    Now when you run the screen again, the Selected State will be displayed.

    Cascading Lists Based on a Single Table

    Another option is to create cascading lists based on a single table. For instance say we do not want to have a State table at all. Instead it may make more sense to store the State on the City. So our data model could be simplified by having just a City table related to many Customers. image

    This time when we create a parameterized query called CitesByState, we’ll set it up Where the State is equal to a new parameter called State.

    image

    On the screen, select “Add Data Item” to add the CitiesByState to the screen and set it as the Choices property of the City auto-complete box just like before.

    image

    This time, however, the State is the query parameter we need to bind. Add a string screen property to the screen to hold the selected state. Click “Add Data Item” again, add a required Local Property of type String and name it SelectedState.

    image

    Drag the SelectedState onto the content tree above the City. This time LightSwitch will create a textbox for us since this is just a local string property.

    image

    Finally, we need to set up the query parameter binding. Select the State query parameter and in the properties window set the Parameter Binding to SelectedState.

    image

    In order to set the SelectedState when the screen opens, the same code as before will work. Now when we run this, you will see a textbox that will filter the list of cities.

    image

    However, this may not be exactly what we want. If the user has a free-form text field then they could mistype a state code and the query would return no results. It would be better to present the states in a auto-complete box like before. Close the application and open the Screen Designer again. Select the SelectedState screen property. Notice in the properties window you can display this as a static list of values by creating a Choice List.

    image

    Enter the states that the user should select from and then run the application again. Now we get an auto-complete box like before. However, this approach leaves us having to define the choice list of states on every screen we want this functionality. The first approach using a State table solves this issue but there is also one other approach we could take to avoid having to create a separate table.

    Using a Choice List on the Entity

    We could improve this situation by defining the choice list of states on the Customer entity. Then we would only have to define the lists of states in one place. Create a State property on the Customer using the Data Designer and on the properties window select Choice List and specify the list of states there.

    image

    Now add a new detail screen for Customer and you will see the State and City properties are set up as auto-complete boxes. Next add the CitiesByState query to the screen by clicking “Add Data Item” like before. We can use the same CitiesByState query as the previous example. Select the City auto-complete box and in the properties window set the Choices property to CitiesByState like before.

    The difference is the query parameter binding. Select the State query parameter on the left and in the properties window set the Parameter Binding to Customer.State.

    image

    With this technique, you also do not need to write any code to set the initial selected State because we are now storing that value on the Customer record. Run the application again and the screen should behave the same. The only difference now is that we are storing the State on the Customer instead of a separate table.

    image

    This technique is the simplest to set up, so if you have a lot of Customer screens, then this may be the best choice for you if you have a static list of values like States. However if you have dynamic list of values then it’s better to store these in a separate table like the first technique showed.

    For more information on filtering data and configuring lists see:

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    LightSwitch Community & Content Rollup– December 2011

    • 0 Comments

    Happy New Year everyone! I hope you all had a wonderful holiday and enjoyed some well-deserved time off. I sure did! Now that I’m back in the office I’m a few days overdue for this post so here ya go! A few months ago I started posting a rollup of interesting community happenings, content, samples and extensions popping up around Visual Studio LightSwitch. If you missed those rollups you can check them out here:

    Usually December is a pretty slow month all around, but there were still a lot of awesome things around LightSwitch, especially the number of community articles this month! Check them out…

    “LightSwitch Star” Contest

    “LightSwitch Star” Contest on CodeProjectDo you have what it takes to be a LightSwitch Star? Show us your coolest, most productive, LightSwitch business application and you could win a Laptop and other great prizes! 

    In November The Code Project launched the “LightSwitch Star” contest. You just answer some questions and email them a screenshot or two. They’re looking for apps that show off the most productivity in a business as well as apps that use extensions in a unique, innovative way. Prizes are given away each month (see here for more details on prizes). In early December they announced the November winners and today they announced the December winners in each category:

    Most Efficient Business Application Most Ground-breaking Business Application
    November November
    1st prize: Security Central
    2nd prize: PTA LightSwitch
    1st prize: Church+
    2nd prize: Engineering App
    December December
    1st prize: Patient Tracker
    2nd prize: Instant Assets
    1st prize: Health and Safety Management System
    2nd prize: Orion

    Congrats to all! Can’t wait to see what people submit in January. There were some really cool applications submitted in December. Here’s a breakdown of what was submitted last month (see all 23 apps that have been submitted so far here). Make sure to vote for your favorite ones, grand prize is a laptop!

    7 More Production Apps…

    3 More Tutorials/Samples/Videos…

    ComponentOne Scheduler for LightSwitch Released

    imageComponentOne released another LightSwitch extension last month in addition to the OLAP Control. This ready-to-use LightSwitch screen gives you a complete Outlook-style scheduling application! Check it out:


    Notable Content this Month

    Here’s some more of the fun things the team and community released in December.

    Extensions released in December (see all 71 of them here!):

    Build your own extensions by visiting the LightSwitch Extensibility page on the LightSwitch Developer Center.

    Team Articles:

    In December I kicked off a series aimed at beginner developers just getting started with LightSwitch and was featured in the MSDN Flash Newsletter. This brought A LOT of traffic to my blog – in fact, it is at an all-time high since the month of December! WOW! This series is popular!

    Matt Thalman also wrote the following article that address a top request in the LightSwitch Forums:
    Creating a Custom Login Page for a LightSwitch Application

    Community Articles:
    Samples (see all of them here):

    LightSwitch Team Community Sites

    The Visual Studio LightSwitch Facebook Page has been increasing in activity thanks to you all. Become a fan! Have fun and interact with us on our wall. Check out the cool stories and resources.

    Also here are some other places you can find the LightSwitch team:


    LightSwitch MSDN Forums
    LightSwitch Developer Center
    LightSwitch Team Blog
    LightSwitch on Twitter (@VSLightSwitch, #VisualStudio #LightSwitch)

    Join Us!

    The community has been using the hash tag #LightSwitch on twitter when posting stuff so it’s easier for me to catch it (although this is a common English word so you may end up with a few weird ones ;-)). Join the conversation! And if I missed anything please add a comment to the bottom of this post and let us know!

    Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Beginning LightSwitch Part 6: I Feel Pretty! Customizing the "Look and Feel" with Themes

    • 3 Comments

    Welcome to Part 6 of the Beginning LightSwitch series! In parts 1 thru 5 we built an Address Book application and learned all about the major building blocks of a Visual Studio LightSwitch application -- entities, relationships, screens, queries and user permissions. If you missed them:

    In this post I want to talk about themes. Themes allow you to change the colors, fonts and styles of all the visual elements in the user interface. Now that our Address Book application is complete, we’re almost ready to get this in front of real users. But before we do, it would be really nice to apply a different look-and-feel to our application in order to make it stand out above the rest. Visual Studio LightSwitch comes with only one theme out of the box, but you can download more. In fact, there are all kinds of extensions you can download to enhance what LightSwitch can do out of the box, not just themes.

    Visual Studio LightSwitch Extensibility

    LightSwitch provides an entire extensibility framework so that professional developers can write extensions to enhance the LightSwitch development experience. Many third-party component vendors as well as the general community have released all sorts of extensions for LightSwitch. These include custom controls, business types, productivity libraries and designers, and of course themes. Check out some of the featured extensions from our partners. If you are a code-savvy, professional .NET developer with Visual Studio Professional or higher, then you can create your own extensions. For more information on creating extensions see the Extensibility section of the LightSwitch Developer Center.

    Downloading and Enabling Extensions

    Luckily, you don’t need to be a hardcore programmer to use extensions. They are easy to find and install. Just open the Extension Manager from the Tools menu.

    image

    The Extension Manager will come up and display all your installed extensions. Select the “Online Gallery” tab to choose from all the LightSwitch extensions from the Visual Studio Gallery. (Note: if you have Visual Studio Professional or higher and not just the LightSwitch edition installed, then you will need to filter the Extension Manager on “LightSwitch” to see those extensions.)

    image

    You can also download these extensions directly from the Visual Studio Gallery. Select the extension you want and click the download button to install.

    For our Address Book application I’m going to apply the LightSwitch Metro Theme which is one of the most popular extensions (at the time of this writing) so it’s right at the top. Once you install the extension, you’ll need to restart Visual Studio LightSwitch. After extensions are installed, you need to enable them on a per-project basis. Open the project properties by right-clicking on the project in the Solution Explorer and select “Properties”. Then select the “Extensions” tab to enable the extension.

    image

    For our Address Book application, enable the Metro Theme extension. Also notice that there is the “Microsoft LightSwitch Extensions” also in this list which is always enabled and used in new projects. This is an extension that is included with the LightSwitch install and contains the business types Email Address, Phone Number, Money and Image that you can use when defining your data entities like we did in Part 1. You should never have to disable these.

    Applying a Theme

    Now that the theme extension is installed and enabled, you can apply the theme by selecting the “General Properties” tab and then choosing the LightSwitch Metro Theme.

    image

    Then just build and run (F5) the application to see how it looks!

    image

    For more information on the Metro Theme extension (and source code) see the LightSwitch Metro Theme Extension Sample.

    Some More Cool LightSwitch Themes

    Besides the Metro Theme, there are a lot of other nice looking themes available, some for free and some for a small fee. If you open the Extension Manager to the Online Gallery tab and enter the search term “theme” you will see a long list of them. Here are the top 5 most popular on the gallery (at the time of this writing):

     

    1. LightSwitch Metro Theme
    2. Spursoft LightSwitch Extensions
    3. Themes by Delordson (LightSwitchExtras.com)
    4. Luminous Themes
    5. VS Dark Blue Theme

    Also check out Paul Patterson’s “Uber Theme Resource” which provides more screenshots and reviews of all the themes on the gallery!

    Wrap Up

    As you can see it’s easy to download and enable themes in Visual Studio LightSwitch in order to change the look-and-feel of your business applications. LightSwitch provides an entire extensibility model that not only allows the community to create themes, but all kinds of extensions that enhance the LightSwitch development experience that you can take advantage of. If you’re a code-savvy developer that wants to create your own themes, head to the Extensibility section of the LightSwitch Developer Center to get set up and then read this walkthrough Creating a Theme Extension.

    Well that wraps up what I planned for the Beginning LightSwitch Series! I hope you enjoyed it and I hope it has helped you get started building your own applications with Visual Studio LightSwitch. For more LightSwitch training please see the Learn section of the LightSwitch Developer Center. In particular, I recommend going through my “How Do I” videos next.

    Now I’m going to go enjoy some well-earned Christmas vacation. I’ll be back in a couple weeks. Happy Holidays LightSwitch-ers! Enjoy!

  • Beth Massi - Sharing the goodness that is VB

    Beginning LightSwitch Part 5: May I? Controlling Access with User Permissions

    • 0 Comments

    Welcome to Part 5 of the Beginning LightSwitch series! In parts 1 thru 4 we learned about entities, relationships, screens and queries in Visual Studio LightSwitch. If you missed them:

    In this post I want to talk about user permissions, also known as Access Control. In most business applications we need to limit what resources users can access in the system, usually because of different job function or role. For instance, only system administrators can add new users to the system. Certain data and screens in the application may be sensitive and should be restricted unless that user has rights to that part of the system. LightSwitch makes it easy to define user permissions and provides hooks on entities, screens and queries that allow you to check these permissions.

    For a video demonstration on how to set up user permissions see: How Do I: Set Up Security to Control User Access to Parts of a Visual Studio LightSwitch Application?

    Authentication & Authorization

    There are two pieces of information LightSwitch applications need in order to determine which users have rights to what parts of the system. First, the system needs to verify the user accessing the application. This is called Authentication. In other words: “Prove you are who you say you are.” There are two supported types of authentication in LightSwitch; Windows and Forms.

    Windows authentication means that the application trusts the user based on their Windows credentials. So once a user successfully logs into their Windows desktop, those credentials are automatically passed to the LightSwitch application. Forms authentication means that the application requests a username & password of its own, completely independent of any other credentials. So when you choose to use Forms authentication a login screen is presented to the user and they must type their username and password every time they want to access the application.

    Once a user is authenticated, the application can determine access to parts of the system by reading their user permissions. This is called Authorization. In other words: “Now that I know who you are, here’s what you can do in the system.”

    Setting Up User Permissions

    It all starts on the Access Control tab of the Project Properties. To open it, right-click on the name of your project in the Solution Explorer and select “Properties” from the menu.

    image

    Then select the Access Control tab to specify the type of authentication you want to employ as well as what user permissions you want to define.

    image

    By default, the application doesn’t have authentication enabled so here is where you select the type of authentication you want to use.

    Using Forms authentication means you will be storing usernames and encrypted passwords inside the LightSwitch database. This type of authentication is appropriate for internet-based applications where users are not on the same network and you need to support other operating systems besides Windows.

    Using Windows authentication is appropriate if all your users are on the same network/domain or workgroup, like in the case of an internal line-of-business application. This means that no passwords are stored by your LightSwitch application. Instead the Windows logon credentials are used and passed automatically to the application. This is a more secure and convenient option if you can use it. In this case you can also choose whether you want to set up specific users and roles or whether any authenticated user has access to the application.

    image

    The best way to think of the two options for Windows authentication are:

    • Give special permissions and roles to the Windows users that I administer within the application. (This is always on if you have selected Windows authentication)
    • ALSO, let any Windows user access the unprotected parts of my application

    Next you define user permissions that you check in code in order to access resources (we’ll work through an example next). There is always a SecurityAdministration permission defined for you that is used by LightSwitch once you deploy the application. When you deploy, LightSwitch will create a single user with this permission which gives them access to the screens necessary to define the rest of the users and roles in the system. However, while debugging your application, LightSwitch doesn’t make you log in because this would be tedious to do every time you built and ran (F5) the application. So instead you can use the “Granted for debug” checkbox to indicate which sets of permissions should be turned on/off in the debug session.

    Let’s walk through a concrete example by implementing some security in our Address Book (Contact Manager) application we’ve been building in this series.

    Checking User Permissions in the Address Book Application

    Let’s start by selecting an authentication scheme. Since this application will be used by a small business to manage all their contacts, I’ll choose Windows authentication. I’ll also select “Allow any authenticated Windows user” into the system so that everyone in the company can search for and edit contacts by default. However, in order to add or delete contacts, users will need special permissions to do that.

    So we need to create two new permissions. You can name the permissions whatever you want. You only see the name in code. When the system administrator sets up users and roles later, they will see the Display Name on the screen so be descriptive there. So add two permissions; CanAddContacts and CanDeleteContacts.

    image

    Next, leave the “Granted for debug” unchecked for both of those permissions so that we can test that they are working. When you leave this unchecked, the permission will not be granted. This allows us to easily test combinations of permissions while debugging. In order to see the Users and Roles screens while debugging you can enable it for SecurityAdministration. Now that we have these permissions set up here, we need to check them in code. As I mentioned, LightSwitch provides method hooks for you so you can write code when you need for all sorts of custom validation and business rules, including access control.

    For more information on writing code in LightSwitch see the Working with Code topic on the LightSwitch Developer Center.

    For more information on writing custom business rules see: Common Validation Rules in LightSwitch Business Applications

    So in order to implement the security, we need to write a couple lines of code to check these permissions. LightSwitch provides access control methods on entities, screens and queries. To access these methods, drop down the “Write code” button on the top right of any designer and you will see an “Access Control Methods” section in the list. When you want to restrict viewing (reading), inserting (adding), editing or deleting entities, open the entity in the Data Designer and drop down the “Write code” button and select the appropriate access control method.

    image

    For this application, select the Contacts_CanDelete method and this will open the code editor to that method stub. All you need to do is write one line of code (in bold below) to check the CanDeleteContacts permission you set up:

    Namespace LightSwitchApplication
    
        Public Class ApplicationDataService
    
            Private Sub Contacts_CanDelete(ByRef result As Boolean)
                'Add this one line of code to verify the user has permission to delete contacts:
                result = Me.Application.User.HasPermission(Permissions.CanDeleteContacts)
    
            End Sub
        End Class
    
    End Namespace
    

    Note: This code is Visual Basic. If you chose C# as your programming language when you created the ContactManager project in Part 1, you will need to write the code like this: result = this.Application.User.HasPermission(Permissions.CanDeleteContacts);

    Now go back to the “Write Code” button on the designer and select Contacts_CanInsert and then similarly write the following line of code (in bold) to check the CanAddContacts permission:

    Namespace LightSwitchApplication
    
        Public Class ApplicationDataService
    
            Private Sub Contacts_CanDelete(ByRef result As Boolean)
                'Add this one line of code to verify the user has permission to delete contacts:
                result = Me.Application.User.HasPermission(Permissions.CanDeleteContacts)
    
            End Sub
    
            Private Sub Contacts_CanInsert(ByRef result As Boolean)
                'Add this one line of code to verify the user has permission to add contacts:
                result = Me.Application.User.HasPermission(Permissions.CanAddContacts)
            End Sub
        End Class
    
    End Namespace
    

    You may be wondering why we are checking these permissions in the entity instead of the screens. Checking permissions in the entity guarantees that no matter what screen the user is working with, the data actions are protected. It’s best practice remember to secure your entities first if you need to implement user permissions in your application. However, our application also has a “Create New Contact” screen and we don’t want to show this to the user on the menu if they do not have permission to add contacts to the system. If we forget to hide this screen from the menu, then the user would be able to open it and fill it out with data. However, when they click Save the Contacts_CanInsert method above will run and prevent the actual data from saving.

    So in order to hide this screen from the navigation menu, we need to add one more check. Double-click the CreateNewContact screen in the Solution Explorer to open the Screen Designer. Drop down the “Write Code” button on the top right and you will see the one Access Control method available to you for screens:

    image

    Select the CreateNewContact_CanRun method and then write the following line of code (in bold):

    Namespace LightSwitchApplication
    
        Public Class Application
    
            Private Sub CreateNewContact_CanRun(ByRef result As Boolean)
                'Add this one line of code to verify the user has permission to run the screen:
                result = Me.User.HasPermission(Permissions.CanAddContacts)
    
            End Sub
        End Class
    
    End Namespace
    
    

    Run it!

    Now we are ready to test the application so build and run by hitting F5. Because we didn’t grant the CanAddContacts and CanDeleteContacts permissions for debug you will notice first that the CreateNewContact screen is not showing up on the menu. The first screen that displays is the custom search screen we created in Part 4. If you click on a contact then the details screen will open which allows the user to edit that contact’s information. In order to see if we are restricted from deleting or adding new contacts let’s make a small change to the search screen. While the search screen is open click the “Design Screen” button at the top right to open the screen customization mode.

    image

    In the content tree on the left, expand the command bar under the Data Grid and add two commands; DeleteSelected and AddAndEditNew.

    image

    Click Save (ctrl+shift+S) to save and exit customization mode and notice that the commands are disabled. Since we do not have permission to add or delete contacts this behavior is correct. Also since we are checking these permissions at the entity level all screen commands behave appropriately with no additional code necessary.

    image

    If you go back to your project properties Access Control tab you can check off combinations of permissions you want to test and you will see all commands enable/disable appropriately.

    Users & Roles Screens

    Before we wrap up I want to quickly walk through the Users and Roles screens. When you enable the SecurityAdministration permission for debugging, these screens are available on the menu. However, keep in mind that the data you put into these screens isn’t used at debug time. It isn’t later until you deploy the application when these screens are used. So putting data into these screens is for demonstration purposes only. When your application is deployed the first time, LightSwitch will ask you for an administrator username & password that it deploys into the users table and grants the SecurityAdministration permission. That administrator can then enter the rest of the users into the system.

    First you define roles and add the permissions you defined to that role using the Roles Screen.

    image

    Then you can add new users using the Users Screen and assign them the appropriate Roles.

    image

    Wrap Up

    As you can see defining and checking user permissions in Visual Studio LightSwitch is a simple but important task. Access control is a very common requirement in professional business applications and LightSwitch provides an easy to use framework for locking down all parts of the application through method hooks on entities, screens and queries. Once you deploy your application, the system administrator can start setting up users and roles to control access to the secure parts of your application.

    For more information on user permissions and deploying applications see Working with User Permissions and Deploying LightSwitch Applications topics on the LightSwitch Developer Center.

    In the next post we’ll look at themes and how to change the look and feel of your application by installing LightSwitch extensions. We’ll look at what’s available for free as well as some inexpensive ones that really look great. Until next time!

    Enjoy!

    Go to next article –> I Feel Pretty! Customizing the "Look and Feel" with Themes

  • Beth Massi - Sharing the goodness that is VB

    Beginning LightSwitch Part 4: Too much information! Sorting and Filtering Data with Queries

    • 0 Comments

    Welcome to Part 4 of the Beginning LightSwitch series! In part 1, 2 and 3 we learned about entities, relationships and screens in Visual Studio LightSwitch. If you missed them:

    In this post I want to talk about queries. In real life a query is just a question. But when we talk about queries in the context of databases, we are referring to a query language used to request particular subsets of data from our database. You use queries to help users find the information they are looking for and focus them on the data needed for the task at hand. As your data grows, queries become extremely necessary to keep your application productive for users. Instead of searching an entire table one page at a time for the information you want, you use queries to narrow down the results to a manageable list.  For example, if you want to know how many contacts live in California, you create a query that looks at the list of Contacts and checks the State in their Address.

    If you’ve been following this article series, you actually already know how to execute queries in LightSwitch. In part 3 we built a Search Data Screen. This screen has a built-in search feature that allows users to type in search terms and return rows where any string field matches that term. In this post I want to show you how you can define your own queries using the Query Designer and how you can use them on screens.

    The LightSwitch Query Designer

    The Query Designer helps you construct queries sent to the backend data source in order to retrieve the entities you want. You use the designer to create filter conditions and specify sorting options. A query in LightSwitch is based on an entity in your data model (for example, a Contact entity). A query can also be based on other queries so they can be built-up easily. For instance, if you define a query called SortedContacts that sorts Contacts by their LastName property, you can then use this query as the source of other queries that return Contacts. This avoids having to repeat filter and/or sort conditions that you may want to apply on every query.

    For a tour of the Query Designer, see Queries: Retrieving Information from a Data Source

    For a video demonstration on how to use the Query Designer, see: How Do I: Sort and Filter Data on a Screen in a LightSwitch Application?

    Creating a “SortedContacts” Query

    Let’s walk through some concrete examples of creating queries in LightSwitch using the Contact Manager Address Book application we’ve been building. In part 3 we built a Search Data Screen for our Contacts, but if you notice the Contacts are not sorted when the screen is initially displayed. The user must click on the desired grid column to apply a sort manually. Once the user changes the sort order LightSwitch will remember that on a per-user basis, but we should really be sorting the Contacts for them when the Search screen is displayed the first time.

    To create a query, in the Solution Explorer right-click on the entity you want to base it on (in our case Contacts) and choose “Add Query”.

    image

    The Query Designer will open and the first thing you do is name your query. We’ll name ours “SortedContacts”. Once you do this, you will see the query listed under the entity in the Solution Explorer.

    image

    Next we need to define the sort order so click “+Add Sort” in the Sort section of the designer then select the LastName property from the drop down. Click “+Add Sort” again and this time select the FirstName property. Leave the order Ascending for both.

    image

    Before we jump into Filter conditions and Parameters, let’s see how we can use this simple query on our Search Screen. It’s actually easier in this case to re-create the Search Screen we created in Part 3 because we didn’t make any modifications to the layout. So in the Solution Explorer select the SearchContacts screen and delete it. Then right-click on the Screens node and select “Add Screen…” to open the Add New Screen dialog.

    Select the Search Data Screen template then for the Screen Data you will see the SortedCOntacts query. Choose that then click OK.

    image

    Hit F5 to build and run the application and notice this time the contacts are sorted in alphabetical order immediately. 

    image

    Defining Filter Conditions and Parameters

    Our Search Screen is in better shape now but what if we wanted to allow the user to find contacts who’s birth date falls within a specific range? Out of the box, LightSwitch will automatically search across all String properties on an entity but not Dates. Therefore, in order to allow the user the ability to search within a birth date range, we need to define our own query.

    So let’s create a query that filters by date range but this time we will specify the Source of the query be the SortedContacts query. Right-click on the Contacts entity and choose “Add Query” to open the Query Designer again. Name the query “ContactsByBirthDate” and then select “SortedContacts” in the Source drop down on the top right of the designer.

    image

    Now the query is sorted but we need to add a filter condition. Defining filter conditions can take some practice (like designing a good data model) but LightSwitch tries to make it as easy as possible while still remaining powerful. You can specify fairly complex conditions and groupings in your filter, however the one we need to define isn’t too complex. When you need to find records within a range of values you will need 2 conditions. Once that checks records fall “above” the minimum value and one that checks records fall “below” the maximum value.

    So in the Query Designer, click “+ Add Filter” and specify the condition like so:

    Where

    image

    the BirthDate property

    image

    is greater than or equal to

    image

    a parameter.

    image

    Then select “Add New” to add a new parameter.

    image

    The parameter’s name will default to “BirthDate” so change it to MinimumBirthDate down in the Parameters section.

    image

    Similarly, add the filter condition for “Where the BirthDate property is less than or equal to a new parameter called MaximumBirthDate”. The Query Designer should now look like this:

    image

    One last thing we want to think about with respect to parameters is whether they should be required or not. Meaning must the user fill out the filter criteria parameters in order to execute the query? In this case, I don’t want to force the user to enter either one so we want to make them optional. You do that by selecting the parameter and checking “Is Optional” in the properties window.

    image

    Okay now let’s use this query for our Search Screen. In the Solution Explorer select the SearchSortedContacts screen and delete it. Then right-click on the Screens node and select “Add Screen…” to open the Add New Screen dialog again. Select the Search Data Screen template and for the Screen Data select the ContactsByBirthDate query and click OK.

    Hit F5 to build and run the application. Notice the contacts are still sorted in alphabetical order on our search screen but you see additional fields at the top of the screen that let us specify the birth date range. LightSwitch sees that our query specified parameters so when we used it as the basis of the screen, the correct controls were automatically generated for us! And since both of these parameters are optional, users can enter none, one, or both dates and the query will automatically execute correctly based on that criteria.

    image

    As you can see using queries with parameters like this allows you to perform much more specialized searches than what is provided by default. When using queries as the basis of Screen Data, LightSwitch will automatically look at the query’s parameters and create the corresponding screen parameters and controls which saves you time.

    For more information on creating custom search screens, see: Creating a Custom Search Screen in Visual Studio LightSwitch and How to Create a Screen with Multiple Search Parameters in LightSwitch

    For a video demonstration, see: How Do I: Create Custom Search Screens in LightSwitch?

    Querying Related Entities

    Before we wrap this up I want to touch on one more type of query. What if we wanted to allow the user to search Contacts by phone number? If you recall our data is modeled so that Contacts can have many Phone Numbers so they are stored in a separate related table. In order to query these, we need to base the query on the PhoneNumber entity, not Contact.

    So right-click on the PhoneNumbers entity in the Solution Explorer and select “Add Query”. I’ll name it ContactsByPhone. Besides searching on the PhoneNumber I also want to allow users to search on the Contact’s LastName and FirstName. This is easy to do because the Query Designer will allow you to create conditions that filter on related parent tables, in this case the Contact. When you select the property, you can expand the Contact node and get at all the properties.

    So in the Query Designer, click “+ Add Filter” and specify the condition like so:

    Where the Contact’s LastName property

    image

    contains

    image

    a parameter

    image

    Then select “Add New” to add a new parameter.

    image

    The parameter’s name will default to “LastName” so change it to SearchTerm down in the Parameters section and make it optional by checking “Is Optional” in the properties window.

    image

    We’re going to use the same parameter for the rest of our conditions. This will allow the user to type their search criteria in one textbox and the query will search across all three fields for a match. So the next filter condition will be:

    Or the Contact’s FirstName property contains the parameter of SearchTerm

    image

    And finally add the last filter condition:

    Or the Phone property contains the parameter of SearchTerm. I’ll also add a Sort on the PhoneNumber Ascending. The Query Designer should now look like this:

    image

    Now it’s time to create a Search Screen for this query. Instead of deleting the other Search screen that filters by birth date range, I’m going to create another new search screen for this query. Another option would be to add the previous date range condition to this query, which would create a more complex query but would allow us to have one search screen that does it all. For this example let’s keep it simple, but here’s a hint on how you would construct the query by using a group:

    image

    For more information on writing complex queries see: Queries: Retrieving Information from a Data Source and How to Create Composed and Scalar Queries

    So to add the new Search Screen right-click on the Screens node again and select “Add Screen…” to open the Add New Screen dialog. Select the Search Data Screen template and for the Screen Data select the ContactsByPhone query this time and click OK.

    Now before we run this I want to make a small change to the screen. The default behavior of a search screen is to make the first column a link that opens the Details screen for that record. Since we had to base our query on the PhoneNumber entity, LightSwitch will make the Phone property a link and not the Contact. So in the Screen Designer we need to make a small change. Select the Phone in the content tree and in the properties window uncheck “Show as Link”. Then select the Contact and check “Show as Link”.

    image

    Also change Display Name in the properties window for the PhoneNumberSearchTerm textbox to “Phone Number or Name” to make it more clear to the user what they are filtering on. And while we’re at it, we should disable the default search box by selecting the ContactsByPhone query on the left-hand side and unchecking “Supports search” in the properties window. This isn’t necessary since we are providing more search functionality with our own query.

    image

    Okay hit F5 and let’s see what we get. Open the “Search Contact By Phone” Search screen from the navigation menu and now users can search for contacts by name or by phone number. When you click on the Contact link, the Details screen we created in part 3 will open automatically.

    image

    Wrap Up

    As you can see queries help narrow down the amount of data to just the information users need to get the task done. LightSwitch provides a simple, easy-to-use Query Designer that lets you base queries on entities as well as other queries. And the LightSwitch Screen Designer does all the heavy lifting for you when you base a screen on a query that uses parameters.

    Writing good queries takes practice so I encourage you to work through the resources provided in the Working with Queries topic on the LightSwitch Developer Center.

    In the next post we’ll look at user permissions and you will see how to write your first lines of LightSwitch code! Until next time!

    Enjoy!

    Go to next article –> Part 5: May I? Controlling Access with User Permissions

Page 1 of 55 (548 items) 12345»