Corrado's Blog 2.0

Online thoughts of a technology funatic

Windows 8: Is app running inside Visual Studio?

Sometimes you need to run some additional debugging code when your app is launched from a development environment (e.g from Visual Studio), of course there are compiler directives for this but I’ve found a property inside WinRT that can make this even easier.

bool isInsideVs = Windows.ApplicationModel.Package.Current.IsDevelopmentMode;

please note that property indicates Development mode, this means that it will probably check whether app is running from \Program Files\WindowsApps folder so if you launch the just compiled app from Start menu on same machine it will still returns true.

Try to sideload the app and in this case it will have the value false.

 

The tale of a GridViewItem customization

Once upon a time, in a galaxy not so far away, there was a guy (me Smile) who was working on a Windows Store 8.1 application and was asked to create a GridView whose items should look like this picture:

image

The guy (again, me) thought: What’s the problem, did it many times! and he started setting a data source:

public class Item
    {
        public string Text { get; set; }
    }

    public class DemoViewModel
    {
        public DemoViewModel()
        {
            this.Items = new List<Item>();
            for (int i = 0; i < 10; i++)
            {
                this.Items.Add(new Item() { Text = "Item " + i });
            }
        }

        public IList<Item> Items { get; set; }
    }

He then added a GridView to a page, bound the data source and created a simple ItemTemplate:

<Page x:Class="GridViewDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:GridViewDemo"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d">
    <Page.Resources>
        <local:DemoViewModel x:Key="vm"></local:DemoViewModel>
        <DataTemplate x:Key="MyItemTemplate">
            <Grid Width="100"
                  Height="60">
                <TextBlock HorizontalAlignment="Center"
                           TextWrapping="Wrap"
                           Text="{Binding Text}"
                           VerticalAlignment="Center" />
            </Grid>
        </DataTemplate>
        
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
          DataContext="{StaticResource vm}">
        <GridView ItemsSource="{Binding Items}"
                  ItemTemplate="{StaticResource MyItemTemplate}"
                   />
    </Grid>
</Page>

Run the solution and he got something quite close to what he was asked to realize:

image

Ok, just a couple of customizations and we’re done, he thought…

Let’s start with the selected background: The guy knows that background brush is managed inside ItemContainerStyle so he fired up Blend 2013, edited GridView’s ItemContainerStyle and here’s what he got:

image

Just a simple GridViewItemPresenter that has a series of Brush properties that give you the opportunity to customize several container aspects

image

In his case he needed to customize the color of SelectedBackground so, since it is bound to a resource named ListViewItemSelectedBackgroundThemeBrush he added a Brush resource with the same name inside Page resources and selected state was done, here’s updated result:

<SolidColorBrush x:Key="ListViewItemSelectedBackgroundThemeBrush"
                         Color="Orange"></SolidColorBrush>

image

But a question started to rise in his mind: “How to i set default (gray) background color?” there’s no Background color exposed by GridViewItemPresenter nor he can set it inside ItemTemplate otherwise it wouldn’t change when item is selected.

He tried lookind inside MSDN docs hoping to find a brush key that controls item default background but he had no luck Sad smile and navigated a lot the Internet until he realized he did something similar in the past for a Windows 8.0 application.

He then opened that old source code and discovered what has changed: The GridViewItemPresenter has been introduced in Windows 8.1, here’s how ItemContainerStyle looks in Windows 8.0:

image

Since you have access to all the elements composing the GridViewItem what the guy did was copying the style into Windows 8.1 app and edited VisualStateManager states (I’m sure, dear reader, you know how to do that…)

So, here’s final result:

image

The guy secretly told me that he wasn’t happy for such solution, probably GridViewItemPresenter has been introduced to improve GridView’s performances but he found no other easier way to solve the puzzle.

Based on a true story… Smile

PS: In case you need Windows 8.0 GridView’s ItemContainerStyle you can get it here.

Debug design time issues in Blend 2013

In 2010 (wow! that’s a long time ago…) I blogged about how to debug Blend design time exceptions, since then things have changed, Blend and Visual studio designer merged and so the XAML designer is now hosted in a separate process named XDesProc.exe (at least in Windows Store applications)

Laurent Bugnion has a detailed blog post about how to attach Visual Studio debugger to Blend to debug a Windows Store application at design time so i won’t repeat it here, the reason of this post is to integrate it with another step required when you use Visual Studio 2013 and Blend 2013.

Since with latest release PDB are no longer copied to cache location used by designer your simbols won’t be loaded and your attach procedure won’t work.

The solution is very easy, just point the debugger symbols to the proper PDB files of your application and everything will work as expected.

To point the PDBs just use: Tools –> Options-> Debugger

