BindableApplicationBarBehavior – Windows Phone 7

Many have claimed to have created a bindable ApplicationBar for the lacking Windows Phone 7 OS. After hours of searching for one that would fit my needs I discovered that they are all lacking or not implemented in a way that was sufficient for my needs. I set out to create my own implementation with the help of Tim Askins and Travis Schilling. What we came up with was not an ApplicationBar replacement or derivative, but a new behavior that can be added to any page in XAML. Note this is NOT an attached behavior. We are inheriting from Behavior<T>.

Why a behavior?

Behaviors have no UI. If we were to use any kind of Control derivative the created control would allow placement anywhere in the UI tree. It would need to do extra work to traverse the tree and find the page as well. This also means that it could potentially be part of a UI tree that was invalid. This concept did not make sense to us. By using a Behavior we force the developer to place the behavior as a first class citizen of any page, and it is restricted to PhoneApplicationPage, but would work with derived pages as well. The behavior is also not part of the UI tree.

Any problems with using a behavior?

The behavior is designed with a collection of ApplicationBarIconButtonDelegate objects. These objects expose many of the same dependency properties which a normal button would expose such as IsEnabled, Command and CommandParameter. They also expose an IsVisible and an IconUri property. However, when these objects are being bound to in XAML they live inside of the behavior. This seem like a no brainer, one just needs to remember that means there is no DataContext to pass around. This was easily overcome by setting the page’s DataContext as the DataContext of each button in the override of the OnAttach method. Once this was done each button delegate was able to bind as expected. In the current implementation we do not handle the case where a page does not have a DataContext, however this would be easily overcome by adding an optional DataContext DependencyProperty to the behavior.

Where’s the code?

After testing the code a bit more I will post up what we have created. Assuming all goes well that will be next Wednesday or sooner.

Font Hybridization in HTML 5

Over this Christmas break, I was over at a friends house and got to sit down and tinker with my friends Mac. I’d forgotten how good fonts look, and I suddenly realized why so many sites are now using custom web fonts. Since I primarily use Windows at work and at home, I get annoyed by fonts that are difficult to read or that don’t render well on the screen. Somehow, I’ve never been 100% happy with font rendering on windows. It’s been getting better, but it’s still not as good as a Mac is. Maybe its the screen, maybe its the OS, maybe its the app, maybe its a combination of all of the above. Because I’ve been on this HTML kick, and I’m on windows, I’ve tended toward Cufon as my font replacement tool of choice when building sites since it’s the only one that produces a “more-reasonable” output on my machine.

But Cufon by it’s nature has several drawbacks. First, you can’t copy and paste text rendered with Cufon. With most of the newer browsers you can select it, but there’s not much more you can do beyond that. So, I usually limit Cufon usage to titles, headers, and the more “design-ery” aspects of a page. Second, because Cufon is image based, if someone zooms in on your text beyond 100% Cufon rendered text gets all fuzzy the same way it would if you zoomed in on an image. And finally, because Cufon renders with javascript on the client, there’s no way to cache the text. Javascript is fast, but when you’re rendering a large amount of text on a phone, there’s usually not a good way around a flash of unstyled content. And it happens each time you go to a new page because it can’t be cached.

Web fonts on the other hand, allow you to use fonts in a very similar manner as if you had them installed on your device with native rendering by the OS. You can select, copy, paste, and use it as you would any other piece of text. Web fonts are cacheable, so although you could get a flash of unstyled content when you first visit a page, subsequent visits should render immediately. The disadvantage however, is the OS. On windows, the rendering of fonts just… Sucks. So people don’t use it.

But what if there was a way to do a hybrid between Cufon and Web Fonts?

Besides the rendering issue, Web Fonts are the best option. They’re the most flexible and the most future proof. But they still suffer on Windows, some phones, and on older browsers that don’t support the new @font-face CSS syntax. So what if we did a hybrid? Use @font-face, then fall back on Cufon for older browsers, and for windows. The advantage is that on a new browser the@font-face‘s will be cached, used for the initial rendering of the page, and then cleaned up with Cufon later.

Using Modernizr and a little custom javascript to do user agent testing I put together a page to test out the hybrid font idea:

http://www.paulrohde.com/demo/cufon-hybrid/demo.html

It’s a rough draft. I have some screen shots below from both Mac and PC’s (click for full size versions).

Mac

PC

For simplicity, the javascript code to test and load Cufon and my custom cufon polyfill looks like this:

function rendersNiceFontface() {
	result = navigator.appVersion.indexOf("Win") != -1
		|| navigator.appVersion.indexOf("Android") != -1;
	return result;
}

var supportsNiceFontface = !rendersNiceFontface();

