WordPress database error: [INSERT, UPDATE command denied to user '51213-2'@'10.10.20.57' for table 'wp_options']
INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_doing_cron', '1714814659.2354660034179687500000', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)


Warning: Cannot modify header information - headers already sent by (output started at /home/lexiqued/www/WordPress/wp-includes/wp-db.php:1502) in /home/lexiqued/www/WordPress/wp-includes/feed-rss2.php on line 8
Windows8 – Jonathan ANTOINE's thoughts http://www.jonathanantoine.com Yet another blog about... Sat, 25 Jul 2015 10:12:26 +0000 en-US hourly 1 https://wordpress.org/?v=5.5.3 WinRT exceptions : how to know what the hexadecimal error code means http://www.jonathanantoine.com/2015/07/25/winrt-exceptions-how-to-know-what-the-hexadecimal-error-code-means/ http://www.jonathanantoine.com/2015/07/25/winrt-exceptions-how-to-know-what-the-hexadecimal-error-code-means/#comments Sat, 25 Jul 2015 10:11:08 +0000 http://www.jonathanantoine.com/?p=1542 When working with the WinRT SDK you somethimes get exceptions from it with only an hexadecimal code to help you understand what the error is. Often, when you look for it on Google/Bing, you end with no help and no way to fix the error. There is a way to know the associated error message !

I am talking about this kind of error messages : “Exception thrown at 0x77694598 (KernelBase.dll) in MonAppli.Windows.exe: 0x40080201: WinRT originate error (parameters: 0x80072F19, 0x00000067, 0x0519EE60).” I looked for every hexadecomal code without success.
Excception

To get the message associated with this error, follow this procedure :

  • Activat the native debugger : in the properties of your project, is at the end of the debug tab.
  • Launch your app with the debugger attached and produced the exception.
  • Copy the third hexadecimal code in the exception Windows (0x0519EE60 here).
  • Click on Break.
  • Open the “Memory 1” Windows. It’s only available in Debug mode in this menu : “Debug > Windows > Memory > Memory 1”
  • Paste the value in the adress text box and press the enter key
  • The description is available at the right 🙂

exception2

]]>
http://www.jonathanantoine.com/2015/07/25/winrt-exceptions-how-to-know-what-the-hexadecimal-error-code-means/feed/ 1
WinJS 2.0 / IE 11 : the new and shiny MutationObserver object http://www.jonathanantoine.com/2013/10/28/winjs-2-0-ie-11-the-new-and-shiny-mutationobserver-object/ http://www.jonathanantoine.com/2013/10/28/winjs-2-0-ie-11-the-new-and-shiny-mutationobserver-object/#comments Mon, 28 Oct 2013 06:56:15 +0000 http://www.jonathanantoine.com/?p=1511 Let me introduce you a new feature of Internet Explorer 11 which is available in your Windows 8.1 apps too : the MutationObserver. This object lets you observe the changes on any HTML element of your DOM.

You may already know these monitoring events available before and which are now no more supported :

  • DOMNodeInserted
  • DOMNodeRemoved
  • DOMSubtreeModified
  • DOMAttrModified
  • DOMCharacterDataModified

They have been replaced by the MutationObserver in IE 11 because they have several drawbacks:

  • They are standard JS events, so they bubble the whole DOM : bad for performance.
  • They may spam you because each change raise an event without batching : bad for performance.
  • They are synchronous and block your execution : bad for performance.
  • Did I tell you that there may be performance issues?

The MutationObserver fix these issues and is really easy to use :

  1. Create a mutation observer by giving a callback function as a parameter.
  2. Observe an element and specify “what to observe”
  3. Do something in the callback

Creating a mutation observer is easy as instantiating an object. The callback function takes 2 parameters : an object describing the change and the second one will be the MutationObserver.
[js]function mutationObserverCallBack(changes, mutationObserver) {/*…*/ }

//Creation of the observer
var observer = new MutationObserver(mutationObserverCallBack);[/js]

Then you can observe any html element by calling the observe function on the observer. This function takes as a second parameter a json object with the “monitoring” options. For example, you can monitor only the addition/removal of element on any of its children and any change of “class” :
[js]
var observer = new MutationObserver(mutationObserverCallBack);
observer.observe(element, {
attributes: true,
attributeFilter: ["class"],
childList: true,
subtree: true,
});
[/js]
There is a lot of possible configuration and you can find a full list on this MSDN page.

In the callback, you can explore the changes which is a list of the modifications. Each one has a type field and some properties (added nodes, old value, etc.) which let you know which change has been performed.
[js]function mutationObserverCallBack(changes, mutationObserver) {

changes.forEach(function (mutationRecord) {

console.log("Type of mutation: " + mutationRecord.type);

if ("attributes" === mutationRecord.type) {
console.log("Old attribute value: " + mutationRecord.oldValue);
}
});
}[/js]

changesMoniker

Additionnal links

