LightSwitch hacking challenge: fix the NullReferenceException: sample

Yesterday I came across a rather interesting NullReferenceException, which occurred right after I set a local screen property to a particular value (non-null) then (in the very next line of code) retrieved that property to do some additional work.

Fixing it is easy ONCE you know what causes this odd behavior.  I can promise you that there’s not one single written resource available on the web about this, making it a very blogworthy subject.  Instead of going straight to the explanatory post though, I thought some readers would enjoy a riddle first (I certainly would), hence the hacking challenge.

To avoid confusion over the fact that I’m using a fancy user control or showing a modal dialog, I’ve uploaded a working code sample. You can download it, or just study the sources online.  In the sample, I’ve reduced the fancy control to an absolute minimum, to avoid any confusion (for example: that the NRE is caused by the fanciness of the control). I’ve also rewritten the original problem a bit to avoid confusion about the modal dialog or use of an entity.

Lastly…

BIG BIG SPOILER ALERT!

I added an additional hint in the sample.  To see this hint, simple open the second screen (in the application/code).

 

Good luck, and keep rocking LS!

LightSwitch hacking challenge: fix the NullReferenceException

I’ve been posting so much about the awesome LightSwitch HTML client lately (have you seen the second season of Leading LightSwitch by the way?) that you might get the impression that I’m now an HTML-Hipster exclusively…

No way, and as a tribute to my love to the strongly typed world (also just because it’s really cool) I’m going to challenge your LightSwitch haxpert level with a coding riddle…

I have a normal LightSwitch screen, that has a local property (from Screen Designer > Add data item > Local property: UserRegistration(Entity) ) and a fancy custom user control.  From the screen’ Created method, I’m trying to bind an event handler to an event on this fancy custom user control that is supposed to instantiate the local UserRegistration property, then show a modal popup.  Nothing extraordinary, one would think when looking at the code:

This code actually throws a NullReferenceException at line 15 (much to my own initial surprise)…  I verified this by putting up a breakpoint, and indeed, ‘this.NewUserRegistration’ returns null even though we just assigned the return value of the AddNew method on line 14!!

Your mission, should you choose to accept it: explain why, and propose a fix.  The rules of the challenge are simple: the first one to post the correct answer wins, he/she doesn’t actually win anything (I’m completely broke after giving away $10.000 last month), and you are excluded from entering the competition if your name is Matt Evans, Huy Nguyen, … ( or if you share a whiteboard with any of these guys).

As always, should any member of your team be caught or killed, the Secretary will disavow all knowledge of your actions.

Keep rocking LS!

#LightSwitch and #Syncfusion: simply beautiful applications ($10.000 April raffle!)

With all the blog posts about the new LightSwitch HTML client, it’s easy to lose track of the continued investments in the Silverlight client and the server tier…

One minute summary

Today, this blog post will teach you what you can create by combining 30 minutes of your time with your existing LightSwitch skills, a little ASP.Net Web API creation, some Nuget-for-beginners and custom Silverlight controls to add a dashboard to a LightSwitch application.

Or, because a picture says a thousand words: today we’re going to create this (click-to-enlarge):

LightSwitch & syncfusion: deliver simply beautiful applications

Or, because a sample says more than a thousand pictures: <Download link coming soon> .

Ten minute summary

Prerequisites

To follow this guide, you’ll need:

1. Creating reports on the server

Instead of dragging all records over the wire, we’re going to access the ApplicationServerContext directly on the server, aggregate and transform the data there, then send the summary back.

You’ll know why the latter approach is preferred once you pay for your own Azure bills. :p

Hit the “Toggle View” button in solution explorer so that the LightSwitch application is in File View.  Then, right-click on the server project > Add a folder > Name:”Controllers”.

Next, right-click that new folder and choose to Add New Item… > Web API Controller Class > Name:TopRegionsController.cs  (If you are unfamiliar with ASP.Net Web API, you can skim through this tutorial.)

Before actually implementing the controller, we’ll configure the server for these new controllers.  Right-click the project > Add New Item > Global Application Class:

using System;
using System.Web.Http;
using System.Web.Routing;

namespace LightSwitchApplication
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {

            RouteTable.Routes.MapHttpRoute(
               name: "ReportsApi",
               routeTemplate: "reports/{controller}"
               );

        }
    }
}

Back to the controller, where we’ll implement the GET command:

using System;
using System.Linq;
using System.Web.Http;
using Microsoft.LightSwitch; //1.

namespace LightSwitchApplication
{
    public class TopRegionsController : ApiController
    {
        // GET api/
        public object Get()
        {
            using (ServerApplicationContext context = ServerApplicationContext.CreateContext()) //2.
            {
                var query = context.DataWorkspace.NorthwindData
                    .Orders
                    .Where(o => o.ShipRegion != null)
                    .GroupBy(
                        o => o.ShipRegion) //3.
                    .Select(
                        g => new //4.
                        {
                            Label = g.Key,
                            Value = g.Count()
                        }
                        )
                        .Execute() //5.
                        .OrderByDescending(g => g.Value)
                        .Take(15)
                        .ToList();
                return query;
            }
        }
    }
}

