John Holmes and the case of the mysteriously missing LightSwitch record

Chapter one: the night of disappearance

The cold wind was howling in the streets when Holmes knocked on Elvis’ door.  “It just doesn’t make sense”, was the first thing Elvis said, “it’s simply… gone”…

Aight, pause please. I’m enjoying high 80s (Fahrenheit) at the moment here in the Caribbean, there was no door (just skype) and Elvis is not the actual name of the developer I was helping. I’ll try fiction again in a couple of years, let’s just get through the story of this missing LightSwitch record I encountered last week because I’m pretty sure one day, someone is going to stumble upon a similar issue and this blog post will save him/her half an hour of being dumbfounded…

Chapter one: (for real this time): a record went missing

So here’s what really happened: Elvis called me up because the LightSwitch desktop application that he was working on was throwing an unexplainable nullpointer exception. Unexplainable, because his flow was really basic, textbook easy even:

a) create a record from a “create new entity” screen (the entity was called a “case”)

b) when the screen has successfully saved the new record, use code to close the “create new entity” screen and open the default detail screen for that case enity

c) a nullpointer exception happens in the _initializeDataWorkspace method on this.Case

I’d never seen this before. Right after successfully saving, we show a detail screen on the same entity and the entity just disappears. I’m pretty sure at that point I spent at least 10 minutes of mumbling “I’m dumbfounded“. We started debugging and piece by piece we were able to reassemble the complete puzzle…

See, each screen in a LightSwitch desktop application has its own DataWorkspace.  This is LightSwitch’ implementation of the unit-of-work pattern, whatever changes happen in one screen get committed as a whole upon saving, and either all changes are persisted to the data source or, in the case of an exception, none.

Since each screen has it’s own DataWorkspace, a single entity can exist multiple times (multiple instances) in different DataWorkspaces.  This also means that, unlike the LS HTML client, when you type code like

this.Application.ShowDefaultScreen(this.Case);

the framework will actually take this.Case, an entity which belongs to the DataWorkspace of the “Create new entity” screen,  and pass only the ID field(s) to the new “Detail” screen.  The new screen will then actually use the ID(s) to retrieve the entity again, this time in its own DataWorkspace.

Chapter 2: the resource segment cannot be found

Sure enough, Fiddler soon revealed that when the second screen tried to retrieve the entity again, something went wrong.

Really wrong.

The exception returned was something along the lines of “the resource segment cannot be found for ‘http://localhost:xxxx/ApplicationData.svc/Case'”

Another ten minutes of mumbling about how dumbfounded I was, went by, before we got an Epiphany…

LightSwitch uses the OData protocol to interact with the server tier. OData uses http verbs (GET, POST, etc) for the ‘action’ (***), and a URI to state which entity you want to do your action on. URI is the keyword here: unique resource identifier. Or translated into normal language: your call to “blah blah blah.ApplicationData.svc/case/123” means you want me to retrieve the ‘Case’ entities and return the slice identified by “123”.

Get all resources for “Case” and only return slice (fragment) 123.

So basically this was the “OData way” of saying: case 123 can’t be found.

Thanks for being straightforward and all…

But… we just created it. And according to our select * from Case, the record is in the database, then why could LightSwitch not find it?

Chapter 3: if it looks like a duck

The mystery continued with 10 more minutes of mumbling about dumbfoundedness… But then we remembered that there’s actually a filter active.

LightSwitch supports row-level filtering, ideal for slicing your records in multi-tenant or advanced security/permission situations.

And sure enough, this was the case