This is a just a quick blog post of this good new API. You can find more information on these pages :

]]>
http://www.jonathanantoine.com/2013/10/28/winjs-2-0-ie-11-the-new-and-shiny-mutationobserver-object/feed/ 1
#WinRT : how to easily get the dominant color of a picture http://www.jonathanantoine.com/2013/07/16/winrt-how-to-easily-get-the-dominant-color-of-a-picture/ http://www.jonathanantoine.com/2013/07/16/winrt-how-to-easily-get-the-dominant-color-of-a-picture/#comments Tue, 16 Jul 2013 07:15:39 +0000 http://www.jonathanantoine.com/?p=1500 “Content before Chrome” is the Leitmotif of Windows Store Apps. You’ll usually end up using a lot of images in your app and getting the dominant color of a picture may actually be useful. My first attempt to achieve this was to get the bytes of the picture and calculate the average value. There is actually an easier and faster solution using the Windows Rutime API.

The GetPixelDataAsync method of the BitmapDecoder class lets you get the pixels of a given picture and you can apply transformations during the process. I will the simply ask it to resize the image to a simple unique pixel. The resulting pixel will be the dominant color of the image.

[csharp]
//get the file
var file = await StorageFile.GetFileFromApplicationUriAsync(myLocalImageUri);

using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
//Create a decoder for the image
var decoder = await BitmapDecoder.CreateAsync(stream);

//Create a transform to get a 1×1 image
var myTransform = new BitmapTransform { ScaledHeight = 1, ScaledWidth = 1 };

//Get the pixel provider
var pixels = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Ignore,
myTransform ,
ExifOrientationMode.IgnoreExifOrientation,
ColorManagementMode.DoNotColorManage);

//Get the bytes of the 1×1 scaled image
var bytes = pixels.DetachPixelData();

//read the color
var myDominantColor = Color.FromArgb(255, bytes[0], bytes[1], bytes[2]);
}

[/csharp]

The code is extremely simple: open the file, open its stream, create a BitmapDecoder, grab the pixels applying the transform and read the color.
dominant color

]]>
http://www.jonathanantoine.com/2013/07/16/winrt-how-to-easily-get-the-dominant-color-of-a-picture/feed/ 1
Windows 8.1 : let’s discover the Scheduler of #WinJS http://www.jonathanantoine.com/2013/07/02/windows-8-1-lets-discover-the-scheduler-of-winjs/ http://www.jonathanantoine.com/2013/07/02/windows-8-1-lets-discover-the-scheduler-of-winjs/#comments Tue, 02 Jul 2013 12:29:35 +0000 http://www.jonathanantoine.com/?p=1471 WinJSSchedulerWindows 8.1 comes with a new feature in the WinJS SDK : a scheduler. Let’s see what it is and how to use it!

In Windows 8, every job is nearly done as soon as you execute it. You could play with the msSetImmediate function but it was still a little mode “hack” than “code”.

With Windows 8.1, the SDK introduce a scheduler used by the whole WinJS framework. This scheduler helps you to define what is important (animations, visual feedback, manage user input) from what can be delayed (background work, data processing not used immediatly).

The goal is to let you build application which reacts immedialty to the user will.

What’s in it ?

Everything lives in the WinJS.Utilities.Scheduler namepsace and is written in javascript.
This namespace is often shortcuted “Scheduler” or “S” in the Microsoft samples.
[js]var S = WinJS.Utilities.Scheduler;[/js]

There is 4 importants objects to know :

  • WinJS.Utilities.Scheduler: the main namepsace with a lot of static function which lets you start and manage jobs
  • WinJS.Utilities.Scheduler.IJob : everything thing is a job. When you start a task/work using the scheduler, it returns you an IJob object on which you can call management methods.
  • WinJS.Utilities.Scheduler.IJobInfo : information passed to your work-function when executed.
  • WinJS.Utilities.Scheduler.IOwnerToken : you want to be the owner of a task and manage a group of jobs then use this.

How to use it (101) ?

Launching a job is as simple as providing a function :
[js]
var job = WinJS.Utilities.Scheduler.schedule(function willBeExecuted(){

//work to be done
});
[/js]

There is some optional parameters that can be set too : a priority (default is WinJS.Utilities.Scheduler.Priority.normal.), a this parameter which will be set when the function is executed and name (useful when debugging):
[js]
var whoAmI = {};
var job = WinJS.Utilities.Scheduler.schedule(function willBeExecuted(){

//work to be done
} , WinJS.Utilities.Scheduler.Priority.normal, whoAmI, " I am the job name" );
[/js]

The returned object is a IJob object and you can call some function on it to cancel it’s scheduling, pause it, resume it and have some information like the name, the priority, the owner, etc.
[js]
//create a job
var job = WinJS.Utilities.Scheduler.schedule( /* …*/);
//pause the job
job.pause();

//resume it in 5 secs
WinJS.Promise.timeout(5000).then(job.resume);

//reads the name of the job
var name = job.name;
[/js]

IJobInfo and yielding

In this case “yielding” means “let other task more important than me start and do their job while I am executing and pause me”.
Let’s assume that you have a job which takes 10 seconds to be done and that you can split it in 10 parts.
Then you can launch the job with the scheduler, do the first part and tells it : do something else (other jobs with higher priority) if necessary then call me back. The Scheduler will then manage this process for you.

