Saturday, October 25, 2014

OneDrive File Browser for Windows Phone

I finally got around to update my OneDrive File Browse Task for Windows Phone 8.1 Silverlight projects.  There is newer OneDrive functionality now, but if you are just looking for a quick upgrade, then this may do the trick.  It's also cleaner than redirecting to the OneDrive app to browse files.  I hope it helps you!

Link: https://www.nuget.org/packages/ArianKulp.SkyDrive.BrowseTask/1.5.0

Friday, October 24, 2014

Windows Technical Preview - Update build - Error 0xc1900101 - Fixed!

After attempting around ten installs of the new Windows 10 build the other day, and reading many forums posts, I've finally got it working!  The posts varied somewhat, but mostly seemed to center on devices being the problem.  Like disconnect all external devices, or run the upgrade from Safe Mode.  I tried everything I could think of, until I noticed one thread mentioning free hard drive space.  I had under 20GB free on my drive.  I spent some time and got it to 50GB, and low and behold the update worked!  I'm not on the latest build.  Finally!

If you keep getting the 0xC1900101 error with the build upgrade failing, FREE UP DRIVE SPACE!

Friday, August 8, 2014

Opening large images in Live Photo Gallery

I've just learned that after copying lots of big photos from my Lumia 1020 to my network storage device Live Gallery won't load them anymore.  Just lots of gray boxes!  Just a little bit of searching brought me to a Microsoft support page that provides instructions on how to fix it.  Very easy fix, though the specific registry location has changed since the article was written.  You actually want to go to:

HKEY_CURRENT_USER\Software\Microsoft\Windows Live\Photo Gallery

to create the MaximumFrameSizeMegapixels key.  Other than that, it works like a charm!  This only seems to matter for network images.  When the photos were local I never had this problem.

Link: http://support.microsoft.com/kb/2725211

Friday, May 30, 2014

Awaitable functions in properties

If you've ever needed to call an asynchronous function from within a property setter, you may have been confused, or at least unhappy with the result.  You know that it needs the "await" operator, but if you add it you'll get an error since it's not even possible to make a property async.

public string Name
{
    get{ return _name; }
    set{ await VerifyAsync(value); RaisePropertyChanged("Name"); }
}

If you don't add await, then you'll get a compiler warning, but you'll also lose the flow that you have.  This will probably result in a notify change event being called before your code finishes running.  This is because if you don't await, the asynchronous call is dispatched to a background worker and your code continues running.  This means that interested parties get events before the value might be truly updated!

public string Name
{
    get{ return _name; }
    set{ VerifyAsync(value); RaisePropertyChanged("Name"); }
}

You might be tempted to wait on it, but in many cases this causes issues with deadlocks, or causes responsiveness issues that the async pattern is trying to fix.

public string Name
{
    get{ return _name; }
    set{ VerifyAsync(value).Wait(); RaisePropertyChanged("Name"); }
}

It turns out that the fix is pretty simple by using a delegate and the Task.ContinueWith method.  This lets you dictate code to run when an async call finishes, without using the await keyword.  Just add your code that needs to run after and you'll know it will be in the right order!