if(!Application.Current.User.HasPermission(Permissions.FamilyLaw)
  query = query.Where( case => case.AssignedCategory.Name != "Family");

The user we were testing with did not have the FamilyLaw permission any more, effectively causing all cases to be filtered to only show the ones where the assigned category is not “Family”.

Right?

Right?

Turns out, our problem was even a little more subtle…

This LINQ query filters out all the cases that have an AssignedCategory that is not “Family”.

Read that again… The linq query is actually, unintentionally I assure you, adding two filter criteria behind the scenes:

  case.AssignedCategory != "Family"
  seems to be interpreted as...
  case.AssignedCategory != null && case.AssignedCategory.Name != "Family"

Really, LINQ? Really?

Once we rewrote the LINQ query (to allow cases with AssignedCategory == null), our freshly created case entity (which has not yet been assigned to any category) now found its way down to the details screen.

 

*** PS: LightSwitch doesn’t really use HTTP verbs like (PUT, PATCH, …) directly on the OData service.  Because each screen has it’s own “unit of work”, all changes get posted just once, together, to an URI called $batch.  This HTTP “batch” call actually contains all different changes that happened in a screen (delete this, modify that, etc) in a single HTTP call.  Using transactional techniques, all changes then all get persisted in the data source together or, in the case something goes wrong, none of them get persisted.

It’s 2015, and LightSwitch is dead… Now what?

In case I haven’t seen you yet this year (and chances of that are high since I spent almost all of my time in my hammock so far), happy new year to you!

Just two weeks ago, the year turned 2015, always a great opportunity to reflect upon the past, and to learn lessons for the future.

And what a harsh lesson 2014 has taught us: LightSwitch is dead.

There, it’s out, and apparently I’m the first one to publicly carve these words in cyberspace. But unfortunately, a rose by any other name is still a rose, so let’s just call it what it is: dead.

Stage 1: denial

Let me first shed some light on why I consider the lightswitch to be in eternal off-state: there have been no new substantial developments since the HTML client (you weren’t really sitting around waiting for the O365 stuff now, were you), the ‘team blog‘ hasn’t had any meaningful posts in over half a year and many of the active community bloggers have either changed blogs, or have only been writing about using LightSwitch in combination with other technologies (with most of the focus on the other technologies).

If you want to try denying a technology being dead simply due to lack of evolution, then here’s a quote from the team latest post:

we’re currently planning to actively engage with the community and start our discussions on the roadmap in the middle of next year

Our love is dead, and you have been feeling it for a while now.

Perhaps you haven’t admitted it to yourself. Perhaps you are still in denial, but in this fast-paced world of ever-evolving technologies and agile methodologies, I cannot consider the product of a team that shifts priorities for over a year as the solid foundation for my own work.

Stage 2: anger

If you want to, please do take a quick break from reading now to go to the gym, box club, or whatever else you usually do to vent your anger. If you happen to have any pitchforks and/or torches, you could even join the rest of us in our march in the MSDN forums too, there’s a lot of anger already shared over there.

Stage 3: bargaining

We’re still reflecting the pain of 2014. Those of us who were able to overcome denial and anger stages, started bargaining. End of September, I’ve personally sat down with Microsoft folks to talk about the idea of how providing limited extension points so the community would allow us to create a toolkit to address a lot of the missing features. Others have publicly pled to open-source the entire stack, which would fit in great with MSFT’s latest vision and announcements about open-sourcing parts of their stack.  Some have threatened to mail Mary Jo Foley, others to mail Somasegar, in a passive-aggressive attempt to bargain or even blackmail the team into action.

Unfortunately, none of that led to change.

Stage 5: Acceptance

You skipped stage 4: depression.

You just scrolled up and noticed I did not write about stage 4: depression.

Stage 4 in the Kubler-Ross model (‘the five stages of grief’) describes the emotions of sadness, fear and uncertainty that start to develop during the earlier stages.  Feeling these emotions is natural, personal, and shows that we are slowly entering the final stage: acceptance.   So let’s cut to the point and discuss what acceptance could bring, for me and my relationship with you, my highly valued readers, and you’ll see there is very little sadness to be found.

  • LightSwitch being dead does not mean it does not have a future. At some point, probably end 2015 or early 2016, we’ll see a next version from the same MSFT team. Personally I don’t think they’ll actually revive LightSwitch as some kind of frankenstein monster with new body parts, but instead reuse only their experience can into a new product with a new name and marketing strategy.
  • LightSwitch being dead does not mean it ceases to be important in 2015. Personally I have a ton of ongoing projects and consulting opportunities, and they all still stand valid. LightSwitch has always been a tool to create CRUD-oriented, small to medium sized applications, and that is still true regardless of the evolution of the platform itself.  If LightSwitch is the right answer to a particular problem, then File>New>LightSwitch Application here I come! Or as the team puts it:

If the support we have in Visual Studio 2015 meets the needs of your application, then you should feel confident in developing with LightSwitch or Cloud Business Apps as we build out the roadmap

  • This implies an ongoing commitment to my own blog as well. I’ve always blogged strictly about my own professional experiences, and if I encounter anything worth sharing and I find the time to do so, I will gladly blog it! Being it about LightSwitch, or something else…

So there’s the big cliffhanger… What something else?

What now?

There’s not much presently existing that can match the development speed of LightSwitch. However, because LightSwitch does not offer modularity, has bad testability and devastating performance for medium to large applications, I’ve been looking for alternatives to answer challenges that LightSwitch can not…

And I have found it too.

I have found my sweetspot combination of a technology stack that is completely open source (no longer dependent on MSFT management decisions), highly scalable, highly modular, highly performant, fully customizable but yet offers incredible speed of development.

“No way”, I hear you say, “Such a thing does not exist! If it existed, I would have surely heard about it”.

And you are right in saying so. Such a thing does not publicly exists… Yet. But so far, I’ve been mainly writing about 2014, and 2015 is still so very young. This coming Monday, in an announcement that is not my own, the first tip of this veil of secrecy that holds my future, and perhaps yours, will be lifted…

Leave my endpoints alone!

By default, LightSwitch apps expose the server tier by one public OData endpoint per data-source. Both the desktop and the HTML client make direct calls to these .svc urls to retrieve the data they need.

So here’s an interesting question I got this afternoon: this means that all data is publicly visible?

Well, yes and no. The endpoints are publicly visible, however when you access them, the LightSwitch (actually asp.Net) framework’s authentication and authorization will kick in to protect the data (authentication determines if you can access the endpoint, authorization determines if you can access that particular entity set and what records you can access).

However, there’s some cases where you want to protect your endpoints even more, for example when you’re forced to build an application without authentication, or if you want to prevent a user with a valid username&pw (or windows credentials) to access the data from outside your own apps.

In that case, you can add a custom IHttpModule. This would include registering the module in your web.config…

  <system.webServer>  
    <modules>
      <add name="CustomHeaderModule" type="StrongNamespace.HttpModules.CustomHeaderModule"/>
    </modules>

and adding whatever code you want to your server project…

using System;
using System.Web;

namespace StrongNamespace.HttpModules
{
    public class CustomHeaderModule : IHttpModule
    {
        public void Init(HttpApplication application)
        {
            application.PostReleaseRequestState += new EventHandler(application_PostReleaseRequestState);
        }

        public void Dispose()
        {
        }

        void application_PostReleaseRequestState(object sender, EventArgs e)
        {
            if (HttpContext.Current.Request.Url.ToString().ToLower().Contains(".svc") 
                && !HttpContext.Current.Request.Url.ToString().ToLower().Contains("authenticationservice.svc")))
            {
                var referrer = HttpContext.Current.Request.UrlReferrer;
                if (referrer == null)
                    throw new Exception("Not allowed to access this data"); 
                else if (referrer.Host != HttpContext.Current.Request.Url.Host)
                    throw new Exception("Not allowed to access this data"); 
            } 
        }
         
    }
}

