poniedziałek, 22 listopada 2010

Make Internet Explorer Feeds/podcasts available in Windows Media Player DLNA server with names instead of GUIDs

Last time I found that you can download podcasts using Internet Explorer.
Reasonable next step was to make it available to DLNA Player, so I can watch videocasts on my SONY Bravia KDL-40EX700, or listen podcasts on Nokia Home Music (which I will have soon) in my bedroom.

Windows Media player can share folders, this one is simple to setup. Problem is that Internet Explorer saves all feed attachments in folders named as GUID numbers and it seems that it’s hardcoded and not configurable.


On the other side Windows media Player cannot rename folders it shares through DLNA.

But Uśmiech.

NTFS has ability to create junctions – which means hard link to folder – which means shortcut but on file system level, not a file with .lnk extension.
So we can cheat WMP by creating “podcasts” and “videocasts” folders than create a junctions in it pointing to each podcast or videocast GUID named folder.

Seems simple - but how?

Fortunately I found Link Shell Extension which make it stupid simple. Just “right click” + “drag& drop” GUID named folder to our podcasts folder, choose option to create junction and rename it.







 

And now I can listen/watch my podcasts on TV or Nokia Home Music



 

Simple, but only when you know what to do.

Dear Microsoft – can you make it a little simpler?

Podcast client that can use BITS – IE8

For two years I was looking for some podcast download client that I will be happy with. After few tries I
1) Started to realize what I want,
2) None of available alternatives gived me what I wanted.

So first, my requiremets:

  • It should download podcasts/videocasts correctly – sadly it’s not so obvious.
  • I want to be able to set up how frequently it should check for new podcasts
  • I want to be able to set how much old podcasts should be in download folder (older should be deleted)
  • It should use BITS to download podcasts, so that I use internet for other things also.

I was trying few clients and their quality was really bad. I was so frustrated that almost wanted to create a such.
Then I bought PSP for my son and found that it’s a great podcast client/downloader/viewer. The minor drawback is that it is downloading with full speed, but in exchange you can set it up so that it’s doing it at night (let say at 4:00 PM). The bigger one is that you can only watch MPEG4 AVC videos.

Until now I’m using PSP, but 2 days ago I found that Internet Explorer has everything I want from version 7.
Uhh.

So how to do it

  1. Subscribe to podcast – add it to your Feeds
  2. Right click on it and choose Properties

  3. Check  “Automatically download attached files” and change the number of items that will be stored on your machine to some reasonable value (to avoid filling up your HD)


  4. Now your computer will download podcasts/videocasts in the background using BITS. You can check status of your download by clicking on the feed and reading gray text next to file link. When it changes to (Downloaded), link will point to your disk.


  5. If you receive error “File size exceeds download limit” check this MSDN documentation for FDE_DOWNLOAD_SIZE_LIMIT_EXCEEDED error code and set appropriate value in registry.

piątek, 11 września 2009

My virtual static implementation

What I want is to be able to write code like this:

public T Create<T>() where T : new(string)

{

    return new T("something");

}

or this:

public interface IConverter<Tin, Tout>

{

    static Tout Convert(Tin value);

}

 

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>

{

    return TConverter.Convert(value);

}

but current (4.0) version of C#/CLR doesn’t allow me to do it, so I was forced to think about substitute solution.

If we think about virtual methods we need class that has them and we need instance of this class.

public class IntStringConverter : IConverter<int, string>

{

    public static readonly IntStringConverter Instance = new IntStringConverter();

    public virtual string Convert(int value)

    {

        return value.ToString();

    }

}

But this gives us nothing because we need to know exact type. So I’ve created following class

public static class Static<T> where T : new()

{

    private static bool initilized;

    private static T value;

 

    public static T Value

    {

        get

        {

            if (!initilized)

            {

                value = new T();

                initilized = true;

            }

            return value;

        }

    }

}

to use it instead of Instance field.