When your job is executed, a parameter is actually provided and it implements the IJobInfo interface. This jobInfo object has 2 important functions and 1 important field :

  • setPromise: calling it providing a function tells the scheduler to wait for this promise before to call you back. If you need to download locally an internet resource, the Scheduler does not need to call you before and you can set a promise to wait for the download to be done.
  • setWork : calling it providing a function tells the scheduler which function to call when it wants to continue your processing (after the execution of more importants tasks).
  • shouldYield : read this to know if the function should yield : if true, you set the next function to call using the setWork function and you returns. If false, you do your job.

So how do we implement this feature ? By creating a processing function which will process each part in a loop. At each cycle, we will check if we have to yield. If so, we tells the scheduler to call us back when it wants to restart our process. If the process is done (10 parts processed) then we just returns.

Here is how I will implement this “10 parts processing”.
[js]var partProcessed = 0;

function executeYieldingTask() {

// schedule some work
S.schedule(function myScheduledJob(jobInfo) {

//Process the 10 parts
while (partProcessed < 10) {

//check if I have to yield :new job with higher priority
// may have been scheduled
if (jobInfo.shouldYield) {

//tells the Scheduler to execute myScheduledJob
// when it’s done executing higher priority task
jobInfo.setWork(myScheduledJob);

//we yield so we exit the ‘process loop’
break;

}
else {
/* process the part partProcessed */
partProcessed = partProcessed + 1;
}
}
}, S.Priority.idle);
}

[/js]

The IOwnerToken interface and how to use it

IOwnerToken is an interface which represents the owner of a job. By owner it means “master” : the one who controls and manage it.
A token can be set to multiple jobs at once and there is one function on this interface : cancelAll. This function simply cancel all the jobs owned by the token.

To create a token, you have to call the createOwnerToken function. You can then assign it to created job.
[js]
//create a token
var ownerToken = WinJS.Utilities.Scheduler.createOwnerToken();

//create jobs
var job1 = WinJS.Utilities.Scheduler.schedule( /* …*/);
var job2 = WinJS.Utilities.Scheduler.schedule( /* …*/);

//Be in control
job1.owner = ownerToken ;
job2.owner = ownerToken ;

//Cancel the jobs at once :
ownerToken.cancelAll();
[/js]

This token is then really useful when you want to manage a group of jobs at once. Create an owner, if the user do something else, goes to another page : you cancel all the task at once and retrieve some CPU juice.

Some useful functions

Now let’s discover some useful functions when playing with jobs and the scheduler.

  • requestDrain : use this function if you want to be sure that all scheduled jobs at a given priority are over. Simply pass the targeted priority, it returns a promise which can be use to know the completion of the “error state” of the queue processing
  • retrieveState : you need to dump the schedule queue for debug purpose ? Use this function :). It dumps the name, the id, the priority of the tasks, etc.
  • schedulePromiseXXX : there is a lot of functions with similar names(schedulePromiseAboveNormal, etc.). These functions takes a promise as a parameter. It assures that the completion/error handler is processed on the scheduler with the given priority. If you want a completion handler tob be processed as soon as the promise is done, then use schedulePromiseHigh.

Here are some code example :
[js]
//requestDrain example
var drainPromise = WinJS.Utilities.Scheduler.requestDrain(priority, name);

drainPromise.done(
function complete(){console.log("queue drained");},
function error(){ });

//retrieveState example :
var S= WinJS.Utilities.Scheduler;
S.schedule(function () {/* */ }, S.Priority.aboveNormal,null,"a task name");
S.schedule(function () {/* */ }, S.Priority.idle,null, "infinite square name");
S.schedule(function () {/* */ }, S.Priority.belowNormal,null,"another task name");

var state = WinJS.Utilities.Scheduler.retrieveState();
/*
state looks like this :
Jobs:
id: 22, priority: aboveNormal, name: a task name
id: 24, priority: belowNormal, name: another task name
id: 23, priority: idle, name: infinite square name
Drain requests:
None
*/

//schedulePromiseXXX example
var dldPromise = WinJS.xhr({url:’www.infiniteSquare.com’});
WinJS.Utilities.Scheduler.schedulePromiseHigh(dldPromise)
.then(function(xhrResult){
/* process interesting content */
});

[/js]

Regards.

]]>
http://www.jonathanantoine.com/2013/07/02/windows-8-1-lets-discover-the-scheduler-of-winjs/feed/ 2
Windows 8.1 #XAML new theme management in your Windows Store Apps http://www.jonathanantoine.com/2013/06/30/windows-8-1-xaml-new-theme-management-in-your-windows-store-apps/ http://www.jonathanantoine.com/2013/06/30/windows-8-1-xaml-new-theme-management-in-your-windows-store-apps/#comments Sun, 30 Jun 2013 15:53:33 +0000 http://www.jonathanantoine.com/?p=1460 Did you remember Windows 8 ? The theme of your app was set once at the launch and you could’nt change it dyamically or set once by control. This was really annoying in some case like Settings Flyout where you often wanted to set the opposite one of your app.