The above sample will block any calls to the .svc endpoints (your OData endpoints that expose your data) if the call is not made from a site within the same domain.

This hasn’t been production tested yet (and honestly you’ll probably need to customize the business rules a bit) but at first sight seems not to interfere with the LS desktop (OOB or inB) or HTML client, but do blocking any other calls.

It’s not really ‘web-friendly’ either, in production code I’d suggest rewriting the response to a 403-forbidden instead. But then again who gives a fuck about http status codes… (*grabs popcorn*)

 

Keep rocking LS!
Jan

Preventing a screen from closing in the LightSwitch desktop client

Every day, one of our end-users opens a screen and prints out all open support tickets for that day. When the tickets are printed, we want to make sure those tickets are marked as ‘printed’ on the server, so we have a button on the screen that lets her do just that:

        //Screen has one 'state' boolean
        private bool isMarkedAsPrinted = false; 

        //Normal code behind a button to mark tickets as printed
        partial void MarkAsPrinted_Execute()
        {
            if (!isMarkedAsPrinted)
            {
                foreach (var ticket in this.Tickets)
                    ticket.IsPrinted = true;
                this.Save();
                this.isMarkedAsPrinted = true; //Don't forget to change the screen's state
            }
            else
                this.ShowMessageBox("The tickets are already marked as printed.");
        } 

Sometimes, she’ll forget to press that button, so when the screen closes we want to check if the tickets are printed.  The screen has a ‘Write Code’ button for the _Closing event, and it is passed a bool called ‘cancel’. If you set this bool to ‘true’, the screen closing event will be cancelled.

        //Excecuted when the screen is closed
        partial void PrintTicketScreen_Closing(ref bool cancel)
        {
            //Cancel all closing events unless we set the 'reallyClose' flag 
            cancel = !(isMarkedAsPrinted); 
        }

That works like a charm. Once she prints, the isMarkedAsPrinted boolean is set to true, and the screen can close. When she forgets to press the button, the screen will not close no matter how many times the ‘x’ is clicked.

From a UX perspective though, this is rather weird. The application will just feel like it doesn’t respond to her trying to close the screen. We could have the screen show a message box saying she needs to print first, or better yet: asking her if she wants to print:

        //Screen has one 'state' boolean
        private bool isMarkedAsPrinted = false; 

        //Normal code behind a button to mark tickets as printed
        partial void MarkAsPrinted_Execute()
        {
            if (!isMarkedAsPrinted)
            {
                foreach (var ticket in this.Tickets)
                    ticket.IsPrinted = true;
                this.Save();
                this.isMarkedAsPrinted = true; //Don't forget to change the screen's state
            }
            else
                this.ShowMessageBox("The tickets are already marked as printed.");
        } 
         
        //Excecuted when the screen is closed
        partial void PrintTicketScreen_Closing(ref bool cancel)
        {
            //Cancel all closing events unless we set the 'isMarkedAsPrinted' flag 
            cancel = !(isMarkedAsPrinted);

            if (cancel)
            {
                var answer = this.ShowMessageBox("Would you like to mark these tickets as printed before closing the screen?", "Mark tickets as printed?", MessageBoxOption.YesNoCancel);
            switch (answer)
            {
                case MessageBoxResult.Cancel:
                    //Simply let the screen stay open in current state
                    break;
                case MessageBoxResult.Yes:
                    //Execute mark as printed, then close screen automatically
                    this.MarkAsPrinted_Execute();
                    cancel = false;
                    break;
                case MessageBoxResult.No:
                    //User doesn't want to mark as printed, close screen
                    cancel = false;
                    break;
                default:
                    throw new Exception("Unexpected result.");
            }
            }
        }

Something weird will happen when you run through the code though… When closing the screen, if the tickets haven’t been marked as printed, the dialog will be displayed to remind the user to save. However, half a second later, the screen will close anyways.

Here’s the rub: your screen’s _Closing event is given about one or two seconds to finish executing. When it does not finish executing within that timeframe, the LightSwitch framework will close every open dialog on the screen (including your ‘would you like to mark the tickets as printed’ one), and close the screen anyway.

The workaround is to make sure the _Closing event code returns immediately, but cancels the closing, on first run. Before we return from that method though, we’ll kick off a background worker. This background worker will ask the screen’s logical dispatcher to show the ‘would you like to mark the tickets as printed’ dialog. This request will be queued by the screen’s logical dispatcher and executed whenever it has time (read: whenever it is done not closing your screen).

