Category Archives: Microsoft

Anything related to Microsoft technologies or the company

IKnow IEquatable

Well, now anyway. Sometimes I think the statement “Necessity is the mother of invention.” should – when applied to coders – be restated as “Necessity is the mother of fruitless hacks, StackOverflow searches and more code.” Catchy, eh?

Prior to my somewhat painful re-education (not going to use a diaeresis this time), I was operating under the ridiculous assumption that comparing to collections would be straightforward…if not downright simple. But my code kept telling me two identical collections were not. Of course a better coder would immediately recognize a reference problem underlying this. First I had blithely tried:

if (savedExercisesCollection != ExercisesCollection)
{
 for (int i = 0; i < ExercisesCollection.Count; i++)
 {
 ExercisesCollection[i].Order = i;
 }

App.StorageSettings["SettingsChanged"] = true;
}

But that was always returning true. Next, I turned to LINQ (’cause it is the solver of all problems, isn’t it?). Well, at any rate, my thinking was that it would actually compare the values. And it is elegantly concise:

if (savedExercisesCollection.Except(ExercisesCollection).Any())
{
 for (int i = 0; i < ExercisesCollection.Count; i++)
 {
 ExercisesCollection[i].Order = i;
 }</pre>
App.StorageSettings["SettingsChanged"] = true;
 }

I had also tried SequenceEqual but with the same sad results…until I stumbled across the IEqualityComparer<T> IEquatable @ http://msdn.microsoft.com/en-us/library/bb348567.aspx.

if (!savedExercisesCollection.SequenceEqual(ExercisesCollection))
{
 for (int i = 0; i < ExercisesCollection.Count; i++)
 {
 ExercisesCollection[i].Order = i;
 }

App.StorageSettings["SettingsChanged"] = true;
}

Now I was on the path to righteousness. All it would take is adding a comparer to my original class. I approached this with some trepidation since I’m relying on being able to serialize portions of that class. But the only way to know if something will blow up is to light the fuse. Turns out no worries.

I modified the class as follows:

