# 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]
select name,recovery_model_desc from sys.databases
Alter database [YourDatabaseName] SET RECOVERY SIMPLE
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).


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


Each ‘field’ has properties set:


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
-- <snip other tables>
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [Id] in table 'Artists'
ALTER TABLE [dbo].[Artists]
-- <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.
  • Click on the 1 entity and add an association, make it a 1-to-0..1, example:
  • Double click the association and set a referential constraint.
  • 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
SELECT '['+SCHEMA_NAME(schema_id)+'].['+name+']'
 AS SchemaTable
 FROM sys.tables where type_desc = 'USER_TABLE'
--A procedure level temp table to store the results
     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)
     --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
--Get rid of the cursor
CLOSE tableCursor
DEALLOCATE tableCursor
--Select all records so we can use the results
FROM #TempTable
ORDER BY tableName
--Final cleanup!
#    Comments [0] |
# Monday, June 13, 2011

Maine Code Camp #2

The dates are set and confirmed! We have the Mt. Blue Campground booked for July 29th and July 30th. We'll be tenting, presenting and hanging out! If you're interested in speaking or attending the second Maine Code Camp then please email: mark.blomsma@maine-devnet.org. We'll be tenting, presenting and hanging out! More information to follow!

Update: Just to be clear, the code camp will be Friday to Sunday from the 29th to the 31st, with two nights spend at Mt. Blue State Park.

#    Comments [0] |
# Thursday, June 09, 2011

Madam Silverlight

Just wanted to call out attention to a new Silverlight site created by Maine’s own Carolyn Smith: www.silverlightmadam.com

“Silverlight Madam is the creation of Carolyn Smith. For many years Carolyn's preferred medium was watercolors. Then she discovered computer graphics and now she specializes in creating art in Silverlight.”

Note: Carolyn also runs the site www.pixycolors.com.

#    Comments [0] |
# Tuesday, June 07, 2011

Fixing Skype [Windows]

I just had Skype crashing on me every time it tried to connect and go online. The following worked for me (on Windows 7):

1. If the Skype icon is displayed in the system tray at the bottom right of the screen, right-click it and select Quit.
2. Click Start, type "run" and press Enter. (On Windows XP: Click Start and then Run.)
3. Type "%appdata%\skype" and click OK.
4. Locate and delete the file shared.xml. The file may be displayed as shared if file extensions are not displayed by default on your computer.
5.If you cannot find this file:
-> Click Start, type "run" and press Enter. (On Windows XP: Click Start and then Run.)
-> Type "control folders" and click OK.
-> In the View tab, ensure that Show hidden files and folders is enabled.
-> Repeat the instructions from the beginning.
6. Restart Skype.
7. Choose ‘Check for Updates’ from the ‘Help’ menu. Perform upgrade to the latest version.

#    Comments [0] |
# Thursday, May 05, 2011

IT Outsourcing to Bangladesh

Gartner is mentioning Bangladesh as a country that is growing when it comes as a place for outsourcing IT. Omnext was part of a Dutch trade delegation that went down to Bangladesh to explore opportunities. This article (in Dutch) has the details. Omnext delivers software and services to create an MRI-scan of your software. This can be used in outsourcing projects to measure progress, quality and complexity.

#    Comments [1] |
# Monday, May 02, 2011

Augusta Business Intelligence Event, May 16th, 2011

On May 16th the Maine Developer Network will be hosting the Augusta Business Intelligence Event and you're invited to attend.

Thanks goes to John Gagnon for putting together a great event! Here is the tentative agenda for the day:

8:30am - 9:00am Registration (and Breakfast if we find a sponsor)  
9:00 am - 10:00 am Designing the Business Process Dimensional Model  
10:10 am - 11:30 am ETL System Physical Design -
11:40 am - 12:40 am Lunch
12:40 pm - 2:00pm Designing the Analysis Services OLAP Database - Slava Kokaev
2:10 pm - 3:20pm  Interactive Dashboards with PerformancePoint 2010 - Sunil Kadimdiwan
3:30 pm - 4:30pm Custom BI Applications and Interactive Dashboards -  Slava Kokaev

