Tag Archives: C#

Tips Windows Phone 7/8

Enum.GetValues for Windows Phone (and portable libraries)

Windows Phone is missing quite a lot of different things, but I never figured it would be missing something as basic as Enum.GetValues. Since I need it (obviously for my current top secret project), I just went ahead and wrote a replacement. Also, since the original returned Array, I figured that the new and improved method should be much better and that it should return IEnumerable where T should be the enumeration type. It makes code a lot prettier.

So, without further ado, here is the final code:

public static IEnumerable<T> GetValues<T>()
{
    if (!typeof(T).IsEnum)
        throw new InvalidOperationException("Type must be enumeration type.");

    return GetValues_impl<T>();
}

private static IEnumerable<T> GetValues_impl<T>()
{
    return from field in typeof(T).GetFields()
            where field.IsLiteral && !string.IsNullOrEmpty(field.Name)
            select (T)field.GetValue(null);
}

It couldn’t be implemented as an extension method since you cannot define extension methods on a type. You have full freedom to implement this method in e.g. EnumHelpers class. I am also aware that this method has no caching whatsoever implemented and that you will need to do that in case you are using it in highly performant code, but this will suffice for basic daily needs.

Happy coding.

Windows 8 Windows Phone 7/8

Async, portable libraries and Windows Phone 7 in Visual Studio 2012

Windows phone topic Portable classes in Visual Studio 2012 are simply awesome. They allow high code reuse for multiple platforms. Another great addition in Visual Studio 2012 is support for asynchronous programming in C# 5 which, sadly, was not initially available for Windows Phone 7 developers.

If you want to target Windows Phone 8 and Windows Store, you can use Async if you also target .NET 4.5. If you want to target Windows Phone 7.1 and Windows Store, you cannot use asynchronous features from C# 5. But with the prerelease version of Async for .NET Framework 4, Silverlight 4 and 5, and Windows Phone 7.5 and 8 you can finally use Async in your Windows Phone 7 applications. If you want to target largest market, you need to support Windows Phone 7 along with Windows Phone 8, it is too large to simply ignore.

So, can we use Async in portable libraries while still targeting both Windows Phone 7 and Windows Store? Luckily, the answer is yes. But, and there is always a but, with one caveat – you must target .NET 4.0 instead of .NET 4.5.

The procedure is simple: create a new Portable Class Library and select the targets as seen on the image below:

Targets for Portable Class Library project

Portable Class Library targets

To add Async support, run the following command in the Package Manager Console:

Install-Package Microsoft.Bcl.Async -Pre

Voila, you can now write asynchronous code in a portable class library which can then be linked in Windows Phone 7, Windows Phone 8 and Windows Store projects. If you build a Windows Phone 7 application and link to such portable class library, you will need to add the same NuGet package to that project also.

Development

Thoughts on commenting asynchronous functions in C#

While I was wrapping up my asynchronous extension methods library, I realized that to be useful, all methods should have proper documentation. Since the number of extension methods wasn’t really large, I’d decided to add it. After all, how hard can it be? It is practically already properly documented since all I did was wrapping EAP pattern (MethodAsync function with MethodCompleted event) and the original functions were documented. But extracting proper commenting style that is both complete and consistent was actually harder you would expect it to be.

I will go through several items that needed to be commented with explanation why particular commenting style was used. If you are using some other style, please don’t hesitate from leaving a comment. read more »

Windows Phone 7/8

Using SignalR on Windows Phone 7

Windows phone topic If you need real time communication between two or more clients and you are using Microsoft stack, SignalR is the way to go. If you take a look at their github samples, you’ll notice that they already have sample for Windows Phone 8. What about Windows Phone 7 support? Well, due to the beauty of open source, you simply fork it and write the missing client library.

However, this might not be as easy as one thinks. Open the Microsoft.AspNet.SignalR.sln solution and locate Microsoft.AspNet.SignalR.Client.WP8. If you take a closer look, you’ll notice that this project consists only of linked files shared with other client libraries. So let’s add a new project and name it Microsoft.AspNet.SignalR.Client.WP7 (although it would be better to name it 7.1 or 7.5). Now drag all files and folders from the WP8 project to the WP7 project while holding down the Alt key. This adds files as links instead adding their copies. Once you are done, hit Compile.

It won’t compile you say. Of course it won’t, so let’s fix it. read more »

Tips Windows Phone 7/8

Naive HashSet implementation for Windows Phone 7

Windows phone topic HashSet<T> is a nifty little class that is, sadly, missing from Windows Phone 7. Since I need it in some of my projects, I made this simple and naive implementation that is compatible with Windows Phone 8 version of it. This will make the code sharable between Windows Phone 7 and Windows Phone 8 projects.

It is implemented as a naive wrapper around Dictionary<T, bool>. I really hope that Windows Phone 7.8 will have (better) native implementation. You can check out the implementation over at GitHub.

