EzDevInfo.com

windows-phone interview questions

Top windows-phone frequently asked interview questions

Want to start with Windows Phone 7 development

As just now, I heard about the Windows Phone 7 development. So I would like to know the following things regarding Windows Phone 7:

  1. From where can I start with Windows Phone 7 development? What are the best books/article/code blog/tutorial, etc.

  2. Which are the tools I should need/download to start with Windows Phone 7 development?

Update:

I found this very much helpful: http://www.devx.com/VS_2010/Article/45898/9851


Source: (StackOverflow)

Reactive Extensions bug on Windows Phone

Compiled with VS 2012, with project type WP 8.0 the following code will fail if debugger is not attached.

Somehow, if debugger not attached, compiler optimizations ruins the code inside Crash() - see comments in code.

Tested on Lumia 1520 (8.1) and Lumia 630 (8.0).

Any ideas why this is occurring?

public partial class MainPage : PhoneApplicationPage
{
    public MainPage()
    {
        InitializeComponent();
        Button.Tap += (sender, args) => new A<B, string>(new B(), "string").Crash();
    }
}
public class B
{
    public void Foo<T>(T val) { }
}
public class A<T1, T2> where T1 : B
{
    private T1 _t1;
    private T2 _t2;
    public A(T1 t1, T2 t2)
    {
        _t2 = t2;
        _t1 = t1;
    }
    public void Crash()
    {
        var obs = Observable.Return(_t2);
        obs.Subscribe(result =>
        {
            //CLR is expecting T2 to be System.String here,
            //but somehow, after passing through Observable
            //T2 here is not a string, it's A<T1, T2>

            new List<T2>().Add(result);
        });
        //Will run normally if commented
        _t1.Foo(new object());
    }
}

Source: (StackOverflow)

Advertisements

Async POST fails on WP7 and F#

When I do let! read = from.AsyncRead buf in F#, it blocks and doesn't return until the TCP socket is dead. Why? And how do I fix it?

Its code:

module StreamUtil

open System.IO

/// copy from 'from' stream to 'toStream'
let (|>>) (from : Stream) (toStream : Stream) =
  let buf = Array.zeroCreate<byte> 1024
  let rec doBlock () =
    async {
      let! read = from.AsyncRead buf
      if read <= 0 then
        toStream.Flush()
        return ()
      else
        do! toStream.AsyncWrite(buf, 0, read)
        return! doBlock () }
  doBlock ()

It's being called from this code:

use fs = new FileStream(targPath, FileMode.CreateNew, FileAccess.ReadWrite)
do! req.InputStream |>> fs

and requested over HTTP with this code from Windows Phone 7.1 emulator:

public void Send()
{
    var b = new UriBuilder(_imageService.BaseUrl) {Path = "/images"};

    var req = WebRequest.CreateHttp(b.Uri);
    req.ContentType = "image/jpeg";
    req.Method = "POST";
    var imgLen = SelectedImage.ImageStream.Length;
    req.Headers[HttpRequestHeader.ContentLength] = imgLen.ToString(CultureInfo.InvariantCulture);
    req.Accept = "application/json";
    req.BeginGetRequestStream(RequestReady, new ReqState(req, imgLen));
}

void RequestReady(IAsyncResult ar)
{
    var state = (ReqState)ar.AsyncState;
    var req = state.Request;

    var reqStream = req.EndGetRequestStream(ar);

    SmartDispatcher.BeginInvoke(() =>
        {
            using (var sw = new StreamWriter(reqStream))
            using (var br = new BinaryReader(SelectedVoucher.ImageStream))
            {
                var readBytes = br.ReadBytes(state.ImgLen);

                // tried both 2
                sw.Write(readBytes);
                //sw.Write(Convert.ToBase64String(readBytes));
                sw.Flush();
                sw.Close();
            }
            req.BeginGetResponse(ResponseReady, req);
        });
}

// WHY U NO GET CALLED???
void ResponseReady(IAsyncResult ar)
{
    try
    {
        var request = (HttpWebRequest)ar.AsyncState;
        var response = request.EndGetResponse(ar);

        SmartDispatcher.BeginInvoke(() =>
            {
                var rdr = new StreamReader(response.GetResponseStream());
                var msg = rdr.ReadToEnd();

                var imageLocation = response.Headers["Location"];

                Debug.WriteLine(msg);
                Debug.WriteLine(imageLocation);
            });
    }
    catch (WebException ex)
    {
        Debug.WriteLine(ex.ToString());
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.ToString());
    }
}