[DataContract]
 public class Exercise : IEquatable<Exercise>
 {
 public List<Asset> AssetsList;

public Exercise(int id, int order, string description)
 {
 Id = id;

Order = order;

Description = description;

AssetsList = new List<Asset>();
 }

[DataMember]
 public int Id { get; set; }

[DataMember]
 public int Order { get; set; }

[DataMember]
 public string Description { get; set; }

 public bool Equals(Exercise other)
 {
 //Check whether the compared object is null.
 if (ReferenceEquals(other, null)) return false;

//Check whether the compared object references the same data.
 if (ReferenceEquals(this, other)) return true;

//Check whether the products' properties are equal.
 return Id.Equals(other.Id) && Order.Equals(other.Order);
 }

The take-home lesson from this is that unless an ObservableCollection is instantiated from the same source as another they are not automatically comparable. I can see this knowledge coming in handy when rehydrating a chunk of JSON, for instance to compare a remotely stored to-do list with one on the client.

Did ya hear the one about the serial killer?

Turns out his victim was found floating in a tub full of corn flakes and milk. Bahhh, dahhh, dahhh, da.

Anyway, in this case it was more that the serializer got killed…by an uncoöperative class. (BTW, that’s not an umlaut over the second “o”. It’s a diaeresis. Lovely sounding term. More on the subject: http://www.newyorker.com/online/blogs/culture/2012/04/the-curse-of-the-diaeresis.html). Typically, this happens because the class has a constructor with parameters. I couldn’t get around that. Well, I don’t want to anyway. I also didn’t want to depart from my vanilla JSON serializer, although in the past I’ve found SilverlightSerializer to be a solution when all else fails…like serializing an entire model. (Why would you want to do that? Long story, for some other time).

The solution is to simply mark up the class with the DataContract attribute and use DataMember for each of the members you want to serialize. In my case, this had the advantage of not serializing a voluminous sub-list I don’t want included. And it allows this class to be used in several places, rather than creating a separate Dictionary or similar.


[DataContract]
public class Exercise
{
 public List<Asset> AssetsList;

public Exercise(int id, int order, string description)
 {
 Id = id;

Order = order;

Description = description;

AssetsList = new List<Asset>();
 }

[DataMember]
 public int Id { get; set; }

[DataMember]
 public int Order { get; set; }

[DataMember]
 public string Description { get; set; }
}

And, voila, we end up with something that can be saved to IsolatedStorage:

[{“Description”:”JUMPING JACKS”,”Id”:0,”Order”:0},{“Description”:”WALL SIT”,”Id”:1,”Order”:1},{“Description”:”PUSH UPS”,”Id”:2,”Order”:2},{“Description”:”CRUNCHES”,”Id”:3,”Order”:3},{“Description”:”STEP UPS”,”Id”:4,”Order”:4},{“Description”:”SQUATS”,”Id”:5,”Order”:5},{“Description”:”TRICEPS DIP”,”Id”:6,”Order”:6},{“Description”:”PLANK”,”Id”:7,”Order”:7},{“Description”:”HIGH KNEES”,”Id”:8,”Order”:8},{“Description”:”LUNGES”,”Id”:9,”Order”:9},{“Description”:”PUSH UP & ROTATE”,”Id”:10,”Order”:10},{“Description”:”SIDE PLANK”,”Id”:11,”Order”:11}]

Localizable Balloon Tooltip Control

I wanted to create a tooltip in the style of the balloons used in Windows Phone apps like Messaging. Almost immediately, I realized it needed to be localizable, which would mean adjustable in width to accomodate text lengths in different languages.

In the past I’ve bound XAML elements, such as WPF menus to the ActualWidth of another element, e.g:

Width="{Binding ActualWidth, ElementName=window, Mode=Oneway}"

However, in this case I couldn’t get the desired result, which is to have a bit of padding on either side of the text. What documentation I read suggested that ActualWidth would take into account Margin settings. But I had to resort to a hack in the code-behind, adding a line to the constructor:


public MessageBoxControl()
 {
 InitializeComponent();

TextGrid.Width = MsgText.ActualWidth + 16;
 }

Here’s the XAML:


<UserControl x:Class="Controls.MessageBoxControl"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d"
 FontFamily="{StaticResource PhoneFontFamilyNormal}"
 FontSize="{StaticResource PhoneFontSizeNormal}"
 Foreground="{StaticResource PhoneForegroundBrush}"
 d:DesignHeight="56" d:DesignWidth="440">

<Grid x:Name="LayoutRoot" Background="Transparent" IsHitTestVisible="False" Height="56"
 Width="{Binding ActualWidth, ElementName=TextGrid, Mode=OneWay}" MaxWidth="440">

<Grid.RowDefinitions>
 <RowDefinition Height="32" />
 <RowDefinition Height="24" />
 </Grid.RowDefinitions>

<Grid Name="TextGrid" Background="#FFD68B" Grid.Row="0" MinWidth="200" MaxWidth="440">
 <TextBlock Name="MsgText" Foreground="#2368B0" FontSize="24" Height="32" MaxWidth="424"
 HorizontalAlignment="Center" TextTrimming="WordEllipsis"
 Text="{Binding Path=LocalizedResources.ResetMessage, Source={StaticResource LocalizedStrings}}"/>
 </Grid>

<Grid Grid.Row="1">
 <Path Name="Tail" Fill="#FFD68B" Data="M-1,-1,24,24,24,-1,-1,-1"
 HorizontalAlignment="Left" Width="24" Height="24" Margin="24 0" />
 </Grid>

 </Grid>
</UserControl>

Note that a MaxWidth is assigned to Grid and Text elements. Also, the TextTrimming attribute is set. This is meant to safeguard against exceeding the width of the display in Portrait mode. 

And a sample screen shot of a (hopefully accurate) French translation of “Hold to reset to 0:00”:

balloon_example

Coming around to MVVM

This is a copy-and-paste from an email to a friend, but has a few observations worth sharing publicly

A couple discussions on knockout.js, angular.js and backbone.js:

http://stackoverflow.com/questions/11083316/angular-js-or-knockout-js-integration-with-other-ui-libraries

http://stackoverflow.com/questions/5112899/knockout-js-vs-backbone-js?rq=1

Previously, I didn’t pay much attention to any of these. But am changing my tune. Why? I finally found a way to use the MVVM pattern that really makes sense and plan to follow that when it makes sense with web programming too. Props to Microsoft evangelist Jerry Nixon for his walkthrough video: http://blog.jerrynixon.com/2012/08/most-people-are-doing-mvvm-all-wrong.html, which in particular had some binding tips for Visual Studio I didn’t even know existed and a nice DelegateCommand class.

My initial experience with MVVM was miserable. For one thing, it is incorrectly named…should be MVMV (as in Model – View Model – View). But then, so is MVC, which should be Model – Controller – View. Because in both cases, the View Model or Controller is the code that sits between a UI View and the task-related code, e.g. a method that grabs a bunch of image URLs based on a search term. The MVVM framework I chose to use was complicated and couldn’t handle everything. Lots of hacks went into Ballistica. So, ironically, the promise of better maintainability was so broken that I’ve never found the time to update the app.

I also found that there is a lot of strict adherence to one model per view model. Really a model is just a class file. So if, for example, you need one class that handles status messages and another that build outlines there’s no reason why a single View Model can’t talk to them both. Now that I have that straight and have learned how to use my IDE more effectively, it has made much more sense. My current project has 111 lines of XAML in the main Window (including whitespace), but just 12 lines in its code-behind C# file (including whitespace and curly brackets)…and all it does is launch the window:

using System.Windows;

namespace HorizontalBuilder2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}

All the controlling logic resides either in the View Model class file or in the model classes.

Here’s an example of XAML that helps explain why Microsoft saw fit to not use SVG:

<MenuItem Command="{Binding BuildOutlinesCommand, Mode=OneWay}" Header="_Build Outlines" InputGestureText="CTRL+B" IsEnabled="{Binding Done, Mode=OneWay}">

<MenuItem.Icon>

<icons:IconGeom />

</MenuItem.Icon>

</MenuItem>

First of all, they could create things like application menus. Then bind various attributes to logical code. In this example, for instance, selecting “Build Outlines” from the menu triggers the BuildOutlinesCommand method. The underscore in front of the Header text allows the user to use ALT-key shortcuts, although I’ve never enjoyed that bit of Windows UI. It’s always just seemed easier to remember something like CTRL-B, which cuts out at least one step, so that’s included. The command is enabled depending on various states of the application. While you can name an item and refer to it in code, e.g. myMenuItem.Enabled = true, one advantage of this way is the menu item is now just a “subscriber” to the Done value. If I had, say, another item on screen like a big “Start” button it to could just use the same snippet. The alternative would be to have to keep track in code of all the items that need to be enabled or not. Also, the programmer can look at the XAML and know where to look in code for what effects the change.

Soon I’ll be posting a nice example of an MVVM app using async Tasks with real-time UI updating…and no freezing the rest of the UI.

New HICT 7-minute workout app for Windows Phone

Windows Phone users, you know who you are…the few and (mostly) proud, eh?
I got inspired by an article in the New York Times magazine (faithfully read by almost all ‘Hiders) on a 7-minute(ish) HICT workout and built an app to make it easy to run through the exercises and memorize the sequence. While I’d rather be out adrenalizing on my mountain bike, I’ve been enjoying going through the routine 3X a day. It’s a much better break than hitting the coffee pot and can be done almost anywhere. All you need is a chair and a section of blank wall big enough to fit your big behind against.
Check out the sped-up demo video:
And head on over to http://www.windowsphone.com/en-us/store/app/7-minute-workout/879efccc-5c9e-4b19-b8e6-346b76ff0133 where you can download a trial version for free.
As soon as I do some code cleanup and refactoring, I’ll be posting on some of the great things I learned (with a bit of pain) on async/await and creating accurate timers for Windows Phone and Windows 8 (using the same code of course!)

Kinda like Regex

So I’ve got this auto-incrementing C# TimeSpan that I need to format to just show single minutes and seconds, e.g. 3:48.

var timeSpan = new TimeSpan(0, 0, 0, secondsElapsed++);

Bugger took a while to figure out because I kept trying things like “m:ss” in my string formatter, not catching on that, just as in a Regex expression, I need to escape the colon. That can be done either by:

var timeStr = String.Format("{0:m\:ss}", timeSpan);

or:

var timeStr1 = String.Format(@"{0:m:ss}", timeSpan);

I find that things like this take longer to figure out not because I don’t know how to do them, but because I have these preconceived notions of how they’re supposed to be done. Ordinarily, a string formatter is very forgiving of input so I expected it to “just work” in a certain way.

On another note, displaying a timer looks much better if you use a mono-spaced font. Otherwise, the number jump around as they change. Since this is being used in a Windows Phone app, I set the text block like this:

<TextBlock Name="TBlockTimerDisplay" TextAlignment="Right" FontSize="36" FontFamily="Segoe UI Mono"/>

THere are a couple other typefaces, such as Courier New, included with Windows Phone, but Segoe UI Mono would be my first choice, since it matches the default typeface for the OS.

What’s In Your Wallet?

UPDATE: Use http://openidtest.uninett.no/jwt instead. The Google link below is okay, but I really get annoyed with all the web traffic that occurs every time you hit any page belonging to Google. And, in this case, every time you test a token. Fiddler just clogs up with a ton of web sessions. Openidtest uses javascript within the page. And it works with any browser I’ve tried.

https://developers.google.com/commerce/wallet/digital/docs/jwtdecoder – for those times when you want to see what’s in your wallet…or…er…just decode a JWT (JSON Web Token)…any JWT…without having to wire up something for testing. For instance, I just threw a brand new blank Windows Phone 8 project into a solution. So far I’d only added a Live Sign In button and wanted to verify that the same UID is being generated from there as is from a Windows 8 app. I have a JWT decoder in my server-side code but still need to wire it up to the WP8 client. The server is expecting more info than just a JWT. You have to appreciate when major competitors – unwittingly or not – work together to help the little guy, yeah?

BTW, if you do sign in with the same Microsoft Account, the UID will be the same. Some more on JWTs related to that subject in an upcoming post.

UPDATE: The decoder doesn’t validate that the JWT is actually signed. This brings up an important point: JWTs are not encrypted. They are signed, but all that means is that the data hasn’t been altered in transit. If you’re going to work with JWTs then SSL is a must…or if you couldn’t (for whatever unfathomable reason) use SSL, some sort of public/private key encryption from client to server.

WinRT Raw Notifications and Suspended State

Something to note if your WinRT app uses raw notifications. They will be received by the device but not by the app if it is suspended. This makes sense but may not be obvious sometimes because swiping the left side of the screen may still show the app on the stack. So it will appear to still be active, even if not in the foreground. The exception, of course, is if your app is registered to use a background service and the user has decided your app is important enough to be one of the “Lucky Seven” (those apps given permission to use the Lock Screen). I wouldn’t count on it.

It took me a bit to spot this behavior. I was noticing an instance of the app on one machine would sometimes receive raw notifications if it wasn’t in the foreground, sometimes not. The “not” occurred after a decent time lapse, which was the first clue. My server notification logs were no help because only client devices that were off or logged out of would return a status other than OK from the notification service. As mentioned, if the device is on and logged into, the notification service will successfully send the message. This makes sense. All it cares about is reaching the client at the specified URI. It’s up to the client to do what it wants with the received message. In this case, it appears the WinRT designers elected not to wake up an inactive app. Not a problem, but something to be aware of.

In my case, raw notifications are used to tell the app to update its data. It just means that the same sort of behavior also has to be triggered by resuming from a suspended state. BTW, for those who don’t know, you can suspend an app from within Visual Studio while debugging. To enable this, select TOOLS > Customize from the Visual Studio menu. Check the box next to “Debug Location”. If you have a solution with multiple projects you may have to select the right WinRT project from the Process pull-down menu.

SQL CASE Statement

Maybe knew of it, but hadn’t had reason until now to use a CASE statement in SQL:

UPDATE Devices

SET InUse = (CASE UserId WHEN 3

THEN 1

ELSE 0 END)

WHERE DevGuid = '94F74150-26B0-4396-982C-675A14A66FAD';

In this situation, there are multiple rows with the same device GUID because more than one user may use the same app on the device (but not simultaneously…unless they’re extraordinarily close). What this query does is get all the rows that share the same device GUID, then sets the InUse bit to true (1) if the UserId matches (3). Any row within that set with a different user ID gets its InUse bit set to false (0). This avoids having to make more than one call to the server.

The “Evil” GEOMETRYCOLLECTION

Recently we encountered a bug in SQL Server’s spatial aggregation algorithms. Sets of polygons that should have been combined strictly into WKT (well-known-text) POLYGON or MULTIPOLYGONs were being stored as GEOMETRYCOLLECTIONs instead. Turns out the algorithm was inserting one or two LINESTRINGs (of two points each) into the collection, forcing it to be stored this way. The bug was supposedly fixed a couple years ago, but I’m going to submit a new bug and sample dataset to Microsoft. Because I’ve double-checked we’re using the latest version of the DLL, etc.

So why do I think the GEOMETRYCOLLECTION is “evil” (or at least don’t think highly of it)? Primarily because it caused our customer to question both the integrity of our software and the use of SQL Server to store AND manipulate spatial data instead of relying on purely an ESRI ArcGIS solution. We were unable to open the SQL Server datasets via ArcCatalog or ArcMap (using the Database Connection in 10.1). On a broader note, I tend to side with ESRI in not supporting more than one data type in a layer, so I’m perplexed that the creators of the WKT standard even thought up such a datatype. I can see where it might make sense to group related geometric objects but believe there are better ways to do that.

I’m tempted (hey, in a post where the word evil is mentioned it seems appropriate word use) to say that this never would have happened in the first place if a GEOMETRYCOLLECTION wasn’t a possibility. But I know that even if the bug gets fixed, Microsoft and others will still adhere to the WKT specification for storing data and ESRI will continue to invalidate coverages that contain multiple datatypes. So we will improve on the hack below to ensure that what gets output in the end is valid by our customer’s definition.


// Well, semi-verified anyway. At least it won't contain any LINESTRINGs.
public SqlGeometry VerifiedPolygonGeometry(SqlGeometry inputGeometry)
{
 SqlGeometry outputGeometry = null;

try
 {
 var goodReservoirGeometriesList = new List<SqlGeometry>();

int numGeometries = (int)inputGeometry.STNumGeometries();

for (int i = 1; i <= numGeometries; i++)
 {

var geometry = inputGeometry.STGeometryN(i);

if (geometry.STGeometryType() != "LineString")
 {
 goodReservoirGeometriesList.Add(inputGeometry.STGeometryN(i));
 }
 }

var agg = new GeometryUnionAggregate();

agg.Init();

foreach (SqlGeometry geometry in goodReservoirGeometriesList)
 {
 agg.Accumulate(geometry);
 }

outputGeometry = agg.Terminate();
 }
 catch (Exception exception)
 {
 Debug.Write(exception.Message);
 }

return outputGeometry;
}