And now I can write Convert method like this:

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>, new()

{

    return Static<TConverter>.Value.Convert(value);

}

or Create method

public interface INew<T, T1>

{

    T New(T1 param1);

}

 

public static T Create<T, TFactory>() where TFactory : INew<T, string>, new()

{

    return Static<TFactory>.Value.New("something");

}

So my solution is to create one instance of my “virtual static” type and make sure all other classes can use it without tight coupling to some static field. Right now, all they need to know is Static<T> class.

wtorek, 25 sierpnia 2009

Why should you use generics instead of simple interfaces in method parameters in .NET

Answer: for performance reasons

Consider following methods

public static void TestMax()

{

    int max = (int)Max(5, 10);

}

 

public static object Max(IComparable left, IComparable right)

{

    return left.CompareTo(right) > 0 ? left : right;

}

Now let see how TestMax() is looking when compiled to IL

.method public hidebysig static void TestMax() cil managed
{
.maxstack 2
.locals init ([0] int32 max)
L_0000: nop
L_0001: ldc.i4.5
L_0002: box int32
L_0007: ldc.i4.s 10
L_0009: box int32
L_000e: call object Test.Program::Max(class [mscorlib]System.IComparable, class [mscorlib]System.IComparable)
L_0013: unbox.any int32
L_0018: stloc.0
L_0019: ret
}


So as we can see for this simple call we have two box instructions. This means that we have two heap allocations (malloc() in c).


Now lets see how generic version will behave:




public static void TestMax()



{



    int max = Max(5, 10);



}



 



public static T Max<T>(T left, T right) where T : IComparable



{



    return left.CompareTo(right) > 0 ? left : right;



}




and TestMax() in IL looks like this:



.method public hidebysig static void TestMax() cil managed
{
.maxstack 2
.locals init (
[0] int32 max)
L_0000: nop
L_0001: ldc.i4.5
L_0002: ldc.i4.s 10
L_0004: call !!0 Test.Program::Max<int32>(!!0, !!0)
L_0009: stloc.0
L_000a: ret
}


As you can see instead of box we now have ldc instructions which means that now we are allocating 2*4 bytes on the stack which is much much faster then allocation on the heap.



So the long answer is: Because by this simple tweak you can speed up your method for all struct parameters.

piątek, 7 sierpnia 2009

How to test generic class/methods with Rhino mocks

Rhino mocks is my isolation framework of choice and as you my notice from my earlier post I use generics as my Inversion of Control tool. Problem is that when you use Rhino Mocks you cannot mock constructor (right now to my knowledge only TypeMock Isolator can do this). The reason for this is that Rhino Mocks generates mocks at runtime, and for testing methods that use new() constraint you need to know the mock type at compile time.
So the only way to solve this seems to be creation of mock classes by hand. But then shortly I realized that all of them seems to look very similar.
So…

Here is how I solved this:
First I created t4 file called Mocks.tt which I attach to my test project.

It’s almost unreadable, so don’t be scared – I’m not t4 expert, it’s my first experiment :-)

This file is:

  • generating MockAttribute class
  • searching for each class in project (it belongs to) that have such attribute and are partial and then creates mock methods for each interface this class implements and for default constructor.

To create such mock type I must first write something like this:

[Mock]

public partial class MockAskEmailWindow : IQuestion

{

}

Then click “Run Custom Tool”

run custom tool

And because IQuestion is defined like this

public interface IQuestion

{

    string Ask(string question);

}

in file generated by t4 script I have following code

public partial class MockAskEmailWindow

{

    private readonly MockAskEmailWindow mock;

    public bool Created;

    public MockAskEmailWindow Object;

 

    public MockAskEmailWindow()

    {

        if (Service<Queue<MockAskEmailWindow>>.Value != null)

        {

            mock = Service<Queue<MockAskEmailWindow>>.Value.Dequeue();

            mock.Created = true;

            mock.Object = this;

        }

    }