Unsuccessfully. The ResponseReady callback is never reached.

Meanwhile, this code works excellent:

open System
open System.Net.Http // WebAPI nuget

let sync aw = Async.RunSynchronously aw

let postC<'a> (c : HttpClient) (r : Uri) (cont : HttpContent) =
  let response = sync <| Async.AwaitTask( c.PostAsync(r, cont) )
  let struc:'a = sync <| deserialize<'a> response
  response, struc

let withContent<'a> (fVerb : (HttpClient -> Uri -> HttpContent -> _ * 'a))=
  let c = new HttpClient()
  fVerb c

[<Test>]
let ``POST /images 201 + Location header`` () =
  let post = withContent<MyImage> postC
  let bytes = IO.File.ReadAllBytes("sample.jpg")
  let hash = SHA1.Create().ComputeHash(bytes) |> Convert.ToBase64String
  let pic = new ByteArrayContent(bytes)
  pic.Headers.Add("Content-Type", "image/jpeg")
  pic.Headers.Add("X-SHA1-Hash", hash)
  let resp, ri = (resource "/images", pic) ||> post

  resp.StatusCode =? Code.Created
  ri.sha1 =? hash
  mustHaveHeaders resp

I couldn't get Fiddler2 working with WP7.


Source: (StackOverflow)

Windows Phone 8 Startscreen Tile sizes and margins

I was wondering if someone knows the exact measurements of the new Windows Phone 8 Startscreen (for 480x800), i.e. margins (top, left & right, between tiles) and the edge length of all three different tile sizes.


Source: (StackOverflow)

StorageFile 50 times slower than IsolatedStorageFile

I was just benchmarking multiple algorithms to find the fastest way to load all data in my app when I discovered that the WP7 version of my app running on my Lumia 920 loads the data 2 times as fast as the WP8 version running on the same device.

I than wrote the following independent code to test performance of the StorageFile from WP8 and the IsolatedStorageFile from WP7.

To clarify the title, here my preliminary benchmark results I did, reading 50 files of 20kb and 100kb:

enter image description here

For the code, see below

Update

After doing benchmarks for a few hours today and some interesting results, let me rephrase my questions:

  1. Why is await StreamReader.ReadToEndAsync() consistently slower in every benchmark than the non async method StreamReader.ReadToEnd()? (This might already be answered in a comment from Neil Turner)

  2. There seems to be a big overhead when opening a file with StorageFile, but only when it is opened in the UI thread. (See difference in loading times between method 1 and 3 or between 5 and 6, where 3 and 6 are about 10 times faster than the equivalent UI thread method)

  3. Are there any other ways to read the files that might be faster?

Update 3

Well, now with this Update I added 10 more algorithms, reran every algorithm with every previously used file size and number of files used. This time each algorithm was run 10 times. So the raw data in the excel file is an average of these runs. As there are now 18 algorithms, each tested with 4 file sizes (1kb, 20kb, 100kb, 1mb) for 50, 100, and 200 files each (18*4*3 = 216), there were a total of 2160 benchmark runs, taking a total time of 95 minutes (raw running time).

Update 5

Added benchmarks 25, 26, 27 and ReadStorageFile method. Had to remove some text because the post had over 30000 characters which is apparently the maximum. Updated the Excel file with new data, new structure, comparisons and new graphs.

The code:

public async Task b1LoadDataStorageFileAsync()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    //b1 
    for (int i = 0; i < filepaths.Count; i++)
    {
        StorageFile f = await data.GetFileAsync(filepaths[i]);
        using (var stream = await f.OpenStreamForReadAsync())
        {
            using (StreamReader r = new StreamReader(stream))
            {
                filecontent = await r.ReadToEndAsync();
            }
        }
    }
}
public async Task b2LoadDataIsolatedStorage()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = r.ReadToEnd();
                }
            }
        }
    }
    await TaskEx.Delay(0);
}

