Udostępnij za pośrednictwem


Beginning LightSwitch in VS 2013 Part 6: More Control! Customizing the app with JavaScript & CSS

NOTE: This is the Visual Studio 2013 update of the popular Beginning LightSwitch article series. For previous versions see:


Welcome to Part 6 of the Beginning LightSwitch in Visual Studio 2013 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 some of the different ways you can customize your HTML client application by adding JavaScript code and CSS.

As you’re probably learning, LightSwitch is all about building mobile business solutions quickly -- defining your data models & business rules and visually creating screens with a set of built-in controls. It does all the boring plumbing so you can concentrate on the real value of your applications. But LightSwitch also allows for all sorts of customizations so you don’t hit that infamous “glass ceiling”. With the HTML client we can take advantage of the huge web ecosystem already out there, so adding customizations can be as easy as finding the JavaScript library you want and wiring it up to your app. 

LightSwitch produces single-page applications (SPAs) based on jQuery and jQueryMobile. These are the fundamental libraries used in the HTML client. LightSwitch then provides data/data binding & query capabilities on top of that in the msls.js scripts.  jQueryMobile CSS is used to control the look and feel of the application.

These files are available to you in the HTML client project. The stylesheets are located in the Content sub-folder and the JavaScript files are in the Scripts sub-folder:

image

For an introduction to jQuery and its syntax in the context of the LightSwitch HTML client see:
Introduction to jQuery for App Customization

Let’s take a look at some of the more interesting ways to quickly customize the HTML client.

Changing the Theme

The HTML Client comes with two themes “in the box” that you can use as-is, or completely change for your needs – a light theme and a dark theme. By default, the light theme is used for new projects. To change the theme to the dark theme, open up the default.htm file in the HTML Client project and change the following:

 <!-- Change light-theme-2.0.0.css and msls-light-2.0.0.css to dark-theme-2.0.0.css 
and msls-dark-2.0.0.css respectively to use the dark theme.  Alternatively, you may 
replace light-theme-2.0.0.css with a custom jQuery Mobile theme. -->
    <link rel="stylesheet" type="text/css" href="Content/dark-theme-2.0.0.css" />
    <link rel="stylesheet" type="text/css" href="Content/msls-dark-2.0.0.css" />

Let’s apply this change to the Address Book app we’ve been building in this article series. When we run our app we now see the dark theme which has a black/grey background with white text and icons.

image 

Using ThemeRoller

Of course we’re not limited to these two themes, we can design our own. However, if you’re not design savvy or a CSS wiz, I encourage you to use jQueryMobile ThemeRoller to save you loads of time.

To start using ThemeRoller head to https://jquerymobile.com/themeroller/. To make it easy, you can import a stylesheet and then just tweak the elements you want. So in Visual Studio open the stylesheet we’re using /Content/dark-theme-2.0.0.css and copy all the contents into your clipboard. Using ThemeRoller, select version 1.3, click the Import button at the top of the screen, paste in the CSS, and then click Import:

image

This will load the dark theme into a swatch on the design surface. Now you can customize any of the elements by changing the properties on the left. Alternatively, you can select from a variety of pre-built themes and colors and simply drag them onto the swatch.

image

When you’re finished, export the theme by clicking on the Download button at the top of ThemeRoller and naming the new theme. This will download a ZIP with your theme (the ZIP includes a version that is readable and a min version that has the whitespace taken out).

Extract the contents of the ZIP, and in the theme folder, copy the CSS file (I named mine orange-theme), and paste it back in Visual Studio into the Content folder with the other stylesheets. Finally open up default.htm and replace the dark theme with ours.

     <link rel="stylesheet" type="text/css" href="Content/orange-theme.css" />

Branding

As an extension to changing the theme, you probably also want to add your company or product logo to your app. If you don’t want to dive into the CSS to do this, you can simply replace the stock images. One is displayed while the app is loading and the other displays on the top left of your home screen.

Just open up the Content\Images folder and replace the user-logo.png and user-splash-screen.png.

image

Applying this to our Address Book app gives us a nice polished look:

image

Visual Indicators on Data with CSS

Often times in business applications we need to do some UI validation, like changing the color of data based on its value. This needs to happen on the client. LightSwitch gives you hooks on controls in the screen designer so that you can either make changes to the control or completely render it yourself, depending on what you are trying to do.

