Category Archives: LightSwitch

How to disable Save button in LightSwitch screen based on role

There could be time, that your customer, or user can have quite logical requirement :

Please, disable Save button on whole screen according to role. You as dev will say OK, why not. Then you will come to Lightswitch IDE , right click Save button to create Can Run event handler and you will see (screaming, swearing / insert appropriate) something like this :

save button context menu lightswitch

All custom added buttons have also Can Execute option, but not out of box (save, refresh) buttons.

First thing – please consider also rights on datasource. I mean


partial void SaveChanges_CanExecute(ref bool result)

on each datasource.

This is where you should check rights and say no to user in case you don’t want him to save changes. But this will not make Save button disable him self automatically. It will only display note to user, he can’t save what he changed. It’s also server side check and thus little more safer (no more client side hacks).

This is how whole app will look when you have check on model :

datasource check

But how to say disable to Save button in code?

For example like this :


public partial class EditableUsersGrid
{
partial void EditableUsersGrid_InitializeDataWorkspace(List<IDataService> saveChangesTo)
{
if (!this.Application.User.HasPermission(Permissions.CanSaveUsers))
{
saveChangesTo.Clear();
}
}
}

I’m checking for a permission and then I’m clearing collection of datasources for this particular screen. I had this idea, because I was dealing with problem of two datasources on one screen and InitializeDataWorkspace is the event where you can add another datasources needed. So why not to try clear them out? 🙂

This is the result : disabled Save button :

screen check

As always here is the demo app to play with and feel free to ask if you have any questions :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1801&parid=78A5783DE37D2EBE!1779

How to avoid problem with Auto Complete Box not saving selected values in Lightswitch

At first, I would say that behavior of LightSwitch I will show you today is a bug. I haven’t investigated that much about it in Microsoft Connect. It happens in one edge case I will describe today.

Say we have data model like this :

data model lightswitch

We have entity that has reference to another entity. Employee has reference to Status. This second Status table has set for some business requirement that his Summary property must be set to value that can repeat. I know this makes it hard to tell which value from all possible was picked, but say it is so. Another reason is that summary property is displayed as selected value in grid.

OK, so far so good. Here comes trouble.

auto complete box lightswitch problem

This is, how the screen would look like. If we select first 1200 and save it, data would be saved correctly. But if I would select second 1200, update to database will be triggered with ID of first (I know that, because I spent some time with investigating on this error and first thing that came to my mind – it’s not you code, debug the result, SQL 🙂 ). From my experience, when you have multiple same values, the first from top will be selected (like if you would search a list and take first one) and this value will be used to update record.

OK, what we can do about it.

There are two possibilities :

  • Choose some unique value column as Summary Property of your entity (but you should be damn sure there will be no duplicates, maybe you could put a unique constraint on that column in DB or so, because some user can put same value there),
  • Create a computed column that will be unique (I’m creating it from two other columns), like I did here

entity with computed column lightswitch

You have to also set it as Summary Property.

Then UI could look like this :

ui with auto complete box for computed column lightswitch

With this approach Lightswitch app will work as expected. Hopefully. 🙂

As always, both solutions to elaborate on can be downloaded here :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1788&parid=78A5783DE37D2EBE!1779 and look for AutoCompleteProblem.zip 66MB file.

How to pre populate and post populate some data for new item in AddAndEditNew or other events in LightSwitch screen

This week I had to deal with requirement from customer, that I wasn’t able to find somewhere on web, so I will try to share my small solution with you. 🙂

So, what was this problem?

Really common user request is : Please, prefill some data when adding new item in the grid. It’s quite logic to prefill some values when you know which value should be there to either help user to not search in items, or you don’t want user to be able to change values when inserting. That could be date (yes , this could be easily done in DB), but this applies more to some business objects like you boss or so on related to record you are creating.

At first, I would like to point you to resources that are creating also own popup window :

http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/33/LightSwitch-ndash-Modal-Add-and-Edit-Windows.aspx

or

http://blogs.msdn.com/b/lightswitch/archive/2011/07/07/creating-a-custom-add-or-edit-dialog.aspx

or

