UWP App Certification Launchactivatedeventargs.Prelaunch - windows-store-apps

I'm trying to test my UWP application for submitting it to the store with Microsoft App Certification Kit. The only problem I have is:
in the onlaunched method implementation of the app, ensure you handle the launchactivatedeventargs.prelaunch option to be prelaunch event aware
I've never changed it, I'm using the original project from Visual Studio
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override async void OnLaunched(LaunchActivatedEventArgs e) {
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached) {
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null) {
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) {
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (!e.PrelaunchActivated) {
if (rootFrame.Content == null) {
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(FormView), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
I googled a bit but everyone's speaking about a Template10 for UWP such al from this link
App Certification fails because of PreLaunch Test
Any suggestions? Thank you!

Yes, this is a way to pass WACK. Sometimes the package can also passed the store certification even though it failed WACK before.
When you test your project under project property in the Build section, and then you checked “Compile with .NET tool chain”, it mean that you run your project in “Release” mode.by default your app utilizes the .NET Native toolchain. Since the package is compiled to native binaries, the package does not need to contain the .NET framework libraries. In addition, the package is dependent on the latest installed .NET Native runtime as opposed to the CoreCLR package. The .NET Native runtime on the device will always be compatible with your application package.
Local native compilation via the “Release” configuration will enable testing your application in an environment that is similar to what your customers will experience. It is important to test this on a regular basis as you proceed with development.
Because store will test the package that you submitting in .NET Native mode, you will passed the certification by checking “Compile with .NET tool chain”.
In addition, here is an article about .NET Native, you could refer to it.

I think I found the solution but maybe it's just a lucky coincidence.
If under Project Property in the Build section, I checked "Compile with.NET Native tool chain" and now the result is Passed
Do you think it's the right answer?

Related

Windows Phone 8 background agent only runs when using a debug build (seems to not be running on a release build)

This is a weird one.
My Windows Phone 8 app's background agent seems to be updating absolutely fine throughout the day when I'm running a debug build. However, when I change to a release build, it either doesn't run at all or very infrequently. This is for a weather app: my live tile's content should change every hour. I've seen it sometimes update every hour, but then stop for a few hours, and then suddenly start again. At no point does the app's background agent get blocked by the OS either, which suggests to me there's nothing wrong with the background agent or it's just not getting run much/at all.
At the moment, I have debug and release builds of the app on my Lumia 1020 running Windows Phone 8.1. Code-wise they are identical. The debug build is updating every 30 minutes (I know cause of a timestamp on the live tile), whereas the release build has not updated once since it was created 90 minutes ago (but its background agent is still listed as being 'allowed' to run on the Battery Saver app).
Here's the method that creates the agent:
private void AddAgent(string periodicTaskName)
{
periodicTask = ScheduledActionService.Find(periodicTaskName) as PeriodicTask;
if (periodicTask != null)
{
RemoveAgent(periodicTaskName);
}
periodicTask = new PeriodicTask(periodicTaskName);
periodicTask.Description = "LiveTileHelperUpdateTask";
try
{
ScheduledActionService.Add(periodicTask);
// If debugging is enabled, use LaunchForTest to launch the agent in 5 seconds.
//#if(DEBUG_AGENT)
ScheduledActionService.LaunchForTest(periodicTaskName, TimeSpan.FromSeconds(1));
//#endif
}
catch (InvalidOperationException)
{
}
catch (SchedulerServiceException)
{
}
}
And here's the scheduled agent code:
public class ScheduledAgent : ScheduledTaskAgent
{
/// <remarks>
/// ScheduledAgent constructor, initializes the UnhandledException handler
/// </remarks>
static ScheduledAgent()
{
// Subscribe to the managed exception handler
Deployment.Current.Dispatcher.BeginInvoke(delegate
{
Application.Current.UnhandledException += UnhandledException;
});
}
/// Code to execute on Unhandled Exceptions
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
/// <summary>
/// Agent that runs a scheduled task
/// </summary>
/// <param name="task">
/// The invoked task
/// </param>
/// <remarks>
/// This method is called when a periodic or resource intensive task is invoked
/// </remarks>
protected async override void OnInvoke(ScheduledTask task)
{
// If the app has not been purchased and trial has expired,
// don't do anything here.
if( (bool) IsolatedStorageSettings.ApplicationSettings["TrialExpired"] == true )
return;
// Setup view model to get data from.
LiveTileViewModel viewModel = new LiveTileViewModel();
await viewModel.getWeatherForTileLocation();
// Use a dispatcher because we are NOT on the UI thread!
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
try
{
RadFlipTileData extendedData = new RadFlipTileData();
extendedData.IsTransparencySupported = true;
// Determine which sized tile will be the live tile.
// Only create a live tile for it due to memory constraints.
string liveTileSize = IsolatedStorageSettings.ApplicationSettings["LiveTileSize"].ToString();
switch (liveTileSize)
{
case "SMALL TILE":
extendedData.SmallVisualElement = new LiveTileSmall()
{
Icon = viewModel.Location.Hourly.Data[0].Icon,
Temperature = viewModel.Location.Hourly.Data[0].Temperature
};
break;
case "REGULAR TILE":
// Code here similar to small tile's
break;
default:
// Code here similar to small tile's
break;
}
FreeMemory();
foreach (ShellTile tile in ShellTile.ActiveTiles)
{
LiveTileHelper.UpdateTile(tile, extendedData);
break;
}
NotifyComplete();
}
catch (Exception e)
{
}
});
}
}
}
Anyone got any ideas what might be causing this or had any similar experience where the background agent only works on a debug build?
Thanks for your time.
did you try uninstalling the debug build and install the release to verify the background task execution?
And also try to remove the ScheduledActionService.LaunchForTest method call for release build, see the caution section in the docs. In the current code, you specified to trigger test run of background task for every 1 second. There is a limitation, in some cases if this time is below 60 seconds task may not run.

