Tag Archives: Programming

msdn-logo

Dot Net Gotcha #1 – List versus Collection constructor

Don’t Google it!

Do you know (without Googling it) what will this console application display when executed?

    class Program
    {
        static void Main(string[] args)
        {
            var originalNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };

            var list = new List<int>(originalNumbers);
            var collection = new Collection<int>(originalNumbers);

            originalNumbers.RemoveAt(0);

            DisplayItems(list, "List items: ");
            DisplayItems(collection, "Collection items: ");

            Console.ReadLine();
        }

        private static void DisplayItems(IEnumerable<int> items, string title)
        {
            Console.WriteLine(title);
            foreach (var item in items)
                Console.Write(item);
            Console.WriteLine();
        }
    }

If you try to think logically, you expect that both List and Collection will contain numbers from 1 to 6 when they are displayed, right?

Wrong, otherwise this would not be a proper gotcha ;)

Here is the actual output of the application (surprise, surprise):

Do you know why?

Answer is actually very simple. If you check the MSDN documentation for Collection constructor that accepts generic IList you will see this text:

Initializes a new instance of the Collection class as a wrapper for the specified list.

That means that this constructor creates just a wrapper around the existing IList, so adding or removing items to the original list will also affect the new Collection we just created,  because its just a wrapper and uses original List under the hood.

On the other hand List constructor that accepts IEnumerable<T> behaves properly and does what you would logically expect it to do:

Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

So when you create a new List and pass an existing List to its constructor it will create a proper new empty list, and then copy all the references from original List to the new List.

Because of that, the new List is ‘detached’ from the original and this is why it remains unchanged even if we modify the original List.

Moral of the story

This is simply how Microsoft made these two classes (i would not say its very consistent or good but who am i to judge, right?) and as long as you know it – its fine.

And if you don’t know this – it can bite you really hard.

All that you can do is to try to remember this, and also: RTFM.

Btw, did i said that this can be an excellent job interview question?   ;)

Until next Dot Net Gotcha, keep reading those manuals…

Windows-Phone-7-logo

Why I think Windows Phone is superior phone OS?

Windows Phone? How did that happen?

Well over the last couple of months i was experimenting with mobile devices a lot because i was kind of tired of the Desktop and the whole HTML5 madness (yes i don’t like Java Script that much and i certainly don’t think its the-way-of-the-future, but that’s subject for another post).

Out of desperation at first i tried Android and got me a LG Optimus One phone. And I must admit that i liked it very much.

Yes, battery lifetime was problem at start, but installing CyanogenMod custom ROM completely solved that. I even spent some time programming an Android game but that failed miserably because my productivity was close to zero considering all the new things i needed to learn (Java, Open GL).

And all that time one good friend was constantly telling me how great his Windows Phone was. I was very skeptical about that since I previously owned Windows Mobile 6.5 phone  and it was complete failure. I even recall at some time in the past promising to my self that i will never buy Windows powered phone again!

But after hearing all the good things about new Microsoft phone OS I eventually decided to give it a try and got me a Samsung Focus with Windows Phone Mango installed.

Boy was i pleasantly surprised.

And lets be honest here: its not that i did not like Android.  Its good and mature mobile OS.
Its (kind of) Open Source and its has significant market share – not without good reason.

But using Windows Phone after Android was a really pleasent and refreshing experience. And there is no way I’m going back.

Disclaimer: before I continue i want to make few things clear: i don’t work for Microsoft, and i never did and probably never will. Everything i say on this blog is my personal opinion and not of my neighbors or my dog.

So now let me try to summarize the things i