This was good old times and these issues are gone in Windows 8.1 : youpi !

Let’s digg a little more Smile

The theme can be updated at runtime

Windows 8 theme resources are provided using StaticResource and so can’t be updated at runtime. The resources are loaded once at the app startup and even if you update it, the controls won’t update themselves because the StaticResource provide the value once and only once : when parsed.

Now comes a new markup extension named ThemeResource. You can use it like the StaticResource object but this special resource will update the targeted control if the Theme of the control is updated. You can see it as the DynamicResource in WPF but only for some “theme” resource and triggered only by a theme change.

Of course, all the template of the frameworks are now using this new feature and you are free (must Smile) use it in your own controls. You can actually use it anywhere in your XAML :
[xml]
<Border RequestedTheme="Light"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Border>
[/xml]

The theme can now be set by control

In Windows 8 you had to set the RequestedTheme property at launch (in the constructor of you app for example) and it could be set only once.

Now this is a property of the FrameworkElement class which is the base class for any control. The value will be inherited by all its children (this is actually done because it overrides values in the resource dictionary which will be available to the children of the control).

In this sample I override the theme twice in the same visual tree :

[xml]
<StackPanel RequestedTheme="Light"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Hello World !" />
<Border RequestedTheme="Dark"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock Text="Another theme" />
</Border>
</StackPanel>
[/xml]
It then produce this view :
Screenshot (1)

 

Be aware that this is a “low priority” setting and that all the styles, directly set attributes/properties, triggers, animations and even implicit styles are winning over it.

 

Questions ?

  • Can we set it by code ? : yes of course, this is a normal property.
  • Can we use binding ? : Yes !
  • What are the value of RequestedTheme for the children of a control ? : The value is “Default”. This only means that the value is not overriden and not that this use the App’s theme (it’s the theme of the first overriden parent which is used).

You can read this post in french too.

You can find more by exploring the “XAML requested theme sample (Windows 8.1)” of the samples pack provided by Microsoft.

Have a nice code 🙂

]]>
http://www.jonathanantoine.com/2013/06/30/windows-8-1-xaml-new-theme-management-in-your-windows-store-apps/feed/ 3
[WinRT] How to get the language code actually used to resolve a resource http://www.jonathanantoine.com/2013/06/05/winrt-how-to-get-the-resolved-resource-language-code/ http://www.jonathanantoine.com/2013/06/05/winrt-how-to-get-the-resolved-resource-language-code/#comments Wed, 05 Jun 2013 16:25:41 +0000 http://www.jonathanantoine.com/?p=1445 I am working on an app with a lot of different languages. This is really great because there is a lot more chances that the user get the app in its spoken tongue. You can read more on this topic on MSDN.

Then I wanted to get a basic information : the language used by the app. Let’s say that the user is spanish and that I didn’t translate my app for this tongue then the app could be in english because it’s the one tongue matching the best its preference. The “english” won’t necessary be the first language declared in my manifest but the best one for the user.

By using a ResourceLoader object, you can get any string in the right language but I didn’t find an easy way to get the actually used language.

By digging into the WinRT APIs, I found a way to get this information and it could help you.

A solution

The trick is to use the MainResourceMap of the app to retrieve a resource candidate for a resource key I know being in all my resources files. With this ResourceCandidate, I can get the ResourceQualifier which made the framework choose this resource. On this qualifier, I can then retrieve the name of the used language…

[csharp]
//I have a resource file named "Resources" for each my language
// and each one has a ‘AResource’ object in it.
var namedResource = ResourceManager.Current.MainResourceMap
.FirstOrDefault(nR => nR.Key == "Resources/AResource").Value;

//I resolve this resource
var resourceCandidate = namedResource.Resolve();

//The qualifier let me know the used language code.
var resourceQualifier= resourceCandidate.Qualifiers.FirstOrDefault();

var languageCode = resourceQualifier.QualifierValue;
[/csharp]

You can also get interesting information from the resourceCandidate object :

  • IsMatch: is this resource found using the a language defined in your manifest.
  • IsDefault : is this resource found using the default “language” (the one defined in your manifest) ?
  • Score : the score of the retrieved resourceCandidate in the resource-matching algorithm used by the framework

An interesting thing is that you can also know the score of the retrieved resourceCandidate in the resource-matching algorithm used by the framework. It’s the Score property of the ResourceCandidate.

Another one

An another solution is to put the language code of each resource file inside the resource. Then you could use the ResourceLoader to get it.
Resources

Things I tried

I also tried to use the ApplicationLanguages.ManifestLanguages list but with this API I can get the language declared in my manifest, not the one actually used by the app.

Same thing with ApplicationLanguages.Languages which let me know the user defined languages but not the one actually used by the app.

