# 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.

image

image

image

10 minutes later:

image

Another 25 minutes later:

image

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

image

Restart required:

image

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

image

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!

image

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” );
    Response.End();
}

#    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
Microsoft
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!

468IMAGE_129IMAGE_128

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;
6: 
7:     return  query.SingleOrDefault();
8: }
9: 

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”.

image

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 ;
4: 
5:     var  query = from  e in  db.Employees
6:                 where  e.EmployeeId == employeeId
7:                 select  e;
8: 
9:     return  query.SingleOrDefault();
10: }

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

image

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] |
# Saturday, January 01, 2011

Goals for 2011

Today seems like a good day to set some geek goals for 2011.

  1. I want to master (at least) two new platforms. Currently on my thoughts are:
    1. A Windows Azure application
    2. A Facebook application
    3. … anyone want to suggest another platform worthy of attention?
  2. I want to master (at least) two new technology stacks:
    1. ASP.NET MVC3 & Razor
    2. … suggestions?
  3. I want to do at least 6 Live Meetings for the Maine Developer Network.
  4. I want to help make the 2nd Maine Code Camp happen.
  5. I want to get another Microsoft professional developer certification.
  6. I want to write at least 4 technical articles this year.
  7. I’d like to build a line of business WCF service with F# and fully understand to pros and cons.
  8. I’d like to write at least one extensive blog entry every month.

Let’s see how 2011 goes.. Smile

#    Comments [4] |

The 2011 Microsoft® MVP Award

I just received the magic email: I've been awarded the MVP Award 2011! It's an honour to receive the award, thank you Microsoft!

"Congratulations! We are pleased to present you with the 2011 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual C# technical communities during the past year."

#    Comments [0] |
# Wednesday, December 29, 2010

IE9 and VS2010 debugging issue (DNS error)

Etienne Trembley found the solution to a problem that’s been haunting me since I installed IE9 beta. As it turns out IE9 prefers IPv6 over IPv4 AND on a Windows 7 64bit machine the hosts file (in c:\windows\system32\drivers\etc) does not provide an IPV4 entry to make localhost look at 127.0.0.1. Adding the localhost entry in the host file solves the issues!

Read the full post here: http://geekswithblogs.net/etiennetremblay/archive/2010/10/07/ie-9-cassini-and-the-dreaded-dns-error-or-page.aspx

#    Comments [0] |
# Friday, December 10, 2010

ASP.NET Stack Overflow leads to redirect to login page

I ran into a problem yesterday that took me a while to figure out and Bing and Google were no help, so here is a blog post for those unfortunate souls that run into the same issue.

Application:
ASP.NET website running on Internet Information Server using both Windows Authentication as well as Forms Authentication.

Symptoms:
A action on the site leads to some processing on the server. Suddenly, in mid processing, the browser will redirect to the login page (or attempt to get new Windows credentials).
Log files show no error what so ever, and try/catch around the code in the event handler does not catch a problem.

Cause:
A stack overflow on the server completely kills the process. There is no error handling. No entry in the log file. IIS steps in and starts up a new w3wp.exe process.
The browser detects that your session is lost and redirects to the login page to ask for credentials.

#    Comments [0] |
# Thursday, December 09, 2010

Augusta Developer Event, December 16th 2010

You are here by invited for the Augusta Developer Event on December 16th in Augusta, ME.

Location:
41 Anthony Ave
Augusta, ME.

Date:
December 16th, 2010.

Time:
Everyone is welcome starting at 9am, sessions will start at 9:30am.
Lunch will be at 12pm, pizza will be provided.
Sessions will resume at 12:30pm.
Door prizes will be drawn at 3:45pm.
End of event at 4pm.

Speakers:
We have two confirmed speakers at this time:
- Chris Bowen, developer evangelist for Microsoft and friend of the Maine Developer Network
- Mark Blomsma, software architect for Develop-One and co-organizer of the Maine Developer Network

Sessions:
The exact session descriptions are still a little up in the air,
but we expect to cover the following topics:
- ASP.NET MVC 3
- C# 4.0
- Silverlight
- Cloud Computing
- Windows Azure
- SQL Azure
- HTML 5
- Windows Phone 7
And most likely some more topics, but we're still working on the exact agenda
(which will be posted on the site as soon as we have it).

Register:
Please let us know if you plan to attend (so we can ensure seating and pizzas!):
http://www.maine-devnet.org/Home/SignUpForEvent.aspx

#    Comments [0] |
# Thursday, December 02, 2010

Books on Windows Phone 7 development

Here are some books for people that are looking to get into Windows Phone 7 development (some are pre-order only at this time):

[Update]
There is a free eBook version of Programming Windows Phone 7 by Charles Petzold which can be downloaded here (thanks for Greg Howe for the link).

#    Comments [0] |

Software Developer Event December 13th 2010

For my European friends and readers: don’t forget that December 13th the SDN will be organizing another Software Developer Event.  The agenda is below, go here to register.

image

#    Comments [0] |
# Thursday, October 21, 2010

DiscountASP offers hosted TFS