Once the tickets are marked as printed, or the user refuses to mark the tickets as printed (perhaps the screen was opened by accident in the first place, or the printer ran out of paper), we’ll flip a boolean and close the screen programmatically. The second time the screen’s _Closing event code is executed, it’ll pick up this boolean (or notice the tickets have been marked as paid) and let the screen close this time:

        //Screen has two 'state' booleans
        private bool isMarkedAsPrinted = false;
        private bool userDoesNotWantToMarkAsPrinted = false;

        //Normal code behind a button to mark tickets as printed
        partial void MarkAsPrinted_Execute()
        {
            if (!isMarkedAsPrinted)
            {
                foreach (var ticket in this.Tickets)
                    ticket.IsPrinted = true;
                this.Save();
                this.isMarkedAsPrinted = true; //Don't forget to change the screen's state
            }
            else
                this.ShowMessageBox("The tickets are already marked as printed.");
        } 
         
        //Excecuted when the screen is closed
        partial void PrintTicketsScreen_Closing(ref bool cancel)
        {
            //Cancel all closing events unless we set the 'isMarkedAsPrinted' flag OR 'userDoesNotWantToMarkAsPrinted'
            cancel = !(isMarkedAsPrinted || userDoesNotWantToMarkAsPrinted);

            if (cancel)
            {
                //If this method takes longer than a second, the LS framework will close all dialogs as 'cancelled'
                //Hence, we start a backgroundWorker so that we can return from this method straight away
                var sleepy = new BackgroundWorker();
                sleepy.DoWork += (s, e) =>
                {
                    //This code will execute on the thread of the background worker, so
                    //we must ask the screen's dispatcher to invoke the 'askPrintBeforeClosing' 
                    //instead of asking this on the background worker's thread
                    this.Details.Dispatcher.BeginInvoke(() => { askPrintBeforeClosing(); });
                };
                sleepy.RunWorkerAsync();
            }
        }

        //Helper method
        void askPrintBeforeClosing()
        {
            var answer = this.ShowMessageBox("Would you like to mark these tickets as printed before closing the screen?", "Mark tickets as printed?", MessageBoxOption.YesNoCancel);
            switch (answer)
            {
                case MessageBoxResult.Cancel:
                    //Simply let the screen stay open in current state
                    break;
                case MessageBoxResult.Yes:
                    //Execute mark as printed, then close screen automatically
                    this.MarkAsPrinted_Execute();
                    this.Close(false);
                    break;
                case MessageBoxResult.No:
                    //User doesn't want to mark as printed, close screen automatically
                    userDoesNotWantToMarkAsPrinted = true;
                    this.Close(false);
                    break;
                default:
                    throw new Exception("Unexpected result.");
            }
        }

Keep rocking LS!
Jan

 

 

 

 

 

Loading of collections in the desktop client on a ‘need to see’ basis.

I just spent my Saturday afternoon on a really fun puzzle: loading data on a ‘need to see’ basis. This code hasn’t been production tested at all (use at own risk), but is way too fun not to share.

Challenge

The LightSwitch desktop application can sometimes feel really sluggish, this is partly because collections on a screen ‘execute automatically by default’, this means that they are loaded automatically if they are used in the UI, even if that part of the UI is not visible (for example if the grid is on a tab that is not active at the moment). So here’s the challenge: can we speed up the application by loading data on a ‘need to see’ basis? Can we make our application intelligent enough so that data is loaded if and only if it needs to be visualized?

I have a screen that contains a couple of collections, let’s say that Foo has a one-to-many relationship with Bar and I made a list-detail screen with three tabs, one containing the Foo’s details, one containing the Foo.Bars as a Data Grid, and one containing the Foo.Bars as a List.Image 247Or at runtime:Image 248

When I go to the Foos List Detail, using Fiddler or another network sniffing tool, I can see that both the Foos, and the first Foo’s.Bars are automatically loaded.Image 251

(Well: obviously, because in the screen designer both the Foo and Bars collection have their ‘Auto Execute Query’ selected…)Image 243

Making your application smarter

Add a new class to your client project, named ‘LoadOnDemandExtensions’. Copy the source for that class from this gist.  It’s in C#, but here’s a good link for our VB friends.

(For those of you that actually clicked the VB link, I’m sorry. That was mean. To make it up, I posted the VB code at the bottom of that same gist 😉 )

Step 2: right-click on the client code in Solution Explorer, hit ‘View Application Code’ to open your client application code. In the Application_Initialize method, write:

C#
    public partial class Application
    {
        partial void Application_Initialize()
        {
            this.LoadVisualCollectionsOnDemand(); 
        } 
    }
VB
    Public Class Application

        Private Sub Application_Initialize() 
            Me.LoadVisualCollectionsOnDemand() 
        End Sub
    End Class

End of blog post.

No, really!  Press F5 and see how your application is behaving when it starts up now:Image 249

Even though the ‘Auto Execute Query’ is still on for Bars, the Lightswitch application didn’t load them because they aren’t visible at the moment. As soon as you hit the ‘Bars’ tab:

Image 250

 What is this sorcery?

The LoadVisualsOnDemand method will dig in the LightSwitch extensibility model to grab a hold of the NotificationService. It’ll ask that NotificationService to be notified whenever a screen is opened.

When a screen is opened it’ll loop over every collection on that screen and use some nifty hacking techniques (reflection is forbidden in SL in-browser sandboxed applications, but there’s a little loophole) to turn off ‘Auto Execute Query’ on the loader of each collection.

Also, it will search the screen for any ‘ContentItem’ (that is the right-hand side of your screen designer, which looks like a ‘visual tree’) that is displaying a collection (in reality this’ll be your List, Data Grid, or SuperDynamicGrid really). It will ask to be notified whenever such a control becomes visible/hidden. As soon as this happens, it’ll re-hack the VisualCollection to turn the ‘Auto Execute Query’ back on/off based on visibility.

This results in your collection becoming loaded, working (apparently paging, sorting and quicksearch do not work using other screen performance tips) and staying in sync (for example, you click on another Foo, this causes the Bars to be reloaded)