mvvmcross: NavigationService.Navigate throws an MvxException "Unable to find incoming mvxviewmodelrequest"

In my WP8 app, I have MainView referencing MainViewModel. MainView is a menu where users can navigate to other views to do some tasks. Navigating from MainView works perfectly as I use ShowViewModel. However, navigating from other views when user completes a task, back to MainView using NavigationService.Navigate(URI) throws an exception "Unable to find incoming mvxviewmodelrequest".
To avoid this exception, I have construct the URI like below
var req = "{\"ViewModelType\":\"MyApp.Core.ViewModels.MainViewModel, MyApp.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\",\"ClearTop\":\"true\",\"ParameterValues\":null,\"RequestedBy\":null}";
NavigationService.Navigate(new Uri("/MainView.xaml?ApplicationUrl=" + Uri.EscapeDataString(req), UriKind.Relative));
Does anyone have a better way to use NavigationService.Navigate?
Most navigations in the MvvmCross samples are initiated by either MvxAppStart objects or by MvxViewModels. Both of these classes inherit from MvxNavigatingObject and use the ShowViewModel methods exposed there - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross/ViewModels/MvxNavigatingObject.cs
From MvxNavigatingObject, you can see that MvvmCross routes the navigation call to the IMvxViewDispatcher which in WindowsPhone is a very thin object - all it does is marshall all calls to the UI thread and to pass them on to the IMvxViewPresenter - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.WindowsPhone/Views/MvxPhoneViewDispatcher.cs
The presenter is an object created in Setup - and the default implementation uses an IMvxPhoneViewModelRequestTranslator to convert the navigation call into a uri-based navigation - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.WindowsPhone/Views/MvxPhoneViewPresenter.cs
Silverlight/WindowsPhone then uses this uri for navigation, creates the necessary Xaml page, and then calls OnNavigatedTo on this page. As part of the base.OnNavigatedTo(); handing in MvxPhonePage, MvvmCross then calls the OnViewCreated extension method. This method checks if there is already a ViewModel - if there isn't one then it attempts to locate one using the information in the uri - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.WindowsPhone/Views/MvxPhoneExtensionMethods.cs
With this explanation in mind, if any app ever wants to initiate an MvvmCross navigation from a class which doesn't already inherit from MvxNavigatingObject - e.g. from some Service or from some other class, then there are several options:
You can provide a shim object to do the navigation - e.g.:
public class MyNavigator : MvxNavigatingObject {
public void DoIt() {
ShowViewModel<MyViewModel>();
}
}
// used as:
var m = new MyNavigator();
m.DoIt();
You can instead use IoC to locate the IMvxViewDispatcher or IMvxViewPresenter and can call their Show methods directly
var request = MvxViewModelRequest<MyViewModel>.GetDefaultRequest();
var presenter = Mvx.Resolve<IMvxViewPresenter>();
presenter.Show(request);
You can write manual code which mimics what the IMvxViewPresenter does - exactly as you have in your code - although it might be "safer" to use the IMvxPhoneViewModelRequestTranslator.cs to assist with generate the url - see https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.WindowsPhone/Views/IMvxPhoneViewModelRequestTranslator.cs
var request = MvxViewModelRequest<MyViewModel>.GetDefaultRequest();
var translator = Mvx.Resolve<IMvxPhoneViewModelRequestTranslator>();
var uri = translator.GetXamlUriFor(request);
One other option that Views always have is that they don't have to use the standard MvvmCross navigation and ViewModel location. In WindowsPhone, your code can easily set the ViewModel directly using your own logic like:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (ViewModel == null) {
ViewModel = // something I locate
}
// if you are doing your own logic then `base.OnNavigatedTo` isn't really needed in winphone
// but I always call it anyway
base.OnNavigatedTo(e);
}
Alternatively in WindowsPhone, you can even replace MvxPhonePage with a different base class that uses it's own logic for viewmodel location. This is easy to do in WindowsPhone as all Xaml pages have built-in data-binding support.