My favorite hosting provider now also offers hosted Team Foundation Server. DiscountASP.NET is offering hosted TFS at $20 per user per month. Check it out.

#    Comments [2] |
# Wednesday, October 20, 2010

Reporting using Entity Framework

For many years the mantra for implementing business logic in your line of business application has been: “don’t put it in the database, don’t put it in the user interface”. In other words, apply the layers design pattern if at all possible, together with implementing the Model-View-ViewModel (MVVM) or Model-View-Controller (MVC) pattern. Technologies like Entity Framework help us convert data in the database to .NET objects and add logic. Life is good.

Then it is time to create a report. Traditionally reports are run against the database and any self respecting reporting technology will to this day still offer you the option of building a report by querying directly against the database. Out the door goes the reuse of your .NET based business logic, right? No need to fear, Visual Studio offers a solution. Starting with Visual Studio 2005 Microsoft started shipping the ReportViewerControl with Visual Studio. Where SQL Server Reporting Services is full fledged reporting solution, with it’s own server, scheduling engine, user interface, the ReportViewerControl is only a small part of the food chain. The ReportViewerControl will render a report defined by an RDLC file against the data you feed into it. The data can still come from a database, but also from a WCF Service, any .NET object or SharePoint.

Let’s look at a sample. The sample will work on the AdventureWorks2008R2 database which can be downloaded from CodePlex. I’ve then created two views: CustomerView and OrderView. These views limit the data to Massachusetts and join a couple of table to make for more demo-friendly data.

The following script will add the two views that we’ll be using:


USE [AdventureWorks2008R2]
GO
 
/****** Object:  View [dbo].[CustomerView]    Script Date: 01/21/2011 05:53:18 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[CustomerView]'))
DROP VIEW [dbo].[CustomerView]
GO
 
/****** Object:  View [dbo].[CustomerView]    Script Date: 01/21/2011 05:53:18 ******/
SET ANSI_NULLS ON
GO
 
SET QUOTED_IDENTIFIER ON
GO
 
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[CustomerView]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[CustomerView]
AS
SELECT DISTINCT Sales.Customer.AccountNumber, Person.Person.LastName, Person.Person.FirstName, Sales.Store.Name AS StoreName, Sales.Customer.CustomerID
FROM         Sales.Customer INNER JOIN
                      Person.Person ON Sales.Customer.PersonID = Person.Person.BusinessEntityID INNER JOIN
                      Sales.Store ON Sales.Customer.StoreID = Sales.Store.BusinessEntityID INNER JOIN
                      dbo.OrderView ON Sales.Customer.CustomerID = dbo.OrderView.CustomerID
' 
GO
 
/****** Object:  View [dbo].[OrderView]    Script Date: 01/21/2011 05:54:51 ******/
IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[OrderView]'))
DROP VIEW [dbo].[OrderView]
GO
 
/****** Object:  View [dbo].[OrderView]    Script Date: 01/21/2011 05:54:51 ******/
SET ANSI_NULLS ON
GO
 
SET QUOTED_IDENTIFIER ON
GO
 
IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[OrderView]'))
EXEC dbo.sp_executesql @statement = N'CREATE VIEW [dbo].[OrderView]
AS
SELECT     Sales.SalesOrderHeader.SalesOrderID, Sales.SalesOrderHeader.CustomerID, Production.Product.Name AS ProductName, Sales.SalesOrderDetail.OrderQty, 
                      Sales.SalesOrderDetail.UnitPrice, Sales.SalesOrderDetail.UnitPriceDiscount, Sales.SalesOrderDetail.LineTotal, Person.Address.AddressLine1, 
                      Person.Address.AddressLine2, Person.Address.City, Person.Address.PostalCode, Person.StateProvince.StateProvinceCode, Person.Address.SpatialLocation
FROM         Person.StateProvince INNER JOIN
                      Person.Address ON Person.StateProvince.StateProvinceID = Person.Address.StateProvinceID AND 
                      Person.StateProvince.StateProvinceID = Person.Address.StateProvinceID AND Person.StateProvince.StateProvinceID = Person.Address.StateProvinceID INNER JOIN
                      Sales.SalesOrderDetail INNER JOIN
                      Sales.SalesOrderHeader ON Sales.SalesOrderDetail.SalesOrderID = Sales.SalesOrderHeader.SalesOrderID INNER JOIN
                      Production.Product ON Sales.SalesOrderDetail.ProductID = Production.Product.ProductID ON 
                      Person.Address.AddressID = Sales.SalesOrderHeader.ShipToAddressID
WHERE     (Person.StateProvince.StateProvinceCode = N''MA'')
' 
GO

Next step is to create a WCF service application, add an Entity Framework model and drag the two views onto the model:
image
Next we’ll implement two methods to use the Entity Framework model to select the data and return a list of CustomerView or OrderView objects. 
Note: Normally you would not select all the contents in a view, but since we know that the number of rows in our views are already limited in numbers there is no problem here.

