Tech in the 603, The Granite State Hacker

Getting at Office 365 SharePoint Lists In Windows Phone 7 Silverlight Apps

[Edit 7/8/2013:  I’ve tweaked this to note that this was for WP7.  WP8 has a whole new set of SDKs for SP integration, and it’s a different, and much easier story to use them.]

As promised from my presentation at SharePoint Saturday New Hampshire, I owe a code listing on the meaty part of the chat…  the Office 365 authentication component, especially.  It allows a Windows Phone Silverlight app to access things the lists.asmx service behind the Windows Live ID authentication.  (Frankly, the technique is the same, no matter what kind of client you’re using, but the demo I was doing was using Silverlight 4 for Windows Phone 7.

I also owe slides:

Here’s the activity rundown:

1)  The client app (“Windows Phone App”) makes a SAML SOAP request to https://login.microsoftonline.com/extSTS.srf
2)  The SAML response comes back, allowing the app to parse the SAML token.
3)  Make another call, this time to  {your Office365 team site}/_forms/default.aspx?wa=wsignin1, posting the token.
4) The response that comes back need only be checked for errors, the magic is in the cookie container.  It contains an HTTPOnly token (which the development tools do a terribly good job of hiding.)
5)  Assign your cookie container from your previous result to the ListSoapClient that you’re using to make your service calls from.
6)  Profit!

I broke up the “Activation” line on the client side to point out that the calls are Async.

In any case, I have a very rough SPAuthenticationHelper class that I also promised to post.

Here’s an example of how you can use it:

    class SPTasksList

    {
 
        SPAuthenticationHelper _authenticationHelper;
        ListsSoapClient _listsClient;
        bool isBusy = false;

        TaskItem currentUpdate = null;

        string _taskListUri = http://spsnh.sharepoint.com/TeamSite/Lists/Tasks/AllItems.aspx”;

        public SPTasksList()

        {
            _authenticationHelper = new SPAuthenticationHelper(_taskListUri);
            _listsClient = new ListsSoapClient();
            _listsClient.GetListItemsCompleted += newEventHandler<GetListItemsCompletedEventArgs>(_listsClient_GetTasksListCompleted);
            _listsClient.UpdateListItemsCompleted += newEventHandler<UpdateListItemsCompletedEventArgs>(_listsClient_UpdateListItemsCompleted);
        }
 

        public voidBeginGetTasksList()

        {
            if (!_authenticationHelper.IsAuthenticated)
            {
                _authenticationHelper.OnAuthenticated += newEventHandler<EventArgs>(_authenticationHelper_OnAuthenticated_GetTasks);
                _authenticationHelper.SigninAsync(Configuration.UserName, Configuration.Password);
            }
            else if (!isBusy)
            {
                isBusy = true;
                XElement query = XElement.Parse(“Completed”);
                string ListName = “Tasks”;
                string ViewId = “{f717e507-7c6e-4ece-abf2-8e38e0204e45}”;
                _listsClient.GetListItemsAsync(ListName, ViewId, query, null, null, null, null);
            }
        }

        void_authenticationHelper_OnAuthenticated_UpdateTask(objectsender, EventArgs e)

        {
            _listsClient.CookieContainer = _authenticationHelper.Cookies;
            BeginUpdateTask(currentUpdate);
        }

……
} 

I ported this from a few other examples I found online to Silverlight for Windows Phone.  I apologize,  I haven’t had time to polish it, and I’m having a hard time with the embedded SOAP litteral, but here’s the SPAuthenticationHelper class:





using System;

using System.Net;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
 
namespace SPSNH_SPConnector.Implementation
{
    public class SPAuthenticationHelper
    {
        public CookieContainerCookies { get; set; }
        public boolIsAuthenticated { get; privateset; }
        public event EventHandler<EventArgs> OnAuthenticated;
 
        private bool_isAuthenticationInProgress = false;
 
        const string_authUrl=https://login.microsoftonline.com/extSTS.srf&#8221;;
        const string _login=“/_forms/default.aspx?wa=wsignin1.0”;
       
