WordPress database error: [INSERT, UPDATE command denied to user '51213-2'@'10.10.20.25' for table 'wp_options']INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_doing_cron', '1715253235.7754590511322021484375', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)
You may already know these monitoring events available before and which are now no more supported :
They have been replaced by the MutationObserver in IE 11 because they have several drawbacks:
The MutationObserver fix these issues and is really easy to use :
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]
This is a just a quick blog post of this good new API. You can find more information on these pages :
]]>
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.
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.
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 :
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]
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 :
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]
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.
Now let’s discover some useful functions when playing with jobs and the scheduler.
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.
]]>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 :
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.
]]>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 !
]]>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]