# Tuesday, 27 November 2012

Visual Studio 2012 Update 1 is available

Microsoft has just made good on its promise of frequent updates to Visual Studio. The first update for Visual Studio 2012 is now available for download.

Somegar has done a nice blog describing the new features in this update: http://blogs.msdn.com/b/somasegar/archive/2012/11/26/visual-studio-2012-update-1-now-available.aspx

Or jump straight to the download at: http://www.microsoft.com/visualstudio/eng/downloads#d-visual-studio-2012-update

#    Comments [0] |
# Sunday, 02 September 2012

Entity Framework 5 + Enumerations => What’s not to love?

Entity Framework 5 now supports enumerations (when using Visual Studio 2012 and targeting the .NET 4.5 framework).

So let’s have a look. We’ll create a table called Planet with a name and a field to indicate whether it is habitable.

CREATE TABLE [dbo].[Planets](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](max) NOT NULL,
    [Habitable] [smallint] NOT NULL,
    [Id] ASC

Note: the data type for ‘Habitable’ is a smallint.

Next we’ll generate an entity data model from the database. Nothing exciting, since our database has just one table.


When we inspect the properties of the ‘Habitable’ property we see that, as expected, it is mapped to an Int16 (short).


Instead of a short we want to map the field to the following enumeration (note that having the enumeration be of type ‘short’ is significant, the type you select for your enum needs to match the column type in the database):

public enum HabitableEnum : short
  Humanoids = 1,
  Insects = 2,
  Droids = 3,
  None = 4,
  All = 5

In order to so, we need to update the model with information about the enum. This is done in the Model Browser.


Look for the “Enum Types” node and right click to add an Enum to the conceptual model.


We can have a locally defined enumeration (to be used in the T4 code generation) or we can refer to the previously defined enumeration by checking the “Reference external type” checkbox.

After adding the enumeration to the model we can now go and update the “Habitable” property in the conceptual model, the enumeration will now be displayed in the type listbox.


If we now browse through the generated code (click the triangle next to the Edmx file in your solution explorer) you’ll see that the generated class for “Planet” is now using the enumeration.

public partial class Planet
    public int Id { get; set; }
    public string Name { get; set; }
    public EF5Demo.Xyz.HabitableEnum Habitable { get; set; }
Should you not see the change, then right click on <yourmodelname>.tt and choose “Run Custom Tool” in order for the T4 template to regenerate the classes.

We can now write some code to insert and query the database. Here is an example:

var ctx = new StarWarsEntities();
Planet p1 = new Planet() { Name = "Tatooine", Habitable = HabitableEnum.Droids };
Planet p2 = new Planet() { Name = "Coruscant", Habitable = HabitableEnum.Humanoids };
ctx.Planets.Add( p1 );
ctx.Planets.Add( p2 );
var query = from p in ctx.Planets
            where p.Habitable == HabitableEnum.Humanoids
            select p;
foreach ( var p in query )
  Console.WriteLine( p.Name + " - " + p.Habitable );

When we run it:


That’s all there’s to it. Using enumerations with Entity Framework 5.

But wait, would it not be nice if we could use byte based enumerations and assign multiple values of the HabitableEnum to a planet?

Lets modify the enumeration to use the Flags attribute:

public enum HabitableEnum : byte
  Humanoids = 0x1,
  Insects = 0x2,
  Droids = 0x4,
  None = 0x8

We need to change the type of the ‘Habitable’ column in the database to a tinyint and we need to modify the information in the conceptual schema to inform the entity framework of our change in design:


The screenshot shows that we need to change the underlying type as well as check the “Set Flags attribute”.

We can now write code that assigns multiple values to the habitable field:

using ( var ctx = new StarWarsEntities() )
HabitableEnum x = HabitableEnum.Humanoids;
x |= HabitableEnum.Insects;
Planet p1 = new Planet() { Name = "Tatooine", Habitable = HabitableEnum.Droids };
Planet p2 = new Planet() { Name = "Coruscant", Habitable = x };
ctx.Planets.Add( p1 );
ctx.Planets.Add( p2 );
var query = from p in ctx.Planets
            select p;
foreach ( var p in query )
  Console.WriteLine( p.Name + " - " + p.Habitable );

The output looks like this:


If you wish to query for just insects you need to write a bitwise AND statement, like:

var query = from p in ctx.Planets
            where ( p.Habitable & HabitableEnum.Insects ) == HabitableEnum.Insects
            select p;

That’s all folks, have fun!

#    Comments [2] |
# Sunday, 26 August 2012

Entity Framework 5 is available

