Why do I get a TypeLoadException when moving my project to .NET 4?

There have been some security changes in the .NET 4.0 Framework, so when moving a project to .NET 4.0 you may get the following exception:

TypeLoadException - Derived Types must either match the security accessibility of the base type or be less accessible.

There are two approaches to fixing this problem:

 1. If you are you using the SecurityTransparentAttribute in your project's AssemblyInfo.cs/vb file you need to remove this attribute since it's now obsolete in the .NET 4 Framework.

 2. If this isn't the case, try adding the following attribute to your project's AssemblyInfo.cs/vb file to get past the exception:

 [assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]

For more information, check out this MSDN topic: http://msdn.microsoft.com/en-us/library/dd233102(VS.100).aspx

Best Regards,
Kevin McNeish
INETA Speaker
President, Oak Leaf Enterprises, Inc.
Home of the MM .NET Framework
www.oakleafsd.com

 

Silverlight 4 101: Using Silverlight Assemblies in your non-Silverlight Projects

If you're like me, you have been coding in .NET for a long time (for me, pre-version 1.0) and you have many libraries containing classes you would like to reuse in your Silverlight applications.

However, if you try to reference a non-Silverlight assembly from a Silverlight project, you will get the following error message from Visual Studio:

You can't add a reference to <assembly name> as it was not built against the Silverlight runtime. Silverlight projects will only work with Silverlight assemblies.

Although you can't reference a non-Silverlight assembly from a Silverlight project, starting with Silverlight 4 and .NET 4, you CAN go the other way--reference a Silverlight assembly from a non-Silverlight project. This feature is known as "assembly portability". This portability currently only works with the following Silverlight assemblies:

- Mscorlib
- System
- System.Core
- System.ComponentModel.Composition
- Microsoft.VisualBasic

So, as long as you convert your existing .NET class libraries to Silverlight projects and only referene the above assemblies, you can use these libraries from both Silverlight and non-Silverlight projects.

For more information, check out this CLR Team Blog post: http://blogs.msdn.com/b/clrteam/archive/2009/12/01/sharing-silverlight-assemblies-with-net-apps.aspx

Best Regards,
Kevin McNeish
INETA Speaker
Chief Software Architect, MM .NET Applicaiton Framework
www.oakleafsd.com

Silverlight 4 101: Silverlight Project Templates

In Silverlight 4 with Visual Studio 2010, there are five Silverlight project templates to choose from. Here is a summary of each:

Silverlight Application
Creates a blank Silverlight project. After selecting this template, a dialog appears asking you to specify whether you want to host the Silverlight application in a new Web site (either an ASP.NET Web Application Project, ASP.NET Web Site, or an ASP.NET MVC Web Project). You can also specify the Silverlight Version (based on the list of Silverlight SDKs installed on your machine), and whether you want to enable WCF RIA Services (discussed below). This template does not implement the Silverlight Navigation Framework (discussed below).

Silverlight Class Library
Creates an empty class library that can be used from a Silverlight application. When you select this template, a dialog appears asking which version of Silverlight you want to target. The resulting solution contains a single project with a single class definition.

Silverlight Business Application
Creates a project that is set up to use both the Silverlight Navigation Framework (discussed under the next template) as well as RIA Services (discussed under the last template).