public string Name
{
    get{ return _name; }
    set{
        VerifyAsync(value).ContinueWith((t)=> {
            RaisePropertyChanged("Name"); }
    }
}

Thursday, May 15, 2014

Seventh Annual Oregon Game Project Challenge

Every year Oregon students get a chance to compete in the Oregon Game Project Challenge (OGPC).  This was the seventh year where Middle School and High School kids could use their drawing, modeling, composing, writing, programming, and other skills to create a game based on a provided theme.  This is great fun, but also a chance to put their skills together to create something amazing as a group.

This year, the High School award for Art and Assets went to Crescent Valley High School's Penteract team for a game created in Unity with all custom-made sounds, music, graphics, and code.

Congratulations to Lorelei, Dylan, Gabriel, Alana, and Hayden!

Team 916 group photo
Link: http://www.ogpc.info/home/2014/5/12/ogpc-70-winners.html

Thursday, May 1, 2014

Windows Phone Live Tile Data Binding Challenges

I struggle with my Live Tiles.  It seems like such an easy proposition, and indeed, all of the samples make it look trivial!  As long as you are just setting text and a static image, you'll have no problem.  As soon as you want to generate dynamic images you will have problems!

There are a few things to remember.  First of all, you will usually want to use a UserControl for layout and rendering of your content, then use WriteableBitmap to encode and save the bitmap.  Ideally you should use an extension package to encode as PNG in order to get a transparent background (especially with this being so popular in WP 8.1).  As long as you generated the tile content from within the app you are probably able to run it from a click handler or within a dispatcher pretty easily (you must have a dispatcher to create a UserControl).  If you are in a background agent, or on a background thread in the main app then you will get a cross-thread access exception.  From the agent you can't just get the current dispatcher like you can from within a control.  Not exactly the same anyway.  Instead of getting it from another control, just take it from the current deployment:

Deployment.Current.Dispatcher.BeginInvoke()

That part's easy!  What's not so easy is what happens if you include an image in your control.  You'll notice that the rendered tile is blank where the image should be.  This is incredibly frustrating to figure out!  If you test from within the app it will look fine.  You might get sites telling you to just add arbitrary delays to fix this.  It might even work, but it's not a great way to do it.  Instead, you need to subscribe to the image's ImageOpened event.  Once this fires (or the ImageFailed fires) you know that it's ready to save as a bitmap.  This causes some issues with synchronization, but in an agent, remember that the agent isn't complete until you call NotifyComplete(), so just make sure it's wherever the code is actually done.

The next thing to worry about is databinding.  If you set the data context, you expect your fields to be bound!  Unfortunately, that's not always the case.  For example, any "simple" scenarios such as TextBlock.Text, Image.Source, or Border.Foreground will look fine.  Issues come in with "multi-level" scenarios such as ItemControl items and TextBlock Run's.  What I discovered is that the binding all starts to take place, which is to say, an ItemsControl will create four templated items if there are four items in the collection, but the individual fields will never bind to the context.  If you set a FallbackValue, you will see that come through, but never the bound value.  In the same vein, a TextBlock with Run elements for text control, will show only the FallbackValue for each Run.  It's incredibly frustrating!  Unfortunately, I haven't found a solution.  I tried binding to many different events to see when the actual binding takes place, and if I run the UserControl within a running instance of the app it looks perfect, but I had to give up from an agent.

The solution is to convert a TextBlock with Run elements to a StackPanel of TextBlock elements.  Even worse, for an ItemsControl you need to actually create static controls for each item which should be generated dynamically!  This looks stupid in the XAML, but works fine.  Key to remember, is that you can use array indexing within binding.  For example, if your ItemsSource would have been "People" and in your GeneratedItem template you bound to "Name", then you can bind to "People[0].Name".  Really!  It works.  Of course it will cause silent errors if you go higher in index than actual values, but it won't cause issues with the final image.

It would be great if Microsoft gave us a way to pass a control type and data context to an UpdateLiveTile method, but until then, you will save much frustration by remembering these lessons I've learned!

Windows Phone Day, Portland

Live in the Pacific Northwest?  Ready to get some apps published for Windows Phone?  Be sure to register for Windows phone day in Portland, Oregon.  We've got lots of sponsors and some great speakers.  Come to hang out with other WP devs, or to get help starting or finishing your pet project.

Prizes include AdDuplex credit, special DVLUP raffle, and chances at winning devices!  It's free to come, just bring your own hardware.  Make sure you register for DVLUP first (also free) to take full advantage of the day.

See you there!

Link: www.eventbrite.com/e/windows-phone-day-portland-tickets-10776503813

Tuesday, April 29, 2014

You can only use State between OnNavigatedTo and OnNavigatedFrom in Windows Phone

If you've ever seen this error when debugging a Windows Phone app you have probably learned that you can't reference the State object* outside of OnNavigatedTo() or OnNavigatedFrom().  Easy fix!  Move those calls to the right methods.  If, for some reason, you can't act on that data at that moment, get the value that you need, stuff it in a field/property, then use it later.

The bigger frustration is when you do this but still get the error.  In other words, if you check and double-check, but you definitely only use State in the navigation methods.  If this happens to you, I might have the solution!

I recently came across this issue and was pretty frustrated at first, until I thought about what I was doing a bit more:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    var x = await Something();
    var y = State["key1"];
    // And so on...
}

