WordPress database error: [INSERT, UPDATE command denied to user '51213-2'@'10.10.20.12' for table 'wp_options']INSERT INTO `wp_options` (`option_name`, `option_value`, `autoload`) VALUES ('_transient_doing_cron', '1715094736.9879479408264160156250', 'yes') ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)
The solution I ended up with is to create an AppDomain by “worker” and to execute the already existing code in each one. The context will be unique in each AppDomain and I will be able to reuse my existing code.
To have this working I have to perform these steps:
The code for the StartPoint class is very easy :
public class MonPointDentree : MarshalByRefObject { public static string Context; public void Execute(string input) { // Task can't be marshalled : let's wait ExecuteAsync(input).Wait(); } private async Task ExecuteAsync(string input) { Debug.WriteLine("[BEFORE] " + Context); Context = input; Debug.WriteLine("[AFTER] " + Context); // call my legacy code here } }
The “MaDllAPart” is added as a reference to the WPF project : this let’s me create an instance of StartPoint without special configuration from my side. Be sure to use the full name (with the namespace) of the instanciated type.
private static void LaunchProcess() { for (int i = 0; i < 10; i++) { var domain = AppDomain.CreateDomain("MonAppDomain_" + i); var startPoint = (MonPointDentree)domain .CreateInstanceAndUnwrap("MaDllAPart", "MaDllAPart.StartPoint"); startPoint.Execute("module " + i); } }
Happy coding !
]]>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 :
Not really obvious but this works fine
If you want to see this feature in action, it will soon be available in our last app “Say it With Flowers” !
PS: the whole procedure is describe in depth on MSDN but I am sure you love this recap
PS2: the localized app name won’t be displayed on the Store page because of a bug in the Store : http://blog.webrox.fr/?p=61
]]>
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.
]]>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.
]]>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.
]]>This is quite boring because it also raises the SelectionChanged event twice and can mess up your business logic.
Let’s see how to fix this temporary (I hope!) issue :
The problem is that the LongListMultiSelector listen to the changes(add/remove/replace/clear) in it’s SelectedItem collection so we can’t use it directly.
The solution is to ‘fake’ an user selection using the LongListMultiSelectorItem which is the container of each item.
So instead of writing this code :
[csharp]
foreach (var item in LongListMultiSelector.ItemsSource)
{
//LongListMultiSelector.SelectedItems.Add(item);
}
[/csharp]
you have to write this code :
[csharp]
foreach (var item in LongListMultiSelector.ItemsSource)
{
var container = LongListMultiSelector.ContainerFromItem(item)
as LongListMultiSelectorItem;
if (container != null) container.IsSelected = true;
}
[/csharp]