Silverlight Navigation Application
Creates a project that uses the Silverlight Navigation Framework (http://www.silverlightshow.net/items/The-Silverlight-3-Navigation-Framework.aspx) which allows you to easily navigate between pages in a Silverlight application, as well as interaction with the Browser History journal and provides Uri mapping.

WCF RIA Services Class Library
Creates a solution containing two projects that enable you to create reusable middle-tier and presentation-tier logic. A link exists between the generated Silverlight and middle-tier project that facilitates generating presentation-tier code from middle-tier code. For details, check out this link: http://msdn.microsoft.com/en-us/library/ee707336(v=VS.91).aspx.

Best Regards,
Kevin McNeish
INETA Speaker
Chief Software Architect, MM .NET Application Framework
www.oakleafsd.com

Silverlight 4 101: Installing Silverlight

Microsoft releases new versions of Silverlight out of step with the release cycle for Visual Studio, so even if you have the latest updates for Visual Studio installed on your development machine, you still need to go to the Microsoft Silverlight site to download the latest Silverlight bits:

http://www.silverlight.net

To install Silverlight 4 on your VS 2010 development machine, you can download the installer from this link:

http://www.microsoft.com/downloads/details.aspx?FamilyID=902a7539-c4b5-4e54-b4c9-1432daabe1e8&displaylang=en

This installer includes the following components:

- Silverlight 4 Developer Runtime
- Silverlight 4 Update for Visual Studio 2010 and Visual Web Developer Express 2010
- Silverlight 4 SDK
- Silverlight 4 Tools Package for Visual Studio 2010
- WCF RIA Services V1.0 for Silverlight 4
- F# Runtime for Silverlight 4

If you have a previous version of Silverlight on your development machine, the installer will also:

 - Uninstall Earlier Visual Studio 2010 Update
 - Uninstall Earlier WCF RIA Services

Best Regards,
Kevin McNeish
INETA Speaker
Chief Software Architect, MM .NET Application Framework
http://www.oakleafsd.com

 

Using NUnit in Visual Studio 2010

To use NUnit with Visual Studio 2010, follow these steps:

1. Make sure you have the latest version of NUnit installed

2. In Visual Studio, open up the nunit.exe.config file found at:

C:\Program Files\NUnit 2.x.x\bin\net-2.0\

3. Under the <configuration> element, add the following (make sure the version number is correct for your installation of VS 2010):

     <startup>

           <requiredRuntime version="v4.0.30319" />

     </startup>

4. Under the <runtime> element, add the following:

<loadFromRemoteSources enabled="true" />

Best Regards,
Kevin McNeish
INETA Speaker
Chief Software Architect, MM .NET Application Framework
www.oakleafsd.com

WPF: Setting Focus in a Custom User Control

When you create a custom user control, it typically contains child user interface elements. To provide a proper "Focus" experience at run time, you need to do the following:

1. Select your user control in design mode and check the Focusable check box

2. Create a handler method for your user control's GotFocus event. In the event handler method, add a line of code that sets focus to the child control you want to initially receive focus. For example:

private void AutoCompleteTextBox_GotFocus(object sender, RoutedEventArgs e)
{
  
this.txtTextBox.Focus();
}

Best Regards,
Kevin McNeish
INETA Speaker
Chief Software Architect, MM .NET Application Framework
www.oakleafsd.com

Silverlight: Fixing the "Tag Expander Does Not Exist" Compiler Error

If you create a new Silverlight Navigation project, then compile immediately with no changes, you will get the following compiler error:

The tag 'Expander' does not exist in XML namespace 'clr-namespace:System.Windows.Controls;assenbly=System.Windows.Controls'

This is because the Expander element (as well as DockPanel, WrapPanel, HeaderedContentControl, Viewbox, and DataForm have been moved to the Silverlight Toolkit.

To fix this problem:

1. If you haven't already done so, download and install the Silverlight Toolkit (http://www.codeplex.com/Silverlight)

2. Add the System.Windows.Controls.Toolkit assembly to your project

3. Add the following namespace reference to the top of your project's ErrorWindow.xaml file:

xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"4.

4. In the body of the ErrorWindow.xaml file, change the prefix of the Expander control from "controls" to "controlsToolkit". Remember to do this on both the opening and closing tags:

<controlsToolkit:Expander Grid.Row="2" Header="Details" Margin="0, 10, 0, 0" >

 

   <TextBox Text="{Binding ErrorDetails}"
      
Height="100"
      
TextWrapping="Wrap" IsReadOnly="True"
     
VerticalScrollBarVisibility="Auto" />

 

</controlsToolkit:Expander>

Best Regards,
Kevin McNeish
INETA Speaker
Chieft Architect, MM .NET Application Framework
www.oakleafsd.com

WPF: Setting the Height or Width to Auto in Code

At times, you may want to programmatically set the Height or Width of a WPF element to Auto in code. To do this, just use the Double.NaN (Not a Number) value.

For example, in C#:

this.txtName.Width = Double.NaN;

And in VB .NET:

Me.txtName.Width = Double.Nan

Best Regards,
Kevin McNeish
INETA Speaker
Chief Architect, MM .NET Application Framework
www.oakleafsd.com

 

 

Setting Entity Framework MergeOptions - What Works, What Doesn't

The Basics
When retrieving entities using object queries with the Entity Framework, there is a MergeOption setting that allows you to specify how you want entities to be retrieved. The default value is AppendOnly, which specifiies that if an entity already exists in the ObjectContext, to retrieve it from there. Otherwise, it is retrieved from the database. This means that if you retrieve an entity, change some of its property values and then retrieve it again from the ObjectContext, you will not get a fresh copy from the database--you'll get the cached object in the ObjectContext. For a great explanation of how all this works, check out this link:

http://blogs.msdn.com/dsimmons/archive/2010/01/12/ef-merge-options-and-compiled-queries.aspx 

How to Specify the MergeOption
There are a few ways to specify the MergeOption you want. I'll concnetrate on doing this with a LINQ query, and for these examples, I will change the value to OverwriteChanges, which retrieves a new entity from the data store rather than a cached instance from the ObjectContext.

1. Set the value of the EntitySet.MergeOption property

When you do this, any queries you create from the entity set will use the MergeOption value you specify. For example:

this.ObjectContext.EmployeeEntitySet.MergeOption = MergeOption.OverwriteChanges;
IQueryable<EmployeeEntity> query = from e in this.ObjectContext.EmployeeEntitySet
      where e.EmployeeID == employeeID
      select e;
return query.FirstOrDefault();

2. You can create an object query and set its MergeOption property

When you do this, the setting only applies to the current query. For example:

ObjectQuery<EmployeeEntity> query = this.ObjectContext.CreateQuery<EmployeeEntity>("[EmployeeEntitySet]");
query.MergeOption = MergeOption.OverwriteChanges;
var res = from ei n query
      where e.EmployeeID == employeeID
      select e;
return res.FirstOrDefault();

3. You can convert the IQueryable<T> into an object query, call Execute() and specify the MergeOption

This also sets the MergeOption on a specific query, rather than all queries of that type. For example:

IQueryable<EmployeeEntity> query = from e in this.ObjectContext.EmployeeEntitySet
      where e.EmployeeID == employeeID
      select e;
ObjectQuery objectQuery = (ObjectQuery)query;
ObjectResult<EmployeeEntity> result = (ObjectResult<EmployeeEntity>objectQuery.Execute(MergeOption.OverwriteChanges);
return result.FirstOrDefault();

4. The following does NOT work.

IQueryable<EmployeeEntity> query = from e in this.ObjectContext.EmployeeEntitySet
      where e.EmployeeID == employeeID
      select e;
ObjectQuery objectQuery = (ObjectQuery)query;
objectQuery.MergeOption = MergeOption.OverwriteChanges;
return query.FirstOrDefault();

Setting the MergeOption at this point is 'too late to the dance!". The query will use the default AppendOnly option instead.

Best Regards,
Kevin McNeish
INETA Speaker
Chief Architect, MM .NET Application Framework
www.oakleafsd.com

Preventing WPF Controls from Being Displayed in the Visual Studio Toolbox

In other technologies such as Windows Forms and Web Forms, you can adorn a class with the [ToolboxItem(false)] attribute and it will not appear in the Visual Studio Toolbox.

In Windows Presentation Foundation (WPF) you use the [ToolboxBrowsable(false)] attribute instead. This attribute is found in the Microsoft.Windows.Design namespace in the Microsoft.Windows.Design.dll assembly.

Best Regards,
Kevin McNeish
.NET MVP for past seven years
INETA Speaker
Chief Architect,  MM .NET Application Framework
www.oakleafsd.com

Fixing WPF TextBox Mouse Events Not Firing

If you create a handler for the WPF TextBox's mouse events, you will find that the code in your handler never fires. This is because the event is marked as "handled" in the .NET Framework, so it never reaches your code.

To get around this bad behavior, you can use the TextBox's AddHandler() method to register your handler method, passing a true for the handledEventsToo parameter. For example:

this.txtCustomerID.AddHandler(ControlMouseLeftButtonUpEvent, 
    new MouseButtonEventHandler(txtCustomerID_MouseLeftButtonUp), true);

Best Regards,

Kevin McNeish
INETA Speaker
Chief Architect, MM .NET Application Framework
http://www.oaleafsd.com

 

Fixing "Configuration System Failed to Initalize" Exception

If you see the "Configuration System Failed to Initialize" exception at run time, it is typically caused by an invalid entry in your app.config or web.config file. In my case, I encountered this exception when I had an "<add key...>" element out of place. Oddly enough, the compiler didn't warn me about this when I rebuilt my solution with the config file open (as it usually does with most other config file errors).

Best Regards,
Kevin McNeish
INETA Speaker
Microsoft .NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
www.oakleafsd.com

Fixing LINQ Error: Sequence contains no elements

When you get theLINQ Error "Sequence contains no elements", this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault().

 Take for example the following code that uses First() on the results of the LINQ query. If there are no results, the call to First() triggers the "Sequenc contains no elements" error.:

var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().First();

To fix the problem, all you have to do is change First() to FirstOrDefault() which returns a null value when there are no results from the select:

var rel = (from r in relEnds
   where r.Contains(added.OtherEndKey(entity.EntityKey))
   select r).OfType<EntityReference>().FirstOrDefault();

Kevin McNeish
INETA Speaker
.NET MVP 2002-2009
Chief Architect MM .NET Application Framework
www.oakleafsd.com

Entity Framework: Fixing "The number of errors in the conceptual type...does not match with the number of members on the object side type..."

You will typically get the error "The number of errors in the conceptual type...does not match with the number of members on the object side type" in version 1.0 of the Entity Framework when you have manually edited one or more of your entities. In version 1.0 of EF, all members of your conceptual model must be mapped to properties in your object model and all properties in  your entity classes adorned with the EdmScalarProperty attribute must be defined in your conceptual model.

Best Regards,
Kevin McNeish
INETA Speaker
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
www.oakleafsd.com

Entity Framework: Programmatically determining the Entity Set name of an Entity

Here is an extension method for the Object Context that allows you to programmatically derive an Entity Set name associated with a particular entity. To put this in context, when adding a new entity object to an Object Context, you need to specify the associated entity set of the entity you are adding.

Here is an extension method for the ObjectContext class that allows you to do this:

public static string GetEntitySetFullName(this ObjectContext, EntityObject entity)
{
   // If the EntityKey exists, simply get the Entity Set name from the key

   if (entity.EntitKey != null)
   {
      return entity.EntityKey.EntitySetName;
   }
   else
   {
      string entityTypeName = entity.GetType().Name;
      var container = context.MetaDataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);
      string entitySetName = (from meta in container.BaseEntitySets
                              where meta.ElementType.Name == entityTypeName
                              select meta.Name).First();

      return container.Name + "." entitySetName;

   }
}

Best Regards,
Kevin McNeish
.NET MVP 2002-2009
Chief Architect MM .NET Application Framework
INETA Speaker
www.oakleafsd.com

Understanding the Entity Framework ConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows...

When working with the Entity Framework in n-Tier applications where you are unattaching and attaching entities from an object context, you may encounter this exception:

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.

This exception is letting you know that no rows were updated. There are several reasons why you may encounter this error.

One simple reason is that when attaching entities to an Object Context, you need to use the AddObject() method if the entity is newly created (and doesn't have an Entity Key), whereas you can use the Object Context Attach() method if the entity already exists and is being updated. Here is some code to demonstrate this (where "EntityContainerName" is the name of your Entity Framework container and "EntitySetName" is the name of the Entity Set to which you are adding the entity):

if (entity.EntityKey == null || entity.EntityKey.IsTemporary)
{
   this.ObjectContext.AddObject("EntityContainerName.EntitySetName", entity);
}
else
{
   this.ObjectContext.Attach(entity);
}

Note that you need to be careful when adding entities that are related to other entity objects because Object Services attempts to add the related objects too.

Best Regards,
Kevin McNeish
.NET MVP 2002-2009
Chief Architect, MM .NET Application Framework
INETA Speaker
www.oakleafsd.com

Using Reflection to Determine if a Property Data Type is Nullable

You can easily determine if the data type of an object property is nullable using the following code:

Type t = objectReference.GetType();
Type pt;

// Test for Nullable
bool isNullable = pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>);
PropertyInfo pi = t.GetProperty("MyPropertyName");

if (isNullable)
{
   // Returns the basic data type without reference to Nullable (for example, System.Int32)
   pt = pi.PropertyType.GetGenericArguments()[0];
}

Best Regards,
Kevin McNeish
Chief Architect, MM .NET Application Framework
INETA Speaker
.NET MVP 2002-2009
www.oakleafsd.com 

Silverlight 3 DataForm Edit Pencil

Here's a quick tip--if your Silverlight 3 DataForm is not dsplaying an Edit Pencil in the upper right corner, set the DataForm's AutoEdit to false (or if using the Visual Studio or Expression Blend IDE, uncheck the AutoEdit checkbox).

Best Regards,
Kevin McNeish
INETA Speaker
Chief Architect MM .NET Application Framework
www.oakleafsd.com

Silverlight 3 and the Bindable Attribute

You may see a number of videos and sample code for Silverlight 3 that uses the Bindable  attribute to specifying editing features of an entity property when working with the Silverlight DataForm control. However, the Bindable attribute (as well as the System.ComponentModel assembly) were removed from Silverlight with the Silverlight 3 RTM.

Now, if you want to specify if an entity property you are binding to should be readonly, set its Editable attribute like this:

 

[

Editable(false)]
public DateTime BirthDate { get; set; }

If you want to specify that a user interface control should not be automatically generated for a particular entity property, set its Display attribute like this:

 

[

Display(AutoGenerateField=false)]
public int EmployeeID { get; set; }

Best Regards,
Kevin McNeish
Chief Architect, MM .NET Application Framework
Oak Leaf Enterprises, Inc.
www.oakleafsd.com

Don't Miss the Silverlight Toolkit for Getting Additional Silverlight Mojo!

Regardless of whether you have installed Silverlight for VS 2008 or VS2010, you will want to install the additional Silverlight Toolkit:

http://www.codeplex.com/Silverlight

This toolkit gives you additional controls, components and utilities released outside the regular Silverlight release cycle. This is good news because Microsoft is releasing new Silverlight functionality iteratively. Rather than providing these controls with a "big bang" release, Microsoft is releasing them iteratively to get feedback from the developer community (can anyone say "user stories") before officially including them in the product.

These new controls are designated with different quality bands, indicating their level of maturity. This helps you decide whether you want to include them in your projects right now, or possibly wait until more mature versions of the controls are released. Here is a list of the four quality bands, listed in ascending order from least to most mature:

- Experimental
- Preview
- Stable
- Mature

Check out this link for a description of each quality level: http://silverlight.codeplex.com/wikipage?title=Quality%20Bands&referringTitle=Home.

This kind of iterative release is a good example for developers to follow. Software developers often have difficulty "letting go" of their code because they don't want to put something in front of end uers that isn't perfect, so they wait until they are finished to get feedback. The problem with this approach is that users can't really provide solid feedback until they have something in front of them that they can play with. So, developers who wait until their software is complete before letting users provide feedback often find themselves rewriting and refactoring their code, and ultimately delaying the release of their software.

The moral is, get feedback as early and often as possible!

Best Regards,
Kevin McNeish
INETA Speaker
Chieft Architect, MM .NET Application Framework
www.oakleafsd.com

 

More Posts Next page »