Windows Dev Posts By a Dev Theologian

WP8 Speech Recognizers 

Monday, April 15, 2013 10:51:50 AM Categories: Speech WP8

If you don’t know I have been deep into WP8’s Speech SDK for the last 6 months. So much so that I am starting to help others along the way. I just got a question about how to get the confidence rating on a recognized word.

If you don’t know what that means, let me explain. Basically the speech recognition is not an exact science. There are complicated algorithms that analyze your speech to determine what words were spoken. One of the cool things with WP8’s SDK is that you can provide a list of words or phases you are looking for and this makes things a little more accurate (mainly because you are limiting the number of combinations to look for).

WP8 has 2 objects that you can use to recognize speech: SpeechRecognizer and SpeechRecognizerUI.

SpeechRecognizer gives you something a little more low level. It won't show the “pretty” UI that is shown while listening to the user speak; it won’t play a beep sound to indicate that speech is being recorded for recognition, nor does it give the user any feedback whatsoever. It does let you supply a list of words or phrases you are looking for as well as will do the big check for listening for any word. The SpeechRecognizerResult will give you the word (or words) it thinks the user said. It also will give you a list of alternates (via the GetAlternates() method) that might be what the user said. It also gives you a number to tell you how accurate it estimates that it was (and gives this rating for each of the alternates as well). It will also let you do your own recording and will process the speech from your recording (but it accepts a much smaller clip than what the actual MS mechanisms do). Actually doing a recognize for any word will allow for a shorter amount of data.

SpeechRecognizerUI does a lot of work for you. It puts up the UI, plays the beep to inidicate to the user to speek, handles the case where a word isn't quite recognized, and generally let’s the user know what is going on throughout the process. It returns a SpeechRecognizerUIResult object which contains SpeechRecognizerResult (in the RecognizerResult property), but the confidence is usually high (I have yet to see any alternates come through). I think this is mainly because the UI object does the extra work of clarifying with the user when it estimates that the accuracy of the recognition isn’t quite that high.

From my work, I have found that I tend to use SpeechRecognizerUI more often the the lower level mechanism. Mainly because the added UI/indicators creates a very good experience for the user.

[I find it difficult to not attribute human qualities to the recognizer. It was tough not to use words like “guess” during this post.. the recognizer is really amazing how accurate it is and when it is wrong, it’s usually pretty understandable why.]

Test post.. nothing to see here yet 

Friday, January 18, 2013 9:59:18 AM

Just putting a test post out..

Logo For Windows8 in JavaScript: Lessons Learned 

Thursday, November 29, 2012 3:15:29 PM Categories: WinRT/WIn8-Metro

So Kevin Wolf created a community challenge with a ARM Surface Tablet as the prize. He presented this to the local Florida Windows8 Development Community which I am a part of.

Here’s the basics of the challenge:

  • The Windows 8 App must be 100% JavaScript/HTML/CSS; no other client technologies allowed.
  • It had to be in the Windows Store by Dec. 1st (we had approximately 2 months to do it)
  • He wanted the app to be non-trivial so therefore there was criteria for what was “non-trivial”:
    • App must have a market base that was not the development community (and could not be a sample app). In other words it had to have an audience, a real audience.
    • App must implement some form of capture (first name, last name, etc)
    • App must connect to a web service of some type and pull and push data to it (both reads and writes); social networking sites were disallowed, but any other public or private web service was acceptable
    • Needed to implement either search or the share contracts
    • Must use either:
      • the camera in a meaningful way
      • Location services AND Bing maps in a meaningful way
    • Must implement 1 animation

That was it. When I saw the list I was thought, “Boy, he rigged the contest.” I could do that, but I’ve done this kind of insane project in the past. I considered doing it and forgot about it for a month.

A Funny Thing Happened on the way to a presentation

So  along the way I had agreed to do a presentation for the Great American Teach in at my kids’ school. I decided that I would show them some beginning programming with the Logo programming environment (aka Turtle Graphics). I decided since I would be using my Samsung Slate to do this that I should probably go ahead and find a Windows 8 implementation of logo. I couldn’t find one. After a bit of searching around I found a nifty one in JavaScript using the HTML5 Canvas. I decided to take this single page environment and make a full Windows 8 Store app with it. It was all rather trivial. I think the initial version took me 2 evenings to get working (so a couple of hours). I did have to change things. The version I had was using jqConsole which seemed to be overkill, but it provided one nice thing: history. So I fired up TyopeScript and created a nice little history component for my jqConsole replacement (essentially a Textbox with a sprinkling of JavaScript code to sniff for the enter key). I also added a few buttons to make it convenient to retrieve past history items and a scrollable region containing that history.

