A memory profiler for Xamarin.Android

Here is a first ever snapshot of my home-grown memory profiler for Xamarin.Android.

While very spartan it does the core job – comparing two snapshots for objects with growing instances (aka memory leaks). An array of Autofac.Core.IRegistrationSource[] is showing its references (one root, one to a List<>).

There you. Interested?

PS. Sample features DevExpress WPF components, chiefly XpfGrid.

Running DevExtreme as MVC project in simulator

DevExtreme has a nice (web) simulator that lets you preview your application on a target device (tablet, phone, iOS, Android).

 

That’s really nice. However, out of the box, it works only when you have a special type of Visual Studio project that comes with DevExtreme (when you create a new DevExtreme project through one of its templates). Which might be a problem if you have other project type (i.e. MVC) instead – DevExtreme project is meant for distribution as a packaged “native” application. In that case no simulator for you, at least not out of the box.

Luckily here is a simple solution how to enable simulator for any web project. The mandatory step is to

  • find WebServer folder that is part of DevExtreme extension for Visual Studio. Mine is located in C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\Extensions\mblaqgom.mw5.
  • from WebServer folder found in step above copy simulator.html and Images and Simulator folders to root of your MVC project.
  • Do not copy web.config – it will wreck your application

That’s it. You can run your application by going to URL/simulator.html?appPage=index.html (assuming your starting page is index.html). Note that you can pass other parameters to simulator as well, like device=iPhone and orientation=p..

If you want to omit the appPage=index.html parameter you can rename index.html to app.html and simulator will pick app.html by default.

Incoming TypeScript definitions for PhoneJS and ChartJS (DevExtreme)

PhoneJS along with ChartJS are DevExpress’ efforts in providing single page web applications for mobile platforms (think Tablets and Phones).  Together they are combined into DevExtreme combo. In practice they are pure javascript libraries without ties to any server side platform - which is good, are built with KnockoutJS, jQuery in mind, etc (really plenty of nice features, check hyperlinks). And they can be packed into “native” applications for various platforms using PhoneGap. Added bonus is an emulator (again in javascript) that let’s your preview applications. Everything you need to run projects based on DevExtreme is a web server. Any web server on any OS since they are client side stuff.

I recently poked around this technologies and I soon felt that one, rather important feature (well, to me at least) was missing. Typescript definition files were missing. Until now that is. They are coming with v13.2 and you can already preview them in beta. Plus, there is a template that let’s you start your project with Typescript code instead of Javascript. While this doesn’t seem a big deal, well, it is. Typescript is a huge boost for javascript development, more so when it comes to bigger projects. Hence it is a big deal to be able to use all of Typescript goodies with DevExtreme goodies. And now I can.

Other improvements are coming as well (improved theming, improved and new widgets, localization…). While I can’t call myself experienced in DevExtreme it will be definitely my first choice for new projects.

An exotic DevEx’ ReportDesigner breaking change in 12.2

If you ever customized (excellent) DevExpress ReportDesigner you might have used this line of code to obtain a reference to IDataSourceCollectionProvider within ReportDesigner class which allows to access field list:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    designerHost.GetDesigner(designerHost.RootComponent) 
    as IDataSourceCollectionProvider;

This code worked well in 12.1 and perhaps in earlier 12.2 versions but it certainly won’t work in 12.2.5. The bad part is that it fails in runtime, while it still compiles perfectly. At least it fails consistently – always. The reason is that access to various services (IDataSourceCollectionProvider is one of them) is now through ReportDesigner.GetService(Type serviceType) method. Replacing the part above with the one below does the trick:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    (IDataSourceCollectionProvider)designerHost.GetService(
        typeof(IDataSourceCollectionProvider)
    );

The new is more readable and it could be even better if it used generics. I’d certainly consider this declaration instead:

T GetService<T>()
  where T: class
{
   ...
}

which would yield even more readable assignment:

IDataSourceCollectionProvider dataSourceCollectionProvider = 
    designerHost.GetService<IDataSourceCollectionProvider>();

There you have the fix.

FindViewById<> CodeRush template

Here is an useful CodeRush editor template if you work with Mono For Android.

FindViewById<«FieldStart»«Caret»«FieldEnd»>(Resource.Id.«FieldStart»«FieldEnd»);«Target()»

I use string fv as trigger. That makes binding variables/fields to Views a bit faster and with less typing.

Example, I’d type

someView = fv

then I’d press SPACE and I’d get an extended template

someView = FindViewById<|>(Resource.Id.|);|