Some code highlights:

  1. Don’t forget to add the using statement to bring the Microsoft.LightSwitch namespace into scope.
  2. This is the powerfull ServerApplicationContext.  An IDisposable  , type-safe object that represents your LightSwitch application on the middle tier.  You can access user information, the Dataworkspace, …
  3. Pro tip! This GroupBy method (only available after step 1.) is something you can’t do over OData.  The grouping itself is done directly in the data source, if your data source supports it.  SQL obviously does.  (In other words, calling this GroupBy method will cause your SQL query to contain a GROUP BY statement :-))
  4. We’re gathering the results in an anonymous type.  Bluntly put: why bother?
  5. Don’t forget to execute the query!

Et voila, the server is done.  One quick way to test if you have done everything correctly, is to press F5 to start debugging, then navigate your browser or fiddler to http://localhost:<assigned port number>/reports/TopRegions .

Image 037

2. Fetching the data from the client

Add an empty Screen to the LightSwitch (Silverlight: in or out-of-browser) application called “DashBoards”, using the “List and Details” screen template but leaving Screen Data blank.

From the Screen Designer, hit the “Write Code” button and choose “DashBoards_Activated”.  This will generate a method stub for you, where you can add some code to match the following outline snippet:

using Microsoft.LightSwitch.Presentation.Extensions;
using System.ComponentModel;
namespace LightSwitchApplication
{
    public partial class Dashboards : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public object TopRegions { get; set; }

        partial void Dashboards_Activated()
        {
            //What comes here? :-s
        }
    }
}

As you can see, we’ve added a local property called “TopRegions”, of type object.  Because this can’t be done from the screen designer, we’ll have to notify when the property changes ourselves too.   The big question is what we should fill in as method body.  How do we find out what the server address is, perform the HTTP GET call asynchronously, and handle exceptions?

Luckily, when there’s a tough technical challenge, you can often hire “a developer in a box” (as I call it), or “Paul Van Bladel in a Nuget package” (as normal people would refer to it).

Open the package-manager console (if you don’t know what that is: View>Other Windows>Package Manager Console), make sure the LightSwitchApplication.Client project is selected as Default Project, then type:

Image 038

Pro tip!: after typing “inst” or “thelight”, you can press tab and have the rest of the command auto-completed.

This package will install some utility extension methods, which we can call from our method body (and effectively reduce this article from 14 pages to just 4):

        partial void Dashboards_Activated()
        {
            this.StartWebApiRequest<MySyncfusionControls.DataItemViewModel[]>//1
                ("reports/TopRegions",//2.
                (exception, result) =>
                {
                    if (exception != null)
                    {
                        this.ShowMessageBox("There was an error while fetching the data.");

                    }
                    else
                    {
                        Microsoft.LightSwitch.Threading.Dispatchers.Main.BeginInvoke(() => //3.
                            {
                                TopRegions = result;
                                this.PropertyChanged(this, new PropertyChangedEventArgs("TopRegions"));  
                            }
                        );
                    }
                }
            );
        }

Some code highlights:

  1. StartWebApiRequest is one of the methods added by the Nuget package, doing all the heavy lifting.  Thanks Paul!  We call the method and (by using the generic method signature) ask to cast the return value (a JSON list of anonymously typed stuff) to an array of MySyncfusionControls.DataViewModel (We’ll create this class in a second, by the way).  In a loosely typed language like JavaScript, or in an un-sandboxed environment like WPF, you could get away with not casting the return value (ie: casting it to object) but you’ll run into security problems trying to bind to it from the user controls later.  (Silverlight is very harsh on reflection-lovers, meaning safer for the end-user).
  2. This is the last part of the URI by which the server is exposing it’s endpoint, determined by the routing we set up in the Global.asax file, and the name of the controller.
  3. We’re currently on the logical thread.  This event will be handled on the UI thread.  Read about the incredible dual dispatcher objects in LightSwitch… O… wait…  //TODO: can someone blog about dual dispatcher objects?

 3. Creating the user control

To visualize the report to the user, you need some kick-ass controls.  LightSwitch Controls come in three flavors:

We’ll take the latter route: right-click on the solution > Add New Project > Silverlight 5 Class Library > Name:MySyncfusionControls

Replace the default class1 with:

    public class DataItemViewModel
    {
        public string Label { get; set; }
        public double Value { get; set; }
    }

This is the DTO we’ll use, duly note that the names of the two properties (“Label” and “Value”) match the one used in our anonymous type used to return the data from the server.

Goody, now for the actual control.  Add references to Syncfusion.Chart.Silverlight, then right-click the project > Add New Item > Silverlight User Control > Name:ColumnChartWrapper.  Replace the XAML with:

<UserControl x:Class="MySyncfusionControls.ColumnChartWrapper"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:syncfusion="clr-namespace:Syncfusion.Windows.Chart;assembly=Syncfusion.Chart.Silverlight"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">

    <Grid x:Name="LayoutRoot" Background="White">
        <syncfusion:Chart Margin="10" Name="Chart1" MinHeight="300" MaxHeight="450" MinWidth="600" MaxWidth="1000" Background="White">
            <syncfusion:ChartArea BorderThickness="0">
                <syncfusion:ChartArea.Header>
                    <TextBlock FontSize="20" Text="{Binding DisplayName}" />
                    <!-- 1. -->
                </syncfusion:ChartArea.Header>
                <syncfusion:ChartArea.PrimaryAxis>
                    <syncfusion:ChartAxis RangePadding="Normal" ValueType="String" Interval="1"/>
                </syncfusion:ChartArea.PrimaryAxis>
                <syncfusion:ChartArea.SecondaryAxis>
                    <syncfusion:ChartAxis RangePadding="Normal" IsAutoSetRange="True"/>
                </syncfusion:ChartArea.SecondaryAxis>
                <syncfusion:ChartSeries x:Name="series" 
                    BindingPathX="Label" 
                    BindingPathsY="Value" 
                    DataSource="{Binding Value.TopRegions}" 

                    Type="Column" StrokeThickness="0"
                    ColorEach="True"
                    EnableEffects="True"
                    EnableAnimation="True" AnimateOption="Rotate" AnimateOneByOne="True" AnimationDuration="00:00:10"
                    >
                    <!-- 2. -->
                    <syncfusion:ChartSeries.AdornmentsInfo>
                        <syncfusion:ChartAdornmentInfo x:Name="Adornments_pot" Visible="True" SegmentLabelFormat="0.0"
                                                                   AdornmentsPosition="Top" 
                                                                   HorizontalAlignment="Center" 
                                                                   VerticalAlignment="Bottom" >
                            <syncfusion:ChartAdornmentInfo.LabelTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <TextBlock  TextWrapping="Wrap" Text="{Binding}" FontSize="20" Foreground="White" HorizontalAlignment="Right" VerticalAlignment="Bottom">
                                        </TextBlock>
                                    </Grid>
                                </DataTemplate>
                            </syncfusion:ChartAdornmentInfo.LabelTemplate>
                        </syncfusion:ChartAdornmentInfo>
                    </syncfusion:ChartSeries.AdornmentsInfo>
                </syncfusion:ChartSeries>
            </syncfusion:ChartArea>
        </syncfusion:Chart>
    </Grid>
</UserControl>

Some XAML highlights:

  1. Bind to the DisplayName (which we’ll set in a minute)
  2. Well…
    • DataSource is set to Value.TopRegions.  The datacontext is the ContentItem that we’re about to drag on the screen designer.  This ContentItem has a property “Value”, which we’ll bind to the “Screen” in the screen designer.  This screen has a property called “TopRegions”, which we added in the code earlier.
    • BindingPathX and BindingPathsY are set to “Label” and “Value”, which are the names of the properties on or DTO that we created earlier.  This is where you would run into troubles if you didn’t cast the JSON result to a strongly typed object in a strongly typed language in a sandboxed environment.
    • Animations: you need lots of them and Syncfusion has some truly beautiful animations.  For demos, always include “EnableAnimation=”True” AnimateOption=”Rotate” AnimateOneByOne=”True” AnimationDuration=”00:00:10″”, you only get one shot at making a first impression so make sure there’s lots of shinies to catch your audience’s attention .  Pro tip! For production code, removing animations makes customers happier.

4. Finishing the screen

The heavy lifting is over…  So far, we’ve used ASP.Net Web Api and the LightSwitch ApplicationServerContext to gather and expose custom data reports, we’ve used C# code and a Nuget package to get that data to the client, and we created a custom Silverlight control based on one of the 7 billion (more or less) Syncfusion charting controls to visualize that data.

The glue to bind this all together: open the Dashboards screen in the screen designer, and in the middle area, select the main root (labeled “Columns Layout – Dashboard”) > Click on the Add link > New Custom Control. > Add Reference to the MySyncfusionControls library that we created, then > Select ColumnChartWrapper  > Data: Screen (ie: leave the default) > hit OK.

Image 024

Before finishing, select the user control in the screen designer, then in Properties Panel:

  • Set Display Name to “Top Regions”.  Remember the first of the XAML highlights? We’ll bind to this Display Name from the control. 🙂
  • Set Label Position to “None”
  • Set Horizontal Alignment to “Stretch”
  • Set Vertical Alignment to “Stretch”

Also, select the Save button in the screen command bar and in Properties Panel, set Is Visible to false.

Finally, press F5…

Boom!

Image 026

By the way: the purple column seems to be falling, that’s because I intentionally took the screenshot in the middle of the  “Rotate” loading animation.  – Showoff…

Thirty minute summary

There is no thirty minute summary, so rinse, repeat, try out some other charting controls, …  I added two more custom controls in the sample <Download link coming soon>, (don’t forget the prerequisites) which you could already see in action at the top of this blog post!  

If you like what you saw, feel free to leave a comment and automatically enter the Syncfusion Raffle…

O yes…  “Almost forgot”… (wink, wink, nudge, nudge) <Smooth transition> 

The Syncfusion Raffle!

You might think that this blog post is a little biased towards Syncfusion.  I won’t deny that, but in fact, the opposite is also true: Syncfusion is biased towards my blog readers.  Even more so, they are giving away five Enterprise Syncfusion Essential Studio licences worth $1999 each!

Let that sink in a little…  Syncfusion is giving my blog readers TEN THOUSAND DOLLARS of licences!

To enter the raffle:

  1. Before May 1st 2013: send out a tweet containing the #LightSwitch and #Syncfusion hashtag, and a link to this blog post.  For example: “#LightSwitch and #Syncfusion: simply beautiful applications. http://wp.me/p1J0PO-eW ” or “Thousands of dollars worth of #Syncfusion licences thanks to this #LightSwitch blog http://wp.me/p1J0PO-eW” or …
  2. Grab the permalink, and post the link to your tweet as a comment to this blog post (make sure you use a valid email address to comment, I need to be able to contact you if you win!)