My presentation went off wonderful, and now I was thinking about finishing the app and getting it into the store (really as a convenience for others). It was at this point that I remember the challenge and realized that I had done the first couple items. Next up was the whole Share contract. Essentially what I did was make it possible to share out your history. I also implemented (I think) the opposite mechanism where you can share text back to the Logo app where each line will be executed by the Logo interpreter.

For the animation I created a simple movement of my turtle in CSS; he starts at the bottom of the page and moves to the center where he belongs.

Next I implemented hitting my personal App Analytics server for Error reporting (mainly). It stays off in most cases unless I am having issues with something then I turn it on for an app. Anyway, I only implemented the read component of this.

At this point I submitted to the Windows8 Store. I failed for not having a privacy policy (you have to have one when you need Internet access). That was harder than it should have been since I needed to learn a few things about doing this in HTML5 apps (which, BTW, is easier than what it takes in XAML.. HTML5 apps have a few more controls that we should have in XAML, but I digress). I got in…

I announced that I had won the challenge, only to read closer and realized that I needed GPS and WebService pushes. I decided to implement a non-standard GLAT/GLONG expressions in the Logo interpreter as a nicety for teaching students how to write a “how close am I too the equator (or other landmarks)” function. This didn’t take that long.

I next implemented a simple write to my Web service and got it working (this was harder). For both of the these I wrote TypeScript. I’ve learned enough about JavaScript that if I am writing something non-trivial I want a tool to help me. There are way too many gotchas with JavaScript that it just makes sense to me (Mind you, I have maintained systems that have tens of thousands of lines of JavaScript code and even worked on a system with 100k of JavaScript! By no means am I a rookie). I got it working and got rejected on Tuesday do to something not working.. not sure what that would be…

BUT I realized that the requirement was to write something with GPS AND Maps.. Not just GPS. If I had chosen camera (and I could have come up with something for that, but reasons also matter, because of the words “meaningful way”), I would have more or less been there. I have resubmitted but even if this version gets in before Dec. 1, I still didn’t complete the challenge…

Surprises

I ran into a couple of surprises. In some respects the set of controls that MS has enabled with WinJS/Html is a little more rich, and pretty easy to setup. The biggest item was the flyout when I built a settings panel for my GPS Enabler. The code to write this was mostly HTML and magic CSS Classes (I say magic because the MS Environment just knows what to do with them to create the control). This actually had me slightly enamored..

Takeaways

First of all if you have talked to me in the last week or so you may have gotten a different impression. I mentioned some positives to this. There are definitely some positives. BUT, I also need to factor in me. I was a trainer during the Web 2.0 craze. I knew my stuff. I once worked on/maintained/added features to a web project that had close to 100k lines of JavaScript code. I want you to ponder that for a moment…. you back? Good. Now realize that I can do non-trivial things with JavaScript and HTML (things you might not be able to do). I’m not as knowledgeable with the latest and greatest on the HTML5 track, but by no means am I an newbie with this.

Also, the project I took was something that already worked well with IE10, and I simply sucked it into the Windows8 Templates. If that was the end of the story then I would say everyone should be doing this, but it’s not. While my project was non-trivial, the task seemed to be trivial. Creating the share contract for instance involved me tweaking the JS code to expose things I could share. I imagine this is the case with Search as well.. you will have a fair bit of tweaking to make things happen.

Lessons Learned

So the positives, Microsoft has thought through this and what they have delivered is a nice environment. You can do some stuff with this. They have enabled a pretty easy mechanism for you to access the various controls via CSS Styles which makes things pretty easy on that front. If you are doing something fairly trivial (port a single page over that already works in IE10, or single page that sucks in rss feeds) then have at it. You can do it with HTML5/WinJS.

