# Wednesday, February 29, 2012

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

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] |
# 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] |
# 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] |
# 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] |
# 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] |
# 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] |
# Thursday, May 27, 2010

Learning more about Unit Testing

I just had an email in my inbox recommending "The Art of Unit testing" by Roy Osherove. I guess I’ll put in another order at Amazon. :-)

I've been doing unit testing for a long time, but since I'm largely self-taught I can probably learn something. Perhaps I’ll even sign up for a course at DevelopMentor. I know all the basics, I feel the biggest challenge with unit testing larger applications is managing test data.

#    Comments [0] |
# Tuesday, May 25, 2010

Opening up Outlook .pst files

Microsoft has announced two open source solutions for accessing Outlook .pst files. Read the press release here: http://www.microsoft.com/presspass/press/2010/may10/05-24PSTToolsPR.mspx

I’ve been able to find the following on Codeplex:

PSTViewTool : http://pstviewtool.codeplex.com/

PST SDK: http://pstsdk.codeplex.com/  [Thanks to Greg!]

Also, doing a search for Outlook on CodePlex offers a lot of solutions for looking at Outlook data or integrating with Outlook: http://www.codeplex.com/site/search?query=outlook

Update: Added the PST SDK.

#    Comments [4] |
# Monday, February 08, 2010

Visual Studio 2010 RC and Team Foundation Server 2010 RC available

Both Visual Studio 2010 RC as well a Team Foundation Server 2010 RC are available to MSDN Subscribers as of today.
Go to: http://msdn.microsoft.com/en-us/subscriptions/downloads/default.aspx

If you want to provide feedback on this release then you do so by using Microsoft Connect.
Go to: https://connect.microsoft.com/VisualStudio

For any additional information about versions of Visual Studio 2010 and .NET Framework 4,
Go to: Visual Studio 2010 and .NET Framework 4 Release Candidate

#    Comments [0] |
# Tuesday, February 02, 2010

MDN - Augusta Developer Event, 24th of February 2010

Time for the first Augusta Developer Event of 2010. Join us for a morning filled with information about Silverlight. Shawn, Chris and Mark will present a variety of topics and we've planned a group discussion, so make sure you come prepared with questions, examples and your experiences.

When
February 24th, 2010 at 9:00am.

What is Silverlight?
Shawn Robichaud – 15 min
Introduction to Silverlight for decision makers, architects and developers.

Choosing the right technology
Mark Blomsma - 30 min
Silverlight vs. WFP vs. Windows Forms vs. ASP.NET. A session for decision makers, architects and developers. Which technology to use for which scenario?

Choosing the right technology – group discussion
Everyone - 30 min
Silverlight vs. WFP vs. Windows Forms vs. ASP.NET. A session for decision makers, architects and developers. Which technology would YOU use for which scenario? Please come prepared with questions, examples and ready to share your experiences.

