This is the first in a series of LightSwitch Gotcha posts. I have no idea how many there will be, but I suspect there will be plenty as I run into things myself or hear about things that happened to other people.

To see this first gotcha in action, and to perform this trick yourself, build a very simple LightSwitch application. All you need is one table with a handful of properties. Then add a New Data Screen based on that table. Run the application and open the new data screen. You can add a new record.

Figure1

Exit the application and roll up your sleeves to prove there is nothing up them. In the Solution Explorer, right-click on the screen and select View Screen Code. You will see code like the following (the C# code looks very similar):

Private Sub CreateNewEmployee_BeforeDataInitialize()
  ' Write your code here.
  Me.EmployeeProperty = New Employee()
End Sub

Private Sub CreateNewEmployee_Saved()
  ' Write your code here.
  Me.Close(False)
  Application.Current.ShowDefaultScreen(Me.EmployeeProperty)
End Sub

Delete this code. Why would you do that? Perhaps it is days, weeks or months later and you have many screens in the application, as well as lots of data validation and other code. You open this screen code and you don’t recognize the code above. You assume you wrote it a while ago and that it is not needed. You also miss the warning sign, which is the Write your code here comment.

Run the application and open the new screen. Notice the controls are all disabled and the default values do not appear.

 

Figure2

What happened? The code in the BeforeDataInitialize creates a new Employee object and then assigns that to Me.EmployeeProperty, which represents the screen’s data. At this point, a light bulb goes on (get it? Smile). Deleting that code is equivalent to dragging a table from the Data Sources window onto a Windows Form and then going to the form’s Loaded event handler and deleting the code that fills the DataAdapter. If you don’t retrieve data, you can’t populate a data entry screen!

No doubt many of you looked at that code and knew pretty quickly what it did. So when I said delete it, you knew why it would break the application. I am also willing to guess that many of you did not immediately know this, or at least could wind up in a situation where months later you did not recognize that code and immediately understand why you shouldn’t delete it.

The simple moral of the story? Understand that LightSwitch generates code for you. Most of it is behind the scenes, but not all of it. You need to be aware of that and be careful when you look at code. A best practice might be to put the LightSwitch generated code in it’s own region if you aren’t going to touch it. Or add a comment to identify it.

On a personal note, I am now rooting for the Chicago Bears in the NFL playoffs, since the teams from my wife’s and my other current or previous home towns (Boston, Baltimore, Seattle) are all out of it. Go Bears!!