One entry per person, normal contest rules apply.  If you don’t have twitter, just post the message on your blog, facebook, … 

The winners will be announced on May 1st 2013.

Best of luck, and don’t forget:

Keep rocking LS!

PS: not fan of all those colors?  Don’t worry, the sample <download link coming soon> shows you how add a combo box so you can change your color schema at runtime from “boring grayscale” to “metro” to “acid tripping”… 🙂

Image 039

LightSwitch news RSS: bringing you news from around the world! (http://bit.ly/lightswitchnewsRSS)

So…. What’s up doc?

Not much.  Reading some blog posts by other LightSwitch community members…

Sweet! Google Reader?

Errr… Haven’t you heared? Google is dead.  (Google reader*)

The easiest way to keep up to date with the other LightSwitch community members is to wait until the end of the month, then read Beth Massi’s Community & Content Rollup.  Unfortunately, there’s two problems with that approach:

Don’t you have your own twitter bot to keep you up to date?

Well yes, to keep myself up to date on a daily bases (I like news as hot as it gets), I turned each interesting “source” into a tweet by my twitter bot using ifttt.com

Unfortunately, this bot had some weird hiccups lately so after an extremely exhausting week I decided to spend a Friday afternoon rethinking my news model…

Naice! Found something fancy?

Well, actually I did.  After signing up for over a dozen awesome, great or plain terrible services, I found a really fancy service and spent a couple of hours getting the result looking clean and crisp.  Unfortunately, after spending those hours I discovered that this particular service only refreshes once every 24 hours.  I ended up settling for Yahoo! pipes, some kind of workflowy editor that seems to have no other use than to combine RSS feeds.

Which in a way, is exactly what I need. 🙂  And the pipes themselves look kind of fancy.

Image 031

So half a blog post to talk about how you wasted your Friday to end up with an RSS feed instead of a twitter bot?

No.

Half a blog post to talk about how I wasted my Friday to end up with an RSS feed in addition to a twitter bot.

That’s nice. Any downsides to this approach?

Well yes…. I got a bit lazy because Y!Pipes doesn’t have a copy&paste option, so now the bot that listens to the “LightSwitch news RSS feed”, doesn’t know the source of each item anymore.  Basically it  just tweets “#LightSwitch news: ….” now instead of tweeting “News by @AuthorTwitterHandle:  …”

Right… Well listen, thanks for blogging. We’ll give you a call…

Wait, there’s more!

  • RSS feeds are easy to plug into your favorite reader.  Or widget, like the new sidebar on my blog!
  • I can share the RSS feed now: http://bit.ly/lightswitchnewsRSS .  And if I find any good bloggers (feel free to make suggestions too!) I can simply update the Y!Pipes schema and you get all the new content too!

Smart!

And… Boring.  

Mostly boring.

So listen man, unless there’s some code goodies to be found in this post, I’ll be on my way.

Ok… Here you go 🙂

namespace RssDomain
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.ServiceModel.DomainServices.Server;
    using System.ServiceModel.Syndication;
    using System.Xml;

    public class LightSwitchNewsItem
    {
        [Key]
        public string Id { get; set; }

        public string Subject { get; set; }

        public string Content { get; set; }

        public string FullArticle { get; set; }

        public DateTime PublishDate { get; set; }
    }

    public class RssDomainService : DomainService
    {

        private static IEnumerable<LightSwitchNewsItem> allItems;

        [Query(IsDefault = true)]
        public IEnumerable GetDefault()
        {
            if (allItems == null)
            {
                string url = @"http://bit.ly/lightswitchnewsRSS";
                XmlReader reader = XmlReader.Create(url);
                SyndicationFeed feed = SyndicationFeed.Load(reader);
                reader.Close();

                allItems = feed.Items.Select(
                               item => new LightSwitchNewsItem
                                   {
                                       Id = GetId(item),
                                       Subject = item.Title.Text,
                                       Content = item.Summary.Text,
                                       PublishDate = item.PublishDate.DateTime,
                                       FullArticle = GetLink(item)
                                   }
                               )
                               .OrderByDescending(x => x.PublishDate);

            }
            return allItems;

        }

        static int i;

        static string GetId(SyndicationItem item)
        {
            string id = null;
            if (!string.IsNullOrEmpty(item.Id))
            {
                id = item.Id;
            }
            else if ((id = GetLink(item)) == null)
            {
                id = "Unknown  " + (++i).ToString("000");
            }
            return id;

        }

        static string GetLink(SyndicationItem item)
        {
            var link = item.Links.FirstOrDefault();
            if (link != null)
                return link.Uri.ToString();
            return null;
        }
    }
}

My eyes! I’m not supposed to get ugly code in them!  What is that?

It’s the code you can copy&paste in a RIA domain service, then use it as an external data source in your LightSwitch projects.

Image 030

That is indeed pretty cool! 

Thanks!  But not as cool as Dissociative identity disorder.  But anyways, I’m off.  Cya man, and don’t forget:

Keep rocking LS!

You too!

LightSwitch: technology overview.

