Microsoft -LightSwitch – Error – “Request Failed with Status Code ‘500’ and Status Text ‘Internal Status Error.'”

Background

From within Visual Studio, launched an application that I am developing using LightSwitch and received one of those hard to decipher error.

Error Message

Image

requestfailedwithstatuscode500

Text

Request failed with status code ‘500’ and status text ‘Internal Server Error’.

TroubleShooting

As I know so little about LightSwitch, I get petrified anytime I see an error.

Event Viewer

Took to the system’s event viewer and found the obvious problem.

Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult – System.ServiceModel.ServiceActivationException

Image

taskcategory_webhost_2017021_0445pm-cropped-up

Textual

WebHost failed to process a request.
Sender Information: System.ServiceModel.Activation.HostedHttpRequestAsyncResult/35567111
Exception: System.ServiceModel.ServiceActivationException: The service ‘/DBDiagData.svc’ cannot be activated due to an exception during compilation. The exception message is: Memory gates checking failed because the free memory (196927488 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.. —> System.InsufficientMemoryException: Memory gates checking failed because the free memory (196927488 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
at System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)
— End of inner exception stack trace —
at System.Runtime.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Activation.HostedHttpRequestAsyncResult.End(IAsyncResult result)
Process Name: iisexpress
Process ID: 2756

Tabulate

Product Version File Version
 Log Name Application
 Source System.ServiceModel 4.0.0.0
 Event ID  3
 Task Category  WebHost
 Level  Error
 Process Name  iisexpress

 

 

ASP.NET 4.0.30319.0 –  InsufficientMemoryException

Image

taskcategory_aspnet_2017021_0616pm-croppedup

Textual

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 2/21/2017 4:15:03 PM
Event time (UTC): 2/22/2017 12:15:03 AM
Event ID: a9e5abe2978940499d84b3ed7b2bc5a1
Event sequence: 34
Event occurrence: 1
Event detail code: 0

Application information:
Application domain: /LM/W3SVC/2/ROOT-1-131321960967478001
Trust level: Full
Application Virtual Path: /
Application Path: C:\EDiag\bin\Debug\
Machine name: DADENIJI

Process information:
Process ID: 2756
Process name: iisexpress.exe
Account name: dadeniji

Exception information:
Exception type: InsufficientMemoryException
Exception message: Memory gates checking failed because the free memory (179412992 bytes) is less than 5% of total memory. As a result, the service will not be available for incoming requests. To resolve this, either reduce the load on the machine or adjust the value of minFreeMemoryPercentageToActivateService on the serviceHostingEnvironment config element.
at System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)

Request information:
Request URL: http://localhost:62496/Services/Microsoft-LightSwitch-Security-ServerGenerated-Implementation-AuthenticationService.svc/binary/GetAuthenticationInfo
Request path: /Services/Microsoft-LightSwitch-Security-ServerGenerated-Implementation-AuthenticationService.svc/binary/GetAuthenticationInfo
User host address: 127.0.0.1
User: dadeniji
Is authenticated: True
Authentication Type: Negotiate
Thread account name: dadeniji

Thread information:
Thread ID: 11
Thread account name: dadeniji
Is impersonating: False
Stack trace: at System.ServiceModel.Activation.ServiceMemoryGates.Check(Int32 minFreeMemoryPercentage, Boolean throwOnLowMemory, UInt64& availableMemoryBytes)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.CheckMemoryCloseIdleServices(EventTraceActivity eventTraceActivity)
at System.ServiceModel.ServiceHostingEnvironment.HostingManager.EnsureServiceAvailable(String normalizedVirtualPath, EventTraceActivity eventTraceActivity)

 

Tabulate

Product Version File Version
 Log Name Application
 Source ASP.NET 4.0.30319.0
 Event ID  1309
 Task Category  Web Event
 Level  Warning
 Process Name  iisexpress.exe

 

 

Remediation

Using Microsoft’s Task Manager close some of the Applications and Processes that are sagging memory.

Our target is to get more than 5% memory available.

Deploying LightSpeed Application – Web Platform Installer

Background

I need to deploy a small application that I placed together to pilot Microsoft Lightswitch.

We will be using Beth Massi’s “Deploying Lightswitch Applications to IIS 6 & Automating Deployment Packages” as a guide.