Do you know a better way ?

]]>
http://www.jonathanantoine.com/2013/06/05/winrt-how-to-get-the-resolved-resource-language-code/feed/ 1
Win8/XAML : how to create a TextBlock with clickables hyperlinks in it http://www.jonathanantoine.com/2013/05/30/win8xaml-how-to-create-a-textblock-with-clickables-hyperlinks-in-it/ http://www.jonathanantoine.com/2013/05/30/win8xaml-how-to-create-a-textblock-with-clickables-hyperlinks-in-it/#comments Thu, 30 May 2013 12:07:31 +0000 http://www.jonathanantoine.com/?p=1424 Xaml is really powerful and you can build nearly any user interface you want with it.

However it can be hard sometimes and in this post I will describe how you can create something I first thought it will be easy : a wrapping text with hyperlinks in it.

Something like this :
textWrappingWithLinkScreenshot

As you will read, this is not as straightforward as I thought.

I tried a few things before to make it works the way I want to.

#fail 1 : use hyperlink element in the Textblock

Did you remember Silverlight (:p) ? I do and especially the Hyperlink element that you can use in Textblock :
[xml]
<TextBlock IsReadOnly="True">
<Run> Displaying text with</Run>
<Hyperlink NavigateUri="http://www.infinitesquare.com"
TargetName="_blank">hyperlink</Hyperlink>
<Run>.</Run>
</TextBlock >
[/xml]

It’s really nice but…. there is no hyperlink element in the Windows8 Xaml framework… too bad 🙁

#fail 2 : use the tapped event on run elements

There is in fact no such thing in the Windows 8 Xaml Framework so this is a dead end 🙁

#fail 3 : use the textblock’s tapped event to retrieve the aimed run element

My third idea was to create a textblock with runs and Underline element to recreate the same display.

Then I can register myself to the Tapped event and grab the tapped run and then open the matching links.
I would then create something like this :

[xml]
<TextBlock>

<Run Text="Cupcake ipsum dolor. Sit amet I love croissant fawork" />
<Run Text=" " />
<Underline FontFamily="Segoe UI">
<Run Foreground="#FFFF1BF5"
Text="I love ice cream" />
</Underline>
<Run Text=". Chocolate ice cream soufflé pastry." />
<Run Text=" Bear claw chocolate tart brownie apple pie." />
<LineBreak />
<LineBreak />
<Run Text="Pastry sesame snaps cotton candy jelly-o marzipan pastry" />
<Run Text=" cake I love faworki. Wypas I love jelly." />
<Underline FontFamily="Segoe UI">
<Run Foreground="#FFFF1BF5"
Text="I love toffee macaroon chocolate bar." />
</Underline>
</TextBlock>
[/xml]

[csharp]
private void MyTexBlock_OnTapped(object sender, TappedRoutedEventArgs e)
{
var run = e.OriginalSource;
}
[/csharp]

The problem here is that the OriginalSource element is in fact the TextBlock itself and not the Run or the Underline element I created. So there is no way to know which link the user touched but only it touched the TextBlock somewhere.

#fail 4 : use a RichTextBlock with InlineUIContainer and an HyperlinkButton element

After these failures, I decided to use a weapon of mass destruction : a RichTextBlock and a InlineUIContainer element.
You can’t just add Run inside a RichTextBlock but instead, you have to create one (or more) root paragraph element.

The InlineUIContainer lets you put any FrameworkElement you want inside a document(the content of the Paragraph). You can then register handlers to the events of this FrameworkElements as you would have in any Xaml UI.

In the code snippet below, I register myself to Tapped event of the Textblock I insert in my paragraph :
[xml]
<RichTextBlock IsTextSelectionEnabled="False">
<Paragraph>
<Run Text="Cupcake ipsum dolor. Sit amet I love croissant fawork" />
<Run Text=". " />

<InlineUIContainer>
<Border Background="#FFF1EFEF">
<TextBlock Tapped="OnLinkTapped" Foreground="#FFFF1BF5"
TextWrapping="Wrap"> <Underline>
<Run Text="I love ice cream, to write very long text " />
<Run Text="and to take some screenshots." />
</Underline>
</TextBlock>
</Border>
</InlineUIContainer>

<Run Text="A Chocolate ice cream soufflé pastry. " />
<Run Text="Bear claw chocolate tart brownie apple pie." />
</Paragraph>
</RichTextBlock>
[/xml]

Wonderful… wait … oh no… there is still one issue : the paragraph element will consider the InlineUIContainer as “whole block” and not as “text” and then it will wrap strangely your content. In this screenshot, I added a gray border around my TextBlock show this behavior to you :
shouldBeThere

#Success : use a RichTextBlock and the GetPositionFromPoint method

I finally found one hack and if you know a better way, please tell me in the comment which one it is 🙂

My solution is to use the RichTextBlock’s tapped event and its GetPositionFromPoint method. This method returns a TextPointer for a given position of your RichTextBlock. This TextPointer object has a Parent property which is the TextElement (Run, Underline, Span, etc…) the user clicked on : exactly what we want !

