Async CTP–Fixing the Installation Problem

by Mikael Koskinen 22. February 2012 19:42

I wasn’t aware that the Async CTP worked with Windows Phone 7 until I read this good introduction by Kevin Ashley.It’s not just the await and async –keywords which got me excited, it’s the thought of using TPL with WP7.

Unfortunately getting the CTP 3 to install wasn’t an easy task. First time everything seemed to go alright, except I couldn’t find the samples or DLLs from anywhere. Turns out this is a common problem and it is caused by the Silverlight 5 and some Visual Studio Hotfixes. 

Here are the steps I had to take in order to get the Async CTP installed:

  1. Removed Silverlight 5 SDK through Programs and Features
  2. Removed the following updates through Programs and Features / Installed Updates:
    1. KB2615527
    2. KB2635973
    3. KB2549864

All of these can be reinstalled after Async CTP has been installed.

After going through the steps described above, Async with WP7 is a go:

        private async void ButtonClick(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine(await GetWebpage());
        }

        private async Task<string> GetWebpage()
        {
            return await new WebClient().DownloadStringTaskAsync(new Uri("http://www.bing.com"));
        }

Windows Phone 7 Sockets: Debugging

by Mikael Koskinen 19. February 2012 12:49
Advert: IRC7 is the premium IRC-client for Windows Phone 7, supporting features like SSL, SASL, multiple server connections and scripting. Learn more at irc7.org.

This is the part IV of a tutorial series which will describe the WP7’s sockets-support from a developer’s perspective. This tutorial series will focus on developing WP7 applications which require a long running TCP-connection that sends and receives text-based data. In these posts we will go through of building a complete IRC-client.

The focus of these posts is in the WP7’s developer’s perspective. If you want to better understand the inner details of the Internet sockets, Wikipedia has a good introduction on the subject.

This part of the series will focus on debugging sockets. In the next part we’re going to finish this tutorial series by adding SSL socket connections into our app.

Background

The basis of our client is ready. It can open a connection, receive a message and send a message. But it’s not very feature rich. When you start adding features, it’s likely that at some point you have to debug incoming or outgoing messages.

The basic way: Debug.WriteLine

The most basic way of debugging sockets is to use Debug.WriteLine to log every incoming and outgoing message before any processing is done on the message. When this kind of a debugging mechanism is added, we have a starting point for understanding what’s moving between the client and the server.

Debug.WriteLine will log the messages into the Visual Studio’s Output-window:

image

But this window doesn’t show everything. Let’s modify our debugging so that it also trims the received message and prints out the character count:

            Debug.WriteLine("Char count: {0} - Message: {1}", ircMessage.Length, ircMessage.Trim());

Now compare these two lines which we may receive from the server:

image

The messages look like identical, but the character count tells an another story. The reason for this is that the first message contains a special character which the Visual Studio’s output window can’t display. The situation changes when the lines are copy-pasted into the Notepad++:

image

Even though Notepad++ can’t render the message correctly, we can see what is different: There’s a special character just before the ‘0’. In case you wonder where this character origins from, it’s a color coded message sent using mIRC.

Debug.WriteLine allows you to get started rapidly but remember: Your output window may be hiding things from you.

Wireshark

In case Debug.WriteLine is too limited for your scenario, WireShark probably isn’t. WireShark allows you to “go deep”:

Wireshark is a free and open-source packet analyzer. It is used for network troubleshooting, analysis, software and communications protocol development, and education.

With WireShark we can capture every packet which is sent between our app and the server. When you download, install and run it, you’re first greeted with a dashboard, which lists all your network adapters:

image

This computer has only one real network interface called “Atheros L1C PCI-E Ethernet Controller”. The situation differs between various computers but usually there should be only one, maybe two interfaces. When you select the correct one, WireShark automatically starts following the packages and showing this info to you, in real time.

image

