Playing transitions with WinJS and Expression Blend for HTML


Here’s a simple tutorial about using Expression Blend for HTML5 and some little Javascript to create a simple transition effect.

Fire up Expression Blend 5 and by double clicking the elements on Assets library add a button and a div, let’s rename it by double clicking them in LiveDOM pane.

Here’s live DOM contents and it’s HTML counterpart (I’ve manually added button Go! content)

image
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WinJSTransitions</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<!-- WinJSTransitions references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<button id="btn">Go!</button>
<div id="box"></div>
</body>
</html>



It’s time to make the box div look like a rectangle by applying a style: Select box element inside Live DOM and click on the little down arrow inside CSS Properties tab and by using CSS Properties tab let’s add some style properties.
On right you see the Css that Blend generated while playing with properties (approach is very similar to Blend for XAML BTW…)

image
#box {
border-radius: 20px;
width: 200px;
height: 200px;
background-color: #4292B0;
margin-top: 20px;
}

image

Actual preview output

Since I want to use transition for margin-left and opacity properties let’s use Blend capability for this:

image
#box {
border-radius: 20px;
width: 200px;
height: 200px;
background-color: #4292B0;
margin-top: 20px;
-ms-transition-property: margin-left, opacity;
-ms-transition-duration: 0.7s, 1.26s;
-ms-transition-timing-function: linear, linear;
}

As you see I’ve added the two properties inside Transition pane, set it’s duration by dragging the slider on right and set both to use linear easing, on right you can see how the css looks like now.

To trigger the transitions I’m going to dynamically add a class to box div, so let’s define them using Blend by first selecting the default.css file inside Styles tab then clicking on “+” button to create two class definition named “in” and “out” (see below)

image

Now, with “in” class selected let change the value of opacity and margin-left to 1 and 0px respectively then select “out” class and change same properties to 0 and 300px, the related css entries should now look:

.in {
opacity: 1;
margin-left: 0px;
}

.out {
margin-left: 300px;
opacity: 0;
}

Let’s add the “in” class to our div by selecting it and typing “in” inside Attributes pane (manually editing the HTML is probably easier in this case…)

image

It’s now time to write to code (or should I say script? Smile) right click the project inside Blend and select “Edit in Visual Studio” to open the project in Visual Studio 2011

image

Code should look very straightforward: we’re going to subscribe to click event to add and remove “in” and “out” classes to the div element.
Before typing any code is necessary to add a reference to ui.js file from our HTML page because is there that addClass and removeClass methods live.

(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);
var isVisible=true;
WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
document.getElementById("btn").addEventListener("click", function (e)
{
var box = document.getElementById("box");
var toAdd = isVisible ? "out" : "in";
var toRemove = isVisible ? "in" : "out";
WinJS.Utilities.removeClass(box, toRemove);
WinJS.Utilities.addClass(box, toAdd);
isVisible = !isVisible;
}, false);
}
}

WinJS.Application.start();
})();

Press F5 and you’ll see the rectangle moving and fading to the right and viceversa each time you click the button.

No rocket science here, but it works… Winking smile

Technorati Tags: ,

author: Corrado Cavalli | posted @ venerdì 3 febbraio 2012 19.30 | Feedback (1)

Using JQuery with WinJS


I can hardly imagine any serious web development without JQuery so I did  a quick test to check if it can be used inside a WinJS project and answer is: yes! even if not in its total completeness.
You can’t use any CDN to get JQuery library, it must be included in your project (quite obvious since application must load even without any network connection) so I’ve grabbed latest version and added it to my WinJS project

image

I then later created a very naïve HTML page:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WinJsJQuery</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
   1:  
   2:    <script src="/winjs/js/wwaapp.js">
   1: </script>
   2:    <!-- WinJsJQuery references -->
   3:    <link rel="stylesheet" href="/css/default.css" />
   4:    <script src="/js/default.js">
   1: </script>
   2:    <script src="lib/jquery-1.7.1.min.js" type="text/javascript">
</script>
</head>
<body>
<button id="loadButton">Load content</button>
<div id="host">
</div>
</body>
</html>

then fired some JQuery code:

WinJS.Application.onmainwindowactivated = function (e)
{
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch)
{
$("#loadButton").click(function (e)
{
$("<h3>Hello from JQuery</h3>").appendTo($("#host"));
});
}
}

WinJS.Application.start();

and everything works expected.

Tried then adding some dynamic content using JQuery’s load method:

$("#host").load("fragment.html");

but got a security exception (well, it make sense…)

image

Ok, what if content comes from an external site? something like:

$("#host").load("http://www.mysite.it/public/fragment.html", function (content, status, xhr){});
..

$.get("http://www.mysite.it/public/fragment.html", function (response){});

Well, none of the seems to work, load method returns a status=”error” while $.get simply doesn’t invokes callback function.

