# Tuesday, January 17, 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 );
        }
      }
 
      Console.ReadLine();
 
    }
  }
 
  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
  {
    [Key]
    public int Id { get; set; }
    [Required]
    [MaxLength( 50, ErrorMessage = "Customer name must be 50 characters or less." )]
    public string Name { get; set; }
    
    public DateTime? LastOrder { get; set; }
  }
}
#    Comments [3] |
# Wednesday, January 04, 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, January 02, 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, December 26, 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, December 12, 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, November 14, 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, November 01, 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, October 31, 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):

WhatsNewNET45-en

#    Comments [4] |
# Friday, October 21, 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'};
    #endregion
 
 
    /// <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, October 05, 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, September 02, 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] |
# Friday, August 26, 2011

SDN Conferences 2011

For those who will be in the Netherlands in October: the SDN is organizing it’s annual 2-day conference on October 3rd and 4th, 2011. A preview of the schedule is now online and registration has just opened: http://www.sdn.nl/SDN/SDNEvent/SDNConferences2011/tabid/162/Default.aspx

#    Comments [0] |
# Monday, August 01, 2011

Maine Code Camp #2 - Video Impression

A (short) video impression of Maine Code Camp #2:

#    Comments [2] |
# Monday, July 11, 2011

LINQ: Convert list to a dictionary of lists

Suppose I have a list of time cards from multiple employees, but I want to group them into dictionary, based on the Social Security Number (SSN) of the employee. Here is an example of how to convert a list of items into a dictionary of lists:

Dictionary<string, List<TimeCardInfo>> dict;
 
dict = ( from timecard in listOfTimeCards
         group timecard by timecard.SSN ).ToDictionary( x => x.Key, x => x.ToList() );
#    Comments [3] |
# Friday, July 08, 2011

Shrink SQL Server 2008 R2 log files

I just discovered that if you run SQL Server on your developer box and never bother to cleanup your log files, then perhaps they get to be a little big Smile.
Here is a script to quickly shrink a log file:
 
 
Use [YourDatabaseName]
Go
 
select name,recovery_model_desc from sys.databases
GO 
Alter database [YourDatabaseName] SET RECOVERY SIMPLE
GO
Declare @LogFileLogicalName sysname
select @LogFileLogicalName=Name from sys.database_files where Type=1
print @LogFileLogicalName
 
DBCC Shrinkfile(@LogFileLogicalName,100) 
#    Comments [1] |
# Saturday, July 02, 2011

Entity Framework – Model First: Generating DDL for Complex Types

In the model below the phone number for an artist is actually a complex type (a little over engineered, I know, but I was just exploring how well this works).

image

The complex type consists of 4 ‘fields’: CountryCode, AreaCode, Number and Extension:

image

Each ‘field’ has properties set:

image

The great part is that this is fully supported by the DDL generator, so right click on the Entity Framework Designer in Visual Studio 2010 and choose ‘Generate Database From Model…’ and the ‘Artist’ table will be generated as:

 
-- --------------------------------------------------
-- Entity Designer DDL Script for SQL Server 2005, 2008, and Azure
-- --------------------------------------------------
 
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
 
-- Creating table 'Artists'
CREATE TABLE [dbo].[Artists] (
    [Id] int IDENTITY(1,1) NOT NULL,
    [Name] nvarchar(100)  NOT NULL,
    [IsIndividual] bit  NOT NULL,
    [Phone_CountryCode] nvarchar(4)  NOT NULL,
    [Phone_AreaCode] nvarchar(5)  NOT NULL,
    [Phone_Number] nvarchar(10)  NOT NULL,
    [Phone_Extension] nvarchar(10)  NULL
);
GO
-- <snip other tables>
 
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
 
-- Creating primary key on [Id] in table 'Artists'
ALTER TABLE [dbo].[Artists]
ADD CONSTRAINT [PK_Artists]
    PRIMARY KEY CLUSTERED ([Id] ASC);
GO
 
-- <snip other primary and foreign key>
 
 
-- --------------------------------------------------
-- Script has ended
-- --------------------------------------------------
Notice that by default each column is prefixed with the name of the complex type, this is of course needed to ensure column names stay unique across multiple complex types in a single entity.
#    Comments [0] |
# Wednesday, June 29, 2011

Logging and tracing with Entity Framework

If you’re using the Entity Framework and don’t want to implement ToTraceString() at strategic points in your code in order to see what kind of SQL statements are getting generated then check out one of the following:

Update 07-02-2011: Added SQL Server Profiler after comment by Tony Sneed.

#    Comments [2] |

Entity Framework - Model First: One-to-One relationship

If you’re doing Model First with Entity Framework you may run into a scenario where you want to design a 1-to-1 relationship, but also have a foreign key be available on your entity. The default behavior in Entity Framework when doing a 1-to-1 relationship (with Model First), or 1-to-0..1 relationship, is to create a foreign key on the 0..1 side of the association but hide the foreign key. A better approach is this:

  • Start a new model
  • Add the entity that goes on the 1 side of the association, give it a primary key of type integer. Make sure the StoreGeneratedPattern property is set to Identity.
  • Add the entity that goes on the 0..1 side of the assocation, name the primary key as you would a foreign key, make it of type integer. Make sure the StoreGeneratedPattern property is set to None.
    image
  • Click on the 1 entity and add an association, make it a 1-to-0..1, example:
    image
  • Double click the association and set a referential constraint.
    image
  • Now you’re ready to generate your database schema.
#    Comments [0] |
# Monday, June 20, 2011

SQL Server: Getting table size for all tables

Here is a script for getting size information on every table in your SQL Server database. Based on a script by Mitchell Sellers, this script also works if you have multiple schemas in your database:

DECLARE @TableName VARCHAR(100)    --For storing values in the cursor
 
 --Cursor to get the name of all user tables from the sysobjects listing
DECLARE tableCursor CURSOR
 FOR 
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
 AS SchemaTable
 FROM sys.tables where type_desc = 'USER_TABLE'
FOR READ ONLY
 
--A procedure level temp table to store the results
CREATE TABLE #TempTable
 (
     id int identity,
     tableName varchar(100),
     numberofRows varchar(100),
     reservedSize varchar(50),
     dataSize varchar(50),
     indexSize varchar(50),
     unusedSize varchar(50)
 )
 
--Open the cursor
OPEN tableCursor
 
--Get the first table name from the cursor
FETCH NEXT FROM tableCursor INTO @TableName
 
--Loop until the cursor was not able to fetch
WHILE (@@Fetch_Status >= 0)
BEGIN
     --Dump the results of the sp_spaceused query to the temp table
     INSERT  #TempTable
         EXEC sp_spaceused @TableName
     UPDATE #TempTable set tableName = @TableName where id = @@identity 
     --Get the next table name
     FETCH NEXT FROM tableCursor INTO @TableName
END
 
--Get rid of the cursor
CLOSE tableCursor
DEALLOCATE tableCursor
 
--Select all records so we can use the results
SELECT * 
FROM #TempTable
ORDER BY tableName
 
--Final cleanup!
DROP TABLE #TempTable
 
GO
#    Comments [0] |