http://code.msdn.microsoft.com/silverlight/Managing-Custom-AddEdit-ab1c6b58

OK, but what if I’m quite satisfied and don’t want whole custom window, just to prefill / modify / tweak new item and fire up the out of box generated window?

So here is how :

On each screen you have these Add… , Edit… and Delete buttons.

add edit delete buttons lightswitchb screen

They are the key. Please note that when you want to add new buttons, you can have more of them :

add edit delete buttons lightswitch screen more buttons

And please note those names : AddAndEditNew, AddNew, EditSelected etc…

When you right click on these buttons you can override code in them, this is the point where we could modify record in code. OK, but handler code is blank and thus app will not do anything when clicked. So what we need to fire, to have things behaving like out of box? Quite easy, fire up method that have name like button on datasource, that you have on your screen. Like this (note that you don’t have to implement all these event’s, just those that you need to override and put your logic there, they are just sample for datasource method names) :

namespace LightSwitchApplication
{
public partial class EditableEmployeesGrid1
{
partial void gridAddAndEditNew_CanExecute(ref bool result)
{
// Write your code here.

}

partial void gridEditSelected_CanExecute(ref bool result)
{
// Write your code here.

}

partial void gridDeleteSelected_CanExecute(ref bool result)
{
// Write your code here.

}

partial void gridAddAndEditNew_Execute()
{
this.Employees.AddAndEditNew();
}

partial void gridEditSelected_Execute()
{
this.Employees.EditSelected();
}

partial void gridDeleteSelected_Execute()
{
this.Employees.DeleteSelected();
}
}
}

Please note, that CanExecute hanslers are auto generated also.

OK, so now we have code that was generated out of box, nice 🙂

But with this snippet :

Private Sub gridAddAndEditNew_Execute()

Dim newCustomer As Customer = Me.Customers.AddNew()

Me.Customers.SelectedItem = newCustomer

Me.OpenModalWindow("CustomerEditDialog")

End Sub