    public virtual string Ask( string question)

    {

        return mock.Ask( question);

    }

}

Now if we have following method to test:

public string AskForNewUserEmail<TQuestion>() where TQuestion : IQuestion, new()

{

    throw new NotSupportedException();

}

We write test like this:

[Test]

public void ShowUsermNewUserEmailRequestAndRetrieveEmail()

{

 

    var ask = MockRepository.GenerateMock<MockAskEmailWindow>();

 

    ask.Expect(a => a.Ask("Plase type email of the user you want to create")).Return("test@test.pl");

 

    using (Service.CreateQueue(ask))

        Assert.AreEqual("test@test.pl", AskForNewUserEmail<MockAskEmailWindow>());

    ask.VerifyAllExpectations();

}

And to make test pass we change our method to

public string AskForNewUserEmail<TQuestion>() where TQuestion : IQuestion, new()

{

    return new TQuestion().Ask("Plase type email of the user you want to create");

}

Seems, simple :-)
The only unknown class that I used here is Service<> so here is it’s very simple code

public class Service<T> : IDisposable where T : class

{

    private readonly T parent;

    [ThreadStatic] private static T current;

 

    public Service(T service)

    {

        parent = Value;

        Value = service;

    }

 

    public static T Value

    {

        get { return current;}

        private set {current = value;}

    }

 

    public void Dispose()

    {

        Value = parent;

    }

}

 

public static class Service

{

    public static Service<Queue<T>> CreateQueue<T>(T value, params T[] values)

    {

        var queue = new Queue<T>(values.Length + 1);

        queue.Enqueue(value);

        foreach (var v in values)

            queue.Enqueue(v);

        return new Service<Queue<T>>(queue);

    }

}

This class I created as my implementation of service locator earlier when I tried use this pattern to decouple the code. As you can see from code, service implementations can be nested and are specific for current thread (I failed to create services that work between multiple thread because of strange CallContext class behaviour when someone called EndInvoke()). If anyone is interested here is example of usage:

using (new Service<IQuestion>(new MockAskEmailWindow()))

{

    //some code

    using (new Service<IQuestion>(new MockAskEmailWindow()))

    {

        //some other code that uses other version of IQuestion

        //by calling Service<IQuestion>.Value

    }

    //here we use again the first IQuestion

}

But back to generic method testing as you can see from example above the scheme is following:

  • Create mocks using Rhino Mocks
  • put them in the service queue
  • run tested method
  • When mocked type instance is created it takes mock from service queue
  • All calls to newly created object are redirected to mock created in test

And that’s it.

Just one more note: Because of EnvDTE unavailability to read generic constraints (and because it was failing when I called CodeMethod.StartPoint and CodeMethod.EndPoint) I was unable to mock such methods. I solved this by don’t mocking it at all. You must implement such method in your part of partial mock class.

Hope this helps someone

czwartek, 30 lipca 2009

C# generics – free but ugly Dependency Injection

I must admit that: I’m obsessed with generics for some time.

 

Some time ago my way to decouple code was to use IServiceProvider. It was great but required from me and my coworkers to pass it to each newly created class.

In the mean time other developers used different IoC containers which solved this problem by using static methods to register and use specific objects. For example:

IOC.Register<ISomething>(new Something());

 

And later in the code it was used like this:

 

IOC.Resolve<ISomething>().DoSomething();

As I said it solved one problem but I had still other problems with that:

  • Because of static methods I can have only one configuration for the whole application
  • Even if I tried to create my version of IoC container that can be nested like this

    using(new Service<IService>(new ServiceImplementation()))

    {

        //some code

        //and later

        using(new Service<IService>(new AnotherServiceImplementation()))

        {

            //some other code

        }

    }


    I failed to create a version that worked correctly between multiple threads, because I was forced to use static fields and I was unable to force CallContext to not overwrite current Thread configuration when EndInvoke() was called.
  • If I want to write component that may be used by someone else the only way to inform him about required dependencies is documentation, or runtime errors.
  • I must agree with Joel Spolsky that code that uses IoC containers is less readable

