How to list all entity names / table names from your Entity Framework model in Silverlight 4 and RIA services

If you want to list all entity names / table names from your Entity Framework model (*.edmx) in Silverlight 4, use a RIA Invoke operation:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Metadata.Edm;
using System.ServiceModel.DomainServices.Server;
namespace Research.Web
{
public partial class ResearchDomainService
{
/// <summary>
/// Get the entity names from the entity framework model on which this DomainService is generated.
/// </summary>
/// <returns>
/// A list of entity / table names
/// </returns>
[Invoke]
public List<string> GetEntityTypeNames()
{
EntityContainer container = ObjectContext.MetadataWorkspace.GetEntityContainer(ObjectContext.DefaultContainerName, DataSpace.CSpace);
List<string> result = (from meta in container.BaseEntitySets
where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet
select meta.ElementType.ToString()).ToList<string>();
return result;
}
}
}

If the database contains the following tables:

 

image

 

The list will contain the strings:

ResearchModel.Customer

ResearchModel.Person

ResearchModel.Product

ResearchModel.ProductTag

ResearchModel.Tag

Solving: Add and delete buttons on the DataForm are disabled when using an List<Entity> as ItemSoure

 

When you bind the DataForm.ItemSource directly to an entity set returned from your RIA DomainService, the DataForm add and delete buttons are disabled. This is caused by the implementation in RIA Services of the entity sets. If you use an ObserverableCollection the buttons are enabled, found mine solution at: http://forums.silverlight.net/t/190405.aspx/1

Solving: DisplayName not showing in a DataForm in Silverlight 4 by using data annotations on a metadata class.

I was trying to change the displayname of a field in a dataform by placing the DisplayName attribute on the property in the metadata class. This will not work instead you must use the [Display(Name= "This is the correct display name")] attribute on the field in a metadata class:

[MetadataTypeAttribute(typeof(Product.ProductMetadata))]
public partial class Product
{
internal sealed class ProductMetadata
{
// Metadata classes are not meant to be instantiated.
private ProductMetadata()
{
}
public int Id { get; set; }
[Display(Name = "First Name", Description = "Employee's first name")] //Correct !
//[DisplayName("First name 2")] // Wrong!
public string Name { get; set; }
public EntityCollection<ProductTag> ProductTag { get; set; }
}
}

Solving: The attachable property ‘Behaviors’ was not found in type ‘Interaction’

 

I was getting the error: The attachable property ‘Behaviors’ was not found in type ‘Interaction’.

This was generated by a missing reference to the "System.Windows.Interactivity" assembly.

 

You can download the assembly at http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=3062

It is contained in the BlendSLSDK_en.msi

You can extract the msi package without installing it, by using msiexec.

 

Just place the *.msi in C:\Temp and run:

msiexec /a C:\Temp\BlendSLSDK_en.msi TARGETDIR="C:\Temp\Blend" /qn

How to run and debug silverlight unittests inside Microsoft Visual Studio 2010

The Microsoft Test project template in Microsoft Visual Studio 2010 does not support adding a reference to a Silverlight class library. To unittest a function in a Silverlight class library you can follow the steps below:

 