        //namespaces in the SAML response
        const string _nsS = http://www.w3.org/2003/05/soap-envelope&#8221;;
        const string _nswst = http://schemas.xmlsoap.org/ws/2005/02/trust&#8221;;
        const string _nswsse = http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd&#8221;;
        const string _nswsu = http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd&#8221;;
        const string _nswsa = http://www.w3.org/2005/08/addressing&#8221;;
        const string _nssaml = “urn:oasis:names:tc:SAML:1.0:assertion”;
        const string _nswsp = http://schemas.xmlsoap.org/ws/2004/09/policy&#8221;;
        const string _nspsf = http://schemas.microsoft.com/Passport/SoapServices/SOAPFault&#8221;;
        const string _samlXml =@” http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue http://www.w3.org/2005/08/addressing/anonymous https://login.microsoftonline.com/extSTS.srf {0} {1} {2} http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey http://schemas.xmlsoap.org/ws/2005/02/trust/Issue urn:oasis:names:tc:SAML:1.0:assertion “;

        Uri _uri;  
        HttpWebRequest _getTokenRequest = HttpWebRequest.CreateHttp(_authUrl);
        HttpWebRequest _submitTokenRequest = null;
        string _token;
 
        public SPAuthenticationHelper(string uri)
        {
            _uri = new Uri(uri);
            Cookies = new CookieContainer();
        }
 
        public voidSigninAsync(string userName, string password)
        {
            if (!_isAuthenticationInProgress)
            {
                _isAuthenticationInProgress = true;
                getTokenAsync(userName, password);
            }
        }
 
       
        private  void getTokenAsync(stringuserName, string password)
        {
            string tokenRequestXml = string.Format(_samlXml, userName, password, _uri.Host);
 
            _getTokenRequest.Method = “POST”;
            _getTokenRequest.BeginGetRequestStream(newAsyncCallback(Get_GetToken_RequestStreamCallback), tokenRequestXml);
        }
 
        private voidGet_GetToken_RequestStreamCallback(IAsyncResultresult)
        {
            string tokenRequestXml = (string)result.AsyncState;
            var reqstream = _getTokenRequest.EndGetRequestStream(result);
            using (StreamWriterw = new StreamWriter(reqstream))
            {
                w.Write(tokenRequestXml);
                w.Flush();
            }
            _getTokenRequest.BeginGetResponse(new AsyncCallback(Get_GetToken_ResponseStreamCallback), null);
        }
 
 
 
        private voidGet_GetToken_ResponseStreamCallback(IAsyncResultresult)
        {
            _token = null;
 
            varresponse = _getTokenRequest.EndGetResponse(result);
 
            var xDoc = XDocument.Load(response.GetResponseStream());
 
            var body=xDoc.Descendants(XName.Get(“Body”, _nsS)).FirstOrDefault();
            if (body != null)
            {
                var fault = body.Descendants(XName.Get(“Fault”, _nsS)).FirstOrDefault();
                if (fault != null)
                {
                    var error=fault.Descendants(XName.Get(“text”, _nspsf)).FirstOrDefault();
                    if (error != null)
                        throw new Exception(error.Value);
                }
                else
                {
                    var token = body.Descendants(XName.Get(“BinarySecurityToken”, _nswsse)).FirstOrDefault();
                    if (token != null)
                    {
                        _token = token.Value;
                        SubmitTokenAsync();
                    }
                }
            }           
        }
 

        private  void SubmitTokenAsync()
        {
 
            UriBuilder bldr = newUriBuilder(_uri.Scheme, _uri.Host, _uri.Port);
            _submitTokenRequest = HttpWebRequest.CreateHttp(bldr.Uri + _login);
            _submitTokenRequest.CookieContainer = Cookies;
            _submitTokenRequest.Method = “POST”;
            _submitTokenRequest.BeginGetRequestStream(newAsyncCallback(Get_SubmitToken_RequestStreamCallback), null);
        }
 
        private voidGet_SubmitToken_RequestStreamCallback(IAsyncResultresult)
        {
            var requestStream = _submitTokenRequest.EndGetRequestStream(result);
            using (StreamWriterw = new StreamWriter(requestStream))
            {
                w.Write(_token);
                w.Flush();
            }
            _submitTokenRequest.BeginGetResponse(newAsyncCallback(Get_SubmitToken_ResponseCallback), null);
        }
 
        private voidGet_SubmitToken_ResponseCallback(IAsyncResultresult)
        {
            UriBuilder bldr = newUriBuilder(_uri.Scheme, _uri.Host, _uri.Port);
 
            varresponse = _submitTokenRequest.EndGetResponse(result);
            string responseString = (newStreamReader(response.GetResponseStream())).ReadToEnd();
           
            bldr.Path = null;
            Cookies = _submitTokenRequest.CookieContainer;//.GetCookies(bldr.Uri);
            _isAuthenticationInProgress = false;
            IsAuthenticated = true;
            if (OnAuthenticated != null)
            {
                EventArgs args = new EventArgs();
                OnAuthenticated(this, args);
            }
        }
    }
}
 
 