public async Task b3LoadDataStorageFileAsyncThread()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    await await Task.Factory.StartNew(async () =>
    {
        for (int i = 0; i < filepaths.Count; i++)
        {

            StorageFile f = await data.GetFileAsync(filepaths[i]);
            using (var stream = await f.OpenStreamForReadAsync())
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = await r.ReadToEndAsync();
                }
            }
        }
    });
}
public async Task b4LoadDataStorageFileThread()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    await await Task.Factory.StartNew(async () =>
    {
        for (int i = 0; i < filepaths.Count; i++)
        {

            StorageFile f = await data.GetFileAsync(filepaths[i]);
            using (var stream = await f.OpenStreamForReadAsync())
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = r.ReadToEnd();
                }
            }
        }
    });
}
public async Task b5LoadDataStorageFile()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    //b5
    for (int i = 0; i < filepaths.Count; i++)
    {
        StorageFile f = await data.GetFileAsync(filepaths[i]);
        using (var stream = await f.OpenStreamForReadAsync())
        {
            using (StreamReader r = new StreamReader(stream))
            {
                filecontent = r.ReadToEnd();
            }
        }
    }
}
public async Task b6LoadDataIsolatedStorageThread()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        await Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < filepaths.Count; i++)
                {
                    using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
                    {
                        using (StreamReader r = new StreamReader(stream))
                        {
                            filecontent = r.ReadToEnd();
                        }
                    }
                }
            });
    }
}
public async Task b7LoadDataIsolatedStorageAsync()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = await r.ReadToEndAsync();
                }
            }
        }
    }
}
public async Task b8LoadDataIsolatedStorageAsyncThread()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        await await Task.Factory.StartNew(async () =>
        {
            for (int i = 0; i < filepaths.Count; i++)
            {
                using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        filecontent = await r.ReadToEndAsync();
                    }
                }
            }
        });
    }
}


public async Task b9LoadDataStorageFileAsyncMy9()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    for (int i = 0; i < filepaths.Count; i++)
    {
        StorageFile f = await data.GetFileAsync(filepaths[i]);
        using (var stream = await f.OpenStreamForReadAsync())
        {
            using (StreamReader r = new StreamReader(stream))
            {
                filecontent = await Task.Factory.StartNew<String>(() => { return r.ReadToEnd(); });
            }
        }
    }
}

public async Task b10LoadDataIsolatedStorageAsyncMy10()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        //b10
        for (int i = 0; i < filepaths.Count; i++)
        {
            using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = await Task.Factory.StartNew<String>(() => { return r.ReadToEnd(); });
                }
            }
        }
    }
}
public async Task b11LoadDataStorageFileAsyncMy11()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    for (int i = 0; i < filepaths.Count; i++)
    {
        await await Task.Factory.StartNew(async () =>
            {
                StorageFile f = await data.GetFileAsync(filepaths[i]);
                using (var stream = await f.OpenStreamForReadAsync())
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        filecontent = r.ReadToEnd();
                    }
                }
            });
    }
}

public async Task b12LoadDataIsolatedStorageMy12()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            await Task.Factory.StartNew(() =>
                {
                    using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
                    {
                        using (StreamReader r = new StreamReader(stream))
                        {
                            filecontent = r.ReadToEnd();
                        }
                    }
                });
        }
    }
}

public async Task b13LoadDataStorageFileParallel13()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    List<Task> tasks = new List<Task>();
    for (int i = 0; i < filepaths.Count; i++)
    {
        int index = i;
        var task = await Task.Factory.StartNew(async () =>
        {
            StorageFile f = await data.GetFileAsync(filepaths[index]);
            using (var stream = await f.OpenStreamForReadAsync())
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    String content = r.ReadToEnd();
                    if (content.Length == 0)
                    {
                        //just some code to ensure this is not removed by optimization from the compiler
                        //because "content" is not used otherwise
                        //should never be called
                        ShowNotificationText(content);
                    }
                }
            }
        });
        tasks.Add(task);
    }
    await TaskEx.WhenAll(tasks);
}

public async Task b14LoadDataIsolatedStorageParallel14()
{
    List<Task> tasks = new List<Task>();
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            int index = i;
            var t = Task.Factory.StartNew(() =>
            {
                using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[index], FileMode.Open, store))
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        String content = r.ReadToEnd();
                        if (content.Length == 0)
                        {
                            //just some code to ensure this is not removed by optimization from the compiler
                            //because "content" is not used otherwise
                            //should never be called
                            ShowNotificationText(content);
                        }
                    }
                }
            });
            tasks.Add(t);
        }
        await TaskEx.WhenAll(tasks);
    }
}

