Tag: .Net

  • 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

  • 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-

  • Language confusion in Moss

    I had yet another Moss confusion this morning. I have installed an English Moss and then configured the server with a Danish language pack. When i opened up a site directly from my development server, everything was displayed nicely in danish. The top bar greated me with a “Velkommen Kaj” (I guess even US/UK readers can guess what that means in danish 🙂 ). When i opened up the site directly on my laptop, the greating was in English…

    As my little green StarWars friend would say:

    Strange that is.. yeah!

    This does not only apply to the greating, but also to the Site Actions menu and help collection.

    So the same site is shown with different language settings on two different machines.

    After a little investigation, i found out that my laptop was set to be located in America. (Control Panel –> Regional and language Settings –> Location). This is what caused it to show these things in English.

    Only developers from out of this planet will be able to explain why this is the way Moss is behaving. But it is! So learn it and behave correctly. If only Moss used my computers language setting, I could understand. Even better, it would just use the language setting of the site. But it does not!

    Luckily i hadn’t configured my laptop to be located in Uzbekistan!