CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Greg Young [MVP]

December 2007 - Posts

  • RD Stuck?

     

    Oops

    I only get these "Terminal server has exceeded the maximum number of connections" when its 3 am and I am dealing with a production problem where I absolutely need access at that moment. Naturally any admin etc is sleeping and unavailable. Personally walking to the office in my jammies is something I like to avoid so I figured there had to be a better way to get around it and there is. perhaps this is not interesting but I would have bookmarked this a while ago if I had seen it before.

    Step 1: Download psexec from microsoft http://technet.microsoft.com/en-us/sysinternals/bb896649.aspx

    Step 2: Unzip into a folder (let's say c:\pstools)

    Step 3: psexec \\yourserver -u yourusername -p yourpassword qwinsta you will get an ouput like this:

    C:\PsTools>psexec \\MyServer -u gregy -p YeahRight qwinsta

    PsExec v1.93 - Execute processes remotely
    Copyright (C) 2001-2007 Mark Russinovich
    Sysinternals - www.sysinternals.com

    SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
    >console                                     0  Conn    wdcon
    rdp-tcp                                 65536  Listen  rdpwd
                       user1                     1  Disc    rdpwd
    rdp-tcp#21        user2                     2  Active  rdpwd
    qwinsta exited on MyServer with error code 0.

    Output Qwinsta

    Step 4: Kill a connection. Grab the ID field in the above and use it in psexec \\yourserver -u yourusername -p yourpassword logoff ID /v

    C:\PsTools>psexec \\MyServer -u gregy -p YeahRight logoff 2 /v

    PsExec v1.93 - Execute processes remotely
    Copyright (C) 2001-2007 Mark Russinovich
    Sysinternals - www.sysinternals.com

    Logging off session ID 2
    logoff exited on \\MyServer with error code 0.

    Output of log off
  • Asserts are NOT evil

    I have been asking this question to many developers after having heard  the viewpoints of many others on the alt.net list. The common view point seems to be that Debug.Assert is evil and shows a unit test that is missing. Many also made comments such as that if I am using a Debug.Assert that I should have immediately after it matching production behaviour. Some quotes from the discussions I have had:

    Asserts are evil, you should write a unit test to show the failure

    Asserts are antiquated

    Asserts used to be useful in the C/C++ days because you would be testing conditions that should never be false but could be because of direct memory manipulation etc they have no real use in a managed environment.

    I think that all of these viewpoints have really missed the point of why I would want to use an Assert. To me the main reason to Assert is that:

     I want this case tested when in Debug mode but I don't actually WANT to run the test in production. If the test were to fail in production then let it fail or let it return incorrect information

    At the outset this may sound like TDD sacrilege perhaps going through an example will clear it up. Let's say that for whatever reason I am re-implementing Array.BinarySearch. One of the conditions of BinarySearch is that the thing I am searching is sorted. This is a canonical example of where I would want to use an Assert. Writing a unit test for this condition (or expecting a runtime failure from it) is ridiculous as it would be take a O(log n) operation and make it O(n + log n). In other words it would take me longer to insure that the thing is actually sorted than it would take me to actually search it.

     

    Spec# currently also does not support this type of scenario. TO support it I would need the ability to say this condition only applies to the prover, do not emit runtime code for this. Hopefully this is something that will be added in the near future.

  • Constructors ... Hah!

    Chad Myers asked:

    How many, if any, of these kinds of statements should you see in your code:

    ISomeService svc = ObjectFactory.GetObject<ISomeService>();

    0? 1? Less than 12?

     

    Later in the thread:

    (Greg Young channelled Smashing Pumpkins when he said...)
    > 0
    So how do you kick the container off, like what Ayende said in the
    Program.Main() call?

     

    Quite simply I am working on a way to cheat. I am currently working on and I hope to have done + released in early January a mechanism for getting rid of constructors. I have some very basic tests passing now. Here is one, it might make things more clear.

    A a = new A();
    Assert.AreEqual(typeof(AProxy), a.GetType());

    There are lots of reasons this can be good. Think about your IOC setups or for AOP if you use a dynamic proxy! My goal in taking on this project  is not to make this a production system frankly a post build step is a bad (read: fragile) way of doing this. My hope in this is to show the power that comes from this and to then lobby the CLR or C# team to build this for me natively.

    I have a lot of difficult problems to solve still (especially with parameters) but here are the basics so people can comment on it and keep me from making bad decisions.

    I run as a post build step. I find all places in code where a constructor is called and map them to my own generic mega-factory including the parameters associated with the constructor call. This factory dispatches the call to a delegate handler. As of now this handler is strongly typed ...

    Factory.Hook(new ConstructorOf<Foo>.WithSignature<string, int>.To( yourdelegate ))

    The delegate signature would be Foo xxx(string, int)

    If you have hooked a delegate to the constructor I will call your delegate anytime that the constructor is called as opposed to calling the constructor. You can in your delegate return a derived type etc (all without using factories).

    If there is no handler registered I will generate a delegate dynamically that will just pass through and call the original constructor.

    There are some really tough problems here, in particular because I am trying to make things completely transparent. As an example the following condition can happen.

    private static void FooFactory(string _Param) {
        if(_Param == "greg") return new FooProxy();
        return new Foo();
    }

    In this case I want the new FooProxy() to actually call back into the factory but I can't let the new Foo() call come back to the factory (would produce infinite recursion). Since this is runtime configurable I also can't do this at compile time (not that I could anyways because you could always generate code etc that made my assumptions invalid). So what I am left with is needing to have my generic factory look at the call stack (or keep a call stack) in order to figure out if you are already in a call of the same signature in your current construction operation. I think I will write this part quickly tomorrow and throw it up on my blog and give some performance analysis.

    Thoughts?

  • A Use for Extension Methods

    Recently over on the alt.net list there has been alot (read: way too much) talk about extension methods. The running consensus seems to be that extension methods are great for extending someone else's API but have no place in code that you control.

    This view point of many was expressed well by Peter Richie as

    I see no need to release a framework that includes extension methods for classes, public or not.  Releasing updates to a framework that include extension methods for classes is a different story.  The ability to maintain an established level of quality on existing binaries while still offering the ability to add behaviour to the classes in those binaries is very compelling.  But, I agree with Chad that they be avoided on classes whenever possible.  With .NET 3.5 you have to reference new assemblies to bring in extension methods, they don’t magically appear in the existing assemblies.

    and Chad Myers as

    I know I'm doom and gloom, but it seems that ext methods should be avoided where ever possible and treated as smells when unavoidable. They're great in Linq, so the smell is justified, but beware of patchwork ext method frameworks.

    I hope to show some code that benefits from extension methods even on classes that I completely control.

    Fluent Interfaces

    Now I am sure you are thinking "Hey he is going to show how to use native types and extension methods". I won't do this, I think enough people already have and it wouldn't serve my case well for using extension methods on classes that I control.

    I like fluent interfaces, especially for value objects. I have used a builder pattern for some time to create these. If people want I can put up a post explaining more on the relationship between value objects and builders but here is some quick example code.

    public struct CostBuilder

    {

        private readonly int Shares;

        private readonly Money Price;

     

        public CostBuilder Bought(int _Shares)

        {

            return new CostBuilder(_Shares, this.Price);

        }

     

        public CostBuilder Sold(int _Shares)

        {

            decimal alteredprice = this.Price;

            if (alteredprice > 0)

            {

                alteredprice = 0 - alteredprice;

            }

            return new CostBuilder(-_Shares, alteredprice);

        }

     

        public CostBuilder For(Money _Price)

        {

            if (this.Shares > 0)

            {

                return new CostBuilder(this.Shares, _Price);

            }

            else

            {

                return new CostBuilder(this.Shares, 0 - _Price);

            }

        }

     

        public CostBuilder(int _Shares, Money _Price)

        {

            this.Shares = _Shares;

            this.Price = _Price;

        }

     

        public static implicit operator Cost(CostBuilder Builder)

        {

            return new Cost(Builder.Shares, Builder.Price);

        }

    }

     

    Listing 1: A simple Builder

     

    Aaron over at Elutian wrote a post Fluent Fixtures which uses a similar pattern (it is in general similar to the builder pattern). We would then take our builder and put a static instance onto a class named New like this...

    static class New

    {

        public static CostBuilder Cost;

    }

    Listing 2: New class which holds builder

     

    Finally we can use the above example in a manner similar to

    Cost Purchased = New.Cost.Bought(100).For(

        New.Money.InCanada(20000)

    );

    Listing 3: Using code

     

    Now enough about the how to and back to the point of the post Extension Methods... As said earlier we could make this interface nicer possibly by decorating native types with extension methods but the challenge is to show a case where we control the class and we receive benefit from using extension methods.

    We have a problem here productivity wise, every item we do this with lives on the New class. In a large domain this quickly adds up. The easy answer is to start putting New classes into various namespaces. Let me just say that this is not only bad but its really annoying. Enter Extension Methods

    Context Sensitivity

    Extension methods allow me to only have a method visible if you are currently referencing my namespace. This can be used to tweak intellisense a bit so I can only show you what is relevant in your current context when you view the New class unfortunately static methods aren't supported but we can get around that using a static instance.

    public class Builder

    {

    }

     

    public class Create

    {

        public static Builder New = new Builder();

    }


    Listing 4: Create and Builder

     

    Now that I have these I can decorate the Builder with extension methods like:

    public static CostBuilder Cost(this Builder s)

    {

        return new CostBuilder();

    }

    Listing 5: Extension Method for Builder

     

    Now when I go to use it, Create.New will ONLY show me the Cost() method if Cost is in my currently referenced namespaces (as opposed to showing me every object I could every construct). I can do this with all of my objects (I would imagine in a big domain or a generic domain of value objects you may have hundreds of these).

    This makes my finding of these builders more efficient as it will automatically ignore the ones that have no place in my current context.

    Other Uses

    There are lots of things that could use a similar pattern to this. I am simply using it to provide me context sensitive information that I would not otherwise see in a static state. Others that come to mind might be.

    IMyService Service = Instance.For.IMyService().WithContext(Context);

    or to layer something like this over an IOC container so I only see the interfaces that are currently in my context listed as available options.

    ISomeService MyService = Container.For.ISomeService;

     

    Is this good? I'm not sure but the ability to use things in a context sensitive fashion like this certainly seems to offer some interesting possibilities. I can come up with lots of fun ways of abusing using this :)

  • When GhostDoc goes Bad

    The problem with tools like GhostDoc is that you have to use them to remove the tedious bits of documentation, not consider what they produce to be ok as documentation

    I actually came across this today:

     

       44 /// <summary>

       45 /// Initializes a new instance of the <see cref="UpdateOrderPriceCommand"/> class.

       46 /// </summary>

       47 /// <param name="_Gateway">The _ exchange gateway.</param>

       48 /// <param name="_Symbol">The _ symbol.</param>

       49 /// <param name="_BrokerNumber">The _ broker number.</param>

       50 /// <param name="_OrderNumber">The _ order number.</param>

       51 /// <param name="_PriorityTimeStamp">The _ priority time stamp.</param>

       52 /// <param name="_Price">The _ price.</param>

       53 public UpdateOrderPriceCommand(ExchangeGateway _Gateway, string _Symbol,

       54     int? _BrokerNumber, string _OrderNumber, DateTime? _PriorityTimeStamp, decimal? _Price)

       55 {

     

    So is that price per share or price for all of the shares? :)


     

     

More Posts