LightSwitch 2013 HTML Client – Easily add Multi Item Selection to your Lists and Tables!

Enhancing your LightSwitch List, Tiles and Table controls – Updated!

We have refactored from the earlier build… so please review the new steps!

TableWithPersist
CustomersLimit4

As of May 2014, Out of the Box LightSwitch list, tiles and table controls only allow for selection of a single item.

Until now!

The demo/test drive has been updated showing the new upcoming functionality check it out: MultiSelect Preview

So… we’re like squirrels here, constantly distracted. And so with that said, we’ve nailed down our long term name for the library. Going forward we’ll be branding as LightSwitch Wires, or lsWires for short. Since in reality that’s kind of what we all do. We add the wiring to LightSwitch to make things work or work better. And this naming convention works for our other disciplines like Kendo UI and Syncfusion. We’ll keep the “Wires” branding and just swap out the prefix for the type of wires we’re providing. Thanks for your patience, this is the LAST breaking change.

Now on with it… Within the lsWires library we've provided the functionality to enhance the list and table controls

  • Selection of multiple items
  • Ability to limit the number of selections
  • Select/Unselect all items
  • Get the selected item count
  • Retrieve the data of the selected items
  • Persist selections for the session
  • We no longer take over the ItemTap
  • Multiple lists can be on the same screen
  • Same code base works across all 3 control types

Sounds awesome eh? So lets get started on how to implement this new functionality…

  1. Create a new LightSwitch 2013 HTML Application
  2. Lets name it: itgLsMultiSelect
  3. When at the Start with data screen, click on Attach to external…
  4. Data Source Type: OData Service
  5. OData service endpoint:
    http://services.odata.org/northwind/northwind.svc/
  6. Authentication type: None
  7. Choose the following entities:
    Customer
    Employee
    Product
  8. Name the data source: Northwind
  9. Click the finish button
  10. Close any open editor windows
  11. Save your solution
  12. Over in your your Solution Explorer pain
  13. Add the following NuGet package to the HTML Client project
    lo-dash.js
  14. From our GitHub repository
    Add lsWires.js to your Scripts folder
    Add lsWires.css to your Content folder
  15. Now open up your default.htm file in the client project
  16. Add lo-dash.js followed by lsWires.js to the scripts section
  17. Add the lsWires.css as the last stylesheet
  18. Right click on the Screens folder, select Add Screen…
  19. Select Browse Data Screen
  20. Screen Data: Northwind.Customers
  21. Click ok
  22. Save your solution, run the application
  23. Go ahead and click on items, notice single selection
  24. Stop your application
  25. Click on the Tile List, Customers
  26. Click on Edit PostRender Code in the properties window
  27. To get intellisense, drag from solution explorer the file lsWires.js onto your page
  28. Now we only need ONE line of code to enable multi-select
    // Enable multi-item selection on this tile control
    lsWire.list.enableMultiSelect(contentItem);
    
  29. Before you can run, remove the default ItemTap that LightSwitch automatically adds for the list. We did not create the view screen that the ItemTap is expecting so you’ll get an error when selecting if you don’t.
  30. Save your solution, run your app
  31. BOOM! Multi-Select enabled!
  32. You can also unselect by clicking a selected item
  33. Hmmmm… how do I get the data of the selected items?
  34. Stop your application
  35. Under the Customer List Tab, add a new Group
  36. Move it right under the Command Bar
  37. Change the type to be a Columns Layout
  38. Then add 3 more Rows Layout under the columns layout
  39. For all 3 change the width setting to Fit to Content
  40. Add a new Button into the first rows layout
  41. Select Write my own method, name it: GetSelected
  42. Double click the button to edit the code
  43. We're going to add a few lines
    Get the list contentItem
    Call our method to get the data, which returns an array of entities
    Then we'll display the data
    var list = screen.findContentItem("Customers");
    var count = lsWire.list.selectedCount(list);
    var selected = lsWire.list.selected(list);
    var text = "Customers Selected\n\n";
    _.forEach(selected, function(item) {
          text += item.CustomerID + " - " + item.CompanyName + "\n";
    });
    text += "\n\nCount = " + count;
    window.alert(text);
    
  44. Save and run your application
  45. Select a few items, click on Get Selected
  46. Unselect a few, Get Selected, only selected get returned
  47. Ok lets continue going thru adding functionality
  48. Add two local properties, boolean
  49. Name them SelectAll and SetLimits
  50. Drag the SelectAll under the second Rows Layout
  51. Change the control type to be of a Custom Control
  52. Over in the properties window, set the label position to None
  53. Then click on Edit Render Code and add the following
    	// Render a checkbox
    	lsWire.checkbox.render(element, contentItem);
    
    	// When the checkbox changes state, either select all or not
    	contentItem.dataBind("screen.SelectAll", function (newValue) {
    		if (newValue != undefined) {
    			var list = contentItem.screen.findContentItem("Customers");
    			lsWire.list.selectAll(list, newValue);
    		}
    	});
    
  54. Now drag the SetLimits property under your 3rd Rows Layout
  55. Change the control type to be of a Custom Control
  56. Change its Display Name to: Limit of 4
  57. Change the label position to None
  58. Then click on Edit Render Code and add the following for this one, its a bit more lengthy as we’re adding in some cool features
    	// Render our checkbox
    	lsWire.checkbox.render(element, contentItem);
    
    	// When the checkbox changes state, set or remove our limits
    	contentItem.dataBind("screen.SetLimits", function (newValue) {
    		
    		if (newValue !== undefined) {
    
    			// Our dependent item
    			var selectAll = contentItem.screen.findContentItem("SelectAll");
    
    			// Get our list
    			var list = contentItem.screen.findContentItem("Customers");
    
    			// Current count of selected items
    			var count = lsWire.list.selectedCount(list);
    
    			// If the checkbox is selected, limit to 4 items
    			if (newValue != undefined && newValue === true) {
    
    				// Set our limit, returns the limit count
    				var ttl = lsWire.list.totalSelectionsAllowed(list, 4);
    
    				// if select all was set, checked
    				if (selectAll.value === true)
    
    					// set the property to false, dataBinding will do the rest
    					contentItem.screen.SelectAll = false;
    
    				// Else is the current count greater than our limit?
    				else if (count > ttl) {
    
    					// Count is greater, so unselect all items
    					lsWire.list.selectAll(list, false);
    				}
    
    				// Since we are limiting, disable the select all checkbox
    				selectAll.isEnabled = false;
    			} else {
    
    				// Limit was unselected, renable select all and remove limits
    				selectAll.isEnabled = true;
    				lsWire.list.totalSelectionsAllowed(list, null);
    			}
    		}
    	});
    
    
  59. Its that easy!
  60. Save and run your application
  61. Toggle your limits
  62. Select your 4 items, try and select a 5th
  63. No can do! Now unselect a selected and select another
  64. Notice the Select All is no longer a valid option
  65. Uncheck the Limit of 4
  66. Test again, notice the limitations were removed
  67. So what happens if this was a list vs a Tile List?
  68. Stop your application
  69. In the screen designer, change the control type to List
  70. Run your app, test the functionality
  71. As you see, same code, different control type, same results!
  72. Now you ask… table too?
  73. Yep! Go ahead and change it to a table control
  74. Run and test the app
  75. Same code, works as expected on all 3 controls!