image

Then add the folder where your app’s PDB file resides.

Acronis True Image 2014 test drive

As a longtime Acronis user it just took me a second to accept the invite to test the 2014 release of True Image backup software.

For those who don’t know it True Image is a backup software solution that you can use to safely backup your files or entire partitions both locally or, with recent releases, also online using Acronis Cloud (5GB included with the product, other plans available)

While Windows includes it’s own backup solution, i can’t even compare it with the flexibility i get from True Image, using incremental backups i can backup my machine in about 5 minutes after initial full backup which takes indeed more than one hour (but i do it about every two months…)

I have lost the count of how many times this software saved my day, last was about two months ago, and each time i do some “risky” installation, a quick backup with True Image is the rule now, consider me “over conservative” but wasting time re-installing stuff because of a failure its something i hate doing and believe me or not, i rarely repave my machine.

About my experience with True Image 2014: I was running 2013 version and I run the setup without removing the previous version, setup properly took care of update without any problem, old backups configuration have been maintained and i backed up my machine in quite about the same “canonical” 5/8 minutes. Just to test compatibility i tried to open previous backups from True Image 2014 and everything went smooth.

Each time i install a new version i always update the USB key i use to boot my machine in case of a full restore, just in case.

Apart some UI changes which tend to keep the program “as easy as possible” relegating advanced features as “options”

image

i haven’t seen big differences compared to 2013 version, probably new features are on Cloud backup that i don’t use due to my poor upload bandwidth that it will take me days to backup and entire partition online.

I’ll keep using version 2014 in forthcoming months as my backup solution and rest assured I’ll keep you informed if something fails (which i really hope won’t happen and I have no reason to think it should indeed…)

Did i ever said that i also clone my machine into VHDs that i can later boot each time i need to install alpha/beta or stuff that will deliberately compromise your Windows installation using Backup Conversion tool? (love it!)

image

If you’re looking for a compete backup solution that’s fast, realiable and (why not?) cheap I always recommend, and I’ll keep recommending, Acronis product. I know that there are many alternatives out there but when i was in pain with a non booting machine, Acronis always saved me, and that’s what I finally need from a software like that.

Blend can’t locate types in external assemblies

While developing a Windows Store app I run into a Blend issue that caused me some headache.

I tend to define common converters in external assemblies in order to reuse them in other projects, so i added a reference to a Windows Store library project containing the converters I needed then swiched to Blend to use them from Create DataBinding dialog, and here’s what i got:

image

Problem: My library was not listed.

Really weird since here’s what I got doing the same from Visual Studio 2012

image

My MvvmHelper library is listed. Confused smile

Using Visual Studio to add the assembly resulted in following Blend error:

image

Ok, i presume you probably want to know the reason (and how to fix it): The problem was caused by projects having different build configurations: that main project has a X86 configuration (required by Bing Maps component) while all referenced libraries where AnyCPU and looks like that Blend 2012 doesn’t like it.

Moving the entire solution to X86 solved the issue.

Blend team is working on having it fixed before Blend 2013 release.

Happy Blending!

Note: Many thanks to @unni for helping me on this.

Typescript Succinctly book review

Javascript has a sort of love-hate relationship with developers, everyone use it but no one, or I’d better say, “a few”, really love it.

Reason of this, comes from the fact that is a ‘scripting’ language, thus incomplete when compared with other languages like C# (no complete support for OOP concepts, partial type system) and from a characteritic tha represents one of its strength: being a dynamic language thus not allowing development tools like Visual Studio to provide compile time checking and full intellisense support (while getting better with each release)

You can imagine how happy I was when i first knew that Microsoft was working on fixing these language “weakness” with a new superset language called TypeScript that, not only add constructs like Class, Modules, Types with compile time checking but it also made it 100% compatible with existing Javascript using a process known as “Transpiling” a sort of code transformation, this means that what you get at the end is pure Javascript.

TypeScript-Succinctly

While C# is still my primary language I was really curious since it could alleviate my pain when moving from C# to Javascript programming, that’s why during the weekend I enjoyed reading “Typescript Succinctly” by Steve Fenton, a 82 page long Ebook part of a larger family of free ebooks that Syncfusion published online.

The book doesn’t pretend to make you a TypeScript guru but its a great introduction if you want seriously mastering it, it starts from what happens under the hood: how code is transformed into pure ECMASCRIPT compatible javascript and vice versa to how to start writing some code in Visual Studio after installing the required extension.

Chapter 3 is dedicate to language core concept like Types, Modules, Interfaces, Classes and so on while next introduces more advanced concepts like Module organization, scope, inheritance etc.