BTW, that excellent tutorial is here.

 

Web Platform Installer

Overview

  1. Microsoft Web Platform Installer
    • v5.0
      • Support Operating Systems:- Windows 8, Windows 7, Windows Vista SP2, Windows XP SP3+, Windows Server 2003 SP2+, Windows Server 2008, Windows Server 2008 R2, Windows Server 2012.
      • Date Released :- 2/14/2013
    • v4.6

 

Download

To download the full blown installer, please go here.

As of today, 2016-Oct-13, here are the files that are currently available.

Links

Product Version x86 x64
 WebPI 5.0  Link – v5.0 – x86  Link – v5.0 – x64
 WebPI 4.6  Link – v4.6 – x86  Link – v5.0 – x64

 

 

Download & Installed

v5.0

As our box is an old x86 box, downloaded v5.0 x86 version.

 

Usage

From the Start menu, looked for “Web Platform Installer” and initiated it.

 

Error

Unable to download Product List
Image

unabletodownloadtheproductlistfrom

Textual

Unable to product list from .  Check your network connection and try again.  If the problem persists, report the use on the Web Platform Installer 5.0 forum at …

 

Remediation

Courtesy of

Superdoods @ Rackspace
Link

Launch regedit, navigate to the HKLM\Software\Microsoft\webplatforminstaller branch and add ProductXMLLocation to the

  1. Open regedit
  2. Navigate to HKLM\Software\Microsoft\webplatforminstaller
  3. Create a new string value

 

As we are going with the latest Web Platform Installer, v5.0, we went with the registry entry for 5.0

 

Before Registry Entry – v5.0

productxmllocation-before-20161212-1059pm

After Registry Entry – v5.0

productxmllocation-v5-20161212-1101pm

Restarted

Stopped and restarted Web Installer Platform and no more error message.

 

Deprecated

Unfortunately, LightSpeed Runtime is no longer bundled with v5.0, and so NO GO.

 

v4.6

Went back and downloaded v4.6 version.

Usage

From the Start menu, looked for “Web Platform Installer” and initiated it.

 

Search for Products

Search for Visual Studio LightSwitch…

And, we matched on

  1. Visual Studio Lightswitch 2011 Server Runtime without Local SQL
  2. Visual Studio Lightswitch 2011 Server Runtime and Local SQL

visualstudiolightswitch-searchresults

Add Products

As we have a remote SQL Server backend, we chose the “Visual Studio Lightswitch 2011 Server Runtime without Local SQL” option.

 

Prerequisite
Prerequisite – Image

visualstudiolightswitch-prerequisite

Prerequisite – Tabulate
Product File Size Link
 Visual Studio LightSwitch 2011 Server Runtime without Local SQL 1 MB
 Web Deployment Tool 1.1  5.01 MB  Link
 SQL Server 2008 R2 Management Objects  (x86) Only [ ENU\x86\SharedManagementObjects.msi ]  10.42 MB  Link
 SQL Server Native Client [ SQL Server Native Client 10.5 ]  4.49 MB  Link
 Microsoft System CLR Types for Microsoft SQL Server 2008 R2 (x86) [ ENU\x86\SQLSysClrTypes.msi ]  3.31 MB  Link

 

 

Prerequisite – Install Manually

If you will like to install the prerequisite yourself, please go here.

Please make sure that you are looking for the v2008 R2 version.

details

 

Installation
Installing…

install

Installing – Completed

installation-complete

 

Installing – Restart Completed
Image

restartcomputer

Textual

SQL Server Native Client 10.5 has finished installing successfully but requires a computer restart.
Do you want to restart your computer now? Click yes to restart now, or click no to close Web Platform Installer 4.6 and restart later.

 

References

Support

  1. Manual fix for a broken Web Platform Installer that cannot pull the packages from the Microsoft online package repository
    Link
  2. PLEASE READ: WebPI direct download links
    Link

QA

  1. Where to get Visual Studio LightSwitch 2012 Server Runtime from in Web Platform Installer?
    Link

LightSwitch – Simple table with a couple of referenced support tables

Background

One of the common “Beginner go to” Applications is a simple table that has Foreign Key relationships to a couple of Lookup tables.