So there you go… an easy, reproduceable method of enabling multi-select on your LightSwitch list controls. You can even have multiple lists on the same screen, each will behave independently. We'll leave that up to you to go play around and test. Our sample project already has a multi-list screen if you want to go check it out.

We’ve added functionality to persist selections for a session. Its also a key part for a table control if you are going to allow your clients to change the sort order by clicking on the columns. You’ll set the control to persistSelections and it won’t be a problem. Check out the sample project for the code, its quite simple. Also check out the live preview on how it works.

Obviously if you are using an ItemTap to get to an edit/view screen, you would not implement this, but you could, since we no longer take that over and we do allow for persistent selections. But for most, selection and batch processing, this is the ticket.

One final note regarding the Select All functionality. We are selecting and working with rendered items. So with virtual scrolling, not all items from a query have been returned and rendered. Which means if you do a Select All, scroll and more data comes down, the new data is not selected. Of course one could go and press the Select All button again, or you could do a dataBind and fire off another Select All. But I don't see many instances of where that is appropriate. But you could.

Enjoy! More to come…

LS2013 – Easily add Checkboxes to your project!

This quick tutorial will show you how to turn a LightSwitch boolean property into a checkbox.

  • Cross browser
  • No text checkbox
  • Custom CSS for checked/unchecked
  • Still use the power of LightSwitch dataBind
  • Aligns with existing LightSwitch controls
  • … its free…

Checkboxes

You can download the code and sample project from our repository at GitHub.
You’ll find the Stylesheet and JavaScript for this tutorial in the Assets folder..

