Silverlight sparkline chart

According to Wikipedia

A sparkline is a very small line chart, typically drawn without axes or coordinates.

Though this chart is not included by default to the Silverlight Toolkit library, it is very easy to implement such chart by styling the built-in Line chart. Here is an example which I’ve implemented:

silverlight_sparkline_sample

At first I’ve changed the default control template of the Chart control, I’ve removed all paddings, the chart title, and reduced the minimum height and width of the chart. Also I’ve changed the DataPoint template (made them invisible) and the Polyline template (reduced its thickness). Here is the XAML code:

<UserControl.Resources>
    <Style x:Key="ChartWithoutPaddings" TargetType="chart:Chart">
        <Setter Property="Padding" Value="0" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="ChartAreaStyle">
            <Setter.Value>
                <Style TargetType="Panel">
                    <Setter Property="MinWidth" Value="100" />
                    <Setter Property="MinHeight" Value="20" />
                </Style>
            </Setter.Value>
        </Setter>
        <Setter Property="PlotAreaStyle">
            <Setter.Value>
                <Style TargetType="Grid">
                    <Setter Property="Background" Value="Transparent" />
                </Style>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="chart:Chart">
                    <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}">
                        <chartingprimitives:EdgePanel x:Name="ChartArea" Style="{TemplateBinding ChartAreaStyle}">
                            <Grid Canvas.ZIndex="-1" Style="{TemplateBinding PlotAreaStyle}" />
                        </chartingprimitives:EdgePanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <Style x:Key="EmptyDataPoint" TargetType="Control">
        <Setter Property="Background" Value="Black" />
        <Setter Property="Template" Value="{x:Null}" />
    </Style>

    <Style x:Key="OnePixelLine" TargetType="Polyline">
        <Setter Property="StrokeThickness" Value="1" />
    </Style>
</UserControl.Resources>

This code is almost all that you need to create a sparkline chart. All that is left is to remove axes. It wasn’t a trivial thing, so I used some kind of a hack: I set their width (for Y axis) and height (for X axis) to zero.

<chart:Chart Style="{StaticResource ChartWithoutPaddings}">
    <chart:LineSeries ItemsSource="{Binding FirstIndexItems}" IndependentValuePath="Number" DependentValuePath="Value" 
                        DataPointStyle="{StaticResource EmptyDataPoint}" 
                        PolylineStyle="{StaticResource OnePixelLine}"  />
    <chart:Chart.Axes>
        <chart:LinearAxis Orientation="X" Height="0" Opacity="0" />
        <chart:LinearAxis Orientation="Y" Width="0" Opacity="0" />
    </chart:Chart.Axes>
</chart:Chart>

Links
Source code: SparklineChartSample.zip
Showcase: SparklineChartSampleTestPage.html

19 invitations to careers.stackoverflow.com giveaway

Maybe http://careers.stackoverflow.com will be useful for someone, so I have 19 invitations that I don’t need.

You can post your email in comments bellow or send me a request to my email vortexwolf@gmail.com and I will send you an invitation to this website.

invitations carreer stackexchange

It could be better to create a shareable link, but I would rather send invitations in person.

The proposal remains valid as long as you see this post. If I don’t have invitations, I will delete the post.

Windows Phone Marketplace app submitting

In this article I will show how the windows phone marketplace looks and how to publish apps there.

When you click the Submit App link, you will see the following page:
mainpage

Read more of this post

Windows Phone display images from URL

The built-in Image element is quite good for loading and displaying images from the web, because it loads them asynchronously in the background thread and doesn’t freeze UI.

In this example I will show how to display a loading indicator while the image is loading and an error message if the image loading has failed.

wp7_imageloading_loadingviewwp7_imageloading_imageview

You shouldn’t use the Source property in the XAML markup, instead you should set the Source property in the code-behind.

The XAML markup looks so:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <TextBlock x:Name="loadingView" Visibility="Collapsed" Text="Loading..." VerticalAlignment="Center" HorizontalAlignment="Center" />
    <TextBlock x:Name="errorView" Visibility="Collapsed" VerticalAlignment="Center" HorizontalAlignment="Center" />
    <Image x:Name="imageView" Visibility="Collapsed" />
</Grid>

The code-behind:

public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();

        var bitmap = new BitmapImage(new Uri("http://upload.wikimedia.org/wikipedia/commons/6/63/Wikipedia-logo.png"));
        bitmap.ImageFailed += (s, e) => this.ShowError("Error while loading the image.");
        bitmap.ImageOpened += (s, e) => this.ShowImage();

        this.ShowLoading();
        this.imageView.Source = bitmap;
    }

    private void ShowLoading()
    {
        this.loadingView.Visibility = Visibility.Visible;
        this.imageView.Visibility = Visibility.Collapsed;
        this.errorView.Visibility = Visibility.Collapsed;
    }

    private void ShowError(string message)
    {
        this.loadingView.Visibility = Visibility.Collapsed;
        this.imageView.Visibility = Visibility.Collapsed;
        this.errorView.Visibility = Visibility.Visible;

        this.errorView.Text = message;
    }

    private void ShowImage()
    {
        this.loadingView.Visibility = Visibility.Collapsed;
        this.imageView.Visibility = Visibility.Visible;
        this.errorView.Visibility = Visibility.Collapsed;
    }
}