Let us see whether Microsoft Lightspeed makes short walk of it or whether it stumbles.

 

Data Model

Diagram

Admittedly, it is an awkward looking Diagram.

DataModel

 

But, hopefully it is easy enough to follow with four entities.

 

Entities

Entity Use Content
listofServers lists all of our servers HRDB, HRWeb, mail gateway
listofApplications List the few applications that we support HR, Sales, Marketing
listofServerEnvironment Dev, QA, Test, Performance, and Prod
listofApplicationServers Joins the aforementioned entities

 

Foreign Key

Let us use sp_fkeys to get the foreign keys defined on our table.

Syntax


exec sp_fkeys
         @fktable_name = [table-name]
       , @fktable_owner = [schema-name]

Sample


exec sp_fkeys
         @fktable_name = 'listofApplicationServers'
       , @fktable_owner = 'dbo'

Output

sp_fkeys__listofApplicationServers-20161117-0940PM

Explanation

  1. We have declared three foreign key relationships
  2. The first one listed is FK_listofApplicationServers_listofApplications
    • The join is on ApplicationID
  3. The second one listed is FK_listofApplicationServers_listofServerEnvironment
    • The join is on serverRole (listofApplicationServers) to EnvironmentID ( listofServerEnvironment )
  4. The third one listed is FK_listofApplicationServers_listofServers
    • The join is on serverName
    • But, there is an important different between this join and on our other joins
    • This join does not target our Primary Key
      • Please take a look at the last column ( PK_NAME )
      • The first two joins targets PK_listofApplications and PK_listofServerEnvironment
      • And, the last targets IX_listofServers_ServerName
        • The reason is that the PK on dbo.listofServers is a serverID and not serverName
        • We chose to introduce serverID as a firewall against server name changes

 

 

LightSpeed

Once we are in light speed we will quickly go to work.

 

Data Source

Attach Data Source Wizard

Choose your Database Objects

 

AddDataSource-20161017-0703PM

 

 

 

LSML Files

listofServerEnvironments

Diagraming

Here is what our lsml display of the listofApplicationServer entity looks like

listofApplicationServer-lsml-20161117-0651AM

 

Explanation
  1. Our Primarky key is a composite key
    1. And, it has ApplicationID, serverName, and serverRole has the columns in the composite
  2. There are two additional properties
    • And, those are listofApplication and listofServerEnvironment
    • They allow us to map many-to-one  to our support tables ( listofApplication & listofServerEnvironment )
  3. A careful observer will not that our join to listofServers is missing. Why?

 

Add Relationship

By clicking on an empty spot in the panel, we can initiate the “Add Relationship”  option

    Add New Relationship – Begin

AddNewRelationship-20161118-0622AM

 

 

    Add New Relationship – In Process

Here we attempt to tie the listofApplicationServer table to the listofServer table

AddNewRelationship-InProgres-20161118-0720AM

 

But, we get an eror message that reads:

Image

RelationMustBeMappedOnTheKeyFields

 

Textual

The relationship must be mapped on the key fields and only the key fields of the primary side of the relationship.

 

Screens

Next thing to do is to setup the Screens.

Doing so involves deciding which screens are needed and customizing the default layout design of each screen.

 

Add New Screen

Let us Add New Screen …

 

AddNewScreen-20161119-0809AM

 

 

Explanation:

  1. Screen Sheet Name
    • ManageApplicationServer
  2. Screen Data
    • Syntax
      • DataSourceName.DataSetName
    • Sample
      • DBDiagData.listofApplicationServer

 

 

Layout – Default

 

Browse

Here is the layout of the Browse Screen

BrowseManageApplicationServers=-20161119-0811AM

 

Explanation
  1. Our three primary columns are displayed in the Browse Screen
  2. And, so for each each record we have our key columns display
  3. This makes it easy for specificity in row selection
  4. BTW, the key columns are Server Name, ApplicationID, and Server Role

 

 

 

View

Here is the layout of the View Screen

ViewManageApplicationServer-20161119-0811AM

 

Explanation
  1. The layout is two rows displayed horizontally
  2. And, all columns are displayed

 

Add Edit

AddEditManageApplicationServer-20161119-0812AM

 