Silverlight and Section 508 compliance
Mark Blomsma – 30 min
“Section 508 requires that all Web site content be equally accessible to people with disabilities. This applies to Web applications, Web pages and all attached files. It applies to intranet as well as public-facing Web pages.” (http://usability.gov).

Silverlight architecture overview
Chris Bowen – 30 min
Introduction to XAML, Silverlight assemblies, n-tier development, asynchronous behavior, …

Silverlight + Windows Communication Foundation overview
Chris Bowen - 30 min
Introduction to WCF based on a Silverlight demo.

Silverlight + RIA Service overview
Chris Bowen - 30 min
Introduction to RIA Services based on a Silverlight demo.

Wrap up
15 minutes.

 

Location
The event will be held at:
State of Maine Offices
Harlow Building
First floor conference room
18 Elkins Ave
Augusta

RSVP
Please register so we can make sure we have sufficient room.
Register here: http://www.maine-devnet.org/Home/SignUpForEvent.aspx.

#    Comments [0] |
# Friday, January 01, 2010

MVP 2010

Whoah! Just received an email from PJ:

“We are pleased to present you with the 2010 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.”

I’ve once again been honored with the Microsoft Most Valuable Professional Award. This is the seventh year running that I’ve been lucky enough to receive this great award and I it’s great to be part of the group of people that receive this award.

#    Comments [1] |
# Thursday, November 05, 2009

Get the latest version of the .NET Framework on your machine

Scott Hanselman put up a page to help you detect whether you’re running the latest version of .NET available and also helps you figure out what the smallest version is tha you can download.

Go to http://www.hanselman.com/smallestdotnet/ for more information.

 

#    Comments [0] |
# Tuesday, October 20, 2009

Team Foundation Server 2010 Basic to replace SourceSafe

Brian Harry has a post on a little gem called Team Foundation Server 2010 Basic. Price and such is not yet know, but it is set to be a replacement for Visual SourceSafe.

TFS 2010 Beta 2 is available for download (if you’re an MSDN subscriber).

Read the more here: http://blogs.msdn.com/bharry/archive/2009/10/01/tfs-2010-for-sourcesafe-users.aspx

#    Comments [0] |

Visual Studio 2010 Beta 2 available to MSDN Subscribers

VS2010MSDNBeta2

Go to: http://msdn.microsoft.com to start downloading (I’m at 15% right now :-) ).

If you’re a little confused about the rebranding, then go here for a nice overview of the new names and how they replace previous versions.

The MSDN Visual Studio 2010 page can be found here.

#    Comments [0] |
# Monday, October 19, 2009

Registration for the 4th quarter MSDN (.NET) Northeast Roadshow has just opened up!

clip_image001Registration for the 4th quarter MSDN (.NET) Northeast Roadshow has just opened up!  This totally FREE event will be held on Tuesday, December 15th.   Thankfully, we were able to secure more convenient hours this time around.  The event will run from 9:00 am thru 3:30 pm in the Florian Hall of the Central Maine Commerce Center in Augusta. (a.k.a. Public Safety/M.E.M.A)  These events target .NET developers and analysts, or those actively training to become one.  Microsoft Developer Evangelists Chris Bowen and Jim O’Neil will be making the drive up from their regional offices in Massachusetts in order to lead the presentations.

 

AGENDA

•    WCF (Windows Communications Foundation)
•    Silverlight RIA (Rich Internet Applications) and the MVVM design pattern (Model-View-ViewModel)
•    Where to find help when you get stuck.
•    LINQ  (Language INtegrated Query)
•    ASP .NET Webforms and AJAX

Please register in advance by using the following link:
http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032429336&Culture=en-US

#    Comments [0] |
# Sunday, October 18, 2009

Windows 7 resources for developers

Jim O’Neil has a great post with a list of links to resources that are useful for developers targeting Windows 7.

Go here: http://blogs.msdn.com/jimoneil/archive/2009/10/17/code-camp-12-7-on-7-resources.aspx

#    Comments [0] |
# Sunday, October 11, 2009

Unblocking assemblies in Windows 7

I just ran into a little problem when attempting to run a Visual Studio unit test on my Windows 7 machine. I downloaded log4net.dll and wanted to use it in a project, but when running the unit test I ran into the following error:

Failed to queue test run 'Mark@L-ONE 2009-10-11 14:08:38': Test Run deployment issue: The location of the file or directory 'c:\users\mark\documents\visual studio 2008\projects\sources\developone.myproject.unittests\bin\debug\log4net.dll' is not trusted.

Turns out that a downloaded file is blocked. You can unblock the file by right clicking the file and choosing “Unblock”.

image

Make sure you remove all copies of the assembly (if you have copy local = true) and then recompile.

#    Comments [0] |
# Tuesday, September 08, 2009

MSDN Northeast Road Show will hit Augusta, ME on 24th of September 2009

Chris and Jim are coming to Maine and this time their bringing their TechNet friend Dan Stolts.
Augusta will be home to the MSDN Northeast Road Show and the TechNet Unleashed tour on the same day!

More info on the event can be found at: http://blogs.msdn.com/cbowen/archive/2009/07/20/announcing-the-fall-2009-northeast-msdn-roadshow.aspx

Note: You need to register separately for the MSDN and TechNet event!

Update [09-10-2009]: Corrected Jim’s name and Dan is the man that is doing the ITPro sessions :-)

#    Comments [1] |
# Wednesday, August 26, 2009

Tools that make a developers life easier

Last night at the BAND (www.bangordevelopers.com) meeting we all did 10 minute presentations on the tool(s) we love as developers.

On my list were: Total Commander, LinqPad, Microsoft Office (codegen with Excel rules :-)), VMWare & VirtualPC, Live Mesh. Also on the list should have been Reflector.

Total Commander

Great tool for FTP-ing files and comparing a local folder hierarchy to the hierarchy on the ftp-server. Also much more reliable in FTP-ing large amounts of files than Windows Explorer.
image

See: www.ghisler.com

LinqPad

A must have for people using LINQ to SQL and Entity Framwork. Helps a lot with figuring out what the exact SQL statement is that get generated from your LINQ statement.
image
See: www.linqpad.net

VMWare Converter, VMWare Workstation and VirtualPC

These tools are invaluable in creating clean testing environments and separating multiple development environments on a single machine. VMWare converter allows you to grab a physical harddrive and convert it into a virtual machine. Very useful for Windows 7 migration scenarios!
See: www.vmware.com, www.microsoft.com/virtualpc

Live Mesh

Is only in beta, but already an invaluable tool for remote desktop connections across firewalls and synchronizing files across (virtual) machines.
See: www.mesh.com

Reflector

.NET Reflector is a tool any serious .NET developer cannot do without. View sources of any .NET library you use in order to track internal workings. Love it!
See: http://www.red-gate.com/products/reflector/

#    Comments [0] |
# Thursday, August 20, 2009

LINQ to Outlook

VSTO offers a number of classes to access Outlook information, but these classes do not implement IEnumerable<T> and are therefore not useable in a LINQ expression.

I wanted to be able to search for appointments using LINQ and write code that looks like this:

var appointments = new Appointments();