At first I create the BitmapImage instance, after the creation of this object I subscribe to its events ImageFailed and ImageOpened. Then I display the loading indicator (the ShowLoading method). And as soon as the line ‘this.imageView.Source = bitmap’ is called, the image loading process starts. After some time either ShowError or ShowImage will be called.

The sample application you can download here: https://dl.dropbox.com/u/8047386/WordPress/PhoneImageLoadingSample.zip

My Windows Phone open source application

Though I know Windows Phone development in theory, I haven’t ever developed applications for this platform. That’s why I decided to create one application for one web site which provides json api. The site is an imageboard like 4chan, i.e all topics and messages are anonymous and you can attach images to your messages.

The source code is situated on my github account. I’ve already created an Android application for this web site and published it on Google Play, so it wasn’t so difficult to reimplement the application for Windows Phone. It is definitely much easier than to develop it from scratch.

The Windows Phone project is situated here.

So far the application looks like this:

wp1wp2wp3

At the moment the application has the following functionality:
1. Downloads and parses JSON files.
2. Displays the loading indicator during loading, displays the error message if an error has occured.
3. Loads and displays list images (thumbnails) asyncronously.
4. Opens full images in the WebBrowser.
5. Converts HTML posts to RichTextBox controls (the parser isn’t ideal, but it works at least for this website).
6. Makes HTTP POST requests.

By the way, the application is already published in the marketplace and available here: http://www.windowsphone.com/en-us/store/app/2ch-browser/3f63fa2c-4b35-4b8a-b3c0-51b54b460d70

The certification process was without problems, but I had to wait 5 days.

Displaying progress bar while loading JSON from Web Services for Windows Phone 7

In one of my previous posts I explained how to download and parse JSON response from web services. I used a simple text to show that the content is loading, but it isn’t convenient because you don’t know how long it remains to wait. In this post I will add the ProgressBar control to the project which will constantly display the number of downloaded bytes in per cents.
Here is how it looks:
wp7_json_loading

At first, I added some code to the XAML view so that it displays the ProgressBar and its description:

<StackPanel Visibility="{Binding IsLoading, Converter={StaticResource BooleanToVisibilityConverter}}"
            VerticalAlignment="Center">
    <TextBlock Text="{Binding ProgressDescription}" HorizontalAlignment="Center" Style="{StaticResource PhoneTextNormalStyle}" />
    <ProgressBar Value="{Binding ProgressValue}" Maximum="1" IsIndeterminate="False" Height="50" />
</StackPanel>

After that I’ve tried to find some event of the HttpWebRequest class which can report progress, but I haven’t found it, so I implemented my own ProgressStream class which looks like a common stream but has the OnProgressChanged callback.

public class ProgressStream : Stream
{
    private readonly Stream _stream;
    private long _length;

    public ProgressStream(Stream stream, long length)
    {
        this._stream = stream;
        this._length = length;
    }

    public override bool CanRead
    {
        get { return this._stream.CanRead; }
    }

    public override bool CanSeek
    {
        get { return this._stream.CanSeek; }
    }

    public override bool CanWrite
    {
        get { return this._stream.CanWrite; }
    }

    public override void Flush()
    {
        this._stream.Flush();
    }

    public override long Length
    {
        get { return this._length; }
    }

    public override long Position
    {
        get
        {
            return this._stream.Position;
        }
        set
        {
            this._stream.Position = value;
        }
    }

    public override int Read(byte[] buffer, int offset, int count)
    {
        int readCount = this._stream.Read(buffer, offset, count);
        this.ReportProgress();

        return readCount;
    }

    public override long Seek(long offset, SeekOrigin origin)
    {
        long seekCount = this._stream.Seek(offset, origin);
        this.ReportProgress();

        return seekCount;
    }

    public override void SetLength(long value)
    {
        this._length = value;
    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        this._stream.Write(buffer, offset, count);
        this.ReportProgress();
    }

    public Action<double> OnProgressChanged { get; set; }

    private void ReportProgress()
    {
        if (this.OnProgressChanged != null)
        {
            var percent = this.Position / (double)this.Length;
            // System.Threading.Thread.Sleep(500); // for test purposes
            this.OnProgressChanged(percent);
        }
    }
}