tl;dr; LightSwitch will now ignore your ‘Auto Execute Query’ attempts and turn that on/off depending on visibility.

Noteworthy caveat

Bugs incoming! This method will control the ‘Auto Execute Query’ property on all collections, every screen. However, some of your code might already depend on the implicit assumption that a screen collection is loaded. Screen your screen code files, and if you spot a spot where you access a collection in code, make sure it’s loaded using this other nifty extension method.

C#
        partial void Method_Execute()
        {
            this.Bars.LoadIfNeeded();
            var count = this.Bars.Count; //for example
        }
VB
        Private Sub Method_Execute()
            Me.Bars.LoadIfNeeded()
            Dim count = Me.Bars.Count 'for example
        End Sub

But what if…

What if I don’t want this behavior on every screen?

Instead of turning this on on an application level, you can activate it on a screen-by-screen basis.

On those screens where you need it, turn off the ‘Auto Execute Query’ manually on each collection. Then, write this in the screens _Activated code:

C#
        partial void FoosListDetail_Activated()
        { 
            this.LoadCollectionsOnDemand();
        }
VB
        Private Sub FoosListDetail_Activated()
            Me.LoadCollectionsOnDemand()
        End Sub

What if I don’t want this behavior on every collection?

Instead of turning this on on an application or on a screen level, you can activate it on a collection-by-collection basis.

On those screens where you need it, turn off the ‘Auto Execute Query’ manually on those collections. Then, write this in the screens _Activated code (repeat for every collection):

C#
        partial void FoosListDetail_Activated()
        {
            this.Bars.LoadOnDemand();
        }
VB
        Private Sub FoosListDetail_Activated()
            Me.Bars.LoadOnDemand()
        End Sub

 

Keep rocking LS!

(But only the visible parts)

Jan

 

 

 

Addendum: Multi-tenant LightSwitch applications: favor convention over configuration.

Wut wut, did I not already cover the generic multi-tenant filter in my previous blog post? Well how observant of you, dear reader, I most certainly did. However, in this post I’d like to elaborate a bit about a hidden ‘convention’ in PowerProductivityStudio.Server, the nuget package that you install on your LightSwitch server project to weave generic code entry points into your application.

See, when we (me and my alter ego) initially built PPS, we already had the idea in mind to use these generic code entry points to facilitate multi tenancy. Multi-tenancy is where a single deployed instance of a (LightSwitch) app is used by multiple groups of users (each group is a tenant), who share the hosting costs of the server and the database. This means that their data is in the same tables, and must thus generally be filtered so that tenants cannot view, let alone alter, data that belongs to another tenant.

Additionally, we figured that some default data would sometimes be common between different tenants as well. This data can be seen by any of the tenants, but changed only by the administrator.

In a nutshell, we needed an easy way for any LightSwitch project to:

  • filter data based on the TenantId of that data
  • show data that belongs to tenant “0” (default, shared data)
  • prohibit any changes/creations to data that belongs to tenant “0” (default, shared data)
  • make sure when a user creates a record, that data is correctly labeled with the correct TenantId
  • make sure when a user tries to update or delete data that belongs to a different tenant, this is blocked by the application.

Now, if these requirements sound like something you require (pardon my English vocabulary on Mondays…), you’ll be glad to find out that PPS has a hidden convention.

Here’s how that works:

Step one: add an integer “TenantId” column to any data that needs filtering, for example:

Image 183

Note: I suggest turning off ‘Show by default’ and setting the TenantId property as nullable. This way, the client will not ever have to bother with the property.

Now, just as a test, go to the Project entity where you added the TenantId property, and hit the “Write Code” > “Projects_Filter” button.

Image 190

A method stub will be generated that has one argument, and a code comment with a suggestion on how you can implement a filter here.

Put a breakpoint in the generated method stub and run the application. By default, you’ll notice that the ‘Filter’ argument is null…

Image 191

Instead of manually coding a lambda expression that filters records though, we’re going to use a convention in PowerProductivityStudio…

Wait, in whut whut?

Step two: install the PowerProductivityStudio.Server nuget package on your LightSwitch server project. PPS is a nuget package that contains a code weaving task. This task will add generic ‘code entry’ point to your application, so you can write code when ‘any entity is created/updated/deleted/queried’, …  This way you can create a generic filter at runtime, like in my previous post. However instead of writing a generic filter, we’ll take it one step further than my previous post again.  To install PowerProductivityStudio.Server, right-click on your server project and select ‘Manage nuget packages’. Search for ‘PowerProducitivityStudio.Server’ and install it.

Step three: tell PPS about your current tenant. To do this, add any class to your LightSwitch server application and implement the PowerProducitivityStudio.Extensibility.IMultiTenantService interface, for example:

using System.Web;
using Microsoft.LightSwitch;

namespace LightSwitchApplication
{
    public class MyMultiTenantService : PowerProductivityStudio.Extensibility.IMultiTenantService
    {
        public int GetCurrentTenantId()
        {
            return 1;
        } 
    }
}

Step four: launch your application!

If you still have your breakpoint in the ‘Projects_Filter’ method, you’ll notice that the query no longer is ‘null’, but actually has a valid ‘Multi-Tenant-Filter’ now…

Image 192

Succes? Let’s see…Image 184

All done… We just found an easy way for any LightSwitch project to:

  • filter data based on the TenantId of that data
  • show data that belongs to tenant “0” (default, shared data)
  • prohibit any changes/creations to data that belongs to tenant “0” (default, shared data)
  • make sure when a user creates a record, that data is correctly labeled with the correct TenantId
  • make sure when a user tries to update or delete data that belongs to a different tenant, this is blocked by the application.