Then I have to type just TextView, ENTER, someView, ENTER, ENTER and I’d get

someView = FindViewById<TextView>(Resource.Id.someView);| <- this is cursor

So instead of typing the whole enchillada I had to type only the letters in yellow.

someView = fvSPACEFindViewById<TextView>(Resource.Id.someView);

With Android these statements are quite common and thus the fv template spares me a lot of typing.

But hey it can get better. If stick to a naming convetion that variable name is the same as Id name + View suffix I can enhance the template, I will name it fvx.

«FieldStart(Name)»«Caret»«Link(viewName)»«BlockAnchor»«FieldEnd»View = FindViewById<«FieldStart»«FieldEnd»>(Resource.Id.«FieldStart»«Link(viewName)»«FieldEnd»);«Target()»

Note the «Link» directive that copies the typed text. And the typing result is

fvxSPACEsomeView = FindViewById<TextView>(Resource.Id.some);

Even better now, eh. The only further improvement is to deduce the variable type and type in TextView automatically. I have to investigate this option to refine the template even further.

You can use the two templates by simply creating them in CodeRush (DevExpress/Options/Editor/Selections/Templates) or you can import them (see attached file) into templates – right click in templates list and select Import Templates…

 

CSharp_Righthand_MonoForAndroid.xml (10.42 kb)

Slides (Slovene) from my “compiler as a service” talk at Bleeding Edge 2011

I have to say that I really liked this year’s Bleeding Edge event. It happens rarely that all the pieces fit together: weather was excellent, location was beautiful, I enjoyed my trip (part by train, part by bicycle), attendees were just great and my presentation was a nice interactive (with attendees) one – just as I like. I gave a ton of swag and shown how to enhance your development experience with extending/using CodeRush DXCore, PostSharp or just by using CSharpCompiler.

Hopefully the attendees did like the presentation as well.

Download the few slides below and see you at the next Bleeding Edge!

Prevajalnik kot storitev.ppt (586.50 kb)

My “compiler as a service” talk at Bleeding Edge 2011

Microsoft is working on compiler as a service codenamed Roslyn for Visual Studio 11 which is supposed to come sometime next year, I assume towards the end of the 2012. Not much is known and Roslyn might be less feature rich as one might expect. Microsoft announced at Build conference that they’ll release some Roslyn CTP bits in a few weeks time.

The good news is that you can already use compiler as a service today through tools such as CodeRush(commercial)/CodeRush Xpress(free), PostSharp(commerical) and custom coding. Even if some tools are commercial, they provide a tremendous value.

Anyway, after a sabbatical year, I’ll talk again at the Bleeding Edge. In fact I’ll be talking about how to leverage these tools and use compiler as a service for improving both design time coding and your applications in general.

But most importantly, I'll be giving a lot of swag away :-)

See you at Bleeding Edge - do stop by and say hi.

DevExpress’ FlowLayoutControl and MVVM

FlowLayoutControl unfortunately doesn’t support items binding. You can’t just provide a source and hope FlowLayoutControl will populate the content. But fear not, there is nothing attached properties can’t solve.

I’ve created an attached property ItemsSource that does all that for you. Here is its declaration:

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource", typeof(IEnumerable), typeof(FlowLayoutExtensions), 
            new UIPropertyMetadata(null, new PropertyChangedCallback(OnItemsSourceChanged)));

It accepts an IEnumerable as an input.

And here is the relevant code when ItemsSource changes:

private static void OnItemsSourceChanged(DependencyObject o, IEnumerable oldValue, IEnumerable newValue)
{    
    FlowLayoutControl layout = o as FlowLayoutControl;
    if (layout != null)
    {

        NotifyCollectionChangedEventHandler collectionChanged = delegate(object s, NotifyCollectionChangedEventArgs e)
        {
            switch (e.Action)
            {
                case NotifyCollectionChangedAction.Add:
                    AddItems(layout, e.NewItems);
                    break;
                case NotifyCollectionChangedAction.Remove:
                    RemoveItems(layout, e.OldItems);
                    break;
            }
        };

        // remove event implementation
        if (oldValue != null)
        {
            INotifyCollectionChanged oldIncc = oldValue as INotifyCollectionChanged;
            if (oldIncc != null)
                oldIncc.CollectionChanged -= collectionChanged;
        }
        layout.Children.Clear();

        if (newValue != null)
        {
            AddItems(layout, newValue);
            INotifyCollectionChanged incc = newValue as INotifyCollectionChanged;
            if (incc != null)
            {
                incc.CollectionChanged += collectionChanged;
            }
        }
    }
}