Slava Kokaev - Principal BI Developer/Architect at Industrial Defender, specializing in Design and Development of Business Intelligence Systems, Custom BI Web Applications and BI Integration. Slava is a Boston Microsoft Business Intelligence User Group leader, SQL Server Community and INETA Regional speaker.

Sunil Kadimdiwan - has 25+ years' experience in architecting and implementing database solutions. He has deep knowledge of the Microsoft SQL Server and Business Intelligence technology stack. He is a frequent speaker at Microsoft sponsored code camps and user group meetings in the New England region.

The event will be held at:
Central Main Commerce Center
Florian Auditorium
45 Commerce Drive
Augusta, ME

Go to www.maine-devnet.org/Home/SignUpForEvent.aspx to sign up and find for more information.

#    Comments [0] |
# Thursday, March 31, 2011

Example of TaskSchedular.UnobservedTaskException in action

Today I had a little bit of challenge trying to demonstrate the behavior of TaskSchedular.UnobservedTaskException. TaskSchedular.UnobservedTaskException can be used to deal with any unhandled exception that occurs during the execution of a task. The event fires when the garbage collector tries to clean up the task. My initial code was good, but I forgot to wait for the task to be done before forcing the GC to do its job Smile

The code below is an effective example of how TaskSchedular.UnobservedTaskException works.

1: public  class  Example 
2: {
3:     public  void  Test()
4:     {
5:         Task  t = new  Task ( delegate 
6:         {
7:             Console .WriteLine( "Do test, just before exception."  );
8:             throw  new  Exception ();
9:         } );
10:         t.Start();
12:     }
13: }
15: class  Program 
16: {
17:     static  void  Main( string [] args )
18:     {
19:         TaskScheduler .UnobservedTaskException += new  EventHandler <UnobservedTaskExceptionEventArgs >( TaskScheduler_UnobservedTaskException );
21:         Example  example = new  Example ();
22:         example.Test();
24:         Thread .Sleep( 2000 ); // delay is needed to make sure the task is done before calling GC. 
25:         Console .WriteLine( "Done sleeping"  );
27:         GC .Collect();
28:         GC .WaitForPendingFinalizers();
30:         Console .ReadLine();
31:     }
33:     static  void  TaskScheduler_UnobservedTaskException( object  sender, UnobservedTaskExceptionEventArgs  e )
34:     {
35:         Console .WriteLine( "Error."  );
36:         e.SetObserved();
37:     }
38: }
#    Comments [0] |
# Thursday, March 17, 2011

Better code through code contracts

I’ll be speaking at the Bangor Developers meeting next week (March 22nd) about code contracts. The session is all about improving code reliability and predictability using .NET code contracts. Additionally Mark will demonstrate that using a tool like code contracts static analysis essentially helps you do a thorough code review of your own code. If there is time he’ll also do a demo of the Visual Studio Productivity Power Tools.

#    Comments [0] |
# Thursday, March 10, 2011

Installing Visual Studio SP1

For you benefit and amusement: here is my experience with upgrading to Visual Studio 2010 Service Pack 1.




10 minutes later:


Another 25 minutes later:


NOTE: If you are working on a Word document while installing the Visual Studio Tools for Office then be warned that the installer will automatically shutdown Word when it reaches this step! I lost a bunch of changes because of this! Sad smile


Restart required:


Reboot complete… start Visual Studio 2010 and check the Help | Info screen:


Life is good!

I’ve checked my DevExpress add-in and also the Code Contracts add-in that I’ve got installed and both seem to be working fine. Nice!

#    Comments [0] |
# Wednesday, March 09, 2011

Visual Studio 2010 SP1 + Team Foundation Server SP1 available

Visual Studio 2010 Service Pack 1 and also Team Foundation Server Service Pack 1 are now available! More information about enhancements offered in this release can be found on Somasegar’s blog and Brian Harry’s blog.

Change lists can be found here:

Go to the MSDN download center for immediate downloading.

#    Comments [0] |
# Friday, February 25, 2011

