WordPress database error: [INSERT, UPDATE command denied to user '51213-2'@'10.10.20.167' for table 'wp_options']INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_doing_cron', '1714677504.1347870826721191406250', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)
We wil do this using DirectX and Unity.
As you can see in this video, the “context” of the leaved Windows is kept : the scroll position does not change.
Since a long time now, you can open a new Windows from a Windows Store app (UWP or Universal). For instance, the Mail app does this to let you edit an email in another dedicated window.
To perform this, you have to ask the SDK to create a new View (CoreApplicationView) which maps to a Window (CoreWindow) and an associated Dispatcher. This last point is interesting because you have to be very careful, when you share your ViewModels between windows, to be on the good Dispatcher when raising INotifyPropertyChanged event or doing some UI-related work.
Here is the code to create a Window :
// récupération de l'id courant pour usage ultérieur var appViewId = ApplicationView.GetForCurrentView().Id; //Create a new view \o/ CoreApplicationView newCoreAppView = CoreApplication.CreateNewView(); await newCoreAppView.Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Low, () => { //Get the created Windows Window window = Window.Current; ApplicationView newAppView = ApplicationView.GetForCurrentView(); // create a new frame and navigate to the page var secondFrame = new Frame(); window.Content = secondFrame; secondFrame.Navigate(typeof(MainPage)); // activate the new Window window.Activate(); // make the new window standalone ApplicationViewSwitcher.TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.UseMore, appViewId, ViewSizePreference.Default); });
By providing no argument to the CreateNewView method, we ask the XAML framework to create and manage a XAML UI.
We could also provide an argument of type IFrameworkViewSource to be able to have our own Window managed by our code. This is what DirectX does and it will let us create holograms !
By using the “HolographicDirectXApp” Visual Studio sample, I have all I need to create and display a 3D rotating cube by. The generated code creates an instance of IFrameworkView using DirectX. The sample use SharpDX, some C# classes and shaders that I can simply copy/Paste directly in a new XAML UWP project.
I then only have to use the previous snippet and ask it to use the DirectX AppView.
I have to carefully :
Of course, as all 3D holographic view, my start screen and the 2D View will disappear to let only the 3D objects in my space.
An Unity app being an UWP app the code to write will be very similar. We will only have to customize the generated Unity code to stay in a 2D World instead of going directly to the 3D exclusive View.
To be in the right configuration, I generate a XAML project instead of a Direct3D player in Unity. I then have this :
To have a “standard” Xaml project, I then perform these modifications :
The next steps are easy : I create a new Window, add a frame in it and navigate to the MainPage. I use exactly the same snippet as before and I only have to register an event handler to the activation of the created Window to be able to initialize Unity then. I also store the main view’s Id for further use.
private async Task CreateNewHoloWindowAsync() { var appViewId = MainAppViewId = ApplicationView.GetForCurrentView().Id; var _newCoreAppView = CoreApplication.CreateNewView(); await _newCoreAppView.Dispatcher .RunAsync(CoreDispatcherPriority.Low, async () => { var frame = new Frame(); Window.Current.Content = frame; frame.Navigate(typeof(MainPage)); var res = await ApplicationViewSwitcher.TryShowAsStandaloneAsync( ApplicationView.GetForCurrentView().Id, ViewSizePreference.Default, appViewId, ViewSizePreference.Default); _newCoreAppView.CoreWindow.Activated += WindowActivated; _newCoreAppView.CoreWindow.Activate(); }); } private void WindowActivated(object sender, WindowActivatedEventArgs e) { if (e.WindowActivationState == CoreWindowActivationState.CodeActivated || e.WindowActivationState == CoreWindowActivationState.PointerActivated) { AppCallbacks.Instance.SetInitialViewActive(); // Only need to mark initial activation once so unregister ourself CoreWindow coreWindowSender = sender as CoreWindow; coreWindowSender.Activated -= WindowActivated; } }
To go back to the 2D XAML view, you have to use the ApplicationViewSwitcher class and ask it to go switch back to the main Window.
I provide my Unity’s code an Action (GoBackToEarth.CloseThisHolographicView) it can call when needed.
// let's capture the dispatcher of the current view var dispatcher = Dispatcher; GoBackToEarth.CloseThisHolographicView = () => { // be sure to be on the Window's Dispatcher dispatcher.RunIdleAsync(async _ => { // go back to the main Window await ApplicationViewSwitcher.SwitchAsync(StartupPage.MainAppViewId); // we close the 3D holographic Window Window.Current.Close(); }); };
Happy coding !
]]>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.
To get the message associated with this error, follow this procedure :
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.
This was good old times and these issues are gone in Windows 8.1 : youpi !
Let’s digg a little more
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 ) use it in your own controls. You can actually use it anywhere in your XAML :
[xml]
<Border RequestedTheme="Light"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
</Border>
[/xml]
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 :
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.
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
]]>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.
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 :
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.
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.
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 ?
]]>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 :
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.
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
There is in fact no such thing in the Windows 8 Xaml Framework so this is a dead end
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.
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 :
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.
(Please don’t tell me to do it in HTML/JS :p)
The source code is available here.
]]>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.
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 :
I refer to “a file” but this can be done on any file of your app.
Using this contract is done in 4 steps, one being optional.
The first thing, as for any contracts is to declare the contract in the app manifest. Simply add it :
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 :
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]
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 :
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]
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]
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 :
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 :
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]
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 !
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]
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 !
]]>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’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:
It also can be useful when you need to store a label used on a lot of place in your application.
The .Net resources system is described all around the web and today we are going to explore a little the WinJS one.
In Metro app, the behavior is the same than in .NET, the values will be retrived depending of the current machine language.
The first thing is to add a folder for your resources. The folder name is what permits the resource engine to chose between langages. In our case, let’s create a ‘fr-FR’ folder. You can do it in place this folder anywhere in your solution, not necessary at the root of it.
Now, let’s add a resource file : choose an unique item name, then right-click on the previously created folder, choose “add an item” and select “Resources File (.resjson)”.
In WinJS, resources are JSON files easy to edit. Each value is represented by a key and the value itself. There is no editor like we used to in .NET :
[javascript]{
"greeting" : "Hello",
"_greeting.comment" : "A welcome greeting.",
}[/javascript]
If you want to add another language, just create another folder with the correct name and copy/paster the resource file in it with the same name.
WinJS provide an helper class to retrieve the values : ResourceLoader.
The constructor takes as a param the name of the resource file. I played a lot with it and it seems that you don’t have to provide the full ‘folder path’ of the resource file. It means that for the previous example we create an instance of it like this :
[javascript]
var rS= new Windows.ApplicationModel.Resources.ResourceLoader("/strings");
//AND NOT :
//new Windows.ApplicationModel.Resources.ResourceLoader("/i18n/strings");
[/javascript]
Once you have an instance of it, you use the getString method providing the key of the seeked value as a param :
[javascript]
var theValue= rS.getString("greeting");
[/javascript]
Keys are string value and so you can construct them at runtime very easily…
WinJS comes with an automatic way to push the values from the resources files directly to the HTML controls’ properties.
You have to use the data-win-res attribute and define the resource key to use on each control.
As this time, you can only use textContent specifier.
Here is an example retrieving the value of ‘greeting’ in the resource file and pushing it as the inner text of the “span” element.
[html]
<span data-win-res="{textContent: ‘greeting’}">
[/html]
Once the HTML element defined, you have to tell the resource engine to process the HTML element by using the WinJS.Resources.processAll. This another processAll method but in an another namespace. As a param you provide the element to process. Its child elements will be processed too. If you provide none, the whole document is processed.
You so have to do this each time you load an element.
In the MSDN example, it is done once when the app is loaded and I think this can be a good practice :
[javascript]
WinJS.Application.onloaded = function(){
WinJS.Resources.processAll();
}[/javascript]
When you start an application, you want and need it to be compliant with this theme and one main part of it are icons.
What you may not know is that there is already a lot of icons available for you out of the box in any Metro app.
Let’s discover them !
When I first looked for the icons, I first searched for pictures. I found none of them.
So I digged a little more on the sample and I found out that icons where here as a Font.
This is in fact a really good idea for several reasons :
Also, the font name is not the same in an HTML5 project than in an XAML one :
Each icon is represented by it’s hexadecimal value. These values are the same in both langages.
My first idea was to create a XAML app which will list them all and display them in a GridView.
It’s pretty easy to do, here is the C# which creates the list :
[csharp]
//create a list of my custom class CharAvailable
List<CharAvailable> characters = new List<CharAvailable>();
//we will not cycle trough all the font values
var starter = 0xE10F – 200;
var ender = starter + 1000;
//Create the character list
for (int i = starter; i < ender; i++)
{
characters.Add(new CharAvailable() {
Value = string.Format("0x{0:X} : ", i),
CharToDisplay = (char)i });
}
//Set it as datacontext
DataContext = characters;
[/csharp]
And the XAML to display each item :
[xml] <TextBlock
Text="{Binding CharToDisplay}"
FontFamily="Segoe UI Symbol"
FontSize="34"
/>[/xml]
When you want to display an icon in your HTML5 app, you just need to set the font family name to “Segoe UI Command” and to use the hexadecimal representation of the icon. Here is an example :
[html]
<p style="font-family: "Segoe UI Command";src:local("Segoe UI Symbol");">&#E195</p>
[/html]
Also, these icons are used by commands and you can then set the name of the icon as a shortcut instead of the hexadecimal value. For example here is how you can define a ‘favorite’ app bar command:
[javascript]
{id:’favorite’, icon:’favorite’, section: ‘selection’, onclick: iLoveIt}
[/javascript]
The full list of shortcut is available in the ui.js file (thank you Tom for the tip!).
I also created a PDF which list them all for easy retrieval. You can find it here.
]]>