My Xaml then look like this :
[xml]<RichTextBlock IsTextSelectionEnabled="False"
Margin="30"
Width="600"
TextAlignment="Justify"
FontSize="40"
TextWrapping="Wrap"
Tapped="UIElement_OnTapped">
<Paragraph>
<Run Text="Cupcake ipsum dolor. Sit amet I love croissant fawork" />
<Run Text=". " />

<Underline x:Name="LinkToInfiniteSquare"
Foreground="#FFFF1BF5">
<Run Text="I love ice cream, to write very long text " />
<Run Text="and to take some screenshots." />
</Underline>

<Run Text="A Chocolate ice cream soufflé pastry. " />

<Underline x:Name="LinkToMyBlog"
Foreground="#FFFF1BF5">
<Run Text="Bear claw chocolate tart brownie apple pie." />
</Underline>

</Paragraph>
</RichTextBlock>

[/xml]

The last part is to walk trough the parents of the clicked/touched element to find out its Underline parent, read its name and launch the correct action.

[csharp]
private void UIElement_OnTapped(object sender, TappedRoutedEventArgs e)
{
var richTB = sender as RichTextBlock;
var textPointer = richTB.GetPositionFromPoint(e.GetPosition(richTB));

var element = textPointer.Parent as TextElement;
while (element != null && !(element is Underline))
{
if (element.ContentStart != null
&& element != element.ElementStart.Parent)
{
element = element.ElementStart.Parent as TextElement;
}
else
{
element = null;
}
}

if (element == null) return;

var underline = element as Underline;
if (underline.Name == "LinkToInfiniteSquare")
{
Launcher.LaunchUriAsync(new Uri("http://www.infinitesquare.com"));
}
else if (underline.Name == "LinkToMyBlog")
{
Launcher.LaunchUriAsync(new Uri("http://www.jonathanantoine.com"));
}

}

[/csharp]

By the way, I can not use a TextBlock element because it does not have the GetPositionFromPoint method.

Do you know a better way ?

(Please don’t tell me to do it in HTML/JS :p)

The source code is available here.

]]>
http://www.jonathanantoine.com/2013/05/30/win8xaml-how-to-create-a-textblock-with-clickables-hyperlinks-in-it/feed/ 11
WinJS : use the same data in the zoomed out and zoomed in view. http://www.jonathanantoine.com/2013/05/17/winjs-use-the-same-data-in-the-zoomed-out-and-zoomed-in-view/ Fri, 17 May 2013 14:13:49 +0000 http://www.jonathanantoine.com/?p=1401 The Semantic zoom let you display your data in a zoomed out and zoomed in way. It’s really fine when your data is grouped but sometimes you need to display a non-grouped data just in a different way with a different template.

For example, we did it in the Larousse Illustré Windows 8 app to display media in a different way when zoomed in than zoomed out :zoomedInOut

This is exactly the same data but shown in a different fashion. The user choose the one it prefers.

But, if you try to set the same data source to the both listview in your semantic zoom, your app will crash.

An exception is raised because a method “itemFromDescription” is not defined.

The solution to make everything works is to define this method as below :
[js]
var zoomedInListView = document.getElementById("zoomedInListView").winControl;
var zoomedOutListView = document.getElementById("zoomedOutListView").winControl;

zoomedInListView.itemDataSource = myList.dataSource;
zoomedInListView.itemDataSource.itemFromDescription
= function (it) { return WinJS.Promise.wrap({ index: 0 }); };

zoomedOutListView.itemDataSource = myList.dataSource;
zoomedOutListView.itemDataSource.itemFromDescription
= function (it) { return WinJS.Promise.wrap({ index: 0 }); };

[/js]

I hope this will help you 🙂

A sample is available (scenario 2) on my Dropbox.

]]>
[Win8] The cached file updater contract or how to make more useful the File Save Picker contract http://www.jonathanantoine.com/2013/03/25/win8-the-cached-file-updater-contract-or-how-to-make-more-useful-the-file-save-picker-contract/ http://www.jonathanantoine.com/2013/03/25/win8-the-cached-file-updater-contract-or-how-to-make-more-useful-the-file-save-picker-contract/#comments Mon, 25 Mar 2013 13:11:26 +0000 http://www.jonathanantoine.com/?p=1321 cachedFileUpdaterContractAs you can read on MSDN, there is in fact a lot of contracts available for a Windows 8 app.

Today, I want to describe one which is very useful for the Dropbox client I work on (8 Files In A Box) : The Cached File Updater contract.

As you will see, it can be really useful with the FileSavePicker contract.

First of all :
The code of this blog post is available here.

What is it ?

The Cached File Updater contracts simply declare that your app is responsible for the management of one or many of its files. This is really useful for ‘file management apps’.

You can usethe “CachedFileUpdater” to do some really interesting things :

  • Activate the app before a read is done to your file.
  • Activate the app after a write is done to your file.
  • Set your file as read-only.
  • Use a cached version of your file is internet is not available.
  • Refuse access to the file if internet is not available

I refer to “a file” but this can be done on any file of your app.

How to use it ?

Using this contract is done in 4 steps, one being optional.

1)Declare the contract in the manifest.

The first thing, as for any contracts is to declare the contract in the app manifest. Simply add it :
cachedFileUpdaterManifest