var selectedAppointments = from appointment in appointments
                           where appointment.Start <= end    // end is parameter
                           && appointment.End >= start       // start is parameter
                           && appointment.Categories.Contains("Billable")
                           orderby appointment.Start
                           select appointment;

To do this I converted the Items collection in an Outlook Folder to an IEnumerable<Outlook._AppointmentItem>.
The code for the Appointments class looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace Develop_One.OBiOne
{
    /// <summary>
    /// Class to wrap a collection of Outlook.Items as an IEnumerable of Outlook._AppointmentItem.
    /// Doing this allows you to write LINQ queries against the Appointments.
    /// </summary>
    internal class Appointments : IEnumerable<Outlook._AppointmentItem>
    {
        private Outlook.Items _items;

        /// <summary>
        /// Default constructor will use the items in the default Calendar folder to initialize items collection.
        /// </summary>
        internal Appointments()
        {
            var app = new Outlook.ApplicationClass();
            var cal = app.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
            _items = cal.Items;
        }


        #region IEnumerable<_AppointmentItem> Members

        public IEnumerator<Outlook._AppointmentItem> GetEnumerator()
        {
            // use the private AppointmentsEnumerator.
            return new AppointmentsEnumerator(this._items);
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion

        private class AppointmentsEnumerator : IEnumerator<Outlook._AppointmentItem>
        {
            private System.Collections.IEnumerator _items;

            internal AppointmentsEnumerator(Outlook.Items items)
            {
                _items = items.GetEnumerator();
            }


            #region IEnumerator<_AppointmentItem> Members

            public Outlook._AppointmentItem Current
            {
                get
                {
                    return (Outlook._AppointmentItem)_items.Current;
                }
            }

            #endregion

            #region IDisposable Members

            public void Dispose()
            {
                return;
            }

            #endregion

            #region IEnumerator Members

            object System.Collections.IEnumerator.Current
            {
                get
                {
                    return (Outlook._AppointmentItem)_items.Current;
                }
            }

            public bool MoveNext()
            {
                bool result = _items.MoveNext();
                while (_items.Current is Outlook._AppointmentItem == false && result == true)
                {
                    result = _items.MoveNext();
                }
                return result;
            }

            public void Reset()
            {
                _items.Reset();
            }

            #endregion
        }


    }
    

}
#    Comments [1] |

Paste from Visual Studio

I just came across a nice add-on for Windows Live Writer which allows you to paste colorized source from Visual Studio.

Download it here: http://gallery.live.com/liveItemDetail.aspx?li=d8835a5e-28da-4242-82eb-e1a006b083b9&bt=9&pl=8

#    Comments [0] |

Some useful DateTime extensions

I’m doing some work where a user can select data based on choice like “This week” and “Last month”. I wrote a bunch of extension methods that are pretty generic and may be useful for others.

Here is is:

public static class DateTimeExtensions
{
    /// <summary>
    /// Return the date that is the start of the week relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfWeek(this DateTime date)
    {
        DayOfWeek day = date.DayOfWeek;
        int days = day – CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek;
        DateTime start = date.AddDays(-days);
        return start.Date;
    }

    /// <summary>
    /// Return the date that is the start of the week relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfLastWeek(this DateTime date)
    {
        return date.GetStartOfWeek().AddDays(-7);
    }

    /// <summary>
    /// Return the date that is the end of the week relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfWeek(this DateTime date)
    {
        return date.GetStartOfWeek().AddDays(6);
    }

    /// <summary>
    /// Return the date that is the end of the week relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfLastWeek(this DateTime date)
    {
        return date.GetEndOfWeek().AddDays(-7);
    }

    /// <summary>
    /// Return the date that is the start of the month relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, 1);
    }

    /// <summary>
    /// Return the date that is the start of previous month relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfLastMonth(this DateTime date)
    {
        return date.GetStartOfMonth().AddMonths(-1);
    }

    /// <summary>
    /// Return the date that is the end of the month relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfMonth(this DateTime date)
    {
        return new DateTime(date.Year, date.Month, date.GetDaysInMonth(), 23, 59, 59, 999);
    }

    /// <summary>
    /// Return the date that is the start of previous month relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfLastMonth(this DateTime date)
    {
        return date.GetStartOfLastMonth().GetEndOfMonth();
    }

    /// <summary>
    /// Returns the number of days in the month of the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static int GetDaysInMonth(this DateTime date)
    {
        return DateTime.DaysInMonth(date.Year, date.Month);
    }

    /// <summary>
    /// Return the first day of the year relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfYear(this DateTime date)
    {
        return new DateTime(date.Year, 1, 1);
    }

    /// <summary>
    /// Return the first day of the last year relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetStartOfLastYear(this DateTime date)
    {
        return new DateTime(date.Year - 1, 1, 1);
    }

    /// <summary>
    /// Return the last day of the year relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfYear(this DateTime date)
    {
        return new DateTime(date.Year, 12, 31, 23, 59, 59, 999);
    }

    /// <summary>
    /// Return the last day of the last year relative to the specified date.
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetEndOfLastYear(this DateTime date)
    {
        return new DateTime(date.Year - 1, 12, 31, 23, 59, 59, 999);
    }

}
#    Comments [7] |
# Thursday, July 23, 2009