Say we want to change the color of our contacts on our Home screen based on whether they are Male or Female. We can do this using the _postRender method on the Row Template of the Contact List. Open up the BrowseContacts screen, select the Contact Rows Layout, then drop down the “Write Code” button and select the _postRender method.

image

The method is passed two parameters, the element is the DOM element and contentItem is the screen’s content item in the content tree. The contentItem.value is the Contact entity in our example.

We’re going to want to adorn the element with a particular style so we can use the jQuery addClass method on the element.

image

First let’s create the styles we want. Notice that there’s a user-customization.css in the Content folder. Here is where you can tweak some of the common styles as well as add your own. Let’s add:

 .male { background-color: blue; }
.female { background-color: purple; }

Now back in the _postRender you can add the code to check for the Gender value and apply the right style.

 myapp.BrowseContacts.RowTemplate_postRender = function (element, contentItem) {
    // Write code here.
    if (contentItem.value.Gender == "M") {
        $(element).addClass("male");
    } else {
        $(element).addClass("female");
    }    
};

When we run it we can see our styles applied correctly:

image

However data likes to change in a business application :-). In this particular case, a contact’s gender probably won’t change, but what if we made a mistake when entering a contact? If you want the visual style to update when the data value changes, use the dataBind method to handle this.

This code will set up our function to be called anytime the Gender changes.

 myapp.BrowseContacts.RowTemplate_postRender = function (element, contentItem) {
    // Write code here.
    contentItem.dataBind("value.Gender", function ()
    {
        if (contentItem.value.Gender == "M") {
            $(element).addClass("male");
            $(element).removeClass("female");
        } else {
            $(element).addClass("female");
            $(element).removeClass("male");
        }    
    });
};

Customizing the UI with Custom Controls

You can also take over the complete rendering of controls on screens yourself in order to inject anything you want into the DOM. Since LightSwitch HTML apps are based on jQuery and jQueryMobile, there are a plethora of plugins available for you to use in LightSwitch. Which ones you use totally depends on what you want to provide to your users and the devices that you need to support.

First, add a custom control to your screen where you want it in the content tree. Then drop down the write code button and select the _render method. For a simple example, say we want to add some text to our browse contacts screen under the list of contacts. First add the custom control:

image

Then select the data you want to pass in the contentItem parameter. The default is the entire screen, but you could select other data items available on the screen.

image

Then select the _render method and write your code.

image

For this simple example, let’s just write out the number of contacts found. Because data is loaded asynchronously, we need to use the dataBind trick again so that our code fires after the Contacts are loaded on the screen.

 myapp.BrowseContacts.Contacts_render = function (element, contentItem) {
    // Instead of Screen, we passed Contacts as the contentItem. 
    var contacts = contentItem.value;

    // Set up the callback function to fire after the data is loaded.
    contentItem.dataBind("value.isLoaded", function ()
    {
        if (contacts.isLoaded) {
            //Create the HTML control
            var template = $("<b> " + contacts.count + " contacts found.</b>");
            //Append it to the DOM
            template.appendTo($(element));
        }
    });   
};

In action:

image

More Resources

There are a lot of articles out there on how to implement more advanced controls. I encourage you to check these out.

Well that wraps up the Beginning LightSwitch in Visual Studio 2013 series! Thanks for reading and have fun building mobile business apps with LightSwitch! And for more information, please visit the LightSwitch Developer Center and the LightSwitch Team Blog.

Enjoy!

Download the Completed Sample App