Tech in the 603, The Granite State Hacker

Facebook’s People Hub Problem

I’ve had this thought cross my mind, too… some time ago, actually.   My smartphone, a Windows Phone, is a natural social network browser; a mature response to “how to make social networking easy, practical, and physically portable”. 

I would roughly guestimate that a good 50% of the OS, fresh out of the box, is dedicated to it (particularly the part known as the “People Hub”).   Interestingly, the People Hub isn’t a Facebook app.   It’s exactly what it sounds like…  a contacts hub, a leads hub, management hub, a communications hub, a social hub…   your people hub.   Twitter, Facebook, LinkedIn, multiple Exchange domains, even Windows Live.

Some time ago I actually deleted the Facebook app from my phone, because I couldn’t think of a good reason to let it take up space on my phone.  That was when it hit me.  Aside from the basic description in settings here & there, the Facebook brand did not really exist on my phone.  Nor did any of its advertisements.   My phone became the better part of the Facebook experience… without Facebook.

It doesn’t surprise me in the least that this has come to light in the recent IPO.  I gather that Facebook intends to start adding ads to news feeds.  I wonder how long it will be before Facebook starts offering subscriptions to remove them.   Or how long it will be before someone figures out how to filter them out again.
http://www.insidermonkey.com/blog/the-problem-of-mobility-and-facebook%E2%80%99s-battle-for-revenue-10985/

I have to say, though, the Facebook 2.5 update (relatively new) for Windows Phone does offer a couple features that make it worth keeping on the device.

The latest Facebook app can be found here:
http://www.windowsphone.com/en-US/apps/82a23635-5bd9-df11-a844-00237de2db9e

Tech in the 603, The Granite State Hacker

Windows Phone Live Tiles… What’s happening right now?

The first thing you see when you see a Windows Phone is the start display.  In fact, it’s so distinct, that it becomes the most identifiable feature of a Windows Phone at a distance.  Typically, the start display is populated with a number of application icons…  only on Windows Phone (and Metro) they’re all square or rectangles and are called Tiles.  

On second glance, you start to notice that many of these tiles have some form of light animation to them, typically communicating basic information.  The Tiles that open messaging apps indicate the number of new messages, for example.

When I first started playing with my Windows Phone, the live tiles seemed like a nifty gimmick… important for messaging features, but not really useful for anything else.

As I’ve dug in on app development for Windows Phone, I’ve come to see the Live Tiles as a really under-leveraged feature, communicating with users on a level that previously couldn’t be achieved.  They’re terribly simple, but terribly engaging.  I now see that they are the addictive component of Facebook’s classic “What’s on your mind?” status updates… statuses provided by the apps on your phone. 

In some cases, this literally translates to status update from your friends, since Tiles can be put on your start display for any contact.  (Since contacts are linked via the People Hub to their Facebook, Twitter, and Linked In…  voila!  one tile gets status updates for that individual covering all the bases.)

What’s really cool is that, like I said before, getting status updates is not limited to contacts.  I’ve got apps that have live tiles that… display current weather conditions including radar maps.  …show stock quotes & notifications.  …display photos from various sources.  … even shows your XBox avatar fully animated.

I’m in the process of adding a new feature to my hobby project, Jimmy Sudoku, to make use of live tiles to show the progress of the “current” puzzle.  

A new hobby project I’m working on has to do with the Granite State (NH) SharePoint Users Group that I am a principal organizer of.   This app will eventually be a hub for group information, offering member users easy access to schedules, speaker info, weather delay notifications, registration info, and even Power Point presentation slides.   Interestingly enough, a key feature will be to provide a live tile which will poll a webservice to get updates… the live tile will then let the user know they have important information to review, thus engaging the user.  (Sure, push technology’s available, but in this case, polling will be sufficient.)

The uses for this being able to re-engage a user after they’ve “quit” the application itself are significant.   I can easily imagine a time when the marketing significance of them makes building Windows Phone apps far more attractive to companies than iPhone or Droid apps.  Even if companies aren’t trying to hock a specific product…  imagine corporate “investor information” apps, for example, that provide easily accessible information about a company… but most importantly, providing “status updates” to investors to re-engage interest.