SDN Event on Friday March 18th at Achmea Conferentie Center in Zeist, NL.

The agenda for the upcoming SDN Event has been published and is looking good!


Go here to sign up.

#    Comments [0] |
# Thursday, February 24, 2011

Amazon RDS for C# Developers

Nice! My article on Amazon Relational Data Services has been published on the Amazon AWS website.

Read the article here: http://aws.amazon.com/articles/9979097549052401/177-0027339-2797707

#    Comments [2] |
# Thursday, February 17, 2011

Single hostname gets better search ranking

I just learned something about Search Engine Optimization: if you have two domains for the same site then this will negatively impact your site ranking.

So I have http://www.develop-one.net, but my provider also automatically offers http://develop-one.net as an address for the same site.

By implementing some code to offer a 301 Redirect to anyone visiting the site (most importantly any site crawler looking to index the site) will be forwarded to the www address.
A couple of lines of code in the master page did the trick.

if ( Request.Url.Host == "develop-one.net" )
    Response.Status="301 Moved Permanently";
    Response.AddHeader( "Location", @”http://www.develop-one.net” );

#    Comments [1] |
# Tuesday, February 15, 2011

New England Code Camp 15

I’m happy to copy this information and pass along word that the date is set and venue reserved for the 15th New England Code Camp, a free, full day of knowledge sharing and networking! (What is a Code Camp?)

New England Code Camp 15 CodeCamp
Saturday, May 7th, 2011
201 Jones Road, 6th floor
Waltham, MA

Registration and the Calls for Speakers and Sponsors will be coming later, but in the meantime, mark your calendar and get ready to join hundreds of your fellow developers for this great community event!


Special thanks to Patrick Hynds for volunteering to lead organization of NECC15 (as he did for NECC14)!

#    Comments [1] |
# Tuesday, January 18, 2011

Entity Framework 4 : ContextOption.LazyLoadingEnabled

Entity Framework 4 enables lazy loading of entities by default. I’m not going to argue about whether that is good or bad, but there is something you should be aware of. If you’re like me, then over the years you’ll have learned that most classes that implement IDisposable should be used using a ‘using’ statement. This is especially true if you’re connecting to a database. So using Entity Framework your code may look something like this:

1: using  ( MyEntities  db = new  MyEntities () )
2: {
3:     var  query = from  e in  db.Employees
4:                 where e.EmployeeId == employeeId
5:                 select  e;
7:     return  query.SingleOrDefault();
8: }

This code will run fine and return a single employee. If however the Employee entity has a relationship things get a little interesting. Suppose the Employee has a relationship with a Department entity (via a property named ‘Department’). The department does not get loaded because db.LazyLoadingEnabled is true (by default).

Now suppose the above code is part of a WCF operation. The WCF operation want to return the Employee to the caller. Here is what happens: When WCF starts serializing the Employee object it sees the Department property and will try to access the property, since it setup to do lazy loading it will now go back to the database to load the department row. BUT hold on, the ‘using’-statement has already disposed of the object context and closed the database connection. What is the error that you’ll see? Well it starts with a CommunicationException: “The underlying connection was closed: The connection closed unexpectedly”.


This may throw you off and make you look for a WCF issue, but you’ll be looking in the wrong area. The actual cause of the error is on the server and the fact that the ObjectContext has been disposed yet is being used.

One solution would be to increase the lifespan of the object context and not dispose of it. This, to me, feels wrong. So instead I’ll just disable lazy loading.This can be done in the code:

1: using  ( MyEntities  db = new  MyEntities () )
2: {
3:     db.ContextOptions.LazyLoadingEnabled = false ;
5:     var  query = from  e in  db.Employees
6:                 where  e.EmployeeId == employeeId
7:                 select  e;
9:     return  query.SingleOrDefault();
10: }

Or you can go to the designer and change the default:


Note: I’m note sure why lazy loading enabled is set to ‘True’ by default (but it is on my machine). According to the documentation (http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontextoptions.lazyloadingenabled(VS.100).aspx) it should default to false.

#    Comments [5] |