2)Define some triggers on your file.

When you create a file in your app, you can define some triggers on it using the CachedFileUpdater.SetUpdateInformation method. This is a simple call and it takes 5 arguments :

  1. The Storage file itself.
  2. An id which will be passed to your app when activated for this file.
  3. A ReadActivationMode which define if the app is activated before the file is accessed or not.
  4. A WriteActivationMode which tells if your app is activated after an other app writes “on” your file, or if the file must be read-only.
  5. A CachedFileOptions which tells how “behave” acces to the file when there is no internet connection.

Here is an example which ask your app to be activated after an another app writes on your file :
[csharp]CachedFileUpdater.SetUpdateInformation(fileCreated,
"A content id to identify the file.",
ReadActivationMode.NotNeeded,
WriteActivationMode.AfterWrite,
CachedFileOptions.None);
[/csharp]

3)Override the OnCachedFileUpdaterActivated method of the Application.

Once this is done, you can override the OnCachedFileUpdaterActivated method of your application. The provided arg will give you a propertie “CachedFileUpdaterUI” with some interesting information :

  • An event “FileUpdateRequested” which will be raised when the previously defined triggers are reached.
  • The property “UpdateTarget” which tells you if the file to update is “remote” (the file in your app) or “local”(the file in the other app).
  • An UIRequested event raised when the user needs to provide some input to be able to update the file. We’ll go further on that later

When you don’t have to show any UI to the user, you’ll simply have to grab the file when the FileUpdateRequested event is raised and do something with the file. If the local file have to be updated, you can call the UpdateLocalFile method and provide an up to date file.

Also, you have to set the “args.Request.Status” depending of the success of the operation (in our case to FileUpdateStatus.Complete).
Here is an example :
[csharp]
protected override void
OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args)
{
args.CachedFileUpdaterUI.FileUpdateRequested
+= OnCachedFileUpdaterUIFileUpdateRequested;
base.OnCachedFileUpdaterActivated(args);

//do not forget this
Window.Current.Activate();
}

void OnCachedFileUpdaterUIFileUpdateRequested(CachedFileUpdaterUI sender,
FileUpdateRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();

var theContentId = args.Request.ContentId;
var theTargetFile = args.Request.File;

//Do something to the file

//If the local file have to be updated, call do this :
//StorageFile upToDateFile=null;
//fill upToDateFile with the correct data
//args.Request.UpdateLocalFile(upToDateFile);

args.Request.Status=FileUpdateStatus.Complete
deferral.Complete();
}
[/csharp]

4) Ask the user for some input (optional).

If the update process needs it, you can ask the user for some input.

To do so, you have to tell it in the FileUpdateRequested event handler using the args.Request.Status and set it to FileUpdateStatus.UserInputNeeded.
[csharp]
if (sender.UIStatus == UIStatus.Hidden)
{
args.Request.Status = FileUpdateStatus.UserInputNeeded;

//Can set a custom title
sender.Title = "Requiring input for : " + args.Request.ContentId;

return;
}
[/csharp]

The UIRequested event is then raised and you have to set the content of the Window to your specific UI in the handler. Don’t forget to do it in the right thread.Don’t forget to do it in the right thread : create the page in the first activation event and use the page Dispatcher to set the content.

[csharp]
void CachedFileUpdaterUI_UIRequested(CachedFileUpdaterUI sender, object args)
{
_specificUIPage.Dispatcher.RunAsync(
CoreDispatcherPriority.Normal,
() => { Window.Current.Content = _specificUIPage; });
}
[/csharp]

The FileUpdateRequested event will then be raised once more to inform you that the UI is visible. In the handler, you have to grab the event args and pass it to your UI. The UI will then be responsible to set the Request Status to the correct value. In my case, I save the args as a static field of my application.
[csharp]
public static FileUpdateRequestedEventArgs FileUpdateRequestedEventAr
void OnCachedFileUpdaterUIFileUpdateRequested(
CachedFileUpdaterUI sender, FileUpdateRequestedEventArgs args)
{
bool showSpecificUI = false;

FileUpdateRequestedEventArgs = args;

var deferral = args.Request.GetDeferral();
if (sender.UIStatus == UIStatus.Hidden)
{
args.Request.Status = FileUpdateStatus.UserInputNeeded;

//Can set a custom title for the UI
sender.Title = "Requiring input for : "
+ args.Request.ContentId;
deferral.Complete();
return;
}

if (sender.UIStatus == UIStatus.Unavailable)
{
//failure
args.Request.Status = FileUpdateStatus.Failed;
deferral.Complete();
return;
}

if (sender.UIStatus == UIStatus.Visible)
{
//Do nothing, the UI will do it for us.
return;
}
}

[/csharp]

In my UI, I simply set the status and complete the deferral when the user click on a button:
[csharp]
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
App.FileUpdateRequestedEventArgs
.Request.Status = FileUpdateStatus.Complete;
App.FileUpdateRequestedEventArgs
.Request.GetDeferral().Complete();
}
[/csharp]