February ’13 will be a fun month full of LSL (“LightSwitch Lovin’ – highly addictive”), including a very short high-speed demo at MS Web Cafe, and an intensive evening workout co-hosted by community rock star Paul Van Bladel: “Simple on the outside, rich on the inside“. 

While prepping, I started drawing a bit to try and capture how LightSwitch manages to take a simple idea, and through a simple IDE allows you to create such an impressive ecosystem.

Here’s 3 of my drawings, feedback appreciated!!

A simple idea

A simple idea

In reality (server)

In reality (server)

In reality (client)

In reality (client)

PS: When you’re not counting cursive text, since it represents my random thoughts in between my traditional and formal writing style, this has got to be my shortest blog post ever…

Simple yes or no question: is Silverlight dead?

Looking at the search terms that people enter and happen to result in the outcome of them visiting my blog, I noticed quite some visitors come here hoping to get a simple yes or no answer to their question: “is Silverlight dead 2012”  (or deviations thereof, including “Silverlight vs HTML5” etc).

Although I normally don’t blog about this subject, I can understand the confusion, because I do have quite some posts that would match those keywords, like

With this post, based solely on my own opinion, I wanted to give those people the simple yes or no answer to their question, and here it is:

“Is Silverlight dead 2012?”

Yes, it is.

IF

and ONLY IF

your target is Joe Blow playing FarmVille on his iPad while watching “[YourCountryHere] got talent”.

And there you have it.  My simple answer.

If you are interested in my reasoning behind that answer…

If your target is regular Joe…

I don’t mean this in any demeaning way.  The business to consumer market is huge, and when the iPhone was first released some people became millionaires by creating a $0.99 Fart-Machine-app for that market.

This market segment is so big that the consumerization of IT pretty much dictates what the next major coding language will be this decennium.  I read an interesting post by Shawn Wildermuth about the current state of Silverlight, stating that it was in fact Steve Jobs who is responsible for what is happening to Silverlight.  When Apple (traditionally more popular in the consumer world than in the business world) launched the iPhone & iPad, and decided that no plugins would work on these platforms, that basically killed Silverlight and Flash in the business to consumer market.

Personally, I also believe this is one of the causes why HTML5 is that much more impressive than it’s predecessor, because the death of browser plugins left a gap that needed to be addressed, causing all parties involved to jump on the HTML5 wagon in high pace.

So my advice if you are going to build an app for the business to consumer market, would be not to use Silverlight.  Some IDEs allow you to write code that runs natively on a broad range of mobile devices, HTML5 is platform independent, … or just take a pick and write a truly awesome native app for a specific platform (iOS, Win8, whatever).  Your market is huge, and by the time the technology you picked has peaked, you’ll have plenty of profit to pay for a rewrite anyways…

If your target is the business…

Then the answer becomes a bit more difficult.  There are pros and there are cons now.  Pros include the fact that in the business world, Windows is traditionally a lot more popular than other operating systems, so you’re not really cutting off a significant slice of your potential market if you would decide to actually use Silverlight.  Pros also include the fact that you might have years of experience building Silverlight apps and thus you’re simply better at it.  From the business’ point of view, this means less money for a more stable product.

Personally, I like the way LightSwitch, that primarily targets small to medium LOB applications, is heading here.  Main client is Silverlight, but there is in fact the ability to  quickly pump out a mobile companion app when cross-platform or going mobile becomes a true requirement, or even to write a custom website all-together.

Whenever I can, if the need arises for a small to medium LOB application, I’ll open up LightSwitch and write them the application that will last at least another 15 years as opposed to the 20 that HTML5 might last them (you don’t think HTML5 is the last stadium in IT evolution, do you?), for a tenth of the time it would take someone else the same application in another technology.

If your target is the enterprise…

If you’re lucky enough, like I am on my day job, to be involved in multi-million enterprise to enterprise applications, then the answer to the question become less difficult again.

HTML5, a logical competitor for Silverlight, might be better in quite a large number of ways.  However, the tooling and experience, isn’t better yet.   This will most likely change in a couple of years, but considering the available Silverlight libraries, both open source and built in-house, experience and tooling, still screams that making the swap today would be deadly to your enterprise organisation, unless there’s a specific requirement for another or multiple platforms for the entire application.

So in summary…

There you have your simple answer, or at least my vision about what the most simple answer to that question is.

Also, and this one comes out of personal frustrations & experiences:  if you read the intro to my LightSwitch Succinctly eBook,  you’ll know that I’m a firm believer of focusing on the end-users needs first.  Don’t read this blog post during office hours, especially not if you are looking for posts to back you up in a discussion with your boss or coworkers about the technology to use for the next project, if the real reason is that you are only looking for an opportunity to play around with another technology.  Feel free to play around during your own time, but when there’s real end-users involved, focus on their needs, and the amount of money they end up paying for what they get.  Let that be the dictating factor of your decisions…  /rant

I’d like to end this post with a saying I hear daily from one of my personal friends and work mates: The answer to any question in IT is, always was and always has been: “It depends”. – Quote Arne Wauters.

 

 

Executing an arbitrary method or long-running process on the LightSwitch server: 2. Grab the code.

In the business world that we try to model into bits and bytes, not everything is considered CRUD.  Although LightSwitch excels at creating CRUD-based applications or data services, the need to call an arbitrary method  or long-running process on the server couldn’t really be satisfied without hacks or workarounds…

Until now.