Explanation
  1. This is same the screen design as the View Layout
    • The layout is two rows displayed horizontally
    • And, all columns are displayed

 

 

HTML Client

When we run the uncustomized application, here are the screens generated.

Browse

HTML Client display of the Browse Screen

Browse-20161119-0815AM (brushed up)

 

Explanation
  1. Our three primary columns are displayed in the Browse Screen
  2. And, so for each each record we have our key columns display
  3. This makes it easy for specificity in row selection
  4. BTW, the key columns are Server Name, ApplicationID, and Server Role

 

 

 

View

HTML Client display of the View Screen

View-20161119-0816AM ( Brushed up)

Explanation
  1. The layout is two rows displayed horizontally
  2. And, all columns are displayed
  3. Both the id and literal columns are displayed for columns involved in Foreign Key relationships

 

Add Edit

Here is what is rendered in the Add/Edd HTML Client

AddEdit-Edit-20161119-0819AM (Brushed up)

 

Explanation
  1. All columns are displayed
  2. For the columns involved in Foreign Key relationships both the id and the literal columns are displayed
    • For example
      • The Application ID ( 1 ) and the Application Name ( –PAS ) are displayed
      • The server Role ( 1 ) and Server Environment ( Production ) are displayed

 

 

 

Layout – Revised

 

Browse

Here is the layout of the Browse Screen

BrowseManageApplicationServers-20161119-0825AM

 

 

Explanation
  1. As stated earlier, we kept the identifying parameters
  2. To make them easier to read and identify, we replaced the system ids with their actual literal companions
  3. For record keeping, we did not remove the original system identifiers, we are merely hidden them

 

View

Here is the layout of the View Screen

ViewManageApplicationServer-20161119-0831AM (brushed up)

 

Explanation
  1. We kept the same layout and data has the Browse screen
  2. We could have added more data here, but for this particular entity the other  columns are timestamp tracking columns

Add Edit

 

AddEditManageApplicationServer-20161119-0834AM

Explanation
  1. Again, we kept the same data
  2. The entity we are addressing is a join table and not a user table

 

HTML Client

Now we will run the applicaton post touch up…

Browse

HTML Client display of the Browse Screen

Browse-20161119-0823AM (brushed up)

 

 

Explanation
  1. Again, our three primary columns are displayed in the Browse Screen
  2. But now not just the system ID, but the descriptive literals

 

 

View

Here is the HTML Client display of the View Screen.

We declutter it so that it only has data that we need.

 

View-20161119-0840AM (Brushed Up)

 

Add Edit

Here is what is rendered in the Add/Edd HTML Client

AddEdit-Edit-20161119-0839AM (Brushed up)

 

Explanation
  1. Again, we only have the columns that are needed
  2. And, those the Server Name, Application, and Environment

 

Summary

LightSpeed allows us create simple screens that supports entity and referenced columns.

Unfortunately, though it supports referenced Primary keys, it does not support candidate keys.

LightSwitch – Current User name – Default and Validation

Background

Microsoft’s LightSwitch is marketed as this easy to use tool, but I am finding it as a great easy to confuse tool.

 

Problem Identification

GUI

I have a simple Data Entry GUI that looks like this:

thisfieldisrequired

I am being asked to enter the “added By” name.

Usually I will check on the database’s stored procedure and set it to SYSTEM_USER when empty.

Data Model

BTW, here is the entity..

listofcontact

We can see that “addedBy” is a String and it is Required.

Unfortunately, I am not able to toggle the required flag as it is greyed out.

 

 

Remediation

Entity – properties – Allow Empty String

Property Changes

Here is our first remediation try …

properties-addedby-default

The “Is Required” flag is disabled.  And, so took the easy route of checking the “Allow Empty String” flag.

properties-addedby-modified

And, so now that we are “Allowing Empty String”, I feel good.

Trial

Tried it out and here is where that got me…

GUI

couldnotresolveallowemptystringtoamodelitem

Textual

Failed to load model: Model Error: Could not resolve id ‘:@AllowEmptyString’ to a model item.

 

Solve the error message

Guide

The rest of the afternoon was spent googling for this incredibly useful error message

Failed to load model: Model Error: Could not resolve is ‘:@AllowEmptyString’ to a model item.

Best idea comes through Dave Baker and it is pasted here:

davebaker

 

Here are the steps:

  1. Launch your favorite editor
  2. Identify the lsml file
    • Syntax
      • [Project]\[Project].HTMLClient\Properties\<datasource>\[entity].lsml
    • Sample
      • EDiag\EDiag.HTMLClient\Properties\DBDiagData\listofContacts.lsml
  3. Comment out the DiscardFromCollection element

 

Guide

Faulty

listofcontacts-xml-20161114-0353pm

 

Revised

listofcontacts-xml-20161114-0353-bpm-repaired

 

Entity – properties – Default to single space

Guide

The alternate route is to revisit our entity and take the following steps:

  1. Supporting Work
    1. Unfortunately, Javascript does not provide a user’s name
    2. We have to get on the Server Side
    3. To get it on the Server side we have to tighten things up and require Windows or Forms Authentication
  2.  Entity
    • For the Entity provide code for setting the front-end default value
    • And, if need be the actual backend value

 

Project Properties

From the Solution Explorer, choose the Project, and right click on it

Default Screen

Here is the default setting

projectproperties-accesscontrol-20161114-0449pm

Explanation
  1. The default choice is not to enable authentication

 

Revised Screen

projectproperties-accesscontrol-20161114-0449pm-b

 

Explanation
  1. The Authentication Type is
    • Use Windows authentication
    • We have two choices
      • Allow only users and Active Directory security groups specified in the Users screen of the application
      • Allow any authenticated Windows user
    • We chose to “Allow any authenticated Windows user” as this is just a mock up

 

Entity

  1. Access the HTMLClient Tab
    • Choose “Write Code
    • For the Created Event
      • And, enter a code that supplies a place holder (space) for our property
  2. Access the Server Tab
    • Choose “Write Code
    • In the Inserting Event
      • Check if field is still at default, if so calculate value and overwrite default

HTMLClient

htmlclient-prepare

 

 

Code


/// <reference path="~/GeneratedArtifacts/viewModel.js" />

myapp.listofContact.created = function (entity) {
 // Write code here.

 entity.active = true;
 entity.addedOn = new Date();

 //Add a single space
 var STRING_SPACE = " ";
 entity.addedBy = STRING_SPACE;


};


 

Server

Entity – ListofContact

inserting-initiate-brushed-up

 

Code

        partial void listofContacts_Inserting(listofContact entity)
        {
            //when inserting, set added By to current windows user
            //If added By is still at default
            //entity.addedBy = entity.username;
            if (entity.addedBy == " ")
            {

                //If user is authenticated, then get username
                if (this.Application.User.IsAuthenticated)
                {

                    entity.addedBy = this.Application.User.Name;

                } // if (this.Application.User.IsAuthenticated)

            } // if (entity.addedBy == " ")

        }  // listofContacts_Inserting

 

 

LightSwitch – Application Hangs when exiting “Add/Edit Details Screen”

Background

Upon launching an Add/Edit Details Screen and clicking the Save or Discard button, the Application Hangs.

Reproduction Steps

AddEdit Screen / Before Changes

 

addeditservers-guid-20161022-1124pm

 

Add Edit Screen / Post Clicking on Save or Discard Button

Upon clicking the Discard button, the busy ( unfinished circle ) appears…

addeditservers-guid-20161022-1125pm

 

Banged Head

Really banged my head against the wall, it happened every time, I try the things listed below:

  1. Data Changed
    • Clicked Save or Discard button
  2. No Changes
    • Clicked Save or Discard button

Could not reproduce it on other screens and so sought to see what makes this screen unique.

 

Trouble Shooting

Minimal Table

Database

Created a new table with a couple of columns ( sequence, serverName, serverId).

Same problem.

 

Added candidate key

Database

Structure

Use SSMS Database Diagram, here is the original table’s structure…

databasediagram-listofservers

And, so our primary key is on the sequence column.  That column’s datatype is uniqueidentifier.

 

Index

Added Index

ALTER TABLE [dbo].[listofServers] 
	ADD  CONSTRAINT [constraintUniqueServerId]  
		UNIQUE
			(
				[serverID]
			)

Review Indexes

exec sp_helpindex '[dbo].[listofServers]'

 

index