Project Setup

  1. Create a new Visual Studio LightSwitch HTML Client
  2. Create a new Table named Test with the following properties
    • Boolean1, Boolean, not required
    • Boolean2, Boolean, not required
    • Boolean3, Boolean, not required
    • Boolean4, Boolean, not required
  3. Create the associated Browse/Add/Edit screens for your table
  4. Save and build your solution
  5. Run your app, add some records
  6. Close the app, return to Visual Studio
  7. Right click on the HTML Client project Content folder
  8. Add existing item, navigate to the Assets folder and add itgLsCheckbox.css
  9. Right click on the HTML Client project Scripts folder
  10. Add existing item, navigate to the Assets folder and add itgLsCheckbox.js
  11. Add both to your default.htm in their corresponding sections
  12. Open up the Add/Edit screen
  13. Change the screen to not Show As Dialog, or not
  14. Delete everything under the Details tab
  15. Now under the Details tab create the following structure
    1. Columns Layout – Group
      1. Rows Layout – Col1, width fit to content, min width 100
        • Boolean1, change to custom control
        • Boolean2, change to custom control
        • Boolean3, change to custom control
        • Boolean4, change to custom control
      2. Rows Layout – Col2, width fit to content, min width 100
        • Boolean1, change to flip switch
        • Boolean2, change to flip switch
        • Boolean3, change to flip switch
        • Boolean4, change to flip switch
      3. Rows Layout – Col3, width min of 100, max width 200
        • Boolean1, change to text box
        • Boolean2, change to text box
        • Boolean3, change to text box
        • Boolean4, change to text box
  16. Save and build your solution

Edit Custom Controls

  1. In the Properties tab for each of the controls in Rows Layout – Col1
    • Boolean1, Description: Hello World!
    • Boolean2, Description: My favorite color is blue
    • Boolean3, Description: I like water
    • Boolean4, Description: Leave blank
  2. Again for each of the controls in Rows Layout – Col1
  3. In the Properties tab, click on the Edit Render Code
  4. Once you’ve done all 4, go into the associated JavaScript code behind file
  5. For each of the render methods, add the following code
    itgLs.ui.checkbox.render(element, contentItem);
    

  6. Save and build your solution
  7. Run your application
  8. Navigate to your add/edit screen
  9. You should see a column with checkboxes, one with flip switches, and one with textboxes
  10. Start clicking around, you’ll notice they all get updated no matter where the data changes
  11. Notice how you can have the top label and text as different and showing at the same time
  12. Now for each custom control go change the Label Position property to “none”
  13. Go rerun your app
  14. Hmmm… notice number 4 has text. Here is the order of how we get the text for a control
    • Text property passed in the options object of the function (overrides all)
    • Description field of the control properties
    • Display Name field of the control properties (only if the Label Position is set to None)

Adding Custom CSS

  1. Open up the file: user-customization.css
  2. Add the following to the end of the file
  3. /* These are used for testing our checkboxes */
    .red-small-bold {
        color: red;
        font-size: 10px !important;
        font-weight: bold;
    }
    
    .green-bold {
        color: green;
        font-weight: bold;
    }
    
    .blue-bold {
        color: blue;
        font-weight: bold;
    }
    
  4. Save the file

Customizing Boolean1

  1. Open up your JavaScript code behind file for your Add/Edit screen
  2. We are going to customize the rendering of Boolean1
  3. The following properties can be passed as options to the render method
    • text – Text to display to the right of the checkbox itself
    • checkedCssClassForText – A CSS class to be used on the text when the box is checked
    • uncheckedCssClassForText – A CSS class to be used on the text when the box is unchecked
    • onChange – function to run when the checkbox is clicked and changed
  4. There are no dependencies between options. You can pass all, a single, or none.
  5. Lets make Boolean1 do some fancy stuff when its checked/unchecked
  6. Change the itgLs.ui.checkbox.render function with the following code
  7. // Render our custom control as a checkbox
    itgLs.ui.checkbox.render(element, contentItem, {
        text: contentItem.value ? "This is true" : "This is False",
        checkedCssClassForText: "green-bold",
        uncheckedCssClassForText: "red-small-bold"
    });
    
  8. The code is only for the initial rendering of the control. So for example this is setting the default text to display based on the initial value of the contentItem. Which will override the Description property of the control.
  9. The CSS Classes we added will persist and be used as such until changed
  10. Now add some dataBind code for when the actual data changes, right under our render code
  11. // We will change both Text and CSS when the value changes
    contentItem.dataBind("value", function(newValue) {
    
    	// Make sure the view (html) has been rendered before we try to modify it
    	if (contentItem._view.isRendered) {
    
    		// Create new text for displaying, if desired
    		var txt = newValue ? "This is True" : "This is False";
    
    
    		// Call our helper function to set the text
    		itgLs.ui.checkbox.setText(contentItem, txt);
    
    	}
    });
    
  12. Pretty explanatory with the comments so I won’t repeat here
  13. Save, build and run your solution
  14. Click on the checkbox, click on the flip switch, change the textbox value to 1 or 0 or true or false
  15. Notice how not only the text changes, but also the CSS kicks in.