This sample explores the simple but (for unknown reasons) long-running business process of “inviting a friend to check out an application”.  The sample in itself has no other functionality than the ability to invite more users, who would not want to check this out?

Lesson of today: how to grab the code:

  1. Click this link
  2. Follow your intuition

And that’s all there is to it.

Finally, let’s finish off with a small recap of today’s blog post: click here to get the sample.

 

Keep rocking LS!

 

PS: I’m trolling, obviously, but I really wanted to publish a link to the code sample ASAP, just because I had it ready and working my way through all blog posts might take a while 😉

Executing an arbitrary method or long-running process on the LightSwitch server: 1. Overview.

In the business world that we try to model into bits and bytes, not everything is considered CRUD.  Although LightSwitch excels at creating CRUD-based applications or data services, the need to call an arbitrary method  or long-running process on the server couldn’t really be satisfied without hacks or workarounds…

Until now.

This sample explores the simple but (for unknown reasons) long-running business process of “inviting a friend to check out an application”.  The sample in itself has no other functionality than the ability to invite more users, who would not want to check this out?

Besides the actual source code, there will be a couple of blog posts over the next few weeks that explain the sample in great detail:

  1. Overview – This page.
  2. Grab the code – In case you want to see it all before the blog post series is finished.
  3. Permissions elevation: creating a new user.
  4. Adding a SilverLight compatible WCF (SOAP) service to a LightSwitch application.
  5. Working with the ServerDataContext.
  6. The ABC of WCF: where, how, what?
  7. To channel or not to channel: ChannelFactory vs Add New Service Reference…
  8. Modal, modal, modal: three ways to show a modal window on the SilverLight client.
  9. In summary…

Hope you enjoy, and as always, don’t be afraid to leave a message in the comment section below!

Keep rocking LS!

Rumor has it… LightSwitch HMTL Client preview 2 is released – omg omg omg with a ServerApplicationContext?!?

Testing… 1… 2… Is this thing on?  Man it’s been a while since I blogged, hopefully I still have that fingerspitzegefühl…

Hey LightSwitch lovers out there!  It has indeed been a while since I blogged or actively participated in the community, and this is because I’ve been really unfortunate with my health and energy levels the last couple of months.  I’m gradually getting better though, and taking back control of my life.

And of course, as you can imagine, LightSwitch is still a major part of my life, as is my Hacking LightSwitch blog… So a big thank you to all that kept visiting my blog, posting me comments, tweets or mails, etc.  Time to repay your enthusiasm: it’s the blog, part… euh… Anyways, here we go!

The LightSwitch team released a new preview of our beloved technology yesterday, and it is miiiiiind-blowing!  Normally, when big stuff is about to hit us, I’m quite good at putting together the clues and posting a “Rumor has it…” post at least a couple of days beforehand.

This time though, except for my one tweet about the session that was given at //BUILD, where I noticed that the version they were showing had some slight differences between the preview 1 that I was exploring, the stars failed to predict the bomb that the team was about to drop on us.

So does this imply I don’t have a scoop for you, my dear reader? – O hell no, I do have some exiting news about this release that hasn’t been announced, documented, or even been mentioned in the official channels, or any other community channel.  The new born miracle is called “ServerApplicationContext”, and it’s so magical that I’m going to save it until the end of my post… :p

So what is this update all about?

It installs right over Visual Studio 2012

Which is awesome news. As you might remember, preview 1 was shipped in a vhd of a Win8 machine, which probably scared a lot of people off, myself included.  In my case, it was because I’m usually working on a laptop from work, and it would really be against company policy to decide to install a preview build of Win8 on this machine.  No one in my company knows that I actually installed it.

Crap…

But anyways, this is awesome, because I can’t imagine any serious LightSwitch developer not grabbing this free 30-something-megs of goodness and start playing around with it.  More people means: more content from the community + more feedback to the team = happier life for all of us.

It requires you to make non-functional changes to your projects

Don’t make the mistake I did: if you want to play around with it, create a new project.  If you open an old project and want to use any of the new features:

  • You have to “add an HTML” client first.  This is when the conversion kicks in, and the new features become available to you.  However, when you do so:
  • Your project won’t be compatible with people who do not have this new preview installed.  But than again, what serious LightSwitch hacker is going to be able to resist all these goodies?

Thankfully, like in the past, the team managed to make this conversion a one-time-step where they take good care of your precious project if you stick to the official API’s only.

Damn, I’m basically screwed.  That’ll teach me.

Seriously though, just hold on to your seats for about a minute, and your project will be upgraded without you having to put in any effort.

Like deleting the common project.

Whoa momma, really? 
Yep, a LightSwitch application, that traditionally existed out of three projects (“client”, “common”, “‘server”) will now be reduced to only two projects.

Which in a way, was an obvious step that makes a lot of sense.  The common project contained code in c# (ok or VB.Net if you must), which isn’t really “common” between client and server if your client isn’t a CLR project itself.  The chances of new clients not being written in .NET are pretty high, I’m sorry to shock you if you were one of those people who were waiting for LightSwitch WinForms support, so this was an obvious move.

Anyways, the team will probably blog loads about the new “Entity Designer View”, I just want to point out that they still believe code that can be written only once, should be written only once.  They just decided that a common project was no longer the best way to accomplish this, so made this modification under the hood and focused more on the new clients.

Clients, plural, like the HTML mobile companion client