In this example, I have some pretty basic stuff.  I make a call to do something asynchronously, I get the state value, I do something with that value, etc.  But then it hit me.  That darn awake!  If you remember how await works, you'll realize that this can't really work.  The "secret" of await is that the code executes in two passes.  Everything up to the await runs in the context of the actual function.  After the async line, the containing function (OnNavigatedTo) actually returns.  Once the awaited function returns an actual value, the original code runs on a callback with access to the return value.  A highly simplified view is here:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    Something( (x) =>
    {
        // This is actually a callback invoked when Something is done
        var y = State["key1"];
        // And so on...
    });
}

So the actual flow that is OnNavigatedTo calls Something, then returns.  When the callback is invoked, the runtime correctly complains that the usage of State isn't really happening in OnNavigatedTo.

So what's the solution?  Well, that depends on what you are doing.  In my case, I had a number of initializations to do, and I could just change the order to access State first.  Actually, that's the easiest!  Just access it immediately when the method starts and you'll probably be fine.  There's nothing wrong with an async section in there, as long as you only access State beforehand.  I hope this helps someone else!

* If you've never used the State object, it's pretty handy.  It's just a dictionary, but you can use it to store values in the current page that persist navigation/back, even if you leave the app and come back.  It gets cleared whenever the app is started.

Monday, April 28, 2014

Formatting text to view in Windows Phone Internet Explorer

Sometimes you need to present formatted text to users in your apps, and it's a pretty big pain to implement your own formatting engine.  Rich Text is sometimes an option, but if you are starting with HTML formatted data then the obvious choice is a WebBrower control (even if it is a little heavy as a control).  You probably already know how to use the NavigateToString() method to load am HTML formatted string.  If not, there's little to it:

ctrl.NavigateToString("<i>This should be in italics</i>");

Notice it's from code, not something you can do from XAML.  The problem is that you end up with a plain white background and black text, regardless of phone theme.  If you'd like the text to match the phone theme, all it takes is a little CSS magic!

Theme Colors

The first step is to get the theme colors.  There are typically two colors you want: the background and the foreground.  These (and other built-in static style/theme resources) can be retrieved with the Resources collection attached to the application: App.Current.Resources

What you want are the SolidColorBrush resources named PhoneBackgroundBrush and PhoneForegroundBrush.  Anything you get from the Resources collection is an object, so you need to cast them accordingly:

SolidColorBrush bg = (SolidColorBrush)App.Current.Resources["PhoneBackgroundBrush"],
    fg = (SolidColorBrush)App.Current.Resources["PhoneForegroundBrush"];

CSS

The next step is to create a CSS snippet to reference the color values.  This ensures that you don't need to modify the original HTML string directly.  All you set is color and background-color.  This will affect any text that doesn't have its own local style override.  The CSS looks like this:

<style type='text/css'>body {{color: rgb({0}, {1}, {2}); background-color: rgb({3}, {4}, {5}); font-size: inherit; font-family:Segoe WP}}</style>

I couldn't find a simple way to spit out the #RRGGBB color, so I made it easy on myself and used the CSS rgb() function to take the three values separately.

HTML

Finally, just wrap the original text with the CSS and a basic HTML body.  Obviously if you are working with HTML that is already a complete document, it won't be this simple, but this works great with snippets!

var html = "<html><head><meta name=\"viewport\" content=\"width=device-width\" /><title></title><style type='text/css'>body {{color: rgb({0}, {1}, {2}); background-color: rgb({3}, {4}, {5}); font-size: inherit; font-family:Segoe WP}}</style></head><body>{6}</body></html>";

return string.Format(html, fg.Color.R, fg.Color.G, fg.Color.B, bg.Color.R, bg.Color.G, bg.Color.B, txt);

For my needs, I found it useful to include a viewport declaration too.  This ensures that the content properly fills the screen and doesn't need to be user-scaled right away.  You may or may not need it.