I finally ended up using WinJs.xhr method and it works:

WinJS.xhr({ url: "http://www.mysite.it/fragment.html" }).then(function (request)
{
$(request.responseText).appendTo($("#host"));
}, function (){});

Just some tests, nothing more (let’s not forget that it’s just a developer preview) but glad to see that JQuery’s power is available even in WinJS client application.

Technorati Tags: ,

author: Corrado Cavalli | posted @ martedì 31 gennaio 2012 19.20 | Feedback (13)

Debug a Windows Phone application invoked from a secondary tile


Adding a secondary tile that ‘deep links’ into your application is a trivial task and can be done in just a few lines of code…

private void button1_Click(object sender, RoutedEventArgs e)
{
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString() == "/Page2.xaml");
if (tile == null)
{
StandardTileData secondaryTile = new StandardTileData
{
Title = "My app",
BackgroundImage = new Uri("/ApplicationIcon.png", UriKind.Relative),
Count = 13,
BackTitle = "News",
BackBackgroundImage = null,
BackContent = "Something happened on the way to heaven..."
};

ShellTile.Create(new Uri("/Page2.xaml", UriKind.Relative), secondaryTile);
}
}

The problem now is: How can I debug my application when launched from a secondary tile since debugger gets detached once you click it?

The smarter solution I’ve seen is to temporarily add a background task, this way debugger remains attached and you can continue debugging as usual, here are the steps:

  • Add a new “Windows Phone Scheduled Task agent” project to your solution.
  • Add a reference to it from your main application (see below)

    image

That’s all: now you can launch your app, close it on emulator and see that it is still running and ready to trigger any breakpoint once you hit the secondary tile.

Hope it helps!

Technorati Tags: ,,

author: Corrado Cavalli | posted @ giovedì 24 novembre 2011 10.26 | Feedback (10)

WinRT Pills: Make your own Async methods


In WinRT any method that takes more than 50 ms is exposed as an asyncronous operation and thanks to C# await keyword (or Javascript’s Promises) what could be a programmer’s headache becomes a straightforward task, but what if you have your own asyncronous code?
Let’s say you have a basic downloader class that simulates downloading a string from the internet, in practice something like:

public class MyDownloader
{
public event EventHandler Completed;

public string Result { get; set; }

public void Download()
{
TimeSpan delay = TimeSpan.FromMilliseconds(1000);
var timer = ThreadPoolTimer.CreateTimer((tpt) =>
{
this.Result = DateTime.Now.Ticks.ToString();
this.Completed(this, EventArgs.Empty);
}
, delay);
}
}

this code simulates an asyncronous operation running on a secondary thread using WinRT’s ThreadPoolTimer that sets Result property to current ticks value and raises a Completed event.
To use it, the code required is:

private void Button_Click(object sender, RoutedEventArgs e)
{
MyDownloader downloader = new MyDownloader();
downloader.Completed += (s, a) =>
{
this.Dispatcher.Invoke(Windows.UI.Core.CoreDispatcherPriority.Normal, (t, o) => tb1.Text = downloader.Result,this,null);
};

downloader.Download();
}

We subscribe the event and when raised we use WinRT’s CoreDispatcher to mashal invocation back to UI thread (tb1 is a TextBlock element), no very ‘natural’ flow but that’s how we wrote code until now.
Let’s try to convert Download method to a WinRT’s  Async method adding a DownloadAsync method to MyDownloader class:
public Task<string> DownloadAsync()
{
TaskCompletionSource<string> taskCompletionSource = new TaskCompletionSource<string>();
this.Completed += (s, a) =>
{
taskCompletionSource.SetResult(this.Result); //SetException
};

this.Download();
return taskCompletionSource.Task;
}

Method is no longer void, but returns a Task<string> since we expect a string to be returned as operation result, we then invoke Download method as usual but when completed we ‘signal’ that operation has finished using SetResult (or SetException in case task failed and an exception need to be reported back to caller)
You might think: “Well’ not so easy either…”  but now let’s see the code required to get the same goal as before:

async private void Button_Click2(object sender, RoutedEventArgs e)
{
MyDownloader downloader = new MyDownloader();
tb1.Text= await downloader.DownloadAsync();
}

No more handlers, no more Dispatchers, just added async and await keywords and, more important, the code flow is absolutely linear even if execution continues to be asyncronous.
Lot easier isnt’ it?
 
Technorati Tags: ,,

author: Corrado Cavalli | posted @ martedì 25 ottobre 2011 9.16 | Feedback (0)

WinRT pills: Where is MessageBox?


As most developers, my first test with a new technology begins with the good old “Hello World” sample and the same happened when I started digging into Metro/WinRT SDK, and you can imagine my face when I discovered that MessageBox class is no longer there.
After a few second of panic :-) I placed a search on SDK and (relief) found that its indeed alive and kicking (even in a different form) inside Windows.UI.Popups namespace with a brand new name: MessageDialog

