Installing your app on your Windows RT device

Alright… so my app is almost finished and I want to install it for real on my Surface tablet. How do I do that? Is it possible?

Yes it is.

NB: People, seems like I was not entirely accurate. Before you can install the package this way, you need a developer license for your Win RT device. You can get one by installing the remote tools for VS2012 on your Surface (http://go.microsoft.com/?linkid=9810474) and remote debug at least one app you created yourself.

It involves 4 steps:

  1. Create the app packages
  2. Get files to your tablet
  3. Install the certificate included in the package on your tablet
  4. Install the app on your device

Create the app package

To do this you can navigate to Project > Store > Create App Packages…

You will be asked whether you have a Windows store account, just select ‘no’ and continue. Now you will be asked for the details of your package like the version and the architecture.

Modify as needed or just click ‘Create’. After that you will be shown a window with a link to the outputpath of the package and the possibility to start the Windows App Certification Kit. Klik on the first link to be taken to your package and then click ‘OK’.

You’ll find an .appxupload file and a folder with more files. The .appxupload file is just a zip (if you rename you can open it). The folder contain the interesting documents though…

Getting the files on your tablet

There is one awesome way to get the files on your tablet: SkyDrive! Of course mail, usb or similar will also work.

Move these files to your device: the .appx file and the certificate. Optionally you could include the .appxsym file to include the symbols. BTW both the appx and the appxsym files are zip files.

I placed the files in my SkyDrive and downloaded them to my desktop on my tablet.

Install the certificate on your tablet

When I open the certificate file on my tablet I get option to install the certificate. Now, you should install it to the local machine, make sure the certificate is installed in the ‘Trusted Root Certification Authorities’ store (NOT automatically selected).

Now this step is done… easy right?! On to the files stage: installing your app…

Install the app on your device

Open a powershell window in administrator mode. (Open start, search Powershell, select by dragging down, select ‘Run as Administrator’)

In the powershell console, navigate to the place where your application is. (Hint: ‘cd’ for change directory works fine…)

Now type ‘Add-‘ and tab to let powershell finish the command. It now says: Add-AppxPackage

Just specify the appx filename: Add-AppxPackage .<filename>.appx

Hit enter. The app should now install.

NB: People, seems like I was not entirely accurate. Before you can install the package this way, you need a developer license for your Win RT device. You can get one by installing the remote tools for VS2012 on your Surface (http://go.microsoft.com/?linkid=9810474) and remote debug at least one app you created yourself.

Happy coding! And running, I guess…

Windows 8 –Live tiles

My friend Pascal (http://www.pazquality.com/) is also working on a windows 8 application. He was having trouble with getting the Live tiles to work so I volunteered to find out how to cycle to a couple of tiles and keep cycling between them.

Well, it’s surprisingly simple… Here’s the code that I wrote in the constructor of the App:

//I installed the following nuget package: http://nuget.org/packages/NotificationsExtensions.WinRT


//This will give you access to the Templates without having to go through the xml…


//Add to Tiles


var x1 = TileContentFactory.CreateTileSquareText01();

x1.TextHeading.Text = “Text 1”;


var x2 = TileContentFactory.CreateTileSquareText01();

x2.TextHeading.Text = “Text 2”;


//Make ScheduledTileNotifications out of them with a due date of 10 and 20 seconds from now…


ScheduledTileNotification n1 = new
ScheduledTileNotification(

x1.GetXml(), new
DateTimeOffset(DateTime.Now.AddSeconds(10)));


ScheduledTileNotification n2 = new
ScheduledTileNotification(

x2.GetXml(), new
DateTimeOffset(DateTime.Now.AddSeconds(20)));


//Initialize the TileUpdater


var m = TileUpdateManager.CreateTileUpdaterForApplication();


//Enable Queuing (this is what makes it cycle….)

m.EnableNotificationQueue(true);


//Add the ScheduledTileNotifications to the schedule…

m.AddToSchedule(n1);

m.AddToSchedule(n2);

The tile is now cycling through these 2 notifications…

Happy coding, pazzie!

Windows 8 & Caliburn.Micro – Being a Sharing Target

I wanted to be able to add items to GetPocket.com via my app. To do this in the nicest way possible, it would be awesome to be able to share urls from other apps to my app.

I saw that you can add an OnShareTargetActivated method to your app.xaml.cs where you can capture the ShareOperation.

It looks like this:

protected
override
void OnShareTargetActivated(ShareTargetActivatedEventArgs args)

{

var op = args.ShareOperation;

}

Information how to implement Share Target Contract without Caliburn.Micro can be found at http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh871368.aspx

However… I want my Caliburn.Micro!

This question on Stack Overflow (the answer, that is) shows us the MarkerMetro WinRT example. But this is not our default Caliburn.Micro but a fork… I don’t want no forks, but the code showed me the way. This is how they did it:

protected
override
void OnShareTargetActivated(ShareTargetActivatedEventArgs args)

{

// Normally wouldn’t need to do this but need the container to be initialised

Initialise();

 

// replace the share operation in the container

container.UnregisterHandler(typeof(ShareOperation), null);

container.Instance(args.ShareOperation);

 

DisplayRootViewFor<ShareTargetViewModel>();

}

Basically the point is to unregister the already registered instance if the shareoperation and than register a new one… Unfortunately, the standard Caliburn.Micro doesn’t have the UnregisteredHandler method.

So I ended up creating a ShareContext class which has a ShareOperation property.:

public
class
ShareContext

{

public
ShareOperation Operation { get; set; }

}

This way I can register an instance of ShareContext in the Configure method and leave the Operation parameter null.

So here is my code:

protected
override
void OnShareTargetActivated(ShareTargetActivatedEventArgs args)

{

Initialise();

ShareContext c = container.GetInstance(typeof(ShareContext), null) as
ShareContext;

c.Operation = args.ShareOperation;

DisplayRootViewFor<AddByShareViewModel>();

}

Windows 8 – Using Caliburn.Micro

A collegue of mine followed this blogpost (http://www.jfarrell.net/2012/11/caliburn-from-windows-8-apps.html) to implement Caliburn.Micro in the WinRT app…

He stumbled upon a problem. The post seems to suggest that you should remove all content from your App.xaml, but then the reference to the resource common/standardstyles.xaml will be missing and the default item templates for pages are going to give you errors.

I followed this blogpost (http://mikaelkoskinen.net/caliburn-micro-for-winrt-getting-started) which prevented that issue… However, I still had a problem with getting a new Basic Page to use my ViewModel.

The problem was the line marked in yellow below:

<common:LayoutAwarePage

x:Name=”pageRoot”

x:Class=”InThePocket.BasicPage1″

DataContext=”{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}”

xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”

xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”

xmlns:local=”using:InThePocket”

xmlns:common=”using:InThePocket.Common”

xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″

xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

mc:Ignorable=”d”>


<common:LayoutAwarePage>


This line binds the page to a DefaultViewModel and thus overrides the binding that Caliburn.Micro creates.


Hope it will help you avoid or solve these problems…

Windows 8 – WebClient and the AppBar or flyouts

Here’s what I found out the hard way. If you show web content in a WebView control and you want to use the AppBar in the same page (overlapping the WebView) than the AppBar isn’t shown. This allegedly also happens to flyouts.

Very annoying. Apparently it has to do with the internal drawing logic of the WebView control. Luckily there is a way around it. As Alex Yakhnin’s blog (http://blogs.msdn.com/b/priozersk/archive/2012/08/13/how-to-display-charms-on-a-top-of-the-webview.aspx) suggests you can replace the current content of the WebView with the same content used as a brush on a rectangle and this works as a charm.

So here’s what I did:

private
void AppBar_Opened_1(object sender, object e)

{


WebViewBrush wvb = new
WebViewBrush();

wvb.SourceName = “contentView”;

wvb.SetSource(WebViewCtrl);

wvb.Redraw();

WebViewBrushRectangle.Fill = wvb;

WebViewCtrl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;


}


private
void AppBar_Closed_1(object sender, object e)

{

WebViewCtrl.Visibility = Windows.UI.Xaml.Visibility.Visible;

WebViewBrushRectangle.Fill = new
SolidColorBrush(Windows.UI.Colors.Transparent);


}


And the result is:

I’m back, starting a new blogging style

It’s been a while since I blogged. I have been busy with other stuff, but I’m back…

I am currently building a Windows 8 application for Pocket (http://www.getpocket .com). I want to share my experiences here. It won’t be a blog with long posts, but instead I will try and push small messages. They will be representations of my thoughts.They can vary in size.

So, without further ado… Let’s start…

(Super cool image copied from: http://inboundmarketing.kohfa.com/blog/bid/241680/Some-Thoughts-on-Website-Redesign)

Specification Pattern Continued

In a previous post, I talked about the specification pattern. In the last sentence I promised you to keep you posted on the next version of the implementation. I still owe you guys that result. So without further ado:

Download it here.

The implementation itself is pretty straightforward. The class has a protected property Predicate that takes in a Lambda expression that results in a boolean ( a predicate). It is protected so that you have to set the predicate in the derived class.

/// <summary>
/// Use the Specification to make some complex (business) logic explicit.
/// </summary>
/// <typeparam name="TEntity">The Type of entity that is the subject of the specification</typeparam>
public abstract class Specification<TEntity>
{

protected Func<TEntity, bool> evalCompiled;
protected Expression<Func<TEntity, bool>> evalExpression;

protected internal Expression<Func<TEntity, bool>> Predicate
{
get
{
return evalExpression;
}
set
{
evalExpression = value;
evalCompiled = evalExpression.Compile();
}
}

/// <summary>
/// Use this method to evaluate the predicate for a single item.
/// </summary>
/// <param name="item">The item to examine</param>
/// <returns>A boolean.</returns>
public bool IsSatisfiedBy(TEntity item)
{
return evalCompiled(item);
}

/// <summary>
/// Use this method to filter IQueryables using the Predicate
/// </summary>
/// <param name="candidates">The IQueryable that needs filtering</param>
/// <returns>An IQueryable that has the added filter</returns>
public IQueryable<TEntity> SatisfyingElementsFrom(IQueryable<TEntity> candidates)
{
return candidates.Where(evalExpression);
}
}

The usage is simple.

Suppose that there is a business rule that big orders need approval by a manager. Big orders are orders above a 1000 euros. There are 2 cases when we need to know whether an order is a big order. First, when the order is created so that we can send a request for approval to the manager and second in a managers app that shows all the big orders.

The class IsBigOrderSpecification is a business rule made explicit. This rule could be throughout your system. Here’s what it looks like:

class IsBigOrderSpecification : Specification<SalesOrderDetail>
{
public IsBigOrderSpecification()
{
Predicate = (o => o.LineTotal >= 1000);
}
}

When a new order is created we can now use this specification to enforce the business rule.

SalesOrderDetail orderLine = new SalesOrderDetail();
orderLine.LineTotal = 999;
bool isBigOrderLine = isBigOrderLineSpec.IsSatisfiedBy(orderLine);
if (isBigOrderLine)
{
Console.WriteLine("LineTotal {0} means this is a big orderline.", orderLine.LineTotal);
}
else
{
Console.WriteLine("LineTotal {0} means this is a not big orderline.", orderLine.LineTotal);
}

Yet the same specification can be used when querying for these big orders in the system. Because it works on IQueryable<SalesOrderDetail> we get all the advantages of deferred execution.

AdventureWorksEntities db = new AdventureWorksEntities();

var query = from so in db.SalesOrderDetails
select so;

var bigOrderLines = isBigOrderLineSpec.SatisfyingElementsFrom(query);

Console.WriteLine("{0} big OrderLines in database", bigOrderLines.Count());

 

Composite specification

In the solution you can also find the code to create composite specifications. Composite specifications are specifications that have been combined. What if we changed the business rule (the manager is getting to busy) to state that only big orders from sales people that have little experience have to be approved. Little experience has been qualified at working at the company less than 2 years. You probably get an IsExperiencedSalesPersonSpecification.

We are now able to combine the 2 specifications as follows:

bool needsApproval = isBigOrderLineSpec.And(new IsExperiencedSalesPersonSpecification().Not()).IsSatisfiedBy(orderLine);

 

My opinion is that this specification pattern is quite powerful in specifying and enforcing business rules in a distributed system.

Fixing a Branching Mess

At work we never really had a branching strategy. This resulted in a big branching mess. People were either not branching at all or were making it up as they went along.

Now we have chosen to follow guidance given at http://tfsbranchingguideiii.codeplex.com/. The Basic Branch Plan should work fine for us in most cases. This plan dictates that our branch hierarchy should look like this:

image

However, our branch hierarchy looked more like 2 separate trees or just a single column like this:

image

That’s not good.

I came across the option to reparent a branch from: http://social.msdn.microsoft.com/Forums/en/tfsversioncontrol/thread/70eb6d7d-ac81-4de0-a182-89993803b3de

However, when I tried this I saw that I could not select certain branches as a parent to other branches. The solution to this is the same as fixing branches after a migration. Do a baseless merge! This is nicely described in this post,  step 2:

http://www.richard-banks.org/2010/09/how-to-fix-branches-after-migration-to.html

 

And look at our branch hierarchy now:

image

Specification Pattern Implementation

For some time now I’ve been willing to find a good implementation of the Specification Pattern. Information about this pattern can be found here:

http://en.wikipedia.org/wiki/Specification_pattern

interface ISpecification<TEntity>
{
	bool IsSatisfiedBy(TEntity item);
}

The idea I had was to use the IQueryable of Linq to query over large collections of objects and get all the benefits of delayed execution.

Recently I came across a blog post by Dennis Doomen who  did exactly that. Read about it here:

http://www.dennisdoomen.net/2010/10/my-silverlight-4-reference-architecture_12.html

That implementation gives me:

public class ActiveRegistrationsSpecification
{
	public IQueryable<Registration> SatisfyingElementsFrom
	(IQueryable<registration> registrations)
	{
		return registrations
			.Where(r => r.Status != AgreementStatus.Incomplete);
	}
}

What I ultimately wanted was an implementation that has both capabilities, to evaluate a single item and to get all items from a collection.

Today I found a very old blog post of Nicholas Blumhardt that did that:

http://nblumhardt.com/archives/implementing-the-specification-pattern-via-linq/

public abstract class Specification<T>
{
	public bool IsSatisfiedBy(T item)
	{
		return SatisfyingElementsFrom(new[] { item }.AsQueryable()).Any();
	}

	public abstract IQueryable<T> SatisfyingElementsFrom
	(IQueryable<T> candidates);
}

However this implementation has a downside as Nicholas Blumhardt already states:

“Unknown performance ramifications of AsQueryable() under heavy usage”

And he is right. The AsQueryable() usage is very slow compared to the normal IsSatisfiedBy method.

My idea to improve this implementation was to make the both methods use a Predicate. Of course this wasn’t all that easy, but after some testing I ended up with this very useful implementation:

 

public abstract class Specification<TEntity>
{
	protected Func<TEntity, bool> evalCompiled;
	protected Expression<Func<TEntity, bool>> evalExpression;

	internal Expression<Func<TEntity, bool>> Predicate
	{
		get
		{
			return evalExpression;
		}
		set
		{
			evalExpression = value;
			evalCompiled = evalExpression.Compile();
		}
	}

	public bool IsSatisfiedBy(TEntity item)
	{
		return evalCompiled(item);
	}

	public IQueryable<TEntity> SatisfyingElementsFrom
	(IQueryable<TEntity> candidates)
	{
		return candidates.Where(evalExpression);
	}
}

Next on my wishlist is to get a CompositeSpecification so I can combine specifications with And and Or or Negate a specification. I will keep you posted.

Cannot resolve the collation conflict…

Ever tried to do a join on text columns? Like this:

SELECT * from LocationAustralie la 
left join steps s on la.StepText = s.Value 

If your tables have different collations you get the error message:

Msg 468, Level 16, State 9, Line 2: Cannot resolve the collation
conflict between "Latin1_General_CI_AS" and 
"SQL_Latin1_General_CP1_CI_AS" in the equal to operation.

 

Two of my colleagues had this problem in a single week and asked whether I had a solution. I have…

So here is the solution: the keyword COLLATE.

Just add the collate to one of the columns on the join

SELECT * from LocationAustralie la
left join steps s on la.StepText = s.Value collate Latin1_General_CI_AS

Happy Querying!