Tag Archives: windows phone

BOMbin’ the L (aka Wierd Errors with XmlWriter)

[Title from a track on Come Find Yourself– Fun Lovin’ Criminals]

Have you experienced strange errors when working with XML generated by an XMLWriter? If so, this post may be helpful to you. I just spent a few hours trying to figure out why I was getting a weird error when I was sending some XML to the Windows Azure Notification Hubs client api (post on that coming up, just as soon as I have my sample working).

There’s a page here Get Started with Notification Hubs with tutorials on using this technology with Windows Store C#, Windows Phone, Android and iOS clients. In the Windows Phone tutorial, it walks through creating a Windows Phone client (needless to say) and a console app which simulates your backend logic that you use to send Tile, Toast or Raw notification messages to the mobile clients. In the instructions for the console app it includes the following:

In your Program class add the following method:

private static async void SendNotificationAsync()
{
    NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString("<connection string with full access>", "<hub name>");
    string toast = "<?xml version="1.0" encoding="utf-8"?>" +
        "<wp:Notification xmlns:wp="WPNotification">" +
           "<wp:Toast>" +
                "<wp:Text1>Hello from a .NET App!</wp:Text1>" +
           "</wp:Toast> " +
        "</wp:Notification>";
    await hub.SendMpnsNativeNotificationAsync(toast);
}

Make sure to insert the name of your hub and the connection string called DefaultFullSharedAccessSignature that you obtained in the section “Configure your Notification Hub.” Note that this is the connection string with Full access, not Listen access.

Then add the following line in your Main method:

SendNotificationAsync();
 Console.ReadLine();

Easy enough! So, using this as my guide, I created my own app that followed these principles, the main difference being that instead of creating a string with the XML payload in it, I thought I’d use an XmlWriter instead, because that’s neater:

        private static string prepareToastPayload(string text1, string text2)
        {
            MemoryStream stream = new MemoryStream();
            XmlWriterSettings settings = new XmlWriterSettings() 
                                            { 
                                                Indent = false,
                                                Encoding = Encoding.UTF8   
                                            };
            XmlWriter writer = XmlWriter.Create(stream, settings);
            writer.WriteStartDocument();
            writer.WriteStartElement("wp", "Notification", "WPNotification");
            writer.WriteStartElement("wp", "Toast", "WPNotification");
            writer.WriteStartElement("wp", "Text1", "WPNotification");
            writer.WriteValue(text1);
            writer.WriteEndElement();
            writer.WriteStartElement("wp", "Text2", "WPNotification");
            writer.WriteValue(text2);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

            return Encoding.UTF8.GetString(stream.ToArray());
        }

Wierd exception

When I ran this, I got the following exception:

System.ArgumentException: The payload is not in accepted XML format. The first node should be Tile/Toast. If want to send raw notification, please set “X-NotificationClass” to “3” in header.rn   at Microsoft.ServiceBus.Notifications.RegistrationSDKHelper.DetectMpnsTemplateRegistationType(String body, String errorMsg)rn   at Microsoft.ServiceBus.Notifications.MpnsNotification.OnValidateAndPopulateHeaders()rn   at Microsoft.ServiceBus.Notifications.Notification.ValidateAndPopulateHeaders()rn   at Microsoft.ServiceBus.Notifications.NotificationHubManager.BeginSendNotification(Notification notification, Boolean testSend, AsyncCallback callback, Object state)rn   at Microsoft.ServiceBus.Notifications.NotificationHubManager.<>c__DisplayClass1.<SendNotificationAsync>b__0(AsyncCallback c, Object s)rn   at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl(Func`3 beginMethod, Func`2 endFunction, Action`1 endAction, Object state, TaskCreationOptions creationOptions)rn   at System.Threading.Tasks.TaskF
actory`1.FromAsync(Func`3 beginMethod, Func`2 endMethod, Object state)rn   at Microsoft.ServiceBus.Common.Parallel.TaskHelpers.CreateTask[T](Func`3 begin, Func`2 end)… in c:\Development\AzurePushNotificationsDemo\NotificationSenderUtility\NotificationSenderUtility.cs:line 139

Now as it turns out, the error message here is rather misleading. “The first node should be Tile/Toast” seems to be referring to the expected XML format if you are sending toast messages using the (very useful) template capability of Notification Hubs, which allows you to send a generic message to Notification Hubs just once, and it will build the appropriate payloads for your actual clients, whether they are Windows Phone, Windows 8, Android or iOS, all of which have different payloads. But “The payload is not in accepted XML format” is a bit more interesting and forced me to take a look at the XML I was generating.

And here it gets really confusing. I swapped out the XmlWriter code and replaced it with just simply setting a string variable directly, similar to the original tutorial – that works! So what is different about the string generated by my prepareToastpayload method? I then put the two methods one after the other and stored the results in two different string variables which I then examined when stopped at a breakpoint – identical!! So, what gives?

Examining the string bytes

Of course, the strings WEREN’T identical, despite what the Visual Studio debugger was showing me! A bit of a web search led me to this useful post by Jon Skeet, author of the book “C# In Depth”. His post Strings in C# and .NET includes a warning about the Visual Studio debugger not showing you the whole story, and he includes some useful code for dumping the bytes of a string to output. I plugged in the suggested methods and the output revealed the following at the beginning of the XML string I was sending to SendMpnsNativeNotifiactionAsync():

image

Aha! What are these (Possibly non-printable) xFEFF bytes at the start? Next web search was for FEFF and I came upon a few posts explaining that hex FEFF is something called a BOM or Byte Order Mark, which is something that is usually inserted into UTF-8 encoded files that are stored on disk, which XML parsers can look for to figure out how to interpret the file contents. However, if you are formatting XML to send as payload in a web service call as we are here, then you don’t want it. Best post that explain this is a six year old blog by Rick Strahl, XmlWriter, Strings and Byte Order Marks .

Un-BOMbin’ the L

Rick gives the solution as well. It’s actually very difficult to stop the XmlWriter for outputting XML without a BOM, but you can get it to behave by creating a custom UTF-8 encoding where you can specify you don’t want a BOM by passing false into an override of the constructor, and then use that in your XmlWriterSettings object:

        private static string prepareToastPayload(string text1, string text2)
        {
            // Create encoding manually in order to prevent
            // creation of leading BOM (Byte Order Mark) xFEFF at start
            // of string created from the XML
            Encoding Utf8 = new UTF8Encoding(false); // Prevents creation of BOM
            MemoryStream stream = new MemoryStream();
            XmlWriterSettings settings = new XmlWriterSettings() 
                                            { 
                                                Indent = false,
                                           //   Encoding = Encoding.UTF8    !!NO-> adds Unicode BOM to start
                                                Encoding = Utf8,    // Use manually created UTF8 encoding
                                            };
            XmlWriter writer = XmlWriter.Create(stream, settings);
            writer.WriteStartDocument();
            writer.WriteStartElement("wp", "Notification", "WPNotification");
            writer.WriteStartElement("wp", "Toast", "WPNotification");
            writer.WriteStartElement("wp", "Text1", "WPNotification");
            writer.WriteValue(text1);
            writer.WriteEndElement();
            writer.WriteStartElement("wp", "Text2", "WPNotification");
            writer.WriteValue(text2);
            writer.WriteEndElement();
            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();

            var payload =  Encoding.UTF8.GetString(stream.ToArray());
            DisplayString(payload); // Inspect bytes
            return payload;
        }

Conclusion

So there you have it. Once you know what the problem is – an unwanted BOM – it’s quite easy to find posts that discuss it and give you a solution. But many developers who are having difficulty with XML they have created in code will not know what the problem is they are trying to fix. No amount of studying the code, from inspecting strings in Visual Studio, or quite likely the exception message will tell you that maybe there is a hidden and unwanted character at the start of the generated XML. For you, hopefully this post will help you find a solution.

UK Windows App Builder Reward Programme

www.appbuilder-rewards.co.uk

Show us that you’re a game changer and collect points every step of the way of your app building journey to redeem rewards like a brand new Lenovo Tablet 2. Create the next app phenomenon by building your original and unique Windows Store and/or Windows Phone app – and get recognised and rewarded for your hard work. Further, get bonus rewards for migrating your Windows Phone app to Windows Store and vice versa or incorporating one or more Windows Azure Services.

4 Simple Steps to Start Earning Points for your Awesome Apps

1. Register yourself on the UK App Builder Reward Programme website.

2. Build & publish your original & unique app.

3. Claim points by telling us about the app you’ve published and we’ll award points to you accordingly.

4. Redeem your points for a range of fantastic prizes and gadgets.

Build & publish an app between Monday 4th Feb 2013 and Tuesday 30th Apr 2013 to be eligible for points you can redeem for rewards. Here are the different ways you can earn points:

Points for Apps

Publish a New Windows Store App

50 Points

Publish a New Windows Phone App

25 Points

Bonus Points

Your Windows Store or Phone App incorporates one or more Windows Azure Services

+ 25 Points

Your app Windows Store app is migrated from Windows Phone or Windows Phone app is migrated from Windows Store

+25 Points

Example

For example, if you have built and publish a Windows Store app which was ported from an existing Windows Phone app and is hosted on Windows Azure, you will be eligible for up to 100 points for that app.

Windows Store App = 50 Points

+ Hosted on Windows Azure = 25 Bonus Points

+ Ported from Windows Phone = 25 Bonus Points

Total = 100 Points

To recognise your hard work, the more apps you publish, the more points you receive. The more points you get, the more exciting rewards you can claim. Here’s a brief selection:

Publish 1 Windows Phone App

Publish 1 Windows Store App

Publish 5 Windows Store apps + Windows Azure Services + Migrated from WP

Publish 10 Windows Store apps + Windows Azure Services + Migrated from WP

Get a XBOX360 Wireless Headset

Get a XBOX360 12 Months Gold Subscription

Get a Lenovo Tablet 2

Get a Two Night Deluxe Paris Cuisine Break for 2

In addition to the fantastic selection of rewards and experiences you can redeem using your points, we’re also offering some bonus rewards to give your journey to publishing great apps that extra boost.

For Windows Store Apps Builders

For Windows Phone Apps Builders

Receive one of the latest XBOX360 titles if you are one of the first 50 app builders who accumulate 150 points from publishing Windows Store Apps.

Receive a Nokia Lumia 620 Windows Phone 8 Handset if you are one of the first 20 App Builders who accumulate 100 points from Windows Phone Apps published (~windows phone apps)

Receive a copy Visual Studio 2012 Professional (with MSDN Subscription) if you are one of the first 5 app builders who accumulate 400 points from publishing Windows Store Apps.

Receive a Nokia Lumia 920 Windows Phone 8 Developer Handset if you are one of the first 10 App Builders who accumulate 200 points for publishing Windows Phone apps (~8 Windows Phone apps)

The UK App Builder Rewards Programme finishes on the 30th April so get your thinking caps on and we look forward to rewarding your awesome apps very soon.

UK App Builder Rewards Programme www.appbuilder-rewards.co.uk

UK Windows Phone App Developers–’Port Your App to Windows 8’ Competition!

Having just completed the Windows Phone 8 JumpStart, you might think I would be totally focused on helping our developer community to incorporate some of the great Windows Phone 8 features into their phone apps. Well I am Smile – but we also want to focus on the great opportunities awaiting Windows Phone developers if you port your Windows Phone app to Windows 8. As published Windows Phone app developers, you are well-placed with the skills and knowledge of app building you need to create great Windows 8 apps. If your Windows Phone app would work well on a Windows 8 slate or tablet, think about porting your app to Windows 8 now, and you could win great prizes in a promotion we are running up to Christmas!

The Windows Store is open and a new opportunity is here. This is perfect for you as a Windows Phone app builder as you can create even more immersive app experiences, reach more people on more devices, and make more money on your terms. Richard Walter’s Calculator2 app on Windows 8 is now approaching 100,000 downloads after porting it from Windows Phone. More importantly, you already have the development skills needed to make the most of Windows 8. Check out the resources to get started or drop your details and register for a free consultation about building a Windows 8 app. You can port your Windows Phone 7.1 Silverlight apps to Windows 8 XAML, and if you have a game built with XNA you can port those to Windows 8 using MonoGame – see this blog post series for details on how to do that.

If you publish your Windows Phone app on to Windows 8 Store before 25th December 2012, you will go into an exclusive prize draw where you will have the chance to win one of 2 x ASUS VivoTab RT slates. Simply drop an email to ukmsdn@microsoft.com with your contact details and the URL & screenshot of your app in the Windows Store and you will get in the draw. If you can publish more than one app then you increase your chances of winning as you can have one entry per app. Note that terms and conditions apply (see link at the end of this post).

Furthermore, if you get a Windows 8 app in store before Christmas Day (25 Dec, 2012), you will get additional chances of winning great prizes including Windows 8 Slates and PCs. Click here to learn more. We are giving away one amazing 32 GB Windows tablets every day up to Christmas – that’s one lucky winner drawn at random from those who publish a Windows 8 app during this period. We also have the best app competition where 10 x finalists will walk away with a Windows 8 Ultrabook, a Windows tablet and Nokia Lumia 920 Windows Phone 8 device.

I hope you can take advantage of this new and significant opportunity to take your apps from Windows Phone to Windows 8.

Andy

Windows Phone 8 Jump Start Video Recordings now available!

The videos for last weeks’ two days of demo-packed fun that was the Windows Phone 8 Jump Start are now available online. So if you missed the event, or part of it, or were there and want to watch it all over again, you can find them in one of these two places:

On Channel 9:

Here you can find the 21 (count em!) sessions we delivered over the two days, so start at the beginning and settle down to two days of information, or pick out the sessions that interest you, from the following:

Full course outline:

At the Microsoft Virtual Academy:

If you prefer a different way of learning, you can take the Building Apps for Windows Phone 8 Jump Start course at the Microsoft Virtual Academy which includes the same video content, but allows you to track your learning through your dashboard at the MVA, and accumulate points as you take part in the learning. There are also many other courses and Jump Starts you can take part in.

Enjoy!

Upcoming Windows Phone 8 DevCamps

clip_image001

With Windows Phone 8 SDK being released around two weeks ago, we are getting a lot of people wondering when we are going to run a Windows Phone 8 DevCamp to get you up to speed on the new dev features.

Wonder no more! The first Windows Phone 8 DevCamps will be help in London on Friday 14th December and Saturday 15th December. Booking details here:

14th December, Modern Jago
Event ID: 1032536241

URL: https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032536241&Culture=en-GB&community=0

Phone: 0870 166 6670 ref – 6241

15th December, Modern Jago
Event ID: 1032536242

URL: https://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032536242&Culture=en-GB&community=0

Phone: 0870 166 6670 ref – 6242

The Windows Phone 8 Camps have been designed to show you how to build a Windows Phone 8 app. You can tailor the day to make it as personally productive and rewarding as possible. You can work on your own projects with assistance from Windows Phone 8 experts, network with others and also have the option of attending short tutorial sessions on Windows Phone 8 related topics.

The Windows Phone 8 Camps will cover an introductory overview session as well as a range of short tutorial sessions. Short tutorial sessions will include topics such as the Windows Phone 8 application lifecycle, new Windows Phone 8 controls such as the LongListPicker, a high level view of the platform – i.e. how .NET and the Windows Phone Runtime APIs work together and the choice around implementation technology, new Windows Phone 8 features such as the Speech API, app to app communication with file and protocol associations, lock screen notifications and in-app purchase, how to make the most of the new Tile templates, and how to make best use of the tooling – the role of Visual Studio and Expression Blend. We’ll also cover how to share code between a Windows Phone 8 app and a Windows 8 app.

In addition, you will learn how you can publish your Windows Phone 8 app into the Windows Phone Store.

The Windows Phone 8 Camp will kick off at 9am and officially finish at 6pm or 9pm for the hardcore attendees.

Welcome to my new blog!

Andy WigleyHi, and welcome to the new home of my blog.

I started working for Microsoft as a technical evangelist a few weeks ago. In this blog, I will write on topics that will mostly be tips and techniques to help developers build apps for Windows Phone devices and tablets, slates and other mobile computers running Windows. Two weeks ago, we launched Windows 8 and last week we launched the Windows Phone 8 SDK – what an exciting time to be joining Microsoft!

Before this, I was a proud partner of APPA Mundi, the UK-based mobile consultancy and training company. They are still one of the best companies you can go to if you want to talk to some of the smartest mobile application developers on the planet. My old blog is still where I left it at http://community.appamundi.com/blogs/andywigley and there’s some good stuff on there. I may duplicate some of the most popular posts on here, but please go take a look at that blog as well for posts on .NET development on Windows Phone , Windows Embedded and Windows Mobile.

So, on with the show…