I’ll admit, at some level, this reminds me of electronic kids toys that attempt to re-engage kids in play after the kid has put it down and walked away by flashing a few lights & making a little noise.  There’s reasons those kids toys do that, though, and anyone paying attention with a mind for marketing will get what they are.

This is another Non-App for Windows Phone… one of the many cool features built into the device in an accessible, but non-cluttering way… and another reason I keep seeing Windows Phone as the IBM Compatible of smart phones.

So the above is why you want Live Tiles…   Here’s a code snippet that illustrates how:

using Microsoft.Phone.Shell;

… 

public static void UpdateAppTile(JimmySudoku4.Puzzles.SudokuState state)

{
    ShellTile appTile = ShellTile.ActiveTiles.First();

    if (appTile != null)
    {
        StandardTileData data;
        if (state.GetElapsedTime().Ticks == 0)
        {
            data = new StandardTileData()
                {
                    BackContent = “Game Complete”,
                    BackTitle = “Try again!”, Count = 0
                };
        }
        else
        {
            int completeCellCount =
                state.MasterList.Where(c => c.Value != 0).Count();
            int percent = (int)((decimal)((decimal)completeCellCount / (decimal)81)
                * (decimal)100);
            if (percent < 100)
            {

                data = new StandardTileData()
                    {
                      BackContent =
                            string.Format(“Elapsed Time:\n{0:hh:mm:ss}”,
                                 state.GetElapsedTime()),
                        BackTitle = string.Format(“{0}% complete”, percent)
                    };
            }
            else
            {
                data = new StandardTileData()
                    {
                        BackContent = string.Format(“Completion Time:\n{0:hh:mm:ss}”,
                            state.GetElapsedTime()),
                        BackTitle = “You Won!”
                    };
            }
        }

        appTile.Update(data);
    }
}

Tech in the 603, The Granite State Hacker

My Favorite "Non-Apps" for Windows Phone 7

There’s a lot of cool stuff built in the current Windows Phone 7… stuff that competing phones need to download an App for.  These are features of the Windows Phone operating system that are built-in.  You could call it “An App for That”, but it’s not something a Windows Phone user needs to spend time to find, download, and install.   (There’s something to be said that you get your choice from dozens of them on iOS and Droid.  I wonder how much time iPhone users spend figuring out which ones work well for them and which ones don’t…?)  

People Hub is one of the best.  It’s so well integrated and natural that it’s easy to take for granted. (the fact that all your contacts from all your social media hubs and work contact lists are integrated by default, and you can group and manage communications among groups very easily… hard imagine not having that.)

Some of my favorite lesser known “Non-Apps” in Windows Phone involve the built in search functionality.  Hitting the handy magnifying glass that’s an identifying feature of every Windows Phone out there brings you to Bing Search.  While I’ve been an admittedly slow adopter for Bing, the features in Windows Phone’s Bing Search are awesome.  

Visual Search just rocks.  Tapping the icon that looks like an eye from the search page fires up the device’s camera.  Simply point the camera in the direction of nearly *any* common, standardized barcode or QR code.   As soon as the phone “sees” the code, it will highlight it and immediately try to identify it. 

At Trader Joes, and want to know a bit more about their uncrystalized candied ginger?  Scan the UPC code.  It will remind you that the small package contains about 8 servings, [so don’t eat it all at once!]  🙂   Chances are just about anything you find at any store will have a barcode, QR code, or even an MS Tag associated with it.  

My favorite use for Tags, by the way, is printing Tags associated with your virtual Card on the back of classic Business Cards…  scan the Tag, and all the info on the card can be imported into your phone!  I never give out my card unless it’s Tagged. 

Tags can get really fancy, by the way… sometimes they’re almost hidden, and, especially out of context, it might take a moment for a human to recognize (but your phone will pick it out instantly!).  There’s a very creative cottage industry popping up around the art of Tagging things.  Exemplified by this Angry Birds Tag by Extreme2D.com. (Facebook) (and visit their site for an array of other very creative Tags!)

Visual Search does a whole slew of other awesome stuff too..  visual text identification (and TRANSLATION to foreign languages!)

Another favorite Windows Phone “Non-App” is Audio Search.  Let’s just say this is how I discover most of the music I download.  Ever out & about and hear a song that you are really taken by, but have no idea who it is?   Simply hit the music note icon in search, and let the phone listen for a moment. 

I heard the 2011 remaster of Pink Floyd’s The Wall, doing cuts I’d never heard before on someone’s radio not too long ago.  It was such a fresh cut that I didn’t even believe it was actually Pink Floyd’s recording of their own song.   Upon hitting it on Audio Search, I found the tune, and the album, and immediately downloaded the whole thing!   Awesome stuff!