Too easy? To short of a blog post?

Well, I could elaborate a bit more about my progress in learning Spanish (I can conjugate 12 verbs now, and know 27 different ways to order a beer), or I could help you a bit with that multi-tenant filter implementation.

First suggestion I would have for your multi-tenant filter (I know you’re not interested in my Spanish progress) would be to not hardcode it to “return 1;”.  You could set up a table that stores all tenants and their corresponding HostURL (for SharePoint provider hosted apps, like in the last post), or add a related table that stores which login (/user) belongs to which tenant.

Then, when PPS asks you for the tenant, just look that up using the ServerApplicationContext:

using System.Web;
using Microsoft.LightSwitch;

namespace LightSwitchApplication
{
    public class MyMultiTenantService : PowerProductivityStudio.Extensibility.IMultiTenantService
    { 
        public int GetCurrentTenantId()
        {
            var user = ServerApplicationContext.Current.DataWorkspace.ApplicationData.Users.Where(u => u.Login == ServerApplicationContext.Current.Application.User.Name).Single();
            return user.Tenant.Id;
        } 
    }
}

Sweet, but this will bog your system down quite a bit, since any data that is being retrieved/edited, will result in at least one extra call. Below is a revised version that will cache the current tenant id for a particular user in the HttpContext.Current.Cache. In addition, it also takes scenarios in mind where there might not be an existing ServerApplicationContext (if you use Web API for your fancy word document generation, for example), and shaves some milliseconds of the query by retrieving the User and it’s Tenant at the same time.

using System.Web;
using Microsoft.LightSwitch;

namespace LightSwitchApplication
{
    public class MyMultiTenantService : PowerProductivityStudio.Extensibility.IMultiTenantService
    { 
        public int GetCurrentTenantId()
        {
            int tenantId;
            if (HttpContext.Current == null //can happen if you have custom Web API calls
                || HttpContext.Current.Session["CurrentTenantId"] == null)
            {
                if (ServerApplicationContext.Current != null)
                {
                    var user = ServerApplicationContext.Current.DataWorkspace.ApplicationData.Users.Include("Tenant").Where(u => u.Login == ServerApplicationContext.Current.Application.User.Name).Single(); 
                    tenantId = user.Tenant.Id; 
                }
                else //can happen if you have custom Web API calls
                {
                    using (var context = ServerApplicationContext.CreateContext())
                    {
                        var user = ServerApplicationContext.Current.DataWorkspace.ApplicationData.Users.Include("Tenant").Where(u => u.Login == ServerApplicationContext.Current.Application.User.Name).Single();
                        tenantId = user.Tenant.Id;
                    }
                }
                HttpContext.Current.Session["CurrentTenantId"] = tenantId;
            }
            else
            {
                tenantId = (int)HttpContext.Current.Session["CurrentTenantId"];
            }
            return tenantId;
        }
    }
}

Badam tsss!

Just one more thing: PPS weaves the multi tenant filter just before the call is made to your “Projects_Filter” or “WhateverEntity_Filter” method.  There’s good news and bad news to that timing: if the multi-tenant filter that PPS creates does not fit your needs, you can easily overwrite it with whatever custom code you want, and re-assign the filter parameter. The bad news: if you already have a filter implemented (let’s say you only want projects with an ‘a’ in the name to appear), you’ll need to merge your custom filter and the existing filter together:

Image 194

 

Now, if you’ll actually try this, you’ll get a compilation exception, because combining two expressions is not supported unless you add this little helper class somewhere in your server project  😉

Badam tsss again 😉

Sample project has been uploaded to my OneDrive, and as always…

Keep rocking LS!

 

Addendum: a generic way to create A LightSwitch SharePoint 2013 Multi-Tenant Provider-Hosted Application

A couple of months ago (is it August already, really?)Michael Washington published a detailed article on creating multi-tenant Cloud Business Applications.  Multi-tenancy is a hot subject in the SAAS world, because it allows a single deployed server instance to serve multiple groups of users (called tenants because they usually pay for that service), which cuts down hosting costs and makes software updates so much easier.

The article is awesome, and after wasting Michael’s time because I thought there was a small security issue (which there isn’t) gets my absolute official seal of approval, along with a great A- rating!

Wait, A-? Why not A+?  Well, the implementation relies on you writing a bit of code each time an entity is inserted, updated, or queried.  Multiply this by 200-300 entities and you have a lot of typing to do, and a lot of chances to forget a particular entity. Unfortunately though, since LightSwitch has no generic way built-in to write code when ‘any’ entity is inserted, updated, or queried, there’s no way to built-in way to save your keystrokes…

Smooth transition: faithful readers of my blog will already know that when I say: no ‘built-in’ way, a small hack is just around the corner…

PS: this hack works for non-CBA LightSwitch apps as well.

Part 1: making the code more generic.

The name of the game is simple: when a LightSwitch application gets compiled, we will use a custom MSBuild task to open the server assembly, interpret the IL, and weave in calls to a generic event handler, then write code in our generic events.

Save yourself the headache (trust me, there’s a lot of headaches) involved in the actual hacking, and install a nuget package called powerproductivitystudio.server on your server project instead.  This package will add a custom MSBuild task to open the server assembly when it gets compiled, which interprets the IL, and weaves in calls to a generic event handler for you.  If you have seen my recent development on app-stitch, you’ll understand we use it ourselves extensively to drive events that happen in your LightSwitch app to the app-stitch event processor.