From aforementioned article (I mean this one : http://blogs.msdn.com/b/lightswitch/archive/2011/07/07/creating-a-custom-add-or-edit-dialog.aspx) we are able to do this :


partial void gridAddAndEditNew_Execute()
 {
 this.Employees.AddAndEditNew(e => { e.Surname += " some other surname text"; e.Name += " something added here..."; });
 }

partial void gridAddNew_Execute()
 {
 var emp = this.Employees.AddNew();
 emp.Name = "name";
 emp.Surname = "surname";
 this.Employees.SelectedItem = emp;
 this.Employees.EditSelected();
 }

As you can see I implemented two methods : AddAndEditNew and AddNew. Difference is, that :

AddAndEditNew will make work for you with creating new item and add it to selected item, but only one. And will also delete that item when you click on cancel on popup that will open. Also you can specify to post tweak your data only in anonymous lambda method, not to prefill it. When you are happy with that, use this one. You can access all fields of item, also those that you hide from user.

With AddNew you have to create new item and here you can prefill it and then manually open popup over selected item. New item fill be prefilled and user can modify fields. You could also create bulk of new items like this :


partial void AddMoreItemsMethod_Execute()
 {
 var itemsFromSomewhere = new List();

itemsFromSomewhere.Add(new Employee { Name = "name 1", Surname = "surname 1" });
 itemsFromSomewhere.Add(new Employee { Name = "name 2", Surname = "surname 2" });
 itemsFromSomewhere.Add(new Employee { Name = "name 3", Surname = "surname 3" });
 itemsFromSomewhere.Add(new Employee { Name = "name 4", Surname = "surname 4" });

foreach (var item in itemsFromSomewhere)
 {
 this.Employees.SelectedItem = item;
 }

this.Employees.EditSelected();
 }

Obviously, EditSelected will open popup only over last inserted item. But certainly, you can do this as well.

Please also note that with case where you disable Delete button on grid (in case customer want’s no delete workflow, you will have a problem, because you can’t delete new object/objects in SelectedItem collection and Save action on whole datasource will trigger insert to DB. With AddAndEditNew when user clicks on cancel, it will remove this new item from grid, but with AddNew you have a problem, new item stays.

 

So this is basically everything I found out. I hope this will be helpful. 🙂

Whole application to play with you can find here :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1787&parid=78A5783DE37D2EBE!1779

and look for file NewItemPrepopulateLightswitch.zip

Microsoft Lightswitch grid controls – Modal Window picker, Auto Complete Box and small tweaks

LightSwitch is quite flexible when it comes to displaying data in grid. You can even use your own custom Silverlight controls, that you can build according to some rules, but when you need it, it’s there. Nice to feature, when all out-of-possibilities fail.

In this small post I will try to elaborate on built in controls and how to tweak them.

I will start with small sample project, that you can download if you want to dig deeper on you own pc.

Some good old grid in Lightswitch can look like this :

lightswitch grid in editor

Here you can see some sample data. Every node in Data Grid Row means it will be 1 row in a grid. You see icon and then name of each property like Name, Surname, etc. With small dropdown you can select type of control Lightswitch will use when displayed so for example when you need to display something read only, then you can select to display label.

lightswitch grid types of controls

Types that will Lightswitch display are dependent on type of property. When you have DateTime property, you will have more choices :

lightswitch grid types of controls datetime

When you need some column as read only you can use Date Time Viewer in this case.

OK, now comes the tweaking.

When you reference another table, then your screen can look like this :

lightswitch grid in editor another table reference

This is the default, but you can change it. Choosing type next to Country (in this case of course) will result in what you see when you see just grid. In this default case it will look like this :

lightswitch grid in editor default combo

But maybe you want to display a grid in cell of this main grid. OK, just change default to columns layout and you will have this :

lightswitch grid columns in grid

Your users like rows better? OK, here you go :

lightswitch grid rows in grid

Say you want a quite requested feature : you need combo box, but when you click on it, you need grid. OK, here we go :

Set country type to Auto Complete Box but change also underlying type to grid. The way it works in Lightswitch is that you can control what to see in grid by changing node on Data Grid Row level, but change in underlying level will change what you see once you click on down arrow of Auto Complete box. And this can be also table layout. This is how it looks like in editor :

lightswitch grid in editor combo with grid

This at runtime :

lightswitch grid in editor combo with grid runtime

OK, now to another common task with this grid, that will also affect something else. Say you want to display not Slovakia or Czech republic in the grid for selected item, but something else. How to set it? Well, “use the force Luke” :), but we will use model. Lightswitch is written so, it will mind order of properties when we created model. This order is preserved in auto generated window for adding, editing and removing items but also it will take first property and show it here. So once we change model (I moved Currenty to top) like this :

lightswitch model change

It will change also this :

lightswitch grid another property autocomplete

and this :

lightswitch add new country popup

So please be aware of that.

Last things that I would like to show you are modal windows.

Say you need a picker to choose from some another grid, you you can user a Modal Window Picker and in the picker you can have a grid (table layout) and it will look like this ion grid :

lightswitch picker in grid

and with open popup :

lightswitch picker popup

Or just plain old button that will open window properties of current record we want to edit in different controls. Picture text box with very long text. You can add button behind this column to open popup window that will have only one textbox, but that will be multiline and that will enable users to edit this long text more user friendly.

If you have any questions, feel free to ask, or mail me.

Solution can be downloaded here :

https://skydrive.live.com/redir.aspx?cid=78a5783de37d2ebe&resid=78A5783DE37D2EBE!1786&parid=78A5783DE37D2EBE!1779&authkey=!AE2rYVVr0I8FBww and look for ComboApplication.zip file.

Enjoy.

Don’t forget to build LightSwitch apps with Release configuration for customer

Today I learned small thing about deploying LightSwitch apps. Don’t forget to publish for customer with Release set on, because it seems that LighSwitch will publish also code that will show button Design Screen intended for developers to rearrange UI when debugging. This button will be available for everyone on deployed application. So app will look like this on every machine installed, and that isn’t the intention. 🙂

lightswitch design screen button

Handling many to many (n to m) relationships in Microsoft LightSwitch

Many to Many (or n to m) relationships in real world scenarios are quite common. Unfortunately this cardinality LightSwitch doesn’t handle out of box (maybe in next version we will see). But this task can be done. With help of WCF RIA Services. And resources around the internet, like this one.

Firt of all , reasons I decided to write this post are :

  • I was able to (at least I think :)) write code in RIA Services little better (not everything in one .cs file), than it is in samples I found,
  • There are some tweaks in UI that I would recommend you to do (but are not required)