Following chapter goes more practical describing how to interact with existing Javascript code and how to apply Uniit tests to TypeScript projects.

Recent Generics addition is not covered, probably because book went out before TypeScript team released them.

I really enjoyed this ebook, reading goes fast and smooth and it uses a pratical approach, something not always true in language related books,  i got what expected: a broader view of what TypeScript is and how to begin using it.

Get the book for free here: TypeScript Succinctly or get browse the entire library here.

The remote procedure call failed. Exception from HRESULT: 0x800706BE issue in Windows Store apps

There are days where technology seems to be against you, yesterday was one of those.

It all started in the morning when I inadvertently pressed the sleep button on my Logitec keyboard and my notebook gone into sleep mode, something i do often indeed, but this time it was different because at resume all i got was a black screen. Since this happened a couple of times in the past I switched it off hoping to solve it soon, but after machine boot the black screen was still there. A voice inside of me started saying “is gonna be a hard day…”, so i started, without much faith honestly the: boot, safe mode, repair, try restore point ritual but, as always happened in my personal experience, without luck.

Since I really hate repaving my work machine, I’m a bit paranoid with backups: I do backup at least once/twice a week and before any important update. so I inserted the USB recovery key of my favorite’s backup tool: Acronis True Image and started a sector-by-sector restore of July 28th backup.

After a while my notebook was brought back to life, and nobody will ever know what happened on this bright July 30th morning, but who cares, it’s time to go back coding…

Since I’m working on a Windows Store app that interacts with Facebook I started digging into Facebook SDK documentation and in short time I wrote a test app that logins and retrieves user profile.

Time to test the code: I lanched the app, the login dialog appeared and successfully logged in, but, wait, there’s a an issue: the breakpoint I added to read the returned token didn’t fired and application seems never returning from Login method.

Ok, let’s find what’s wrong but starting from Facebook developer registration down to code everything looks fine.

Let’s try an old sample I wrote in the past I know was ok: same problem.

Let’s use WebAuthenticationBroker sample from Developer portal, it must work!: well it wasn’t.

Since I lost any idea I asked my friend @CristianCivera some hints and you can image my face when after some pair debugging he told me: “Know what? the sample works on my machine

Below my face as soon as I read the message:

Also my friend @imperugo confirmed: The only machine on earth where the WebAuthenticationBroker.AuthenicateAsync() method was not returning was mine…

Just to be 100% sure I started a remote debugging session with my tablet and everything was working as expected.

I started to getting nervous since I had no idead why that call wasn’t working on my PC.

While trying to find a solution i thought: And if problem isn’t in just WebAuthenticationBroker but in all async methods? So I opened the FilePicker example from Windows Store dev portal, launched it and put a breakpoint on yellow line:

image

Result: I can select the file, breakpoint doesn’t fire anyway,  but now Visual Studio reports an exception:

The remote procedure call failed. (Exception from HRESULT: 0x800706BE)"}

a search on Interned pointed me to several possible solutions but none was the right one, looks like async call for unknown reason never returns, even launching the standalone app..

I started realizing that can’t work on any Windows Store app until I get this fixed and wondered: Why didn’t got into this before?, I spend the day between async/await and breapoints always worked.

Tried another Windows Store app that uses async/await and breakpoints worked, so why some async calls raise the exception and others don’t?

After long thinking I realized that both OpenPicker.PickSingleFileAsync() and WebAuthenticationBroker.LoginAsync() deal with UI, former opens file selection while latter displays a dialog, so I started thinking about graphic drivers (don’t ask me why, maybe someone took pity on me…) so I updated my NVidia driver and restarted.

No way, problem still there…

Before starting to tear my hair (and remind me that I do not have…) i remembered that I also have a USB video driver that controls my 3rd monitor: A quick check and saw that it driver was outdated, so i installed the recent one. Rebooted the machine launched the sample and…

YESSSSSS!!! The problem gone! probably something in the driver was conflicting with WinRT causing the exception thus preventing the call to return.

To recap this long post: If your async calls seems not to return and you get weird: The remote procedure call failed. (Exception from HRESULT: 0x800706BE)" message: check your video drivers.

If all this sound unbeliveable, you’re right, IT IS! (while true…)

Hope this will save you working hours (and hairs) in future.

Exception deriving from WebClient on Windows Phone 7.5

I was working on a Windows Phone 7.5 app that requires to use WebClient class to post a HEAD request to the server, since WebClient doesn’t support it, i used the trick to derive from WebClient and override the GetWebRequest method.

public class WebClientEx : WebClient
        {            
            public WebClientEx()
            {
            }
            
            public string Method
            {
                get;
                set;
            }

            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest webRequest = base.GetWebRequest(address);

                if (!string.IsNullOrEmpty(Method))
                    webRequest.Method = Method;

                return webRequest;
            }
        }