personally love about my new Windows Phone:

 

  • Superb UI - The whole phone User Interface is absolutely AMAZING!  Its very simple and intuitive.
    Yet at the same time it manages to stay slick and beautiful with subtle animations and transitions that do not annoy user but enhance the overall UI experience and make it fun and pleasant.
    UI team did a great job – without any compromises. This is huge win for the platform.
  • Live Tiles – When we speak of the User Experience I must mention the excellent Live Tiles concept.
    Live Tiles are actually just animated squares on your home screen  that represent applications or shortcuts for documents, contacts, URLs or any other static/dynamic piece of information that you can pin and arrange on your mobile ‘desktop’.
    They are called Live for a good reason – they often change their content to show additional information – like number of emails in inbox for email application Live Tile, current temperature for weather app Live Tile etc.
    I like this because it works great for the limited screen space of the phone – each of the tiles can show more info by flipping to display live content as it becomes available/relevant.
  • The phone Just Works – From the practical everyday usage perspective the OS feels very natural and in 99% of cases works exactly as you think it will.
    I have to admit that i never expected this from Microsoft but the whole Windows Phone is so well planed and designed that its never in the way when you are using it. One good example is how built-in music player works with non-standard headphones.
    I tried plugging in the headphones from my old Android phone (it’s a different manufacturer) and I was able to control music playback by pressing the hardware button on the headphones, one press for play/pause, double press to skip current track. Yes I know this is minor and expected thing, but  remember i found this out just by trying and expecting that it should work, and it ‘just worked’  even with non-supported headphones.
    And when you use the phone you often catch yourself thinking ‘Wow this works just as I expected it to work’. After few moments like that and I was already bought.
  • General Email experience is great! In my opinion its superior when compared to the built in email clients on IPhone or  Android. And I don’t mean just MS Exchange email.
    I’m a long time Google Mail user and i don’t use Exchange Server at all. So i was little worried how this will work with MS phone – but without any reason.Gmail works flawlessly out of the box without ANY additional  apps or customizations. I  just added my Google account and it worked. Even the push notifications worked without a single glitch. It also synced my Google Email Contacts and Google Calendar  in expected way, no fuss.
  • Built in keyboard is great! Unlike Android you cannot replace keyboard with 3rd party replacement, but there is really no reason for you to do so any way.
    Default keyboard flawlessly supports multiple languages – I’m using English and Czech settings and i can enter all the Czech special characters very easily (they appear by long pressing the keys – as expected).
    Actually I’m deliberately writing this post on the phone using that same keyboard just to prove the point (therefore don’t mind my spelling, please).
    Copy and paste works very nice and another thing i like is the caret repositioning – just by long pressing the screen and then moving the caret around – i would love to see this working so nice on Android.
  • Multitasking experience is very nice at least in the Mango Windows Phone version that i have.
    Actually there is no real multitasking (if you exclude the occasional background data sync) because only one app is active at the moment. Others are ‘tombstoned‘ until you activate them.
    But there is very nice illusion of multitasking that does the job pretty well.
    By long pressing the Back hardware button you get on the screen very cool visual ‘Task Manager’ where you can see list of your app screens which you can scroll through and choose which app you want to activate now.
    Simply brilliant.
    On the other hand Android has true multitasking but list of running apps is hidden in phone settings and not so slick at all.
  • Phone and SMS functionality – Simple, quick and feature rich yet not in your way when you want to do quick call or SMS somebody. And I could hardly say that for Android or IPhone. Very impressive.
  • TextToSpeech and SpeechToText – Windows Phone has pretty decent voice recognition and when you use wireless or wired headsets you can set it up so that it reads you your SMS messages and you can reply to them over voice command and then dictate your answer. Have a look at this Windows Phone voice commanding demo if you want to know more. Yes i know its not Siri and it can be much better but even as it is now is quite usable if you are native English speaker.
  • Marketplace – Even though there are less apps then for other platforms, there are enough of them and number is growing so time will fix that. But generally speaking Marketplace is already mature and useful.
  • Social Networks integration is flawless. Again without any third party tools.
    Facebook, Twitter, LinkedIn you name it. Its all integrated into People hub on the phone, so you can merge Facebook account with your SIM card phone contact to use it as his/hers account picture etc.
  • do i need to mention that phone integrates nicely with desktop MS Office? OneNote, Word, Excel it works as good as it can get on a mobile device. I don’t use it too much except for OneNote but i think its huge win for corporate users.
  • Built in Music Player and Radio app are great and i enjoy using them for they simplicity and stability. Not a single crash. Try that on android device and good luck trying!
  • One big advantage of Windows Phone for .NET software developers especially for Silverlight folks is that programming Windows Phone is very familiar experience.  Visual Studio has very good support for phone development and Emulator for Windows Phone is in my personal opinion much better and faster then Android one. (Off course one could say I am biased since I’m .NET developer but speed is something that is easily measurable).
    If you have .NET background you can start app development or XNA game development in no time.
    And the Marketplace is not overcrowded. Anyone mentioned word Opportunity?
  • Another small thing that can be a lifesaver is the phone boot time.
    My Samsung Focus boots in 20 seconds and its immediately ready to make phone calls or to write SMS.
    My Android device was not even close to that and even when it was booted it remained to be slow for some time, probably until Micro SD card is initialized and until all the services are up and running.
    Sometimes when you need to make an urgent call this can be really important feature.
  • Every Windows Phone has built in Find My Phone feature that allows you (if you enable it) to see on the map where is your phone and to start the Ringing on the phone, Lock it or Erase it (off course it needs to be connected on the network for this to work).
    This is useful if you lose your phone, or if it gets stolen. I’m not sure about IPhone but I know that on Android you need to install third party apps for this so this is another nice benefit of this platform.
  • Battery Saver – if enabled phone automatically switches to power saving mode when battery is low (stops background sync for example)  and your phone calls and SMS functionality continues to work until there is juice in the battery. I really like this because after all this is a phone device so my calls are more important then my Facebook updates :)
  • Lock Screen on Windows Phone is beautiful. It is following the general minimalistic approach but still manages to show all the relevant information – calendar items, missed calls, messages, emails etc. If you are playing some music there are small controls there.
    All in all very nice without unnecessary bells and whistles.