WireShark is an excellent tool, but in our case it has one problem: It shows too much data. There’s just too many packets moving around and without filtering it it’s just not possible to find the related bits and pieces. But fortunately WireShark contains good tools for getting rid of the irrelevant data.

We want to monitor only the packages which are sent between our IRC-client and the server. So, let’s start by selecting Capture – Stop from the menu:

image

Then, let’s add a filter which removes everything except the packages which are from or to our IRC-server. In this case our server’s IP-address is 195.197.52.90. Here’s a filter which removes everything else:

ip.src eq 195.197.52.90 or ip.dst eq 195.197.52.90

This filter can be added to the top-left part of WireShark:

image

Now, start capturing the data by selecting Capture – Start. WireShark offers you the option to save the last capture as a file but we can continue without saving. Then, run your app and try to connect to the server. WireShark shows the packages moving between the client and the server and this time there isn’t that much data.

image

Try double clicking one of the lines with protocol “IRC” and you’ll see the exact message:

image

The listing is now quite good but still, we can make it even better. As you notice, there’s few items in the list with protocol TCP and if you look at the details of these messages, you’ll notice that they don’t contain any meaningful data for us. We can filter those out too:

(ip.src eq 195.197.52.90 or ip.dst eq 195.197.52.90) and irc

Now we have a filter which shows only the messages between our client and the server and in addition to that, it shows only the messages related to the IRC-protocol.

Conclusion

In this post we went through of couple different ways of debugging socket connections. Debug.WriteLine gets you started rapidly but remember, some character may not be visible. WireShark is the other option. It’s much more harder to use but also much more advanced.

Next up: Using SSL with Windows Phone sockets.

Source code

The whole source code for this tutorial is available from the GitHub.

Links

Unity: Passing Constructor Parameters to Resolve

by Mikael Koskinen 11. February 2012 18:55

In this tutorial we will go through of couple different ways of using custom constructor parameters when resolving an instance with Unity:

  1. By using the built-in ParameterOverride
  2. By creating a custom ResolverOverride.

Background

When you’re using a DI-container like Unity, you normally don’t have to worry about how the container resolves the new instance. You have configured the container and the container will act based on your configuration. But there may be cases where you have pass in custom constructor parameters for the resolve operation. Some may argue that this screams of bad architecture but there’s situations like bringing a DI-container to a legacy system which may require these kind of actions.

Resolved class

In this tutorial we are resolving the following test class:

    public class MyClass
    {
        public string Hello { get; set; }
        public int Number { get; set; }

        public MyClass(string hello, int number)
        {
            Hello = hello;
            Number = number;
        }
    }

It is registered to the container using RegisterType-method and without passing in any parameters:

            var unity = new UnityContainer();
            unity.RegisterType<MyClass>();

So let’s see how we can pass in the “hello” and “number” variables for the MyClass’ constructor when calling Unity’s Resolve.

Unity ResolverOverride

Unity allows us to pass in a “ResolverOverride” when the container’s Resolve-method is called. ResolverOverride is an abstract base class and Unity comes with few of these built-in. One of them is ParameterOverride which “lets you override a named parameter passed to a constructor.” 

So knowing that we need to pass in a string named “hello” and an integer called “number”, we can resolve the instance with the help of ParameterOverride:

        [Test]
        public void Test()
        {
            var unity = new UnityContainer();
            unity.RegisterType<MyClass>();

            var myObj = unity.Resolve<MyClass>(new ResolverOverride[]
                                           {
                                               new ParameterOverride("hello", "hi there"), new ParameterOverride("number", 21)
                                           });

            Assert.That(myObj.Hello, Is.EqualTo("hi there"));
            Assert.That(myObj.Number, Is.EqualTo(21));
        }

We pass in two instances of ParameterOverride. Both of these take in the name and the value of the parameter.

Custom ResolverOverride: OrderedParametersOverride