Windows Phone 8 Connection Handler / Internet Availability

My team is working on a team project aplication. At the moment, we need an event handler to check the connection status (if it's on/off).
I had big hopes in the System.Net.NetworkInformation Namespace, but unfortunately most important things aren't supported in wp8.
Can anyone help me with it a bit?
Edit 1#
It seems, I didn't specifed my problem well.
I'm using Mvvm light expresion, and it does not support that namespace or at least I can't add it.
I'm a newbie in using VS and c# atm, mayby I'm doing someting wrong, but simply when im trying to add the refernce to my project it does not list.
I haven't tried the System.Net.NetworkInformation namespace on WP8. But the new WP8 Windows.Networking.Connectivity Windows Phone Runtime namespace works just fine.
Use Windows.Networking.Connectivity.NetworkInformation.NetworkStatusChanged to know when network conditions change and use Microsoft.Phone.Net.NetworkInformation.NetworkInterface properties or Windows.Networking.Connectivity.NetworkInformation properties to see what's up.
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
PrintNetworkStatus();
NetworkInformation.NetworkStatusChanged += NetworkInformation_NetworkStatusChanged;
}
void NetworkInformation_NetworkStatusChanged(object sender)
{
PrintNetworkStatus();
}
private void PrintNetworkStatus()
{
Dispatcher.BeginInvoke(() =>
MessageBox.Show(NetworkInterface.NetworkInterfaceType +
Environment.NewLine +
NetworkInterface.GetIsNetworkAvailable()));
}
When I test this code snippet on my WP8 Lumia 920 it works as expected. On startup when my phone is on WiFi only I see the following MessageBox:
And once I shutdown my WiFI router and the WiFi connection on the phone is lost I see the following MessageBox:
Try this:
bool isNetwork=NetworkInterface.GetIsNetworkAvailable();
if(!isNetwork)
{
//proceed with your code
}
In App.xaml.cs, create a property like below
/// <summary>
/// check if network is available
/// </summary>
public bool IsNetworkAvailable
{
get
{
return NetworkInterface.NetworkInterfaceType != NetworkInterfaceType.None;
}
}
And you can use this property anywhere in your project as in below code
if (((App) Application.Current).IsNetworkAvailable)
{
//Lines of Code
}
else
{
MessageBox.Show("Not Connected to Network!", "Checking Connection!",
MessageBoxButton.OK);
}

NPE in StrutsTestCase after enabling Tiles