public async Task b15LoadDataStorageFileParallelThread15()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    await await Task.Factory.StartNew(async () =>
        {
            List<Task> tasks = new List<Task>();
            for (int i = 0; i < filepaths.Count; i++)
            {
                int index = i;
                var task = await Task.Factory.StartNew(async () =>
                {
                    StorageFile f = await data.GetFileAsync(filepaths[index]);
                    using (var stream = await f.OpenStreamForReadAsync())
                    {
                        using (StreamReader r = new StreamReader(stream))
                        {
                            String content = r.ReadToEnd();
                            if (content.Length == 0)
                            {
                                //just some code to ensure this is not removed by optimization from the compiler
                                //because "content" is not used otherwise
                                //should never be called
                                ShowNotificationText(content);
                            }
                        }
                    }
                });
                tasks.Add(task);
            }
            await TaskEx.WhenAll(tasks);
        });
}

public async Task b16LoadDataIsolatedStorageParallelThread16()
{
    await await Task.Factory.StartNew(async () =>
        {
            List<Task> tasks = new List<Task>();
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                for (int i = 0; i < filepaths.Count; i++)
                {
                    int index = i;
                    var t = Task.Factory.StartNew(() =>
                    {
                        using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[index], FileMode.Open, store))
                        {
                            using (StreamReader r = new StreamReader(stream))
                            {
                                String content = r.ReadToEnd();
                                if (content.Length == 0)
                                {
                                    //just some code to ensure this is not removed by optimization from the compiler
                                    //because "content" is not used otherwise
                                    //should never be called
                                    ShowNotificationText(content);
                                }
                            }
                        }
                    });
                    tasks.Add(t);
                }
                await TaskEx.WhenAll(tasks);
            }
        });
}
public async Task b17LoadDataStorageFileParallel17()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    List<Task<Task>> tasks = new List<Task<Task>>();
    for (int i = 0; i < filepaths.Count; i++)
    {
        int index = i;
        var task = Task.Factory.StartNew<Task>(async () =>
        {
            StorageFile f = await data.GetFileAsync(filepaths[index]);
            using (var stream = await f.OpenStreamForReadAsync())
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    String content = r.ReadToEnd();
                    if (content.Length == 0)
                    {
                        //just some code to ensure this is not removed by optimization from the compiler
                        //because "content" is not used otherwise
                        //should never be called
                        ShowNotificationText(content);
                    }
                }
            }
        });
        tasks.Add(task);
    }
    await TaskEx.WhenAll(tasks);
    List<Task> tasks2 = new List<Task>();
    foreach (var item in tasks)
    {
        tasks2.Add(item.Result);
    }
    await TaskEx.WhenAll(tasks2);
}

public async Task b18LoadDataStorageFileParallelThread18()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");

    await await Task.Factory.StartNew(async () =>
    {
        List<Task<Task>> tasks = new List<Task<Task>>();
        for (int i = 0; i < filepaths.Count; i++)
        {
            int index = i;
            var task = Task.Factory.StartNew<Task>(async () =>
            {
                StorageFile f = await data.GetFileAsync(filepaths[index]);
                using (var stream = await f.OpenStreamForReadAsync())
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        String content = r.ReadToEnd();
                        if (content.Length == 0)
                        {
                            //just some code to ensure this is not removed by optimization from the compiler
                            //because "content" is not used otherwise
                            //should never be called
                            ShowNotificationText(content);
                        }
                    }
                }
            });
            tasks.Add(task);
        }
        await TaskEx.WhenAll(tasks);
        List<Task> tasks2 = new List<Task>();
        foreach (var item in tasks)
        {
            tasks2.Add(item.Result);
        }
        await TaskEx.WhenAll(tasks2);
    });
}
public async Task b19LoadDataIsolatedStorageAsyncMyThread()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        //b19
        await await Task.Factory.StartNew(async () =>
        {
            for (int i = 0; i < filepaths.Count; i++)
            {
                using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        filecontent = await Task.Factory.StartNew<String>(() => { return r.ReadToEnd(); });
                    }
                }
            }
        });
    }
}

