Thursday, February 18, 2010

Using Entity Framework Self Tracking Entities with Workflow Persistence in .NET 4.0 RC

I just ran into a problem when trying to use Workflow Persistence with Self Tracking Entities in .NET 4.0 RC.

The execution of the InstancePersistenceCommand named {urn:schemas-microsoft-com:System.Activities.Persistence/command}SaveWorkflow was interrupted by a
n error. ---> System.Runtime.Serialization.InvalidDataContractException: Type ‘ElasticSoftware.DownloadSheriff.Domain.Model.Entities.TrackableCollection`1[ElasticSoftware.DownloadSheriff.Domain.Model.Entities.Customer]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for other supported types.

By Default the TrackableCollection in the Types.tt is not annotated with a DataContract attribute.

You can fix this by going to Line 1401 and adding the DataContract attribute like so:

[DataContract]
public class TrackableCollection<T> : ObservableCollection<T>



Then regenerate from your T4 templates and you should be good to go.

Breaking Changes for Visual Studio 2010 RC

Just installed the Visual Studio RC and have come across the following issues.

System.Runtime.Persistance has been replaced by
System.Runtime.DurableInstancing

All the Workflow Persistance Schema and Logic has changed and there is no Migration path. You can find the latest scripts here:

C:\Windows\Microsoft.NET\Framework\v4.0.30128\SQL\en\

These were the only issues I had when upgrading a 30 project solution.

Really enjoying the increased speed combined with ReSharper 5.0

Saturday, January 30, 2010

Disabling the Shut Down button on Windows Server 2008

The very first thing I do when building an Amazon EC2 image is too disable the Shut Down button.

Shutting Down an instance has the same effect of terminating the instance, meaning you lose all data not stored on EBS volumes.

Click Start > Run > Type “gpedit.msc” and press enter

Go to User Configuration > Administrative Templates > Start Menu and Toolbar

The option you are looking for is “Remove and prevent access to the Shut Down, Restart, Sleep, and Hibernate commands”

Right Click > Properties > Select Enabled > Click Apply > Click OK

disableShutDown

Now when you go to the Start Menu you will see this with the only options being Lock and Log Off. Now you can use the AWS Management Console to manage reboots or terminations.

ShutDown

Saturday, January 16, 2010

Migrating to Amazon EC2 from GoGrid

Recently Amazon EC2 announced that they were going to support Windows Server 2008 instances.

The experience with GoGrid has been rocky to say the least and most recently the MyGSI’s shortcomings confirmed that the service was not able to meet our applications requirements for using instances on demand.

Which brings me to this post. After 14 months with GoGrid I have just recently completed a migration of all applications and databases to Amazon EC2 and thought I would outline the steps I took.

Creating New Instances

Before you start you will need to create your new instances in Amazon EC2. I have covered this previously in another post.

When you set up the firewall it is important that you open Port 1433 for traffic coming from your previous web server in GoGrid. Or if you want you can even create a temporary VPN between your GoGrid web server and EC2 database server using Amazon Virtual Private Cloud. This is an important step in ensuring minimal downtime.

At this point you’ll want to create CNAMES for the Amazon instance and add these bindings to IIS so that you can test all your applications before the DNS changes take affect.

Transferring Files & Data

The way I transferred the files was via Amazon S3, download speeds between EC2 and S3 are very fast. If you don’t have an S3 account yet just go to http://aws.amazon.com/s3/ and click the “Sign Up” button.

You will need to put an S3 Client on your servers, I tend to use a combination of FireFox and the add-on S3Fox.

Once these are done all you need to do is backup any databases then zip the databases and files up and upload to a bucket in S3.

Once Uploaded you can download from within your EC2 instance, unzip and change any configuration values.

If you can put an indicator on one of your web pages which will help you to see that the DNS has gone through.

Test, Test, Test

Goes without saying but once you have all files and databases setup on your new instance you will want to perform some serious testing.

Don’t forget those Folder Permissions.

Making the DNS Change

Whether or not you have downtime depends entirely on the nature of your application. For a standard content managed website your data and files aren’t going to change that often so you should have plenty of time.

If you have a highly active system with lot’s of database writes then the downtime will be limited to the Backup, Restore process of your database. This was the case for me.

Load a temporary message onto your app advising users of the scheduled maintenance and make sure no users can log in.

Backup any data and files on your live GoGrid instance that may have changed after the last backup.

Upload to S3.

Download an unzip on EC2 instance. Restore any files and databases.

Change any Database Connection Strings on your live instance to point to your new EC2 instance on port 1433.

Update the DNS to point to your new server.

Done

Once the DNS change has taken full affect (wait a week) you can terminate your GoGrid instances and enjoy the goodness of Amazon EC2.

I will still be using GoGrid as a failover provider in case of any outage on Amazon EC2.

Thursday, November 12, 2009

Configuring Custom Error Pages on IIS7

One thing that often trips me up whenever I setup a new Windows Server 2008 box is the IIS default error pages for standard error codes 401, 404, 500 etc.

These seem to override the Custom errors section in your Web.Config. ErrorPagesOnII7

If you notice above the default for IIS7 is:

“Detailed errors for local requests and custom error pages for remote requests”

In order to make use of the Custom error pages in your Web.Config you need to select the “Detailed Errors” option.

Wednesday, November 11, 2009

Microsoft-Windows-IIS-W3SVC-WP Event id 2294 - Visual Studio 2010 Beta 2

Just ran into this mysterious error when trying to deploy a WCF project to IIS.

The description for Event ID 2294 from source Microsoft-Windows-IIS-W3SVC-WP cannot be found. Either the component that raises this event is not installed on your local computer or the installation is corrupted. You can install or repair the component on the local computer.

If the event originated on another computer, the display information had to be saved with the event.

The following information was included with the event:

v4.0.20506"

It turns out that after installing Visual Studio 2010 Beta 2 there were some of the old framework files floating around.

To solve this go to %windir%\Microsoft.Net\Framework\

and delete the directory named v4.0.20506

Restart your Application Pool and you should be good to go.

Sunday, November 8, 2009

CAS Policy changes in .NET 4.0 Visual Studio Beta 2

I ran into a interesting exception yesterday when trying to run NServiceBus on Windows 7 with Visual Studio 2010 Beta 2

System.NotSupportedException: An attempt was made to load an assembly from a network location which would have caused the assembly to be sandboxed in previous versions of the .NET Framework. This release of the .NET Framework does not enable CAS policy by default, so this load may be dangerous. If this load is not intended to sandbox the assembly, please enable the loadFromRemoteSources switch. See http://go.microsoft.com/fwlink/?LinkId=131738 for more information.

I found some more info on this blog.

Basically the fix is to add the following to your App.Config

<runtime>
<loadFromRemoteSources enabled="true"/>
</runtime>

Wednesday, October 21, 2009

Visual Studio 2010 Beta 2 – Upgrade Issues

Just upgrading some of my projects and am going to note some of the breaking changes for anyone else.

Entity Framework

System.Data.Objects.ObjectContextOptions



//deprecated
ContextOptions.DeferredLoadingEnabled = true;

//beta 2
ContextOptions.LazyLoadingEnabled = false;




Update:







It seems the T4 template for the Self Tracking Entities was not updated with this change for the ContextOptions.






Here is the Fix



Just unzip and replace the following files.



C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplatesCache\CSharp\Code\1033\AdoNetEntityDataModelT4SelfTrackingCodeGenCsharp.zip\EF.SelfTracking.Context.ctp.CS.tt



C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplatesCache\CSharp\Code\1033\AdoNetEntityDataModelT4PocoCodeGenCSharp.zip\EF.Poco.Context.ctp.CS.tt






Workflow




When I opened up my Solution with a Workflow project it was unable to open it.

It seems they have now added two new Workflow Project Types.




WCF Workflow Service Application

Workflow Console Application




Also it seems the XAML has changed and the designer can’t interpret old Activities.









workflow_breaking







Update:







Found another bug which I just battled an hour with.




My Custom Activities weren’t showing up in the Workflow toolbox it turns out that they only show up when the Activity Library project is not contained in a Solution folder.






The referenced assembly "DLLName.dll" could not be resolved because it has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted framework ".NETFramework,Version=v4.0,Profile=Client".   

Tuesday, October 20, 2009

Visual Studio 2010 Beta 2 Available

Just found out that Visual Studio 2010 Beta 2 is now available to all MSDN subscribers. According to Scott Hanselman it will be available to the General Public on Wednesday.

Here is the link to the download page (Login required):

https://msdn.microsoft.com/en-us/subscriptions/securedownloads/default.aspx?pv=18%3a370 

The timing couldn’t have been better as I have just started working on some Workflows which need to go live next month.

According to Jeff Beehler there is also a Go Live license available.

One thing to mention is that there is no more Team Edition but rather an Ultimate Edition.

Am downloading as I write this so will write a follow up post soon about any install problems.

Update:

Edition Price
Visual Studio 2010 Pro / exc. MSDN Subscription $799
Visual Studio 2010 Professional
inc. MSDN
$1199
Visual Studio Premium 
inc. MSDN
$5469
Ultimate Visual Studio
inc. MSDN
$11924

Visual Studio Developer, Database, Architect & Test Editions have been officially dropped.

Based on this article here are the features for each edition. 

Edition Features
Visual Studio Professional IDE
Parallel Debugging
Core Features
Visual Studio Premium Code Analysis
Database Deployment
UI Testing
Test Impact Analysis
TFS Integration
Visual Studio Ultimate Everything in Premium +:
UML Tools
Historical Debugging
Manual Testing
Load Testing
Team Foundation Server

Wednesday, September 9, 2009

GoGrid MyGSI First Thoughts – follow up

I recently embarked an creating my first GoGrid MyGSI and in my previous post I mentioned that I had an open support case to resolve the fact that I could not create an instance from the image that I saved.

After five long days of waiting for some sort of resolution finally the Engineers decide that the image is “unclean” and they can’t debug the issue any further.

They did suggest however that I create another MyGSI from scratch. 

I wasn’t happy to accept this as a one off problem as I still needed to move an instance over from EC2 so I decided to test the system myself.

I created another instance without installing any application files or additional components and connected to the Cloud Storage then ran the prep script.

Again I got the same result. It booted me out of RDP but did not change to the status which allows saving the image.

I submitted another support request and the finally the cause was identified.

Assigning an Internal IP Address (which is required for Cloud Storage)was the culprit.

Admittedly this does make sense from a technical perspective, however as an end-user it would be nice if this was detailed in the documentation or if there was some sort of error or log message.

I’m pleased to say that after the cause of the problem was identified I was able to successfully migrate from EC2 to GoGrid albeit 2 weeks later than anticipated.

After becoming confident that service did in fact work it came time to create images for my running instances that were created before MyGSI was available.

The requirements for the machine are:

  1. Windows Server 2008
  2. SQL Server 2008 Express with Advanced Services SP1
  3. IIS7.0
  4. SMTP Server
  5. FTP Server
  6. MSMQ
  7. .NET 3.5 SP1

I created my instance and set about installing all of the required components. I then came to installing SQL Server and to my dismay found that there wasn’t enough room left on the sandbox.

This is before even installing any application files or databases.

Again another waste of time. In a world where data is cheap why put unnecessary restrictions? My guess is they are aiming at start-ups with very small databases, but not allowing enough space to do a standard web server install is pretty weak. 

This whole experience has been nothing short of frustrating but I guess that’s the price you pay for being an early adopter and working with Beta software. It should be said that the support is really good and you can always get quick responses on Twitter.

GoGrid MyGSI shows good potential but there are a few thing’s you need to be aware of before diving in.

  • 20GB Limits on the Image Sandboxes.                           Actual limit of 6.18 GB on Win2008 after OS footprint.
  • No way to create an image from a running instance.
  • No Windows Server 2008 Pre-Installed Images at present
  • No equivalent EBS solution
  • Light documentation
  • Setting up the Private network for Cloud Storage causes the Image shutdown to fail. Remember to remove any routes and disable the LAN2 before running the prep script.

Friday, September 4, 2009

First thoughts on MyGSI from GoGrid

Those of you who read my blog would know that I have been using GoGrid for almost a year now as a primary host for our suite of applications.

Although the EC2 offering is much richer and far more advanced, GoGrid has the benefit of Windows Server 2008 images which was too compelling to ignore. However choosing to go with GoGrid meant forfeiting the very solid infrastructure that EC2 has.

So it was to my delight on August 10th that GoGrid announced MyGSI.

“The MyGSI feature allows you to create, save, and store a "Server Image" in which to instantiate Database and Web/App Servers from.”

My requirement was to set up a Windows Server 2003 – 64-bit image with IIS, SQL Server 2005 Express, MSMQ, SMTP Service and FTP Service. Pretty standard setup really for a .NET app.

The first (of many) disappointments was that there is no way to create an image from a running instance. This is a big PITA and is one of the key reasons why it’s taken me till now to try out the new offering.

I was able to create the Sandbox server with no problems and get working within minutes.

Beware however that the Image Sandbox only comes with only 20GB storage but that should be enough for most applications.

First on my list was to install FTP Service, SMTP Service and MSMQ. Was pretty annoyed to find that the files needed to install these weren’t on the server. After chatting to a support person they clarified that the files should be there, however they weren’t.

Next up I needed to connect to my Cloud Storage drive and ran through the steps on their wiki but again it did not work correctly and I needed to go to support for help, they resolved it swiftly but would be nice if thing’s worked first time.

Cloud Storage works differently to the EC2 EBS Solution and acts more or less like a NAS unlike the EBS which acts like a mounted drive. This effectively means you wouldn’t want to run all your application files and database off of this drive as the performance (I think) would be too slow. Also as far as I can tell there is no CDN offering for Cloud Storage so it isn’t really a solution for serving unstructured data either. It makes for a nice backup solution but that’s about all.

So eventually I managed to build my image sandbox and everything was working nicely, it then came time to save my image.

Now the process of saving your image is quite scary to say the least because you first have to “Prep” it. This involves running a little console app and then follow the instructions. This then triggers the server to shut itself down and boots you out of RDP.

What happened next was not the intended behaviour (I hope).
There was no log or status updates to be found in the GoGrid Console so I guess you just have to cross your fingers and hope for the best. I later found out that only the network adapter was shutdown which meant I couldn’t use RDP and the image was not created.

Again I had to use support and they resolved the issue quickly.

Finally I had my image saved and ready. Now came the true test, creating a new instance from my saved image.

Given the experience thus far I thought maybe it could be redeemed. Nope! no such luck. The “Creating Virtual Server” job failed with the very helpful “Fatal” error message. I tried again twice and got the same error.

Again I had to use support, they couldn’t resolve the issue and I currently have an open support ticket.

So basically this arduous process was a waste of half of my day with no result. In total I had to use the support chat four times, once at every major step of the process.

The big picture goal I was trying to achieve here was moving some of our infrastructure from EC2 to GoGrid. I’m now in the position of being responsible for not delivering on these tasks because to my fault I trusted that this service would work as intended.

It highlights what seems to be a growing trend in agile tech companies. Releasing Alpha versions of products/services, labelling them as Beta then letting your paying customers test them and swallow the support costs.

I certainly don’t envy GoGrid and other cloud computing providers who are effectively playing catch up on Amazon who are miles ahead of anyone in this area.

Responding with less features is acceptable given that they function correctly and there is a clear roadmap for new features. However the ability to create and maintain server images of which to create instances from is an absolute fundamental part of the Cloud Computing model and as such should be the main priority.

To GoGrid’s credit the support team are very helpful and can answer and respond to most questions quickly. However with the Amazon Web Services there is no support (unless you pay for it) but there hasn’t been a single case where I’ve needed it because everything “just works” as it should and there is documentation a plenty.

 

Pros

  • Ability to add meaningful names and descriptions to your instances and images, this is something that bugs the hell out of me in Amazons new Management Console
  • You can downgrade your instances. (In EC2 you can’t go smaller than the instance you created the image from).
  • 24/7 Support

Cons

  • No answer yet to Amazon EBS Volumes
  • Not all files exist on the server for the optional Windows components (FTP Service etc).
  • Can’t create Images from running instances. 
  • Pretty meaningless logs and messages.

Wednesday, August 5, 2009

Speed up your browser in 5 easy steps

Step 1: Open your existing browser

Step 2: Navigate to http://www.google.com/chrome/

Step 3: Click “Download Google Chrome”

Step 4: Click “Accept and Install” then follow install instructions.

Step 5: Open Chrome and enjoy your super fast browsing.

Friday, July 31, 2009

Hosting .NET MVC on RackspaceCloud Cloud Sites

Last week I deployed a pet project (pun intended) of mine Borrow a Pet to the RackspaceCloud Cloud Sites environment.

So far I’m very pleased with the performance of the site, however I thought I would highlight a few areas you need to be aware of when developing/deploying .NET MVC apps to the Cloud Sites environment as their documentation right now is fairly light.
 
It should be said that the 24/7 Support team are fantastic, however I found myself having to use them a bit too often for my liking.

The technologies/tools/components I used goes like this.

  • .NET MVC for the Presentation Layer
  • LINQ to Entities for the data layer
  • SQL Server 2008 Database
  • Third Party Google Maps Wrapper for GeoCoding
  • Unity for the IoC Container

 

Medium Trust
Believe it or not but in my eight or so years of .NET development I’ve never had to develop with Medium Trust in mind. Boy had I been spoilt. For more details on Medium Trust information go to the knowledge base.

IIS7 Integration Mode
By default sites created on IIS7 are set to Classic Mode which means that if your using the .NET MVC Framework your routing won’t work. All you need to do is use the Live Chat support and ask them to change it to Integration Mode, they do it pretty much instantly.

AspJpeg
One of the requirements is to generate Thumbnails whenever an Image is uploaded, seems simple enough. RackspaceCloud advertise this component as being available. What they don’t do however is document that it DOES NOT work in the .NET environment and only works with Classic ASP.

http://www.aspjpeg.com/

I actually changed my Thumbnail Generation process to use this component on the understanding that it would work. You can imagine my reaction when I was told that this doesn’t work and that quote “if you recode in Classic ASP it will work”.

So rather than rewrite my clean, sexy Unit Testable MVC application I decided to just roll my own and go with the System.Drawing and System.Graphics libraries and it all works fine.

IoC
As I strictly practice TDD there was the need for an IoC Container to resolve any dependencies at runtime. I have religiously used Castle Windsor now for a couple of years. What I discovered however is that the Release Build of Castle Windsor does not work in a Medium Trust environment, there is a way to Rebuild the project however having tried to download the Castle source and build it before proved problematic. So I made the switch to Unity and all is well. So when choosing an IoC container make sure you use one which doesn’t use reflection internally.

Impersonation
This one is fairly simple, but you will need to impersonate your NT account (same as the FTP account ) if you plan on doing any System.IO operations. This can be set by adding the Identity element to your Web.Config

<system.web>
<identity impersonate="true" userName="dfw\username" password="strongpassword"></identity>
</system.web/>


Email

There are some Rules around using the Cloud Site’s mail relays.


You can only send 25 emails at a time and no more than 250 messages in a 20 minute period. If you want to send more than this then you need to contact Rackspace.





As I use Google Apps for all my email, my MX records were pointing to Google’s servers. This isn’t a problem so long as you set up an email account via the Rackspace UI then use those credentials when specifying the Network Credentials in the Smtp object like below.








var smtpClient = new SmtpClient(host, port)
{
Credentials
= new NetworkCredential(fromEmail, smtpPassword),
DeliveryMethod
= SmtpDeliveryMethod.Network,
};

smtpClient.Send(mailMessage);





Your Smtp Host to use is mail.yourdomainname.com and port 25 is fine.



The knowledge base lists all the mail servers available.



Third Party Libraries

One of the key features of the site is Location based personalization which provides content to users based on their geographical location. In order to achieve this I needed to GeoCode the User addresses at account creation time.



For this I used Geocoding-net which is an awesome C# wrapper for Google Maps, Virtual Earth and Yahoo Maps.



By default though it didn’t work in a partially trusted environment. Fortunately I was able to get the source and add the following attribute to AssemblyInfo.cs and this was enough to get it work.



[assembly: AllowPartiallyTrustedCallers]


When analysing third party components make sure they support Partially trusted and if not make sure you have access to the source code.



If you take note of these limitations/restriction and are still able to provide all the functionality of your application then the gains can be massive.



Overall the Cloud Sites model is very attractive and is more inline with Windows Azure. What Cloud Sites allows you to do is focus on features and not get bogged down with Server Administration, which I for one am no fan of.

Thursday, July 16, 2009

Windows Azure pricing announced, Cloud Computing pricing and feature comparison

Well the wait is over Microsoft have finally announced the Pricing for Windows Azure, thanks Darko for letting me know.

Full post here.

All in all there are no surprises and the pricing is pretty much on a par with other Cloud Computing providers.

Let’s do a quick pricing comparison.

  Windows Azure Amazon EC2 GoGrid RackspaceCloud Cloud Sites
From $100 / month
Compute Cycles $0.12 $0.125 $0.19 inc 10,000 / month
$0.01
Inbound Bandwidth $0.10 $0.10 FREE inc 500 GB / month
$0.25 / GB
Outbound
Bandwidth
$0.10 $0.17 $0.50 inc 500 GB / month
$0.25 / GB
Storage / GB $0.15 $0.10 $0.15 inc 50 GB / month
$0.50 / GB
CDN N/A $0.17 / GB N/A $0.22 / GB

Feature Comparison

  Windows Azure Amazon EC2 GoGrid RackspaceCloud
Cloud Sites
IIS7 Yes No Yes Yes
SQL Server No Yes Yes Yes
24/7 Support No No Yes Yes
CDN Support No Yes No Yes
Full Trust Yes Yes Yes No
API No Yes Yes Yes
Auto-Scale Yes Yes No Yes
Server Images No Yes No No
Load Balancing Yes Yes Yes Yes
RDP Access No Yes Yes No

Wednesday, July 15, 2009

Log Shipping in SQL Server Express 2008

When you entrust your Applications and Data to the Cloud Based Service Providers such as GoGrid and Amazon EC2 it becomes absolutely critical to employ a strict Disaster Recovery strategy.

As part of of our strategy it was imperative that we have a failover for our SQL Server. The only problem was that SQL Server Express 2008 doesn’t support Log Shipping.
Well technically it does but SQL Server Express does not have SQL Server Agent.

Now I’m a big fan of SQL Server, but when it comes to doing something a bit more complicated the Express editions limitations become a bit of a problem, that’s why it’s time to find creative solutions.

To set up Log Shipping the first step is to Backup your database and then Restore it on another instance making sure set the Recovery state as “RESTORE WITH STANDBY”. See below

restore

To get this going you’ll need three stored procedures, one in the Master database and two in the slave database.

Now when you are trying to do this across Networks and Hosting Providers you will need a reliable way of transferring the Logs from the Master server to the Slave. For this we use Windows Live Sync, but that’s a whole other blog post.

Here are the stored procedures you need to get this going.
NB: These only work in SQL Server 2008 and our not backward compatible.

BackupLog

All you do here is specify the path for the log and the name of the database you want the transaction log for.

USE [master]
GO
CREATE PROCEDURE [dbo].[BackupLog]
@LogPath nvarchar(
500),
@DatabaseName nvarchar(
100)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
BACKUP LOG @DatabaseName to disk
=@LogPath with NOINIT, NOSKIP, NOFORMAT
END
GO




RestoreLog



All you do here is specify the path for the log and the name of the database you want to restore the transaction log for.



CREATE PROCEDURE [dbo].[RestoreLog]
@LogPath nvarchar(
500),
@DatabaseName nvarchar(
100)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @StandbyFile nvarchar(
1000);
SET @StandbyFile
= 'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup\' + @DatabaseName + '.undo';
DECLARE @spid as varchar(10)
DECLARE @CMD
as varchar(1000)
DECLARE cur CURSOR FOR SELECT spid FROM master.dbo.sysprocesses WHERE dbid
=
(SELECT dbid FROM sysdatabases WHERE name
= @DatabaseName)
open cur
FETCH NEXT FROM cur INTO @spid
WHILE @@FETCH_STATUS
= 0
BEGIN
SET @CMD
= 'kill ' + @spid
EXEC (@CMD)
FETCH NEXT FROM cur INTO @spid
END
CLOSE cur
DEALLOCATE cur

DECLARE @i
int
DECLARE @j
int
SET @j
= 1
SET @i
= 0
RESTORE HEADERONLY FROM DISK
=@LogPath
SET @i
= @@ROWCOUNT
WHILE @i
+1 > (@j)
BEGIN
RESTORE LOG @DatabaseName FROM DISK
=@LogPath
WITH FILE
= @j,
STANDBY
= @StandbyFile
SET @j
= @j + 1
END

SET @j
= 1
SET @i
= 0
CREATE TABLE #HeaderTable
(BackupName varchar(
255),
BackupDescription varchar(
255),
BackupType
int,
ExpirationDate datetime,
Compressed
int,
Position
int,
DeviceType
int,
UserName VarChar(
255),
ServerName varchar(
255),
DatabaseName varchar(
255),
DatabaseVersion
int,
DatabaseCreationDate datetime,
BackupSize numeric(
24,0),
FirstLsn numeric(
24,0),
LastLsn numeric(
24,0),
CheckpointLsn numeric(
24,0),
DatabaseBackupLsn numeric(
24,0),
BackupStartDate datetime,
BackupFinishDate datetime,
SortOrder
int,
CodePage
int,
UnicodeLocaleID
int,
UnicodeComparisonStyle
int,
CompatibilityLevel
int,
SoftwareVendorID
int,
SoftwareVersionMajor
int,
SoftwareVersionMinor
int,
SoftwareVersionBuild
int,
MachineName varchar(
255),
Flags
int,
BindingID uniqueidentifier,
RecoveryForkID uniqueidentifier,
Collation varchar(
255),
FamilyGUID uniqueidentifier,
HasBulkLoggedData bit,
IsSnapshot bit,
IsReadOnly bit,
IsSingleUser bit,
HasBackupChecksums bit,
IsDamaged bit,
BeginsLogChain bit,
HasIncompleteMetaData bit,
IsForceOffline bit,
IsCopyOnly bit,
FirstRecoveryForkID uniqueidentifier,
ForkPointLSN numeric(
24, 0),
RecoveryModel varchar(
256),
DifferentialBaseLSN numeric(
24, 0),
DifferentialBaseGUID uniqueidentifier,
BackupTypeDescription varchar(
256),
BackupSetGUID uniqueidentifier,
CompressedBackupSize
int
)
INSERT INTO #HeaderTable
EXEC master.dbo.GetRestoreCount @LogPath
SET @i
= (SELECT COUNT(*) FROM #HeaderTable)
DROP TABLE #HeaderTable
WHILE @i
+1 > (@j)
BEGIN
RESTORE LOG @DatabaseName FROM DISK
=@LogPath
WITH FILE
= @j,
STANDBY
= @StandbyFile
SET @j
= @j + 1
END
END
GO




GetRestoreCount


This is used internally by RestoreLog





USE [master]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetRestoreCount]
@FileName AS varchar(
1000)
AS
RESTORE HEADERONLY FROM DISK
=@FileName

GO

Monday, July 13, 2009

Path resolved to Referenced activity Property does not match the Target Type, Workflow Foundation Designer Bug

Just this morning I got this really helpful error when trying to bind to a Custom Activities Dependency Property.

Path resolved to Referenced activity Property 'MyProperty' whose PropertyType 'MyNamespace.MyCustomType ' does not match with the Target Type 'MyNamespace. MyCustomType'.

Basically the error says you can’t bind a property of type Type1 to a property of type Type1. Makes sense really.

Fortunately I was able to find some help on the InfoSupport blog.

The suggested solutions were:

1. Clean Solution
2. Close Visual Studio and Reopen the Solution again
3. Go run %temp% and delete all files.

In reality the only definitive fix for this is to Close Visual Studio and reopen the Solution again.

Hopefully this will be fixed in Visual Studio 2010.

Saturday, July 11, 2009

Silverlight 3 Released

Well it looks like the original release date was right on the money.

Silverlight 3.0 has been officially released.

http://silverlight.net/getstarted/

Interested to see how fast this is adopted, maybe finally Silverlight could be a viable platform for RIAs (Rich Internet Applications).

I’ll be keeping a close eye on the RIAStats.

Friday, July 10, 2009

Official Borrow a Pet blog launched

I have recently launched the official blog for a pet (no pun intended) project of mine called Borrow a Pet.

Borrow a Pet aims to solve a number of problems such as:

  • Finding a pet sitter as an alternative to kennels
  • Allowing would be pet owners the chance to experience the responsibility of owning a pet before they commit, thus reducing the number of abandoned pets.

And many more. You can read all about it in the first post.

Thursday, July 9, 2009

ReSharper for Visual Studio 2010 Preview Build now available

The second build ReSharper for Visual Studio 2010 is now available. You can get it from:

http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+for+Visual+Studio+2010+(Preview)

Have just installed it and at first it wasn’t displaying but if you do the following

Tools > Options > Extension Manager > Select "Load extensions from my local application data folder"


Then close and reopen Visual Studio it should work.

Going to take it for a test drive.

Thanks heaps to the ReSharper team for making this available, Visual Studio seems so primitive without it.

UPDATE: When I put my current 4.5 license it says the license is “not acceptable”. Does anyone know what license to use?

UPDATE: See below comment, a temporary license is available from the Nightly Build Page see the Known Issues section at the bottom.

Thursday, July 2, 2009

The role of Mocking in TDD, Test First with Rhino Mocks, KandaAlpha

Recently I got into a healthy discussion with Keith Patton about Constructor Injection and other such topics to do with Test Driven and Domain Driven Design.

One way or another this lead to the birth of Kanda Alpha with the goal of demonstrating best practice domain driven design utilising Visual Studio 2010 Beta, ASP.NET MVC 1.0 and Db4o as the data store.

I’ve decided to give an explanation as to the benefits of Mocking and the Test First approach.

Mocking quite simply allows you to test components in isolation from their dependencies. By mocking out the results and behaviour of the dependent components you can focus on verifying the behaviour of a single class.

Where I’ve found it most useful is in designing the service layer and this is usually the first thing I design after hashing out the Domain Entities.

There has also been some comments on Keith’s blog about the purpose of the Service layer if all it is doing is acting as a Facade to the Repository. This is a valid point and I’m going to try and give a real life example which demonstrates that this isn’t the case. 

From Martin Fowler’s Domain Driven Design

“A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations.”

http://martinfowler.com/eaaCatalog/serviceLayer.html

Second only to the Entities Model the Service Layer is the heart of your application so should be the focus of the design and that’s where Mocking will add value.

The example I’m going to demonstrate is the very simple but very common Registration of a User.

When a User is created there are a number of requirements that need to be met:

  • Geocode the Users Address
  • Persist the User to a data store
  • Send an Email asking them to confirm their email

Right so let’s see some code.

Firstly I will define the IRegistration interface

regservice

Ok as we are doing Test first let’s create an Implementation and set up our first Unit Test.

regserviceimpl

Now the Mocking framework of choice is Rhino.Mocks.

So here is the very first Unit Test.

regusertest

Note this test will fail as RegisterUser has not been implemented yet, this is fine as it is failing for a very valid reason.

reguserfail

Because of the requirements listed above the IRegistrationService implementation is going to have dependencies on some other components to fulfil these requirements.

  • IUserRepository
  • IAddressGeocoder
  • IMessageSender

So let’s define those

geoservice

Now we will define the IUserRepository which will be used  to persist the User.

userRep

Finally we need a component to send the confirmation email.

messageSender

Ok now that we have defined the Interfaces for our dependencies, let’s add them to our RegistrationService implementation. For this I am going to use Constructor Injection (link here) it will become clear shortly why.

regwithdependencies

Now that we have obviously broken our test  because there is no longer a default constructor.  So let’s fix up our test so that it runs again.

regservicetestwithmocks

You will notice above that I have used the MockRepository to generate in-memory Stubs. We do this because we don’t want to worry about the implementations at this stage.

Now we need to Setup some results.

regserviceStubs

Now that we have setup our test we can write the implementation, which should be easy. 

reguserimpl

Now running the test should give us the all important green tick.

reguserpass

Well that’s it. By following this approach you are forced to think about how classes interact with other classes and as a result you end up with loosely coupled components that are Unit Testable.

The source code is available to on the KandaAlpha project on Codeplex.