So I started writing my first WinRT MessageDialog using this code:

private  void OnMessage(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("Hello WinRT");
dialog.ShowAsync();
}

and nothing happened! :-O
The reason is evident from the Async term appended to Show method: In WinRT any method that takes more that 50 milliseconds to complete is exposed as an asyncronous operation, in .NET this means that ShowAsync return an awaitable operation that must be explicitly started.
Let’s try again opening a MessageDialog and trying executing some code after dialog closes, what we need to write is more or less something like:

private  void OnMessage(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("Hello WinRT");
MessageDialogAsyncOperation operation= dialog.ShowAsync();
operation.Completed = new AsyncOperationCompletedHandler<IUICommand>(this.OnDialogCompleted);
operation.Start();
}

private void OnDialogCompleted(IAsyncOperation<IUICommand> asyncInfo)
{
Debug.WriteLine("Dialog closed");
}

and finally yes! dialog is here:

image

but.. do I really need to write all this code to show a dialog and continuing doing something after user dismissed it? luckily no, thanks to C# 5.0 async and await keyworks previous code can be rewritten to:

private  async void OnMessage(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("Hello WinRT");
await dialog.ShowAsync();
Debug.WriteLine("Dialog closed");
}

far better now isn’t it? ;-) note the presence of async keywork on OnMessage signature and the use of await keyword before ShowAsync() invocation

Is this all about MessageDialog? no, you can add up to 3 custom buttons to the dialog adding UICommand instances to dialog’s Commands property, each UICommand together with the text to display has the callback to invoke when related button is pushed, we can obviously use the same handler and detect the operation to execute inspecting command’s Id property, here’s a sample:

private  async void OnMessage(object sender, RoutedEventArgs e)
{
MessageDialog dialog = new MessageDialog("Hello WinRT");
UICommandInvokedHandler cmdHandler = new UICommandInvokedHandler(cmd =>
{
Debug.WriteLine("id:{0} label:{1}", cmd.Id, cmd.Label);
});

UICommand cmd1 = new UICommand("Cmd1", cmdHandler, 1);
UICommand cmd2 = new UICommand("Cmd2", cmdHandler, 2);
UICommand cmd3 = new UICommand("Cmd3", (cmd) =>
{
Debug.WriteLine("Command3 done!");
}, 3);

dialog.Commands.Add(cmd1);
dialog.Commands.Add(cmd2);
dialog.Commands.Add(cmd3);
dialog.DefaultCommandIndex = 1;

await dialog.ShowAsync();
Debug.WriteLine("Dialog closed");
}

In this snippet, cmd1 and cmd2 share the same handler, while cmd3 has a dedicated one while dialogo’s default button is selected via DefaultCommandIndex property.

Very powerful and flexible, glad to have it in Metro development!

Technorati Tags: ,,

author: Corrado Cavalli | posted @ lunedì 17 ottobre 2011 0.28 | Feedback (0)

[WP7] Error 0x81030120 when deploying application to device


If you get error 0x81030120 when deploying an application to a Mango (7.5) device

image

If might depend on presence on ID_CAP_INTEROPSERVICES capabilities inside application manifest, remove it and problem should gone.

Technorati Tags:

author: Corrado Cavalli | posted @ martedì 4 ottobre 2011 11.17 | Feedback (6)

Enable Snap feature in Windows 8


Snap feature allows you to run two Metro apps side-by-side or share the classic desktop with a Metro App (see below)

image

In order to have this feature on machines with resolution lower than 1366x768 (my Iconia W500 has 1024x800) you must add an entry into registry:

  • Go to HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ImmersiveShell
  • Create a new Key named AppPositioner
  • Add into new key a DWORD value named AlwaysEnableLSSnapping with value 1.

image

Then restart your PC and drag a Metro application from left side of the desktop. ;-)

Technorati Tags: ,

author: Corrado Cavalli | posted @ domenica 2 ottobre 2011 19.45 | Feedback (3)

Debug your Metro apps remotely


I just bought a new Acer Iconia Tab W500 machine to use it for Metro applications development (found a really good deal on EBay :-) ), and immediately installed Windows 8 Developer Preview on it, everything works fine, machine is very responsive and touch experience makes Windows8 lovely than ever. The only thing not working is tablet rotation since still haven’t found a suitable x64 driver for internal Bosch G-Sensor (suggestions are warm welcomed!)

Next step is: How do I test my touch enabled applications?, well I have Visual Studio 2011 installed on Windows 8 but machine isn’t powerful enough for my needs, luckily you can have a Windows Phone development experience even with Metro Development.
Fire Up Visual Studio 2001, selects a new Metro Application choosing your favorite language, then go to Project properties and select Debug Tab:

image

On Target Device you can select among: Local Machine, Simulator and Remote, choosing Simulator Visual Studio reconnects to local machine and host it inside an emulator that resembles the Windows Phone 7’s one.

image

If you instead choose Remote machine, you can connect to a machine running the Visual Studio 20011 Remote debugger, that on developer preview installation it runs by default at startup and it is also automatically added to authorized apps inside Windows 8 firewall.

If you press the Find… button  you can select the remote machine from those found inside your network, but in order to have it listed it looks like the remote machine’s firewall has to be disabled, if you know machine name just type it inside remote machine textbox and no firewall intervention required.

Now add some breakpoints here and there, and press F5: After confirming remote debug connection on remote machine  (first time only) your app is automatically deployed, launched and can be remotely debugged  :-)

From my experience debugger is very fast and breakpoint hits very quickly but I did some tests on very simple apps.

image

Happy (remote) debugging!

author: Corrado Cavalli | posted @ lunedì 26 settembre 2011 11.15 | Feedback (13)

In case you Windows 8 installation on VHD fails…


…you’re not alone! :-)

I’ve successfully used Scott Hanselman’s method to install Windows 8 on a VHD and everything went quick and smooth, I can’t cold boot in 8 seconds but it’s probably due to the fact that the machine is quite older (but is perfect for fundamental developer tools like TweetDeck or Messenger) but today when I was sure that doing the same on my DELL Precision M4500 would be a kid game I didn’t notice that Murphy was sitting behind me and so a nasty problem raised: After file copy, at reboot, no boot option screen appeared (see below)

image

Tried nearly everything, even tried manually adding the BCD boot entry without success. Luckily I remembered that there’s an alternative way to install VHD, sort of OEM like mode consisting in a “sysprepped” installation (did that in the past) a quick search and finally see the light at this post and got my Win8 installation working on my main production machine (phew!)
I must thank @Mister_Goodcat for saving my day.

Just a note: If you don’t like using PowerShell script try this gui based alternative utility

Now is time to dig into WinRT seriously…

Technorati Tags:

author: Corrado Cavalli | posted @ giovedì 15 settembre 2011 22.13 | Feedback (0)

Build day1: Just some personal thoughts…


BUILD

Think you all have seen //Build conference keynote so you know what I’m talking about, here are some thinking on my mind after a day where #bldwin hash nearly crashed twitter (can’t barely seen tweets flowing on TweetDeck…)

  • As you (I assume) I’m in love with Windows 8, just prepared my machines to install the ready-to-come stuff that will take us (even more) busy for the next months :-)
  • HTML5/JS/CSS as expected is the newcomer  into client app development party, this will allow web dev to become windows devs (after they learned Microsoft stuff and tools of course)
  • Silverlight is alive and kicking as being part of WinRT, no more plug-in needed! this will probably put Silverlight 5 release in a corner, but let’s not forget that there are lots of Windows machines not running Win8 out there where Silverlight solution can perfectly fit.
  • WPF is… well, I' want to be optimistic, dead? apart Kinect is se no more reason to invest on it (considering Silverlight 5 new capabilities)
  • Those who believed in Metro have now their investment back.
  • UX is the word, wondering how many “drag&drop some grids, a bunch of buttons and a toolbar applications” will sell on Win8 marketplace.
  • Companies who invested money and energy in UX experience are now more happier than those who “reuse and recycle” was the only RD philosophy.
  • From what I saw the Win8 HTML5 apps won’t be very portable to other OS’es due to JS code very tied to the OS and some Microsoft specific css tags (opinion based of what I saw, I might be wrong on this)
  • Silverlight vs HTML5 battle: Think it depends on matter of competency and capabilities, no idea of what can/can’t be done on any technology, if they’re 100% similar maybe HTML5 has more points but, given missing portability to other OS, you as .NET developer would you exchange C# with Javascript? I love when I can choose…
  • I’ve seen (finally) a real ecosystem growing (expect XBOX and TV mentioned indeed…) the Phone vs Live vs Win8 is becoming a reality, this might be another point to consider when choosing a developing strategy.
  • Being Win8 more a “consumer” product, wondering how “business world” will react to it, would your company IT dept allow installation of Window8 in your locked down company machine and log in flicking fingers instead of company super-secure password? my feelings is that Microsoft realized that they can make more money from consumer than business companies sticking with their machines for years, but that’s just a another personal feeling.

I’m pretty excited about the new stuff, love the new tools  and really excited from what’s going on in California, all I need now is one of those beautiful toys attendees got today, anyone has a spare one? :-) (I promise I will pay for it)

That’s all for now, back to #bldwin stream…

Technorati Tags: ,,

author: Corrado Cavalli | posted @ martedì 13 settembre 2011 22.28 | Feedback (5)