I incorporated my solution to project I’m still working on so it should work as expected (customer will let us know for sure, if not :)).

Links to other blogs I found :

http://blogs.msdn.com/b/lightswitch/archive/2010/12/16/how-to-create-a-many-to-many-relationship-andy-kung.aspx – oldest one, but I didn’t like the UI,

http://www.paulspatterson.com/technology/lightswitch/microsoft-lightswitch-many-to-many-relationships/ – didn’t tried this one,

http://powerbala.com/2011/04/10/many-to-many-control-for-microsoft-lightswitch/ – I started with this one, because I like the way it’s using checkboxes. (you could start with this one and then return to this post, but you don’t have to).

http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/34/Creating-a-Simple-LightSwitch-RIA-Service-using-POCO.aspx – this page isn’t about n to n , but it’s about creating WCF RIA Service library in your LightSwitch project and I would say this is the correct approach. You just need to create Class library, create POCO class and Domain Service Class and reference some WCF RIA Services libraries and you are ready to go. Inserting WCF RIA Services Class library project into LightSwitch solution will also add Web project that isn’t really used anywhere.

So, first thing we need is database with appropriate tables.

In my example I will use these tables :

bike user and junction table

Bike and User have PK column (Primary Key) of type Int and with Is Identity set to true, so it will auto increment on each insert. Same way as LightSwitch. Junction table is table that will say to which Bike we want a User. Each row in this table means one connection between particular User and Bike. Both rows are composite PK so they are unique. We will access this table from WCF RIA Services class library code.

Because I created these tables in SQLExpress, now I need to connect to them in LightSwitch. Click on Attach to external Data Source in VS 2010 LightSwitch welcome screen (Note : LightSwitch maintains it’s own database in \Bin\Data\Temp subfolder of solution. This is the place where all tables are create, when you design them via VS 2010 interface and where all tables for ASP.NET membership are stored. If we would create all these ) :

lightswitch attach to external data source

Choose database and click next, input name of sql server and database name (in my case like this)

lightswitch connecting database

Select one entity (in my case Users) and then you can see something like this in Solution Explorer :

lightswitch data sources

Then add new Class library to whole solution (I was able to do that from Solution Navigator pane) and name it as you like.

Add

I found out, that if you want to structure your class library to have overview over multiple classes, it would be better to :

  • Create folder per every item you want to access from WCF RIA Services. With item currently I mean junction table,
  • Create class for POCO object,
  • Create DAL (Data Access Layer) class that would use POCO Class and handle CRUD in datasource you like (you are accessing, in this case SQL Server Express), you could also create interface that this class will derive from and use it for testing, or perhaps use some DI,
  • Create class that will derive from DomainService and expose all actions per item to LightSwitch – WCF RIA Services Domain Service Class (with adding DomainContext class to the project you also add required references to your .csproj. but we also need to add System.Web and System.Configuration, I will tell you why later)

OK, so now in new Class Library project create a subfolder. I created BikeUser subfolder for this case.

We will follow this article : http://powerbala.com/2011/04/10/many-to-many-control-for-microsoft-lightswitch/ and create class with these properties :

Two properties of type int for both columns in BikeUserJunction table. (BikeFK and UserFK both decorated with [Key] attribute), some usefull name to identify Bike, so we can name it BikeName and IsSelected boolean prop.

And of course one static method to create instance of this object. Code could look like this :


namespace WCFRIAServicesClassLibrary.BikeUser
 {
 using System.ComponentModel.DataAnnotations;
 using System.Data;

public class BikeUserPoco
 {
 [Key]
 public int BikeFK { get; set; }

[Key]
 public int UserFK { get; set; }

public string BikeName { get; set; }

public bool IsSelected { get; set; }

public static BikeUserPoco CreateNew(IDataRecord iDR)
 {
 return new BikeUserPoco
 {
 TermsCategoriesID = (int)iDR["BikeFK"],
 TermsConditionsID = (int)iDR["UserFK"],
 TermCategory = (string)iDR["BikeName"],
 IsSelected = (bool)iDR["IsSelected"]
 };
 }
 }
 }