InputNeeded

Why is it useful with the FileSavePicker ?

In 8 Files In A Box, the Dropbox client for Windows 8, we wanted to be able to save a file and to upload it directly to the user Dropbox.

I first thought it was not possible : as soon as the file save picker provide a file to the requesting app, my app is shut down by Windows 8 and I have :

  • no way to know when the provided file is fully written by the other app.
  • no CPU time because my app is no more running.

Leonard one of my Infinite Square colleague demonstrated me that I was wrong (and that impossible is really not a French word:)).

It can in fact be done using the Cached File Updater contract :

  1. Provide a file the usual way in the file save picker UI.
  2. Use the WriteActivationMode.AfterWrite trigger on it.
  3. Launch an upload when my app is activated after the write is done.

Really simple in fact 🙂 For those who best understand code (as me :)) here a code snippet :
[csharp]
protected override void
OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args)
{
base.OnFileSavePickerActivated(args);

args.FileSavePickerUI.TargetFileRequested
+= FileSavePickerUI_TargetFileRequested;
}

async void FileSavePickerUI_TargetFileRequested(
FileSavePickerUI sender,
TargetFileRequestedEventArgs args)
{
var fileCreated = await ApplicationData.Current
.TemporaryFolder.CreateFileAsync("ThisIsACoolFileName");

CachedFileUpdater.SetUpdateInformation(fileCreated,
"A content id to identify the file.",
ReadActivationMode.BeforeAccess,
WriteActivationMode.AfterWrite,
CachedFileOptions.None);

args.Request.TargetFile = fileCreated;

}

[/csharp]

Others importants things to know

1) don’t forget to activate your app.

At first, I did not manage to make it works : the OnCachedFileUpdaterActivated method was called but the OnCachedFileUpdaterUIFileUpdateRequested event was never raised.

After some research on the internet, I finally found that the Windows.Current.Activate() call to activate your app is really necessary : do not forget it 🙂 !

2) my app is not activated 🙁

Finally, I just want to remind you that the app requesting the file is responsible to let Windows know that it has no more use of the file (the write is done). So if your app is not activated, it could be because the requesting app is simply not asking you to update the file.

If you are using (not implementing but using) the FileSavePicker, please calls the CachedFileManager methods like in this snippet from the file picker sample :
[csharp]
// Prevent updates to the remote version of the file until we
// finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we’re finished changing the file so the other
// app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
[/csharp]

3) be careful with the Dispatcher

When your app is activated, a Dispatcher is created for it. The CachedFileUpdaterUI use another Dispatcher and you have to be careful to be on the right dispatcher(yours) when updating your UI. For example when you set the content of your Windows, don’t forget to do it on your Dispatcher.

I let you digg into my attached code for a more complete example.
If you want another sample, you can download and use the File Picker sample on MSDN.

That’s all for today !

]]>
http://www.jonathanantoine.com/2013/03/25/win8-the-cached-file-updater-contract-or-how-to-make-more-useful-the-file-save-picker-contract/feed/ 1
C++/CX : How to expose/convert an existing concurrency::task to Windows::Foundation::IAsyncAction^ ? http://www.jonathanantoine.com/2013/02/26/ccx-how-to-exposeconvert-an-existing-concurrencytask-to-windowsfoundationiasyncaction/ Tue, 26 Feb 2013 14:15:58 +0000 http://www.jonathanantoine.com/?p=1302 streamVideoBlobWindows81😮 I am really writing a blog post on C++ ? Yest it seems so :). At this year MVP Summit I discovered how much fun I can have with C++ (and especially C++/Cx in my case) thanks to Simon Ferquel and Bruno Boucard.

concurrency::task are available through the “ppltasks.h” header files and can be considered as the TPL tasks in C#.
One of the first thing I tried to do in a C++ component is to create a concurrency::task, use it and expose it as a IAsyncAction to the other C#/JS component.

I often create components which needs initialization, and to do so I create tasks:

  • It will be executed on another thread
  • The “client” does not have to wait for the initialization to complete if they don’t need the component immediately
  • In all my component internal functions, I can wait for the initialization to finish using continuation, if it’s already initialized, it returns immediately

It’s not possible to expose a PPL concurrency::task as a WinRT IAsyncAction. To create and return an IAsyncAction, you have to use the concurrency::create_async function which internally create a task and wraps it. If the passed lambda returns a type, then the create_async will return a IAsyncOperation (isn’t it wonderful ?). Here is an example :
[cpp]
concurrency::create_async([this](){ /* my job to do in a task /* });
[/cpp]

But in my case, the task is already created. So the only solution I found to this issue is to create a lambda which returns my task and feed the create_async method with it. As the lambda returns a task, the create_async will create a IAsyncAction/Operation which will wait for the completion of the init task too.

[cpp]
Windows::Foundation::IAsyncAction^ YoupiTralala::ForceInitAsync()
{
auto toReturn= concurrency::create_async([this](){ return this->initTask;});
return toReturn;
}
[/cpp]

Interesting links:

Do you know a better way to do this ?

]]>