public async Task b20LoadDataIsolatedStorageAsyncMyConfigure()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
            {
                using (StreamReader r = new StreamReader(stream))
                {
                    filecontent = await Task.Factory.StartNew<String>(() => { return r.ReadToEnd(); }).ConfigureAwait(false);
                }
            }
        }
    }
}
public async Task b21LoadDataIsolatedStorageAsyncMyThreadConfigure()
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        await await Task.Factory.StartNew(async () =>
        {
            for (int i = 0; i < filepaths.Count; i++)
            {
                using (var stream = new IsolatedStorageFileStream("/benchmarks/samplefiles/" + filepaths[i], FileMode.Open, store))
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        filecontent = await Task.Factory.StartNew<String>(() => { return r.ReadToEnd(); }).ConfigureAwait(false);
                    }
                }
            }
        });
    }
}
public async Task b22LoadDataOwnReadFileMethod()
{
    await await Task.Factory.StartNew(async () =>
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            filecontent = await ReadFile("/benchmarks/samplefiles/" + filepaths[i]);

        }
    });

}
public async Task b23LoadDataOwnReadFileMethodParallel()
{
    List<Task> tasks = new List<Task>();

    for (int i = 0; i < filepaths.Count; i++)
    {
        int index = i;
        var t = ReadFile("/benchmarks/samplefiles/" + filepaths[i]);
        tasks.Add(t);
    }
    await TaskEx.WhenAll(tasks);

}
public async Task b24LoadDataOwnReadFileMethodParallelThread()
{
    await await Task.Factory.StartNew(async () =>
        {
            List<Task> tasks = new List<Task>();

            for (int i = 0; i < filepaths.Count; i++)
            {
                int index = i;
                var t = ReadFile("/benchmarks/samplefiles/" + filepaths[i]);
                tasks.Add(t);
            }
            await TaskEx.WhenAll(tasks);

        });
}


public async Task b25LoadDataOwnReadFileMethodStorageFile()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    await await Task.Factory.StartNew(async () =>
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            filecontent = await ReadStorageFile(data, filepaths[i]);

        }
    });

}
public async Task b26LoadDataOwnReadFileMethodParallelStorageFile()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    List<Task> tasks = new List<Task>();

    for (int i = 0; i < filepaths.Count; i++)
    {
        int index = i;
        var t = ReadStorageFile(data, filepaths[i]);
        tasks.Add(t);
    }
    await TaskEx.WhenAll(tasks);

}
public async Task b27LoadDataOwnReadFileMethodParallelThreadStorageFile()
{
    StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    data = await data.GetFolderAsync("samplefiles");
    await await Task.Factory.StartNew(async () =>
    {
        List<Task> tasks = new List<Task>();

        for (int i = 0; i < filepaths.Count; i++)
        {
            int index = i;
            var t = ReadStorageFile(data, filepaths[i]);
            tasks.Add(t);
        }
        await TaskEx.WhenAll(tasks);

    });
}

public async Task b28LoadDataOwnReadFileMethodStorageFile()
{
    //StorageFolder data = await ApplicationData.Current.LocalFolder.GetFolderAsync("benchmarks");
    //data = await data.GetFolderAsync("samplefiles");
    await await Task.Factory.StartNew(async () =>
    {
        for (int i = 0; i < filepaths.Count; i++)
        {
            filecontent = await ReadStorageFile(ApplicationData.Current.LocalFolder, @"benchmarks\samplefiles\" + filepaths[i]);

        }
    });

}

public async Task<String> ReadStorageFile(StorageFolder folder, String filename)
{
    return await await Task.Factory.StartNew<Task<String>>(async () =>
    {
        String filec = "";
        StorageFile f = await folder.GetFileAsync(filename);
        using (var stream = await f.OpenStreamForReadAsync())
        {
            using (StreamReader r = new StreamReader(stream))
            {
                filec = await r.ReadToEndAsyncThread();
            }
        }
        return filec;
    });
}

public async Task<String> ReadFile(String filepath)
{
    return await await Task.Factory.StartNew<Task<String>>(async () =>
        {
            String filec = "";
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = new IsolatedStorageFileStream(filepath, FileMode.Open, store))
                {
                    using (StreamReader r = new StreamReader(stream))
                    {
                        filec = await r.ReadToEndAsyncThread();
                    }
                }
            }
            return filec;
        });
}

How these benchmarks are run:

public async Task RunBenchmark(String message, Func<Task> benchmarkmethod)
    {
        SystemTray.ProgressIndicator.IsVisible = true;
        SystemTray.ProgressIndicator.Text = message;
        SystemTray.ProgressIndicator.Value = 0;
        long milliseconds = 0;

        Stopwatch w = new Stopwatch();
        List<long> results = new List<long>(benchmarkruns);
        for (int i = 0; i < benchmarkruns; i++)
        {
            w.Reset();
            w.Start();
            await benchmarkmethod();
            w.Stop();
            milliseconds += w.ElapsedMilliseconds;
            results.Add(w.ElapsedMilliseconds);
            SystemTray.ProgressIndicator.Value += (double)1 / (double)benchmarkruns;
        }

        Log.Write("Fastest: " + results.Min(), "Slowest: " + results.Max(), "Average: " + results.Average(), "Median: " + results[results.Count / 2], "Maxdifference: " + (results.Max() - results.Min()),
                  "All results: " + results);


        ShowNotificationText((message + ":").PadRight(24) + (milliseconds / ((double)benchmarkruns)).ToString());
        SystemTray.ProgressIndicator.IsVisible = false;
    }

Benchmark results

Here a link to the raw benchmark data: http://www.dehodev.com/windowsphonebenchmarks.xlsx

Now the graphs (every graph shows the data for loading 50 via each method, results are all in milliseconds)

1kb file size benchmarks

The next benchmarks with 1mb are not really representative for apps. I include them here to give a better overview on how these methods scale.

enter image description here

So to sum it all up: The standard method used to read files (1.) is always the worst (except in the case you want to read 50 10mb files, but even then there are better methods).


I'm also linking this: await AsyncMethod() versus await await Task.Factory.StartNew<TResult>(AsyncMethod), where it is argued that normally it is not useful to add a new task. However the results I'm seeing here are that you just can't asume that and should always check if adding a task improves performance.

And last: I wanted to post this in the official Windows Phone developer forum but everytime I try, I get an "Unexpected Error" message...

Update 2

Conclusions:

After reviewing the data you can clearly see that no matter the file size every algorithm scales linear to the number of files. So to simplify everything we can ignore the number of files (we will just use the data for 50 files in future comparisons).

Now on to file size: File size is important. We can see that when we increase the file size the algorithms begin to converge. At 10MB file size the previous slowest algorithm takes place 4 of 8. However because this question primarily deals with phones it’s incredibly rare that apps will read multiple files with this much data, even 1MB files will be rare for most apps. My guess is, that even reading 50 20kb files is uncommon. Most apps are probably reading data in the range of 10 to 30 files, each the size of 0.5kb to 3kb. (This is only a guess, but I think it might be accurate)


Source: (StackOverflow)

Device Unique id in Windows Phone 8.1

How to get the device unique id in Windows Phone 8.1? The old way of using DeviceExtendedProperties.GetValue("DeviceUniqueId") does not work for Windows Universal app.


Source: (StackOverflow)

Prevent scrolling out of CordovaView in Cordova for Windows Phone 8

In a Windows Phone 8 Cordova application I'm able to click and drag horizontally in the app and pan/scroll past the horizontal edge of the display. See the Cordova Windows Phone 8 standalone template application:

Panning horizontally past the edge of the Cordova app

The HTML behind this template application has a proper viewport specification, as far as I can see:

<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />

This bug prevents any kind of swipe gesture detection from being useful. The iOS UIScrollView control has a bounces property that allows a somewhat similar effect to be canceled.

Is this a Cordova bug? Is there some setting that can be placed on the container of the Cordova WebBrowser such that this panning can't happen?


Source: (StackOverflow)

Windows Phone 8.1 Universal App terminates on navigating back from second page?

I have 2 pages in my Windows Phone 8.1 Universal App.

I navigate from Page1.xaml to Page2.xaml by using a button with the click event code:

this.Frame.Navigate(typeof(Page2));

When I am on Page2, and I use the hardware back button the app closes without an exception or anything. It just returns to the startscreen.

I already tried the following on Page 2:

public Page2()
    {
        this.InitializeComponent();
        Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
    }

    void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
    {
        Frame.GoBack();
    }

As far as I know I do not clear the back stack.

What is going on, and how can I fix this?

Kind regards, Niels


Source: (StackOverflow)

Deleting project/pages/usercontrols from memory

I have made a windows phone app, that unfortunately has some memory leak, because pages are not removed correctly. This was solved by using the answer:

Remove Pages windows phone Stating:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
while (App.RootFrame.RemoveBackEntry() != null) ; //line if you navigate without backkey
base.OnNavigatedTo(e);

this.Dispatcher.BeginInvoke(() =>
{
    GC.Collect();
    GC.WaitForPendingFinalizers();

    this.Dispatcher.BeginInvoke(() =>
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();

        this.Dispatcher.BeginInvoke(() =>
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        });
    });

}