Modernizr.load([
	{
		test : Modernizr.fontface && Modernizr.canvas && supportsNiceFontface,

		nope : [ 'cufon-yui.js', 'BebasNeueRegular_400.font.js', 'cufon-polyfill.js' ]
	}
])

Using the Modernizr yepnope.js, I’m able to completely skip loading Cufon at all if the browser supports good @font-face rules. There’s more that I’d have to do to clean it up before I’d use it in a real setting, but it demonstrate the concept, and is something I could definitely use later as a @font-face polyfill. It does have some drawbacks though, you have to maintain both your CSS rules and your Cufon replacement calls, and Cufon doesn’t work well with a large amount of body text, so if you don’t support @font-face, I’d fall back to a good secondary font and forgo Cufon in those cases.

I hope this got some gears turning, I’m looking forward to some comments.

iOS 4 Persisting Data

I’m thinking of writing a very simple iOS app that has a login control. So a user can register or login with an existing account. While brain-storming how to approach this, I’ve looked in to SQLite that has been around for the longest time or using from the Cocoa Touch Library that was introduced in iOS 3, Core Data Framework. Currently I’m in the middle of researching the difference between the two. But I started thinking more and obviously I want my repository to be at a central location so multiple devices running my simple login app can access it.

Thus, I’m also looking into setting up a web service, perhaps a WFC service and throw it up on a web service I own. Then write some objective-c in my login app using NSURL, NSURLRequest and NSURLConnection classes. While scouring online, there’s a great SDK by Red Gate company, MobileFoo called iSQL SDK that allows you to retrieve data from a SQL Server at http://www.mobilefoo.com/ProductIndex.aspx. Look forward to a future blog post as I’ll play around with their SDK and see how seamless their wrapper classes allow me to hook up my login sample client app with a SQL Server database that will authenticate a user.

Azure Table Storage Exceptions with Multiple Table Entity Schemas

 

I’ve been messing with Azure Table Storage recently and needed to create a somewhat nontrivial data model to try some things. 

This data model includes patients, patient addresses (email, IM, postal, phone, etc.) and patient events.  I also wanted to store all of this data in the same table so I had table entities with differing schemas in the same table.

I then wrote some code to created an array of patients and for each patient I added the patient record and a random number of different patient addresses to the table. 

The more I work with Windows Azure the more I come to the conclusion that debugging Windows Azure code is like a Doctor treating a patient, i.e. make random changes and see if that fixes the problem.  Trying to figure out what the problem is from the exception information is like looking in a crystal ball in that it just doesn’t show anything other than what you can imagine.

Executing the code results in what appears to be one of the most common exceptions there is when working with Windows Azure:

{Microsoft.WindowsAzure.StorageClient.StorageExtendedErrorInformation}
    AdditionalDetails: null
    ErrorCode: "InvalidInput"
    ErrorMessage: "0:One of the request inputs is not valid."

 

So my next issue is that I had added multiple records so which one was causing the problem?  To figure that out you need to enumerate the DataServiceRequestException.Response property.  You get an IEnumerable<ChangeOperationResponse> collection from this property.  From my experience so far there only ever appears to ever be one entity in this collection no matter how many records you create that would have had problems.  What you look for is a header by the name of “Content-ID” on the OperationResponse.  The value is the 1 based index of the records that were added before calling TableContext.SaveChangesWithRetries(SaveChangesOptions.Batch).

You can see this a lot better if you use Fiddler to view the input/output of the batch request.  See http://learningbyfailing.com/2009/12/using-fiddler-with-azure-devstorage/ to see how to get Fiddler to display the output.

In my case it kept pointing to the second record that I added (the first was the patient record and the second was an address record).  If I saved the patient record by itself it worked and if in a separate batch I saved the address records it worked.  So in spite of the exception pretty much not telling me what the problem was I came to the conclusion that I can’t mix table entity schemas in a single batch.  Apparently this is a restriction for development storage but will work when using cloud storage.

It’s too bad the exception didn’t tell me this.

WinLiveHelper for Windows Phone 7

Today I’m proud to announce the home of WinLiveHelper on codeplex. The purpose of this library is to provide lightweight objects and the http calls required to easily interact with the Windows Live SDK that was released 7 Dec 2011. I will be starting with Calendaring and then moving to Documents. After that we’ll see what priorities come up. If you’d like to help out let me know!

Overview of Stanford Online Class Introduction To Databases

