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  ;-)

https://gist.github.com/janvanderhaegen/1620fee98ea8578862aa

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

Summer is here! (And so is app-stitch)

Two weeks ago, summer has officially started. Time for cocktails, trips to the beach, and late night BBQs.
What’s that, you say, ‘too busy’? ‘Too much work to do’?
Man do we have great news for you…

Introducing app-stitch

app-stitch has been in beta for a while, and after ironing out some last bugs and making sure we have a streamlined support process, app-stitch is ready to help you design your business rules.
In case you need a quick reminder: app-stitch is a visually simple yet powerful way of designing business rules.
Whether you need to add some detailed auditing, check for a permission before allowing a user to create a new invoice, or send out an email at a certain time of the day, app-stitch is there to help!
Image 099

Available exclusively for Visual Studio LightSwitch (at the moment), app-stitch can be found at a very low launching price, only on app-stitch.com.
Not enough? Still too much work ahead?
Well I’m not sure what more you could want… Except perhaps, some kick-ass controls?

Introducing Blue Breeze Experience Suite

Our new suite for Visual Studio LightSwitch desktop applications starts off small with four grandiose and unique controls.

Super dynamic grid

sdg

Empower your end users by allowing them to customize your grids at runtime into unlimited personalized views.  Each view supports grouping, sorting, advanced filtering, adding additional columns, importing&exporting the data, and even printing.

Notes control

notes

Stick digital post-its to any entity.  Notes come in many colors and can contain urls or links to files and pictures too.

Learn more artifacts

learn more

Sometimes a tooltip can’t really supply all the help your end users need. The learn more artifacts control allows you, at runtime, to create rich help artifacts with text, images and video, and then insert a link to the help artifact at any place in any screen.

Color picker

color picker

Over 16 million colors at your finger tips.

Introducing Blue Breeze Consulting Services

Let’s be honest, off-the-shelve controls and even a kick-ass generic event process won’t be able to do all the work you want to get done by the end of this year…
Have an exciting project that could benefit from years of LightSwitch and/or .Net expertise? Want an honest second opinion? Need some out-of-the-box-thinking brain power?

The team behind app-stitch is always looking for a new challenge, and would love to help you on your next quest.  On top of our own experience, we have assembled a panel of world-renowned LightSwitch and .Net experts to help us help you when and where it really matters.

Get in touch! First round of beer is on us.

Have a great summer!

The app-stitch team.

 

Introducing app-stitch (beta)!

My hands are literally shaking as I can finally announce our new baby… the result of three years worth’ in Saturday mornings, a strategic partnership and a shiny new startup…

app-stitch baby

Yea baby!

If LightSwitch was designed to take 80% off your development time by removing the tedium involved with designing entities, queries and screens, app-stitch is designed to take another 80% out of your remaining 20% by allowing you to design your business logic!

app-stitch is a new extension that you can ‘plug’ into your LightSwitch server project (nuget).  Once installed, it adds a small web interface where you and your end users can ‘design’ your business rules at runtime…

Image 099

These business rules are active immediately, and can: change data when you create a new entity, send out emails when you update an entity, prevent a particular user group from deleting entities, turn an incoming sms/mms into a support ticket, check for permissions, audit changes, read files and turn them into new entities, create a QuickBooks invoice when a Paypal payment clears, turn that into a social media status and release the drones to deliver the package*,   and so, so, soooooo much more.

* Drones control is highly experimental, unstable and also not really existing. But our other channels are kickass!

If you have a minute or two, please pay a visit to our (unfinished) website, play around with our sample application (guide available), or check out our promotional video:

app-stitch is currently in beta (please join our beta program ;-) ), after which we’ll release it, initially only for Visual Studio LightSwitch!!!

(We do have other technologies/platform on our ambitious roadmap, as well as dozens of channels to increase the number of rules you can make!)

I really hope you’ll enjoy our crazy invention and support us as we help this baby grow!

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