Category Archives: Web.Api

LightSwitch HTML Client – How to gracefully handle session timeouts

Annoyed with session timeouts when using Forms Authentication?

Check out this quick, easy fix that will gracefully handle this situation and send them back to the login page.

No doubt that you’ll add this to every one of your forms authentication application, LightSwitch or not.

Click here to go to our tutorial.

LightSwitch HTML Client – The lsWire Core Project

Our new lsWire Core project will be the basis for all of our tutorials going forward.

Its based on the lsWires framework and is our first tutorial being hosted on our new site, http://lightswitch.codewriting.tips

This is also our first tutorial that we’re providing a “Starter Kit” so that you can not only quickly get going, but that you can create as many new solutions from this core project as needed.

This little item alone will, hopefully, dramatically change the landscape of the LightSwitch ecosystem. By allowing developers to provide their own starter kits from their own amazing solutions.  Especially since Visual Studio has not provided a means for creating templates from LightSwitch Applications.

Click here for a direct link to the tutorial.

Tagged , ,

LightSwitch 2013 How To Use – GetExpandedUser

We’ve been asked how to use some of our AccountController features. One very handy, which everyone should start to use, is the GetExpandedUser call. With this call you can easily get user data that includes Roles and Permissions and have it saved into the global application space. This allows you to easily do some client side branching without going back to the server.

Obviously this is only valid for the current user session but if, when logging in, the user opts in to “Remember Me”, it will easily pull the data when the new session starts.

Typically you’ll add this to your startup screen created method.


myapp.UserMenu.created = function (screen) {

     // If we don't have a global user, go get the logged in user data
     if (myapp.user == undefined) {
          $.getJSON("/rpc/Account/LoggedInUser").then(function (data) {
               $.getJSON("/rpc/Account/GetExpandedUser/" + data.Name, function (userData) {
                    if (userData != undefined) {
                        myapp.user = $.parseJSON(userData);
                    }
               });
          });
     }
};

LightSwitch 2013 User Management – HTML – Part 2

Adding the User Interface

There are a few prerequisites in order for this to work and/or make any sense.  So please go thru the following posts to get up to speed:

Start here…  How To Create An Expanded LightSwitch 2013 Project

Then… LightSwitch 2013 User Management – HTML – Part 1

Note that we are using JQuery 1.9.1, if something breaks check the file requirements in the _AdminLayout.cshtml.

So now that we have LightSwitch, MVC, Web API and our AccountController all working correctly, lets go add a UI to manage our users.  To do this we’ll be using Kendo UI for our grids and Bootstrap for the responsive layout.

  1. Right click on your server project, Select Manage NuGet Packages…
  2. Search for and install KendoUIWeb
  3. Add a new folder under your server scripts folder, name it: App
  4. Copy the files roles.js and users.js, from the GitHub zip, into this folder and include them in your project
  5. Under your server project Views folder create a new folder named: Admin
  6. Copy the files Index.cshtmlRoles.cshtml and Users.cshtml into this folder and include them in your project
  7. Copy the file _AdminLayout.cshtml into your server project Views/Shared folder and include it in your project
  8. Copy the file AdminController.cs into your server project Controllers/Mvc folder and include it in your project
  9. We now need to update jquery.validate, so right click on your server project, Select Manage NuGet Packages…
  10. On the left side of the NuGet dialog, Select Updates
  11. Select JQuery Validation, click Install
  12. Close NuGet
  13. Open the AccountController.cs and remove your comment from the [Authorize] attribute
  14. Final item… Critical for testing!!
  15. Open your server project root web.config file, Update the following appSettings:
    Microsoft.LightSwitch.Admin.UserName
    Microsoft.LightSwitch.Admin.FullName
    Microsoft.LightSwitch.Admin.Password
  16. Select Build, Clean Solution
  17. Select Build, Build Solution
  18. Run your solution.
  19. Test at http://localhost:{port}/Admin and select Users or Roles.

Few things that need mentioning

  • Complex data is sent in the body of the request
  • When editing a user in the Admin App we don’t mask the password input on purpose
  • You can unlock a locked account by editing a user and unchecking the Locked checkbox
  • When editing a user, password will  only be changed if you add something into the password box, standard password rules apply
  • We’ve stripped out a lot of the validation to simplify this demo
  • We are not using bundling, again to simplify the tutorial
  • The client app is responsible for catching and notifying the user of exceptions.
  • This version of the AccountController is designed for Ajax calls.  We also have a version designed for server side MVC/API code.  Converting is a good exercise that I highly recommend
  • Remember… this is a demo!

I hope this will be as valuable to you as it is to us.. finally no reason for the Silverlight Client!

Happy Coding!

LightSwitch 2013 User Management – HTML – Part 1

Building The Base

This project builds upon a previous project. If you have not already done so, follow the instructions in the following blog post first:

How To Create An Expanded LightSwitch 2013 Project

You will also need the code from GitHub at:
Updated on GitHub: AccountController.cs

LightSwitchUserUserManagement

Make sure you right click on your downloaded file and unblock the file.