For the last 10 weeks, I’ve been taking the Introduction To Databases class online through Stanford, http://www.db-class.org. I’m just going to write an overview of my experience with the class. The class was taught by Professor Jennifer Widom. She did an excellent job of lecturing us on topics that covered Relational Databases, XML, Relational Algebra, SQL, Relational Design Theory, UML, Indexes, etc at a high level. Her process of video lectures and PowerPoint/PDF slides helped understand the information. She also provided Optional Exercises and resource textbooks to help you prepare for the weekly quizes/exercises and exams.

The QA Forum message board helped a lot to get through the class. It allowed students to socialize and interact on the course material. If you didn’t understand a topic discussed in the video lecture, a student would post a message and in minutes another student would comment or help explain the topic. This helped me solve homework problems I was having trouble finding a solution. Overall, this class was a great introduction to databases. It leaves me wanting to take another class to learn at a lower-level about databases. Plus, the Stanford online class was FREE.

The Kinect SDK and Xbox: Part Deux

So in my previous post on this topic I was trying to made an effort to discover some details about who, exactly, can become an Xbox developer, and have access to the Kinect API.   The information is not readily available, and the most info I could find was from this page.

There it states that to apply to the Xbox 360 Registered Developer Program,  you need to send an email to xboxrdb@microsoft.com with your contact info and a game concept.  If the proposal is of interest, you will be contacted.

Cool!  So I applied, describing who we were and what we wanted to do- which would be of great benefit to all mankind by the way.  I figured that they would probably ignore it if it wasn’t interesting , but if they responded I could glean some information about what there entry requirements were.  And maybe… just MAYBE we would get in!

I figured it would take some time for them to respond so I prepared for a wait…

But to my surprise, I had a response the next day!  I think I may have hit a nerve though, here’s what I got back:

“Thank you for your interest in developing for the Xbox 360 and Kinect for Xbox 360.

The Xbox 360 Registered Developers Program works exclusively with professional game developers. It is only open to qualified professional game development companies with a wealth of previous professional industry experience, financial backing and solid game concepts. As such, your inquiry lies far outside the scope of this program.”

Well!  So not only did they just pooh-pooh the request, they managed to sound a bit snooty about it as well.   Excellent.

But anyways, now what can we learn from this?

  1. To be in the Xbox 360 RDP you need to be a professional game developer
  2. You must have a wealth of previous professional experience
  3. You must have lots of money (how do they know we do or not?)
  4. You must have a solid GAME concept.

That’s the interesting part to me- GAME concept.  I take this to mean that unless it’s a game, you cannot be on the Xbox 360 platform.  Healthcare app to help people?  Nope.  App to assist in the home for the elderly?  Not likely.

But I won’t cry about this.  I think the SDK is improving rapidly.  With a commercial version set for Q1 of 2012 and active development it would appear to have a bright future indeed.

Ah well, back to my Kinect SDK development!

The Real-Time Web With SignalR

Today for RECESS I looked into SignalR.  The SignalR site (which currently is just the github repository) describes it as an “async signaling library for ASP.NET to help build real-time, multi-user interactive web applications.”  What does this mean to you and me?  This library allows you, in just a few lines of code, communicate in real-time amongst browsers that are hitting your site.

Scott Hanselman does a good job of summarizing what SignalR does and how we got here, so I won’t repeat it here.

I followed the super quick sample – a browser based chat application as described Scott’s post.  I ran out of time before I could get the lower level connection working, but the higher level “Hub” based connection works great.

It’s super cool to see it working – I have 3 different browsers (IE, Chrome, Firefox) in the chat together.  When I enter a chat message in one, the other two receive the message instantaneously.

    $("#broadcast").click(function () {
      // send() is the method on the ASP.NET Hub class running on the server
      chat.send($('#msg').val());
    });

The use of dynamic objects in the ASP.NET implementation of the Hub allows me to call any method on the Hub, as long as that function exists in the client side JavaScript.

    public class Chat : Hub
    {
        public void Send( string message )
        {
            // addMessage is a client side javascript function
            Clients.addMessage(message);
        }
    }

Here’s a couple shots of IE Developer Tools (F12) when running the chat client.

Waiting for a response on the first call to signalr/connect:

CropperCapture81

Got the response from the first connect (a message was broadcast to all the clients), now turn right around and connect to wait for the next “reply” from the server:

CropperCapture82

 


 

Windows Phone 7 – Windows Live SDK

Talk about good mojo! 7 days ago I was I was researching how to access Windows Live and SkyDrive from my Windows Phone 7. It just so happened to be the release date of the brand new Windows Live SDK that day, 7 Dec 2011. I now get the privilege to blog about my discoveries. Most of what I found is really good stuff. I’m going to let Microsoft do the heavy lifting on this one since their samples are quite good.

What is the Windows Live SDK?

