Archives

Archives / 2008
  • NHibernate and WCF is Not a Perfect Match

    From the last days of playing around with and learning NHibernate it's quite clear to me that NHibernate is not a perfect match for a WCF solution. I'm perfectly aware of the fact that I'm still a total NH newbie, so please correct me or help me out if you can.

    From the moment I heard of Hibernate years ago I thought it was best made for stateful solutions and not web apps or web services, and from what I can see that is still the case. I like many of the things I see in NH, especially the way you can map existing and bad looking databases to better looking domain entities, and the work on NHibernate Fluent looks promising.

    You have to understand how lazy loading does (not) work with web services and serializing problems you may run into. But I think the biggest problem lies in the session management of NHibernate and where to open and close your NHibernate session. I won't even go into the different options proposed by hundreds of bloggers, just Google it. The thing is I don't want to be dependant on more 3rd party or open source components than necessary - it can easily get out of control.

    I still want to use NHibernate for our WCF project because I do think can help us map the old, existing database we have to work with to decent domain entities, but I'm afraid we will run into weird problems later on. This approach seems to be one of the best so far, but I need to test it out some more and I'm not sure it will handle lazy loaded/HasMany data. Quite a few projects have run into problems with the session being closed before the serialization of lazy loaded objects happens :/

    We may have to use EF instead.

  • WCF, Unity and NHibernate - First Findings

    This blog post is to continue on the one I wrote a few days ago about a new architecture for a WCF project we're trying out.

    My colleague Tomas and I sat down the whole day yesterday and dug into the topic and came out with a first rough code architecture that seems to work. Both of us knows WCF pretty well, but we're new to Unity and NHibernate so this baby has to be tested thoroughly :)

    First, thanks to Ray Henry, who wrote a couple of nice posts about how to use Unity with WCF. That information was superb. Basically we're using a custom Service Host Factory which we point at from the .svc markup file:

    <%@ ServiceHost Language="C#" Debug="true" Service="WcfUnity.TestService" 
    CodeBehind="TestService.svc.cs" Factory="WcfUnity.UnityService.UnityServiceHostFactory" %>

    The UnityServiceHostFactory is where we currently registers the types that is to be injected into our code. Right now we're doing it in code, and we're only working with 2 classes; the NHibernate Repository and the NHibernate Session Manager (which is a singleton):

            protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

            {

                var unity = new UnityContainer()

                .RegisterType<IRepository, NHibernateRepository>()

                .RegisterType<INHibernateSessionManager, NHibernateSessionManager>(new ContainerControlledLifetimeManager());

     

                var host = new UnityServiceHost(serviceType, baseAddresses)

                               {

                                   Container = unity

                               };

     

                return host;

            }

    The Session Manager is responsible for setting up the NHibernate Session Factory which is expensive and you only want to do that once. In short - the factory creates a new WCF service host which creates a service behavior which is called each time before a requested service class is instantiated. To be able to resolve and inject our registered classes, the behavior uses a specific instance provider which does Resolve as part of its GetInstance() method. It's all described in detail by Ray in his post, so go check it out. I've not seen a better example of Unity + WCF out there yet and from what I can see in our, so far limited, testing it works well.

    When that plumbing is done (some 4 small classes, that's all), we got a very clean service implementation class with the IRepository injected into it:

        public class TestService : ITestService

        {

            private readonly IRepository _repository;

     

            public TestService(IRepository repository)

            {

                _repository = repository;

            }

     

            // ITestService members goes here...

     

        }

     

    You don't see any trace if a container, just the way it should be. Currently we're looking at our Repository interface and a decent syntax for a Unit Of Work. I'm fond of the lambda style of coding, and I'm playing something like this now:

                var response = new GetPersonResponse();

                _repository.UnitOfWork(() =>

                   {

                       var person = _repository.Find<Person>(request.Id);

                       ret.Person = person;

                   });

                return response;

    Or for a transaction:

                var response = new AddPersonResponse();

                _repository.TransactionalUnitOfWork(() =>

                    {

                        _repository.Save(request.Person);

                        response.Person = _repository.Find<Person>(request.Person.Id);

                    });

                return response;

    The TransactionalUnitOfWork method would do things like:

            public void TransactionalUnitOfWork(Action action)

            {

                _session = sessionManager.GetSession();

                var transaction = _session.BeginTransaction();

                try

                {

                    action();

                    transaction.Commit();

                }

                catch (Exception)

                {

     

                    transaction.Rollback();

                    throw;

                }

                finally

                {

                    transaction.Dispose();

                    _session.Close();

                }

            }

    The "problem" is that the UoW shouldn't go into the repository implementation, it's wrong but I'm only trying things out here. I might as well wrap the opening and closing of a NH Session and transaction within an IDisposable and call it my UoW as many others have done before me, but I kind of like this. Have to think about not letting things that should stay inside the repository "leak" out... At this moment we're only playing around with things :)

    We also need to encapsulate and inject business rules in a good way as we will host the services at more than one customer with different rules. MEF could be an option actually... more on that later :)

  • Please Feedback! Unity, nHibernate, Fluent, Linq... Trying New Architecture Combinations

    We're thinking about a new architecture for a set of pretty large WCF (and perhaps also REST) services that's going to be developed during the next year and perhaps you dear reader would like to comment!

    The services themselves are pretty straight forward, we're going to serve data from a huge SQL Server database which unfortunately is old and lacks relationship/fk/pk between most tables. Nothing we can do about that I'm afraid but we thought that nHibernate could be a good way to map data to domain objects. Some of the services will need to handle more complex business rules, but no heavy computing or long running stuff (not atm anyway).

    What more can I say... everything is going to be running on .NET 3.5, and we have a pretty good view of the business domain, we're currently modelling the information/domain together with the customer and we will probably be developing the whole thing in a DDD-ish way, using unit and integration tests, IoC...

    So, currently we're thinking of WCF/REST for the service layer, Unity as container and building something around nHibernate for the Repository (looking at the IRepository implementation in Fluent). We're new to nHibernate but have been looking at nHibernate.Linq which looks really nice, and I think we'll use the Fluent API and map the classes in code instead of using XML configuration (which I'm allergic against). Just have to figure out a good way to make it all fit together, especially to get a decent UnitOfWork to work with the nHibernate session and the repository. I'll see what I come up with and post it here.

    Ideas? Please comment or send me an email of you like.

  • WPF Learnings - Drawing on Multiple Monitors

    Writespace Some time ago I wrote a fullscreen editing environment add-in for Word to learn some WPF and some Office Ribbon stuff. The editor is called Writespace and is now available om Codeplex as open source.

    Scott Hanselman was kind enough to take a few minutes and review the first draft of the editor and told me I should support multiple monitors and that I could look at BabySmash code to see how he did it. Said and done, I downloaded the BabySmash code, dug into the multi-monitor stuff and found out it's not that strange.

    Writespace is a fullscreen editor, and when the user press CTRL+M I want to move the whole thing over to the next available monitor. First you may want to do some sanity check that you got more than one monitor available. This is easy enough with something like this:

    if (SystemInformation.MonitorCount < 2)

    {

        ...only one monitor available...

    }

     

    The different screens are available via the Screen.AllScreens[] array so once I've picked a screen to draw on I send it as a paramter to a CreateEditor() method:

    private static void CreateEditor(Screen screen)

    {

        var editor = new TextEditorWindow

                        {

                            WindowStartupLocation = WindowStartupLocation.Manual,

                            Left = screen.WorkingArea.Left,

                            Top = screen.WorkingArea.Top,

                            Width = screen.WorkingArea.Width,

                            Height = screen.WorkingArea.Height

                        };

     

        //setting up other stuff, like events and things here...

     

        editor.Show();

        editor.WindowState = WindowState.Maximized; //do this after Show() or won't draw on secondary screens

        editor.Focus();

    }

    The setting of WindowState to Maximized after Show() is a trick/workaround for something that seems to be a bug or something I don't grok about WPF in full screen and multiple monitors. The editor window itself has WindowStyle="None" ResizeMode="NoResize" set.

    Hope this helps someone.

  • Big Problems with iTunes and App Store

    itunesappstoreApple currently got what seems to be huge probs with iTunes and the iPhone App Store. People all over the world cannot log into iTunes App Store to buy and upgrade programs because of connection timeouts. Some people are taking it with a smile, I guess they're used to it:

    It's only 3:30AM in Cupertino. You don't expect an online store to be open in the middle of the night, do you?

    I wrote yesterday about my gripes with iTunes, and this sure doesn't make things better I can tell you. One would think that Apple had the App Store system spread out the world for concurrency and minimize problems like this, but apparently not.

  • iTunes and iPhone...

    Why is iTunes one of the most widespread, annoying, unresponsive but still CPU-munching program out there? Probably because you cannot sync your iPhone without installing it... It's amazingly bad and Apple has to do something about it.

    There... feels much better now, but I'm definitely getting closer and closer to that jailbreak decision.

  • Windows Live ID Becomes an OpenID Provider

    openid According to this blog post on the Windows Live Dev blog:

    Beginning today, Windows Live ID is publicly committing to support the OpenID digital identity framework with the announcement of the public availability of a Community Technology Preview (CTP) of the Windows Live ID OpenID Provider.

    You will soon be able to use your Windows Live ID account to sign in to any OpenID Web site!

    The Windows Live ID OpenID Provider (OP) enables anyone with a Windows Live ID account to set up an OpenID alias and to use that alias for identification at an increasing number of OpenID 2.0 relying party sites-for example: Plaxo, Pibb, StackOverflow.com and Wikispaces.

    I think it's just brilliant and a move in the right direction.

  • Visual Studio 2010 and .NET Framework 4.0 CTP Direct Links

     Visual Studio 2010 and .NET Framework 4.0 CTPVisual Studio 2010 and .NET Framework 4.0 CTP

    Want to download and play with the VS 2010 bits? You can read about and download it from MSDN Downloads, or install a pretty good Download Manager (open source, GNU GPL, quite good IMHO) and cut/paste the direct links below.

    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part11.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part10.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part09.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part08.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part07.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part06.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part05.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part04.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part03.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part02.rar
    http://download.microsoft.com/download/d/c/5/dc51bdda-8925-4aef-b6d9-4d07e4dc6737/VisualStudio2010CTP_11PartsTotal.part01.exe

    NOTE! There are some system requirements that you should be aware:

    • Supported Operating Systems: Windows Server 2003; Windows Server 2008; Windows Vista; Windows XP
    • Minimum 75 GB available HDD space
    • The host computer must have a minimum of 2 GB RAM, with 1 GB allocated to the host operating system and 1 GB allocated to the VPC.
    • We recommend that the host computer CPU be at least a Core Duo 2 GHz processor.
    • Service Pack 1 of Microsoft Virtual PC 2007 is required to access the VPC.

    You also need to download and install Virtual PC 2007 and then upgrade to Virtual PC 2007 Service Pack 1.

  • WCF Client Calling ASMX Service with Soap Headers

    Need to send soap headers from WCF (Service Reference) clients to older ASMX services? The ASMX service not handling the header properly? It may have to do with namespaces being set in the soap header XML in a way differently from what the ASMX service is expecting.

    So, how do you create and add the same type of headers, with the correct namespace, in a WCF client? For every outgoing call?

    First, a simple ASMX service for your pleasure to play with:

    [WebService(Namespace = "http://tempuri.org/")]

    public class Service1 : WebService

    {

        public MyHeader myHeader;

     

        [WebMethod]

        [SoapHeader("myHeader")]

        public string HelloWorld()

        {

            if (myHeader != null)

                return "Got header: " + myHeader.MyFirstValue + " " + myHeader.MyOtherValue;

     

            return "Got no header!!";

        }

    }

    That's it on the server side. Over to the client side... Well, the header itself can be either a class which implements the MessageHeader class, but I prefer to use a normal class decorated with DataContract attribute. Notice the namespace property which matches the one on the service above:

    [DataContract(Namespace = "http://tempuri.org/")]

    public class MyHeader

    {

        [DataMember]

        public string MyFirstValue { get; set; }

        [DataMember]

        public string MyOtherValue { get; set; }

    }

    In ASMX clients you normally create a soap extension to add the header to every outgoing call, but here the ASMX soap extension is replaced by a (Client)MessageInspector in WCF, which is added to a client endpoint via a behavior. I'm cramming the whole sample implementation into one class:

    public class AddSoapHeaderBehavior : BehaviorExtensionElement, IClientMessageInspector, IEndpointBehavior

    {

        #region IClientMessageInspector Members

     

        public void AfterReceiveReply(ref Message reply, object correlationState) { }

     

        public object BeforeSendRequest(ref Message request, IClientChannel channel)

        {

            var myHeader = new MyHeader { MyFirstValue = "Yeeehaaaw!!", MyOtherValue = "Gaaah!" };

            var messageHeader = new MessageHeader<MyHeader>() { Actor = "Anyone", Content = myHeader };

     

            request.Headers.Add(messageHeader.GetUntypedHeader("MyHeader", "http://tempuri.org/"));

            return null;

        }

     

        #endregion

     

        #region IEndpointBehavior Members

     

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) { }

        public void ApplyClientBehavior(ServiceEndpoint serviceEndpoint, ClientRuntime behavior) { behavior.MessageInspectors.Add(this); }

        public void ApplyDispatchBehavior(ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher) { }

        public void Validate(ServiceEndpoint serviceEndpoint) { }

     

        #endregion

     

        #region BehaviorExtensionElement Members

     

        protected override object CreateBehavior() { return new AddSoapHeaderBehavior(); }

        public override Type BehaviorType { get { return GetType(); } }

     

        #endregion

    }

    The endpointbehavior and behaviorextensionelement member implementations are just boilerplate stuff that should be hidden as default behavior by WCF if you ask me, but you need to type this out.

    Finally, the behavior must be loaded in the config (or via code):

    <?xml version="1.0" encoding="utf-8" ?>

    <configuration>

      <system.serviceModel>

        <behaviors>

          <endpointBehaviors>

            <behavior name="MyEndpointBehaviors">

              <ClientSoapHeaderAdderBehavior />

            </behavior>

          </endpointBehaviors>

        </behaviors>

     

        <extensions>

          <behaviorExtensions>

            <add name="ClientSoapHeaderAdderBehavior"

                type="MyBehavior.AddSoapHeaderBehavior, MyBehavior, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />

          </behaviorExtensions>

        </extensions>

     

        <client>

          <endpoint name="Service1Soap"

                    address="http://localhost:4221/Service1.asmx"

                    binding="basicHttpBinding"

                    behaviorConfiguration="MyEndpointBehaviors"

                    contract="ClientProxy.Service1Soap" />

        </client>

      </system.serviceModel>

    </configuration>

     

    Hope it helps someone.

  • WPF Learnings - Animated Screen Glint Effect

    To learn some WPF I wrote this full screen editor called Writespace, which is now open source on Codeplex. I wanted to add some bling to the editor when it was loaded up, so I created a simple animated "screen glint" effect which is totally useless but looks kind of nice (IMHO). Basically it's a semi-transparent gradient, in a rectangle, on a canvas, the size of the screen, which animates over the screen from left to right.

    Sample app

    I had a question about the best way to do this over at Stackoverflow, so check it out if you want some sample code which produces the test-output you see above (which is in mid-animation :)

  • LINQ to XML in VB.NET and Using the Right Language for the Job

    I'm almost always using C# in my .NET projects, unless I'm doing Office automation where the VB-way of dealing with optional parameters helps out making the code a bit cleaner.

    The last week we've been upgrading ASMX-clients to become WCF-clients for a number of old .NET 1.1 and 2.0 projects, and we ended up with a bunch of app.config files with loads and loads of WCF client endpoint sections, each of them pointing at their own binding configuration. To manually clean this up would take hours and hours of tedious work which would probably result in more than a few errors.

    So I thought maybe I could do search/replace with a regexp-capable editor... or try out XML Literals in VB.NET. I wanted to remove old behaviors, extensions and bindings, then add my own behaviors and extensions and finally change some attributes on each client endpoint. Doing this with XML Literals and XDocument/XElement in VB.NET was quite straight forward and didn't result in too many lines of code:

    Imports System
    Imports System.Xml.Linq
    Imports System.IO
    Imports System.Linq
        Sub FixupConfig(ByVal infile As String, ByVal outfile As String)
            Dim defaultBindingConfigurationXml = <binding name="defaultBindingConfiguration"
                                                  maxBufferSize="1065536"
                                                  maxBufferPoolSize="524288"
                                                  maxReceivedMessageSize="1065536"/>
    
            Dim behaviorsXml = <behaviors>
                                   <endpointBehaviors>
                                       <behavior name="FacadeSoapEndpointBehavior">
                                           <SetMaxFaultSizeBehavior size="100000"/>
                                           <ClientExceptionHandlerBehavior/>
                                       </behavior>
                                   </endpointBehaviors>
                               </behaviors>
    
            Dim extensionsXml = <extensions>
                                    <behaviorExtensions>
                                        <add name="SetMaxFaultSizeBehavior" 
    type="SomeType.SetMaxFaultSizeBehavior, SomeAssembly, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=null
    "/> <add name="ClientExceptionHandlerBehavior"
    type="SomeType.ClientExceptionHandler, SomeAssembly, Version=1.0.0.0,
    Culture=neutral, PublicKeyToken=null
    "/> </behaviorExtensions> </extensions> Dim xdoc = XDocument.Load(infile) xdoc...<system.serviceModel>.<behaviors>.Remove() xdoc...<system.serviceModel>.<extensions>.Remove() xdoc...<system.serviceModel>.Single().AddFirst(extensionsXml) xdoc...<system.serviceModel>.Single().AddFirst(behaviorsXml) xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Descendants.Remove() xdoc...<system.serviceModel>.<bindings>.<basicHttpBinding>.Single().Add(defaultBindingConfigurationXml) Dim elems = xdoc...<client>.<endpoint> For Each element In elems element.@bindingConfiguration = "defaultBindingConfiguration" element.@behaviorConfiguration = "FacadeSoapEndpointBehavior" Next xdoc.Save(outfile) End Sub

    I've heard people recommend to use VB.NET when dealing with XML and I agree - use the right language for the job. When doing this - remember to import System.Linq or you'll miss some vital extensions like the .Add() and .Single() methods ;)

  • Windows Home Server Learnings - Don't Install the HP Add-Ons

    This is a general warning to Windows Home Server owners in general and HP Media Smart Server owners in particular. The "Power Pack 1" update to WHS comes with 2 add-ons:

  • McAfee’s Total Protection Service (anti-virus/anti-malware)
  • PacketVideo’s PVConnect Media Server (media sharing)
  • But unless you've gone through the hard work to actually upgrade the memory from 521MB to 2GB, don't install these add-ons because you may end up with a totally unusable home server. The hardware just isn't up to it! PVC alone requires 512 MB.

    I actually tried to installed PVConnect and the first thing I noticed was that the WHS Console was quite non-responsive and sluggish it it's behavior. Then I clicked the PVConnect "tab" and got this, in spanish!?!

    PVConnect

    After a while I got tired of it and went to install it, which wasn't easy because of the non-responsive console. Eventually I got rid of it, but not without blood shed:

    Crap

    Like the missing/transparent/black features? :) Anyway, I clicked the white (that I presume said "OK") button and the Console got reset. Now I was soon greated by the "Your WHS Network is at Risk" notification:

    What risk? I log on to the WHS and to see what's wrong:

    Network Health

    This health warning thingy in WHS is not making sense to me. What is there to warn about? Will this list be a mile long in a year? I need to clean this list up... does anyone know how to do it? BTW. The AV software on my mediacenter server IS NOT out of date...

    There's a good story about this on Rafael's Within Windows blog.

  • Writespace - Fullscreen Writing Environment Add-in for Word

    Logo2_white_small I just published this open source project on Codeplex, and this information is available on the Writespace Codeplex home page as well.

    Writespace is a fullscreen writing environment, developed with WPF (Windows Presentation Foundation) as a ClickOnce installed add-in for Word 2007 . Unfortunately Codeplex cannot host ClickOnce applications, so to install the add-in you will have to download and run the installer locally until I've found a site to host it.

    Writespace is inspired by Dark Room (http://they.misled.us/dark-room) for Windows and Write Room (http://www.hogbaysoftware.com/product/writeroom) for OS X. One advantage of Writespace is the built in spellcheck support (English, French, Spanish and German).
    margin1.png
    The program is quite simple, but I've been missing a plug-in for Word like this one. I've been using the excellent Dark Room editor, but unfortunately it doesn't have support for spell checking or Word integration.

    IMPORTANT NOTE

    Always, always, always keep a copy of your orginal document or text before you try out or use Writespace so you can revert if things go bad. Writespace is work in progress and has not yet been tested enough to be called "stable".

    System Requirements

    NOTE: I need help with specifying the requirements to run this, but personally I'm on Vista, .NET 3.5 SP1 and Word 2007.

    Downloads and Installation

    The add-in is installed as a ClickOnce application, but it's not possible to host ClickOnce installers on Codeplex, so you will either have to download the binaries as a zip or download the source and run it from Visual Studio 2008.

    Shortcuts

    Writespace supports the following shortcuts from within the writing environment:
    CTRL+Mousewheel - Zoom in/out
    CTRL+F - Search
    F3 - Find next
    CTRL+G - Go to line
    ESC- Exit to Word
    CTRL+S - Save
    Writespace also supports the standard Undo/Redo/Select/Cut/Paste functionality you are used to.

    Word Integration

    Writespace is started from the View-tab of the Word 2007 Ribbon, just click the "Writespace" button and the text of the current document is grabbed and put into the Writespace full screen editor. When you escape from Writespace, the text in the Word document is updated with the text from Writespace. Note that Writespace removes all formating of the text, so italics, font size, bold text, is removed and converted into the font, color and size Writespace uses. Word documents containing tables, pictures and other "non-text" content will not be possible to move to the Writespace editor, and you will get an error dialog if you try this. This is to protect you from messing things up.
    ribbon.png

    Text Formatting

    Writespace does not have any support for formatting the text. You can select the size, color and type of font, which will affect the whole editor, but that's it. This may change in the future though. Note that if you enter the Writespace editor from an existing document in Word, the formatting of that text will be removed and converted to plain Writespace text.

    Spell Check

    Writespace uses the built in spell checking support which comes with WPF. Language is set from the options dialog. Unfortunately WPF only supports English, French, German and Spanish at the moment. If you still want to spell check your text, just escape back to Word and let it handle that for you.
    spelling.png

    Drag/drop Margin

    The left and right side margin can be changed without leaving Writespace. Just move the mouse over the left margin until it lights up, and adjust the size of the margin until you are satisfied.
    margin1.png
    Drag the margin with left mouse button and release. The new margin size will be saved to settings automatically.
    margin2.png

    Find

    Press CTRL+F to display the find dialog. Press F3 to find next, next, next... as you are probably used to.
    find.png find_result.png

    Goto Line

    Press CTRL+G to display the goto dialog which helps you go to a specific line in the text.
    goto.png

    Status Bar

    The editor has a descrete status bar to show information about file saved and it also displays the current row and column in an animated, fade-out way. Feedback about the status bar and the row/col informaiton is appreciated.

    Mousewheel Zoom

    The font size can also be changed without leaving the writing environment. Just hold CTRL and use the mouse wheel to zoom in our out of the text. The current size will also be saved to the settings.

    Options

    It's possible to set color, font, size and margin from the options dialog. It's also possible to enable/disable spellchecking by specifying the language. 
     Options_small

    (image is shrinked down to fit in the blog)

    Writespace Re-use

    The Writespace editor and options dialog have public classes, methods and properties which makes it possible to run it from other .NET compatible languages. This will be better documented in the future.
  • Expiring Temp ClickOnce Certificates - Create Your Own With Long Expiration

    I'm looking at ClickOnce and ran into several blog posts where people were worried about expiring certificates when using a temporary PFX file created by VisualStudio. Appearently the certs issued by VS expire after a year and you will probably start running into problems with new deployments after that.

    There is a KB article on MSDN that describes this problem but doesn't offer any good solutions (IMHO). Instead, if you have the Windows SDK installed you can create a certificte with much longer expiration, then create a PFX file from the cert and use with your ClickOnce application:

    makecert.exe -r -pe -a sha1 -n "CN=MyClickOnceApp" -b 01/01/2000 
    -e 01/01/2036 -eku 1.3.6.1.5.5.7.3.3 -sv MyClickOnceApp.pvk MyClickOnceApp.cer
    pvk2pfx.exe -pvk MyClickOnceApp.pvk -spc MyClickOnceApp.cer -pfx MyClickOnceApp.pfx

    This has been described in several places out there and my initial tests with makecert/pvk2pfx seems to work well so I'm storing the steps here for later use. I'm going to use it for a Codeplex project I'm opening up soon, so stay tuned...

  • A Decent Search Replace In Multiple Files Tool

    TextCrawler screenshotJust wanted to share this tool with you.

    I needed to search/replace text strings in some 600 files, and I've been downloading a bunch of crappy utilties that doesn't deliver. TextCrawler does this one thing and it does it good. A few features listed from their homepage:

    • Find and Replace across files
    • Fast searching, even on large files.
    • Simple to use interface
    • Flexible search parameters
    • Text Extractor - rip text into a new file
    • Search and replace using Regular Expressions.
    • Regular Expression test tool
    • Regular Expression library - Save your searches.
    • Create backup files
    • Highlighted search results
    • Export Results
    • Batch find and replace operations

    Also, it's freeware :)

  • Status of Messenger Services

    image

    Yeah sure :)

    Is it just me or has the Messenger service been kind of flunky the last couple of days? I keep getting these 81000314 error codes all the time. Not even WebMessenger is working.

  • Better Log Formatting for CruiseControl.NET and MSBuild

    cruisecontrol This is just a blog post to bump the topic on search engines to help people using MSBuild and CruiseControl.NET to get to the right place. I personally recommend to use the "Improved MSBuild Integration" logging option by Christian Rodemyer. If you follow the instructions on this page, you'll get it right.

    You may also have to change the dashboard stylesheet somewhat if you want to add or remove smileys or other GUI-related things depending on the results from unit testing etc, but the output in the CruiseControl dashboard is nice and clean.

  • How to Update Google Chrome

    googlechromeSo you've downloaded and installed the beta of Google Chrome and found that that Ajax story of Chrome isn't the best? You're thinking that the Google guys must have fixed it by now and you start looking for news related to Chrome on *.google.com but finds nothing... a bit frustrating to me at least.

    Then you find out there's no obvious way to "Check for update..." in the Chrome app itself - unless there's actually a new version available! The trick is to click the "Customize and Control Google Chrome" button and look at the "About Google Chrome..." dialog, which will check to see if there's a new version available. If there is, it'll look something like this down at the bottom of said dialog:

    google-chrome-about-new-version

    Dave Taylor has written a nice detailed blog post about it, that's how I found out. Thanks Dave!

    If anyone knows of an RSS feed, or official site to get news about Chrome updates, I'd love to get that URL.

    UPDATE: It seems that the best URL is "The Official Google Blog" on http://googleblog.blogspot.com/ which unfortunately doesn't seem to use categories or tags unless I'm not blind. Would have been nice to have a Chrome category/tag as I'm not that interested in Picasa and the Democratic National Convention... :/

    Now I just hope the introduction of Google Chrome doesn't lead into another browser war with website-breaking features like those we've had so many problems with before.

  • Google Chrome and Facebook...

    googlechrome ...is just not working as it should. There are major Ajax problems in that browser. I know, it came out like this week, but they talk much about the rigorous testing they go through and how Chrome should work well on popular sites. Well Facebook should count as quite popular I guess.

    I'm sure it'll be fixed very quick, and other than that - the browser seems to work pretty well. The UI feels clean and bare-bone, and occationally it feels somewhat faster.

    I like the Google Chrome story they made, very cool.

  • Sorry, Deleting Your Account Can Not be Done Easily at the Moment

    image That's the message I got from the people at a free wiki hosting site when I asked them to terminate my account. I'm thinking their wiki-system is either a mad hack with database dependencies all over the place, or they just want to keep their member count up...

    They told me to "go to Account settings and disable everything you can find there"...

    Sigh... what to say? I was invited by a friend for a project of his. I know this situation is not unusual, and sometimes it can be hard (like removing yourself from Facebook before they made it much easier due to the massive preassure from the users), but things like this upsets me.

    I guess I have to blame myself for registering there in the first place and I guess it's more or less a fact that if you register yourself at a (most often free) site on the Internet, expect to get a number of newsletters and stuff from that site eventually and don't expect it to be easy to terminate your account.

  • Hug a Developer

    This video gave me a few laughs :)

     

  • ASP.NET MVC Preview 5 Released

    Hey, I'm just helping to spread the word! A sampled a few links and quotes that has already been posted to blogosphere for your pleasure and knowledge. :)

    Download it here -> http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16775

    Phil Haack said:

    We didn’t originally plan to have another preview. However, we implemented a few significant chunks of functionality and were dying to get feedback so that we could incorporate it into the product before Beta. It helps that with five or so of these interim releases, we’ve become pretty efficient producing these releases.

    We plan to have our next release be our official Beta, which means we’ll have a lot more test passes to produce and run before we release the next one.

    Some preview 5 related blog posts:

    Brad Wilson wrote about changes to partial rendering and view engine in preview 5.

    Maarten Balliauw wrote about easier form validation with preview 5.

    Nick Berardi has a list of news and changes and also a few issues he's found and submitted bug reports for:

    Derik Whittaker had a few comments regarding sealed classes in preview 5:

    It looks like that they removed the sealed keyword from many of the Attributes such as HandleErrorAttribute, AuthorizeAttribute and various other existing Attributes. 

    However, looks like many of the other attributes (some new, some not) such as AcceptVerbsAttribute, ModelBinderAttribute and NonActionAttribute are still marked as sealed.  Guys, please unseal all your stuff.  If you have a very, very, very valid reason then fine seal them.  But if not, let developers loose and unseal them.

  • Auto Postback with Javascript in ASP.NET MVC

    I've looked this up twice now so I'm posting it to my blog for future reference and as a quick-tip for others. Say you got a web page with a dropdown/select listbox and you want to reload/auto postback the page when the selection changes.

    image

    One way to do this without involving a Javascript or Ajax library like jQuery (which probably is a good idea anyway :) is to use the "htmlAttributes" parameter of the Html.DropDownList() helper method and add a "onchange" attribute through an anonymous type. Something like this:

        Select a name: <%=Html.DropDownList("Name", ViewData.Model, 
    new { onchange = "doSomeJavascript()" })%>

    To submit a form, for example:

        <% using (Html.Form<HomeController>(p => p.DropDown(), 
    FormMethod.Post, new { id = "myform" })) {%> Select a name: <%=Html.DropDownList("Name", ViewData.Model,
    new { onchange = "document.getElementById('myform').submit()" })%> <% } %>

     

    The minimal DropDown() method of the HomeController class to support this sample looks like this:

    public object DropDown()
    {
        var list = new List<string> { "Adam", "Bob", "Charlie" };
        return View(new SelectList(list, Request["Name"] ?? list.First()));
    }

    As you can see, the htmlAttributes parameter is available on many of the Html-helper methods and I'm using ot to add a name attribute to the HTML form as well.

    End Note About Basic Knowledge of Javascript and Html

    Heh, ASP.NET MVC sure forces you to dust off that old, basic knowledge of HTML and Javascript that I think every web developer should have but the ASP.NET programming model has made us forgot... One could argue that it's niggy gritty stuff that we shouldn't have to worry about, but for me it feels good to know I'm in full control of the generated HTML and I'm not sending one byte more on the wire than what's needed. Yes, it's possible to have the same control with standard ASP.NET applications and controls, but I've seen experienced developers make mistakes around this more than once. ViewState anyone? :D

  • Returning Json from RESTful Interface with WCF

    WCF2 Someone commented on an earlier blog post I did on REST, POX/POJO and WCF and the comment read:

    How about REST WCF bits from .NET 3.5 SP1? Is it possible now to let the user decide in which format he wants the response (xml or json) like MySpace API for example?

    The convention is to use a file like extension at the end of the resource to specify data return type (.xml or .json)

    api.myspace.com/.../details.xml

    api.myspace.com/.../details.json

    UPDATE/EDIT: Turns out I was doing this the hard way as there is support for json serialization right from the ServiceContract which makes this extremely easy. Just make sure to specify the ResponseFormat to be json. In a previous "version" of this blog post, I used the JavaScriptSerializer class, which is... dumb :)

    First go take a look at the sample that Kirk Evans had on his blog.

    Note that it may be easier to create a RESTful interface with ASP.NET MVC if you're into that tech, but that's another blog post.

    So, first I'm modifying the REST interface somewhat, adding support for /details.xml and /details.json URI:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate="customers/{id}/details.xml")]
        Customer GetCustomer(string id);
    
        [OperationContract]
        [WebGet(UriTemplate = "customers/{id}/details.json", 
    ResponseFormat=WebMessageFormat.Json)]
    Customer GetJsonCustomer(string id); }

    As you can see, on the GetJsonCustomer() method, I'm specifying the ResponseFormat to be json. That's it :)

    A sample implementation for this interface looks like this:

    public Customer GetCustomer(string id)
    {
        return new Customer { ID = id, Name = "Demo User" };
    }
    
    public Customer GetJsonCustomer(string id)
    {
        return GetCustomer(id);
    }

    Using Fiddler to simulate client request and see what comes out of our RESTful service, we get this result from the /customers/123/details.xml request:

      <Customer xmlns="http://schemas.datacontract.org/2004/07/RESTfulWCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><ID>1</ID><Name>Demo User</Name></Customer>

    ...and this from the /customers/123/details.json request:

      {"ID":"123","Name":"Demo User"}

  • Why Developers Are Interested in REST

    I had a laugh when I saw James Kovacs' blog post abot Why Developers are Interested in REST:

    I'm doing some WCF work for a client, specifically around WS-Security. I stumbled upon the System.ServiceModel.MessageSecurityVersion class today. Its static properties alone should explain why developers are craving simpler technologies like REST...

    I think he's got a point there actually. Web services with WCF can be very easy to use, and it can be so very complex it'll get your head to spin. The REST and POX/POCO style of services is definitely getting more attention, even from within Microsoft. WCF now supports RESTful interfaces, and we've seen REST-related demos by well known Microsoft presenters several times now, especially around WCF, EF and Astoria/ADO.NET Data Service. Also, it's very easy to create a RESTful service with ASP.NET MVC. We saw several REST-related presentations at Mix07 and Mix08 and I'm sure there will be a lot of REST/POCO/POX/Atom demos at PDC later this year.

    Ofcourse there will be a number of situations and type of applications which require a more complex protocol than what REST can offer, but as a developer and software architect who prefers simple solutions, I just love the simplicity of it all. Or maybe I'm just old and smilingly recognize old techniques coming back again - we did XML on (S)HTTP with ASP years and years ago, didn't we? And it worked pretty darn well I can tell you ;)

    The "REST effect" is perhaps the result of the WS-* race, which in my opinion exceeded the speed limit a long time ago. It's just impossible for an average human beings to keep up with it unless you want to become a WCF/WS expert and do nothing much else, which is not an option for me. I know, there are people out there, like my colleague Eric, who groks it all, but he's not human ;)

  • SyncToy 2.0 Released

    image Version 2.0 of SyncToy has been released on MSDN Downloads. SyncToy does not replace FolderShare for syncing files between different computers, but is a more effective way to copy/move/sync files on your computer. The dev-team uses the tool primarily to move pictures and music from devices (cameras, mp3 players etc) to folders on their computers or network shares in a more effective way. It's not a service/system tray kind of thing, just a utility that remembers a number of different "syncs" you've setup so that you can run them again and again when you need to.

    The download page says:

    SyncToy, a free PowerToy for Microsoft Windows, is an easy to use, highly customizable program that helps users to do the heavy lifting involved with the copying, moving, and synchronization of different directories. Most common operations can be performed with just a few clicks of the mouse, and additional customization is available without additional complexity. SyncToy can manage multiple sets of folders at the same time; it can combine files from two folders in one case, and mimic renames and deletes in another case. Unlike other applications, SyncToy actually keeps track of renames to files and will make sure those changes get carried over to the synchronized folder.

    The tool has got a number of new features added from version 1.0, and I'm listing a few interesting ones:

    • Dynamic Drive Letter Assignment
    • True Folder Sync
    • Exclusion Filtering Based on Name
    • Filtering Based on File Attributes
    • Command line enhancements: Added the ability to manage folder pairs via the command line interface.
    • Sync Encrypted Files
    • 64-Bit Support

    SyncToy is built upon the Microsoft Sync Framework, which seems to get better and better all the time. Worth keeping an eye on for everyone involved in developing applications which requires replication or off-line modes.

  • The Touch Wall Demonstration by Bill Gates

    This video has been around for a few months now, but it's still cool. It's not one of Bill's better demos as he's kind of standing in the way of the screen all the time, but it still shows off the Touch Wall/Surface capabilities pretty well. I'm sure we'll see something like this in class rooms and larger meeting rooms in the future. It's easy to learn to use, but the presenter will have to learn how move on the podium as well as work with the presentation and give the talk. Interesting... what do you think?

     

     

     

    The video sequence is from the Microsoft CEO Summit 2008.

  • Excel Automation - Example with Named Ranges

    excel And now to something completely different... the Excel automation. Every now and then you need to open up an Excel file and do stuff with it. In this case we needed to create and read from named ranges in Excel, and it's not overy easy to get information about how to do that, so I thought I might as well post some sample code here.

    To get started with Excel automation, there is a good KB-article on MSDN: http://support.microsoft.com/kb/q302094

    Now, here's a console app in .NET 3.5 using VB.NET (I prefer to work with VB.NET with Office Interop and VSTO), which opens Excel, adds a new workbook, creates a (3,5) string array with values, fills the a range with these values, creates a named range and gets the values again to see that it worked properly.

    Imports Microsoft.Office.Interop
    
    Module Module1
    
        Sub Main()
            Dim application = New Excel.Application
            application.Visible = True
            Dim workbook = application.Workbooks.Add()
            Dim worksheet As Excel._Worksheet = workbook.ActiveSheet
    
            Dim saRet(3, 5) As String
    
            For iRow = 0 To 3
                For iCol = 0 To 5
                    saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()
                Next iCol
            Next iRow
    'get a range, alternative 1 'Dim range As Excel.Range = worksheet.Range("A1:E3", Reflection.Missing.Value) 'get a range, alternative 2 Dim range As Excel.Range = worksheet.Range("A1", Reflection.Missing.Value) range = range.Resize(3, 5) 'set value of range to that of the string array range.Value = saRet 'name the range, explicitly (using dollar $ sign) workbook.Names.Add("NamedRange", "=$A$1:$E$3")
    'clear range range = Nothing 'get the values of the named range range = worksheet.Range("NamedRange") Dim values(,) As Object = range.Value Console.WriteLine("rows:" & values.GetUpperBound(0)) Console.WriteLine("cols:" & values.GetUpperBound(1)) Console.WriteLine("value of row 2, column 4 (D4) = " & values(2, 4)) Console.WriteLine("Press key to exit...") Console.Read() workbook.Close(False) application.Quit() End Sub End Module

    Hope this helps someone.

  • Totally Off Topic - Swedish Rune Stones From the Viking Age

    Ölsastenen This is totally off topic from the things I usually write about, but I thought I might show some pictures of a few beautiful rune stones we have scattered around not far from where we live (Botkyrka, southern part of Stockholm, Sweden) and tell you something about this particular type of landmark the Vikings left us. My knowledge of rune stones and runic inscriptions are minimal and I may get some info slightly wrong here, so bear with me :) I'm sure Wikipedia got tons of info on the topic if you hunger for more.

    The typical rune stone is a raised stone with runic inscriptions on it, but it also happens that you run across runes inscribed on bedrocks. It seems that the main purpose of these stones where to mark important events, explain inheritance, boast about the construction of a bridge or a road and very often to bring glory to kinsmen who travelled far and (quite often) died in foreign lands. Most rune stones are located in Scandinavia (Sweden, Norway, Denmark, Iceland), but there are also a few in locations where the Scandinavians of that time (mostly Norsemen) went, like England, Greenland and Ireland.

    What's so cool is that most of these stones were carved and erected during the Viking Age (from around year 790 to 1100), and thousands of these stones still stand where they were erected more than a thousand years ago. Some stones have been moved from where they were first found to a place close nearby where they are more accessible to folks who are interested in them. Through the years stones have been destroyed by construction, stolen by collectors and damaged by air pollution but still there are over 6.000 registered rune stones or fragments of them around, most of them (over 3.000) are located in Sweden, and most of those in the province of Uppland on the eastern coast of Sweden, just north of Stockholm.

    In Sweden, most of the stones are kept in a healthy state and looked after by a state organization. These people remove lichen and sometimes paint the runes with red paint, which is believed to be the most common color used. There are stories of runes being reddened by blood, but that's probably just that - stories. The rune stone above to the right is called "Ölsastenen", found in Uppland but moved to Skansen, an open air museum and zoo located in the middle of Stockholm. It is painted in (probably) authentic manner. That picture I took with my mobile camera, so the quality is quite bad.

    If you ever visit Stockholm and want to see a few rune stones, Skansen is probably the easiest place to go.

    The alphabet used on most of stones around where we live is the one called The Younger Futhark which consists of 16 characters:

    younger futhark

    Some experts are so skilled in this language, they can read it right off the stones if the runes are clear enough to read. What may be interesting to know is that the English language borrowed hundreds of words from the language spoken by the Vikings of this age, Old Norse. The Scandinavian words were introduced during the Viking invasion of England in the 9th and 10th century. It's easy to recognize some of the words written on the rune stones in both the English and Swedish language. For example, the Viking word faþur, means father which is fader in Swedish. There are many, many other examples of old, basic words which are similar in English and Swedish. Now, I think that Old English and Old Norse were derived from the same Germanic language, so it may be that the word father came from there, but it's still cool. I've read somewhere that Scandinavian "businessmen" visiting the British islands could make themselves understood quite well, even without screaming and raised swords...

    Most of the rune stones in the Uppland area have a Christian cross carved into them, showing they were of the Christian faith or supported a Christian king.

    Hamra

    This picture I took with a somewhat better camera and show the stone at Hamra (Sö 289). It reads "Björn and Holm--- erected this stone after Kättilbjörn, their --- God help the soul". Some carvings cannot be clearly read as you can see.

    Uringe, Grödinge

    This is the stone at Uringe (Sö 298) and reads "Håur and Karl and Sighjälm and Vihjälm and Kåre erected this stone after Vigmar, their father". How nice of them! The stone is over 1000 years old.

    Uttran

    To get an understanding of the size of some of these stones, here's a picture of the stone at Uttran (Sö 305) and myself. The picture is taken by my son Pontus and a rune stone excursion we did earlier this summer. This stone was erected by two brothers and reads "Sibbe and Tjarve erected this stone after Torkel their father".

    Glömsta Glömsta

    The pictures above show the bedrock carvings in Glömsta (Sö 300), just 5 minutes from where we live. This rune stone is a bit special because it's dedicated to a mother: "Sverker built the bridge after Ärengunn, his good mother". The bridge Sverker mentions is probably not a bridge over water, but rather improvement of the (what is believed to be an important) road that passed by this very place. So to honor his mother, perhaps he inherited lands from her, Sverker had this road improved and let everyone that used it read about this. 1000 years ago. I know, it's not like wall paintings in pyramids, but still cool.

  • My Toolbelt

    ToolbeltMy friend Jan-Erik told me he was about to write a blog page about good tools he is currently using, so I thought I might just do the same. I like my machine clean, so if I'm not using a program or tool for some time, it's out. I'm not listing the most obvious tools and programs from Microsoft (word, vs etc.), but these tools I use frequently and they help me do my work as a developer and software architect, so in no particular order:

    Windows Live Writer - a wonderful tool from Microsoft for writing and managing your blog posts. I'm using it now and will probably use it for a very, very long time. It's that good.

    Cropper - a superb screen capture utility by Brian Scott. It's small, neat and looks great too :)

    µTorrent - a pretty good bit-torrent client that just works.

    Fiddler - web debugger by Microsoft (written by Eric Lawrence I believe) that will help any developer who's into AJAX, REST, ASMX, WCF, plain HTML or whatever project that involves sending stuff over HTTP.

    Paint.NET - not as good as Photoshop, but not far from it and free! Written in .NET, this wonderful program gets new features every week it seems. Was #19 on PC World "Top 100 Products of 2007".

    Foxit Reader - a light weight, free, alternative to Adobe Reader for reading (and annotating) pdf files. I wish I could replace all programs from Adobe like this, man how I hate the extra junk Adobe installs on my machine. I just want to be able to read PDF files... same call goes to HP while I'm at comapnies that install "things" that bogs down the startup of my laptop.

    Gmail Notifier - I don't use Gmail alot, sometimes I'm not in there for over a week or two, so a notifier is required or I'll miss some important message. This notifier is not great, but it works (most of the time). Thinking of boiling my own notifier or just jack Gmail into Outlook...

    TortoiseSVN - the "The coolest Interface to (Sub)Version Control". I use this to get open source projects, like IronRuby and ASP.NET MVC. The Windows Explorer integration is really nice.

    TrueDownloader - open source download manager I've been using for a while now. As with uTorrent above, there are loads of download managers out there, but this one works and has no banners or ads.

    FolderShare - from Microsoft, and it's one of the coolest free tools you can get your hands on. Keep files in sync across your computers, share folders with friends and access your files from any computer. And it works :) If you haven't used this program yet, give it a try. I use it to backup source code and documents between 3 computers.

    Daemon Tools - 'nuf said!

    Developer Specific Tools and Addins

    I thought I'll go through the more developer specific tools and addins in a separate list, so here goes:

    Expresso - a powerful tool to help you write regular expressions. Requires a registration code after 60 days, but it's free.

    NUnit - one of the most frequently used unit test frameworks for .NET out there.

    PostSharp - an aspect oriented programming "weaver" for .NET which plugs in to visual studio and MSBuild. PostSharp is a great tool for doing AOP weaving in .NET, if you need it that is. Read up on AOP before you go there, most times there are other options.

    ReSharper - the number one addin to VisualStudio ever written. If you're a c# or vb.net developer, this is the one tool you should learn to use. There is so much to say about this work of art from the JetBrains, but it makes you way more productive and it helps you become a better programmer.

    GhostDoc - addin for VisualStudio by Roland Weigelt which tries to automatically generate XML documentation comments. No block buster, but it's cute :)

    Moq - a mocking library for .NET which takes good advantage of .NET 3.5 with linq- and lambda expressions. My mock library of choise!

    PowerShell and PowerTab - if you're a powershell user and also a .NET developer, make sure you install powertab by Marc van Orsouw (the powershell guy), which is an extension to powershell that gives you tab-expansion for the .NET library. To get an understanding of the power (heh) of this, check out this DNR-TV episode with Scott Hanselman.

    Reflector - aw, you know this one already! This is a now legendary tool by Lutz Roeder.

    Note: the toolbelt image is a leather toolbelt from Charles & Hudson that I just thought looked great

  • More on RESTful Service with WCF and POX/POCO

    Kirk Eveans wrote a blog post about Creating RESTful Services Using WCF, which gives you a good understanding of how to get started with REST on WCF. In his sample, Kirk has 2 methods in a REST interface:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "customers/{id}")]
        Customer GetCustomer(string id);
    
        [OperationContract]
        [WebInvoke(UriTemplate = "customers")]
        Customer PostCustomer(Customer c);
    }

    The Data Contract for Customer looks like this:

    [DataContract(Namespace = "")]
    public class Customer
    {
        [DataMember]
        public string ID { get; set; }
        [DataMember]
        public string Name { get; set; }
    }

    Kirk also describes how to use the Fiddler tool to send REST request to the service, which is a wonderful tool for these circumstances.

    Now, to get the customer with ID 123, just send a GET request to the url: http://127.0.0.1:8000/customers/123 and the service will return:

    <Customer>
    <ID>123</ID>
    <Name>Demo User</Name>
    </Customer>

    To call the other method, PostCustomer(), send a POST request to http://127.0.0.1/customers with the following request body:

    <Customer>
    <ID>123</ID>
    <Name>Demo User</Name>
    </Customer>

    This returns:

    <Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ID>123</ID>
    <Name>Hello, Demo User</Name>
    </Customer>

    NOTE: Remember that you must add a HTTP header, specifying the content type, or the POST request will fail (Content-Type: application/xml).

    Wrong Order of Nodes?

    But what if the programmer sends the <Name> node before the <ID> node? Like this:

    <Customer>
    <Name>Demo User</Name>
    <ID>123</ID>
    </Customer>

    The service will then return:

    <Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ID i:nil="true"/>
    <Name>Hello, Demo User</Name>
    </Customer>

    Note that the ID is null! If the ID was declared as an integer in the Data Contract, the response from the service would be:

    <Customer xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ID>0</ID>
    <Name>Hello, Demo User</Name>
    </Customer>

    Note that ID is 0 (zero), which could become a somewhat hard bug to catch. I asked Kirk about this and he confirmed the reason for this behaviour is the way the DataContractSerializer works. If no order is specified in the DataContract, it will (de)serialize in alphabetic order. If this is a problem for you, there is away around it by specifying the XmlSerializerFormat attribute on the REST interface:

    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebGet(UriTemplate = "customers/{id}")]
        [XmlSerializerFormat]
        Customer GetCustomer(string id);
    
        [OperationContract]
        [WebInvoke(UriTemplate = "customers")]
        [XmlSerializerFormat]
        Customer PostCustomer(Customer c);
    }

    POCO Support in SP1

    One of the new features in .NET 3.5 SP1 is the support for POCOs - the DataContractSerializer supports serializing types that doesn't have the [DataContract] or [Serializable] attributes. Aaron Skonnard has a good post on this. This means you can safely get rid of the attributes on the Customer class:

    public class Customer
    {
        public string ID { get; set; }
        public string Name { get; set; }
    }

    Note that the DataContractSerializer is still picky about the XML it gets to be able to deserialize it properly. Again, to get a more "relaxed" REST interface where WCF accepts the Name and ID nodes in any order, use the XmlSerializerFormat. I'm not sure this is what you want, but it's an option.

    I had a short mail conversation with Kirk about this, and he raised an interesting question about the lack of a industry accepted standard for describing RESTful services and I think he's right there. The XML-node order wouldn't be a problem at all if I gave the client programmer a schema or a contract which specified exactly how the RESTful interface was to be accessed and in which order the XML-nodes must come. Kirk had a lot to say about this, and I do hope he writes up a blog post about his thoughts ;)

    There are ways to send and receive any XML to a RESTful interface with WCF, and I'll write a blog post about that another day.

  • WPF is Different - The XAML Way of Doing Things

    WPF Wow, I've finally spent some time looking at Silverlight and WPF samples, and it sure takes a while to wrap your head around "The XAML Way of Doing Things". It's so easy to fall back to the WinForms coding style when you're supposed to do it The XAML Way.

    For example, if you have an options dialog with user settings for your app - DON'T do it the old WinForms way, but look at Configuration with Databinding (from Scott Hanselman's adventure with BabySmash). The code behind you need is really minimal if you do it the right way.

    There are also a gazillion ways to handle control events declaratively within the XAML itself, without having to create a code behind event and code things up from there. Take a look at WPF Styles and Triggers and learn it! Especially if you want to create nice looking effects, animations and such, but styles and triggers are useful for more than bells and whistles. For many things related to the UI there are 2 ways of doing it - in XAML or in code behind. There's a pretty good starter on Styles and Triggers on the Microsoft Belgium MSDN site. It may not be wrong to do it in code behind, and some things *must* be coded that way, but always search for The XAML Way of doing it before falling into old WinForms behaviour.

    Finally, what will take me a long time to understand and learn (if I ever learn it) is the XAML layout manager. I'm trying to position a group of controls in the center of a WPF Window that may be in full screen mode. First I used the Canvas panel and hacked away in a WinForms style specifying location depending on screen size and stuff, but I'm sure it can all be done in XAML... somehow *smile* ScottGu wrote an intro for Silverlight 2 on the layout manager, which is good reading if you are new to this.

    I should probably install Expression Blend and learn at least the basics of it. The XAML editor in VS2008 is just not enough for more complex layouts. What scares me somewhat is that a fairly complex WPF/Silverlight window may result in pretty nasty XAML with a bunch of Grids, Stackpanels, Canvases, more Stackpanels within Stackpanels within a certain Grid.Column and so on. Add a bunch more if you're using triggers and animation. I know you can shrink the XAML somewhat by using Styles, but are we getting back into HTML Table Hell again when we've just been saved by CSS?

  • Open a WPF Window from WinForms

    If you find yourself in need to open a WPF Window from a WinForms program - this is one way to do it (works for me):

    1) Create/Add a new project of type "WPF Custom Control Library"

    image

    2) Add a new Item of type "Window (WPF)"

    image

    3) Do your thing with the WPF Window

    4) From your WinForms app, create and open the WPF Window:

    using System;
    using System.Windows.Forms;
    using System.Windows.Forms.Integration;
    var wpfwindow = new WPFWindow.Window1();
    ElementHost.EnableModelessKeyboardInterop(wpfwindow);
    wpfwindow.Show();

    There you go!

    The EnableModelessKeyboardInterop() call is necessary to handle keyboard input in the WPF window if loaded from a non-WPF host like WinForms. I understand there are other ways to do this and you can read more about WPF/WinForms interop here.

  • IronRuby with ASP.NET MVC

    MVCIronRuby Now that ASP.NET MVC preview 4 is out, Phil Haack did as promised and made available a working prototype of IronRuby + ASP.NET MVC integration. He wrote:

    Now that Preview 4 is out, I revisited the prototype and got it working again. I use the term working loosely here. Yeah, it works, but it is really rough around the edges.

    To be able to use Ruby with ASP.NET MVC there has to be some c# glue/bridge code, especially in global.asax, which loads the routing tables (via extensions) and points at a specially made Ruby Controller Factory:

    protected void Application_Start(object sender, EventArgs e)
    {
        RouteTable.Routes.LoadFromRuby();
        ControllerBuilder.Current.SetControllerFactory(new RubyControllerFactory());
    }

    That glue code is placed in a c# library called IronRubyMvcLibrary, which also contains support for .rhtml view pages. The objects you need to use from within the view page is accessible through Ruby global variables - $model, $response, $html and so on.

    As John and Phil points out, this is a prototype and a test to try out a few things with IronRuby and MVC, and I think it's cool. Much will change over time, like how they use instance variables on the controller to pass data to the view.

    This is a step towards something which may become quite popular in the Ruby community, and perhaps to Rails people who has to, or wants to, write web apps on the .NET platform in the future. For those that hasn't been looking at IronRuby yet and want to have some fun with this - note that you don't have any intellisense or anything lika that in Visual Studio yet.

  • Fetching User Details from OpenId via Attribute Exchange

    CropperCapture[4]Rob Conery did another excellent episode of his MVC Storefront series the other day where he ripped out his user membership code and replaced it with OpenId.

    Implementing the whole OpenId protocol yourself isn't necessary as there are some great libraries for you out there which makes it really, really simple to use and integrate with both WebFoms and A SP.NET MVC. Rob uses the DotNetOpenId library to authenticate the user but didn't show how to fetch user details like the user full name.

    Well, this is possible using Attribute Exchange which is a way of transferring information about the user between the OpenID provider and relying party. The DotNetOpenId library supports this too, and it just requires a small change to the DotNetOpenId code samples I've seen out there.

    First, most people redirect to the provider like this:

    openid.CreateRequest(id).RedirectToProvider();

    But instead, create the request manually and add extension requests to fetch user information (like the name for example) to it before redirecting:

    var openidRequest = openid.CreateRequest(id);
    var fetch = new FetchRequest();
    fetch.AddAttribute(new AttributeRequest("http://schema.openid.net/namePerson"));
    openidRequest.AddExtension(fetch);
    
    openidRequest.RedirectToProvider();

    Just keep on adding the attributes you're interested in, like email, website etc. Remeber to inform your user about you wanting to fetch the extra information before doing the authentication.

    After a successful OpenId authentication the provider redirects back to your site and you normally authenticate and redirect like this:

    switch (openid.Response.Status)
    {
        case AuthenticationStatus.Authenticated:
            FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false);
    //...snip...

    Now, before the redirect statement, you have the chance to fetch out the attributes you asked for from the OpenId response, like this for example:

    switch (openid.Response.Status)
    {
        case AuthenticationStatus.Authenticated:
            var fetch = openid.Response.GetExtension<FetchResponse>();
            if (fetch != null)
            {
                //assuming we got data back from the provider - add sanity check to this :)
                var name = fetch.GetAttribute("http://schema.openid.net/namePerson").Values[0];
                //...store name in session or something...
    }
    FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false); //...snip...

    Note that DotNetOpenId library offers a few "well known" attributes as enums which all uses the "axschema.org" schema, but they do not work with the myOpenId provider. That's why I'm using the "schema.openid.net" schema instead.

    Rakuto Furutani blogged about the attribute schema problems in a Ruby on Rails post:

    myOpenID supports only some attributes that can be exchange with OpenID Attribute Exchange, but you should care about Type URI, because myOpenID doesn't support Type URI described on "http://www.axschema.org/types/". You should specify Type URI with "http://schema.openid.net/" instead.

    It could be I'm using an older version of the DotNetOpenId library and it's been changed in newed releases. I have to check this out.

    Also, Andrew Arnott has written a longer post on how to use DotNetOpenId's Attribute Extensions extension which you should read if you want some more in-depth sample code (he's using ASP.NET WebForms).

  • ThreadPool.QueueUserWorkItem with Anonymous Types

    I thought this blog post by Matt Valerio was good, and it gave me a few ideas to use in a current test project. He wrote a helper method to be able to use anonymous types when calling a delegate or lambda in the ThreadPool:

    public delegate void WaitCallback<T>(T state);
    
    public static class ThreadPoolHelper
    {
        public static bool QueueUserWorkItem<T>(T state, WaitCallback<T> callback)
        {
            return ThreadPool.QueueUserWorkItem(s => callback((T)s), state);
        }
    }

    And his example code for using this method:

    ThreadPoolHelper.QueueUserWorkItem(
        new { Name = "Matt", Age = 26 },
        (data) =>
        {
            string name = data.Name;
            int age = data.Age;
            // Long-running computation
        });

     

    Cute, eh?

  • RROD - Our Xbox 360 Finally Gave Up

    UPDATE: And this morning it works again! Amazing. Yesterday I tried everything together with the support guy on the phone - unplugged power, hard drive, network, everything - but it was RROD still after 8-10 retries. And now, 20 hours later it works again? Weird. I'll let the box run for a few hours today and tomorrow. If nothing crashes I'll call Xbox support again and hear what they've got to say about it.

    ANOTHER UPDATE: And a few days later it really, really died so I sent it in for repairs. :) I just got it back today - it took about 2 weeks "door-to-door", which is not too bad considering it travelled to Germany for repairs and back again to Sweden. The motherboard replaced.

    Some time ago our Xbox 360 here at home started to glich - the screen froze up after a few minutes with a short squeeky noise from the speakers, one of the red lamps on the front lit and I thought the Xbox was going down. I contacted the support center to have it repaired (I would have to pay for it because we've had it for a couple of years and the warranty didn't cover this error), but they had problems with their incident system for a couple of days and therefore couldn't submit repair request... I asked them to call me back or send me an email when the system worked again, but they couldn't do that (boooh). That made me a bit angry, and I kind of dropped the Xbox from a few inches of height into the floor... and it worked pretty well after that!

    ...until now that is. This morning we had a real proper RROD (Red Ring of Death) - hardware failure. Argh!

    I called the support center again and was prepared to pay for the repairs, but I was told that Microsoft extended the warranty for RROD/hardware failures to 3 years - good! I just got the UPS lables to print out and stick onto the box and will arrange for UPS to pick it up on Monday. They said it might take up to 3 weeks to have the thing repaired and sent back to us, but there's not much I can do about that.

    I guess we'll have to power up the old Xbox console now and play Worms for a while :)

  • [Ruby] IronRuby Running Unmodified Rails

    I just saw this interesting twitter entry from John Lam:

    CropperCapture[1]

    I've also seen messages on the IronRuby mailing list like these:

    We're just in a big time crunch before RailsConf so we're pretty well implementing anything that we need to in order to get Rails to run.

    I'm not at the conference - anyone know if they managed to amaze anyone there?

    Update: John just published more information regarding IronRuby and Rails on his blog. Check it out - the IronRuby project is groundbreaking in many ways.

  • OpenID Support for ASP.NET MVC

    I've been monitoring the OpenID progress for a while now, and when I saw this post from Scott Hanselman about how easy it is to add OpenID support for ASP.NET MVC through the use of the DotNetOpenId package, I had to give it a try. It it sure wasn't hard at all.

    If you go to the DotNetOpenId website and download their stuff, you even get sample code for ASP.NET MVC that you can copy/paste from. If you know some OpenID and some ASP.NET MVC it won't take more than a few minutes to get the integration working.

    Cool thing is also that if you get yourself an ID on www.myopenid.com (which is just one of many OpenID providers), you get Information card/CardSpace support as well! Oh I wish more websites could support this, I don't know how many different accounts and passwords I've created the last years. Thank God for "forgot my password" links... :)

    New to OpenID? Learn more about OpenID and get your own.

  • T4 Support in VS2008

    Did you know there's T4 (Text Template Transformation Toolkit) support inside VS2008 now? Add a file with the .tt or .t4 extension to your project and you got a T4 template which VS2008 will automatically run when you save it. If you're into this and want to try it out, go to http://www.t4editor.net/ and download the T4-editor from Clarius. It gives you proper editing support from within Visual Studio. They got a version for vs2003 as well.

    This may not be as attractive as it used to be, now that we got designer tools for Linq to Sql, entity framework and so on to help us generate boilerplat code for database access, but I'm sure I can come up with some good use for this. The ASP3-like syntax is very easy to grasp, so basically there is no excuse for not using this if you know you're going to produce lots of code that looks or behaves the same. As long as you have some metadata to work from, be it a database, xml file or text file, I'm sure this can be of help to you. Ah yes, you can write the templates in either c# or VB.

    Some T4 resources for you maybe:

    Hilton Giesenow blogs about T4 and you can download a couple of VS T4 templates from him!

    Oleg Sych has a large number of very, very good blog posts about T4, Oleg is THE T4 blogger out there.

    The T4-editor website by Clarius has a couple of videos.

    The Text Template documentation for vs2008 on MSDN.

    On MSDN there's also a good intro video on the topic that you might want to look at if this is of interest to you.

  • What Happened to the Rails Website?

    I was going to look at some of the Ruby on Rails screencasts on www.rubyonrails.org site, but someone must have forgot to pay the right amount of money in time or something :)

    image

     

    I'm sure things will be working fine by the time you read this blog post :)

  • Try Ruby in the Browser

    There's a pretty awesome online "Ruby in your browser" tutorial that you could try. It has a built in Ruby console and everything is interactive. It's takes 15-30 minutes or so to go through, and it's good. Someone put a whole lot of effort and love into making this one for us Ruby newbies. Go check it out, but use a FireFox browser, because I couldn't make it work properly in IE in Vista.

    http://tryruby.hobix.com/

  • A .NET Guy Looking at Some Ruby (Part 2)

    This is me continuing scribbling down notes as I go along relearning lost Ruby skills and at the same time comparing the Ruby syntax and way of writing code to .NET. In my previous post I very briefly went through the basics of variables, loops, iterators, conditionals and basic sorting. This post will look at classes, methods, inheritance and how to reuse Ruby code with include (require) statements.

    Methods

    Method or function declaration in Ruby is simple, perhaps even simpler than how VB does it:

    def my_method(name)
        puts "Hello " + name.to_s
    end

    my_method "johan"
    my_method("johan")

    As you can see, you may call the method with or without parenthesis, to Ruby it doesn’t matter. I’ll have to read some more Ruby code to see if there are any exceptions or aesthetic rules to using parenthesis or not, but it seems that many Rubians use parenthesis when calling functions or methods on objects/classes, but leaving it when calling simple methods like puts and similar:

    Oh, and Ruby doesn’t support method overloading! There are ways around this with default method parameters, add-ons to the language and so on, but basically – no method overloading. I’ll show some sample code later on when I get to class initialization.

    Classes, Constructors and Properties

    Ruby is of course object oriented, and very much so (without going into the “where everything is an object” speech). So, of course you can declare objects with properties and methods on them. Declaring a class is familiar:

    class MyClass
    end

    You instantiate a class using a built in static “new” method on the class:

    a_class = MyClass.new

    Adding a (instance) method to the class is straight forward:

    class MyClass
      def hello(name)
        puts name
      end
    end

    Static methods, or class methods, are declared by prefixing the method with “self.”, like this:

      def self.reverse_upcase(name)
        name.reverse.upcase
      end 

    Adding a constructor or initializer to the class is done by declaring an initialize function:

      def initialize(name)
        @name = name
      end

    As constructor overloading is not possible, you’ll have to add a default value to the parameter, making it optional in a VB-style of way:

      def initialize(name = "Anonymous")
        @name = name
      end

    The @name variable is called an object variable and it is distinguished by the use of the ‘@’ sign. There is no need to declare the object variable in any other way, but to access the object variable (or property or attribute or…) you have to add property accessor code to the class:

      def name
        @name
      end

      def name=(name)
        @name = name
      end 

    Now, class properties is used so much that there is a so called attribute accessor keyword available for you in Ruby, making things a bit simple to type:

    attr_accessor :name

    There are also other attribute keywords like attr_reader and attr_writer available for your pleasure.

    Inheritance

    Last thing to say about the basics around classes in Ruby is how to handle inheritance. The syntax is similar to c#, but instead of a colon (:), use the less than (<) operator. A very simple example of where the class Employee inherits from Person could look like this:

    class Person
      attr_accessor :name

      def initialize(name)
        @name = name
        end
    end

    class Employee < Person
      attr_accessor :number

      def initialize(name, number)
        @name = name
        @number = number
      end

      def to_s
        @name + " (emp# " + @number + ")"
      end

    end

    e = Employee.new("Johan","123")

    puts e
    puts
    e.is_a?(Person)
    puts
    e.is_a?(Employee)

    Would print:

    Johan (emp# 123)
    true
    true

    Class Reuse

    If you want to “use” or “include” Ruby code you’ve already written? Save your code (class) into a MyClass.rb file (as an example) and add a “require” statement to the top of your code where you want to reuse the MyClass class:

    require "MyClass"

    and classes in the MyClass.rb file will become available for you.

    Wrapping Up

    I guess that’s enough for now. I think this will be enough to be able to understand some Ruby code if you come across it, unless it contains too many weird class methods like Array#flatten and such J. Then there are a bunch of modules available to Ruby for doing a number of things. I may get into that in a later blog post, I’ll see.

    All in all I think Ruby is cool. I’ve used dynamic languages and scripting languages before, but nothing as sleek as Ruby. Ruby is minimal code, fast to type and there’s a flow to the code which makes it quite easy to read.

    Next

    Next I’ll blog about downloading and building IronRuby and using it to call on .NET libraries, WPF and perhaps Silverlight (which seems to be all the buzz right now). I think I’ll look at exceptions and error handling after that and see if I can get some time to look at Rails again.

  • A .NET Guy Looking at Some Ruby

    I’m thinking it would be nice to relearn the basics of Ruby (which seems to gain more and more popularity) and compare it to some of the dynamic features .NET 3.5 has been blessed with. I’m also interested in where the Microsoft version of the language, IronRuby, is now and how I can use the .NET libraries from it. I installed and looked at Rails some (long) time ago now, but I never got the chance to use it and my minimal Ruby skills have now faded to nil again. So this is me taking it up again, hoping I can use it for something real, perhaps for unit testing or just test driving some .NET code with the help of IronRuby.

    What you’re reading is just me scratching down notes as I go along, it’s not an article or so, this is just for me to have something to get back to later on, so bear with me. I will probably write down things that are not right or make wrong assumptions, but I’m happy to get comments if you see something awfully wrong.

    Edit: I had to change the section on line continuation, because I was wrong about what I first wrote.

    Getting Started

    So how do I get started? First I need a Ruby implementation for the platform I’m running on, in my case Windows Vista. On RubyForge there is a Windows installer for Ruby which contains everything you need to get going. It’s available on http://rubyforge.org/projects/rubyinstaller/ and I’m going for it. Later on I’m also going to download and build IronRuby and .NET applications using the Ruby language, but you will still need Ruby installed to build IronRuby. The IronRuby website www.ironruby.net has some notes on all this, but I’ll blog on that later I think.

    The installer will give you the Ruby language, runtime and an editor called SciTE. It also includes a samples directory which may come in handy. With Ruby you got several options to create and test small console apps. After the installation completes, just open up a command prompt and type “irb” and you’ll get an interactive Ruby command prompt, which is very handy for both testing and learning. Another option is to go to the Start menu and use “fxri”, which is a graphical interface to the Ruby documentation and also includes an interactive Ruby console. I’ve used both today. Fxri is great when you’re looking at someone else’s Ruby code and you see a command or class you don’t recognize.

    The Ruby installer also comes with an electronic version of the book “Programming Ruby - The Pragmatic Programmer's Guide” by Dave Thomas – which I can tell is also a great source for knowledge. I’ve not read it yet, but I’ve used it to look up certain things.

    Tutorials

    Next I need some getting started articles or such, and there are tons of it on the Internet. You could use the book above, but I’m looking for something which will get me into the dirt quickly.

    I found a “Learning Ruby” website by Daniel Carrera which looks promising, and I’m using it to learn the very basics. You’ll find it at http://www.math.umd.edu/~dcarrera/ruby/0.3/index.html  and it’s using the “irb” console in its first steps, which works perfect with IronRuby. Just open up a command prompt and type:

    irb --simple-prompt

    You'll be greeted with a prompt like this…

    >>

    …and off you go. Just type your code and press enter. There are other great intros to Ruby on the Internet, and this one by Steve Litt looks good, http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm

    Variables and Strings

    Most tutorials start with numbers, strings and variables. There’s not much to say about Ruby variables – you don’t have to declare them, just initialize the variable with a value and start using it:

    i = 1

    Exactly what I’m expecting from a dynamic language, and strings are very easy to work with:

    name = "Johan"
    name = name + " Danforth"
    puts name

    The string class in Ruby has a number of powerful methods you can use to work with, same as with the string class in .NET, but the Ruby string class has more than 100 methods on it (from counting the methods in fxri). The .NET string class has around 70 methods, but 45 of these are extension methods that are new to .NET 3.5, and I think many of them were inspired by dynamic languages just like Ruby. I have to say though that some of the methods in Ruby do the same things sort of and some methods are quite funny. Like squeeze, chomp, chop and such :) Methods for parsing, encoding, converting and such are also included in the Ruby string class, functionality that may be baked into other libraries in the .NET framework.

    Running a Ruby Program File

    Running a Ruby program from a file is dead easy. From the console type “ruby myprogram.rb” and press enter. The installer also associates the .rb file extension with the Ruby executable, so it’s possible to just type “myprogram.rb” or click the file from Windows Explorer.

    A good editor for your .rb programs seems to be SciTE which also comes with the Ruby installer. Just open up the editor, type the program and press F5 to run it (make sure you have saved it with the .rb file type). The results will be shown in the right pane of the SciTE editor. Nifty.

    Type Conversion

    What strikes me as odd is that Ruby is a dynamic language, but automatic type conversion is sometimes not as good as I would think, and something as simple as this will give you an error:

    sum = 1 + 2
    puts "The sum is " + sum

    test.rb:2:in `+': can't convert Fixnum into String (TypeError)

    So, in a print statement like the above, Ruby won’t convert the number variable into a string like c# or VB does:

    Dim sum = 1 + 2
    Console.WriteLine("The sum is " & sum)

    You’ll have to convert the sum variable to a string like this:

    puts "The sum is " + sum.to_s

    Aesthetic Code

    Ruby seems to be much about the aesthetics of the code you write. Most Ruby tutorials seem to bring up naming of variables, classes and methods in an early state. What is funny is that the casing of a variable matters to the interpreter, because if you uppercase a variable, it’s treated as a constant. You can change the value of a constant, but the runtime will give you a warning:

    PI = 3.14
    puts PI
    PI = 3.14159265
    puts PI

    test.rb:3: warning: already initialized constant PI
    3.14
    3.14159265

    But what about code statements that are too long? In c# you can make a line break after almost any statement, and it's the same thing in Ruby. I was wrong about this at first, because in Ruby (as in VB) you can put a backslash (underscore in VB) at the end of the line to do break up a line of code: 

     puts "this is a " + "very " +
      "long statement"

    Be careful not to put a space after the backslash, or you’ll get a strange looking error:

    test2.rb:1: syntax error, unexpected $undefined
    puts "this is a " + "very " + \
                                   ^

    I’m not fond of the line continuation underscore thing in VB, and I’m thinking the same of the backslash in Ruby, so you won't see me use it.

    Loops

    Ruby seems to be good at this, and the most common syntax for-loops is easy to read and pretty nice:

    i = 1
    4.times do 
      puts "pass " + i.to_s 
      i += 1
    end

    Well, this is just like any other for-loop out there, but the syntax is nicer. There are other ways to type the same thing in Ruby but I’ll get back to that later. I know people have tried to come up with a similar syntax using .NET 3.5 method extension and lambda expressions, but I think it’s hard to make it as compact as in Ruby. My 10 minute feeble attempt at making a c# version of the Ruby times-method would probably be an extension method like this:

            public static void times(this int number, Action codeblock) 
           
                while (number-- > 0) 
                    codeblock(); 
            }

    And I could call it with a one-liner lambda expression like this:

                var i = 1; 
                4.times(() => Console.WriteLine("hi! " + i++));

    Or with a delegate (with some richer code inside) like this:

                var i = 1; 
                4.times(delegate(){ 
                    Console.WriteLine("pass " + i); 
                    i += 1; 
                });

    Not as nice as the Ruby variant, but close :) The System.Action Delegate class in .NET 3.5 is pretty awesome btw, and you got a generic version of it as well if you need to pass arguments on to the delegate.

    Of course Ruby has the traditional VB-like “for” statement as well, with a couple of variations. A 1-5 for-loop looks like this:

    for x in 1..5 
      puts x
    end

    But a 1-4 for-loop looks like this, see the difference?

    for x in 1...5 
      puts x
    end

    2 periods mean as long as the variable is less than or equal to the “to” value (inclusive), 3 periods mean as long as the variable is less than the “to” value (exclusive). I’m sure this is a common coding mistake, as it’s easy to miss. And as you can see, no braces/brackets like in c#, so I guess VB programmers feel a bit more comfortable with this syntax, but the for-loop statement in Ruby is, I believe, syntax sugar for this statement, which involves braces/brackets but equally valid:

    (1...5).each {|i| puts i }

    Conditional Statements

    Conditional statements, in Ruby are a bit of a mix between VB and c#. Like in c#, “=” assigns values and “==” compares. I like that. For example:

    a = 1
    if a == 1 then 
      puts "true" 
      else 
        puts "false" 
      end

    Arrays and Lists

    Arrays in Ruby have much in common with the same in c# and VB.NET, especially with the new features in .NET 3.5. Ruby is zero based, so you address a specific item in the array with [] , and it’s possible to initialize arrays in a similar way in all languages. In Ruby:

      numbers = [ "zero", "one", "two" ]
      addresses = [ [ 10, "Kings Rd" ], [ 25, "Queens Rd" ] ]

    Initializing a simple string array in c# 3.5 is quite similar:

     var numbers = new[] { "zero", "one", "two" };

    The “addresses” array can be solved in many different ways in .NET, but I think the c# equivalent would be: 

    var addresses = new[]

               new object[] {10, "Kings Rd"}, 
               new object[] {25, "Queens Rd"}
    };

    As you can see, c# requires a bit more typing. Personally I prefer to create an array of anonymous types in c#, as it is much easier to code against:

    var addresses = new[] { 
               new  { Number=10, Street="Kings Rd" }, 
               new  { Number=25, Street="Queens Rd" }
    };

    The VB.NET equivalent of a simple string array and array of anonymous types is something like this I think (I’m not a VB-guy):

            Dim numbers() = {"zero", "one", "two"
            Dim addresses() = {New With {.Number = 10, .Street = "Kings Rd"}, _ 
                               New With {.Number = 25, .Street = "Queens Rd"}}

    Oh, the number of things you can do with arrays in Ruby, and in a very intuitive way too. Reverse, sort, add, remove and other methods we recognize from -.NET List and List<> types, but like the Ruby string class there’s a number of unusual but powerful methods on Ruby arrays like flatten (sample taken from the docs):

      s = [ 1, 2, 3 ]            #=> [1, 2, 3] 
      t = [ 4, 5, 6, [7, 8] ]  #=> [4, 5, 6, [7, 8]] 
      a = [ s, t, 9, 10 ]       #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] 
      a.flatten                   #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10

    If I coded Ruby for 10 years, I’m not sure I would ever use that method :) It flattens an array of variable length arrays into a one-dimensional array recursively. Cool to have this method built into the Ruby language from scratch.

    But other than a few methods like this, it feels like you can do about the same things with the .NET lists and arrays. You may have to turn your array into a list or vice versa, so again we’re talking a little bit of more code than Ruby, but not too much.

    Iterators

    Related to arrays are of course iterators. A common way to iterate through a Ruby array is to use do – end like some of the samples above. But there is a cool way to use a similar syntax, each – do – end  and pass the current item of the array into a block of code. This seems to be a common style of coding in Ruby:

    friends = ["Melissa", "Jeff", "Ashley", "Rob"]
    friends.each do |friend| 
         puts "I have a friend called " + friend 
       end 
      

       5.times do |i| 
         puts "pass " + i.to_s 
       end

    It’s quite possible to use a similar style of coding in c#, by using a foreach loops, lambda expressions or delegates:

    var friends = new[] {"Melissa", "Jeff", "Ashley", "Rob"};

    foreach(var friend in friends) 
               Console.WriteLine("I have a friend called " + friend);

    5.times(ii => Console.WriteLine("pass " + ii));

     

    public static void times(this int number, Action<int> block)

        int i = 0; 
        while (i < number) 
       
            block(i); 
            i++; 
        }
    }

    As you can see, I’m using a method extension to create my own times() method, using a lambda expression to pass a block of code to the times() method with the help of the generic Action delegate. It’s a variation of the times() method I used earlier.

    Sometimes when the loop just contains one line of code some Ruby coders seem to replace the do – end with curly braces like this:

    6.times { |i| puts "pass " + i.to_s }

    As I mentioned earlier when I wrote about loops, this is just another way to type it. If the compiler turns the do-end into braces or vice versa I don’t know – it just works.

    The “each” keyword in Ruby seems to be pretty powerful and lets you iterate through different sorts of lists in many ways. It is also used to handle hash-tables. A hash-table in Ruby is declared and initialized like this:

    fruits = { 
     "123" => "Apple", 
     "456"  => "Banana", 
     "789"    => "Orange"
    }

    As you can see, we’re using squiggly/curly braces/brackets instead of squares. Not sure why it is like this and I would have preferred to use squares here to as for arrays, but this apparently is the way… To access a particular value, just address it with the key of course:

    puts fruits["123"]

    And iterating through the table with the each – do – end syntax is starting to feel natural now:

    fruits.each do |key, value| 
     puts key + " => " + value
    end

    Of course you don’t need to use the names “key” and “value”.

    It’s quite similar to the way most other languages handle hash-tables. Hash-table declaration and initialization in c# is quite similar thanks to the new language features in c# 3.5:

    var h = new Hashtable
               {"123", "Apple"}, 
               {"456","Banana"}, 
               {"789","Orange"}};

    Sorting Your Own Way

    In c# lists and arrays there are ways to do your own custom sorting, but in Ruby it’s done in a different way. You write your own sorting in-line in a sort – do – end loop like this for example:

    friends = [ 
        [ "Johan", "Danforth" ], 
        [ "Eric", "Quist"],
        [ "Björn", "Poppe" ]
    ]

    friends = friends.sort do |a,b| 
      a[1] <=> b[1]   # compare last names
    end

    Nice thing here is that is seems to be quite simple to do custom sorting of arrays with complex objects in them. The <=> operator is something which is built into Ruby because sorting and comparing is so often done. Basically a <=> b,

    - returns -1 if a is less than b

    - returns 0 if a is equal to b

    - returns 1 if a is greater than b

    The operator is able to work with strings and numbers.

    That’s Enough for Now

    I think this is enough for now. I’ll post a follow up about methods, classes, inheritance and such later on.

  • March 2008 TFS/Team Suite Download List

    Just what I was looking for - a list of all the URLs to the VPC-parts, easy to add to a download manager. Steve got the links from Martin Danner and I'm passing the links on :)

    Martin Danner has passed along a list of the URLs to use to download the TFS/VSTS 2008 Trial VPC using Free Download Manager.  Just copy the list and paste (using Ctrl+Shift+V) into Free Download Manager then wait...

    This VPC includes Office 2007 SP1, all Windows Updates and the December 2007 power tools.  It also contains 38 hands-on labs for your learning pleasure.  The VPC is set to expire on Dec. 31, 2008.

     

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0001.exe

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0002.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0003.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0004.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0005.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0006.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0007.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0008.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/en_visual_studio_team_system_2008_team_suite_and_tfs_rtm_vpc_march2008.part0009.rar

    http://download.microsoft.com/download/d/7/3/d73b91d4-6daa-4da6-8635-3f10a1b918db/VSTS%202008%20Hands-on%20Labs%20March%202008%20Release.msi

  • My Xbox 360 is so D**n Noisy

    :rant on

    I've had the Xbox 360 for almost 2 years now or something like that, and it's a wonderful console to play games on. Last year I configured it as a media extender and hooked it to my Vista Ultimate box sitting in my office with a Tv-tuner so that I can watch live TV and recorded TV shows on the Xbox.

    Everything would be all and well if it wasn't for the amazingly loud noise the 360 gives off. I know about the noisy fans and the DVD drive, and people say they DVD-drive is the worst, but I'm not so sure. The noise from the spinning DVD drive doesn't bother me that much, becasue when me and my son play games, we crank up the volume on the surround system anyway :)

    The sound from the Xbox when watching a DVD movie isn't too bad either, because the DVD revs down and the fans too it seems like.

    No, what bothers me is the annoyingly loud noise from the machine when using it as a media extender. As soon as I press that green button on the remote and the media center program starts, the fans in the Xbox revs up to a maximum and it sure must be louder than 60 decibel. It almost sounds like a hair dryer for crying out loud. Watching TV late at night with the volume turned down is impossible, you won't hear what they say on the show.

    I've been peeking at various Xbox modding articles about how to replace the fans, the DVD drive, adding sound dampeners and what not, but I'm not so sure it helps. Some people say it doesn't help a bit. The only thing that seems to work is to rip out the fans completely and replace with water cooling or bigger external fans. Also, some rumours say Microsoft will detect a modded fan and ban you from Xbox Live, but I think that's an urban legend.

    There's also talk about the lates versions of the Xbox 360 console being more quiet than the earlier versions, but how quiet is that?

    No, the wife acceptance factor and my own patience will probably have me go back to using a standard cable tv receiver with a recordable disc in it. I was happy to get rid of all the extra equipment from the living room and only have a TV, the Xbox and the surround system but as I said - the noise from the console is just too much.

    Any good ideas for what I can do before I dust off and reconnect my old equipment?

    :rant off

  • Track Your Halo 3 Progress on Internet

    This has not so much to do with coding as such, but there is a great deal of cool architecture involved in this. I'm sure all of you knows about the Xbox game Halo and especially Halo 3 for Xbox 360 from the guys over att Bungie. The single player campaign game itself is wonderful, but once you've played it through maybe you'd like to test your skills against 100.000+ other Halo players on Xbox Live. But be warned, the guys (mostly kids way younger that yourself) are quite skilled, and you will get your butt kicked around.

    Everything is tracked

    What's so cool about Halo and Xbox Live is that all your progress, matches, achievments, stats, screenshots, film clips and even the latest look of you player model (armour, colors etc) are sent to the Bungie Halo web site so you can track everything from there. You can go back to every game you played and look at details about score, how many opponents you beat down, with what weapon, what medals you earned and so on. You even get heatmaps of where you are most active and successful on each map!Pixie King

    Playing with my son

    I'm spending a lot of time at home together with my 12 year old son, who unfortunately got a serious disease in his bone marrow and has to stay at home or at the hospital all the time until he recovers (which will take many months yet), and we're playing a few games on Xbox Live every day - sometimes many games ;) When we've finished playing, we pull up the laptop to look at our player stats on Bungie.net. Needless to say, my son is way better than I am. I'm more used to playing with a keyboard and mouse than with the Xbox controls ;)

    These are the Halo 3 stats for my son, and these are my stats. Don't laugh at my stats and rank please...

    Interesting game design

    I was once into multiplayer game design and development on an open source project for Unreal Fortress *dreamy look* and I sometimes thought about connecting the games to a website in a way similar to what Bungie has done. Multiplayer stats on websites has been around for a long time for games like Quake, Team Fortress, Unreal (and so on), but I've never seen anything like the service on Bungie.net. The game architecture of Halo 3 itself is something too - I'm very impressed with how you can go and look at a complete game afterwards and see EVERYTHING that happened in the game in detail. Not just from your view, but from everyones view. Something I know isn't, or wasn't possible with the Unreal/Unreal2 engine and I don't thing the Quake engine could do that too.

    The only thing I miss is being able to change player armour, emblem, colors and such on Bungie.net instead of from Xbox only.

    Ranking system from Microsoft Research

    Halo 3 uses a ranking system so that every player can earn experience points and be ranked (if you chose to play ranked games) compared to other Xbox Live players. The ranking system is based on Trueskill from the Microsoft Research division. It's somewhat complex but you don't have to care and it seems to work pretty well. If you want to get XP, make sure you end up on the winning team of a team game or in the upper half of a "Lone Wolf" game without teams. The matchmaking system tries to assamble games which are as even as possible, based on the ranks of the players available on-line. Sometimes it takes a minute or two to get a game started, but most of the time it's very quick and many of the team-based games are very, very even.

  • New ASP.NET 3.5 Extensions Videos

    Videos and screencasts are great ways to learn new programming techniques, at least it works well for me. If you're interested in ASP.NET MVC, maybe you've already downloaded the preview 2 which was released a couple of days ago. In that case you also might want to head over to the ASP.NET webby and have a look at the 4 new videos of ASP.NET MVC. It shows off viewing and editing data as well as the new Html helpers and testing.

  • [Service Factory] New Software Factories

    Seems that the PAG team (Patterns & Practices) have been really busy - 2 new Software Factories have been released! My friend Eric just blogged about the release of Web Service Software Factory: Modelling Edition and a few days ago I read about the Web Client Software Factory (which I haven't looked at yet).

    We've been running a modified version of an earlier Service Factory release to much joy, and I've looked at a pre-release of the modeling edition, which was very cool. Cudos to Dmitri Ossipov and Don Smith and their teams!

    Also visit the community site of Service Factory at Codeplex.

  • [Tools] Cropper the C# Screen Capture Program

    It doesn't really matter what language the tool is written in, but this program happens to be one of the smoothest screen capture utilities around, and it happens to be written in C#. I've been using it for months, and I have no plans to replace if for another cropper/clipper/capture tool.

    It's available on CodePlex and there's also a Cropper Plugins project there with a bunch of more or less useful plugins :)

    CropperUI

    (picture from the Cropper CodePlex site)

  • [Tools] Microsoft SharedView Beta2

    I just tried it out with Eric, and it worked like a charm. 

    Connect with up to 15 people in different locations and get your point across by showing them what's on your screen. Share, review, and update documents with multiple people in real time.A Windows Live ID (Passport, Hotmail, or MSN) is required to start sessions, but not to join sessions. New in Beta2: now even easier to use, with group chat and performance improvements!

    Download details: Microsoft SharedView Beta2

    I think I'll use it as a support tool when my dad has computer probs. Problem is, it's usually his broadband connection that is the source of the problem... :)

  • IIS Web Deployment

    Note to self: Try out the Web Deployment tool. I wonder if I can hook it on to MSBuild or CruiseControl.NET in a good way...

  • Support for Core Form Controls in Silverlight 2.0

    Happy to see this announcement on ScottGu's webby:

    The next Silverlight preview release will add support for core form controls (textbox, checkbox, radiobutton, etc), built-in layout management controls (StackPanel, Grid, etc), common functionality controls (TabControl, Slider, ScrollViewer, ProgressBar, etc) and data manipulation controls (DataGrid, etc).

    .NET Web Product Roadmap (ASP.NET, Silverlight, IIS7) - ScottGu's Blog

    A rich set of controls for Silverlight is sure needed if Silverlight is to be used for more than creating flashy video players... :)

  • ScottGu on the ASP.NET MVC Framework Road-Map

    ScottGu blogged about the roadmap for the ASP.NET MVC Framework, and it sure looks like this framework is shaping up to become quite a diamond with all the new features. I especially like this:

    Starting with this upcoming preview release we will enable applications to instead directly reference the System.Web.Mvc.dll assembly from the application's \bin directory.  This means that no setup programs need to be run on a sever to use the ASP.NET MVC Framework - you can instead just copy your application onto a remote ASP.NET server and have it run (no registration or extra configuration steps required).

    We are also doing work to enable the ASP.NET MVC framework to run in "partial/medium trust" hosting scenarios.  This will enable you to use it with low-cost shared hosting accounts - without requiring the hosting provider to-do anything to enable it (just FTP your application up and and it will be good to run - they don't need to install anything).

    They've also changed the default behaviour of a few things, like not having to explicitly mark controller action methods with an attribute. I think too that was a request from the community which the MVC-team has taken to ther hearts and implemented.

    This framework will sure be widely used...

  • www.NServiceBus.com is Online

    Udi Dahan just blogged about the new site for nServiceBus:

    www.NServiceBus.com is online.

    It’s not “done” yet, but I’m pretty sure it’s past time that nServiceBus had its own site separate from this blog. I’m still working out the DNS and other domain forwarding and hosting stuff, but we’re live.

    There is some information on the “overview” page about one-way messaging, store-and-forard, and why those patterns were chosen for nServiceBus.

    Check it out.

  • [Vista] SP1 Available for MSDN Subscribers

    Lots of people have now blogged about the availability of Vista SP1 on MSDN Subscription, but what is new and when will it be available for the public? I Googled around a bit...

    Mike Nash on the Windows Product Management group blogs on the Windows Vista Blog:

    With Service Pack 1, we have made great progress in performance, reliability and compatibility.

    ...

    ...with SP1, copying or moving files around your PC, your home network or your corporate network should now be much faster.

    ...

    In addition, on many kinds of hardware, resuming a Windows Vista-based PC from sleep is faster on Service Pack 1.

    ...

    we will begin making SP1 available through Windows Update in mid-March

    Mike also writes about better support for hardware, which is about time ;) There's a pretty good page on Technet which describes the Notable Changes in Windows Vista Service Pack 1.

  • Differentiated UX

    I cannot help to smile when reading Udi Dahans view on "Differentiated UX":

    As if there wasn’t enough stuff for developers to deal with.

    After the grand release of WPF, and the industry’s collective shrug and back to business, Microsoft stirs the pot again.

    Yes, a compelling user interface may sell and 3D-views may help get a better understanding or a new insight of complex data, but showing the right data, at the right time is more important. Having said that, some of the new features of WPF and Silverligth migth actually help you with that, but application designers/architects should know what to prioritize.

    I've always been interested in trying out new stuff, but .NET developers are getting swamped with too many new things from Microsoft now. Being a generalist gets harder and harder - I've no idea when I will find time to sit down and have a look at all new stuff. I used to find time to install and test new frameworks and tools, but it's mostly down to reading blogs and looking at webcasts for me nowadays.