If you are doing anything more complex, I would suggest skipping HTML5, and putting on your “big boy” pants and building your app with XAML, VS2012, Blend (if you need it), and a copy of John Papa’s Data-Driven Services with Silverlight 2 (which needs to be renamed “Data-Driven Services with XAML” because it still applies today). With all that in hand you can do XAML. It’s not that hard. AND, by “complex” I mean web services in any form (where you don’t already have a fully tested/stable JavaScript library to access that service), Maps, Fancy Animations, File Apis, anything data driven…

Another lesson learned, if you have to write JavaScript, write TypeScript instead. You still have to remember that you are using closures from things like events, but it’s certainly a lot better having the design environment tell you when something is wrong due to typing, or misspelling, etc.

Html/WinJS has the same net effect in my mind as most of the JavaScript apps I have written in the past.. they are quirky. My Xaml apps feel much more solid. In my mind I will keep an eye on the technology, but I am going to stick with XAML for the near future… (you can’t do everything in JavaScript as some would like us to believe).

Windows Store Rejection#1: Lessons Learned about Age Ratings 

Wednesday, October 10, 2012 10:45:54 AM Categories: WinRT/WIn8-Metro

Just thought I would fire up a quick post (and maybe a little advice to the powers that be at Microsoft).

I have been working on a Dropbox Client for the last several months in my spare time. I actually almost quit on the process and realized that what I had was more integrated with Windows 8 than anything else in the Windows Store, and that I really wanted to use my own app over anything else that is currently out there. Mind you I was about a week away when I decided to quit. When my work schedule broke a little I decided I NEEDED to finish this. So last Tuesday I finished it up and submitted to the Windows Store.

When I was filling out the submission, I got to the line that asks about Age Rating.. this seems weird to me, I hadn’t really thought about it. I mean I would expect it to be rated E (for Everyone) because you bring your own content. I could see a 3 year old being able to operate it.. so I set it to 3 and eliminated any country that wanted me to back that up (at least for now).

SIDENOTE: In other Mobile AppStores (you know the one who considers themselves the owner of the name “AppStore”), they don’t ASK you what you think your rating should be, they ask you a series of questions about your app and then they TELL you what your rating is.

So, A whole week later, I get the notification (this morning, actually) that I got rejected. I wasn’t offended. It happens there are many things in the guidelines and it’s really easy to miss something or to have a corner of your app that is not as well tested. This was my first time through so I expected this. Of course it was for the aforementioned Age Rating. I checked SkyDrive and saw it was Age Rated for 12+.  I assume from reading the materials it was because I have ads in an app and they don’t think anyone younger than 13 should see ads. Seems weird, but OK..

NOW, This is the rub. I made 2 clicks to change the Age Rating from 3+ to 12+ and hit resubmit.. No code has changed. Nothing has REALLY changed except that my age was set too low. Where am I in the process now? At the back of the line waiting another 7 days to hear if there was anything else.

[Warning Rant to proceed from here on]
I’m assuming that most of the tough stuff is out of the way, but I don’t really know. It does seem strange that I went through the whole process already and I have to wait 7 days. I mean I already passed presumably a number of issues. It seems like a waste of EVERYONE;’s time for me to have to wait and to have EVERYTHING thus far tested for a ZERO code change (no new binaries have been uploaded). This process needs to be streamlined some more that is for sure. Especially considering they want to have 100,000 apps in the Windows Store by January. If they don’t change the process some then that goal will never happen. Just my 2 cents.

Why MetroOAuth? or C# Async makes life easier 

Wednesday, July 18, 2012 12:36:04 PM Categories: WinRT/WIn8-Metro WP7

Yesterday, I finally pushed some of the oAuth libraries I have been tinkering with. I have a really nice and simple library (and this simplicity seems to flow throughout the library). I decided to pull out some examples using my DropboxClient to show how much simpler a library can be.

