EzDevInfo.com

windows-store-apps interview questions

Top windows-store-apps frequently asked interview questions

How can I get useful information (like stack traces) on C# Windows Store (Metro) Apps, when they crash?

So I'm doing my first steps in C# (and .NET/Visual Studio in general) and started by writing a simple tile puzzle as a portable library and writing UI's for different target platforms. I started with a Console UI and moved to a WPF Application. Then I tried "Windows Store" and for the most part I could copy the WPF code and just change some namespaces and method signatures.

But some thing do behave a bit differently and it took me over an hour of googling to get it to give me any kind of information about the crashed I was having. So if for example I make something like this in the conventional WPF application:

Storyboard.SetTargetProperty(animation, 
     new PropertyPath("{Canvas.MispelledProperty}"));

I get a .NET exception at the exact place where the exception is raised. If I do the same mistake in the Windows Store App all I get to see is this

#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
        UnhandledException += (sender, e) =>
        {
            if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
        };
#endif

(Edit: this is in a file called App.g.i.cs)

And then I have to carefully look at the output to find

WinRT information: Cannot resolve TargetProperty (Canvas.MispelledProperty) on specified object.

Now in some cases this might be enough but, but I really find it hard to believe that is all you can get. I got some problem related with nuances in the way Storyboar works sorted out pretty easily (Completed events attached directly to the animation where not being fired like in the WPF counterpart) but right now I'm completely clueless about a this error:

A first chance exception of type 'System.ArgumentOutOfRangeException' occurred

caused simply by wildly clicking around, which also crashes the entire app.

Now my app is really trivial and it probably has something to do with how I handle PointerPressed and PointerReleased events but it's really frustrating not to have something better to start with.

So I guess the actual question would be: Is it really supposed to be like this or can I configure the debugger to give me more useful information? And if not then: What kind of debugging techniques/workarounds do you guys use when developing Windows Store Apps?

UPDATE:

Well at first I thought this only happened to WinRT related Exception that where happening outside the CLR and where not properly wrapped but it turns out all unhandled exceptions take you to App.g.i.cs instead of the place where they happened. For instance I purposely tried to access a list out of it's ranges in a method to see if Visual Studio would take me there when the exception was raised but instead it took me again to App.g.i.cs. In the locals I get this Windows.UI.Xaml.UnhandledExceptionEventArgs and the message string has some information that looks almost like stack trace but has no line numbers. Here is an example of my intentional error:

System.ArgumentOutOfRangeException
   at System.ThrowHelper.ThrowArgumentOutOfRangeException()
   at System.Collections.Generic.List`1.get_Item(Int32 index)
   at StorePuzzle.PuzzleRenderer.HandleTileReleased(Object sender, PointerRoutedEventArgs e)

All I want is Visual Studio to immediately take me to place where the exception is being raised instead of taking me to App.g.i.cs just like it does in "Non Store Apps". Now, that compiler preprocessor directives makes it look like I could just turn it off (#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION) but googleing it has not showed me any way of doing so.


Source: (StackOverflow)

How does Windows 8 Runtime (WinRT / windows store apps / Windows 10 Universal App) compare to Silverlight and WPF? [closed]

I am trying to get my head round the new Windows 8 Runtime that is used to create Metro style apps. I know you can use it with XAML and it is based on .NET so C# and VB.NET can be used to write the apps, but then it seems to have something to do with HTML, CSS, DOM, and JavaScript.

Can someone explain what it is in a few paragraphs, in terms that a .NET UI programmer can understand? (I am missing something “key” that is necessary to understand it)


We all know that WPF and Silverlight and Winforms, etc will keep working under windows 8 (and windows 10) on at least on Intel system, so please don't tell me that...


Source: (StackOverflow)

Advertisements

Thread.Sleep replacement in .NET for Windows Store

Thread.Sleep doesn't seem to be supported in .NET for Windows Store apps.

For example, this

            System.Threading.Thread.Sleep(1000);

will compile when targeting any .NET Framework (2.0, 3.5, 4.0, 4.5), but not when targeting .NET for Windows Store apps (or in a portable class library which targets both 4.5 and store).

System.Threading.Thread is still there, it just doesn't have the Sleep method.

I need to delay something for a few seconds in my app, is there a suitable replacement?

EDIT why the delay is needed: My app is a game and the delay is to make it look like the computer opponent is "thinking" about his next move. The method is already called asynchronously (main thread isn't blocked), I just want to slow the response time down.


Source: (StackOverflow)

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

So, I'm trying to sign a Windows 8 appx package with a pfx file I have. I'm using a command like so:

signtool.exe sign /fd sha256 /f "key.pfx" "app.appx"

And from this, I get:

SignTool Error: No certificates were found that met all the given criteria.

What "criteria" am I not meeting? This is only for testing so these are self-signed certificates. I've tried importing the key and then signing it, but it always results in the same error. How do I fix this?


Source: (StackOverflow)

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Preface: I'm looking for an explanation, not just a solution. I already know the solution.

Despite having spent several days studying MSDN articles about the Task-based Asynchronous Pattern (TAP), async and await, I'm still a bit confused about some of the finer details.

I'm writing a logger for Windows Store Apps, and I want to support both asynchronous and synchronous logging. The asynchronous methods follow the TAP, the synchronous ones should hide all this, and look and work like ordinary methods.

This is the core method of asynchronous logging:

private async Task WriteToLogAsync(string text)
{
    StorageFolder folder = ApplicationData.Current.LocalFolder;
    StorageFile file = await folder.CreateFileAsync("log.log",
        CreationCollisionOption.OpenIfExists);
    await FileIO.AppendTextAsync(file, text,
        Windows.Storage.Streams.UnicodeEncoding.Utf8);
}

Now the corresponding synchronous method...

Version 1:

private void WriteToLog(string text)
{
    Task task = WriteToLogAsync(text);
    task.Wait();
}

This looks correct, but it does not work. The whole program freezes forever.

Version 2:

Hmm.. Maybe the task was not started?

private void WriteToLog(string text)
{
    Task task = WriteToLogAsync(text);
    task.Start();
    task.Wait();
}

This throws InvalidOperationException: Start may not be called on a promise-style task.

Version 3:

Hmm.. Task.RunSynchronously sounds promising.

private void WriteToLog(string text)
{
    Task task = WriteToLogAsync(text);
    task.RunSynchronously();
}

This throws InvalidOperationException: RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.

Version 4 (the solution):

private void WriteToLog(string text)
{
    var task = Task.Run(async () => { await WriteToLogAsync(text); });
    task.Wait();
}

This works. So, 2 and 3 are the wrong tools. But 1? What's wrong with 1 and what's the difference to 4? What makes 1 cause a freeze? Is there some problem with the task object? Is there a non-obvious deadlock?

Please help me understand.


Source: (StackOverflow)

Is it possible to await an event instead of another async method?

In my C#/XAML metro app, there's a button which kicks off a long-running process. So, as recommended, I'm using async/await to make sure the UI thread doesn't get blocked:

private async void Button_Click_1(object sender, RoutedEventArgs e) 
{
     await GetResults();
}

private async Task GetResults()
{ 
     // Do lot of complex stuff that takes a long time
     // (e.g. contact some web services)
  ...
}

Occasionally, the stuff happening within GetResults would require additional user input before it can continue. For simplicity, let's say the user just has to click a "continue" button.

My question is: how can I suspend the execution of GetResults in such a way that it awaits an event such as the click of another button?

Here's an ugly way to achieve what I'm looking for: the event handler for the continue" button sets a flag...

private bool _continue = false;
private void buttonContinue_Click(object sender, RoutedEventArgs e)
{
    _continue = true;
}

... and GetResults periodically polls it:

 buttonContinue.Visibility = Visibility.Visible;
 while (!_continue) await Task.Delay(100);  // poll _continue every 100ms
 buttonContinue.Visibility = Visibility.Collapsed;

The polling is clearly terrible (busy waiting / waste of cycles) and I'm looking for something event-based.

Any ideas?

Btw in this simplified example, one solution would be of course to split up GetResults() into two parts, invoke the first part from the start button and the second part from the continue button. In reality, the stuff happening in GetResults is more complex and different types of user input can be required at different points within the execution. So breaking up the logic into multiple methods would be non-trivial.


Source: (StackOverflow)

Where do I mark a lambda expression async?

I've got this code:

private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
    CheckBox ckbx = null;
    if (sender is CheckBox)
    {
        ckbx = sender as CheckBox;
    }
    if (null == ckbx)
    {
        return;
    }
    string groupName = ckbx.Content.ToString();

    var contextMenu = new PopupMenu();

    // Add a command to edit the current Group
    contextMenu.Commands.Add(new UICommand("Edit this Group", (contextMenuCmd) =>
    {
        Frame.Navigate(typeof(LocationGroupCreator), groupName);
    }));

    // Add a command to delete the current Group
    contextMenu.Commands.Add(new UICommand("Delete this Group", (contextMenuCmd) =>
    {
        SQLiteUtils slu = new SQLiteUtils();
        slu.DeleteGroupAsync(groupName); // this line raises Resharper's hackles, but appending await raises err msg. Where should the "async" be?
    }));

    // Show the context menu at the position the image was right-clicked
    await contextMenu.ShowAsync(args.GetPosition(this));
}

...that Resharper's inspection complained about with, "Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call" (on the line with the comment).

And so, I prepended an "await" to it but, of course, I then need to add an "async" somewhere, too - but where?


Source: (StackOverflow)

How to uninstall an app that another user installed?

I keep hitting this problem when I try to debug my Windows 8 apps and there is a copy already installed on another user account:

DEP0700 : Registration of the app failed. Another user has already installed a packaged version of this app. An unpackaged version cannot replace this. The conflicting package is {{{PackageName}}} and it was published by CN={{{Certificate Stuff}}}. (0x80073cf9)

Sometimes I can just log in or ask someone else to log in to the machine and uninstall the app. Alternatively I can change the application name/id, but one is not always possible and the other is risky (I don't want to check in the changed application id to source control).

There must be some way to uninstall it. Maybe a PowerShell script?


Source: (StackOverflow)

What must I do to make my methods awaitable?

How can I roll my own async awaitable methods?

I see that writing an async method is easy as pie in some cases:

private async Task TestGeo()
{
    Geolocator geo = new Geolocator();
    Geoposition pos = await geo.GetGeopositionAsync();
    double dLat = pos.Coordinate.Latitude;
    double dLong = pos.Coordinate.Latitude;
}

...but sadly also see that not just any method can be made async willy-nilly, though; to wit: this doesn't work:

private async Task TestAsyncAwait()
{
    int i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5);
}

...it stops me with the compile error, "Cannot await int"; a hint at design time similarly tells me, "type 'int' is not awaitable"

I also tried this with the same results:

    Task<int> i = await TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5);

What must I do to make my methods awaitable?

UPDATE

As Linebacker and S. Cleary indicated (any relation to that cat who used to be on KNBR?), this works:

int i = await Task.Run(() => TaSLs_Classes.TASLsUtils.GetZoomSettingForDistance(5));

...that is to say, it compiles -- but it never "moves."

At runtime, it tells me I should "await" the CALL to TestAsyncAwait(), but if I do that, it doesn't compile at all...


Source: (StackOverflow)

How does WinRT handle BitmapImage and Image memory

I am new to programming Windows Store Apps with C# and I am trying to understand how image memory is handled. My app is very simple:

1) it references a bitmap from a file using a Windows.UI.Xaml.Media.Imaging.BitmapImage object and then uses that as the Source for a Windows.UI.Xaml.Controls.Image object. In my case the image on disk has larger dimensions than what is being displayed on screen so it is being scaled by the system.

My question is how does WinRT handle the memory for the image? I used the vmmap tool and I see in the Mapped File section there is an entry for my image file. I guess this means that the raw bytes for this file are fully loaded into memory. Since this is a JPG these bytes must be decoded into pixel bytes. It seems from my tests that setting the UriSource of the BitmapImage doesn't actually cause any processing to take place since it takes 0 ms and that instead there is some lazy loading going on.

So the questions are: Which object is dominator of the the uncompressed unscaled pixel data? What object is the dominator for the scaled pixel data that gets drawn on screen? Are there tools that can easily show me this? In the Java world I use the Eclipse memory analyzer tool. I tried using PerfView but the results make no sense to me, it seems the tool was meant for analyzing performance.

UPDATE:

At the BUILD conference the team discussed the Windows Performance Toolkit. I never heard anyone mention PerfView so I believe that WPT is the latest and greatest tool for analyzing memory and performance, here is a link:

http://msdn.microsoft.com/en-us/performance/cc825801.aspx


Source: (StackOverflow)

Am I right to ignore the compiler warning for lacking await for this async call?

I have the following method that is triggered when an exception occurs in a part of my Metro application

void Model_ExceptionOccured(Exception ex)
{
    var dlg = new Windows.UI.Popups.MessageDialog("An exception occured during verification: " + ex.Message, "Exception");
    dlg.ShowAsync();
}

The 'dlg.ShowAsync()'-call is asynchronous, but I don't care to wait for the result. The compiler generates a warning for it though:

Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call.

Should I care? Is there any reason I should add the await keyword, other than to get rid of the warning?


Source: (StackOverflow)

Getting content/message from HttpResponseMessage

I'm trying to get content of HttpResponseMessage. It should be: {"message":"Action '' does not exist!","success":false}, but I don't know, how to get it out of HttpResponseMessage.

HttpClient httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.GetAsync("http://****?action=");
txtBlock.Text = Convert.ToString(response); //wrong!

In this case txtBlock would have value:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Vary: Accept-Encoding
  Keep-Alive: timeout=15, max=100
  Connection: Keep-Alive
  Date: Wed, 10 Apr 2013 20:46:37 GMT
  Server: Apache/2.2.16
  Server: (Debian)
  X-Powered-By: PHP/5.3.3-7+squeeze14
  Content-Length: 55
  Content-Type: text/html
}

Source: (StackOverflow)

Choosing between XAML's ListView and GridView in WinRT

The GridView and the ListView in XAML seem to be the same control.

How does a developer choose between the two?


Source: (StackOverflow)

Which local database is suitable for Windows 8 Store Apps?

I'am programming a Windows 8 Store App (Metro Design) with C# and XAML using Visual Studio 2012.

There is no need for a database server with multi user support etc.

I want to store my data in a local database and don't know which database is suitable for my needs. Maybe SQLite? Or are there solutions that fits better for Windows Store Apps and integrates better in Visual Studio?

The app is kind of a calender and the database should store the user data that consists of the dates, tasks and so on.


Source: (StackOverflow)

What is the Windows RT / Windows Store App answer to App.config?

What is the best way to go about reading and writing simple configuration data like we used to use App.config and Web.config <appsettings /> available through ConfigurationManager before, for use within your Windows 8 / Windows RT / Windows Store / Windows Modern UI App?


Source: (StackOverflow)