I could continue like this for some times because there are many other nice things that deserve mention.

But at the same time this is young phone platform so there are also some problems to be addressed.

The biggest issue I currently see for Windows Phone is that its not open enough for developers. Many OS features are exclusively used only by OS apps and by Vendors apps and everyday developers don’t have APIs to access them. Much has been written on the subject so I wont repeat it here, so read the post 10 ways to improve Windows Phone 7 if you are interested or WP7 Extensibility Rant from same author.

Typical example is that in 3rd party apps you cannot subscribe to some user invoked actions, for example there is no way for user to send url to non system application.

I dont see anyone benefiting from this kinds of limitations.

I really hope that Windows Phone team will address these problems and give developers more power.

There is WPDev User Voice Feedback site where all the requests from the developer community are listed – so there is hope this will change soon.

Another thing I don’t like is that for some settings there is no quick way of access.
For example WiFi or Flight Mode. In order to manipulate them you need to go to System Settings and choose menu item  and then switch them on or off. Instead of this hassle I would like to have quick toggle button somewhere on the phone desktop.

Again this is something that would be solved if developers could have access to those settings to programmatically manipulate them.

I guess Microsoft do not want to open the Pandora’s Box by giving  too much power to 3rd party apps, but I think they over did it in this case.

Right balance between opennes and system security on Windows Phone needs yet to be determined.

I would also love to see support for more languages for Text To Speech and Voice Recognition. Im not sure abut Microsoft plans but this would be a killer feature since i think voice is the way to go when it comes to the future of mobile platforms.

Wow this was longer post that I originally intended it to be!

I hope I was able to explain why I personally choose Windows Phone over other modern phone platforms.

Then again, this is all my personal experience and your mileage may vary.

It all depends on what you expect from your phone:

  • If you want to pay for Brand, then simply buy IPhone.
  • If you want phone that does everything you want and that is completely customizable yes often fails because its complex and bloated with unstable apps – get Android.
  • if you just wont cool phone that dont stand in your way but does all things you really could need from mobile device – i recommend Windows Phone

I don’t really expect my phone to be Swiss army knife capable of EVERYTHING but failing to do anything efficiently.

I like minimalistic approach and simplicity so probably this is why I like Windows Phone so much.

But the war of the platforms is still on so don’t be surprised if tomorrow I choose another :)

Those were my 2 cents on the subject, let me know what’s your experience and what is your best mobile OS out there, and most importantly: WHY?

Silverlight MergedDictionaries – using styles and resources from Class Libraries

If you were developing larger Silverlight/WPF applications and trying to keep things like styles, control templates and other resources organized it can become really hard.
Prior to Silverlight 3 it was hell to be honest :D

