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: "Could not activate cellular data network" on a Vodafone iPhone 4 after iOS 5 upgrade.

After updating mine Vodafone iPhone 4 to iOS 5, all was working well, except no data connection.

Error: Could not activate cellular data network. You are not subscribed to a cellular data service.

I found mine solution at: http://www.iphoneclub.nl/iphone-tips/telefoonfuncties/probleem-met-mobiele-datanetwerk-oplossen/

 

Personal Hotspot

One very nice thing about the iOS 5 update, is the return of Personal Hotspot. On my iOS 4.3.3 update the menu item Personal Hotspot disappeared, now it’s back, so I can share mine internet connection on my iPhone with other devices.

Resolving: Validator.TryValidateObject always returns true in a UnitTest, when using a MetadataType class in Entity Framework 4

When you use a metadata class in Entity Framework the registration between the entity and the metadata class is not registered for all Microsoft Visual Studio Project types (the "test project class library" for example).

I found the solution at: http://stackoverflow.com/questions/2657358/net-4-rtm-metadatatype-attribute-ignored-when-using-validator. It demonstrates registring all metadata classes in an assembly.

 

Solution

Add the following class, to the assembly that contains the Entity Framework model (*.edmx) and the metadata classes:

using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
/// <summary>
/// Metadata classes are not always automatically registered, for example in a UnitTest classlibrary.
/// This class can be used to register all metadata classes find in this assembly.
/// 
/// Registration will only be done once.
/// </summary>
public static class MetadataTypesRegister
{
private static bool _installed = false;
private static readonly object InstalledLock = new object();
/// <summary>
/// Register all metadata classes found in this assembly.
/// Registration will only be done once.        
/// </summary>
public static void InstallForAssembly()
{
if (_installed)
{
return;
}
lock (InstalledLock)
{
if (_installed)
{
return;
}
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
foreach (MetadataTypeAttribute attrib in type.GetCustomAttributes(typeof(MetadataTypeAttribute), true))
{
TypeDescriptor.AddProviderTransparent(new AssociatedMetadataTypeTypeDescriptionProvider(type, attrib.MetadataClassType), type);
}
}
_installed = true;
}
}
}

 

In entity framework, you define metadata attributes in an internal sealed metadata "buddy" class like:

[MetadataType(typeof(CustomerMetadata))]
public partial class Customer
{
internal sealed class CustomerMetadata
{
[Required(ErrorMessage = "Id is required")]
public Int32 Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public String Name { get; set; }
[DataType(DataType.EmailAddress)]
public String Email { get; set; }
[RegularExpression("^[0-9]{4}[a-z|A-Z]{2}$")]
public String Zipcode { get; set; }
}
}

You can unit test the metadata attributes by using the following unit test class.

using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Research.Dal2;
using System.ComponentModel.DataAnnotations;
[TestClass]
public class CustomerTester
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext) 
{
MetadataTypesRegister.InstallForAssembly();
}
[TestMethod]
public void ValidateZipcodeTest()
{
var customer = new Research.Dal2.Customer();
customer.Zipcode = "this is a wrong zipcode";
var vc = new ValidationContext(customer, null, null) { MemberName = "Zipcode" };
var validationResults = new List<ValidationResult>();
// Validate only the zip code.
bool isValidZipCode = Validator.TryValidateProperty(customer.Zipcode, vc, validationResults);
Assert.IsFalse(isValidZipCode);
// Validate the whole Customer entity.
bool isValidCustomer = Validator.TryValidateObject(customer, vc, validationResults, true);
Assert.IsFalse(isValidCustomer);
}
}

 

Solving: No microphone sound in Skype, when using remote desktop in Windows 7: No audio devices are installed.

I was using Microsoft Remote Desktop on a Microsoft Windows 7 machine to remotely control an other Windows 7 machine an I was running Skype on the remote machine. There was coming sound through the boxes of the local machine, but the microphone was not recorded even when the settings of the Local Resources where: Remote audio playback [Play on this computer] and Remote audio recording [Record from this computer].

 

image

 

The problem was found in the control panel > sound > recording > Select a recording device below to modify its settings:

this list was empty.

 

Solution

After setting the registry key [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp\fDisableAudioCapture] to [0] on the remote machine and reconnecting the problem was solved.

Solving: Running a unittest in the current context [CTRL + R, T] will not rebuild the Microsoft Visual Studio Test project.

Normally when you alter code in your Microsoft Visual Studio test project, pressing [CTRL + R, T] will rebuild the project and will execute the correct code.

In my case altering the code in the unit test did not result in recompiling the test project.

 

Turns out the test project was disabled in the Configuration Manager:

 

image

 

Enabling the project in the configuration manager will resolve the problem.

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

Solving: Invoke operation ‘MyOperation’ failed. Unable to load the specified metadata resource.

If you encounter the error: “Invoke operation ‘MyOperation’ failed. Unable to load the specified metadata resource”. Please check the connection string used by Entity Framework.

In my case, I changed the namespace for the *.edmx file, but forgot to change the namespace in the connection string in the Web.config:

 

I placed the *.edmx file in a folder Models en changed the namespace, so the following connection string was wrong:

<add name=”MyModel” connectionString=”metadata=res://*/MyModel.csdl  ………………………

 

Should be
<add name=”MyModel” connectionString=”metadata=res://*/Models.MyModel.csdl ……………………………….

 

StackTrace

at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
at System.Data.Metadata.Edm.MetadataCache.SplitPaths(String paths)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
at System.Data.Objects.ObjectContext.RetrieveMetadataWorkspaceFromConnection()
at System.Data.Objects.ObjectContext..ctor(EntityConnection connection, Boolean isConnectionConstructor)
at System.Data.Objects.ObjectContext..ctor(String connectionString, String defaultContainerName)

 

An other create resource for resolving this problem is: http://blogs.teamb.com/craigstuntz/2010/08/13/38628/