But what if you don’t like passing in the parameter names and instead you want to pass in just the parameter values, in correct order? In order to achieve this we can create a custom ResolverOverride. Here’s one way to do it:

    public class OrderedParametersOverride : ResolverOverride
    {
        private readonly Queue<InjectionParameterValue> parameterValues;

        public OrderedParametersOverride(IEnumerable<object> parameterValues)
        {
            this.parameterValues = new Queue<InjectionParameterValue>();
            foreach (var parameterValue in parameterValues)
            {
                this.parameterValues.Enqueue(InjectionParameterValue.ToParameter(parameterValue));
            }
        }

        public override IDependencyResolverPolicy GetResolver(IBuilderContext context, Type dependencyType)
        {
            if (parameterValues.Count < 1)
                return null;

            var value = this.parameterValues.Dequeue();
            return value.GetResolverPolicy(dependencyType);
        }
    }

The parameter values are passed  in through the constructor and put into a queue. When the container is resolving an instance, the parameters are used in the order which they were given to the OrderedParametersOverride.

Here’s a sample usage of the new OrderedParametersOverride:

        [Test]
        public void TestOrderedParametersOverride()
        {
            var unity = new UnityContainer();
            unity.RegisterType<MyClass>();

            var myObj = unity.Resolve<MyClass>(new OrderedParametersOverride(new object[] {"greetings", 24 }));

            Assert.That(myObj.Hello, Is.EqualTo("greetings"));
            Assert.That(myObj.Number, Is.EqualTo(24));
        }

Sample code

The above examples can be found from GitHub.

Tags:

c#

Graze and GrazeWP7 available from the NuGet

by Mikael Koskinen 5. February 2012 20:51

Both Graze and GrazeWP7 are now available through NuGet. To get started, first create a new “Empty Project” with Visual Studio and then add the Graze or GrazeWP7 using NuGet. Graze.exe and the template-folder are installed into the root of your project. Installing GrazeWP7 will automatically install Graze.

Project sites:

Tags:

graze | grazewp7

WP7Graze: Creating WP7 App Marketing Web Site using Graze and Twitter Bootstrap

by Mikael Koskinen 4. February 2012 20:52

screenshot_smallGrazeWP7 is a Windows Phone 7 app marketing site generator. It uses the Graze templating engine with Twitter Bootstrap to create static web sites.

GrazeWP7 uses a simple configuration file to generate a static web site for your application. The generated sited is pure HTML / CSS / JavaScript and can be hosted on any web server.

More details

More details about WP7Graze, including the quick start, are available from the project’s home.

Inspiration

The GrazeWP7 was inspired from the following projects:

It uses Windows Phone image assets from those projects.

Tags:

graze | grazewp7

Graze: Static site generator using Razor

by Mikael Koskinen 4. February 2012 18:23

Graze is a simple static site generator. It takes a template and a configuration file and generates a static web site. The generated sited is pure HTML / CSS / JavaScript and can be hosted on any web server. The Graze templates are created using the Razor Syntax.

Getting started

  1. Download and extract the Graze. It comes with an example.
  2. Run graze.exe.

The static site (index.html) is generated into the “output” folder.

Graze templates

The Graze templates are created using the Razor.

<html>
<head>
    <title>@Model.Title</title>
</head>
<body>
    <h1>@Model.Description</h1>
</body>
</html>

Graze configuration

The configuration for Graze is done in XML.

<?xml version="1.0" encoding="utf-8" ?>
<site>
  <Title>Graze</Title>
  <Description>Graze: Static site generator using Razor</Description>
</site>

The configuration file represents the data which is injected to the generated static site.

Generating the static site

Once the Graze template and the configuration file are in place, the static site can be generated running the graze.exe. The static site is outputted to the output-folder.

Examples

The GrazeWP7 uses Graze to generate marketing sites for Windows Phone 7 applications.

screenshot_small

Features

Lists