Customizing Boolean2

  1. Open up your JavaScript code behind file for your Add/Edit screen
  2. We are going to customize the rendering of Boolean2
  3. Remember, the following properties can be passed as options to the render method
    • text – Text to display to the right of the checkbox itself
    • checkedCssClassForText – A CSS class to be used on the text when the box is checked
    • uncheckedCssClassForText – A CSS class to be used on the text when the box is unchecked
    • onChange – function to run when the checkbox is clicked and changed
  4. And remember, there are no dependencies between options. Pass all, a single, or none.
  5. Change the itgLs.ui.checkbox.render function with the following code
  6. // Render our custom control as a checkbox
    itgLs.ui.checkbox.render(element, contentItem, {
        text: contentItem.value ? "My favorite color is green" : "My favorite color is blue",
        checkedCssClassForText: "green-bold",
        uncheckedCssClassForText: "blue-bold"
    });
    
  7. The code is only for the initial rendering of the control. So for example this is setting the default text to display based on the initial value of the contentItem. This will override the Description property of the control.
  8. The CSS Classes we added will persist and be used as such until changed
  9. Now add some dataBind code for when the actual data changes
  10. // We will change both Text and CSS when the value changes
    contentItem.dataBind("value", function(newValue) {
    
    	// Make sure the view (html) has been rendered before we try to modify it
    	if (contentItem._view.isRendered) {
    
    		// Create new text for displaying, if desired
    		var txt = newValue ? "My favorite color is green" : "My favorite color is blue";
    
    		// Call our helper function to set the text
    		itgLs.ui.checkbox.setText(contentItem, txt);
    
    	}
    });
    
  11. Pretty explanatory with the comments so, again, I won’t repeat here
  12. Save, build and run your solution
  13. Click on the checkbox, click on the flip switch, change the textbox value to 1 or 0 or true or false
  14. Notice the new changes when clicked!

Customizing Boolean3

Ha! We are going to do nothing more with Boolean3.
This will demonstrate how you can easily render a simple checkbox.

Customizing Boolean4

  1. Open up your JavaScript code behind file for your Add/Edit screen
  2. We are going to customize the rendering of Boolean4
  3. Change the itgLs.ui.checkbox.render function with the following code
  4. // Render our custom control as a checkbox
    itgLs.ui.checkbox.render(element, contentItem, {
        text: ""
    });
    
  5. This simple code will create a checkbox with no labels. Remember the passed text property overrides all
  6. Save, build and run your solution
  7. Click on the checkbox, click on the flip switch, change the textbox value to 1 or 0 or true or false

Final Thoughts

  1. You can also have a no label checkbox without passing an empty text property by the following method
    • No text in the controls Description property
    • A single space for the Display Name property for the control
  2. Notice resizing the browser works as expected
  3. Remove the other labels from the other controls, notice alignment is as expected
  4. Works as expected on IE and Chrome
  5. Has not been tested yet on IOS
  6. There is additional functionality for updating the text and CSS
  7. Uh… its been tested heavily, but there is no bug free! :)
    • setText(contentItem, text, classToAdd, classToRemove)
    • addCssClassForText(contentItem, cssClass)
    • removeCssClassForText(contentItem, cssClass)
    • initializeCss(element, css)

Based on the work of the following folks, many thanks go out to them, please frequent their blogs:

Jewel Lambert and Mike Droney

LightSwitch 2013 – March 2014 Update – Bug

This is one of a few “issues” that are cropping up with the March 2014 update to LightSwitch 2013.

This is most likely for those that go outside the expected “normal” for LightSwitch, which fortunately may affect only a few. For example, creating a screen that does not have any “official” data items. Where we are just creating our own custom control and rendering our own content.

The LightSwitch runtime does NOT like this, yet will not complain until the worst possible time… to repro:

  1. Create a new Browse screen, No screen data
  2. Don’t add any properties or data items
  3. Add your custom control, render as you see fit
  4. Or for this exercise, don’t add anything, same result
  5. Save your solution
  6. Build and run
  7. All works as expected

Until…

User is on your custom screen and presses the refresh button on the browser
The LightSwitch JavaScript runtime will error out due to an array length issue
Bug was tracked down to starting at line 11909 in file msls-2.5.0.js
It does not like the fact that screenParameters has an “undefined” value

So whats the work around?

  1. Add a data item to your screen
  2. Can be any, ie: boolean
  3. Name doesn’t matter
  4. Not necessary to add to your visual screen design
  5. Save your solution, run and test
  6. Issue resolved

This was/is causing a problem with my core project, which I’m in the process of upgrading.

Also take a look at this thread where others are also having issues when it comes to the new “Deep Linking”.

Be forewarned!

LS2013 HTML Client – New Screen Template for Enhanced Table (grid)

Back in business!  Seems it was a process issue which I’ve taken care of by automating the said process.  Which was the order of the javascript files and lodash needing to be before our file.  Now our itgLsEnhancedTable NuGet package will take care of modifying the default.htm file for you.

We’ve published a LightSwitch extension into the Visual Studio Gallery to help with your usage of our Enhanced Table code.  This is a standard vsix extension and can be installed from within Visual Studio itself.

In Visual Studio, go to Tools, Extensions and Updates, on the left side of the dialog, select Online.

Search for itgLsEnhancedTable

You should get one result, install the extension

Create a new LightSwitch HTML Client