You had to scatter resources all around your application, on control level and put global ones in App.xaml and soon it would all grow beyond control.

But then nice people from Microsoft introduced lovely little feature called MergedDictionaries that allows you to combine the resources from different places in your application.

The beauty of this simple technique is that you can use resources from different files that can even reside in different Class Libraries in your project and just ‘reference’ them in the application level (App.xaml) and they will immediately become available to all the controls in your application.

Not to mention the moment of reuse: you can group your application resources into assemblies, for example one can hold the Styles, another can contain Control Templates, third can have text resources etc and then you can just reference them in any project and easily (re)use them.

So lets see how to actually accomplish this.
Luckily its very simple. We just need to add few lines to our App.xaml file:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Class="ResourceDictionariesInLib.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/ResourceDictionariesInLib.BasicStyles;component/StylesForShapes.xaml" />
                <ResourceDictionary Source="/ResourceDictionariesInLib.FontStyles;component/StylesForFonts.xaml" />
                <ResourceDictionary Source="LocalStyles/BasicStyles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
  </Application.Resources>
</Application>

As you see here I’m using resources from two different Silverlight Class Libraries and one is from local subfolder called “LocalStyles”.
The format is clear, for resources in DLLs you use:
Source=”/AssemblyName;component/FileName.xaml”
The “component” part is just a keyword that tells the parser that resource is in referenced DLL.

One important catch here is if you are merging resources from DLLs than you need to actually add references to those Class Libraries that hold your resources so in this case i had to Add Reference to two DLLs: ResourceDictionariesInLib.BasicStyles.dll and ResourceDictionariesInLib.FontStyles.dll.

Format for the resource file in the application is self-explanatory.

In order to create a xaml file in some Class Library to hold resources just choose Add->New Item and then select SilverlightResourceDictionary from the list.

Also its important to state here that you can put MergedDictionaries at every level, meaning that you can put them to App.xaml and then those merged resources will be available to every element of your application, but also you can place MergedDictionaries in the CustomControl (in CustomControl.Resources) and then this resources will be available only to this control.

So lets see how those MergedDictionaries of resources can be used.

In the StylesForShapes.xaml file i have some background gradient brushes:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <LinearGradientBrush x:Key="EllipseFillBrush" EndPoint="1,0.5" StartPoint="0,0.5">
        <GradientStop Color="Black" Offset="0" />
        <GradientStop Color="#FFD41313" Offset="1" />
    </LinearGradientBrush>

  <LinearGradientBrush x:Key="RectangleFillBrush" EndPoint="1,0.5" StartPoint="0,0.5">
    <GradientStop Color="Black" Offset="0" />
    <GradientStop Color="#FF3AD859" Offset="1" />
  </LinearGradientBrush>

</ResourceDictionary>

So since i referenced StylesForShapes.xaml file in MergedDictionaries in my App.xaml file i can use styles from that file in any Silverlight control in the whole application.

    <Grid x:Name="LayoutRoot" Background="White" Height="348" Width="489">
        <Ellipse Fill="{StaticResource EllipseFillBrush}" />
        <Rectangle Fill="{StaticResource RectangleFillBrush}" />
    </Grid>

You can do the same for any other property like FontSize or FontFamilly.

Just extract property value to a resource and then reuse it in your app.

Another very nice thing about MergedDictionaries is that they are supported by Visual Studio 2010 and Blend 3/4 so if you have DLLs with resources and you merge them in App.xaml then when you are extracting new resources you can specify those resource files in DLL’s as the place where that newly extracted resource will be created.

Here is the example:
In Visual Studio create UserControl and put an Ellipse element on it and set its Fill property to be some nice GradientBrush and then click on the black diamond symbol to the right of the Fill property and in the pop-up menu choose option Extract value to Resource:


After clicking on the Extract Value to Resource menu item you will need to choose where to save the newly created resource and you can here choose any of the resource xaml files in your Class Libraries like this:

So here is how a sample page that uses MergedDictionaries to set styles and fonts on its controls looks like:

And here is the Visual Studio 2010 demo solution.

Have fun! :D