SOLUTION

The final version can be made into a simple function to pass the HTML to, then to the control:

string PrepareText(string txt)
{
    SolidColorBrush bg = (SolidColorBrush)App.Current.Resources["PhoneBackgroundBrush"],
        fg = (SolidColorBrush)App.Current.Resources["PhoneForegroundBrush"];

    var html = "<html><head><meta name=\"viewport\" content=\"width=device-width\" /><title></title><style type='text/css'>body {{color: rgb({0}, {1}, {2}); background-color: rgb({3}, {4}, {5}); font-size: inherit; font-family:Segoe WP}}</style></head><body>{6}</body></html>";
    return string.Format(html, fg.Color.R, fg.Color.G, fg.Color.B, bg.Color.R, bg.Color.G, bg.Color.B, txt);
}

var html = PrepareText("<i>This should be in italics</i>");
web.NavigateToString(html);

NEXT STEPS

This is a pretty good way to get HTML-formatted text to look more like native text in an app. If you are going for an ebook reader type of text presentation, then you might want to also create a helper class for this and create properties for the foreground and background colors.  That would make it easier to support a cream background, or a sepia foreground for better readability.

Wednesday, April 16, 2014

Vote for Damian's game!

My son Damian and his friend Ben have created a great HTML 5 game, Outlaw of Gravity.  It works cross-browser including mobile browsers.