Then we need DAL Class that could look like this :


namespace WCFRIAServicesClassLibrary.BikeUser
 {
 using System.Collections.Generic;
 using System.Data;
 using System.Data.SqlClient;

/// <summary>
 /// Data Accesss Class. This class will be called by DomainService class.
 /// </summary>
 internal class BikeUserDAL
 {
 /// <summary>
 /// Selects the bike user records from db.
 /// </summary>
 /// <param name="UserFK">The user FK.</param>
 /// <param name="ConnectionString">The connection string.</param>
 /// <returns></returns>
 public static IEnumerable<BikeUserPoco> SelectBikeUser(int? UserFK, string ConnectionString)
 {
 var sComm = new SqlCommand { CommandType = CommandType.Text };
 sComm.Parameters.AddWithValue("UserFK", UserFK);

sComm.CommandText = @"SELECT b.BikeID AS BikeID, @UserFK AS UserFK, b.BikeName AS BikeName,
 CASE WHEN
 j.UserFK IS NULL
 THEN
 CAST (0 AS BIT)
 ELSE
 CAST (1 AS BIT)
 END AS IsSelected
 FROM
 Bike AS b LEFT OUTER JOIN
 BikeUserJunction AS j ON
 b.BikeID = j.BikeFK AND
 j.UserFK = @UserFK;";

using (var sConn = new SqlConnection(ConnectionString))
 {
 sComm.Connection = sConn;
 sConn.Open();

SqlDataReader sDataReader = sComm.ExecuteReader();
 if (sDataReader.HasRows)
 while (sDataReader.Read())
 yield return BikeUserPoco.CreateNew(sDataReader);
 sConn.Close();
 }
 }

/// <summary>
 /// Inserts the bike user records from db.
 /// </summary>
 /// <param name="UserFK">The user FK.</param>
 /// <param name="BikeFK">The bike FK.</param>
 /// <param name="ConnectionString">The connection string.</param>
 public static void InsertBikeUser(int UserFK, int BikeFK, string ConnectionString)
 {
 var sComm = new SqlCommand { CommandType = CommandType.Text };
 sComm.Parameters.AddWithValue("UserFK", UserFK);
 sComm.Parameters.AddWithValue("BikeFK", BikeFK);

sComm.CommandText = @"INSERT INTO BikeUserJunction (UserFK, BikeFK) VALUES (@UserFK, @BikeFK)";

using (var sConn = new SqlConnection(ConnectionString))
 {
 sComm.Connection = sConn;
 sConn.Open();
 sComm.ExecuteNonQuery();
 sConn.Close();
 }
 }

/// <summary>
 /// Deletes the bike user records from db.
 /// </summary>
 /// <param name="UserFK">The user FK.</param>
 /// <param name="BikeFK">The bike FK.</param>
 /// <param name="ConnectionString">The connection string.</param>
 public static void DeleteBikeUser(int UserFK, int BikeFK, string ConnectionString)
 {
 var sComm = new SqlCommand { CommandType = CommandType.Text };
 sComm.Parameters.AddWithValue("UserFK", UserFK);
 sComm.Parameters.AddWithValue("BikeFK", BikeFK);

sComm.CommandText = @"DELETE BikeUserJunction WHERE UserFK = @UserFK AND BikeFK = @BikeFK";

using (var sConn = new SqlConnection(ConnectionString))
 {
 sComm.Connection = sConn;
 sConn.Open();
 sComm.ExecuteNonQuery();
 sConn.Close();
 }
 }
 }
 }

And last one : DomainService (uncheck Enable Client Access when inserting this class) that could look like this :