Entity Framework 5 is included in Visual Studio 2012, but is also available to users of Visual Studio 2010 (as a NuGet package: http://nuget.org/packages/EntityFramework/ ).

Note: Some Entity Framework 5 features are only available when writing an application that targets .NET 4.5. This includes enum support, spatial data types, table-valued functions and the performance improvements.

Read more about what is new on the MSDN ADO.NET blog: http://blogs.msdn.com/b/adonet/archive/2012/08/15/ef5-released.aspx

Update [08-27-2012] : Julie Lerman has an excellent post describing the difference between running EF5 in a .NET 4 versus a .NET 4.5 application, read more on: http://thedatafarm.com/blog/data-access/when-entity-framework-5-ef5-is-not-entity-framework-5-ef5/

#    Comments [1] |
# Thursday, 16 August 2012

Windows 8 RTM and Visual Studio 2012 now on MSDN

For those of us with an MSDN subscription: Windows 8 RTM and Visual Studio 2012 are both available for download. Go to https://msdn.microsoft.com/en-us/subscriptions to get your copy.



#    Comments [2] |
# Monday, 30 April 2012

String literals and ‘==’ versus Equals(…)

I had a little fun today playing with ‘==’ vs. the Equals(…) method. I knew that somewhere in .NET 2.0 (I believe) there had been some improvements in String.Empty versus “”, but I didn’t quite realize that this affected all string literals.

In the code below you can see how value types and reference types may behave differently when using ‘==’ versus the Equals method.
My surprise came when I discovered that line 39 and 41 both return TRUE. Apparently the string literals in an assembly get put in a master list of string constants and then reused where the same string literal gets used. Nice!
The way to force the reference comparison of the string against object to actually be different is to delay the creation of the string until runtime, like in line 52.

   1:  static void Main(string[] args)
   2:  {
   4:      // value types
   6:      int x = 10;
   8:      int y = 10;
  10:      Console.WriteLine( x == y );  // compare by value -> return true
  12:      Console.WriteLine( x.Equals( y ) ); // compare by value -> return true
  14:      Console.WriteLine( object.ReferenceEquals( x, y ) );  // compare by reference -> return false
  17:      Console.ReadLine();
  19:      // Reference types
  21:      StringBuilder s1 = new StringBuilder( "yes" );
  23:      StringBuilder s2 = new StringBuilder( "yes" );
  25:      Console.WriteLine( s1 == s2 ); // compare by reference -> return false
  27:      Console.WriteLine( s1.Equals( s2 ) ); // compare by value -> return true
  29:      Console.WriteLine( object.ReferenceEquals( s1, s2 ) ); // compare by reference -> return false
  31:      Console.ReadLine();
  33:      // object and string
  35:      object o1 = GetName();
  37:      string o2 = "Mark";
  39:      Console.WriteLine( o1 == o2 );  // compare by reference -> return true
  41:      Console.WriteLine( o1.Equals( o2 ) ); // compare by value -> return true
  43:      Console.WriteLine( object.ReferenceEquals( o1, o2 ) ); // compare by reference -> return true
  45:      Console.ReadLine();
  48:      // object and string
  50:      object ss1 = "Mark";
  52:      string ss2 = "Markx".Substring( 0, 4 );
  54:      Console.WriteLine( ss1 == ss2 );  // compare by reference -> return false
  56:      Console.WriteLine( ss1.Equals( ss2 ) ); // compare by value -> return true
  58:      Console.WriteLine( object.ReferenceEquals( ss1, ss2 ) ); // compare by reference -> return false
  60:      Console.ReadLine();
  61:  }
  63:  static object GetName()
  64:  {
  65:      return "Mark";
  66:  }
#    Comments [4] |
# Wednesday, 29 February 2012

Windows 8 Consumer Preview

ISO images with the Windows 8 Consumer Preview are now available for download. Go to http://windows.microsoft.com/en-US/windows-8/iso to get the bits.

#    Comments [3] |

Microsoft Visual Studio 11 Ultimate Beta

Microsoft Visual Studio 11 Ultimate Beta has just become available for download. Go to http://www.microsoft.com/download/en/details.aspx?id=28975 to download the bits.

#    Comments [0] |
# Tuesday, 24 January 2012

Type-Safe Include extension method for Entity Framework

If you’re interested in the Include method in a LINQ to Entities queries to be type-safe, then Joe Ferner has the answer for you in this post: Type-Safe Entity Framework Include: http://www.nearinfinity.com/blogs/joe_ferner/type-safe_entity_framework_inc.html

#    Comments [0] |
# Tuesday, 17 January 2012

Generating an index in the database using Entity Framework Code First

If you’re using Entity Framework Code First, then you may want to create an index on some of your table. The way to do this is to call “Database.ExecuteSqlCommand” in the “Seed” method of your database initializer. The sample below shows how it is done (thanks to Rolf for pointing me in the right direction):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace CodeFirstPlayground
  class Program
    static void Main( string[] args )
      Database.SetInitializer<CodeFirstSampleModel>( new CodeFirstSampleDbInitializer() );
      using ( var model = new CodeFirstSampleModel() )
        var query = from c in model.Customers
                    where c.Name != null
                    select c;
        foreach ( var item in query )
          Console.WriteLine( item.Name );
  public class CodeFirstSampleModel : DbContext
    public CodeFirstSampleModel()
      : base( "CodeFirstSampleDB" )
      Customers = this.Set<Customer>();
    public DbSet<Customer> Customers { get; set; }
  public class CodeFirstSampleDbInitializer : DropCreateDatabaseAlways<CodeFirstSampleModel>
    protected override void Seed( CodeFirstSampleModel context )
      context.Database.ExecuteSqlCommand( "CREATE INDEX IX_Customer_Name ON Customers (Name) " );
      Customer c = new Customer()
        Name = "Mark",
        LastOrder = DateTime.Now
      context.Customers.Add( c );
      base.Seed( context );
  public class Customer
    public int Id { get; set; }
    [MaxLength( 50, ErrorMessage = "Customer name must be 50 characters or less." )]
    public string Name { get; set; }
    public DateTime? LastOrder { get; set; }
#    Comments [3] |
# Wednesday, 04 January 2012

SharePoint UG Maine

Just a quick service announcement:

Winxnet, in Portland, has started hosting the first Maine based SharePoint User Group.

For more information visit: www.winxnet.com/spugme

#    Comments [3] |
# Monday, 02 January 2012

Microsoft Most Valuable Professional 2012

mvp-logoI’m honored to have been awarded the Microsoft Most Valuable Professional 2012 Award for contributions in the Visual C# technical communities. I’m honored to be counted amongst the 228 people world wide to receive this award.

“At Microsoft, we believe that technical communities enhance people’s lives and the industry’s success because independent experts, like you, help others extract greater value from products and technologies through the free and objective exchange of knowledge. As a Microsoft MVP, you are part of a highly select group of experts that represent technology’s best and brightest who share a deep commitment to community and a willingness to help others.”
    - Heather Kostes

Thank you Microsoft and thank you Heather! I’m looking forward to organizing more events again this year for the Maine Developer Network and hanging out with the Bangor Area .NET Developers and I’m looking forward to Maine Code Camp #3 and also to meeting my fellow MVPs and product groups in Seattle at the MVP Summit 2012.

- Mark

#    Comments [0] |
# Monday, 26 December 2011

How to discover what font was used

Sometimes you’re working on a website and you get some images with text in them, but no one remembers what fonts was used in the image. No fear! There is a website call “What The Font” that will take your picture and tell you what font was used: http://new.myfonts.com/WhatTheFont/

#    Comments [0] |
# Monday, 12 December 2011

Silverlight 5 release

Silverlight 5 got released this weekend and can be downloaded here: http://www.silverlight.net/downloads.

Summary of the features

(from the Silverlight 5 download package)

Improved media support
  • Low Latency Audio Playback
  • Variable Speed Playback
  • H/W Decode of H.264 media
  • DRM Key Rotation/LiveTV Playback
  • Application-Restricted Media
Improved Text support
  • Text Tracking & Leading
  • Linked Text Containers
  • OpenType and Pixel Snapped Text
  • Postscript vector printing
  • Performance improvements for Block Layout Engine.
Building next-generation business applications
  • PivotViewer
  • ClickCount
  • Listbox/ComboBox type-ahead text searching
  • Ancestor RelativeSource Binding
  • Implicit DataTemplates
  • DataContextChanged event
  • Added PropertyChanged to the UpdateSourceTrigger enum
  • Save File and Open File Dialog
  • Databinding Debugging
  • Custom Markup Extensions
  • Binding on Style Setters
Silverlight 5 performance improvements
  • Parser Performance Improvements
  • Network Latency Improvements
  • H/W accelerated rendering in IE9 windowless mode
  • Multicore JIT
  • 64-bit browser support
Graphics improvements
  • Improved Graphics stack
  • 3D
"Trusted Application" model
  • Multiple window support
  • Full-Trust in-browser
  • In-browser HTML support
  • Unrestricted File System Access
  • P/Invoke support
Tools improvements
  • Visual Studio Team Test support
#    Comments [3] |
# Monday, 14 November 2011

Augusta Developer Event, November 16th 2011

The next Maine Developer Network meeting will be in Augusta on Wednesday November 16th, starting at 9:00am finishing at 12:00 pm.
It is going to be a unique event about Windows Azure: "Playing Games in the Cloud" and will be hosted by Jim O'Neil, Microsoft Developer Evangelist. It will be more of a workshop than just presentation, so bring your laptop and make sure it is prepped to for the class.
For more info see: www.maine-devnet.org

#    Comments [3] |
# Tuesday, 01 November 2011

Streaming XML using LINQ to XML (continued)

Richard Blewett reminded me that the XmlReader.ReadSubtree method makes it even easier to use LINQ to XML with a streaming approach. The code sample below will load nodes from an arbitrary XML files and yield them to the caller as they’re read from file:

static IEnumerable<XElement> Load(string filename, string elementName)
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.IgnoreWhitespace = true;
    using (XmlReader reader = XmlReader.Create(filename, settings))
        while (reader.ReadToFollowing(elementName))
            // build element from subtree
            XElement element = XElement.Load(reader.ReadSubtree());
            yield return element;
#    Comments [0] |
# Monday, 31 October 2011

Streaming XML

I just rediscovered this blog post about reading and parsing XML as it becomes available in conjunction with LINQ to XML: http://blogs.msdn.com/b/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx

It’s a little dated, but still relevant Smile.

#    Comments [3] |

What’s new in .NET Framework 4.5

Just came across this great picture of what’s new in .NET Framework 4.5 (click for larger version):


#    Comments [4] |
# Friday, 21 October 2011

Custom color in reports : convert color to Hex

I was implementing a client report (RDLC) using the Microsoft Report Viewer control and I wanted to set the background color of a table field based on value from my object source. At first I used the Color.ToKnownColor() method, but discovered that this does not work for all colors. I needed to convert to Hex. Here is the little extension method I used:

public static class ColorExtensions
    #region -- Data Members --
    static char[] hexDigits = {
     '0', '1', '2', '3', '4', '5', '6', '7',
     '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
    /// <summary>
    /// Convert a .NET Color to a hex string.
    /// </summary>
    /// <returns>ex: "#FFFFFF", "#554ECE"</returns>
    public static string ToHexString( this Color color )
        byte[] bytes = new byte[3];
        bytes[0] = color.R;
        bytes[1] = color.G;
        bytes[2] = color.B;
        char[] chars = new char[bytes.Length * 2];
        for ( int i = 0; i < bytes.Length; i++ )
            int b = bytes[i];
            chars[i * 2] = hexDigits[b >> 4];
            chars[i * 2 + 1] = hexDigits[b & 0xF];
        return "#" + new string( chars );
#    Comments [3] |
# Wednesday, 05 October 2011

Visual Studio 2010: Debugging a x86 WCF service on a x64 machine

I just ran into an issue where I have a WCF service that depends on a .NET assembly that is compiled specifically for x86. In order to use that assembly I need to compile the service as a x86 service. No problem, but now when I want to test or add a service reference to this WCF service I ran into the problem that WcfSvcHost and WcfTestClient both will run a x64 because I’m running Windows 7 x64.

How to solve this? I found the answer in the forums and adapted the answer for my specific problem:

1.Copy WcfSvcHost.exe and WcfTestClient.exe from C:\program files (x86)\Microsoft Visual Studio 10.0\Common7\IDE to a local directory. Keep a backup copy of this file, of course.
2.Start a Visual Studio 2010 Command Prompt (one of the links from the start menu -> Visaul Studio 2010)
3."cd" to the directory where your copy of WcfSvcHost is located.
4.Execute the command "corflags /32BIT+ /FORCE WcfSvcHost.exe"
5.Copy the files back to where you found it.
Now your WcfSvcHost and WcfTestClient will be running in 32 bit mode.

#    Comments [3] |
# Friday, 02 September 2011

Omnext @ New York CloudExpo 2011: “If it ain’t Dutch, it ain’t much”

Omnext was part of a Dutch trade delegation visiting the New York CloudExpo 2011.
Here is a link to a great article by Theo Loth (coordinator EuroCloud Nederland) about the event: omnext - cloudexpo 2011.pdf (in Dutch).

If your looking to find out more about Omnext and how Source2VALUE can help improve the ROI of your software development investments, then visit www.omnext.net or talk to Jaco and Andre at the 2011 European Outsourcing Summit in Madrid, Spain.

#    Comments [3] |