Double click on the properties for the LightSwitch project, go to the Extensions tab and enable the itgLsEnhancedTable extension.

Right click on your HTML Client project, Add our Nuget package itgLsEnhancedTable.

Add a datasource, we’ve started to use the Northwind odata feed at http://services.odata.org/northwind/northwind.svc/ for our tutorials going forward.

Add a new screen to your project, select our extension Itg Ls Enhanced Table, select your datasource.

Boom!  Screen gets created, code is generated.

Delete any unnecessary data fields from the table control.

Run your app.

Let me know what you think and if we should continue with screen templates.

Enjoy!

LS2013 HTML – Enhancing Table Control with Multi Column Sort and Filters

Mar 6, Here we go again! This is ANOTHER major update…

eht_final

  • Ability to sort on multiple columns
  • Easily Toggle Ascending, Descending, or no sort
  • Columns show their individual position in the sort order
  • Filtering on individual columns
  • Filter on Strings, Numerics and Dates
  • Popup filter dialog
  • Filtering can be disabled if not needed
  • Can be configured for batch processing
  • Batch mode can also be dynamically toggled
  • Compatible with latest LightSwitch update

Lets start by having you go up to http://github.com/dwm9100b/LsEnhancedTable and grab the latest code for this project. Make sure you right click on the downloaded zip, go to properties, and click on the Unblock button before unzipping.

As usual though, I’ll go thru a step by step process on how we got to the project you just downloaded. We’ve made this so easy its going to be hard to resist. So lets get to it…

  1. Create a new LightSwitch HTML Project
  2. Lets name it: EnhancedTable
  3. We’re going to use an external data source
  4. Select the OData Service option
  5. Use the following endpoint:
  6. Uncheck the ‘as read-only’
  7. Under authentication, select none
  8. When prompted to Choose your Entities
    • Select Order
    • Expand Order, Related Entities
    • Select Employee
  9. Name the data source: Northwind
  10. Click on finish, save your project

That’s all we’ll have to do with the ‘Server’ part of this project. The rest of the tutorial will be with the HTML Client.

  1. Right click on your HTML Client project
  2. Select Manage NuGet Packages
  3. Select the Online packages
  4. Search and install itgLsEnhancedTable
    • Three files get installed
      • Lo-Dash which is an awesome, lightweight alternative to Underscore.js. They’ve even included a ton of extras. Highly recommend that you check it out!
      • itgLsEnhancedTable.css (some quick styles used for the new table)
      • itgLsEnhancedTable.j
  5. Add all 3 files to your HTML Client default.htm
    • itgLsEnhancedTable.css
    • Lo-Dash.js
    • itgLsEnhancedTable.js
  6. We now automagically take care of step #5 for you when you install the NuGet package.

Great! That’s all the pre-work needed. Now lets go create our screens.

  1. Right click on your Screens folder
  2. Select Add Screen
  3. Lets use the new “Common Screen Set”
  4. Screen Data, Select Northwind.Orders
  5. Once LightSwitch does its magic, you’ll land on BrowseOrders
  6. Change the default Tile List for Orders to a Table
  7. Drag over some additional Order properties
    • Freight
    • ShipName
    • ShipCity
    • Employee
  8. Expand the Employee, change to a row layout
  9. Drag the Employee Last Name up under Ship City
  10. Delete the rest of the row layout for employee
  11. Change the Display Name for Last Name to Employee Last NameHere is how the screen should look by now
    eht_BrowseOrdersScreen_Base
  12. Good time to do a full build and test run your app. Test the out of the box functionality.
    • Notice you’ll only able to sort a single column at a time
    • Also the Search only supports strings
    • Not able to search on multiple columns
    • Unable to remove the Search input once its displayed

Ok, enough of that. Lets supercharge this table!

We start off by creating a few local properties via the Add Data Item. Uncheck the “Is Required” on all you create.

  1. Type: String, Name: ColumnName
  2. Type: String, Name: Operator1
  3. Type: String, Name: Value1
  4. Type: String, Name: Concat
  5. Type: String, Name: Operator2
  6. Type: String, Name: Value2

The following new Local Properties need to have a Choice List. So for each one:

  • Operator1
  • Concat
  • Operator2
    1. Over in Properties
    2. Click on Choice List
    3. Add a single value, “a”

We dynamically load choices, hence the reason for just a single value so LightSwitch will initialize the control

Great! Now lets go create our Filter popup

  1. Add Popup
  2. Leave as default Rows Layout
  3. Change the name to: FilterPopup
  4. Case sensitive!
  5. In order, drag the following local properties into this popup
    • ColumnName
    • Operator1
    • Value1
    • Concat
    • Operator2
    • Value2
  6. Change Column Name to be a Text control
  7. In properties for each, change Label Position to NoneYou should have a screen that looks as soeht_BrowseOrdersScreen_WithFilterProperties
  8. In your popup, add a new group, change it to Columns Layout
  9. Add a button into this group
    • Write my own method
    • Method name: SetColumnFilter
    • Change its Display Name to “Set”
  10. Add another button into this group
    • Write my own method
    • Method name: ClearColumnFilter
    • Change its Display Name to “Clear”