Here’s how you log in to Dropbox (in c#):

// if the user has already auth'd you can save this in ISO Store or localstorage
var accessKey = ""; // in our case we are setting it to empty (but it's not required)
var client = new DropboxClient(kDropBoxAppKey, kDropBoxAppSecret, accessKey);
var authd = false;
if (client.IsAuthenticated) // do we already have an access key
  authd = true;
else
  authd = await App.DropboxApi.Authorize("http://www.tbwindev.org"); // URI to go to once logged in
 
if(authd)
{
    // Do something
}

We put everything into that example just so you can see the full set up. You don’t need the accessKey for instance and can simply leave it off that call (it’s optional). Like the comment says, after the user has Authorized your app you can grab that value from the client (stored in a property) and save it off, and then the user will not need to re-authenticate.

The “if” statement where we check if the user is already authenticated is really a convenience method, but you don’t want to re-authorize the user.

The only lines you really need are the creation of the DropboxClient and the line to Authorize.

Now what is behind that Authorize call is what makes this amazing to me. There are 2 http calls that happen with a call to the WebAuthenticationBroker to show the user a web browser window that is on the Dropbox site. All of these things happen asynchronously, but they happen in order. So, there is a call to get a temporary key which we use with the URI that we push the user to the Dropbox site’s login. After they have logged in (or closed the windows), we check to see if we got a code from the call. If so we make a call to get our official accessKey, and we can proceed from there. Again, all of this happens asynchronously, and your UI will be responsive during this time.

Async makes it so we don’t have to set up any kind of response action or event, etc. Each of the calls returns a Task or a Task<T>. We simply tell the compiler that we want to wait for the task that was passed back to us to complete before we proceed. Inside of the task that we get back there might be other tasks that get awaited. This makes it possible to have a method have a single responsibility without having to clutter it up with what happens or a link to what will happen on return.

 

AND, all this works in Metro and WP7.x (as long as you install the Async CTP)

Anyway, I’ll blog some more on this soon.

BTW, my project is at http://metrooauth.codeplex.com and the current (rather cluttered) code repo is at https://bitbucket.org/DevTheo/metrodropbox

Metro Nuggets: Cloud-based File Contracts helper - UriBasedStorageFile 

Wednesday, March 28, 2012 3:19:12 PM Categories: WinRT/WIn8-Metro

I have been doing a series of posts around my adventures in creating a cross-platform Dropbox library for Windows Phone and WinRT. I actually have a working API at this point, so of course the next step is to look into implementing a File Open Contract.

One of the first things you will notice is that you have to return set of IStorageFile back to the caller. So you have to essentially hand back a mechanism that the caller can use to open your file from the cloud (without the caller necessarily needing to know anything about that). At least this is my understanding at this point. I might have to pre-download my files (something I will be testing very soon).

Regardless, I thought it would be nice to go ahead and implement IStorageFile based on an URI. So I have created (and am letting you tinker with) this class. Here’s what happens with it. You call the constructor of my class with a URI that can be used to access the file (aka download the file), and my class builds up a read-only file that the file system thinks is a regular old file (BUT there are a bunch of things unimplemented, so you won’t be deleting files for instance). You can even control how the class acts when an unimplemented function is called (it can silently fail or generate an exception).

Let’s see some code:

var cloudFile = new UriBasedStorageFile(
            new Uri(someUrl, UriKind.Absolute), 
            "Application/text", // optional mime type (default is "application/octet-stream")
            "test.txt", // optional file name (default last part of the path)
            true); // Ignore Not Implemented items
var file = await cloudFile.CopyAsync(Windows.Storage.KnownFolders.DocumentsLibrary);

Yep, that’s 2 lines of code to copy a file from a URI to a file. Pretty cool hunh?

Implementation details (stuff I learned)

Implementing this interface is a little difficult. Well, not majorly so, but there are some gotchas. First of all, I am used to working with Tasks, something that you will get very familiar/comfortable with when/if you get into the Async stuff. The interface requires that you return IAsyncActions and IAsyncOperation<T>s. If you look at Task you will see that it implements this at some level, but casting does not work. After digging a bit I discovered an extension (which is a part of System). Essentially you can call your functions that return Task and Task<T> and then call AsAsyncAction() or AsAsyncOperation() on the returned Task to get it cast to the appropriate type.

Design

So, here’s what I did with this class. I implemented the interface and then call individual methods that  return Task based equivalents and then use the AsAsync___ extension methods mentioned above. My actual methods are virtual and protected (which means you could derive a new class from them and override the missing functionality and get a something that is closer to fully functioning). I’ll actually be doing this with my Dropbox implementation so I can pass Dropbox-based files to the OS and things will act like these are actual files on the file system. Pretty cool, hunh?

By the way, none of this is done yet. If you want to help out, let me know.

Also, my description of building a File Open Contract may be incomplete. Like you I am learning this stuff. There might be a future post where I state that everything I knew is wrong. As far as the Open contract goes, at this point I am assuming that I will need to hand back the object and the caller will be able to open up the file. I am hoping that the caller will not need any kind of Internet access defined, but if that happens I will be rewriting these classes a little (so that this isn’t required.

So here’s the link to where the project lives: https://bitbucket.org/DevTheo/metrodropbox/overview
Here’s the link to where the file lives: https://bitbucket.org/DevTheo/metrodropbox/src/3617e9282c60/Common/IStorageFile

Oh yeah, the code from the last couple Metro Nuggets can be found here as well. (there have been some updates. For instance the Windows Phone WebAuthenticationBroker object has changed a little due to a bug I discovered).

Metro Nuggets: WebAuthenticationBroker an oAuth solution 

Tuesday, March 20, 2012 4:09:35 PM Categories: WinRT/WIn8-Metro WP7

A few years ago I worked for a company that sponsors the Facebook C# SDK. I wrote a number of the initial demos and answered questions on StackOverflow for the project. I know what our users’ biggest challenge: getting an AccessToken.

In terms of oAuth getting an AccessToken for an App is the equivalent to logging in. Essentially you are authenticating and getting permission from the user. As previously mentioned, I am building a Dropbox client for Windows8 Metro. Dropbox has a new oAuth style library which is (or at least appears to be) the recommended manner to communicate with Dropbox programmatically. So, my new Windows8 Metro/WinRT library needs to communicate in this manner. We will not go into the ins and outs of oAuth, but the first steps are pretty critical for you to understand. Here’s what they are (provided you don’t have an AccessToken, yet):

  1. Get a RequestToken (this is a temporary key/secret) for your application
  2. Redirect user to specific URI –inside of a browser window of some sort-- to logon and accept your app (you can provide an optional redirect URI which the user gets sent to after authenticating and accepting your app)
  3. Detect that the user has accepted your app, and get an AccessToken (a more permanent key/secret) using the request token

The next steps after this are to first save off the AccessToken and then use the AccessToken when making requests to the REST API. There’s a lot wrapped up in this, but the 1st step and the 3rd step are simply calls to the REST API (they are signed in a manner outlined by the oAuth spec, but let’s not get too heavy into that). That middle step is problematic for people. Constructing the URI is easy, but monitoring the Browser can be a problem for some reason.

Enter the WebAuthenticationBroker
Microsoft solved this for us in Metro/WinRT. They have a gizmo called the WebAuthenticationBroker. Essentially this manages the process for step 2. The challenge is that sometimes an oAuth service will return additional data that we need in the QueryString of the call to our callback URI (yep, we need to do that). Cutting through all that can be a little work –especially when all you really want to be able to do is make a call to a service and use a third party API to facilitate that. Here’s what it looks like:

WebAuthBroker

Essentially a chromeless browser window appears on the screen. Now I fully expect that Dropbox will be detecting the Windows8 Metro UI and will give us a slightly different UI (right now you have to scroll over to the login). A couple additional important items here. If you look closely you will see 2 links at the top of the WebAuthenticationBroker’s control. The one on the right restarts the process presumably taking the user back to the original URI. The one on the left allows the user to simply say “let’s go back to the app.”

The code for this is awesome! I can’t stress how cool it works. Basically you do an await on the WebAuthenticationBroker. It returns you an object that indicates whether the user canceled, an error occurred, or we successfully got to the target URI. If we got to the target URI then we also get the additional data passed in with that request via another property. Here’s the pertinent snippet of code from my library:

String DropBoxUrl = await GetAuthorizeUri(endUrl);
 
System.Uri StartUri = new Uri(DropBoxUrl);
 
System.Uri EndUri = null;
if(!String.IsNullOrEmpty(endUrl))
    EndUri = new Uri(endUrl);
 
Debug.WriteLine("Navigating to: " + DropBoxUrl);
 
WebAuthenticationResult WebAuthenticationResult;
if(!String.IsNullOrEmpty(endUrl))
    WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                        WebAuthenticationOptions.None,
                                        StartUri, 
                                        EndUri);
else
    WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                        WebAuthenticationOptions.None,
          
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success ||
    (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.UserCancel && WebAuthenticationResult.ResponseData != null))
{
    Debug.WriteLine(WebAuthenticationResult.ResponseData.ToString());
    var accessToken = await GetAccessToken();
}
else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
{
    Debug.WriteLine("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
}
else
{
    Debug.WriteLine("Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseStatus.ToString());
}

I try to get an AccessToken regardless of whether the user canceled or not because if the programmer didn’t specify an EndUri then I need to assume the user might have simply closed the WebAuthenticationBroker control via the link (back to app).

Anyway, this is a very cool mechanism. I don’t have to attach this code to the UI in any manner. It simply injects itself into the UI all on its own.

Windows Phone compatibility object
I have also mentioned that I am back-porting this library to Windows Phone. In the process I realized that I needed a mechanism like this one. In fact after looking at this one, I have to say that this is the way it SHOULD be done. I haWebAuthBroker-WPd arguments with a few folks back in the day with the FB C# SDK in that I thought we should provide the mechanism. I was shot down (mainly because there were too many scenarios to handle.. that project provides Facebook to everything). Anyway, going back to that SHOULD be done. I realized that there should be a mechanism like this for Windows Phone. I have done that. Warning: it does rely on the Async CTP (truth be told this is what sold me on Async), BUT the code for Windows Phone is the same as the code above. To the right is a scrren shot of the the same code running on the Windows Phone emulator (using my compatibility object):

As you can see Dropbox knows the Windows Phone browser and presents a nicer dialog. You can also see that I have the same links in the project, etc. My underlying object injects it’s UI on top of the current page, so you don’t need to add anything other than the 3 files to your code to get this. There’s still work to be done.

I am attaching an early release of this to this post (but will probably bundle my compatibility plugins into an open source project (or at least will be exposing the source code repository publicly). I need to figure out a few more things before I can call this close to done, but feel free to play around with it (and if you spot any bugs or fix them.. let me know).

Metro Nuggets: Async is your friend 

Tuesday, March 20, 2012 2:15:04 PM Categories: WinRT/WIn8-Metro WP7

I’m in the process of exploring the Metro-Style Win8 API. If you’ve done much looking you probably have discovered that the new Async is everywhere! This is not a bad thing as your code is much cleaner and easier to read. The downside though is that creating something that is compatible between say Win8 Metro and Windows Phone (the original metro) can be difficult.

Luckily there is still a CTP of the Async stuff that works with Windows Phone (and it has a GoLive license, so you can use it). CTP sounds scary (it did to me too). If you are deciding to do install the Async CTP, you might want to go here --http://blogs.msdn.com/b/lucian/archive/2011/11/01/async-ctp-v3-installation.aspx-- and read up.. since I am betting you –like I-- have some VS patches that will prevent you from installing it). To get it installed you need to temporarily uninstall the Silverlight 5 tools and any Visual Studio patches after say December.. if you look at the link it will get you started (there are a couple forum posts that were helpful to me).

Now you are ready to play. I’m sure by now you have seen the syntax, but let’s make some comparisons (and we’ll use WIndows Phone code and an example on a class that I have rarely seen discussed: HttpWebRequest):

Here’s the old way (warning there is a lot of code here):

   1: // Pretend like Item info below just contains a couple pieces of info:
   2: //  like Uri, Method, and possible a filename to save to --in IsoStorage
   3: void downloadSomething(UriInfo item) { 
   4:     var webReq = HttpWebRequest.CreateHttp(UriInfo);
   5:     webReq.Method = item.UriMethod;
   6:     WebRequests.Add(item, webReq);
   7:     // If we were passing post values to the routine we would need to 
   8:     // Begin getting the request stream with a callback and then End Getting 
   9:     // the request stream (this is bad enough.. don't want to overcomplicate things)
  10:     webReq.BeginGetResponse(ResponseCallback, item);
  11: }
  12: protected void ResponseCallback(IAsyncResult ar) {
  13:     IFileItem item= (IFileItem) ar.AsyncState;
  14:     var webR = WebRequests[item];
  15:     var resp = (HttpWebResponse) webR.EndGetResponse(ar);
  16:  
  17:     if (resp.StatusCode == HttpStatusCode.OK) {
  18:         // We could also do the whole Begin/End on the Response Stream 
  19:         // (with another calllback)
  20:         using (var strm = resp.GetResponseStream()) {
  21:             var buffer = new byte[4096];
  22:             item.BytesDownloaded = 0;
  23:             // If the file exists we need to delete it (BTW, using Jay's IsolatedStorage Facade which looks like System.IO.File, Directory, FileInfo, and DirectoryInfo -- "PS" stands for persisted storage)
  24:             if (PSFile.Exists(item.DestinationNameAndPath))
  25:                 PSFile.Delete(item.DestinationNameAndPath);
  26:  
  27:             // We should actually check to see if the path exists for this file.. 
  28:             // BTW, this uses my Isolated Storage Facade classes 
  29:             // (so PSDirectory == SystemDirectory, but just against IsolatedStorage)
  30:             if (!String.IsNullOrEmpty(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath)) && !PSDirectory.Exists(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath)))
  31:                 PSDirectory.CreateDirectory(System.IO.Path.GetDirectoryName(item.DestinationNameAndPath));
  32:  
  33:             using (var fs = PSFile.Create(item.DestinationNameAndPath)) {
  34:                 var fileLength = item.ActualSize;
  35:                 do {
  36:                     int count = strm.Read(buffer, 0, 4096);
  37:                     if (count < 1)
  38:                         break;
  39:                     fs.Write(buffer, 0, count);
  40:                     item.BytesDownloaded += count;
  41:                 } while (true);
  42:             }
  43:             item.BytesDownloaded = item.ActualSize;
  44:         }
  45:     }
  46:     //else 
  47:         // We got an error or something. Normally I notify the end user of this (this is left up to you to do on your own)
  48:  
  49: }

New Way:

   1: public static async Task<string> simpleHttpPost(string url)
   2: {
   3:     var uri = new Uri(url);
   4:  
   5:     HttpWebRequest client = HttpWebRequest.CreateHttp(uri);
   6:     client.Method = "POST";
   7:  
   8:     var response = (HttpWebResponse) (await client.GetResponseAsync());
   9:     var _lastResultCode = response.StatusCode;
  10:  
  11:     if ((int)_lastResultCode < 400) {
  12:     using (var strm = (new StreamReader( response.GetResponseStream())))
  13:         return await strm.ReadToEndAsync();
  14:     }
  15:  
  16:     return "";
  17: }

Admittedly when giving examples you try to keep the code similar for comparison sake. I decided to simply grab some code from my new project and from an old project. Please forgive me. I will do my best to highlight the big differences here.

The old way with HttpWebRequest was that you did a Begin____(callbackFunction) for nearly everything. The callback function must (among other things) call End______() to actually get what you were looking for (this could be the RequestStream, so you could make a post and push post variables, or it could be the response, or the ResponseStream – the ResponseStream at least has a synchronous version which I used above). Because this was going on you could use delegates and not lose context, but the execution order was jumbled.. so essentially you created a delegate for each callback (so the code came first) then you would call the Begin which would go out do the activity and then make calls into your code that was previously defined.. it is very ugly and hard to follow what is happening…

The new way introduces the use of the await or Await (in VB) keyword. When I first saw this I thought it was a gimmick, but the reality is that our APIs can be cleaner. You get the ability to simply suspend execution of your code while you wait for something to come back. You do have to mark your function with the async (or Async in VB) Keyword and use Task<T> as a result.

I really feel like the second example is much cleaner and easier to follow. At the very least you know what order things are happening..

An Added Benefit
Let’s make a not so contrived example to show you something else that is pretty cool. Let’s assume that we have an app whose first action is to run out to a service of some sort and get some data that will be databound to the UI. Meanwhile we have a few additional things that need to be done (so we don’t want to be prevented by the download)..

   1: protected void setupMainPage() {
   2:     getData();
   3:     // Next line will happen before the getData call fully completes
   4:     // this is because we are not "await"ing the return
   5:     doSomethingElse();
   6: }
   7: protected async void getData() {
   8:     var result = await simpleHttpPost(new Uri("http://someDomain.com/someService"));
   9:     var dataObject = deserializeObject(result); // turns json string into object
  10:     this.DataContext = dataObject;
  11: }

So essentially we can fire things off and when they complete they will continue running. We don’t have to await everything.

Preview of Future posts
At present I am building a new Dropbox client library for Windows8 and am retrofitting it for Windows Phone. To do this I had to create some compatibility objects for Windows Phone to make this happen. I actually also had to create some helper objects that do things like HTTP because they are very different and I wanted to avoid compiler directives as much as is possible. I will be writing about all of this in the coming weeks. I will eventually be speaking at a combines Tampa Bay Windows Phone UG and Tampa Bay Windows Dev UG meeting about all of this.

Windows8 CP: Almost there! 

Friday, March 02, 2012 8:09:16 AM Categories: WinRT/WIn8-Metro

So this is more of a review and less of a techy post. Yesterday as I was exploring Win8, I discovered 2 apps in the store that are important in my mobile world: EverNote and the YouVersion Bible.

You see, I have a daily routine where I bring up YouVersion on my Acer Iconia (Android) Tablet (before this I used an iPad2.. before that I had a less techy way of doing this). I read a little scripture and then note a couple verses and then I bring up EverNote paste in the scriptures and write a few notes for myself as well as do some general journaling. It helps to keep my thoughts together before I go full force in my day.

I was stoked because I could possibly move entirely to Windows 8. I actually started checking prices on Tablets that would run Win8, and I was thinking I could have my tablet experience with the full power of Windows.. this would be more than cool!

Now I tried this with the developer bits, but the desktop EverNote didn’t bring up the keyboard appropriately, I gave up and went back to my iPad at the time..

So this morning I tried it. You can guess by the post’s title that something didn’t work. I was actually able to not only bring both apps up, but pin the Bible on the left hand side. Where things failed was EverNote. It let’s you edit notes, but I could not change the notebook I was saving too. It seems to default to a Notebook I set up to do a knowledge transfer to my job (as I was leaving the company). I also couldn’t figure out how to edit after I had accidently closed the notebook. I will have to wait for an update to EverNote before I can really use this.

Oh yeah, I will also be wanting the YouVersion guys to update their app and give me offline bibles (otherwise I have to have wifi always which in the morning isn’t too much trouble).

Beyond this fact I am liking the evolution of the OS from the Developer Bits. I have read some stuff about how the OS isn’t necessarily intuitive in all respects, and I would concur. I have watched all the intro videos, so I know to swipe up to get app’s menu or swipe on the right hand side to get the charms or to swipe left to bring in an already running app.. and I figured out the whole swipe down to be able to throw your app off screen (shutting it off).

Forced Landscape Printing in Silverlight (On a Mac) 

Tuesday, February 14, 2012 11:25:02 AM Categories: Silverlight

I ran into an issue with the Silverlight5 app I am working on. One of the very important things in this app is the ability to print (in formats other than Letter format in portrait mode). My client uses a Mac and as he was testing the app on his Mac he discovered that the print dialog did not offer Landscape printing to him. After searching quite a bit on the Internet I discovered that low and behold Silverlight (both 4 and 5) don’t really have the best story for Landscape printing on a Mac. In fact if you are using Silverlight to produce printouts, you need to be aware of this fact especially when you know that your printout must be on a Landscape page.

The solution is relatively simple (and I discovered the initial technique in this blog post – http://earok.net/sections/articles/web-dev/easy-landscape-printing-silverlight?page=3%2C8)

This essentially gives us the ability to print Landscape, but on a PC the user could choose landscape mode. Here’s how I detect it:

bool rotateContentForLandscape = false;
void doc_PrintPage(object sender, PrintPageEventArgs e)
{
    rotateContentForLandscape = (e.PrintableArea.Height >= e.PrintableArea.Width);
    var printedPage = generatePrintContent();
 
    if (rotateContentForLandscape)
    {
        var transformGroup = new TransformGroup();
        transformGroup.Children.Add(new RotateTransform() { Angle = 90 });
        transformGroup.Children.Add(new TranslateTransform() { X = e.PrintableArea.Width });
        printedPage.RenderTransform = transformGroup;
    }
    e.PageVisual = printedPage;
}

I use a class level variable rotateContentForLandscape, so in the process of creating content I can detect if there are any weird edge cases where I need to generate something slightly different (I might never really need this). The whole TransformGroup code (inside the If) simply rotates the content and positions it properly on the print page.

That’s all there is to it. Depending on your UI you might not want to detect quite like I’m doing. Your preference might be to have a checkbox in the UI to force landscape and then do the Landscape detection.

Page 1 of 4 1 2 3 4 > >>
Site Map | Printable View | © 2008 - 2013 Intradynamics | Powered by mojoPortal | HTML 5 | CSS | design by dcarter