Aside from above I’m using static language C#. Why should my dependencies be resolved at runtime. I had never written application that required dynamic dependencies. All of them was known to me while I was writing my applications. Why not use compiler as my dependency resolver.

So, I want to write decoupled and reusable methods and classes.  This can be achived partially by parameter or property Dependency Injection.

Great, but after a while you come to the moment when you must create new object that will be passed to this method or property.

What now, how can I create instance of class without coupling to concrete type, and not using IServiceProvider or static IoC Container (or worse: use reflection). Then it hit me: we can make new() constraint on generic type. That way I can write my method/class in a way that it will create instances without knowledge of concrete type. We can create really decoupled/reusable code using  generics.

 

After few tests I also created short rule:

Every time you must call new() – do it on generic type. (It doesn’t matter if it’s method or class scope generic type)

 

There is one problem with this rule – I must use default constructor - which means – I must inject all already instantiated dependencies by properties or method parameters.

Last month I had small project to create application to manage users in database where data are encrypted. It was separate, small exe file – so I thought that I test my thoughts about generics. As example of decoupled code lets see fragment of my UserCreator class:

public class UserCreator<TRepository, TCertificateStore, TCertificate, TUserLoginQuestion, TPasswordGenerator> : IUserCreator<TRepository>

    where TRepository : IRepository

    where TCertificateStore : ICertificateStore<TCertificate>, new()

    where TCertificate : ICertificate

    where TUserLoginQuestion : IQuestion, new()

    where TPasswordGenerator : IPasswordGenerator, new()

{

    public TRepository Repository { get; set; }

 

    public void CreateFirstUser()

    {

        var store = new TCertificateStore();

        var adminCert = store.CreateAdministratorCertificate();

        store.SaveAdministratorCertificate();

        var login = new TUserLoginQuestion().Ask();

        var userCert = store.CreateUserCertificate(login);

        store.SaveUserCertificate(userCert);

        var userCertBytes = userCert.ToBytes();

        Repository.CreateNewUser(login, userCert.Encrypt(Encoding.ASCII.GetBytes(new TPasswordGenerator().Generate())), userCertBytes);

        Repository.CreateNewAdministrator(userCertBytes, adminCert.Sign(userCertBytes));

    }

}

Uhh, little ugly – but (almost) completly decoupled (Encoding.ASCII.GetBytes is not important dependency in that case). To make this class more usable I created also default version

public class UserCreator : UserCreator<RepositoryDataContext, CertificateStore, Certificate, AskUserEmailForm, PasswordGenerator>{}

As you can see I can change everything this class uses to whatever implementation I want. What blows my mind is – how such small method requires so much dependencies. Below you have example of usage:

public static void Main<TRepository, TAdministratorTable, TAdministrator, TUserCreator, TLogin, TApplication>(TRepository repository)

    where TRepository : IRepository, IAdministratorRepository<TAdministratorTable, TAdministrator>

    where TAdministratorTable : IQueryable<TAdministrator>, ITable

    where TAdministrator : IAdministrator, new()

    where TUserCreator : IUserCreator<TRepository>, new()

    where TLogin : ILogin, new()

    where TApplication : IApplication, new()

{

    try

    {

        if (repository.Administrators.Count() == 0)

            new TUserCreator{Repository = repository}.CreateFirstUser();

        var login = new TLogin();

        login.Login();

        if (login.UserAuthenticated)

            new TApplication().Start();

    }

    catch(CancelException)

    {}

}

In line

            new TUserCreator{Repository = repository}.CreateFirstUser();

you can see that I must pass repository as property. It will be great if I can make a constraint for constructor other than default. For example

    where TUserCreator : IUserCreator<TRepository>, new(TRepository)