Comments

  • Anonymous
    January 29, 2014
    Thanks for another great post! Honestly how do you keep coming up with those titles? Extra hint for the readers: you can make the 'gray border' around each record disappear by applying the male of female CSS class to the parent ListItem instead of to the actual element: $(element).parent('li').addClass("female"); Keep rocking LS! Jan

  • Anonymous
    January 29, 2014
    LOL Thanks Jan! Thanks for the tip! In my case though, I want to preserve the orange highlight on the boarder when the item is selected, so I did it this way. I should also mention to everyone that F12 debugging tools in IE are your friend for figuring out the DOM elements you're working with. Kevin's post talks about this blogs.msdn.com/.../introduction-to-jquery-for-customization-in-cloud-business-apps-kevin-mehlhaff.aspx Enjoy!

  • Anonymous
    January 30, 2014
    Hi, any chance you or your team can do a post about how Globalization is being handled on the HTML client? Thanks

  • Anonymous
    January 31, 2014
    @Mihai - we did a post a while back here: blogs.msdn.com/.../localizing-a-lightswitch-application.aspx You can also chek out this step-by-step in the library: msdn.microsoft.com/.../xx130603.aspx Cheers, -Beth

  • Anonymous
    February 02, 2014
    The comment has been removed

  • Anonymous
    February 03, 2014
    @Ankur -- Sorry you're having trouble. Sounds like a bad install, but I'm not sure. Can you please post in the forums if you haven't done so already? People there can help troubleshoot better: social.msdn.microsoft.com/.../home

  • Anonymous
    February 03, 2014
    @Ankur's problem is resolved :) Nice article as always!

  • Anonymous
    February 04, 2014
    Thank you Beth! It's exactly what I wanted to see.

  • Anonymous
    February 09, 2014
    Hi Beth, I use VS 2013 LightSwitch to create a cloud app for O365. Datasource is a SharePoint (2013) list. I am not able to see the attachments to the list items. I found this article saying that list item attachment is NOT supported in LS V1. Is it still the case for LightSwitch VS 2013? This is the link to the article that I found. social.msdn.microsoft.com/.../accessing-sharepoint-list-item-attachments Thanks so much for your help!

  • Anonymous
    February 13, 2014
    @Sydney - that's correct we don't currently support list attachments directly. However there is a NuGet package available that you can use to add some custom code to upload attachments to a document library. See: blogs.msdn.com/.../html-upload-control-for-lightswitch-sharepoint-apps.aspx HTH, -Beth

  • Anonymous
    February 14, 2014
    Thanks Beth!

  • Anonymous
    February 24, 2014
    Thanks for great post!.. can you share the sample project code base

  • Anonymous
    February 24, 2014
    @sravan - Sure, the sample is here: blogs.msdn.com/.../beginning-lightswitch-in-visual-studio-2013-address-book-html-sample.aspx

  • Anonymous
    February 24, 2014
    @Beth Massi.. Thanks for quick response and source code

  • Anonymous
    March 16, 2014
    Hi Beth, I'm still a little behind with all this HTML Client stuff, but I'm getting there, I'm slowly catching up. It's great articles like this one that are helping that process along. Thanks!

  • Anonymous
    March 18, 2014
    @Yann -- Thanks! It's great to "see" you again :-)

  • Anonymous
    April 08, 2014
    Hi Beth, I had some trouble with adding custom control. When I run it, I see "0 contacts found. 6 contacts found" below the list. since I have 6 contacts. it seems the app is counting twice the no of contacts.

  • Anonymous
    April 08, 2014
    its ok now. I re-started VS and it is working now

  • Anonymous
    April 28, 2014
    I use the same html design and silverligth same database?

  • Anonymous
    October 06, 2014
    I worked through the whole series using VS2012.4 with support for the HTML Client. However I couldn't get the custom control showing the number of contacts to display. (I wish the context menu didn't overlay the screen design tree in the figure above.) I then used the link at the bottom of the article to downloaded the completed sample app, so I could examine the Browse Contacts screen with the custom control added. I unzipped it to a temp folder (so as not to conflict with my own solution by the same name) - however it wouldn't load, and then when I tried to re-open my own solution that was broken too! I WISH THERE HAD BEEN A WARNING ABOUT OPENING THE DOWNLOAD, IF IT WAS ONLY GOOD IN VS2013 AND MIGHT CLOBBER AN EXISTING SOLUTION WITH THE SAME NAME. If this page is still being monitored any advice would be appreciated.

  • Anonymous
    October 06, 2014
    Hi Laura, Sorry you're having trouble but there should be no effect on your solution if you downloaded the sample to a separate location. In fact, the VS2013 solution shouldn't have even opened in VS2012. What was your exact error? -Beth

  • Anonymous
    October 07, 2014
    The comment has been removed

  • Anonymous
    January 08, 2015
    Hi, i have an html client app, then i have a screen called records where the users score parameters with decimal numbers, the decimal separator is comma (,). how can i change it to dot (.)?

  • Anonymous
    August 22, 2015
    Hello Beth, We expect tutorials from lightswitch 2015.