You can also get it as package from NuGet:
PM> Install-Package WP7Helpers.Common.HashSet

Windows Phone 7/8

WP8 XAML and DirectX app crashes when adding navigation

Windows phone topic Creating applications from default templates without understanding them might introduce serious bugs in your application. Consider the simple Windows Phone XAML and Direc3D App project template. Let’s create basic app and pretend we are building a new game. We probably want to add some other XAML pages e.g. for settings, high scores, about dialog, etc.

I will first add simple button with caption “High scores” to the bottom of MainPage using the following XAML:

<Button Content="High scores"
        HorizontalAlignment="Center"
        VerticalAlignment="Bottom"
        Click="_btnHighScores_Click" />

The application looks simple enough so far. read more »

Thought crime

I wish that C#…doesn’t throw when iterating over null collection

Consider the following code:

List<string> list = null;
foreach (var element in list)
  //... NullReferenceException above

Boom, in your face! We want to go through all elements in the nonexisting collection. Not empty, but nonexisting. While you may argue that semantically there is some difference, when do you actually want that exception to blow up? Fix is easy, but ugly:

if (list != null)
{
    foreach (var element in list)
        //
}

One way to implement this would be to allow a compiler flag that will expand foreach (var element in list) into:

if (list != null)
    foreach (var element in list)

This is the same question as before: should you ever return null collections.

My answer is no, forget the null and make code prettier :)

Windows 8

DirectX and XAML in Windows (Phone) 8 – part 2 of N – WinRT component and C# integration

This entry is part of a series, DirectX and XAML»

In the previous post I have created a basic Windows 8 application featuring both DirectX and XAML. However, the sample was written in C++/CX and there aren’t any project templates for writing applications with both XAML and DirectX since the latter one is exposed only in C++. Luckily, there is a way for you to write C++ code that deals with DirectX which you could then reference in C#/VB – by creating WinRT component.

Creating an WinRT component

You can create Windows Runtime components in either C++ or your favorite managed language. Start Visual Studio and create new project with Visual C++/Windows Store/Windows Runtime Component. Delete the sample class created by the template (seen on the image below).
read more »

Thought crime

Why you should (almost) never write void asynchronous methods?

I came across this interesting post by Christian Jacobsen titled async/await in C# – a disaster waiting to happen? in which he describes that simple refactoring can introduce serious bugs in async code. While there is definitely something to be said about possible problems with the new Async feature, his example can teach us something.

I will borrow his code to illustrate the point:

async void AcquireFromCamera(object sender, RoutedEventArgs e)
{
    try
    {
        var imageStream = await _cameraCapture.Shoot();
        var dto = new Dto(){ImageStream = imageStream};
        _handler.ImageCaptured(dto);
        Frame.Navigate(typeof(EditDataPage), dto.Id);
    }
    catch (Exception ex)
    {
        new MessageDialog(ex.Message).ShowAsync();
    }
}

async void ImageCaptured(Dto dto)
{
    dto.Id = Guid.NewGuid().ToString();
    var file = await _fileHndlr.CreateFileAsync(dto.Id);
    dto.ImageFilePath = file.Path;
    _fileOperator.StoreStream(dto.ImageStream, file);
    SaveNewDataItem(dto);
    var dataItem = dataSource.GetItem(dto.Id);
    StoreData(dataItem);
}

Christiansen argues that this is a buggy piece of software since the AcquireFromCamera method calls ImageCaptured as if it was a synchronous method. And he is right since both methods are non-returning. This usage of asynchrony is called fire and forget.

To fix this one needs to change the return type from void to Task and the compiler will now warn you with the following warnings:

warning CS4014: 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.

Void returning asynchronous methods are called fire and forget simply because you don’t need to know when they complete, you initiate them and that is it. The code above requires the ImageCaptured function to complete before continuing and for that you need to await it.

Change the return type for all asynchronous methods from void to Task or Task<T>. If the asynchronous method does not return any value, use Task. If it returns an instance of type T, use Task<T>.

So which methods can be both void and async? Only event handlers since the caller does not need to know when the method completes.

Windows Phone 7/8

Basic Facebook integration for your Windows Phone 7 application

Windows phone topic Facebook is unavoidable social engagement tool. If you are building a Windows Phone 7 application for a certain event, celebrity or anything that has a associated Facebook page, you should consider adding some sort of engagement with it in the app. One example is adding the most recent posts in some format to your client application. However, you cannot simply retrieve data from Facebook publicly, calls need to be authenticated first and for that we need to create a Facebook application first.

This post will show how to fetch the most recent posts from the page using only RestSharp. If you are building something more complicated with more integration, consider using this awesome library – Facebook C# SDK.

You can do that on the Facebook developers/Apps page and click Create New App and give your application a name. For the testing purposes, use some random app name. Creating new Facebook application read more »