i then used the new class this way:

WebClientEx client = new WebClientEx() { Method = "HEAD" };
client.DownloadStringCompleted += (s, e) => ...
client.DownloadStringAsync(new Uri(uri, UriKind.Absolute));

Nothing new indeed, so what is the reason of this post? the fact that everything was fine in Windows Phone 8 but it was failing with a “inheritance security rules violated by type WebClientEx. Derived types must either  match the security accessibility of the base type or be less accessible.  If the base class has a non-transparent default constructor, the derived class must also have a default constructor, and the method inheritance rules apply across those two methods.”  when run on a Windows Phone 7.5 device.

A quick search and it looks like that the reason comes from a missing attribute applied to derived class constructor.

Adding a default constructor marked with SecuritySafeCritical attribute solved it (Phew!)

[System.Security.SecuritySafeCritical]
public WebClientEx()
{
}

MvvmStack for WinJS: Application Resuming support

I’ve checked in a new version of MvvmStack that has a small tweak and a “new” feature, let’s start with the latter:

Resuming support

Sometimes you need to be informed when app resumes, an example is because you want to download some fresh data if app has been suspended longer than a certain amount of time.

With MvvmStack all you need to do to is to add a onAppResuming method to your services and/or ViewModels, something like: (see sectionViewModel.js on sample code)

onAppResuming: function () {
            console.log("SectionViewModel notified that app has been resumed.")
        }

And it will be invoked each time app resumes.

The ‘tweak’ regards the way you add new  ViewModels, in this post, on Closing section i mention:

“3- Add a new property “pagenameViewModel” to ViewModelLocator’s  viewModels object“ 

starting from this version the step is no longer required Smile

MvvmStack for WinJS: Command support

A Command represents an abstraction over an action, the command can also indicate whether the action is available or not and, normally, UI elements tied to a command disables themselves when command is not available, if you’re new to MVVM’s commanding I recommend this article.

While more a .NET concept than a Mvvm pattern core feature, i decided to add support for it with latest checkin since its wide popularity and to keep the stack aligned with other .NET based libraries.

In  .NET a Command depends upon the ICommand interface and it is generally implemented by generic classes like RelayCommand or DelegateCommand, for MvvmStack I’ve used a simpler implementation available in relayCommand.js

(function (winjs) {
    "use strict";

    var RelayCommand = WinJS.Class.define(function(execute) {
        this.execute = execute;
        this.execute.supportedForProcessing = true;
        this.canExecute = winjs.Binding.as({value:true});
    },
        {
            execute: null,
            canExecute: null
        });

    winjs.Namespace.define("MvvmStack", {
        RelayCommand: RelayCommand
    });

})(WinJS)

To use it all you need is to expose instances of RelayCommand from your viewmodels, sample code exposes them in sectionViewModel.js

firstCommand: new mvvmStack.RelayCommand(function (element) {
            this.currentPage.value = 0;
            this.firstCommand.canExecute.value = false;
            this.lastCommand.canExecute.value = true;
        }),
        lastCommand: new mvvmStack.RelayCommand(function (element) {
            this.currentPage.value = this.images.length - 1;
            this.firstCommand.canExecute.value = true;
            this.lastCommand.canExecute.value = false;
        }),

then we wire the commands with application bar commands in section.html page

<div data-win-control="WinJS.UI.AppBar">
            <button
                data-win-control="WinJS.UI.AppBarCommand"
                data-win-bind="onclick:firstCommand Binding.Mode.command"
                data-win-options="{icon:'home', id:'', label:'Home', section:'global', type:'button'}">
            </button>
            <button
                data-win-control="WinJS.UI.AppBarCommand"
                data-win-bind="onclick:lastCommand Binding.Mode.command"
                data-win-options="{icon:'next', id:'', label:'Last', section:'global', type:'button'}">
            </button>
        </div>

In order to keep button state in sync with commands availability we use a new Binding.Mode.command initializer, also note how click event binds to command and not to its execute function.

As usual the binding initializer is defined inside binding-extensions.js, you can update it in case you need to handle other enable/disable scenarios.

Binding.Mode.command automatically adds a mvvm-disabled class to invoking element (app bar buttons in our case) so that you can use a css class to change the look of the control while in disabled state.

To see commands in action, run the sample, navigate to section page and click application bar’s buttons or navigate through images to see how buttons follow current’s image position.

Hope you like it Smile

PS: In order to simplify dev life I’ve added a watch function to viewModelBase that allows to invoke a function when an observable property changes (just a simple wrapper around bind function indeed Winking smile)

Older Posts »