Lists can be created in XML and accessed in the Graze template. Example XML:

  <Features>
    <Feature>Layouts defined using Razor syntax.</Feature>
    <Feature>Dynamic data models created in XML.</Feature>
    <Feature>Supports complex data models and arrays.</Feature>
    <Feature>Fast static site generation.</Feature>
    <Feature>Pure HTML / CSS / Javascript output. Host in Apache, IIS etc.</Feature>
  </Features>

Example template for accessing the list:

    <h2>Features:</h2>
    <ul>
        @foreach (var feature in Model.Features)
        {
            <li>@feature</li>
        }
    </ul>

Complex types

By default all the data in the XML is of type string when accessed from the template. But complex types can be created also:

<Link Url="https://github.com/mikoskinen/graze">Source code hosted in GitHub</Link>
<a href="@Model.Link.Url">@Model.Link.Link</a>

Case sensitive

The configuration is case sensitive.

Folder structure

Graze expects the following folder structure:

graze.exe
--template/
----configuration.xml
----index.cshtml
----assets

The assets folder is copied wholly to the output folder. The assets folder can include the CSS / JSS / image files required by the template.

License

Graze is available with the MIT-license. It uses the RazorEngine to generate the output.

Source code

Graze is hosted at GitHub.

Tags:

graze

WP7: Display Different Data Template for Different Items in the List - DataTemplateSelectors with the help of Caliburn.Micro

by Mikael Koskinen 20. January 2012 16:27

imageIn this Windows Phone 7 tutorial you will learn how to take advantage of Caliburn.Micro when displaying a list of non-identical objects to the user.

Background

Displaying a ListBox for a list which contains different kinds of items is a common scenario when developing applications for Windows Phone. For example your list can present a folder which contains files and subfolders. When presenting this list to the user you usually want the files and folders to look different. There’s many ways to make this happen, like ValueConverters and the following implementation using abstract DataTemplateSelector.

But if you’re using the Caliburn.Microframrwork, you’re all set. The functionalities inside the framework will take care of this automatically for you.

Scenario

You want to present a folder structure to the end user. You have one bindable list which contains both the subfolders and files and you have one ListBox inside the XAML which shows both types of items. The File.cs and Folder.cs files contain our models:

    public class File
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
        public double Size { get; private set; }

        public File(int id, string name, double size)
        {
            Id = id;
            Name = name;
            Size = size;
        }
    }
    public class Folder
    {
        public int Id { get; private set; }
        public string Name { get; private set; }
        public List<Folder> SubFolders { get; private set; }

        public Folder(int id, string name, List<Folder> subFolders)
        {
            Id = id;
            Name = name;
            SubFolders = subFolders;
        }
    }

In the ListBox you want to display the item’s name and a little icon next to it to indicate the item’s type.

Implementation – The ViewModel

What we’re going to need is just one ViewModel. We’re not going to create ViewModels for our models:

  • MainPageViewModel – The main VM which contains the list which is shown to the user.

The MainPageViewModel inherit’s the Caliburn.Micro’s Conductor-class. The Conductor provides our VM an observable list where we can add items. When the list is modified, our view automatically gets a notification and knows to update itself.

You could manually create a new ObservableCollection , but in our case we try to take the full advantage out of our framework of choice.

The list can be accessed through the Items-property. So, to add a new item into our observable list, we can just call Items.Add(OurObject). As you’ll notice, we have defined the conductor as type of object. This mean that the Items-property inside the conductor is of type BindableCollection<object>. Meaning, you can actually add any type of items inside the collection. You can use more precise type if you know what kind of items your list contains.

The actual work the MainPageViewModel has to do is to create some fixed data for our application:

    public class MainPageViewModel : Conductor<object>.Collection.AllActive
    {
        protected override void OnInitialize()
        {
            Items.AddRange(new List<object>()
                               {
                                   new Folder(1, "Folder 1", null),
                                   new Folder(2, "Folder 2", null),
                                   new File(1, "File 1", 30.0),
                                   new File(2, "File 2", 30.0),
                                   new File(3, "File 3", 30.0),
                                   new Folder(4, "Folder 3", null),
                               });
        }
    }