DevelopMentor RSS Feed

I believe the URL has changed, so just in case you lost it… Keep track of blog posts from all the DevelopMentor instructors by subscribing to: http://browse.develop.com/bmsfeed/developmentor http://feeds.feedburner.com/DevelopmentorInstructors

Updated 08-19-2009: Feed is now available at: http://feeds.feedburner.com/DevelopmentorInstructors

#    Comments [0] |
# Monday, July 20, 2009

ReportViewer in VS2010

I’ve been using the ReportViewer control in Visual Studio quite a bit to create RDLC (offline) reports that are based on the result of LINQ queries against object trees. It’s been a while since there has been a new release of this control and Visual Studio 2010 did not include anything major with regards to the ReportViewer control. I asked around and got an email from Robert Bruckner answering my two main questions:

1. Yes, the ReportViewer control in VS2010 will run on both .NET 3.5 as well as .NET 4.0.
2. Yes, the ReportViewer control in VS2010 will support Export to Word for RDLC (offline) scenarios.

Thanks Robert (and the rest of the people working on this technology), great news!

#    Comments [8] |
# Monday, June 08, 2009

Exam objectives for 70-536 with links to MSDN

Copied from : http://www.proprofs.com/forums/index.php?showtopic=11932

 

Microsoft 70-536 Objectives

Objectives as updated on Microsoft's Web site: March 29, 2007

 

Developing applications that use system types and collections
Manage data in a .NET Framework application by using the .NET Framework 2.0 system types (Refer System namespace)

Manage a group of associated data in a .NET Framework application by using collections. (Refer System.Collections namespace)

Improve type safety and application performance in a .NET Framework application by using generic collections. (Refer System.Collections.Generic namespace)

Manage data in a .NET Framework application by using specialized collections. (Refer System.Collections.Specialized namespace)

Implement .NET Framework interfaces to cause components to comply with standard contracts. (Refer System namespace)

Control interactions between .NET Framework application components by using events and delegates. (Refer System namespace)

Implementing service processes, threading, and application domains in a .NET Framework application
Implement, install, and control a service. (Refer System.ServiceProcess namespace)

Develop multithreaded .NET Framework applications. (Refer System.Threading namespace)

Create a unit of isolation for common language runtime in a .NET Framework application by using application domains. (Refer System namespace)

Embedding configuration, diagnostic, management, and installation features into a .NET Framework application
Embed configuration management functionality into a .NET Framework application. (Refer System.Configuration namespace)

Create a custom Microsoft Windows Installer for the .NET Framework components by using the System.Configuration.Install namespace, and configure the .NET Framework applications by using configuration files, environment variables, and the .NET Framework Configuration tool (Mscorcfg.msc).

Manage an event log by using the System.Diagnostics namespace.

Manage system processes and monitor the performance of a .NET Framework application by using the diagnostics functionality of the .NET Framework 2.0. (Refer System.Diagnostics namespace)

Debug and trace a .NET Framework application by using the System.Diagnostics namespace.

Embed management information and events into a .NET Framework application. (Refer System.Management namespace)

Implementing serialization and input/output functionality in a .NET Framework application
Serialize or deserialize an object or an object graph by using runtime serialization techniques. (Refer System.Runtime.Serialization namespace)

Control the serialization of an object into XML format by using the System.Xml.Serialization namespace.

Implement custom serialization formatting by using the Serialization Formatter classes.

Access files and folders by using the File System classes. (Refer System.IO namespace)

Manage byte streams by using Stream classes. (Refer System.IO namespace)

Manage the .NET Framework application data by using Reader and Writer classes. (Refer System.IO namespace)

Compress or decompress stream information in a .NET Framework application (refer System.IO.Compression namespace), and improve the security of application data by using isolated storage. (Refer System.IO.IsolatedStorage namespace)

Improving the security of the .NET Framework applications by using the .NET Framework 2.0 security features
Implement code access security to improve the security of a .NET Framework application. (Refer System.Security namespace)

Implement access control by using the System.Security.AccessControl classes.

Implement a custom authentication scheme by using the System.Security.Authentication classes. (Refer System.Security.Authentication namespace)
Encrypt, decrypt, and hash data by using the System.Security.Cryptography classes. (Refer System.Security.Cryptography namespace)

Control permissions for resources by using the System.Security.Permission classes. (Refer System.Security.Permission namespace)

Control code privileges by using System.Security.Policy classes. (Refer System.Security.Policy namespace)

Access and modify identity information by using the System.Security.Principal classes. (Refer System.Security.Principal namespace)

Implementing interoperability, reflection, and mailing functionality in a .NET Framework application
Expose COM components to the .NET Framework and the .NET Framework components to COM. (Refer System.Runtime.InteropServices namespace)

Call unmanaged DLL functions in a .NET Framework application, and control the marshaling of data in a .NET Framework application. (Refer System.Runtime.InteropServices namespace)