What you have left to do, is add a class where you can handle the generic LightSwitch events.  The class can be added anywhere in your server project, it can have any name, as long as it implements ‘PowerProductivityStudio.Extensibility.IServerEventHandler’, it will be recognized by the PPS framework at runtime and the methods will be called appropriately.  Here’s an empty stub to get you started:

    public class MyGenericFilter : PowerProductivityStudio.Extensibility.IServerEventHandler
    {
        public void EntityCreatedEventOccured(Microsoft.LightSwitch.IEntityObject entityObject)
        { 
            //Gets called when eny entity is created on the server.
        }

        public void EntityPermissionRequestOccured(string action, string entityPluralName, ref bool result)
        { 
            //Gets called when the server is asked if a user has rights to view/edit/... an entity.
            //Set result to true or false.
        }

        public void EntityValidatedEventOccured(Microsoft.LightSwitch.IDataService dataService, Microsoft.LightSwitch.IEntityObject entity, Microsoft.LightSwitch.IValidationResultsBuilder validationResultsBuilder)
        { 
            //Gets called whenever an entity is validated on the server.
        }

        public void FilterRequestOccured(ref T originalFilter) where T : class
        { 
            //Gets called whenever a set of entities is retrieved, and could be filtered.
        }

        public void ServerEventOccured(string action, Microsoft.LightSwitch.IEntityObject entity, Microsoft.LightSwitch.IDataService dws)
        { 
            //Gets called whenever an entity is being inserted, updated, deleted or is inserting, updating or deleting.
        }
    }

To make Michael’s Task_Inserting and Tasks_Updating code work for every single entity, you can implement the last method as:

        public void ServerEventOccured(string action, Microsoft.LightSwitch.IEntityObject entity, Microsoft.LightSwitch.IDataService dws)
        {  
            if (action.EndsWith("Inserting") || action.EndsWith("Updating"))
            {
                if (entity.Details.Properties.Contains("HostURL"))
                { 
                    var hostUrl = "MyTenantID123"; //this.Application.SharePoint.HostUrl.Host;
                    entity.Details.Properties["HostURL"].Value = hostUrl;
                }
            }
        }

The code checks if the entity has a property called ‘HostURL’ (Sometimes, multi-tenant apps have a set of commonly used data, which will not have the ‘HostURL’ property), and will set your tenant’s ID (the SharePoint Host URL in Michael’s example) on inserts and updates.

Almost done, and your app is forever multi-tenant… The last task is to make sure every entity that has a property called ‘HostURL’, is filtered so that each tenant can only access his/her data.

Michael does this by creating a filter (a lambda expression) and assigning it in the Tasks_Filter method. We’ll do exactly the same, only write some generic code to create the lambda expression at runtime, in the FilterRequestOccured method:

        public void FilterRequestOccured<T>(ref T originalFilter) where T : class
        { 
            //T is Expression<Func<Entity, bool>>
            var entityType  = typeof(T).GetGenericArguments()[0].GetGenericArguments()[0];
            if(entityType.GetProperty("HostURL") == null)
                return;
            
            var hostUrl = "MyTenantID123"; //this.Application.SharePoint.HostUrl.Host;

            // Only allow users to see records from their own site by creating a filter (Function) at runtime
            // filter = e => e.HostURL == this.Application.SharePoint.HostUrl.Host;     
            var e = System.Linq.Expressions.Expression.Parameter(entityType, "e");  
            var myTenantId = System.Linq.Expressions.Expression.Constant(hostUrl);
            var hostURLProperty = System.Linq.Expressions.Expression.Property(e, "HostURL");
            var hostURLEqualsMyTenantId = System.Linq.Expressions.Expression.Equal(myTenantId, hostURLProperty);
             
            Type funcType = typeof(Func<,>).MakeGenericType(entityType, typeof(bool));
            var newFilter = System.Linq.Expressions.Expression.Lambda(funcType, hostURLEqualsMyTenantId, new[]{ e }) as T;

            originalFilter = newFilter;
        }

Congratulations, your app is now forever multi-tenant, and you can continue with Michael’s awesome post.

Part 2: app-stitch: multi-tenant business rules

Hold on to your hats though, there’s one more chapter to tell in the multi-tenant story: business rules.  Business logic is usually hard-coded in the application, but sometimes one tenant has slightly different rules than another tenant.

To answer this need, we’ve made sure that app-stitch supports multi-tenant scenarios as well, so that each tenant can only see his/her own rules, but more importantly, to make sure that a business rule only fires on actions on data that actually belong to the tenant.

Once you have app-stitch installed, open the folder appstitch/appstitch.LightSwitch and open the class ItemUserAndContextProvider.cs.  Each time app-stitch needs an AppStitchItem (rules/audited events/settings), information about the current user or a ServerApplicationContext instance, the ItemUserAndContextProvider class will provide just that.

Locate this piece of code:

                Microsoft.LightSwitch.Server.IServerApplicationContext context;
                using (GetServerApplicationContext(out context))
                {
                    user = new AppStitch.UserInformation();
                    user.FullName = context.Application.User.Identity.Name;
                    user.CanView = true;
                    user.CanEdit = true;
                    user.IsDebugAdmin = context.Application.User.HasPermission(Permissions.SecurityAdministration); 
                }

This is where your application creates an ‘AppStitch.UserInformation’ instance to give app-stitch information about the current user.  (Note: this is also the place where you could deny a user from creating or even viewing the app-stitch business rules)