but right now I must live with a tools I have (c# 3.0). I don’t have strong opinion which is better default constructor + properties or specific constructor.

 

I was afraid that when my codebase will grow the list of dependencies will grow, especially in Main() method. What I observed instead of this was that each method require max 6-10 dependencies. Not so scary.

 

OK time for some summary:
Pros:

  • Completly decoupled/reusable code
  • Completly testable code
  • Best performance possible (no boxing for value types)
  • Free – you already have all tools – I mean you already have one tool – compiler :-)
  • All dependencies are resolved by compiler
  • User of your code knows all dependencies at compile time (using only intellisense)
  • Because dependencies are static, they will not change in other thread (until you say so)

Cons:

  • Little ugly method/class definition (I’m sure that better type inference would help here, but I’m not sure how much better is possible)
  • Only constraint for default constructor is possible
  • No possibility to use static methods (MS please add static virtual methods)

If anyone isintrested I’ll try to write in short time how I test such generic methods/classes. Especially how I test newly created instances. All I can say right now is that I use t4 script and Rhino Mocks.

czwartek, 9 października 2008

Is it possible to write c# application without using cast?

For last few months I'm more and more fascinated with .NET generics. Especially interesting for me is a (totally academic) question: Is it possible to write application without using an cast?
While considering that option first 2 problematic cases I found was some kind of cache or ServiceProvider implementations. I even asked a question on stackoverflow.com if it's possible, but the only answer I had was that it's not or that I should have something like WeakDictionary - which probably will use cast in its implementation.

But I wouldn't be oneself if I will abandon this subject :-). As I showed in question it's possible for only one instance using static generic fields, but I can't find the solution for non static objects. After few days I think I found the solution to this - not so elegant, but it should work.

So here you have fully generic (but simplified) implementation of ServiceProvider:

    6 public class ServiceContainer : IDisposable

    7 {

    8     readonly IList<IService> services = new List<IService>();

    9 

   10     public void Add<T>(T service)

   11     {

   12         Add<T,T>(service);

   13     }

   14 

   15     public void Add<Key, T>(T service) where T : Key

   16     {

   17         services.Add(new Service<Key>(this, service));

   18     }

   19 

   20     public void Dispose()

   21     {

   22         foreach(var service in services)

   23             service.Remove(this);

   24     }

   25 

   26     ~ServiceContainer()

   27     {

   28         Dispose();

   29     }

   30 

   31     public T Get<T>()

   32     {

   33         return Service<T>.Get(this);

   34     }

   35 }

   36 

   37 public interface IService

   38 {

   39     void Remove(object parent);

   40 }

   41 

   42 public class Service<T> : IService

   43 {

   44     static readonly Dictionary<object, T> services = new Dictionary<object, T>();

   45 

   46     public Service(object parent, T service)

   47     {

   48         services.Add(parent, service);

   49     }

   50 

   51     public void Remove(object parent)

   52     {

   53         services.Remove(parent);

   54     }

   55 

   56     public static T Get(object parent)

   57     {

   58         return services[parent];

   59     }

   60 }

As you can see I store all services in static generic Dictionary, which also have information to which serviceProvider this service belong. Normally when ServiceProvider will be cleaned by Garbage Collector, all services also will be removed from memory. But because I have static field that holds them, to avoid memory leaks I'm cleaning those services in destructor/finalizer o ServiceProvider.

I see two drawbacks of this solution

  • Larger memory usage due to need of having two lists of references to those services
  • ServiceProvider stays one generation longer in memory than normal solution with cast, because of finalizer usage.

Now with this example Implementation of cache without cast shouldn't be so hard :-)

LATE EDIT (2009-07-30): As someone may notice from my answer on stackoverflow.com  I tried to implement such ServiceProvider but failed to do it without memory leaks. Uhh :-(

My request to microsoft: Please implement WeakReference<T>.