Implement reflection functionality in a .NET Framework application (refer System.Reflection namespace), and create metadata, Microsoft intermediate language (MSIL), and a PE file by using the System.Reflection.Emit namespace.

Send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery from a .NET Framework application. (Refer System.Net.Mail namespace)

Implementing globalization, drawing, and text manipulation functionality in a .NET Framework application
Format data based on culture information. (Refer System.Globalization namespace)

Enhance the user interface of a .NET Framework application by using the System.Drawing namespace.

Enhance the text handling capabilities of a .NET Framework application (refer System.Text namespace), and search, modify, and control text in a .NET Framework application by using regular expressions. (Refer System.Text.RegularExpressions namespace)

#    Comments [0] |
# Wednesday, June 03, 2009

Switching to Bing (and looking at BING API)

Today I’m switching my default search provider in Internet Explorer over to the new Microsoft Search Engine: Bing.

It seems fast, perhaps even faster than Google and with the few searches I’ve done it seems to provide the right results.

Did some quick looking around, there is a Bing developer page and Bing API as well.

Links:

#    Comments [0] |
# Tuesday, June 02, 2009

Loading data from Excel 2007

I’m playing around with code generation using Visual Studio 2008 T4 and I needed to pull in some data. Easiest way to create the data is using Excel and then pull it into a dataset. Using the right connection string this becomes very easy.

The code below shows how to select the data from a worksheet.

public class Excel2007Reader

{

    private static string BuildExcelConnection( string filename )

    {

        return @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + @";Extended Properties=""Excel 12.0;HDR=YES;""";

    }

 

    public static DataSet Read( string filename, string worksheet, string range, string tableName )

    {

        DataSet result = new DataSet();

        string connectionString = BuildExcelConnection( filename );

        string select = @"SELECT * FROM [" + worksheet + "$" + range + "]";

        using ( OleDbConnection conn = new OleDbConnection( connectionString ) )

        {

            conn.Open();

            using ( OleDbCommand cmd = new OleDbCommand( select, conn ) )

            {

                OleDbDataAdapter da = new OleDbDataAdapter( cmd );

                da.Fill( result, tableName );

            }

            conn.Close();

        }

        return result;

    }

}

#    Comments [0] |
# Monday, June 01, 2009

Checking a string for illegal characters using Regular Expressions

In our Maine Microsoft Certification Study Group we recently had a discussion about using regular expression. Today I found myself writing a RegEx to check for illegal characters in a formula (string). I thought I’d share the solution:

private bool FormulaContainsIllegalCharacters( string formula )

{

    bool result = false;

    try

    {

        Regex r = new Regex( @"(!)|(@)|(#)|(\$)|(%)|(&)" );

        result = r.Match( formula ).Success;

    }

    catch { } // ignore any regular expressions errors -> return false

    return result;

}

In my case I’m not interested in handling exceptions. If a technical error occurs I will accept the input. Notice that I needed to put a “\” before the $ sign, since the $ is a reserved character marking the end of a line.
I don’t need to put each character in “( )” brackets, but for personal preference I just find it easer to read.

#    Comments [0] |
# Friday, May 29, 2009

ASCII table

Whenever I need one I always need search for a good ASII table.

So here is one:

Decimal Hex Unicode Description Character Entity Name Key
000 00 0000 null [nul] Ctrl-@
001 01 0001 start of heading [soh] Ctrl-A
002 02 0002 start of text [stx] Ctrl-B
003 03 0003 end of text [etx] Ctrl-C
004 04 0004 end of transmission [eot] Ctrl-D
005 05 0005 enquiry [enq] Ctrl-E
006 06 0006 acknowledge [ack] Ctrl-F
007 07 0007 bell [bel] Ctrl-G
008 08 0008 backspace [bs] Ctrl-H
009 09 0009 horizontal tab [ht] Ctrl-I
010 0A 000A new line, line feed [nl] Ctrl-J
011 0B 000B vertical tab [vt] Ctrl-K
012 0C 000C form feed, new page [ff] Ctrl-L
013 0D 000D carriage return [cr] Ctrl-M
014 0E 000E shift out [so] Ctrl-N
015 0F 000F shift in [si] Ctrl-O
016 10 0010 data link escape [dle] Ctrl-P
017 11 0011 device control 1 [dc1] Ctrl-Q
018 12 0012 device control 2 [dc2] Ctrl-R
019 13 0013 device control 3 [dc3] Ctrl-S
020 14 0014 device control 4 [dc4] Ctrl-T
021 15 0015 negative acknowledge [nak] Ctrl-U
022 16 0016 synchronous idle [syn] Ctrl-V
023 17 0017 end of trans. block [etb] Ctrl-W
024 18 0018 cancel [can] Ctrl-X
025 19 0019 end of medium [em] Ctrl-Y
026 1A 001A substitute [sub] Ctrl-Z
027 1B 001B escape [esc] Ctrl-[
028 1C 001C file separator [fs] Ctrl-\
029 1D 001D group separator [gs] Ctrl-]
030 1E 001E record separator [rs] Ctrl-^
031 1F 001F unit separator [us] Ctrl-_
032 20 0020 Space Space
033 21 0021 Exclamation mark !
034 22 0022 quotation mark " &quot;
035 23 0023 Number sign #
036 24 0024 Dollar sign $
037 25 0025 Percent sign %
038 26 0026 Ampersand & &amp;
039 27 0027 Apostrophe '
040 28 0028 Left parenthesis (
041 29 0029 Right parenthesis )
042 2A 002A Asterisk *
043 2B 002B Plus sign +
044 2C 002C Comma ,
045 2D 002D Hyphen -
046 2E 002E Period (fullstop) .
047 2F 002F Solidus (slash) /
048 30 0030 0 0
049 31 0031 1 1
050 32 0032 2 2
051 33 0033 3 3
052 34 0034 4 4
053 35 0035 5 5
054 36 0036 6 6
055 37 0037 7 7
056 38 0038 8 8
057 39 0039 9 9
058 3A 003A Colon :
059 3B 003B Semi-colon ;
060 3C 003C less-than sign < &lt;
061 3D 003D Equals sign; =
062 3E 003E greater-than sign > &gt;
063 3F 003F Question mark ?
064 40 0040 Commercial at @
065 41 0041 A A
066 42 0042 B B
067 43 0043 C C
068 44 0044 D D
069 45 0045 E E
070 46 0046 F F
071 47 0047 G G
072 48 0048 H H
073 49 0049 I I
074 4A 004A J J
075 4B 004B K K
076 4C 004C L L
077 4D 004D M M
078 4E 004E N N
079 4F 004F O O
080 50 0050 P P
081 51 0051 Q Q
082 52 0052 R R
083 53 0053 S S
084 54 0054 T T
085 55 0055 U U
086 56 0056 V V
087 57 0057 W W
088 58 0058 X X
089 59 0059 Y Y
090 5A 005A Z Z
091 5B 005B Left square bracket [
092 5C 005C Reverse solidus (backslash) \
093 5D 005D Right square bracket ]
094 5E 005E Caret ^
095 5F 005F Horizontal bar (underscore) _
096 60 0060 Acute accent `
097 61 0061 a a
098 62 0062 b b
099 63 0063 c c
100 64 0064 d d
101 65 0065 e e
102 66 0066 f f
103 67 0067 g g
104 68 0068 h h
105 69 0069 i i
106 6A 006A j j
107 6B 006B k k
108 6C 006C l l
109 6D 006D m m
110 6E 006E n n
111 6F 006F o o
112 70 0070 p p
113 71 0071 q q
114 72 0072 r r
115 73 0073 s s
116 74 0074 t t
117 75 0075 u u
118 76 0076 v v
119 77 0077 w w
120 78 0078 x x
121 79 0079 y y
122 7A 007A z z
123 7B 007B Left curly brace {
124 7C 007C Vertical bar |
125 7D 007D Right curly brace }
126 7E 007E Tilde ~
127 7F 007F delete [del]
#    Comments [0] |
# Wednesday, May 27, 2009

Rounding decimals to X positions

Another little extension method. This one allows easy rounding to a specific number of decimals:

double d = 0.66782423;
string s = d.ToString(3);  // s = “0.668”

This is done by the following method:

 

public static class DoubleExtension

{

    public static string ToString( this double value, int decimals )

    {

        StringBuilder format = new StringBuilder( "0" );

        if ( decimals > 0 )

        {

            format.Append( "." );

        }

        for ( int i = 0; i < decimals; i++ )

        {

            format.Append( "0" );

        }

        return value.ToString( format.ToString() );

    }

}

#    Comments [0] |
# Tuesday, May 26, 2009

Registration for SDN Conference 2009 | OpenForce ’09 Europe is now open!

The leading event for C#, VB.Net, ASP.NET, DotNetNuke and Delphi developers is now open for registration!

 

For the 18th year running the Software Development Network will organize this 2 day event (on October 19th and 20th, 2009) with sessions about :

  • .NET (C#, VB.Net, F#, etc.)
  • User eXperience (ASP.Net, Silverlight, Expressions, Flash, etc.)
  • Information Worker (MOSS, BizTalk, OBA, etc.)
  • DotNetNuke (OpenForce Europe ’09 conference)
  • Delphi
  • Architecture
  • Core Systems (C, Cobol, NonStop, IDMS, PL/1, DB2, CICS, TSO, ISPF, etc.)
  • Databases

Don’t miss out! Click here to register.

#    Comments [0] |
# Monday, May 18, 2009

Visual Studio 2010 and .NET FX 4 Beta 1 available for download

hero_2010_v3

Visual Studio 2010 and .NET FX 4 Beta 1 are available for download from the MSDN Subscriber Downloads as of today.

Go to: VS2010 Beta 1 Download for MSDN

The 5 page factsheet for VS2010 can be found here.

#    Comments [0] |
# Friday, April 24, 2009

Random filename

Today I had to fix a bug in some code involving a program creating multiple files where each file needed to have a unique machine generated filename. I was building my own unique name using the DateTime.Now.Ticks().ToString() as part of the name. Apparently on some machines the Ticks are not going to be unique. So I looked at the Path.GetTempFile() method, but I needed to control the location of the temporary files. Next stop: Path.GetRandomFileName().

Documentation:
The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name. Unlike GetTempFileName, GetRandomFileName does not create a file. When the security of your file system is paramount, this method should be used instead of GetTempFileName.

Works great!

#    Comments [0] |
# Monday, April 06, 2009

Training Kit now on sale at Amazon.com

Yeah, my last Training Kit is shipping!

Get a copy now at Amazon: http://tinyurl.com/dxwdz5

#    Comments [0] |
# Monday, March 23, 2009

Entity Framework: ObjectContext.SaveChanges is transactional

The documentation doesn't specifiy it but in the Entity Framework when you call ObjectContext.SaveChanges the update is 'wrapped' in a transaction.

NorthwindIBModel model = new NorthwindIBModel();

Guid id = Guid.NewGuid();

model.AddToCustomer(new Customer() { CustomerID = id, ContactName = "Andrew", CompanyName = "Northwind Traders" });
model.AddToCustomer(new Customer() { CustomerID = id, ContactName = "Aikido", CompanyName = "Northwind Traders " });

model.SaveChanges(); // exception duplicate key - transactional -> no changes to the database

#    Comments [0] |
# Monday, February 02, 2009

.NET Framework platform availability

I had to find out which platform supports which version of the .NET Framework. The information is a little fragmented, but here is the overview I came up with.

Windows 95
The .NET Framework cannot be installed on Windows 95.

Windows 98
.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0

Windows 98 SE
.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0

Windows ME
.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0

Windows NT 4.0 SP6a
.NET 1.0, .NET 1.1

Windows XP
.NET 1.0, .NET 1.1

Windows XP SP2
.NET 1.0, .NET 1.1, .NET 2.0, .NET 3.0, .NET 3.5

Windows 2000
.NET 1.0, .NET 1.1

Windows 2000 SP4
.NET 1.0, .NET 1.1, .NET 2.0

Windows Vista
.NET 2.0, .NET 3.0, .NET 3.5

Windows 2000 Server SP2
.NET 1.0, .NET 1.1

Windows Server 2003
.NET 1.1, .NET 2.0, .NET 3.0

Windows Server 2003 SP1
.NET 1.1, .NET 2.0, .NET 3.0, .NET 3.5

Windows Server 2003 R2
.NET 2.0, .NET 3.0, .NET 3.5

Windows Server 2008
.NET 2.0, .NET 3.0, .NET 3.5

 

Just to be clear, .NET 3.5 cannot be installed on:

  • Microsoft Windows 95
  • Microsoft Windows 98
  • Microsoft Windows Millennium Edition
  • Microsoft Windows NT Server
  • Windows NT Workstation
  • Windows NT Server Enterprise Edition
  • Microsoft Windows 2000 Professional
  • Windows 2000 Server
  • Windows 2000 Advanced Server
  • Windows 2000 Datacenter Server
  • Windows Server 2003, Enterprise Edition for Itanium-based Systems
  • Windows Server 2003, Datacenter Edition for Itanium-based Systems

 

References:

[UPDATE: .NET 3.0 will not run on Windows 2000 or Windows 200o SP4]

#    Comments [4] |
# Friday, August 29, 2008

Fixes and changes in Visual Studio 2008 SP1 and .NET 3.5 SP1

Visual Studio 2008 SP1 and .NET 3.5 SP1 offer an extensive list of enhancements, but also of bug fixes, here are the links in case (like me) your looking for a specific fix:

http://support.microsoft.com/kb/950263/ - List of changes and fixed issues in Visual Studio 2008 Service Pack 1

http://support.microsoft.com/kb/951845/ - List of changes and fixed issues in Visual Studio 2008 Service Pack 1 for Team Editions 

http://support.microsoft.com/kb/950264/ - List of changes and fixed issues in Visual Studio 2008 Service Pack 1 for Express Editions

http://support.microsoft.com/kb/951847/ - List of changes and fixed issues in Visual Studio 2008 Service Pack 1 for the .NET Framework 3.5

#    Comments [0] |
# Friday, August 01, 2008

XSD.exe turns integer into string

If you're using the xsd.exe tool to generate C# code from an XML Schema you'll find that an attribute defined as an integer is generated into a string field.

The reason is listed on MSDN:

The xs:integer type is specified as a number with no upper or lower bound on its size. For this reason, neither XML serialization nor validation map it to the System.Int32 type. Instead, XML serialization maps the xs:integer to a string while validation maps it to the Decimal type that is much larger than any of the integer types in the .NET Framework.

Update [02/26/2012]:
Using the xs:int will make XSD generate integers, more on http://www.w3schools.com/schema/schema_dtypes_numeric.asp. (thanks Marcus Schommler).

#    Comments [0] |
# Wednesday, June 11, 2008

AIM Map Phone

My article on combining AIM Call Out with geocoding a phone number to display the location of the person you're trying to call has gone live on the AOL Developer Network.

I think it turned into a very cool sample application.

Dial a number and see the location of the person you're calling!

#    Comments [0] |
# Tuesday, May 13, 2008

Building a .NET VoIP Application

The article I wrote about building a Voice over IP .NET application using AIM Call Out and the AOL Open Voice API has just gone live on the AOL Developer Network. Read it here.

#    Comments [0] |

.NET CLR 2.0 SP2

A lot is being blogged about the availability of VS 2008 SP1 and TFS SP1. It contains fixes and many new features and sound almost too good to be true, but I checked, it's not an April fool's joke :-)

A little lost in the noise about new features is the fact that .NET Framework 3.5 SP1 will include .NET CLR 2.0 SP2. I've been unable to find anything about this other than this one post by Eric Eilebrecht, but any CLR update is significant.

#    Comments [0] |
# Sunday, January 13, 2008

System.ServiceModel.Web

In the .NET Framework, most of the time, the name of an assembly matches the namespace of the classes in that assembly.

Since WCF is kind of an add-on to the .NET 2.0 Framework this is not quite true for the assembly System.ServiceModel.Web.dll

Below a screenshot of what .NET Reflector shows to be inside this assembly.

As you can see this assembly extends a number of namespaces like System.Runtime.Serialization and System.Collections.ObjectModel.

The Json serialization classes are also in this assembly.

#    Comments [0] |
# Monday, November 19, 2007

Typed DataSets and changing databases

The last couple of weeks I've been working on migrating an ASP.NET application from using a Visual FoxPro database to using SQL Server 2005. My application has it's logic in library DLL and with some layering uses Typed DataSets to connect to the database.

Typical code within the data access layer looks like this:

internal ViewDataSet.RequestViewDataTable GetViewByPrimaryUser( string user )
{
    using ( ViewDataSetTableAdapters.RequestViewTableAdapter _adapter 
            
= new ViewDataSetTableAdapters.RequestViewTableAdapter() )
    {
        ViewDataSet.RequestViewDataTable table;
        table = _adapter.GetByPrimaryUser( user.Trim() );
        return table;
    }
}

The method 'GetByPrimaryUser' is defined on the TableAdapter and using the GUI designer in Visual Studio I manage my typed datasets. All SQL is stored within the Typed DataSets. There is very limited use of stored procedures.

Migrating the .NET code from using a Visual FoxPro database to using SQL Server 2005 has involved the following:

  • Change the connection string property on every datatable to use the SQL Server connection string instead of the FoxPro connection string.
  • Opening every single query and changing the SQL parameters from question marks '?' to named parameters like '@user'.
  • Rechecking the mapping of the columns in the datatable, sometimes these would get messed up. Especially in cases where non-database columns where added to the datatable.
  • Rechecking column expressions.
  • Some areas of the code accessed the OleDbDataAdapter and OleDbConnection within the typed dataset, this had to be replaced with SqlDataAdapter and SqlConnection.
  • FoxPro does not support the .NET light weight transactions, so code to custom manage the transaction could be deleted and a simple 'using( TransactionScope tx = new TransactionScope() )' could be implemented.
  • There where several areas where 'adapter.Update(row)' did not work with FoxPro, so the Insert/Update/Delete had to be called manually in the data access layer. With SQL Server there are no problems and this 'fix-it' code could be removed.

After following these steps some of the datatables would generate unexplicable validation errors. Not wanting to waste too much time I just re-created those typed tables and re-added the queries on those tables.

 



Since the advent of cheap web hosting, we have had more development in the field of SEM. Thanks to features like internet phone, managing internet network marketing is a lot more feasible now. Marketing strategies like cpc, ppi and pay per click can be managed with much more comfort now. Usually regular advertising agencies miss out on this since they concentrate more on building links through email marketing.

#    Comments [0] |

Visual Studio 2008 Team Suite available on MSDN Subscriber Downloads

Visual Studio 2008 Team Suite has just become available on MSDN Subscriber Downloads.

#    Comments [0] |
# Monday, November 12, 2007

DateTime.ParseExact(...)

Another gem in .NET 2.0. Parsing a string to get a datetime used to be pretty complex. But now with the DateTime.ParseExact(...) method you can specify the exact format of your string.

string s = "20071231T214559";
DateTime d = DateTime.ParseExact( s, "yyyyMMddTHHmmss", null );
this.textBox2.Text = d.ToString();  // this will print: 31-12-2007 21:45:59

Steve Tibbet has a post describing all the options for specifying the format.

#    Comments [0] |

Math.Round(...)

The .NET Framework is huge and I still frequently find new things in .NET 2.0 which I had not seen before. Last week I stumbled across the update in Math.Round(...).
In .NET 1.x the .NET Framework would only support the American way of rounding numbers. This means that:

decimal y = 2.5M;
decimal x = Math.Round(y, 0);     // x = 2

For Dutch people this wrong. We would expect x to be '3'.
In .NET 2.0 there is a new overload, allowing you to specify how the Round method should work.

decimal y = 2.5M;
decimal x = Math.Round(y, 0, MidpointRounding.AwayFromZero);     // x = 3!

#    Comments [0] |