What you have to do, is add the fact that this user belongs to a particular ‘group’.  Rules created by a user will only be visible to other users in the same group, and will only apply to events (data that changes, …) by users in the  same group.  For this example, we’ll say that each tenant is a separate group:

                Microsoft.LightSwitch.Server.IServerApplicationContext context;
                using (GetServerApplicationContext(out context))
                {
                    user = new AppStitch.UserInformation();
                    user.FullName = context.Application.User.Identity.Name;
                    user.CanView = true;
                    user.CanEdit = true;
                    user.IsDebugAdmin = context.Application.User.HasPermission(Permissions.SecurityAdministration); 

                    //add this:
                    user.GroupId =  "MyTenantID123"; //this.Application.SharePoint.HostUrl.Host;
                }

In summary…

app-stitch relies on a nuget package that creates generic code entry points in your application.  With a bit of generic code of yourself, you can make your data and your business rules multi-tenant-ready once and for all.  If you want to see a sample, here’s the bits. 🙂

Keep rocking LS!

Jan

New Syncfusion eBook: #LightSwitch mobile business apps Succinctly

Proud to present: Syncfusion’s newest addition to their Succinctly series: LightSwitch mobile bussines apps, written by yours truly.

Image 096

 

The first eBook I wrote for Syncfusion, LightSwitch succinctly, was a small introduction to LightSwitch’s designers, server, and desktop client (Silverlight).  I got some great feedback so when Syncfusion asked me (some time last year) to write a follow up, I was honored and anxious to get started. I was even more honored when I found out my technical reviewer was community champion Alessandro Del Sole!  (Thanks man!!)

This book picks up where the first one left off, describing some newer features like the DB projects and (of course) the HTML client.  I did some pretty advanced looking UI customizations, and was surprised myself in how easy the HTML client actually is to customize…

I hope you enjoy this one as much as I did writing it!

Keep rocking LS!

Jan

 

Why your hyperlink won’t work in the LS HTML client, part 2

Apparently, there is a part2 in my struggle with this ‘current user hyperlink’ that I inserted in my LightSwitch HTML client as a custom ‘control’

Image 068

At first sight, the link works perfectly: when you click it, the app shows a popup where you can edit your profile.  Because of the databinding, the hyperlink will automatically update its text when the user edits his/her name in that dialog.

At first sight…

Once I added multiple screens to my application, I noticed that the hyperlink databinding behaves correctly when I first open the screen, but after navigating to another screen and then back again, my custom control stopped working.  In fact, after navigating to another screen and then back again, half of my custom controls were behaving funny, the other half was just fine.  And by the time I noticed this subtlety, I had way too much custom controls on my screen to log it as a ‘known issue’ 😉

Image 069

I don’t remember ever running into problems with this before, but apparently there is a subtle difference in behavior between two different ways I interact with my custom ‘controls’.  Zooming in on the ‘offending’ code reveals the problem (when you know where to look, bugs are always easier to find):

I create the usercontrol via a JQuery selector, then save a ‘reference to the usercontrol’ in a variable.  In my first interaction, I use this variable directly.  For some reason, in my second interaction, I use a new JQuery selector to get a new ‘reference to the same usercontrol’.

This seems to work fine for the very first time, but breaks silently on subsequent rendering.

The first fix seems to be the obvious: use the variable instead of using a new JQuery selector.

A second fix that seems to work, is to start the JQuery selector using the parent element (passed as an argument to your _render or _postRender functions) as the context:

$("#userviewer", element);

If anyone can enlighten me as the technical reasoning behind this issue, I’d love to hear it 🙂  Until I understand, I think I’ll stick with this last approach because it seems to be the most stable one…

 

Keep rocking LS!
Jan

 

 

Why your hyperlink won’t work the LS HTML client

(Update: read part 2 as well if you intend to use this code)

In our quest for happiness, my wife and I decided to live in the Caribbean for a couple of years.  Sipping cocktails on white beaches, watching Mojo (my goofy boxer dog) play in the clear blue water, while prototyping a LS app on my laptop.  I can tell you, life doesn’t get more stress free than this.

Unless… you need to add a hyperlink to that LS app…

In the top right corner of my app, I wanted to replace the Logout button with information about the currently logged in ‘user’.  For this app, I have a table with ‘Realtors’, one record per ‘user’ (login+pw combo).  On my screen, I added a local ‘Realtor’ property named ‘Myself’.  I dragged that property on my screen’s visual tree, selected ‘Custom Control’, and clicked the ‘Edit Render Code’ from Properties Window.

A JS file is generated containing a function stub to work my magic.  So far so good.  I bashed together some code to hide the Logout button and insert my link instead.

F5 this!

Image 061

Success!  Now let’s just give that link a quick click to verify it opens the EditMyProfile page…

Wait, whot?

Adding a hyperlink in an HTML5 app might sound like the most trivial assignment ever, but no matter what I tried, the link was not responding to click events.

Hours later (actually 1 and a half Mojitos, so probably not even close to ‘hours’), I found that my custom control wasn’t working because LS was purposely rendering a div named ‘msls-state-overlay’.  Apparently, when you create a custom control, LS by default will take care of the ‘Disabled Rendering’ for you.

And apparently, my link was determined to be rendered as disabled.

And apparently, like all great things in LS, if you don’t like the default behavior, change is but a setting away…

Image 062

One F5 and two sips of Margarita later…

Image 063

Works like a charm… At first sight…  There’s a subtle issue with the code, perhaps I had too much Margaritas :-s

Keep rocking LS!

 

Jan