namespace WCFRIAServicesClassLibrary
 {
 using System;
 using System.Collections.Generic;
 using System.ServiceModel.DomainServices.Server;
 using System.Web.Configuration;

// TODO: Create methods containing your application logic.
 // TODO: add the EnableClientAccessAttribute to this class to expose this DomainService to clients.
 public class CommonDomainService : DomainService
 {
 #region initialization of connection string

/// <summary>
 /// Initializes this <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/>. <see cref="M:System.ServiceModel.DomainServices.Server.DomainService.Initialize(System.ServiceModel.DomainServices.Server.DomainServiceContext)"/> must be called
 /// prior to invoking any operations on the <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/> instance.
 /// </summary>
 /// <param name="context">The <see cref="T:System.ServiceModel.DomainServices.Server.DomainServiceContext"/> for this <see cref="T:System.ServiceModel.DomainServices.Server.DomainService"/>
 /// instance. Overrides must call the base method.</param>
 public override void Initialize(DomainServiceContext context)
 {
 if ((WebConfigurationManager.ConnectionStrings
 [(this.GetType().FullName)] == null) ||
 string.IsNullOrWhiteSpace(WebConfigurationManager.ConnectionStrings
 [GetType().FullName].ConnectionString))
 {
 /*_connectionString = "data source=NorthwindDB;initial catalog= " +
 "Northwind;user id=myID;password=myPassword";*/
 throw new Exception("Can't load connection string for WCF RIA service data source");
 }
 else
 {
 ConnectionString = WebConfigurationManager.ConnectionStrings
 [GetType().FullName].ConnectionString;
 }

base.Initialize(context);
 }

/// <summary>
 /// Private property for current connection string.
 /// </summary>
 /// <value>
 /// The connection string.
 /// </value>
 private string ConnectionString { get; set; }

#endregion initialization of connection string

#region BikeUser

//All this code will be called directly by LightSwitch
 //Fake Function to satisfy WCF RIA requirement
 //without this query LS will not accept this library
 //in NtoN scenario wi will not use this query, its used when whole page is loaded.
 [Query(IsDefault = true)]
 public IEnumerable<BikeUser.BikeUserPoco> SelectFakeBikeUser()
 {
 return BikeUser.BikeUserDAL.SelectBikeUser(-1, ConnectionString);
 }

[Query]
 public IEnumerable<BikeUser.BikeUserPoco> SelectBikeUser(int? UserFK)
 {
 return BikeUser.BikeUserDAL.SelectBikeUser(UserFK, ConnectionString);
 }

[Insert]
 public void CreateBikeUser(BikeUser.BikeUserPoco bup)
 {
 BikeUser.BikeUserDAL.InsertBikeUser(bup.UserFK, bup.BikeFK, ConnectionString);
 }

[Update]
 public void UpdateBikeUser(BikeUser.BikeUserPoco bup)
 {
 if (bup.IsSelected)
 CreateBikeUser(bup);
 else
 DeleteBikeUser(bup);
 }

[Delete]
 public void DeleteBikeUser(BikeUser.BikeUserPoco bup)
 {
 BikeUser.BikeUserDAL.DeleteBikeUser(bup.UserFK, bup.BikeFK, ConnectionString);
 }

#endregion BikeUser
 }
 }

Remember when I told you to add two more references? These assemblies are needed to access connection string from database via WebConfigurationManager.ConnectionStrings classes. Of course there is also another way to access Connection strings from .config files, choose what you like. I chose this approach.

After this, WCF RIA Services class for our LightSwitch app to consume should be ready.

Just a short look at all my references :

lightswitch wcf ria services project references

OK, if you are able to build the project, you can reference it in LightSwitch.

Right click on Data Sources node, choose WCF RIA Services, click  Next and you should be able to Add Reference. If Choose or CommonDomainService class and click Next :

lightswitch add wcf ria services class

Then you will see window like this :

lightswith wcf ria service select datasource objects

This is the place where we can set connection string which will use our code to access data in WCF RIA Services Domain Service. Connections string will be pulled from web.config that will be deployed with published solution. It can look like this :

Data Source=.\SQLEXPRESS;Initial Catalog=LSnton;Integrated Security=True

But please be aware, that this will connect to DB with credentials of user that is running the application and therefore you should user SQL Server authentication.

Connection string is read on overriden Initialize method of Domain Service and as key LightSwitch is using the type of class (GetType().FullName property).

I found this out from MSDN documentation here :