I developed some JUnit tests that extend org.apache.struts2.StrutsTestCase. I used the tutorial on struts.apache.org as my starting point.
Everything was working fine until I modified my simple web application to use Tiles. I have Tiles working fine in the app but now my Action test cases have stopped working.
I'm getting NullPointerException at org.apache.struts2.views.tiles.TilesResult.doExecute when I run the following line of code:
ActionProxy proxy = getActionProxy("/displaytag.action");
The log shows the Struts 2 Action is executing succesfully until it tries to hand it off to TilesResult.doExecute.
I suspect it is because the tests run outside of the container and the tiles.xml is only referenced in the web.xml and therefore my StrutsTestCase tests don't know where to find the definitions in tiles.xml.
Is this making sense?
I'm using Struts 2.2.1.1 and the tiles related jars (v. 2.0.6) included in the Struts distribution.
I'll include a code snippet from my StrutsTestCase but please note everything runs successfully when I run the app from the browser in Tomcat, it only fails when I run the StrutsTestCase outside of Tomcat. And the test cases ran successfully before I added Tiles.
public class TagActionTest extends StrutsTestCase {
static Logger logger = Logger.getLogger(TagActionTest.class);
public void testCreateTagFail() throws Exception {
logger.debug("Entering testCreateTagFail()");
try {
request.setParameter("name", "");
ActionProxy proxy = getActionProxy("/createtag.action");
TagAction tagAction = (TagAction) proxy.getAction();
proxy.execute();
assertTrue("Problem There were no errors present in fieldErrors but there should have been one error present", tagAction.getFieldErrors().size() == 1);
assertTrue("Problem field 'name' not present in fieldErrors but it should have been",
tagAction.getFieldErrors().containsKey("name") );
} catch (Exception e) {
logger.debug("Error running testCreateTagFail()");
e.printStackTrace();
assertTrue("Error running testCreateTagFail()", false);
}
}
Partial stack trace:
java.lang.NullPointerException
at org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
Lastly, can anyone explain what the deal is with StrutsTestCase? There's a tutorial page for using it with Struts 2 on struts.apache.org but the SourceForge page for it hasn't been updated since Struts 1.3 Also, what's the difference between StrutsTestCase and MockStrutsTestCase
I imagine you're initialising tiles with a listener:
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class>
</listener>
You need to initialise that Listener in your tests. I found a few others with the same issue [1].
The code below is in your class that extends StrutsSpringTestCase. You need to override the setupBeforeInitDispatcher. In the code snippet below, the override sets the applicationContext attribute (also needed if you're using spring) and initialises Tiles (inside the if(tilesApplication) segment, where tilesApplication is a boolean so you can toggle this code on an off based on your whether or not your application runs with tiles ):
/** Overrides the previous in order to skip applicationContext assignment: context is #autowired
* #see org.apache.struts2.StrutsSpringTestCase#setupBeforeInitDispatcher()
**/
#Override
protected void setupBeforeInitDispatcher() throws Exception {
//init context
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, applicationContext);
if(tilesApplication){
servletContext.addInitParameter(BasicTilesContainer.DEFINITIONS_CONFIG, "WEB-INF/tiles.xml");
final StrutsTilesListener tilesListener = new StrutsTilesListener();
final ServletContextEvent event = new ServletContextEvent(servletContext);
tilesListener.contextInitialized(event);
}
}
[1] See http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/
It is trying to display the jsp page. So disable by adding ExecuteResult(false) in the code.
So, add the below line
proxy.setExecuteResult(false);
before proxy.execute()

removing mouse events/controls from swing components with glasspane

I have a client-server application and i am using swing in the client side. My swing client has one main window (jframe) and lots of panels, toolbars and menubar in it.
I want to remove all client action/mouse events (or simply grab and do nothing) while client is waiting response from server by means of glasssPane.
Here is the code i wrote:
private final static MouseAdapter mouseAdapter = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
System.out.println("MouseClicked..!");
}
};
private static Cursor WAIT_CURSOR = Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR);
private static Cursor DEFAULT_CURSOR = Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR);
and
public static void startWaitCursor(JComponent comp)
{
MainWindow root = ((MainWindow) comp.getTopLevelAncestor());
root.getGlassPane().setCursor(WAIT_CURSOR);
root.getGlassPane().addMouseListener(mouseAdapter);
root.getGlassPane().setVisible(true);
}
public static void stopWaitCursor(JComponent comp)
{
MainWindow root = ((MainWindow) comp.getTopLevelAncestor());
root.getGlassPane().setCursor(DEFAULT_CURSOR);
root.getGlassPane().setVisible(false);
}
but i am not able to manage the grab mouse events. Changing cursors at the glassPane is working fine but either i am not able to add mouseAdapter or am not able to make glasssPane become to the top level component.
Any idea?
Thanks.
I realized that my code is working but my problem is threading related. My code was something like:
startWaitCursor();
work(); // server request that takes time
stopWaitCursor();
and changed it to:
startWaitCursor();
SwingUtilities.invokeLater(new Runnable() {
poblic void run() {
try
{
work(); // server request
}
finally
{
stopWaitCursor();
}
by doing this modification i could see the settings i made in the startWaitCursor() method while client is waiting response from the server.
But stil there is a small problem. In startWaitCursor() method i desabled key, mouse and focus events for the glass pane but events are still captured by main frame even glassPane is displayed.
addMouseListener(new MouseAdapter() {});
addMouseMotionListener(new MouseMotionAdapter() {});
addKeyListener(this);
setFocusTraversalKeysEnabled(false);
After server response reached to client and stopWaitCursor() method is invoked the events handled in the main frame.
If i disable the main frame of my application while client is waiting than cursor is not being changed to wait_cursor, if i am not disable the main frame then cursor is being changed but the events are queued.
cheers...
After digging swing threads issues couple of days, i finally found the real answer: SwingWorker
Now my final code is something like,
startWaitCursor();
SwingWorker worker = new SwingWorker() {
public Object doInBackground()
{
doWork(); // time consuming server request
return null;
}
public void done()
{
stopWaitCursor();
}
};
worker.execute();
In startWaitCursor() method i set the glasspane visible (with alpha valued background), display a message to warn the user time consuming job is doing, set the cursor to wait_cursor (hourglass) and consume all the key, mouse events. That is it.
And by using SwingWorker my client is actually responsive (it is working as if no server request is made) but since i display the glasspane and consume all key and mouse events it feels like irresponsive.
What a relief.. SwingWorker rocks...
cheers..