First it defines a delegate that gets called upon collection changes (when source is INotifyCollectionChanged) then it unsubscribes from CollectionChanged if it has previously subscribed. And finally it populates FlowLayoutControl with items and optionally subscribes to CollectionChanged event (when source supports it). Note that ObservableCollection<T> implements INotifyCollectionChanged.

Here is the code that adds or removes items:

private static void AddItems(FlowLayoutControl layout, IEnumerable source)
{
    foreach (object item in source)
    {
        GroupBox box = new GroupBox { DataContext = item };
        layout.Children.Add(box);
    }
}

private static void RemoveItems(FlowLayoutControl layout, IEnumerable source)
{
    foreach (object item in source)
    {
        GroupBox match = (from gb in layout.Children.OfType<GroupBox>()
                          where gb.DataContext == item
                          select gb).FirstOrDefault();
        if (match != null)
            layout.Children.Remove(match);
    }
}

Add items adds an GroupBox instance for each new item and sets its DataContext to the item. While RemoveItems searches for a matching GroupBox (based on DataContext match) instance and removes it from the FlowLayoutControl's Children collection.

A bit of XAML is required as well. I control the GroupBox appearance through a Style, like this:

<Style TargetType="dxlc:GroupBox">
    <Setter Property="MaximizeElementVisibility" Value="Visible"/>
    <Setter Property="MinimizeElementVisibility" Value="Visible"/>
    <Setter Property="Width" Value="150"/>
    <Setter Property="Header" Value="{Binding Caption}" />
    <Setter Property="Content" Value="{Binding}" />
</Style>

Note the binding of the Content property (remember, I am assigning current item as DataContext). And here is the FlowLayoutControl instance declaration:

<dxlc:FlowLayoutControl loc:FlowLayoutExtensions.ItemsSource="{Binding}" />

There you go, a MVVM friendly approach.

Note that this is not a fully featured code but it is a good starting point.

31.8.2011 - correct demo files

20.9.2011 - ufff, again uploaded really proper demo

FlowLayoutExtensionsDemo.zip (9.99 kb)

Automating the Righthand Dataset Visualizer build process and a refresh build

Since the last version released I become aware of an issue in the visualizer. If you were working on a project that referenced newer DevExpress assemblies the visualizer might have reported an exception due to the binary incompatibility with its references to the DevExpress assemblies - a assembly binding issue.

(If you want just the binaries you can skip to the end of the article and download them.)

The solution is to use a custom build of DevExpress assemblies. If you have their sources you can build your custom DevExpress assemblies using these useful scripts.

Then I have to use those custom built assemblies with my visualizer but I want to use them only for release build, not for debug. So I created a folder named CustomAssemblies under visualizer solution. I added a reference path to this folder to all of the visualizer projects. Which means that the MSBuild will use assemblies in this folder if they are present or ones from GAC (the original ones) if the folder is empty. Unfortunatelly the reference paths are global to the project and you can't have two different sets for two different configurations.

So the building of the release version looks like: populate CustomAssemblies folder with custom DevExpress assemblies, run MSBuild on Release configuration and at the end clear the CustomAssemblies folder so the debug version works with the original DevExpress assemblies. But there is one more obstacle. The license.licx file lists public key of the DevExpress assemblies and it doesn't match the one found in custom version. So I have to replace all occurences of the original public key with my custom version public key before the build and restore the originals after the build. Problems solved.

The actual release process involves also {SmartAssembly} which merges all assemblies into a single file and signing it with a certificate+timestamping and finally zipping the rather large result. Because I am not a masochist I decided to create a FinalBuilder project that does all of this automatically for me (except for building custom DevExpress assemblies).

Let me know if there are still problems!

Righthand.DebuggerVisualizer.Dataset.2008_v1.0.1.zip (12.67 mb)

Righthand.DebuggerVisualizer.Dataset.2010_v1.0.1.zip (12.67 mb)

Read more about Righthand DataSet Visualizer here.

Comparing heating costs using Silverlight

Out of curiosity I’ve decided to compare actual heating costs versus theoretical heating costs. The calculation shows how much it would cost If I used a modern conditioner instead of a centralized heating provided by city and fuelled by natural gas. Hence I crafted a simple Silverlight application using DevExpress Silverlight components (which helped a lot, but that’s another story).

The default data is my data for January but you can enter your own. While the application is in Slovene you can pretty much understand the huge difference just by looking at the chart below. So much for naively believing that heat provided directly by fire is the cheapest one.

Follow this link to the heating cost calculator