So this doesn’t even really scratch the surface of the stuff that you don’t need an App for with Windows Phone.   It’s like that old spaghetti sauce commercial…  “It’s in there!”

What are your favorite built in (#NonApp) Windows Phone features?

.

Tech in the 603, The Granite State Hacker

Windows Phone… who knew, right?

There is something interesting happening with Windows Phone 7… (a story outside Windows 8, Metro & Silverlight 4).  There’s a chance that the stars could align in an old, somewhat familiar pattern.

I’m thinking about the PC market back in the day (for me, that’s late 80’s early 90’s).  There were three niches in the personal computer business.  The most memorable stars were Apple, IBM, and Commodore.   Apple was the early front runner with high-end consumer technology that dazzled with an artsy focus (if you could afford it).  To try to coax the lower end of the market, they gave away machines to every school that would take them, making them the defacto for education, too.  Commodore (and a few others like them) had a developer and gaming niche…  if you were a lower budget programmer/hobbyist/gamer (as I was), you probably had one of these and half-convinced yourself it was better than an Apple machine.  

The rest of the world wanted a computer, too, but didn’t want the price point of the Apples or the technical overhead of the Commodore class of machines.   That’s where IBM came in, with an affordable machine that wasn’t necessarily the flat out best of anything on the market, but the overall value made it accessible to a broad range of people.  IBM… PC… who knew, right? 

History shows that IBM’s (or, more appropriately, Microsoft’s) strategy won out, with the social forces of the now ubiquitous Windows pc’s swallowing the hobbyist market almost whole, eating most of the Apple pie, and sharing the gaming market somewhat grudgingly with consoles. 

The social force in effect was the desire to make something that worked for the non-technical consumers who weren’t so attracted to the high-end market…  since consumers found commonality in the accessible/value platform, eventually that platform swallowed up the niches.  What hobbyist wants to write software that they can’t share with anyone (short of installing Linux on their mom’s computer)?  What technologist wants to have a separate system for gaming and another for everything else (setting consoles aside)?  In a way, the IBM / Microsoft platform became the “lowest common denominator”… but the important emphasis being on the word common.

Fast forward to the mobile phone market of about a year ago.   My wife picked up a Droid based phone on a deal.  She’s not exactly unhappy with it.  It works, but she doesn’t quite trust it after she had some technical issues she wasn’t prepared to deal with.  Droid based phones seem to appeal to a lot of the guys at work, who don’t mind tinkering with the things.  The Droid reminds me of the “Commodore” of smart phones.

Even more recently, my wife was helping her mother pick out a new phone.  Seeing that the iPhone was a popular choice, they looked at it, but it was a huge step up in cost and it seemed overwhelming to my mother-in-law.  Given that her old phone was a relatively basic mobile phone, she didn’t see the need to spend a ton of money only to buy a phone she felt was more than she needed.   My wife, thinking back to my Windows Phone, realized she really likes its clean, simple-looking style and ease of use.  Since the price point was way better than the iPhones, too, the Windows Phone won out.

(I remember posting a light-hearted lament on Facebook at the time, that maybe I should consider switching phones, because…. how can you see technology which the grandmother of your children uses as the basis of an interesting, relevant, and marketable skill set (and career)? (I really was just kidding! (I still have bruises from several grandmothers over these remarks.)) 🙂  

After a brief break-in period with her new Windows Phone, my mother in law fell in love with it.  She doesn’t have to struggle to figure her phone out, anymore.  She just uses it.   She takes advantage of features she never thought she’d use, because the features are arranged so nicely that they work together.

Interestingly, this opens up technology for me, too, because now I can share the product of my technical interests with her. She was one of the first beta testers of Jimmy Sudoku, my hobby project.

I’ve come to see that Windows Phone is the IBM PC of the modern mobile phone market.  It’s poised to become the common denominator of mobile phones.  It’s less expensive , easy to use, less overwhelming / more accessible to more people, even to those without a technical degree.  (Check out that new Nokia Lumia 900?)  Still, for us geeks, it’s got readily available (free) development tools using fun and marketable skills and a reasonably open app marketplace.  Perhaps Microsoft should review IBM’s old PC marketing strategy before they overlook the opportunity they seem to have set themselves up for.

Like the frying pan in the Disney movie “Tangled”…  Practical, available, affordable, easy to use, and good for more than the obvious stuff…  who knew, right?