Our unique indexes look like:

  1. PK_listofServers
    • sequence ( Datatype is uniqueIdentifier )
  2. IX_listofServers_ServerName
    • serverName ( Datatype is varchar )
  3. constraintUniqueServerId
    • serverId ( Datatype is int)

 

 

Visual Studio

Solution Explorer

In Solution Explorer, right click on the affecting Data Source and choose the “Update  Datasource” menu item

solutionexplorer-updatedatasource

Add Data Source Wizard

Within “Choose your Database Objects”, review the list of columns, the primary key, and candidate keys…

databaseobject-20161023-1204am

 

Explanation
  1. We see that the sequence column is registered as our Primary Key
  2. We see the other columns
  3. But, we do not see any special distinction for our candidate key column, the serverId column

Click the finish button to effect the DB Changes

 

Data Sources – Entity

Solution Explorer – listofServers.lsml

Within the Solution Explorer, select the entity, in this case listofServers.lsml, and double-click on your sslection.

entity-listofservers

 

Entity – listofServers.lsml

Pasted below are the column names, there datatypes, and required indicator.

Columns

Here are the columns, including the sequence column; marked as the Primary Key ( PK ).

entity-listofservers-columns

Column – serverId

The column, serverId, is listed.

Though in the database it is designed as a candidate key, it is marked any differently.

entity-listofservers-columns-page-2

Entity – listofServers.lsml – Property

Unfortunately, we are not able to manually set the Primary Key columns on the listofServers entity.

Entity – listofServers

entity-listofservers-properties

 

Entity – listofServers – Column – sequence

entity-listofservers-property-sequence

Entity – listofServers – Column – serverId

entity-listofservers-property-serverid

 

Summary

LightSwitch does not give us the ability to override the primary keys specified on the backend database.

 

 Create Tracking View

Let us create a tracking view over the table.  And, if we can designate a primary key on the view.

Database

View Design

Here is our view and we included all columns and we are have not included where nor grouping clauses.

dbo

Add Data Source Wizard

Within “Choose your Database Objects”, review the list of columns, the primary key, and candidate keys…

dbo

Explanation
  1. All not nullable columns are included in the list of primary key columns
  2. And, nullable columns are left out

Click the finish button to effect the DB Changes

 

Data Sources – Entity

Solution Explorer – v_listofServers_UI.lsml

Within the Solution Explorer, select the entity, in this case v_listofServers_UI.lsml, and double-click on your selection.

solutionexplorer-v_listofservers_ui-properties-1259pm

Explanation

The default setting is for Views to be marked Un-editable.

And, this is reflected via the “Is Editable” property to be off.

To designate them editable and to be able to set primary key columns on table, please check the “Is Editable” setting.

 

Solution Explorer – v_listofServers_UI.lsml

Navigate the list of columns for the entity and on each column that should be included in the primary key, please check the “Is Key” property.

entity_v_listofservers_column_serverid_v02

 

LightSwitch Backend

Reviewing the files that LightSwitch generates is also a good way to intimate oneself with the Application.

lsml files

What is lsml?

lsml stands for “LightSwitch Markup Language”.

Folder

For entities, the lsml files are placed in this folder

Naming Convention

<project.Server>\DataSources\<Data Source>

Sample

EDiag.Server\DataSources\DBDiagData

Files

Based on the entities we currently have defined, here are the our generated files

foldersandfiles

Sample Files

listofServers

listofservers_lsml

 

v_listofServers_UI

v_listofservers_ui_lsml

 

Tabulated

Entity
Key Column
Property Type
IsReadOnly Attributes
listofServers
 sequence
 :Guid Required
NotSearchable
v_listofServers_UI
 serverId
 :Int32  Yes  Hidden
Required
NotSearchable

 

 

Version

To pinpoint the version of LightSwitch where we experienced the problem, please use the Help\About menu.

Visual Studio – Version

version-14-0-25431-01-update3

Our Base Product & Version # is

Microsoft Visual Studio Community 2015
Version 14.0.25431.01 Update 3

And, for LightSwitch the Version # is

LightSwitch for Visual Studio 2015

Updates available?

To review the list of available updates, please click on the menu items “Tools“/”Extensions and Updates

Here are the Product Updates that are currently available…

productupdates-20161023-0159pm