The Windows Live SDK is a brand new SDK that encapsulates OAuth2 calls and the building of HTTP requests for Windows Live services. The SDK is very light and does not include model objects for calendars, files, etc. Microsoft has provided us with a Live Interactive SDK that walks through some of the available calls and allows the user to experiment with the JSON used.

What can I Access?

The documentation of what is available via the SDK is very comprehensive. The REST API is the one that I looked at. I’d feel like a member of the Redundant Department of Redundancy listing all of the capabilities of the API, so I’ll only mention a few: Albums, Audio, Calendars, Contacts, Folders, Files, Photos, and Videos. OK, so that’s most of them, but I’ll only talk about a few in specifics here.

Calendar

The Calendar portion of the API allows the developer to access all of the Calendars that the user has referenced in Windows Live. The developer can create, read, update, and delete a calendar. The developer can also create, read, update, and delete events on any of the calendars based on that user’s permissions on that calendar. This is a welcome API on the phone since developers can only read calendars and events in the current version of the OS.

SkyDrive (Folders and Files)

The same create, read, update, and delete capabilities that exist for calendars and contacts also exist now for SkyDrive. What I’m still working on is how to use SkyDrive to open a document on the phone from inside of a third-party application (not the Office Hub). Currently the phone only supports a Photo Chooser which cannot view Videos. I have a need to attach Videos and Files to a piece of information, and with the release of the Windows Live SDK developers can now access any uploaded file (video, audio, document, spreadsheet, etc.) that lives SkyDrive.

Thoughts

I’m hoping to create a light library of model objects that will work with JSON.NET for the phone that I’ll be able to pair with the Windows Live SDK. I’m very excited about the simplicity of the APIs and SDK. I’ve heard the horror stories of integrating Windows Live into an application prior to this SDK and set of APIs.

CSS Is A Lie.

According to Wikipedia:

Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (the look and formatting) of a document written in a markup language.

Furthermore:

CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable.

From my informal office survey, the general consensus is that the most important thing™ in CSS is that everything ‘cascades’ correctly. That is, that rules and styles defined further down in a CSS document override styles specified further up in the document (excluding the !important operator of course, which you should not be using anyways). It makes sense if you think about it, after all it’s not called a Cascading Style Sheet for nothing.

Now, the test. Given the following HTML and CSS snippet, what color will the two paragraphs be?

HTML

<p id="myid" class="myclass">
   Hello World.
</p>

<p class="myclass">
   This is another line of text
</p>

CSS

#myid {
   color: red;
}

.myclass {
   color: blue;
}

p {
   color: green;
}

The Answer:
Hello World is red, the second line of text is blue.

Don’t believe me? I put up a demo page with just the html and css here.

After a decent amount of Googling and reading blogs and the W3C Spec on CSS Selectors, I realize now how styles are calculated and applied, but seems to go completely against the ‘cascading’ nature of style sheets since the cascading nature of style sheets only applies when the ‘specificity’ values are the same.

For example, the following snippet behaves as you would expect:

CSS

p {
   color: gray;
   font-size: 20px;
}

/* ... later ... */

p {
   color: green;
}

As you might expect the paragraph will be green, and have a font size of 20px. The rule that is more specific selectors takes precedence over rules that are less specific regardless of where that rule is declared in the markup. You can mentally calculate how specific a rule by the ‘level’ and number of the selectors used. From low to high, you have

  1. Element and pseudo elements such as p, a, span, div, :first-line
  2. Class, attributes, pseudo-classes .myclass
  3. Id attributes #myelement #theonething
  4. From inline style attributes
  5. !important

If there’s anything of a higher level, the higher level overrides the lower level style, and if they’re the same level, the higher count wins, and if they’re at the same level with the same count (.myclass, and .myotherclass) then the one further down takes precedence, this is the “only” time cascading actually happens.

Its something that is unfortunately very subtle because of the way we write CSS, your taught from the begin to start with the most basic generic styles and work your way through the more specific styles. While this is correct, it’s very easy to go for a long time without running into a situation where a more specific styles.

I had no idea up until about a week ago that CSS worked like this. I always assumed that specificity was only used to select the subset of elements the rule applied to, and that if you applied a more general rule after a more specific rule that the more general rule would overwrite anything earlier. This is obviously not the case. If you want to read more, here’s some links to a few more comprehensive articles on the subject:

CSS Specificity and Inheritance: http://coding.smashingmagazine.com/2010/04/07/css-specificity-and-inheritance/

Star Wars and CSS Specificity: http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

Specifics on CSS Specificity: http://css-tricks.com/855-specifics-on-css-specificity/

Art and Zen of CSS: http://donttrustthisguy.com/2010/03/07/the-art-and-zen-of-writing-css/