We now have our ViewModel all set up so let’s concentrate on the Views next.

Implementation – The Views

We need three different Views:

  • MainPage.xaml – The page which contains our ListBox
  • FolderView – A UserControl which displays the Folder-item
  • FileViewModel – A UserControl which displays the File-item

Our MainPage.xaml is simple, containing only the ListBox. We’ll name it “Items” so that the Caliburn.Micro automatically binds it to our MainPageViewModel’s Items-property. What differs from the usual is our DataTemplate. We’re making the Caliburn.Micro to find the correct UserControl to represent our item.

            <ListBox x:Name="Items">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <ContentControl cal:View.Model="{Binding .}" HorizontalAlignment="Left" />
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Now that our MainPage is all set we can create the UserControls which represent the items inside the folder. Here’s the implementation of FileView:

 

    <Grid x:Name="LayoutRoot" Background="Transparent" Margin="12 0 0 0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Image Grid.Column="0" Source="/Icons/appbar.save.rest.png"/>
        <TextBlock Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PhoneTextNormalStyle}"/>
    </Grid>

And the FolderView looks similar, we’ll just change the Image. But notice, you could customize these views anyway you want, for example displaying the folder’s subfolders inline.

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Image Grid.Column="0" Source="/Icons/appbar.folder.rest.png"/>
        <TextBlock Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PhoneTextTitle3Style}"/>
    </Grid>

imageIf we now run the application we will see that everything is almost set, except that the Caliburn.Micro can’t find the correct views for the File and Folder-classes. Let’s take care of that next.

Matching the ViewModel and Models to Views

As you remember, we didn’t create ViewModel-classes for the models. Instead we’ll tell Caliburn.Micro how to match the File and Folder –models to their views.

Caliburn.Micro uses conventions to match Views and ViewModels. The most common convention for finding a View for a ViewModel is to just drop the Model from the type name, for example CustomerViewModel –> CustomerView. The framework is highly configurable and you can add your own conventions. 

In order for the framework to find our views, we’ll add couple rules to its ViewLocator. We configure the ViewLocator inside the application’s bootstrapper. We could have named our models FileViewModel and FolderViewModel and if we had done so, we wouldn’t need the following because the Caliburn.Micro could automatically find the views:

            ViewLocator.NameTransformer.AddRule("caliburn_micro_datatemplate_selector.File", "caliburn_micro_datatemplate_selector.FileView");
            ViewLocator.NameTransformer.AddRule("caliburn_micro_datatemplate_selector.Folder", "caliburn_micro_datatemplate_selector.FolderView");

The code explains itself quite well. We just pass in the ViewModel-type’s full name and the matching View’s full name. To make the code refactoring easier we could use types instead of the magic strings:

            ViewLocator.NameTransformer.AddRule(typeof(File).FullName, typeof(FileView).FullName);
            ViewLocator.NameTransformer.AddRule(typeof (Folder).FullName, typeof (FolderView).FullName);

And that’s it. We now have an application which can handle the situation where one list contains multiple types of objects.

image

Conclusion

Caliburn.Micro offers a powerful solution for those situations where your list contains multiple types of objects and you want to display them in a single ListBox.

Full source code for the sample app is available from the GitHub.

Links

Marketwatcher: WP7 Class Library and Sample Application for Fetching Application Reviews from the Marketplace

by Mikael Koskinen 19. January 2012 19:10

imageI’ve just committed the first working version of Marketwatcher, a library for Windows Phone 7 which can be used to fetch application reviews from the Windows Phone Marketplace. It is available from the GitHub and it’s licensed with MIT, so you can use the library anyway you want.

Get the source code.

Get the compiled binaries.

Sample application

The Marketwatcher GitHub repository contains a sample app which can used to check out how the library is used.

Review data