After that I changed the HttpGetTask class so that it uses the new ProgressStream class if it is possible. It is necessary to check the presence of the Content-Length header, because without this header and with unknown length it is impossible to calculate the progress.

public class HttpGetTask<T>
{
    //...
    
    private void OnGetResponseCompleted(IAsyncResult ar)
    {
        //...
        
        Stream stream;
        if (this.OnProgressChanged != null && response.Headers.AllKeys.Any(key => key == "Content-Length"))
        {
            var progressStream = new ProgressStream(response.GetResponseStream(), response.ContentLength);
            progressStream.OnProgressChanged = v => this.InvokeInUiThread(() => this.OnProgressChanged(v));
            stream = progressStream;
        }
        else
        {
            stream = response.GetResponseStream();
        }

        //...
    }

    //...
    
    public Action<double> OnProgressChanged { get; set; }
}

Then you should update the view model. I added the OnProgressChanged method which updates the ProgressDescription and ProgressValue properties.
Also I changed the url of the sample data, because the website geonames.org which I used earlier doesn’t send the Content-Length header (it sends the Transfer-Encoding header with value ‘chunked’ and unknown length), so I downloaded a JSON response and uploaded it on my dropbox account here.
The ViewModel looks so:

public class MainViewModel : INotifyPropertyChanged
{
    public MainViewModel()
    {
        Cities = new ObservableCollection<CityViewModel>();

        string url = "https://dl.dropbox.com/u/8047386/WordPress/testcities.json";
        
        var task = new HttpGetTask<CitiesList>(url, this.OnPostExecute);
        task.OnPreExecute = this.OnPreExecute;
        task.OnError = this.OnError;
        task.OnProgressChanged = this.OnProgressChanged;

        task.Execute();
    }
    
    //...

    private void OnProgressChanged(double value)
    {
        this.ProgressValue = value;
        this.ProgressDescription = string.Format("Loading {0:F0}%", value * 100);
    }

    //...
        
    private double _progressValue;

    public double ProgressValue
    {
        get { return _progressValue; }
        set
        {
            _progressValue = value;
            RaisePropertyChanged("ProgressValue");
        }
    }

    private string _progressDescription;

    public string ProgressDescription
    {
        get { return _progressDescription; }
        set
        {
            _progressDescription = value;
            RaisePropertyChanged("ProgressDescription");
        }
    }
}

Though the loading indicator is difficult to reproduce on the Windows Phone Emulator because it downloads the file very fast, it will be certainly displayed if the phone has a slow internet connection.
I didn’t add all code to the post, but as usual you can download the full project here:
PhoneJsonProgressBar.zip

Windows 8 calendar control

As far as I see, lot of people search how to add the calendar or datepicker control to their windows 8 applications. Though there is a control which is called WinJS.UI.DatePicker, it is actually not a date picker, it is just 3 comboboxes in one row. But because of the fact that Windows Store apps can be written by using HTML, CSS and Javascript, you can use any HTML controls which was designed for web sites in the internet. Here is a link to a short review of 21 free HTML datepickers.

In this post I will show how to use the most popular JQuery UI Datepicker. You should build your Windows Store app by using Javascript, because for obvious reasons it won’t work with XAML and C# (though you can try to use this control for C# apps, but I’m not sure that it will work).
Here is the screenshot of the app running on the simulator:

win8-calendar

At first, it is necessary to download 3 files. Though it is possible for internet web sites to refer to javascript libraries without downloading them, windows store applications can’t do this, they can use only offline javascript files.
1. jQuery 1.8.3 (the latest stable version at the moment of writing this post, but you can use any other version)
2. jQuery UI
3. jQuery UI style sheet

The first thing that you should do is to modify the jQuery 1.8.3 library. You should add 1 line at the beginning of the file and 1 line at the end:

MSApp.execUnsafeLocalFunction(function () {
// the original file
});

Like this:

win8-jquery-modified

Then add these 3 files to appropriate folders of the project:

winstore_datepicker_sample_solution_explorer

Add links to these files to the head section and add an input element with javascript code to the body section. The whole file looks so:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>DatePicker Sample</title>

    <link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
    <script src="//Microsoft.WinJS.1.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
    
    <script src="/js/jquery-1.8.3.js"></script>
    <script src="/js/jquery-ui.js"></script>
    <link href="/css/jquery-ui.css" rel="stylesheet" />

<!-- These links are not necessary in my application, but they can be useful in other applications -->
<!--<link href="/css/default.css" rel="stylesheet" />
    <script src="/js/default.js"></script>-->
</head>
<body>
    <h1>DatePicker Sample</h1>
    <p>Date: <input type="text" id="datepicker" /></p>

    <script type="text/javascript">
        $("#datepicker").datepicker();
    </script>
</body>
</html>

The source code of the sample application: WinStoreDatepickerSample.zip

Follow

Get every new post delivered to your Inbox.