Here is how your final layout of your popup should be

eht_BrowseOrdersScreen_FinalPopup

Before we go wiring this all up, lets add a couple of main screen buttons to really show the flexibility

  1. Up at the Command Bar for the Order List Tab
  2. Add a new Button
    • Write my own method
    • Method name: ClearAll
    • Change your icon
  3. Add a new Button
    • Write my own method
    • Method name: ExecuteBatch
    • Change your icon
  4. Add a new Button
    • Write my own method
    • Method name: ToggleBatch
    • Change your icon

Done with the screen, here is a picture of how the final layout

eht_BrowseOrdersScreen_FinalLayout

Go ahead and save your solution and do a build.

Now on to the code, this will be the painless side of it.

  1. Click on the Orders Table control
  2. Edit PostRender Code
  3. Add the following code into its method
    // Store our enhanced table as part of our contentItem
    contentItem.enhancedTable = new itgLs.EnhancedTable({
        element: element,
        contentItem: contentItem
    });
    
    

This is the bare minimum you need to do. Go do a build and run your app. Couple of things

  • Multi column sort works
  • Click on the Column name to toggle direction
  • Notice the position number as you add more columns
  • Notice as you remove a column sort, positions adjust
  • Filter popup will display, but we’ve not wired it up yet

Ok cool eh?

Lets go wire some things up

  1. Double click on your ClearAll button
  2. Add the following code to its execute method
    // Get our table
    var table = screen.findContentItem("Orders").enhancedTable;
    
    // Clear all the sorts and filters
    table.clearAll();
    
    // If we are not in batch mode, reQuery
    if (!table.getBatchMode()) table.reQuery();
    
    
  3. Double click on your ExecuteBatch button
  4. Add the following code to its method
    // Get our table
    var table = screen.findContentItem("Orders").enhancedTable;
    
    // Execute the sort/filter settings
    table.reQuery();
    
  5. Double click on your ToggleBatch button
  6. Add the following code to its method
    // Get our table
    var table = screen.findContentItem("Orders").enhancedTable;
    
    // Toggle batch mode
    table.setBatchMode(!table.getBatchMode());
    
  7. Edit PostRender Code for popup button SetColumnFilter
  8. Add the following code to its method
     // A check mark icon with text at the bottom
     itgLs.ui.convertToIconicButton(element, contentItem, "accept");
    
  9. Edit PostRender Code for popup button ClearColumnFilter
  10. Add the following code to its method
    // A minus icon with text at the bottom
    itgLs.ui.convertToIconicButton(element, contentItem, "remove");
    
  11. Double click on your popup button SetColumnFilter
  12. Add the following code to its execute method
    // Get our table
    var table = screen.findContentItem("Orders").enhancedTable;
    
    // Call our set filter function for this column only
    table.setColumnFilter();
    
    // Close the popup
    table.closeFilterPopup();
    
    
  13. Double click on your popup button ClearColumnFilter
  14. Add the following code to its execute method
    // Get our table
    var table = screen.findContentItem("Orders").enhancedTable;
    
    // Call our clear filter function for this column only
    table.clearColumnFilter();
    
    // Close the popup
    table.closeFilterPopup();
    

Not too many lines of code now is it? Would be great if someone out there creates a screen template!

So there you have it… Go ahead and run the app and test away

  • Test multi column filtering
  • Add sorting into the mix
  • Toggle Batch
  • Set up your filter and sorts
  • Then Execute the batch
  • Try the one click clear all, less server trips!

You can pass the following properties when you create the EnhancedTable

filterPopupName
Name of the filter popup
Defaults to FilterPopup
filterPopupColumnName
Name of the ColumnName property
Defaults to ColumnName
filterPopupOperatorName1
Name of Operator1 property
Defaults to Operator1
filterPopupOperatorName2
Name of Operator2 property
Defaults to Operator2
filterPopupConcatName
Name of the Concat property
Defaults to Concat
filterPopupValueName1
Name of the Value1 property
Defaults to Value1
filterPopupValueName2
Name of the Value2 property
Defaults to Value2
batchMode
True/False
Defaults to false
filterDisabled
True/False
Defaults to false

So whats missing and left to do?

Validations on the filter input boxes
Ability to dynamically change the input boxes to a native control
Anything else I forgot… :)

LS2013 Core Project Updated

Note that the March 2014 Update to Visual Studio caused, what seems like, breaking changes to the user management side of this tutorial.

As time in the next few weeks allows, I’ll be working on updating the content.

We have pushed an update to GitHub. This is a major refactoring which will cause issues with the previous code.