This removed the page references from the profiler. But the memory still increased some upon navigation. And it was not obvious where the increased memory came from. I therefore Tried introducing a blank project and navigated to that as a star navigation, Illustrated as:

enter image description here

This made removed upwards of 20 mb, of visuals and other elements. So this was a major step. I therefore wanted to split functionality out onto different projects as to remove any ties between the different functionalities and keep low memory usage. This ended up with the following structure:

  • WebService
  • MainProject
  • SecondaryProject
  • PortableLibrary

I share models between all projects using the Portable Library. This influenced that upon every navigation to a new project everything is cleared in the old project, i.e. only one element of each item exist, major memory improvement. But still some memory leak, however bounded, meaning only a certain increase in memory. But where comes the memory from? Going back into the profiler:

enter image description here

This shows that the pages are not removed specifically, all elements .view. would have been removed by the code in the configuration of all pages being in one project. However the memory leak is similar.

The Question

  1. How do I remove pages and elements from a different project within the same solution?
  2. How do I remove a project from memory?

There is not information shared between the two projects, other than they both can create a version of LibraryOfModels. Therefore no events, variables or references is shared across the project borders. But for the life of me I cannot get it removed from memory. I want to remove them from the memory, as my code snippet in the top does, IF the navigation was only within one project. The issue exists because of the navigation is spread out on two projects. But it has some memory benefits in other areas, which is why I want this structure.

Hope somebody can help. Thx!

Additional tests

I have tried making all pages usercontrols such that I could avoid navigation. But recreating them a couple of times gav a steady leak of 1-2 Mb. The project idea is therefore still best as there is a bound. But still no solution of getting it removed.

Still hoping for the knight with the shiney keyboard ;)


Source: (StackOverflow)

How to pass values (parameters) between XAML pages?

Similar questions have been asked before but this question strives to explore more options and the ability to pass complex objects.

The question is how to pass parameters but it really needs to be broken up into three parts..

  1. When navigating between pages in an XAML application how do you pass parameters?
  2. What is the difference between using the Uri navigation and manual navigation?
  3. How can objects (not just strings) be passed when using Uri navigation?

Example of Uri navigation

page.NavigationService.Navigate(new Uri("/Views/Page.xaml", UriKind.Relative));

Example of manual navigation

page.NavigationService.Navigate(new Page());

The answer to this question applies to WP7, silverlight, WPF and Windows 8.

Note: There is a difference between Silverlight and Windows8

  • Windows Phone: pages are navigated to using a Uri and data passed as a query string or an instance
  • Windows 8: pages are navigated to by passing the type, and parameters as objects

Source: (StackOverflow)

On Windows Phone's IE Touchstart Event Ends Automatically After Few Seconds

I have a very specific problem. I'm writing a web-page for mobile phones which has a button on it. I'm detecting touchevent on every browser including IE, but on IE it's quite specific. After a few seconds it automatically ends. Can you somehow help me? Here is my code (modified one, but still not working properly):

if (window.navigator.pointerEnabled) {
    tapButton.addEventListener("pointerup", function(e) {
        e.preventDefault();
        addClass(this, 'clicked');
        buttonTouched = true;
    }, false);
    tapButton.addEventListener("pointerdown", function(e) {
        e.preventDefault();
        removeClass(this, 'clicked');
        buttonTouched = false;
    }, false);
    alert("pointerEnabled");
}
else if (window.navigator.msPointerEnabled) {
    tapButton.addEventListener("MSPointerDown", function(e) {
        e.preventDefault();
        addClass(this, 'clicked');
        buttonTouched = true;
    }, false);
    tapButton.addEventListener("MSPointerUp", function(e) {
        e.preventDefault();
        removeClass(this, 'clicked');
        buttonTouched = false;
    }, false);
    alert("mspointerEnabled");
}
else {
    alert("ordinary touch");
    tapButton.addEventListener('touchstart', function(e) {
        e.preventDefault();
        addClass(this, 'clicked');
        buttonTouched = true;
    }, false);
    tapButton.addEventListener('touchend', function(e) {
        e.preventDefault();
        removeClass(this, 'clicked');
        buttonTouched = false;
    }, false);
}

And the html tag has in it:

-ms-touch-action: none !important;
touch-action: none !important;

but that does not help either.


Source: (StackOverflow)

(Dis)Connecting bluetooth devices with Windows.Devices.Bluetooth.Rfcomm (WP8.1)