This was created for a contest, so please give it a play (it's quite fun and addictive!) and rate them five stars.  You won't be sorry!

Direct link: http://clay.io/game/outlawofgravity

Wednesday, March 19, 2014

Want to show your coding skills? Lots of contests now or soon!

Some of these (not all) have age restrictions.  Some have cash prizes, some have other items.  Compete for a chance to win, but also as a chance to try out something new.

1. March 22nd, one day, online coding challenges
http://www.codingame.com/kirk/
2. Build an AI for a racecar over two weeks, teams of up to 3, top six teams compete in Finland!
http://helloworldopen.com/
3. Warlight AI (strategy game like Risk), cash prizes
http://theaigames.com/competitions/warlight-ai-challenge
4. Create a HTML 5 game that also runs on mobile devices with touch.  Cash prizes up to $2500
http://clay.io/gotgame

Monday, March 17, 2014

Update: SkyDrive/OneDrive Browse Task

Well, the SkyDrive rename to OneDrive is a month or so old already, so I finally decided to update my file browser package on Nuget!  In addition to the renaming, I also added the ability to set/replace the images used for file types.  This could be useful if you are going for a specific look for your app, or just to show an image for a custom extension that you use.  I haven't renamed the package since that's how the lookup is done for updates, but I may create a second package soon with the new name.  Hopefully people will still find it!

UPDATE: I never mentioned how to set the file extension images!  It's pretty easy really.  Use the extension itself (not including the dot) and a URI pointing to the image:

SkyDriveBrowserTask.AddCustomFileTypeImage("xlf", new Uri("/Assets/xlf-icon.png", UriKind.Relative));

Notice that it's a static method on the task class, not on instances of the task.  Set it once for your app when it starts up, and any task in that session will use it.

Link: https://www.nuget.org/packages/ArianKulp.SkyDrive.BrowseTask/1.4.0

Wednesday, February 26, 2014

HyperlinkButton crash on Windows Phone

Ready to give up on HyperlinkButton?  Getting a crash when you try to navigate to the link?  The fix is stupid simple (and just plain stupid!).  On Windows Phone, the TargetName property is required.  If it's not set, you'll crash and burn.  Set it to _blank and you'll be happy!  I dug around and found it on the MSDN page, but didn't see any other posts about it so maybe this will help someone else!

Tuesday, February 25, 2014

Is there another way to spell Antarctica?

Ok.  This is weird.  After playing with NOKIA's Here Maps service (yes, dumbest name ever), I seem to have come across an error dissing our many scientist friends at the bottom of the earth.  Though the continent of Antarctica is spelled properly, it sure looks to me like they've named the east portion of it in a more phonetic manner.  I did a little searching and could only find "Did you mean" references for this spelling, so I'm feeling confident that I've found a typo in their service.  Maybe I should get a free trip down there... never mind.  A million thanks is all I need!

 Antartica East?
As shown on Bing maps (data by Nokia)

Also, quick double-check on Wikipedia:

First Place in MoDev $10k Windows App contest!

Cool news!  Windows Phone consulting company MoDev recently partnered with Microsoft to give away $10,000 to six different app developers.  Three apps were chosen by public voting, and three by their own judges.  My recent app, Dash Recorder (which missed the DVLUP deadline by just a few days and therefore missed out on XP) (not that I'm bitter) (ok, a little...) won first prize for Judges' Choice!  That's $2,500 in my pocket.  Very nice!  Please take a look at the app and see what you think.



Link: MoDev, Dash Recorder

Tuesday, February 18, 2014

Windows Phone Marketplace Submission

Wow!  There was a recent post about Microsoft reducing certification times for submitted apps.  I submitted an update a day and a half ago and it just went live!  It sounds like it could end up being even faster, but I'm pretty happy to have a turnaround that fast even.  It's nice to see them improving things.

Update: Version 1.3 of SkyDrive Browser Task for Windows Phone 8

Version 1.3 is now live!  I've added a new language, Dutch (nl), courtesy of Jurjen Ladenius.  I also added the ability to override the file icons or set new ones, and I display the file size.  You can override the default icon for folders, albums, or files by specifying a URL to a resource or HTTP resource.

To set a new file type icon, call AddCustomFileTypeImage on the task class, passing it the extension and the Uri to the resource.  For folders, specify "folder" and for albums specify "album".

SkyDriveBrowserTask.AddCustomFileTypeImage("folder", new Uri("/MyAssembly;component/Assets/MyFolderIcon.png", UriKind.Relative));

Grab the package on nuget: ArianKulp.SkyDrive.BrowseTask v1.3

Monday, February 10, 2014

SkyDrive browse task update (v1.2)

A new update?  Oui! Sí! Ja!  I posted version 1.2 of the SkyDrive Browse Task for Windows Phone 8 last night.  The newest version fixes a bug when you refresh the view (it wasn't clearing the list) and it also adds French, Spanish, and German language translation.  This was already there, but I didn't package it properly for Nuget so no one got to see it!  Thanks for the help of Lionel Loscos for improving the French strings.

Anyone who wants another language, let me know.  There are very few strings to translate and I'd be glad to get you a language file.

v1.2 Link: ArianKulp.SkyDrive.BrowseTask on Nuget

Sunday, February 2, 2014

Update to Marketplace Apps List for Windows Phone

If you have tried my Marketplace Apps List control for Windows Phone, I release an update for it last night.  I cleaned up the code, did real template binding, and added the ability to set a Background brush in the declaration of the control.  This is used for the background of the individual app items -- not the control as a whole.  Anyway, give it a look!

Link: Apps List on Nuget

Sunday, January 26, 2014

Cross promote your apps on Windows Phone

Have you ever wanted to cross-promote your apps?  I used to maintain a list of my apps within those same apps!  What a pain that was.  Every time I released a new app I needed to update my other apps.  There must be a better way!



Two years ago I wrote an article for Coding 4 Fun called Let Your Apps Sell Themselves.  Today, I massively updated the code and create a Nuget package to simplify its use.  Check it out!

Among other things, it has a WP7 and WP8 version, it looks at the current version of the device it's actually running on to determine which apps to show, and it is localized for Spanish (more languages coming soon).

Link: Windows Phone App List Display 1.0.0

Wednesday, January 22, 2014

Need Windows Phone development help?

Looking for some help getting started with Windows Phone or trying to get an application ready to publish?  I'm using the relatively new Google Helpouts platform as a way to provide one-on-one instruction including webcam, chat, and screen sharing.  This service lets me charge for my time (a limited resource, to be sure!), but for a limited time Google is giving us providers promotional codes that we can use to introduce people to our services.  If you are interested in giving this a try and need a code, let me know!  I have 20 codes to give out so you'll probably get one if you need it.

My listings can be viewed here: https://helpouts.google.com/104266471681083032610

Modev Windows $10k App Contest Round 2


Update Central

Update Central for Windows Phone made it to Round 2 of the Modev Windows app contest!  I need your votes again to stay in the game!  If you haven't tried it yet, download it today.  With all the rumors and leaks in the news all the time, it makes it easy to stay on top of upcoming Windows Phone updates, read about past releases, and see what you have installed at the moment.  Get it for free today by clicking on the image, then, nter the contest by clicking on the contest link:
http://gomodev.com/modev-windows-10k-app-contest-voting-round-2/

Nested entities won't return in RIA Services

Such stupid things we waste time on!  I had a RIA service which was supposed to return some entities and their entity-based properties.  My troubleshooting clearly showed the entities being present in the service but none of the included entity properties arrived at the client filled out.  Fiddler proved that these entities weren't being serialized.  So where were they?  The problem was that it was an Invoke operation.  I guess I didn't fully understand the difference between Invoke and Load operations.  Very important!

An Invoke operation is intended to return scalar or single-Entity values.  In fact, it can even return a collection of Entities, but it specifically won't return nested properties.  It makes sense when you realize that by definition, Invoke operations don't return tracked entities.  Returning a fully populated object graph without the tracking is seldom something you really want.  Unfortunately, I had to switch into calling two service methods: one to do some entity creation, then a second call to retrieve the created objects as a complete graph.  Clearly not super difficult, but until you realize the limitation you just bang your head against the wall!

Tuesday, January 21, 2014

The parameterized query ... expects the parameter ..., which was not supplied

After spending too much time on a null parameter issue, I finally found the solution!  If you try to execute a parameterized query against an object context in Entity Framework it's not enough to create a parameter and set it null.  You'll get the dreaded "was not supplied" error.  Instead, you have to explicitly set the value to DbNull.Value.

Bad Example:
string x = null;
var p1 = new SqlParameter("param1", x);

Good Example:
string x = null;
var p1 = new SqlParameter("param1", x);
if( x == null ) p1.Value = DbNull.Value;

The more you know!

CodeDay:Corvallis

Twenty-four hours of coding may sound like a lot, but most devs have stayed up pretty late coding before.  CodeDay is a great opportunity for students (HS and college) to participate in a coding event to create apps or games for fun and judging.  Ideas and teams form at the beginning, and then loud music plays as everyone works on their projects through the night.  For games this usually includes music, sound effects, 3d models, sprites, levels, story, and of course the code behind it all.  We had around 30 students in Corvallis with lots of great ideas and fun for everyone!  HP let us use their facilities which was an amazing setup for such an event, and they gave everyone a great tour of their fab areas and massive printing equipment.

If you've never had a chance to take part in one of these, you're really missing out!  We hope to do it again in the future and hope for it to grow even more.



Link: Corvallis Codeday

Thursday, January 16, 2014

Vote for me!

I've got three apps entered in the MoDev Windows $10k App Contest.  There are a huge number of apps on there, but mine are Update Central (keep up to date on Windows Phone updates and releases), Grade Viewer (a Pinnacle PIV grade app), and Dash Recorder (a dash cam app for recording incidents on the road).  If you like any of these apps, please consider putting in a vote for them.  Thanks so much!

Link: Contest entry

Tuesday, January 14, 2014

Silverlight Image Converter

I wrote a simple converter to go from an enumerated type to a different image per value.  Sounds simple, right?  It checks the value, then returns a new BitmapImage with the appropriate image path:

if( v == Enum.Thing ) path = "/images/thing.png";
return new BitmapImage(new Uri(path, UriKind.Relative));

Unfortunately no image appeared.  So frustrating!  It turned out that even though I was starting with a leading slash, it was loading from the wrong root.  No errors, just no image.  A quick run-through with Fiddler showed me what was going on.  After examining the code, I was sure everything was right.  Fiddler is the best tool for finding those weird things that come from needing that closer look!

Monday, January 6, 2014

Looking to get started with programming?

Scott Hanselman (a Microsoft software developer) just published a great post about getting started with programming.  I highly recommended it if you want to get started but don't know what to do.  People ask me this question fairly often, and my new response will be to direct them here!

Link: Scott's Blog