In this update we have moved most of the logic into the external itgLsHelper.js file. There were some minor updates to tables and a few screens that I’ve documented and put in a page here. I’ve also added a BreakingChanges file to the project on GitHub.

Here are some of the items in this update:

  • Password field with validation
  • Confirm Password field with validation, both of these will give you some pretty good information on how to easily implement your own custom validators.
  • A screen picker field used in the tile menu system
  • Client side user roles and permission checking
  • Ability to export the tile menu for inclusion in other or same project(s)
  • Ability to import/use a JSON representation of a tile menu, makes for fast loading
  • Much cleaner by using the itgLsHelper space

Note that these are not specific to the tile menus, but can be used in any other screen/code that you desire. Hopefully you’ll find the value has increased big time with this update. Let me know your thoughts.

Here are a few of the functions included in the itgLsHelper.js file:

init – initializes the system: gets user name & permissions, imports menus

passwordValidator – setup a visual field for password entry and validation

confirmPasswordValidator – setup a visual field for password entry and validate against the password field

screens – returns an array of your screens, name, display name and methods to show them

changeButtonIcon – changes the icon class of a button

colorPicker – setup a visual field as a color picker

iconPicker – setup a visual field as an icon picker

screenPicker – setup a visual field as a screen picker

userHasPermission – does the current user have the permission assignment

userHasRole – does the current user have the role assignment

tileMenu – setup a screen/container for a predefined MetroUI type tile menu

exportTileMenusToJson – export/return a JSON object representing all the tile menus

importJsonTileMenus – import a JSON object representing a set of menus and their tiles

importIconClassList – import a csv list of icon class list

urlParameterByName – get a URL parameter by its name

fixMetadataHandlerForEtag – a fix for a known ETag issue

fixJsonHandlerForEtag – a fix for a known ETag issue

internalHelpers – bunch of functions for internal use, but good information!

Enjoy!

LightSwitch 2013 – Multi-HTMLClient Project!

In this post we will show you how to create a LightSwitch 2013 project that contains multiple HTMLClients. It’s a pretty exciting development, as we can now create apps for specific areas, Admin vs. Worker, and all share the same data source within a single solution. We have tested deployment to Windows Server with IIS and Azure with no issues or workarounds.

A side benefit is app payload. We can break up large enterprise grade apps into multiple clients thus keeping the individual downloads to a reasonable size.

Phil over at Xpert360 gave me a heads up that they had also done some work on multiple HTML Clients. I encourage you to check out their version.

So… here we go!

  1. Open Visual Studio 2013
  2. Create a new LightSwitch Desktop Project
  3. Name: LsMultiClient
  4. Solution name: LsMultiClient
  5. Create two test tables
    App1Item
    App2Item

  6. Set Forms Authentication
  7. Grant debug to SecurityAdministration
  8. Right click on the main LsMultiClient project
  9. Add a new Client, HTMLClient
  10. Name: App2
  11. Add screens to browse App2Items with add/edit
  12. Open the default.htm file
  13. In the document.ready section, update the msls._run() to show the screen you’d like to have as the start screen for this app, msls._run(“App2ItemsBrowse”)
  14. Save all
  15. Right click on the LsMultiClient.App2 project
  16. Select Remove
  17. Right click again on the main LsMultiClient project
  18. Add a new Client, HTMLClient
  19. Name: App1
  20. Add screens to browse App1Items with add/edit
  21. Open the default.htm file
  22. In the document.ready section, update the msls._run() to show the screen you’d like to have as the start screen for this app, msls._run(“App1ItemsBrowse”)
  23. Save all
  24. Right click on the main LsMultiClient solution this time.
  25. Select Add, existing project
  26. Navigate to the LsMultiClient folder, find the LsMultiClient.App2 folder and select the project
  27. Save all
  28. Close your solution
  29. In a Windows explorer, navigate to your LsMultiClient solution folder.
  30. Locate and edit the LsMultiProject.lsxproj in a text editor
  31. Towards the bottom of the file, locate the section.
  32. Copy the LsMultiClient.App1 section
  33. Paste it under the LsMultiClient.App1 section
  34. Change the
    ProjectReference Include=”LsMultiClient.App1\LsMultiClient.App1.jsproj” to
    ProjectReference Include=”LsMultiClient.App2\LsMultiClient.App2.jsproj”

  35. Replace the text in the tag to be LsMultiClient.App2
  36. Get the Project GUID from LsMultiProject.sln for your LsMultiClient.App2 project.
  37. Back in the LsMultiClient.lsxproj file Under the new copied section for LsMultiClient.App2.jsproj
  38. Replace the GUID in the tag with the App2 GUID from your LsMultiClient.sln file
  39. Save your files
  40. Back to Visual Studio 2013
  41. Open your LsMultiClient solution
  42. Select Build, Clean solution
  43. Select Build
  44. Run your app
  45. http://localhost:{port}/App1
  46. http://localhost:{port}/App2
  47. http://localhost:{port}/DesktopClient