1: using  System;
2: using  System.Collections.Generic;
3: using  System.Linq;
4: using  System.Runtime.Serialization;
5: using  System.ServiceModel;
6: using  System.ServiceModel.Web;
7: using  System.Text;
8: 
9: namespace  AdventureServices
10: {
11:     public  class  AdventureService  : IAdventureService 
12:     {
13: 
14:         #region  IAdventureService Members
15: 
16:         public  List <CustomerView > GetReportCustomerData()
17:         {
18:             using  ( AdventureEntities  db = new  AdventureEntities () )
19:             {
20:                 var  query =  from  customer in  db.CustomerViews select  customer;
21:                 return  query.ToList();
22:             }
23:         }
24: 
25:         public  List <OrderView > GetReportOrderData()
26:         {
27:             using  ( AdventureEntities  db = new  AdventureEntities () )
28:             {
29:                 var  query = from  customer in  db.OrderViews select  customer;
30:                 return  query.ToList();
31:             }
32:         }
33: 
34:         #endregion 
35:     }
36: }
37: 
38: 

Next step is to create a report client. We can use any Windows or ASP.NET application and add start using the ReportViewerControl, but Visual Studio also offers a report application template. Very useful for quick demos:

image

Create the project (skip the wizard), then delete the Report1.rdlc. Add service reference to you AdventureServices and then add a new report using the Report Wizard (on my machine I’ve had poor luck adding the service reference as part of the wizard steps.

image

On the first screen of the wizard give the dataset a name (CustomerDataSet), select the service reference as a datasource and pick CustomerView as the available dataset.

image

On the next screen drag the fields we want to display to the ‘Value’ grid. More complex grouping per row and column is also possible.

image

Since we’re doing a very basic report the next screen offers no selectable options, although we’re starting to see part of our report.

image

Next we pick a style. There are a couple to choose from.

image

We click finish to close the wizard.  Our report looks like this:

image

Use the designer and the tool box to enhance the report just a little:

image

Now the next step is to make sure our form will display this report. Go to the Form1 designer, select the ReportViewerControl and look for the smart tag in the top right hand corner of the control.
Activate the smart tag and you’ll see that you have to option to select a report. Select the report you’ve just created:

image

Notice how at the bottom of the forms designer there now is a design time control:

image

The design time binding source allows us to feed data into the report. So far the ‘links’ that we created to the service have only been used to pull in the schema of the data to be used. The actual data needs to be fed into the report when the form is run. For this we implement a call to our AdventureService:

1: using  System;
2: using  System.Collections.Generic;
3: using  System.ComponentModel;
4: using  System.Data;
5: using  System.Drawing;
6: using  System.Text;
7: using  System.Windows.Forms;
8: 
9: namespace  AdventureReports
10: {
11:     public  partial  class  Form1  : Form 
12:     {
13:         public  Form1()
14:         {
15:             InitializeComponent();
16:         }
17: 
18:         private  void  Form1_Load(object  sender, EventArgs  e)
19:         {
20:             using  ( AdventureServiceReference.AdventureServiceClient  client = new  AdventureServiceReference.AdventureServiceClient () )
21:             {
22:                 this .CustomerViewBindingSource.DataSource = client.GetReportCustomerData();
23:             }
24:             this .reportViewer1.RefreshReport();
25:         }
26:     }
27: }
28: 

Note: Even though our service does not take any parameters to filter the data I hope you can see that it would only take a small amount of coding to add a couple of fields to the form and pass any kind of selection to the service. I leave the actual implementation of that up to you, when you’re building your ‘real’ report.

#    Comments [0] |

Microsoft Reporting Technologies

The presentation I did on 10-19-2010 at the Bangor Area .NET Developer meeting about SQL Server Reporting Services, Local Reports and Entity Framework can be found here.

#    Comments [2] |
# Tuesday, October 19, 2010

Reporting Technologies

Jay Taplin, Jeff Hall and me will be presenting tonight on respectively Crystal Reports, DevExpress XtraReports and SQL Reporting Services. Sign up to come and see us! (note: the pizza is free! Smile ).

#    Comments [0] |
# Sunday, September 12, 2010

Playing around with Windows Live Sync 2011 beta

I have been an avid user of Mesh and was so pleased with the beta that I was hesitant to switch to Windows Live Sync 2011 beta. But since the Mesh page started saying that the service is to be replaced I figured I ‘d better get my machines switched over.

For those who don’t know: Live Sync allows you to synchronize folders between devices. Aside from syncing between devices you can also sync with Skydrive. I personally use it so I can have all my files at home as well as at the office at the same time.

Below is a picture of me syncing my Dwinal Pond 4 Seasons Club files with Skydrive. (to make sure I always have a backup).

image

Another cool feature which I use a lot is the remote desktop. By having Live Sync installed on my machine at the office I can access that machine using an HTTP remote desktop connection. It’s all via the Live Sync service, so the machine just needs to be turned on and it’s ready to go, no complicated mappings in the firewall at the office. You may want to check with you IT guy to see how he feels about the security risks, but for me this works really well (I do make sure that my Windows Live, Facebook and Google passwords are all different!).

The picture below show just my local machine, because the machine at the office hasn’t been upgraded yet).

image

#    Comments [0] |