Good news, bad news.  The bad news is: from the looks of it the team reduced the number of HTML mobile companion apps from infinite to just one.  Not exactly sure why that is, but I trust their judgement, and this little loss gets paid back with tons of improved functionality in the HTML mobile companion app designers.  More extension points, in-IDE -debugging (thank god for that!!!), more custom methods, a new Listy control, and much much much more.

Clients, still plural, like the SharePoint apps

Seriously, this is HUGE.  I previously posted the link to the sample SharePoint app, but it seems to be broken. 😦

!!UPDATE!!: our LightSwitch goddess to the rescue: the real link is: http://code.msdn.microsoft.com/Survey-App-Tutorial-a70d0afd

Either way, I consider this to be huge not only because it’ll allow the flock of LightSwitch developers to access new markets and do even more for their end-users, but also because it’ll bring an entire new audience (SharePoint developers) into our precious community.

Welcome guys, take a seat, first round is on me!

Again, I don’t doubt that the teams will blog about this in great detail over the next few weeks, and I don’t have anything interesting to say about it yet (I’m still pondering on how I’m going to hack this), so let’s move on to that scoop then…

Clients, still plural, like the ‘everything you can imagine’

Or at least: almost everything.

Since LightSwitch 2, an app that was previously using WCF RIA services turned into an app that exposed its data via the Open Data protocol.  This opened up a wide range of opportunities, and the community (Michael Washington in particular) went in overdrive coming up with new types of clients that used the REST api to interact with the data.

However, it still felt like you really were creating two apps, one LightSwitch app (or data service) and one additional (random) client.

Many of us have tried to find another way, some kind of mechanism that allows you, from your client code, to tap directly into the LightSwitch application model.  And those that tried really felt like swimming upstream, running into problems with connections remaining open, having to unload the LightSwitch project and manually alter the build process, …

Like always, the team was watching our moves, and decided to facilitate this play in the new preview release:

  • You can now add files to the server project and they will be built and shipped with the project without manual changes.  These files could be anything you would traditionally add to a server, like new WCF services or ASP.Net (web forms / MVC4) pages.
  • From the code-behind, you can actually access a ServerApplicationContext and interact with it (Current user, permissions, tables, queries, etc) like you interact with the ClientApplicationContext in the SL, HTML mobile companion, or SP clients!   Clean, simple, we’re gotten quite familiar with it, and they take care of all the internals for you.

This, is so incredibly huge, I would even dare to describe it as our own Server SDK!   Three potential use cases immediately come to my weird little mind:

  • Create full-blown (‘Desktop’) websites with LightSwitch!  Wow!  This has been requested by so many people.  Also, I bet you $10 bucks I can predict who will be the first to publish some really good community content about this…
  • Create a WCF service and expose it over a duplex binding so that you can implement a PubSub pattern.  No more polling, the server can actually publish to the clients when there is a new “Message” or “Alert” or …
  • Create a WCF service and actually call arbitrary business (non-cruddy) commands on the server, even long-running processes, without the need of the Command Table Pattern.

Sweeeeeeeet!

A very big thank you to the team for coming up with more and more LightSwitch goodness, I tip my hat to all of you!

Now, enough drooling, let’s hop into some code!

Keep rocking LS!

Silverlight is dead. Long live LightSwitch!

[SPOILER ALERT]I’m working on my presentation: “Visual Studio LightSwitch: Under the hood” for community days, and decided to post a little preview of some of the contents…  If you are one of the 8 (or more, hopefully a lot more) people that intend to join my session, don’t read on…

After the usual “TOC” and “About the speaker”, I show a very small demo on LightSwitch for those people that tend to sneak into level 400 sessions without knowing the technology (something I do a lot myself :-)).  Right after the demo, something along the lines of this follows:

So anyways, if this was the first time you have ever seen LightSwitch, I can imagine you’re thinking:

Man, I wish I had LightSwitch about three years ago… When Silverlight wasn’t dead.

As a LightSwitch addict, it must admit it hurts every time I see or hear this.  Silverlight is dead.  Stop saying that.

The truth is, Silverlight is not dead at all.  Microsoft just rolled out an update (5.1 was rolled out on May 8th 2012), and they commit to support SL5 untill at least 2022 on Mac OS 10.5.7 and Windows 7, or lower.  Besides, in my personal experience, when it comes to the technology that’s used to build their products, the business really doesn’t care…

[Small pause]

Did anyone buy a word of what I just said?  Anyone? Did you? 🙂

So here’s the truth, the whole truth and nothing but the truth… At least, what I, as a non-Microsoft-employee, think I know of the truth…  

Screw palliation: Silverlight is dying.  I know it’s a harsh thing to say and I tried to deny it myself for quite a long time, but it’s the truth, so you might as well skip right to the fifth stage of grieving: acceptance.  In the youth-oriented, fast-paced, ever-changing IT world that we live in today, every new technology will die at a certain point.  Silverlight might not be dead *right now*, but since Windows 8 going RTM in less than two months, it sure is dying a lot faster than some other technologies…

However…

Meet Matt Evans.  Besides having one of the goofiest (I mean this in a good way) profile pictures out of all Microsoft employees, he’s a member of the LightSwitch team and an enormous help to anyone with a LightSwitch question on the MSDN forums.  One of his recent replies on those forums, was this:

The first line: “The LightSwitch team here at Microsoft is hiring people”, makes me question two things:

1) The LightSwitch team is hiring? What the h*ck am I still doing here in Belgium??!?

And, more realistically:

2) Why are they hiring?  LightSwitch uses Silverlight as a client, and Silverlight is dead.  Why on earth would you be expanding the team?  (Let’s pretend you haven’t read Matt’s second and third line in that post) I’ll tell you why!  Because they’ve got an ace up their sleeves.  And I personally might not know 100% sure what suit that Ace is, but I know for a fact that they don’t just have an ace up their sleeves… They got pocket rockets and the flop’s about to serve them four-of-a-kind!

I’ll let you in on a little secret

Back in the days, when I started programming, we used something called punch cards that basically contained machine level instructions.  This is of course a flagrant lie, I’m 27 and probably wasn’t born when some of you punched holes in paper as a living…

As technology evolved, and magnetic storage and more powerful computers became available, the world got rid of  machine language (1st generation language) and moved on to a higher level of abstraction: writing assembler (2-GL).

That might have been fun for a while, but to avoid unnecessary repetition,  macros were added and pretty soon the world discovered an even higher language of abstraction: 3GL languages such as COBOL, FORTRAN and LISP.  Random side-note: notice how all these 3-GL languages seem to have names in ALL-CAPS.  Ooooh, metro-ish!

Note that from 1-GL to 2-GL, and again from 2-GL to 3-GL, a important “compatibility” shift happen.  Instead of writing instructions that are tightly-coupled to the processor that will execute them, the 3-GL world is now at a level where they can write in a programming language, and then compile that into machine-dependent instructions.

Fast-forward to today’s situation, both the languages and the compilation process there-of, have taken on considerably higher forms of abstractions.  Object Oriented Programming languages like Java, C# and VB.Net, are a higher level of abstraction over procedural programming, and compile in an intermediate language, which is then (JIT-)compiled by a VM to OS specific instructions, who in turn translates these to machine instructions.

Really moving forward, as history proved, means moving towards higher level of abstractions…

I say this of course in an attempt to make you wonder about what the next level of abstraction is that we can make over Object Oriented code…  Well, the next level of abstraction, X-GL (the value of X kind of depends on who’s counting, meaning I really don’t know) is this:

Quick: out of the programming languages you know, randomly pick either your first, your latest, or your favorite.

Now, in that language, imagine you’re giving this UML-like requirement and you’d have to implement it, ie. write the OOP code.  Can you do it?

Of course you can, and the fact that you can is simply amazing!  Not so much that YOU can, in particular, but the fact that based on the same UML-like input, we were able to write (well: imagine writing) implementations in probably half a dozen programming languages.

Let’s do the same exercise again: here’s the requirements to a query, imagine writing it.

Bam!

Some of you envisioned Entity Framework, some were thinking of LINQ, others had an SQL query in mind.  Based one one input, we can come up with several actual implementations.

See where I’m going to?  Ok one last time, create this screen, mentally, in the technology that you used last before coming to this session:

Were any of you creating this screen in WPF?  Silverlight? HTML5? Swing? A free WebFormsBuilder tool? WinForms?  (If you raise your hand when I say “WinForms” by the way, I do feel for you…)

The point is: based on the same input, you can write all kinds of working applications, varying on (the experience of the developer, and) the requirements of the customer.

And I don’t want to offend anyone’s intelligence here, but if this input is provided in a standard format, a smart compiler could do that too.  Perhaps even better, most definitely even faster.  And if the requirements change to the point where you need to rewrite your application in a different technology, simply take the same input and hand it over to a better compiler…

Pocket Aces, I told you!

This idea is called Metadata driven development, and it isn’t new at all.

In fact, there’s a book called “The pragmatic programmer” (a book I feel everyone should read), which was first printed in 1999, where the DRY-principle was tossed for the very first time…

Although almost everyone will claim to know what “Don’t Repeat Yourself” stands for, I found that a lot of people think it simply means one shouldn’t copy&paste code.  It doesn’t, in fact it describes how every piece of knowledge in a system should have one and only one, unambiguous, authorized source of truth.  Andrew and David describe metadata, and code-generation or interpretation techniques, to accomplish pure “DRY” implementations.

Implementing this DRY principle, the LightSwitch IDE might seem “simple” at first sight, and thus “likely to be inferior” to what you have been doing as a professional developer over the last couple of years. It is easier to dismiss it as a tool for non-developers, than to admit it is actually a higher level of abstraction over the OO code you might have been writing so far.

Each designer in the LightSwitch IDE is in fact a graphical layer over metadata, which is stored in several LSML (“Lightweight & sexy metadata language”) (“LightSwitch Markup Language” actually) files.  This, is the input.

Given enough time and resources, the output, can be whatever you want it to be.

No wonder they are hiring…

Silverlight is dead.  But that was just one way to interpret LSML.  That was just the Ace-ten suited that LightSwitch v1.0 opened with.  Pretty soon the flop will be dealt.  My money, is on the team with the pocket aces up their sleeve…

Silverlight is dead.  Long live LightSwitch!

And then of course I pop open the hood, as we dive deeper in  the metadata driven client, where the metadata is interpret at run time, and in other different engine parts… What do you think?  Good? Bad? Barely staying awake or eye-opening?