– Install the Microsoft Silverlight Toolkit April 2010 (http://silverlight.codeplex.com/releases/view/43528)

– After installing the Microsoft Silverlight Toolkit April 2010, you can find a [Silverlight Unit Test Application] project template, under Installed Templates > Visual C# > Silverlight in the Add New Project wizard in Microsoft Visual Studio 2010.

image

 

– This will add 2 projects to your solution, a [test project] and a [test application] to run the Silverlight unittests in the browser.

– Add a reference in the [test project] to the Silverlight class library to test.

– Now you can run the unittest in a browser by starting the [test application]:

image

 

 

If you don’t want to run the silverlight unittests in the browser, but directly in Microsoft Visual Studio 2010, like normal unittests, follow the steps below:

 

– Install Jetbrains resharper

– Download the JetBrains Resharper plugin agunit [http://agunit.codeplex.com/]

– Create the folder [C:\Program Files (x86)\JetBrains\ReSharper\v6.0\Bin\Plugins\AgUnit] if it does not exist.

– Extract the agunit zip and add the contents to the folder: [C:\Program Files (x86)\JetBrains\ReSharper\v6.0\Bin\Plugins\AgUnit].

– Open your solution containing the Silverlight test project in Microsoft Visual Studio 2010 and click on the green circle next to your silverlight unittest:

 

image

 

You can now run your Silverlight unittest directly from Microsoft Visual Studio 2010

 

You can add only a Silverlight [test project], without the [test application] to a solution by unchecking the [Host the Silverlight application in a new or existing Web site in the solution] checkbox:

image

How to resolve: ListBox UI does not update (refresh) on WCF .NET Ria Services domaincontext async call in Silverlight 3

When you are calling a function on a WCF .NET RIA service, the completed eventhandler will take you back to the UI thread, but if you are binding the ListBox to a List<….> the UI of the Listbox won’t be updated.

Solution: don’t use a List<…> as ItemSource but a System.Collections.ObjectModel.ObservableCollection<…>

How to sett the RootVisual multiple times from code in Silverlight 3

MSDN explains the RootVisual can only be set one time from code:

You can set the value of the RootVisual property only one time from code, although you get its value any number of times.
http://msdn.microsoft.com/en-us/library/system.windows.application.rootvisual(VS.95).aspx

But we can set it to a UserControl that can switch it’s own content, as explained in the blog post:

http://craign.net/2008/03/11/how-to-switch-silverlight-usercontrols/

 

I used this procedure to start with a progressIndicator and after authenticating the user and loading the user properties, showing the masterpage.

Get the DomainService (LINQ to SQL) to load child entities with .NET RIA Services in Silverlight 3

If you have a table with related tables then you can get the child entries by editing the DomainService and the metadata:
Add the include attribute ([Include()]) to the property containing the child table reference and use the DataLoadOptions to specify the child tables to include in the query result view.

In this case a Task table contains a reference to a Project table and the Project table contains a reference to the Customer table:

 

The domainservice class TTSDomainService

// TODO: Consider
// 1. Adding parameters to this method and constraining returned results, and/or
// 2. Adding query methods taking different parameters.
public IQueryable<Task> GetTasks()
{
// Define the child entries to get 
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Task>(t => t.Project);
options.LoadWith<Project>(p => p.Customer);
this.DataContext.LoadOptions = options;
// Get the tasks ordered by customer, project, task
return from t in this.DataContext.Tasks
orderby t.Project.Customer.Name, t.Project.Name, t.Name
select t;
}

 

The domainservice meta data class: TTSDomainService.metadata.cs

 

// The MetadataTypeAttribute identifies TaskMetadata as the class
// that carries additional metadata for the Task class.
[MetadataTypeAttribute(typeof(Task.TaskMetadata))]
public partial class Task
{
// This class allows you to attach custom attributes to properties
// of the Task class.
//
// For example, the following marks the Xyz property as a
// required field and specifies the format for valid values:
//    [Required]
//    [RegularExpression("[A-Z][A-Za-z0-9]*")]
//    [StringLength(32)]
//    public string Xyz;
internal sealed class TaskMetadata
{
// Metadata classes are not meant to be instantiated.
private TaskMetadata()
{
}
public Nullable<int> CategoryAbbrID;
public int CategoryID;
public Nullable<decimal> EstDuration;
public Nullable<int> HourType;
public string Name;
     [Include()]
        public Project Project;
public int ProjectID;
public EntitySet<TaskTimeSpan> TaskTimeSpans;
}
}

 

See:

http://chriswalshie.wordpress.com/2009/08/11/masterdetail-binding-with-net-ria-services-and-the-agdatagrid/

Entities not loaded after domainContext.Load(domainContext.GetUsers) in WCF RIA service

If you use LINQ to SQL and you’re entities are not loaded after you call a GetQuery on the DomainContext, you probably did not use a callback.

TTSDomainContext context = new TTSDomainContext();
LoadOperation op = context.Load(
context.GetTasksQuery(),
result =>
{
if (!result.HasError)
{
//At this point the entities are loaded
       }
},null);