As we installed the tools only this week, we do not appear terribly out of alignment in terms of patches.

 

Summary

So we experienced a small usability problem.

Will have to try to reproduce on other machines to determine if it in actual problem.

Also, the more we work with the tool, we hope to get a lot better at localizing problems.

LightSwitch – Setting default Values for DB Table Columns

Background

Evaluating Microsoft’s LightSwitch for a quick Data Entry Job.

This is my very first application and so it will be basic.

 

Need

Screen

Data Entry Screen

Initial

screen-20161022-1129am

 

Save

When we try to save, we get the error message pasted below:

It states “This field is required“.

screen-20161022-1130am-this-field-is-required

 

Resolution

Data Sources

Set Data Source elements data element fields values to the values you want them to be.

To do so please follows the steps outlined below:

  1. Access Data Source element
  2. Choose Data Object
  3. Access the Write Code menu
    • On the Server Tab
      • General Methods – …. Inserting
    • Or, On the HTMLClient Tab
      • General Methods – … Created

Server

_Created

Menu

datasource-server-writecode-generalmethods-created

 

Code

Here is the C# Code


using Microsoft.LightSwitch;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;

namespace LightSwitchApplication
{
    public partial class listofServersAlt
    {

        partial void listofServers_Inserting(listofServer entity)
        {

            const String guidEmpty = "00000000-0000-0000-0000-000000000000";

            String sequence = null;

            //get sequence as empty GUID
            sequence = guidEmpty;

            //get Sequence from entity sequence field
            if (entity.sequence != null)
            {
                sequence = entity.sequence.ToString();
            }

            //if sequence is empty, then set to new GUID
            if (guidEmpty.Equals(sequence))
            {
                //Guid.NewGuid Method ()
                //https://msdn.microsoft.com/en-us/library/system.guid.newguid(v=vs.110).aspx
                entity.sequence = System.Guid.NewGuid();

            } // if (guidEmpty.Equals(sequence))


        } // listofServers_Inserting

    }

}

 

_Created

Method

On the Data Source, access Write Code \ General Methods \ created

datasource-htmlclient-generalmethods-created-menu

Code

Here is the javascript Code



/// <reference path="~/GeneratedArtifacts/viewModel.js" />


/*
    a)  GUID: The GUID Generator
    http://guid.us/GUID/JavaScript

*/

function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function newGUID() {
    // then to call it, plus stitch in '4' in the third group
    guid = (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();

    return (guid);

}

function guidEmpty()
{
    var empty;
    
    empty = '00000000-0000-0000-0000-000000000000'

    return (empty);
}

myapp.listofServer.created = function (entity) {

    // Write code here.
    //entity.sequence = newGUID(); //System.Guid.NewGuid();

    entity.sequence = guidEmpty();
    entity.active = true;
    entity.iMonitorDatabaseBackup = true;
    entity.iMonitorServer = true;
    entity.iSupportsWinngmts = true;
    entity.passwordEncrypted = false;

    entity.dateCreated = new Date();

};

 

 

Validation

Let us go back and review the screen

screen-20161115-1055am-defaults-filled-with-zeroes

 

Explanation

  1. The sequence label is filled with a an empty GUID
  2. The date created filled is filled with current datetime
  3. And, the check-boxes are auto-filled as well

 

References

  1. Nicole Haugen
    • Microsoft – Developer Network
      • How To: Using the Created Method to Set Default Property Values
        Link
  2. Developer Networks
    • Getting Started with LightSwitch \ LightSwitch Guided Tour  \ Working with Data
      • Validating Data in a LightSwitch Application
        Link
    • Visual Studio 2015 > Visual Studio LightSwitch  > Data: The Information Behind Your Application
      • How to: Handle Data Events
        Link
  3. Tim Leung’s Blog
    • LightSwitch – In What Order do Screen Events Fire?
      Link
  4. Beth Massi
    • Beginning LightSwitch in VS 2013 Part 1: What’s in a Table? Describing Your Data
      Link
  5. Eric Erhardt
    • Updating Records in LightSwitch using Stored Procedures
      Link
  6. Gyan Sangrah
    • Default value in light switch 2011
      Link
  7.  GUID
    • GUID – The GUID Generator
      Link