All done? Great… lets start!

  1. Under your App_Start folder in your server project, Open WebApiConfig.cs
    Add the following new route

    config.Routes.MapHttpRoute(
    name: "DefaultRpc",
    routeTemplate: "rpc/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
    );
  2. Save and close the WebApiConfig.cs
  3. Add a new folder in the root of your server project name it: DTOs
  4. Add another new folder, this time in your Controllers folder: RpcOdd… but with LightSwitch I have found the easiest way to add external files is to load up an instance of Windows Explore and copy from there. Then back in Visual Studio, show all the files for your project, press the refresh button, then right click on the new files and include in your project.So… lets add some files.
  5. Add the AccountDTOs.cs file from the DTOs folder, in the zip you downloaded from GitHub, to your server project DTOs folder.  Include the file in the project.
  6. Add the AccountController.cs from the RPC folder, in the zip you downloaded from GitHub, to your server project Controller/Rpc folder. Include the file in the project.
  7. Right click on the your server project, select Add, Reference, find and select:  System.Web.ApplicationServices
  8. Open the properties of your LightSwitch main project. Click on the access control tab and add a few permissions so you can see how this works.
  9. Save all
  10. Select Build, Clean solution
  11. Select Build, Build solution
  12. Run your solution…

Hopefully you will get a clean build.

So… now lets talk about good ways to test API/RPC type of calls. You might want to Install Fiddler… it’s a pretty robust product…

But, if you have Google Chrome, Go to the app section in Chrome and install the REST Console. This app does a nice job of including authentication into the calls it makes. Definitely should have this in your tool belt since putting authentication into Fiddler is not so easy.

Now that you have the REST Console installed… you can call some of the functions in the account controller. Notice the /rpc/ in the URL:

http://localhost:port/rpc/Account/GetUsers
http://localhost:port/rpc/Account/GetApplicationPermissions
etc

Hmmm… didn’t work? Most likely due to the [Authorize] attribute is still turned on in the controller.

For this exercise, go back into the AccountController.cs and comment out the attribute beginning at line 46 of the controller. Then test again.

Pretty cool eh?  Next up will be a full HTML based User Management app.

How To Create An Expanded LightSwitch 2013 Project!

This process requires the March 2014 Update

I’m happy to report that the March 2014 Update brought back SCAFFOLDING!! Yay!

How to add Web API and MVC to a LightSwitch 2013 project

Visual Studio LightSwitch is a great product. But it’s not the end all and most professional development projects require a mix of technologies to be considered successful. By following these steps, you’ll end up with a LightSwitch project that has the HTML Client, Silverlight Client, MVC, Web API and Web Forms with the naming conventions of your choosing. Giving you a solution without restrictions!

First time thru the tutorial it may still take you 15 minutes. So give it a try and see what you think… Oh… btw you can clone/download the updated sample project from github… you’ll need this, but really only for the WebApiConfig.cs.

  1. Start Visual Studio 2013
  2. Create a new project: File, New Project…
  3. Select LightSwitch HTML Application
  4. Name the project: myTest
  5. Name the solution: myTest
  6. Create new table
  7. Name it TestItem, 1 property, Name
  8. Add your browse/add/edit screens for the TestItems table
  9. Double click on the properties file for the myTest project
  10. Enable forms authentication, and allow Security Admin for debug
  11. Save the solution, do a full build, run the app
  12. Add some test data into the table
  13. Back into Visual Studio
  14. Right click on your server project
  15. From the Add Scaffold window, click on MVC 5 Dependencies
  16. Press the Add button
  17. On the Add MVC Dependencies popup
  18. Select the Full Dependencies option, press the Add button
  19. Close the web.config that gets automatically loaded
  20. In the App_Start folder, open RouteConfig.cs
  21. Add the following line under the other IgnoreRoutes
    routes.IgnoreRoute("{*allsvc}", new { allsvc = @".*\.svc(/.*)?" });
    
  22. Right click on the App_Start folder, add a new Class file
  23. Name it WebApiConfig.cs
  24. Replace the contents with the contents from the WebApiConfig.cs file from our zip file
  25. Add two folders under the Controllers folder
    1. api
    2. mvc
  26. Right click on the api folder, select add, select New Scaffold Item
  27. Select Web Api 2 Controller with Read/Write actions
  28. Name it TestController
  29. Follow the instructions of the readme.txt file that automatically opens in the editor
  30. Make sure the GlobalConfiguration.Configure gets added to the beginning of Application_Start
  31. In the Controllers folder again, right click on the mvc folder, select add, select New Scaffold Item
  32. Select MVC 5 Controller with read/write actions
  33. Name it HomeController
  34. In the HomeController.cs file that gets automatically loaded
  35. Right click on the ActionResult Index()
  36. Select add view
  37. In the Add View dialog, leave all defaults, just click on add
  38. Go edit your default.aspx page in the root of the solution
  39. Comment out the first line… add some test text to the body
  40. Do a full save, then rebuild, run your app

Your LightSwitch html app will run first with your custom URL path
http://localhost:{port}/App

Moving on, let’s test access to the ApplicationData.svc file
http://localhost:{port}/ApplicationData.svc

So far so good eh? How about our MVC?
http://localhost:{port}/Home

Yay! Looking good… now our default.aspx file in the root…
http://localhost:{port}/default.aspx

Yep that works too… final test… the Web.Api side…
http://localhost:{port}/api/Test

You can now go in and clean up the project, delete the test screen, test table, etc.
Save the solution again.

This would be the point when you would add your project into source control.

One of the great features out of this is we can use Visual Studio LightSwitch to do all of our data management without having to go down into the Entity Framework.

Happy coding!

Tagged , , ,