Blog

  • Strongly typed databinding in WinForms – aka. no more magic strings!

    I’ve been working on a WinForms project for a while and I’m getting progressively more tired of the magic strings used when doing databinding. (See MSDN documentation here) The problem is that the datamember of the datasource being bound to the control is a plain old System.String:

    e.g:

    lblName.DataBindings.Add("Text", myViewEntity, "UserName");

    I can live with the propertyName (“Text”) being a System.String, as this property will probably not change the name in the next many releases of .net, but the “DataMember” is nagging me.

    The problem is:
    * Misspelling is only discovered at run time
    * Renaming the property will cause the databinding to break – at runtime.

    The last point is mostly handled by using productivity tools such as ReSharper, but I have often had the experience that the ReSharper refactoring didn’t rename correctly – probably because I was blindly pressing yes or no when asked to refactor.

    A few weeks ago, I started to look around for a better solution and came up with this little snippet:

    public static string GetPropertyName(Expression expression)
    {
        var body = (MemberExpression)expression.Body;
        return body.Member.Name;
    }
    
    
    This little snippet could be used like this:
    
    
    lblName.DataBindings.Add("Text", myViewEntity, GetPropertyName(() => myViewEntity.UserName));

     

    - And the magic string has disappeared :-)
    After a little more work, I ended up making an extension method for the BindingCollection class:
    public static Binding Add(this ControlBindingsCollection collection, string propertyname, object dataSolurce, Expression expression, bool formattingEnabled = true, DataSourceUpdateMode updateMode = DataSourceUpdateMode.OnPropertyChanged, object nullValue = null, string formatString = "", IFormatProvider formatProvider = null)        
    {
        return collection.Add(propertyname, dataSolurce, GetPropertyName(expression), formattingEnabled, updateMode, nullValue, formatString, formatProvider); 
    }

    Using this method, I could write the following code when binding:

    lblName.DataBindings.Add("Text", myViewEntity, () => myViewEntity.UserName);
    
    
    Now we're talking!
    
    

     

    Finally I wrote a whole extension library containing the most common bindings - for binding to a Text, Enabled, Checked etc. causing my code to look like this:
    lblName.BindToText(myViewEntity, () => myViewEntity.UserName);
    
    
    Check out the library in the attached .cs file.
  • Testing private members with PrivateObject and PrivateType

    I’m currently working on a legacy project that has been ported from Visual Studio 2010 to Visual Studio 2012. The project uses the Visual Studio 2010 feature that allowed to access private members through some automatically generated code.

    In Visual Studio 2012, this causes a warning when compiling:

    This task to create private accessor is deprecated and will be removed in a future version of visual studio

    I’ve been looking around to find a solution. The right solution would obviously be to refactor the code in a way that testing private methods is not necessary, but that is not (currently) an option in the solution I’m working on. In stead, I’m relying on two new classes in the .net framework : PrivateObject and PrivateType.
    The PrivateObject can be used to access private methods, properties, fields where the PrivateType class can be used to access static members.

    I have made a simple test project to show the features. The adder.cs class contains a public method as well as some private fields and private static methods. Don’t mind that the code doesn’t make sense as it is only for demo purposes.

    using System.Collections.Generic;
    using System.Linq;
    
    namespace PODemo
    {
        public class Adder
        {
            private int a;
            private int b;
            private int result;
    
            public void Add(int one, int two)
            {
                a = one;
                b = two;
                result = AddNumbers(one, two);
            }
    
            private static int AddNumbers(int one, int two)
            {
                return one + two;
            }
    
            private static int AddNumbers(IEnumerable numbers)
            {
                return numbers.Sum(p => p.Value);
            }
        }
    
        public class Number
        {
            public int Value { get; set; }
        }
    }

    The Add method doesn’t return the result. Suppose I would like to test the functionality by verifying the result field:

            [TestMethod]
            public void PrivateFieldsTest()
            {
                var test = new Adder();
                var po = new PrivateObject(test);
                test.Add(2, 4);
    
                Assert.AreEqual(2, po.GetField("a"));
                Assert.AreEqual(4, po.GetField("b"));
                Assert.AreEqual(6, po.GetField("result"));
            }

    I create a new Adder object and then creates a PrivateObject that wraps the test object. The I can use the GetField methods to access private fields. Also, GetProperty and Invoke methods are available.

    Suppose I would like to test the static methods, I can use the PrivateType object instead.:

            [TestMethod]
            public void PrivateStaticMemberTest()
            {
                var pt = new PrivateType(typeof (Adder));
                var result = (int) pt.InvokeStatic("AddNumbers", BindingFlags.NonPublic | BindingFlags.Static, 2, 4);
    
                Assert.AreEqual(6, result);
            }

    A little aberdabai is that invoking members that take an interface as argument, must be casted to the interfacetype – otherwise the PrivateType cannot identify the correct method to execute.

            [TestMethod]
            public void PrivateStaticMemberWithInterfaceParameterTestSuccess()
            {
                var pt = new PrivateType(typeof(Adder));
    
                IEnumerable param = new[] {new Number {Value = 2}, new Number {Value = 4}};
                var result = (int)pt.InvokeStatic("AddNumbers", BindingFlags.NonPublic | BindingFlags.Static, param);
                
                Assert.AreEqual(6, result);
            }

    Obviously, these classes just wraps some reflection magic underneath the covers, but they still come ind handy when testing legacy code. I would never advise to use these classes when doing green-field development. I strongly believe that it is a code-smell if it’s necessary to use these objects for testing new code.

    MSDN; PrivateType
    MSDN: PrivateObject

  • Why are my clients always wasting their money on me?

    Update 2011/08/31: I’ve had a lot of response from other freelancers with similar experiences. They suggested a few extra issues which have been added below. Thanks.
    —————————–

    As a freelancer / contractor, I startup on new projects or new clients every 6 months or so. I usually get the job through an agent after an interview with the client. During the interview, i try to figure out what the project is about and how the project team is organized, but often the interview is half an hour or less which can make it hard to get all the details nailed down.
    Before i actually start, i try to prepare as much as possible, by googling the company, looking at past projects if any is avaliable etc.
    But recently i concluded that the preparation is mostly waste… Because my clients doesn’t make the same effort to prepare for my arrival. I usually meet up to find that a development environment is missing, the team don’t know where the latest version of requirements is located etc. I usually spend the first week either waiting for people to get me ready or to find the people who knows the procedures of the company. If only the clients preparred, i could be productive much faster => make myself worth the money they pay much faster.

    I’ve made a list of things that should be ready for the contractor (or any other new people on a project – either new employees or existing employess who is transferred to a project.

    • Pc. The hardware must be ready. If it takes time to be preparred by internal it, order the machine to be ready a week before the contractor arrives and test it before. That gives time to fix any issues.
    • Table and chair. Dont start the first day with rearranging people to make space or clear a corner of one of the other consultant desks. A consultant is no different from other employees. Productivity increases in a clean and tidy environment. And make sure the desk is close to the rest of the development team.
    • Make sure the user account is up and running. Both normal user accounts with e-mail access etc, and special dev accounts if needed.
    • Make sure remote access is configured and any security tokens are ready
    • Have a physical access card ready or make an appointment with a photographer if a photo is required on the access card.
    • Make a list of people related to the project. Ensure name, email and phone number. If pictures are available, include it. There is a lot of new faces to remember on any new project. Even better: send the list by e-mail with vcf cards attached. That makes it easy to transfer the contacts to my personal phone, which i will usually use.
    • Make sure that every team member has shared his / her calendar.
    • Have a manual for time registration ready.
    • E-mail with links to
      • Requirements
      • Architecture and design documentation
      • Development standards
      • Decision logs
    • Make sure a few workpackages are ready and assigned and make sure an existing team member is assigned to do pair development the first few days. The pair development makes it much faster to grasp the idea of the design and the toughts behind the code. Its also a good way to make some social engineering with the existing team – which is a huge benefit for both client and contractor.

    All items above must be fixed sooner or later. A late fix is an expensive fix. If the fix is made early, it can be planned and carried out by a way person way cheaper than a consultant , e.g. a project secretary.

    So please prepare and let me do what you pay me to do.

  • Developer pc

    Its been two years since my last blog post. I havent died, but even though im still breathing, its been a coupple of busy years. Another kid, a new house etc have taken all my time. But things are looking brighter and im starting to get more tech focused again.

    Thia blog post is about my thoughts on getting some new hw. I think i already decided, but i need some arguments to make sure that the decission i mad with my heart also is the right one for my needs.

    For the last coupple of years, i’ve been running on mo or less the same hardware. I got a Dell studio XPS 13 a fw year ago. It was equipped with a core 2 dual processor – state of the art at the moment, a decent graphics adapter 4 gigs of mem and 500 gigs of harddrive. It has been upgraded to 8 gb ram to support multiple vm machines and in two steps upggraded, first to a 256 ocz ssd drive and recently to a 600 gb Intel Ssd drive. I even upgraded the battery making the machine run for 5 hrs on a charge. But now it is dying… Its freshly reinstalled and still freezes quite often. It even complains during bios load once in a while. So now its time to look for something new.

    My needs is a state of the art machine for running windows and multiple dev machines on vm ware. I do lots of development in visual studio.

    Im quite into apple gear. I just got my ipad 2 and im loving it. I, of course, have an iPhone and all my digital assets (pics and music) is storred on a mac mini. So my first thought is to get a mac book pro and run windows on it, either natively or using parallels. But wow it is expensive. And it has a few caveats. First, i like to get a 13 inch machine as i do a lot of travelling. But i cant get the 13 inch with a i7 quad core processor, which i would very much like since im doing all my develpment using vm ware machines. The 15″ machine would do it, but it is still to bulky and its very expensive.

    My criterias are as follows
    Intel core i7 quad processor
    8 gb of ram and i will not complain if its possible to upgrade to more.
    Hd isn’t important as i will move the new 600 gb ssd disk into the new machine anyway.
    I prefer a 13 inch because i do lots of commuting (currently 3 hrs pr. day), but a slim 15 inch will do it as well.
    I need a a high resolution on the screen as well. My isight is brilliant and i dont mind if my fonts are small as long as there is lots of pixels to use.
    I dont care about dvd drive. I dont use it at all.

    Ive been looking around using google, and its really hard to find any matches. I’ve been Looking at Lenovo machines, but it looks like a german tank. The Sony Vaio might be a match but have no idea of the build quality. Samsung series 9 is good looking but i cant change the hdd to my ssd.

    So what should i do. Pay dkk 20.000 + for an Apple 15 inch of half the price for a new Dell XPS 15 which meets all my requirements except it seems a little bulky? I really dont mind paying the price as this is a tool that is going to be used every day for the next years. So 10k or 20k… Its down to dkk 27 pr day for the most expensive machine… And thats like the first two minutes of payed work every day…shouldn’t i just accepting that i work for two minutes to have the tool i really want?

    If i were a carpenter, i wouldn’t buy the cheapest nails that bend every time the hammer fall.

    Note. This blog post is written on my ipad… I excuse all the typos.

  • TechEd day 4

    TechEd day 4

    Thomas Garp in the HUUGGGEEEE eating all at TechEd

    Day 4 on TechEd is going to be spend on the following program:

    • Test driven development
    • Custom features that enabled users to develop rate and share content with moss 2007. –
    • No budget for tools – hot tools on a limited budget
      MS silverlight on sharepoint architectural and development patterns
    • Design patterns in the real world
    • .net on linux and mac

    I dont know if I will be able to take part in all the sessions… I hope to be able to escape for some serious shopping for a coupple of hours as well. And tonight is the Jam Session party, and I should be ready for that as well…

  • TechEd Day 3 followup

    Day 3 went off with the Zen of Architechture by Juval Lowy… se other post.

    After that breathtaking session, I went for a certification session. The concept is basically that a guy spends 1 hr telling you how to pass a certification test. What is necessary to know, what isn’t. I attended a session covering the MS SharePoint 2007 configuration exam. Im pretty confident that I could pass it after reading just a little.

    After lunch, I attended the Applied Entity Framework. But I’m afraid that jetlag and 4 days with only very little sleep kicked in in that session, so I didn’t get the benefits I was hoping for. It provided a bit of knowledge in an area that i havent covered in detail before. I think I will try it out, but oher people tell me that I should go for the NHibernate – (When will somebody call it nHyperNate??? It seems to be the new “HYPE” that everything is Hyper 🙂 )

    I realized that I wasn’t able to listnen to more people that day, so I went into solo nerding mode and tried some of the stuff out that i have heard over the last few days. Pretty nice just being me and my friend Visual Studio.

    The day ended in Long Beach with swimming (Not me… I was a woosy) and more mexican food.

  • The Zen of Architecture

    The Zen of Architecture


    Listened to The Zen of Architecture by Juwal Lowy… He has some very interesting points. Everything can be found in the iDesign.net website. Read and learn.

    I think the principles makes sence, but it might be a little over engineered for the relatively small projects that im handling. If i implemented his thoughts, I would spend more time doing plumbing of WCF services than on implementing business logic.

    Still, one has to take the parts of his stuff that makes sence.

    Now i’m up for a session about certification – 70-630 Configuring SharePoint 2007.

  • TechEd 2009 Day 3

    TechEd 2009 Day 3


    I didn’t make it to the blog yesterday, but I will try to put a little info on later about the stuff that happened.

    Today is going to be an exiting day. There is so many sessions I would like to follow but too little time:

    Slot 1:
    Zen of architecture – with Juwal Lowy… Im going to this one.
    Understanding virtualization and MOSS 2007

    Slot 2:
    Preparation for MOSS configuration exam

    Slot 3:
    Applied Entity Framework – I think i will take this one
    Expploring proper MOSS 2007 Installation and topologies

    Slot 4;
    Essential Linq with C# – Probably to intermediate
    Practical web testing
    SharePoint search challenges and tricks
    Building scalable and availabvle web apps with MS Code name Velocity
    Expression Blend from a Dev’s point of view
    How to protect Sharepoint with SCDPM 2007 sp1

    Slot 5:
    ADO Entity Framework – Tips and tricks
    Version and upgrade of sharepoint solutions
    Sharepoinbt online features functionality and customization..

    And a lot of other interesting stuff.

    Over and out.

  • First day at Tech Ed 2009

    First day at Tech Ed 2009


    The TechEd conference of 2009 is kicked off. I am attending with two colleagues from D60, Thomas Garp and Henrik Drachman.

    The stored procedure panel

    I really had high expectations to this one. Finally we were going to end the battle between the T-SQL and SP guys. The panel discussed the various problems with both methods of SQL access, including performance, security and application architecture. The conclusion was, that there is no conclusion. The stored procedures are better in ways of security, performance (Both by using compiled execution plans and by lowering the actual network trafic) and gives a better application architecture by separating the datalayer completely. On the other hand, using T-SQL provides a flexibility that cant be provided by SP’s. A final comment was, that SP’s should be used unless there is compelling reasons not to do so… I think I can agree on that one.

    Keynote
    This years keynote speaker was Bill Veghte, who spoke about Win 7, Windows Server 2008r2 and other stuff. The keynote provided a few interesting point but it was largely a waste of time. The highlight was the announcement of shipdates for win 7 and W2k8r2 before christmas.

    A lap around MS Asp.Net 4.0 and Visual Studio 2010
    This session covered some of the new functionality in VS 2008. Especially snippets for HTML and improvement of the way ASP.Net markup is written was demonstrated. This will give a significant lift to the way HTML and markup is written.
    There was a lot of demos of Ajax, Data access etc, but nothing really interesting. The best announcement was the introduction of the ability to have a debug and production web.config file in a project. ABOUT F…ING TIME!

    Developing SharePoint solutions with the VSeWss3.0 1.3
    Version 1.3 of the VSeWSS 1.3 is in a CTP and soon available. In VS 2010 these tools will be build into the development environment.

    In version 1.3 there is a number of changes: A number of deployment settings have been added, most of the resembling the Carsten Keutmann tool. These tools will probably be the stuff that will make the VSeWSS usable 🙂

    There is also functionalty to rename features, moving files etc in the dev. environment.

    Most important is that the VSeWSS now can run on a 64 bit machine. This functionality is very much needed. There still isn’t a visual designer, but that should also be part of the Visual Studio 2010.

    Thats it for the commercials in this event… The rest was demos and lots of usable code examples. There wasn’t really any earth shaking news, but still good be confirmed in the strategy im using when developing solutions for MOSS-

  • Nerdy joke.

    Its early morning and a long day is ahead… I thought this might start me up in a decent way:

     

    A SQL query walks into a bar and sees two tables. He walks up to them and says ‘Can I join you?’