Notes

  • Create your HTMLClients starting with your last one
  • You can remove the DesktopClient once you are sure you are done adding HTMLClients
  • Keep screen names globally unique
  • Make sure you set your startup project

You can download an example project from our github.

We will be posting an LsCoreProject with multiple HTMLClients soon.

LS2013 Core Project – PowerShell script to create new app

Here is a PowerShell script, as requested, that will copy your LsCoreProject to a location on your drive and change the name to your choosing. Since LightSwitch doesn’t have an easy way to create a template, this is a pretty good alternative.

Edit the script for your project locations, run the script, wait for the Done dialog, open the new project in Visual Studio 2013, Set the startup project, Set the SecurityAdministration as enabled during debug and you are good to go!!

# =================================================================
# Script to copy and rename a LsCoreProject file
# Should also work for any other LS Project with a few minor edits
# =================================================================

# Source solution location
$sourceLocation = "c:\temp\LsCoreProject-master\LsCoreProject"

# Target solution location
$targetLocation = 'c:\Users\Dale\Documents\Visual Studio 2013\Projects\LsCore'

# What is the original solution name
$origSolutionName = "LsCoreProject"

# What is the new solution name
$newSolutionName = Read-Host -Prompt "New Solution Name?"
$newSolutionFolder = $targetLocation + "\" + $newSolutionName

# Copy the Source to the Target folder
Copy-Item $sourceLocation $newSolutionFolder -Recurse

# Make sure we don't move forward until the folder has been created
while (!(Test-Path $newSolutionFolder))
     {
     Start-Sleep -s 1
     }

# Change to the target location
cd $newSolutionFolder

# Get all the files that match our orig solution name
$files = Get-ChildItem $(get-location) -filter *$origSolutionName* -Recurse

# Change the folder and filenames to the new solution name
$files |
    Sort-Object -Descending -Property { $_.FullName } |
    Rename-Item -newname { $_.name -replace $origSolutionName, $newSolutionName } -force

# Get all the files that has our original name in its body
$files = Get-ChildItem -recurse | Select-String -pattern $origSolutionName | group path | select name

# Loop over all the matching files, replace original with new
foreach($file in $files) 
{ 
	# Replace all the name occurances, save back to original file
	((Get-Content $file.Name) -creplace $origSolutionName, $newSolutionName) | set-content $file.Name 
}

# Acknowledge to the user that we're done
read-host -prompt "Done! Press any key to close."


Couple of things, make sure your LsCoreProject.zip file is unblocked before unzipping, edit the script for your source and target locations.

I’ll also post the script file on github.

Updates are also coming to the LsCoreProject.

Enjoy!

LightSwitch 2013 – Screen shots of multi-client project

So we are in the early stages of documenting how you can have multiple HTMLClients in a LightSwitch 2013 project. But thought I’d throw out some teasers showing the viability. A lot more testing is in order but the process is looking good.

What you’ll be seeing is 1 LightSwitch solution with a Silverlight Desktop client, 2 HTML Clients. All sharing the same Server and data sources. I’ll get the process down and perhaps the community can then optimize it…

See what happens when you are challenged!!

MultiClientLightSwitch

MultiClientLightSwitch2

LightSwitch 2013 Core Project with User Management, Tile Screens, Self Registration

Note that the March 2014 Update to Visual Studio caused, what seems like, breaking changes to the user management side of this tutorial.

As time in the next few weeks allows, I’ll be working on updating the content.

NewNativeUserMgt

As noted in the title, this tutorial will show you how to setup a core LightSwitch 2013 project. Not just any LightSwitch project, but one that will allow User Management natively vs. having to use Web API. We’ll also show you how to implement a highly configurable system that supports creating MetroUI style tile menus. Finally, it doesn’t do any good if you can’t deploy the application, so we will show you how with Microsoft Azure.

I know that this is a huge tutorial, again. I did try to make it a bit more manageable by breaking it up into pages vs. one humongous post. I encourage you to go through the tutorial (at least read it) rather than just downloading and running the code, there are some items that you should understand in order to have a successful deployment. Or Not :)

Here are the topics and their logical order:

  1. Create the project
  2. Add external CSS
  3. Add external scripts
  4. Update the default.htm
  5. Add LogIn/LogOut/Register/ChangePassword
  6. Create the security data source
  7. Screens for permissions
  8. Screens for role management
  9. Screens for user management
  10. Tables for tile menus
  11. Screens for icon management
  12. Screens for menu management
  13. Create a tile menu screen
  14. Create a database project
  15. How to deploy successfully
  16. Wrap up
  17. How to update B1 projects

Tutorial code can be downloaded from github at LsCoreProject.

Follow

Get every new post delivered to your Inbox.

Join 145 other followers