Connecting and disconnecting to Bluetooth devices has been giving various results on Windows Phone/Desktop 8.1. I have been using the Windows.Devices.Bluetooth.Rfcomm namespace and I have tried to connect several devices with different Bluetooth versions/classes.

  • Version 1.2 (Class 1 and 2)
  • Version 2.0 (Class 1 and 2)
  • Version 2.1 (Class 1 and 2)
  • Tested on Nokia Lumia 625 and Lumia 635, Dell Latitude E6500 and a Dell Precision M6400.

Whenever I try to connect to either of the 2.0 or 2.1 devices there are issues. The first time I try to connect to each of the devices everything will go fine and the connection will open. When I subsequently close the connection and re-connect the device, the trouble starts. During the re-connect the connection will never open and the debugger will throw a System.Exception :

> Message: No further data is available.

Also, when the connection fails the Windows 8.1 devices will keep trying to (unsuccessfully) connect to the Bluetooth Devices by themselves, even when my own application is terminated. Sometimes the Windows 8.1 device will also show the Bluetooth device as connected, while the device visually shows that it's not connected anymore. The only way to reconnect the Bluetooth device is to unpair it and shutdown/restart Bluetooth on the Windows device.

Whenever I try to make a new call to DeviceInformation after a failed connect it will refuse to return the device that I earlier tried to connect.

> Message: The service cannot be found in the specified name space.

Odd result, the 1.2 devices work perfectly.

Manifest File:

<m2:DeviceCapability Name="bluetooth.rfcomm">
  <m2:Device Id="any">
    <m2:Function Type="serviceId:00001101-0000-1000-8000-00805F9B34FB"/>
  </m2:Device>
</m2:DeviceCapability>

Selecting Device:

Guid RfcommChatServiceUuid = Guid.Parse("00001101-0000-1000-8000-00805F9B34FB");
await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid)));

Connecting:(id = chatserviceid)

StreamSocket _socket;    
RfcommDeviceService service = await RfcommDeviceService.FromIdAsync(deviceInformation1._id);
await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);

Disconnecting:

this._socket.Dispose();
this._socket = null;

I've researched the MSDN, code samples, demo's, channel-9 video's and StackOverflow, no resource can tell me if there are issues with Windows.Devices.Bluetooth.Rfcomm.

Is there someone who recognizes these odd results? Am I doing something wrong?

UPDATE: Working with Windows Phone 8.1 GDR2 is a possible solution.

NOTE: For myself and several other people this update still gives the same issues.


Source: (StackOverflow)

Windows Phone 8: How to animate page navigation?

I am new to Win Phone 8 development and after a tiresome unfruitful Googling, I am posting this simple question here:

How to animate page navigation?

Yes, I know how to navigate from one page to another:

NavigationService.Navigate(new Uri("/AnotherPage.xaml", UriKind.Relative));

But this navigation is instant, and doesn't include any kind of transition. Please help SO!


Source: (StackOverflow)

Sell Windows Phone 7 Apps outside of App Hub

Is it possible to (legally) sell WP7 apps outside of Microsoft's App Hub? Are there license restrictions to this? Is it ideal to even approach app distribution in such a manner (i.e., are there other sites/services that are easily accessible by WP7 users to find new apps).


Source: (StackOverflow)

Windows phone 8 emulator debugging doesn't work

Error: a specified communication resource (port) is already in use by another application

  • This happens only on the Hyper-V emulator, old, 7.1 emulator works fine.
  • Deployment from Blend 2012 works fine.
  • Deleting the virtual machines in Hyper-V manager doesn't help
  • Deleting the %user%\AppData\Local\Microsoft\Phone Tools\CoreCon doesn't help

My output is:

1>------ Deploy started: Project: Proj1, Configuration: Debug Any CPU ------
1>Deploying C:\Users\Валентин\Projects\Proj1\Bin\Debug\Proj1.xap...
1>Connecting to Emulator WVGA 512MB...
1>The application is already installed on the device. Checking if an incremental deployment is possible...
1>Doing incremental deployment...
1>Updating information related to modified files...
1>Deployment of C:\Users\Валентин\Projects\Proj1\Bin\Debug\Proj1.xap succeeded.
========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========

Last status bar message:

Launching TaskHost.exe failed 

I'm using VS2012 express for WP, WP 7.1 project on WP8 emulator, Windows 8 64 bit.

The curious part is that it worked fine earlier, but for some reason stopped working today.

Please share your ideas.


Source: (StackOverflow)