At the moment an app review is described with the following model:

        public string Id { get; private set; }
        public string Author { get; private set; }
        public DateTime UpdateTime { get; private set; }
        public int Score { get; private set; }
        public string Comments { get; private set; }
        public string CountryCode { get; private set; }

Implementation

Marketwatcher uses the Reactive Extensions. It may be that the RX is dropped at some point in favor of a implementation that doesn’t require any other DLLs. The library also references System.ServiceModel.Syndication which is used to parse the review data. The referenced dlls are included in the repository.

Usage

Marketwatcher.Fetcher:

Use either:

public IObservable<List<Review>> FetchReviewsForApp(string appId)

or

public IObservable<List<Review>> FetchReviewsForAppFromOneMarketplace(string appId, string marketplaceCountryCode)

In the app you can subscribe to these. The following example is from the sample app:

            var fetcher = new Fetcher();

            progressIndicator.IsVisible = true;

            var reviews = new ObservableCollection<Review>();
            Items.ItemsSource = reviews;

            fetcher.FetchReviewsForApp(this.Appid.Text)
                .ObserveOn(SynchronizationContext.Current)
                .Subscribe(x =>
                               {
                                   foreach (var review in x)
                                   {
                                       reviews.Add(review);
                                   }
                               },
                               ex => Debug.WriteLine("error"),
                               () => progressIndicator.IsVisible = false);

Nuget

The Nuget package is coming!

Download

GitHub repository.

Binaries.

WP7 Application’s Mango-upgrade: Remember to check TextBox InputScopes

by Mikael Koskinen 5. January 2012 10:19

We recently upgraded one of our Windows Phone 7 apps to Mango and things went quite smoothly using the Visual Studio’s built-in “Upgrade to Windows Phone 7.1” –functionality.

image

But when we started testing the app, we noticed that some of our textboxes had a wrong input scope. In one case this made our app impossible to use with virtual keyboard because the textbox was missing the Enter-key.

We had previously defined the textbox using the InputScope “Number”:

<TextBox InputScope="Number"/>

And with out pre-Mango version this was the output:

image

But, after upgrading the app to Mango, the keyboard was completely different:

image

The Enter-key was gone, rendering the app useless. We had to change the InputScope to “PostalCode” to get the required functionality back:

image

So, even if the Mango-upgrade goes smoothly, it’s a good idea to test all the textboxes before submitting your app.

Links

Tags:

wp7

Caliburn.Micro: RadTransitionControl custom convention

by Mikael Koskinen 25. December 2011 09:06

I’ve recently started using the Telerik’s RadControls for Windows Phone. Here’s a convention for Caliburn.Micro which allows the easier usage of RadTransitionControl:

            ConventionManager.AddElementConvention<RadTransitionControl>(ContentControl.ContentProperty, "DataContext", "Loaded").GetBindableProperty =
        delegate(DependencyObject foundControl)
        {
            var element = (ContentControl)foundControl;

            var useViewModel = element.ContentTemplate == null;

            if (useViewModel)
            {
                return View.ModelProperty;
            }

            return ContentControl.ContentProperty;
        };

With this convention you can use the RadTransitionControl similar to ContentControl but with the difference that RadTransitionControl will show an effect (like fading) when the content changes. Here’s an example where the convention is used by Caliburn.Micro to automatically bind a control named Target to the ViewModel’s property:

XAML:

<telerikPrimitives:RadTransitionControl x:Name="Target" />

View model:

        public NewTargetBaseViewModel Target
        {
            get { return target; }
            set
            {
                target = value;
                NotifyOfPropertyChange(() => Target);
            }
        }

About the author

Mikael is a systems architect at Digia. Writing .NET is what he does most of the days. He is also the founder of a Finnish software and web systems consulting company Software Mikael Koskinen. 

SilverlightShow ContributorStay updated with latest posts by following Mikael on Twitter.

 

Advert

IRC7 is the IRC-client for Windows Phone 7. Learn more at irc7.org.

Month List