http://msdn.microsoft.com/en-us/library/gg589479.aspx – Guidelines for Creating WCF RIA Services for LightSwitch (btw good read)

Now to the UI:

Add new screen like this (Editable grid screen):

lightswitch add new screen

Switch to columns layout. Add new data item and select Query and choose SelectBikeUser with return type of set of BikeUserPoco.

lightswitch add new data item

Now connect UserFK query parameter of SelectBikeUser query with Users query by clicking on UserFK and then on right side textbox ParameterBinding and VS 2010 UI will display possible values. In this case it will be Users.SelectedItem.UserID.

After connection you will see line pointing to UserID in Users query. Like so :

lightswitch n to n datasources

On this picture you can also see that there is only Is Selected and Bike Name in Select User Poco grid. I also recommend you to delete all commands from this data grid from command bar and also disable Show Add-new row checkbox, since its not needed.

After all this you should be able to see window like this one :

lightswitch n to n ui

You can find DB you need and whole sample app packaged on this link (LightSwitch_n_to_n.zip file) :

https://skydrive.live.com/?sc=documents&cid=78a5783de37d2ebe#cid=78A5783DE37D2EBE&id=78A5783DE37D2EBE%211779&sc=documents

You just need to have SQL Server Express installed and mount files in dbs folder and then open project with VS2010 with LightSwitch installed.

In case I missed some step or you need help, just mail me od write in the discussion or consult the original powerbala article. I know I have made just tiny changes to the original, but I hope they will make a change.

Enjoy 🙂

How to create resizable columns and rows in LightSwitch UI

With smaller screen resolution (or with requirement for bigger grids) comes possibility to create slide-able columns or rows in UI very handy. And in LightSwitch it’s possible with few clicks on checkboxes. 🙂 I will show you how in this small example.

I will demonstrate this possibility on simple app where I created User and Car entities with cardinality 1 : N. One User can have multiple Cars assigned. There are many ways how to show UI for this task and one is to have 2 columns. First for User, second for Cars.

In LightSwitch you can create this with simple Columns layout what will have 2 DataGrids. One for Users, second for Cars for selected user. Then in VS 2010 you select first column or row and in properties you can see in the bottom checkbox for Is Column Resizable.

Check it for first column. Because I have only two columns, second will be resizable also. Neat thing is, that you can specify width of column by setting number in Weighted Column Width textbox. This will set column width on startup.

Here is the outcome of Columns UI:

If you are using Rows Layout, same applies for rows. In VS you will find Is Row Resizable checkbox at the botoom,but on right side.

 

As I said, it’s that easy 🙂 In case you want to see this in action, here is link to this small sample app.

https://skydrive.live.com/?cid=78a5783de37d2ebe&id=78A5783DE37D2EBE!1779# and look for ResizableApplication.zip file.

 

Enjoy.

Microsoft LightSwitch – Application failed to load, GetAuthenticationInfo query failed

While debugging of LightSwitch apps I get from time to time strange note about failed query that is in the plumbing of every LighSwitch app. App will hang with note in the middle of screen like this :

Only thing that you can do as developer is : Build > Clean Solution and re-run app. Or just re-run it, but then it may hang like this  :

 

Really strange behavior. Anyway clean works so happy debugging 🙂

 

Adding custom entity validation to LightSwitch

Adding custom validation is quite easy task, but currently Microsoft has problem with not updated MSDN article http://msdn.microsoft.com/en-us/library/ff852045.aspx. I just would like to tell you that code snippet on this MSDN page is not working.

This is correct snippet (this code is placed in SomeEntity_Validate event on server) :

if (entity.SomeBoolProperty == true)
{
results.AddPropertyError(“Text with error for user.”, entity.Details.Properties.SomePropertyToBindErrorTo);
results.AddEntityError(“Text with error for whole property”);
}

 

This way you will see error generated from first row of code as your custom error text from first parameter followed by property name. Second row will generate error with name of property followed by your custom text. Errors could look like this :

possible validation messages lightswitch

 

Please note that this code is fired on server and thus you need to create roundtrip (error will show up when Save was pressed, not on client when filling properties like required fields and so on).