Colin's profileColin Brown MSN MVPPhotosBlogListsMore Tools Help

Blog


    October 22

    Silverlight 3 Programmers Reference - Review

    Title : Silverlight 3 Programmer's Reference (Wrox Programmer to Programmer)
    Author : J. Ambrose Little
      Jason Beres
      Grant Hinkson
      Devin Rader
      Joe Croney
    ISBN : 0470385405
    Price : $49.99
    Rating : 79 out of 100

     

    In America there is a growing trend to take your date to the prom in a limousine with all the pomp and lavishness and it works (I’ve heard stories anyway). The same can be said for books. Technical books that deal with certain subjects, CSS, Silverlight etc. are noticeably enhanced when they are printed in full color and Silverlight 3 Programmers Reference is no exception. It helps to clearly demonstrate what the author(s) are portraying.

    This book covers both the bases of those new to Silverlight programming and those looking to upgrade their skill sets from Silverlight 2. Silverlight 3 has introduced many enhancements in many areas of the product and the authors have done a good job explaining this. It gently eases you like a pair of well worn slippers into the world of Silverlight programming and captures you with the possibilities that this technology can achieve.

    Some chapters of the book are better than others, for example the chapter on styling is the best I’ve read on Silverlight styling but other chapters, although they get the subject matter across appear to leave out some information and sometimes come across as overviews rather than in-depth tutorials.

    The authors have slipped up in a couple of places and you can certainly tell that this book isn’t a complete re-write but rather an update of their book on Silverlight 2 as they have forgotten to update the text. This should not put you off however as Silverlight 3 is backwards compatible so what might apply to Silverlight 2 equally applies to Silverlight 3.

    I would say that this book is aimed mainly at the newcomer to the Silverlight world and it gives you enough knowledge to more than get started with the technology. Those that are already familiar with Silverlight 2 will learn what is new in Silverlight 3 however the book does not point these things out in an obvious manner which is perhaps one of it’s downfalls. The other downfall is you are left with a feeling that some things should have been explained in more depth. It certainly gives you a good introduction to certain things, some things it does cover well and in-depth but this is not consistent throughout the book.

    Some things in this world are exquisite, the minute attention to every detail in a Da Vinci, the song of a Ferrari engine. Some things are good but but lack that something that makes them great and most things fall into the category of Mediocre/Useable. This book I would place in the good category if you are new to Silverlight programming. If you are already proficient in Silverlight 2 and looking to learn what’s new in Silverlight 3 then perhaps this book is not for you as you really have to dig to find that information.


    Digg This

    The CSS Anthology: 101 Essential Tips, Tricks and Hacks Review

    Title : The CSS Anthology: 101 Essential Tips, Tricks & Hacks
    Author : Rachel Andrew
    ISBN : 0980576806
    Price : $39.95
    Rating : 73 out of 100

     

    Like human beings, CSS is constantly evolving. The introduction of new browsers, people learning new techniques and tricks etc. The CSS Anthology is now in it’s third edition and has been completely updated to include the latest browsers including Internet Explorer 8.

    The book takes a slightly different approach than most. It’s still split into different chapters like every other book but rather than teaching you in the normal fashion, this book takes the approach of you reader having asked a question then gives you an answer and an explanation of the answer.

    For example, in the chapter on CSS positioning and layout, there is a question “Can I make an inline element display as if it were a block element and vice versa?”. This then leads to an example of exactly what the question means, an answer and an explanation of how the answer works. If necessary, sidebars are presented to detail certain abnormalities for example, what happens in quirks mode in Internet Explorer, if there are differences in the final renderings between the various browsers or whether the browser actually accepts the specified CSS and if not what a workaround would be. All this information extra information is essential for web developers and is tied nicely in with the specific question.  

    There is a lot to learn in this book if you are fairly new to CSS and even things to learn if you are an old hand but this isn’t really a book on learning CSS so if you are in the market for that I would suggest looking elsewhere and it’s not exactly a reference book either (I would suggest The Ultimate CSS Reference - Book Review also by SitePoint although to my knowledge this book hasn’t been completely updated with the new browsers yet, but is an excellent reference book on CSS).

    The CSS Anthology is beautifully decked out in full color. For certain kinds of books, CSS, Silverlight etc. there is a definite advantage to having the book in color and this shines through here.

    Although this book isn’t really meant as a complete learning guide to CSS due to the way it’s been written as a question and answer scenario the first few chapters are written as if the reader has no knowledge of CSS and therefore would be a newcomer to CSS. This gives the book a slight identity crisis and you’re left not knowing exactly where CSS Anthology should be positioned. Is it a newcomer learning book? Is it a reference book or is it as the title suggests a tips book? It tries to cover all bases when it shouldn’t. This is my main criticism of the book and why I find it hard to unequivocally recommend.  I would say the people who are going to get the most out of this book are people who know the basics of CSS but aren’t quite fully accomplished CSS gurus.

    Digg This
    October 12

    My second MVP award of 2009

    Today I received my Microsoft MVP Award for 2009/2010.

    DSC00002

    On opening the box you get the usual MVP Certificate :-

    DSC00003

    DSC00004

    As you can see the award states October 2009.  There is also an extremely nice crystal award included :-

    DSC00005

    Again as you can see from the little bead on the left, the award states 2009. So why did I get awarded twice for 2009?

    The reason comes down to Microsoft themselves changing the award periods. Over the past years, October was the first award of the new year inline with the financial year. This year however Microsoft is changing the award period to be inline with the calendar year, starting January.  So if you were awarded in October, like I am, then you have essentially been awarded twice for the same year. I now have two very nice crystal awards inscribed with the 2009.

    Technorati Tags: , , ,
    Digg This
    October 09

    Windows 7 House Party Kit

    I received my Windows 7 house party kit in the post when I got home last night. For anyone interested here is what was included :-

    34897516

    The actual party kit with letters explaining included etc.

    34897893

    Windows colored streamers

    34898047

    Windows 7 balloons

    34898484

    A Windows 7 jigsaw (very reminiscent of Terry Pratchetts Discworld)

    34898768

    Windows 7 napkins (will probably come in very handy)

    34899076

    Windows 7 playing cards

    34900218

    10 very nicely decorated Windows 7 tote bags

    34900832

    10 Zune Pass 14 day trial certificates

    34901187

    10 coupons for 40% off Norton 2010

    34901864

    10 coupons for 1 year free Kaspersky Security Suite

    34902447

    10 coupons for 20% off Nero 9 and get Nero Backitup free (worth $60)

    34902725

    10 Windows 7 thank you cards

    34903194

    10 coupons for Corel

    34903443

    A Windows 7 table center piece

    34903790

    A Windows 7 poster

    34899853

    A copy of Windows 7 Ultimate 64 bit edition

    34899497

    and of course the copy of Windows 7 Ultimate 32 bit signature edition (signed by Steve Ballmer)

    Digg This
    September 24

    How to use the Sharepoint People Picker in your own control

    I was recently tasked with creating a quick Sharepoint web part that would require the ability to enter a user and store that user in a list. The overall control was a registration control for various workshops.

    The list included a people field so whatever I programmed from the front end would have to supply a valid user. Also in the list were fields for Email and Display Name. All of these of course can be found in the SPUser object. So the control I created would have to convert whatever the input was into a SPUser object.

    SmartPart1

    Above is the simple control I came up with. As this was just meant to be a quick control I decided to use a SmartPart control which is basically just an ASCX user control.

    In order to do the above, the best way would be to be include SharePoint’s built in People Picker control. Now here is where things got a little confusing. There is indeed a people picker control however this is not what you are actually looking for. What you really want to use is the People  Editor control.

    To use this in your user control you first need to give your control a reference to Microsoft.Sharepoint.WebControls :-

    <%@ Register Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"
        Namespace="Microsoft.SharePoint.WebControls" TagPrefix="cc1" %>

    Once you have added that reference you are free to use any of the built in SharePoint controls. The one we’re specifically wanting is the People Editor control :-

     
        <cc1:PeopleEditor ID="BlazerID" runat="server" MaximumEntities="1" 
        MultiSelect="false" AllowEmpty="false" 
        ErrorMessage="Please Enter a User" ValidatorEnabled="true"  />

    The people editor control has various properties that you can set. Here I have told it that I only want a single entry (only one person) and that this is a required field.

    Now that you have you’re people picker control added to your form, how do you get the value in your code behind and convert it to a SPUser object?

    First off I defined an empty SPUser object that will eventually hold the result :-

    SPUser user;

    The people editor control doesn’t actually return an array of SPUser objects as I would have expected, instead it returns an array of PickerEntities. So first thing you want to do is get the appropriate entry. Since I specified only a single entry I can immediately reference the index of the entry I want :-

    PickerEntity ent = (PickerEntity)BlazerID.ResolvedEntities[0];

    Next I want to convert this into a SPUser object. There are various ways of doing this but the quickest is to first get the UserID of the username entered :-

    int userID = Int32.Parse(ent.EntityData["SPUserID"].ToString());

    Once you have that then you can simply get the SPUser object from the sites authorized users collection :-

    user = SPContext.Current.Site.RootWeb.SiteUsers.GetByID(userID);

    Now that you have a SPUser object you can use all the normal properties associated with a user object (Email, Name etc.).  Here is the code in full I used :-

    SPSite site = SPContext.Current.Site;
    SPWeb web = site.OpenWeb();
    SPUser user;
    try
    {
        PickerEntity ent = (PickerEntity)BlazerID.ResolvedEntities[0];
        int userID = Int32.Parse(ent.EntityData["SPUserID"].ToString());
        user = SPContext.Current.Site.RootWeb.SiteUsers.GetByID(userID);
    }
    catch
    {
        lblError.Text = "Please enter a valid user";
        return;
    }

    …….

    item[item.Fields["FullName"].InternalName] = user.Name;
    item[item.Fields["Email"].InternalName] = user.Email;
    item[item.Fields["BlazerId"].InternalName] = "-1;#" + user.LoginName;

    ……

    The (…….) represents code that isn’t relevant here. The end result is a fully working people picker control on your own custom control :-

    SmartPart2

    Digg This
    September 06

    Powershell Part 3 – CmdLets

    CmdLets (pronounced “Command Lets”) are the building blocks of Powershell scripts.  You can think of them as being like keywords in a programming language. In reality however CmdLets are mini-programs. As you may recall, Windows Powershell is basically built on top of the .Net Framework and a CmdLet simply packages together multiple .Net Framework commands and methods into an easy to use package so that if you’re not used to programming the .Net Framework, are a CLI script writer, you don’t actually have to learn the .Net Framework and it’s thousands of classes and methods in order to use PowerShell.

    Windows Powershell 2 comes packaged with well over 100 CmdLets for you to choose from ranging from simply writing out text to the PowerShell window to advanced functionality like Transactions.  To get a complete list of CmdLets that are available in PowerShell 2 can simply enter :-

    get-commands

    into your Powershell console. This will list not only the CmdLets but their aliases as well. 

    getcommand

     

    To make it a bit easier to read you can issue the following command :-

    get-command | out-gridview

    The out-gridview CmdLet takes the output from any command and displays it in a searchable window :-

    getcommand2

    As you can see there are a mixture of functions, aliases and CmdLets. What is an Alias?  Microsoft added Aliases to most CmdLets to help CLI script writers easily transfer over to Powershell. For example, to get a directory listing of the current directory you would use the following CmdLet :-

    get-childitem

    getchild

    As you can see, this basically just gives you a listing of all the files and folder in the current directory. CLI programmers however are used to the old DIR command :-

    getchild2

    As you can see the output is exactly the same. That is because DIR is just an Alias for get-childitem. There is also another Alias for this command for unix programmers – LS. You can have multiple Aliases for a single CmdLet, depending upon your preference and what you are used to.

    So you have all these commands at your disposal but what do they all do? Well it’s easy to get help on any CmdLet in PowerShell. You simply use the Get-Help CmdLet :-

    gethelp

    As you can see, if you just enter Get-Help by itself then it will give you help about the Get-Help CmdLet itself. From the output however you can see that you can enter the name of a CmdLet as a parameter and it will show you the help for that particular CmdLet, e.g. get-help write-host :-

    gethelp2

    You can also get information about a specific CmdLet from the graphical help file (basically a CHM file). From within your PowerShell IDE (or ISE as it’s called in PowerShell), simply press the “F1” key or use the Help menu item :-

    gethelp3

    The built in Powershell help file is slightly different from the screenshot above as this is the PowerShell Plus help file. PowerShell Plus is a fully interactive PowerShell programming environment from Idera that I will be talking about more in a later posting but for those curious at the moment you can get details at http://www.powershell.com

    Also in a later post I will show you how you can make your own CmdLets, after all, they are really just .Net Framework programs.

    Digg This
    September 03

    Powershell 2 Part 2

    In the last article I showed you where to download Windows Powershell 2 and went through the installation steps along with some initial configuration options.

    In this article I’ll complete the initial configuration options that you may want to do (note these are optional).

    Windows Powershell, just like the CLI that it essentially replaces, looks in certain folders on your drive for commands. It is a good idea to create your own directory on your system to store your own Powershell CmdLets and scripts however if you do, how do you run these scripts if it’s not in the default paths?

    Before getting ahead of ourselves, what are the default paths?  You can easily find this information out by opening Windows Powershell and inserting the following command :-

    $env:Path

    This will return a semi-colon delimited list of directories that Windows Powershell automatically searches through for the command that you are running.

    getenv

    By default, as you can see above, these are :-

    C:\Program Files\Common Files\Microsoft Shared\Windows Live
    C:\Windows\system32
    C:\Windows
    C:\Windows\System32\Wbem
    C:\Windows\System32\WindowsPowerShell\v1.0\
    C:\Program Files\Microsoft SQL Server\100\Tools\Binn\
    C:\Program Files\Microsoft SQL Server\100\DTS\Binn\
    C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\
    C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\
    C:\Program Files\Common Files\Microsoft Shared\Windows Live

    Your default paths may vary from mine as I have various development tools installed that adjust the default path behaviors. As you can see, by default, the folder that you’ve just created to store your CmdLets and Powershell scripts will not be listed. This means that Powershell will not look in your folder for your scripts by default and therefore you cannot run them from anywhere on your system.  To include your Scripts folder so that it gets searched by default you need to adjust your system path environment variable. 

    In Windows Vista or Windows 7 you need to open your System control panel applet. Go to Start menu, Control Panel then select System :-

    SystemCtrlpanel

    From the System Control Panel applet, select the link advanced system settings  near the top left :-

    SystemSettings

    At the bottom of this window you will see a button marked “Environment Variables”. This is the one you want. Click on it to bring up your system variable window. Note, if you do not know what these settings are then please don’t play about with them as you can end up rendering your computer inoperable.

    EnvPath

    The one that we are looking for is in the second list under System variables (although you could add it to your local variable path for if you wish however that would then only include that path for that particular user). Select Path then hit the edit button :-

    EditPath

    To add your own folder, in the “variable value” field, scroll to the end without altering anything that is in there, type in a semi-colon “;” and then type in the full path to your folder. As you can see from the screenshot above, I’ve added ;C:\PScripts to the end as that is where I intend to store my Powershell scripts and CmdLets.  Next “OK” your way out of the dialogs, then you need to reboot your computer as these settings are only loaded on startup. And that’s it, now whatever Powershell scripts and CmdLets you place in this folder can automatically by run from whichever directory your actually pointing to at the Powershell prompt.

    After rebooting your computer, if you now re-run the $env:path command in Powershell you should see that your folder is now included :-

    getend2

    You are now ready to start learning about Powershell and have a folder in which you can place your scripts.

    If you do not wish to do this (or perhaps cannot in a business environment) then you can run your Powershell scripts from any directory. You can either insert the full path to your script in with your script name e.g. :-

    C:\PScripts\TestScript.ps1

    or you can change to the directory that your script is in and put “./”  before your script name e.g. :-

    ./TestScript.ps1

    Notice that all Powershell script files have the extension “ps1” (that’s a number one and not a lower case l).

    Digg This
    September 02

    Windows Powershell 2

    It’s time to start learning a new language, well sort-of a new language. Windows Powershell 2 (although at the time of writing this Powershell 2 is still in CTP and hasn’t actually been released yet).

    You can download the latest CTP 3 from Microsoft here :- Powershell 2 CTP 3

    Powershell 2 has many new features and additions from Powershell 1 however depending on the platform that you’re running Powershell 2 on, not all features may be available to you. For example, remoting uses a new WS-Management (which is also in CTP form at present) that is only available on Vista, Windows 2008, Windows 7 and Windows 2008 R2. So although you can run Powershell 2 on Windows XP and Windows 2003, you can’t use all the features that it provides on these platforms.

    Some of the new features of Powershell 2 over Powershell 1 are it’s remoting, the ability to run background tasks, a new Powershell IDE environment for entering your scripts, new script debugging features and over 63 new Powershell Cmdlets including one that is very useful, the Out_GridView Cmdlet.

    Powershell 2 requires a minimum of .Net Framework 2.0 to be installed on your machine however if you want to take advantage of all of the new features found in Powershell 2 then you need to install .Net Framework 3.5.1 and also the WinRM 2.0 CTP as discussed above.

    Installing Powershell 2 is as simple as downloading the MSI file, double clicking on it and running through the wizard.

    Install1

    After the initial splash screen, click to accept the software license.

    Install2

    and click install :-

    install3

    If you have a previous version (Powershell 1) already installed on your system then you will run into the following dialog :-

    Install4

    Powershell 2 replaces Powershell 1 and you can’t have both installed on your system at the same time. Hopefully by the time Powershell 2 gets released it will automatically do an un-install of previous versions for you so that you don’t need to manually un-install previous versions.

    In order to un-install a previous version you need to have the Show Updates checkbox checked (or View Installed Updates if running Vista for example).

    uninstall

    Once installed there is a little bit of configuration work that you may want to carry out. By default Windows Powershell 2 has 3 modes of operation

    • AllSigned – Only permits scripts that have a trusted signature to execute on your computer
    • RemoteSigned – Permits Powershell scripts downloaded from the web to run only if they are from a trusted source
    • Unrestricted – Allows any Powershell script to run on your system

    By default Powershell 2 runs in AllSigned mode. You can check on this by opening a Powershell and entering the following command :-

    get-executionpolicy

    executionpolicy

    If you’re playing with Powershell and learning it’s ropes then you will probably want to elevate the security mode to unrestricted. Please be aware that there are obviously security consideration to take into account here.  To elevate your permissions to unrestricted you enter the following command :-

    set-executionpolicy unrestricted

    The last thing you may want to take a look at is the script IDE. This is actually called the Windows Powershell ISE (Integrated Scripting Environment)

    Editor

    It’s not as advanced as Visual Studio but it does allow for entering your scripts with TAB completion, debugging and a number of other features.

    You now have your basic environment setup and are ready to start learning Windows Powershell 2.

    Digg This

    Windows Powershell 2

    It’s time to start learning a new language, well sort-of a new language. Windows Powershell 2 (although at the time of writing this Powershell 2 is still in CTP and hasn’t actually been released yet).

    You can download the latest CTP 3 from Microsoft here :- Powershell 2 CTP 3

    Powershell 2 has many new features and additions from Powershell 1 however depending on the platform that you’re running Powershell 2 on, not all features may be available to you. For example, remoting uses a new WS-Management (which is also in CTP form at present) that is only available on Vista, Windows 2008, Windows 7 and Windows 2008 R2. So although you can run Powershell 2 on Windows XP and Windows 2003, you can’t use all the features that it provides on these platforms.

    Some of the new features of Powershell 2 over Powershell 1 are it’s remoting, the ability to run background tasks, a new Powershell IDE environment for entering your scripts, new script debugging features and over 63 new Powershell Cmdlets including one that is very useful, the Out_GridView Cmdlet.

    Powershell 2 requires a minimum of .Net Framework 2.0 to be installed on your machine however if you want to take advantage of all of the new features found in Powershell 2 then you need to install .Net Framework 3.5.1 and also the WinRM 2.0 CTP as discussed above.

    Installing Powershell 2 is as simple as downloading the MSI file, double clicking on it and running through the wizard.

    Install1

    After the initial splash screen, click to accept the software license.

    Install2

    and click install :-

    install3

    If you have a previous version (Powershell 1) already installed on your system then you will run into the following dialog :-

    Install4

    Powershell 2 replaces Powershell 1 and you can’t have both installed on your system at the same time. Hopefully by the time Powershell 2 gets released it will automatically do an un-install of previous versions for you so that you don’t need to manually un-install previous versions.

    In order to un-install a previous version you need to have the Show Updates checkbox checked (or View Installed Updates if running Vista for example).

    uninstall

    Once installed there is a little bit of configuration work that you may want to carry out. By default Windows Powershell 2 has 3 modes of operation

    • AllSigned – Only permits scripts that have a trusted signature to execute on your computer
    • RemoteSigned – Permits Powershell scripts downloaded from the web to run only if they are from a trusted source
    • Unrestricted – Allows any Powershell script to run on your system

    By default Powershell 2 runs in AllSigned mode. You can check on this by opening a Powershell and entering the following command :-

    get-executionpolicy

    executionpolicy

    If you’re playing with Powershell and learning it’s ropes then you will probably want to elevate the security mode to unrestricted. Please be aware that there are obviously security consideration to take into account here.  To elevate your permissions to unrestricted you enter the following command :-

    set-executionpolicy unrestricted

    The last thing you may want to take a look at is the script IDE. This is actually called the Windows Powershell ISE (Integrated Scripting Environment)

    Editor

    It’s not as advanced as Visual Studio but it does allow for entering your scripts with TAB completion, debugging and a number of other features.

    You now have your basic environment setup and are ready to start learning Windows Powershell 2.

    Digg This
    August 29

    Virtual PC does not support X64 guests

    It’s Microsoft rant time. I’m currently running a beefy (12Gb Ram, Intel i7 etc.) Windows 7 Ultimate X64 system and am trying to prepare for upcoming versions of Microsoft software that I know I will be testing and working with on a daily basis once they get released. Like any other developer I want to run these as VMs. I’m specifically talking about Sharepoint 2010 here which is 64 bit only.

    So I download both Virtual PC 2007 SP1 and also the latest Virtual PC for Windows 7 and come to find out that neither supports 64 bit guest operating systems. Come on Microsoft, what are you playing at? VMware has supported 64 bit guest operating systems for ages now. How do you expect developers to develop against your new systems which are going to be 64 bit only if they can’t set up their own development environments? I could perhaps understand from VPC 2007 SP1 but even their new Virtual PC for Windows 7 still only supports 32 bit guests. Microsoft wants to make a dent in VMware but things like this show just how forward thinking VMware is and how much Microsoft is not.

    Virtual PC for Windows 7 is still in the release candidate phase. Lets hope that before it actually goes live, Microsoft have the foresight to allow users to install 64 bit operating systems.

    Another sticking point (although not nearly as bad) is the limit under both Virtual PC environments to allow only 3.7Gb of RAM to be allocated to a Virtual Machine. This is also true by the way for Virtual Server. This limitation also needs to be taken out of these products. Come on Microsoft, get your act together and let the world know you can be taken seriously in the virtual arena.

    Digg This
    August 24

    Professional Silverlight 2 for ASP.NET Developers - Review

    Professional Silverlight 2 for ASP.NET Developers (Wrox Programmer to Programmer)
    Title : Professional Silverlight 2 for ASP.NET Developers
    Author : Jonathan Swift
    Chris Barker
    Dan Wahlin
    Salvador Alvarez Patuel
    ISBN : 0470277750
    Price : $31.49
    Rating : 83 out of 100


    Writing a programming book is extremely difficult. You generally either end up wallowing in a blancmange of technical details suitable only for egg-heads like me or you end up with a meringue, so light on details that your granny would understand every word.

    Professional Silverlight 2 for ASP.Net developers is like a lemon sorbet fitting nicely in-between the two. Light enough to make for easy reading but with enough bite in the technical department that you walk away with a very good knowledge of actually how to do things. Wrox are known for their tombstone like manuals that are everything to everybody, desktop reference books. Over the years Wrox has went from being the absolute authority on programming (if you are old enough you will remember the Wrox book on classic Asp which was the bible for Asp programmers), to books that I honestly wouldn’t expend the energy to lift up. Lately however Wrox have been retracing their steps back to the good old days and this book on Silverlight 2 is definitely a  step along that path.  It comes in lighter than most Wrox books at only a tad over 600 pages so you don’t need professional weight bodybuilding classes just to lift it, but is packed with knowledge and information.

    As you might guess from the title, this book is not for programming newbie's and expects that you have a good understanding of ASP.Net, it’s page lifecycles, event models, and the underlying .Net Framework. This book was written squarely for Asp.Net developers who want to get to grips with Microsoft’s new(ish) Silverlight component. Silverlight 1 was fairly limited in what you could do with it and your only programming choice was JavaScript. Silverlight 2 introduced a condensed .Net Framework and CLR and therefore opened up the programming realm to C# and VB.Net programmers.

    After a brief introduction into the Silverlight world and how it is architected, you delve straight into the meaty aspects of Silverlights XAML model, a cut down version of the full client side XAML model and how to interact with the Silverlight objects in your code-behind. A chapter is dedicated on how to layout your Silverlight application detailing what controls are available to you and giving you tips and guidance on how to appropriately scale up for full-screen mode if you should decide to allow users to use this option. Next the book moves on to varied user controls that come pre-packaged with Silverlight 2, what they are, they’re various properties and quirks and also refreshing to see is some details of controls in the Silverlight Toolkit, a separate download that adds further controls and functionality Silverlight.

    Most Asp.Net developers are trying to produce standards based, best practice websites and they are a myriad of options on how to style objects and controls available within the Asp.Net framework from CSS to theming. Silverlight 2 also has these options available albeit slightly differently, there is no CSS as per se, but there is an equivalent. Chapter 7 of the book covers all of these in detail, except for one which I found odd. The book does cover best practices in separating content from styling but then does not proceed to it’s natural conclusion in removing the styling from the actual page and into a separate resource file. This strangely comes much later in the book under the chapter of working with data and appears to be a bit of a disconnect. A fairly minor gripe as the author’s do indeed cover the subject, along with best practices and explanations as to why.

    Every application needs interaction and responding to what the user is doing, the next chapter covers just this and goes into sufficient detail that you not only know about events from the built in controls but the authors give you a good explanation of the actual event model should you decide at some point to build your own controls. It’s certainly not an exhaustive view of the event model but certainly enough to get you started with your own controls. This is nicely rounded out with a chapter later in the book on precisely that, how to build your own controls.

    The next major chunk of the book deals with communicating with the server and data. Silverlight 2 is a client application with your code-behind actually running client side and not server side like you are used to with the Asp.Net programming model, therefore getting data in and out of Silverlight is slightly different. The book details well all of the possible ways that this can be accomplished and the various ways of actually getting that data into your controls and onto your page. Special attention is paid to data binding which is done slightly differently in Silverlight than in Asp.Net.

    When Silverlight 1 first appeared on the scene, most thought of it as the beauty queen of plugins, very pretty but not much substance. Silverlight 2 retains the looks of its’ predecessor but adds some meat to the bones rounding out a very nice package. The next section deals with the blush and lipstick of Silverlight, what makes it different from it’s main rival Flash, and how to take advantage of this added power and graphical wondrousness. Finally it rounds off with a few chapters on how to Troubleshoot Silverlight errors and your inevitable programming glitches and performance considerations that you should take into account with best practices on how to do this. Remember, Silverlight is a client application and therefore everything has to be sent to the client, but there are ways to do this so that your web page doesn’t take an orbit of the sun to load.  

    This is the first Silverlight 2 book that I have read that really does take into account what knowledge you should have programming web pages in Asp.Net and transferring and molding that knowledge so that it is relevant to Silverlight. The authors have done a fantastic job and given you enough details that you can be confident to get good looking and fully immersive applications in Silverlight 2.  If you are an Asp.Net developer who has a future project that will use Silverlight 2 or you just want to dip your big toe into the pond and make some waves then I thoroughly recommend this book.

    Digg This
    August 15

    New visual effect in Windows 7 that is handy for downloads

    Here’s something that I’ve never noticed before, when you are downloading a file over the internet you get the standard download dialog :-

    Download

    If you switch to another window or minimize this window then you don’t know what the progress of your download is, however in Windows 7 you can easily find the progress of your download just by taking a quick look at the Internet Explorer icon in the taskbar :-

    Toolbar

    As you can see, the Internet Explorer icon is slowly filling with a lighter background. This is actually the progress of your download. So with a quick look you can do a rough check of your download progress.

    May 28

    Beginning JavaScript and CSS Development with JQuery - Review

    Title : Beginning JavaScript and CSS Development with jQuery
    Author : Richard York
    ISBN : 0470227796
    Price : $29.69
    Rating : 79 out of 100


    Every so often in computing a language extension or new technology comes along that is the buzz of the development community. JQuery is one of those. Lots of developers are talking about it and using it, even Microsoft are including native support for it in their upcoming Visual Studio 2010 release.

    With that in mind I thought it was about time to look at what all the hype is about and learn the language. JQuery is really a library of JavaScript routines that makes your life easier. In a way it is akin to the Microsoft AJAX extensions that originally were a separate release but are now baked into the .Net Framework. Microsoft’s AJAX extensions went beyond just handling AJAX calls and put a whole framework behind JavaScript to make it easier for .Net OO developers to code in JavaScript. JQuery does the same thing, makes it easier to code certain things in JavaScript and is cross-browser compatible taking out one of the headaches a lot of developers inevitably come across.

    Beginning JavaScript and CSS Development with JQuery is a beautiful full color book from Wrox Press weighing in at just over 500 pages. Richard York assumes that you are already familiar with JavaScript and also CSS and therefore this is not a book for the complete beginner, only a beginner with JQuery.

    The book is well laid out with chapters devoted to each of JQuery’s main areas, selectors, AJAX, Manipulating the DOM, Event handling etc. etc. with numerous Appendixes that can be used as a quick reference. Each chapter has numerous examples explaining the particular JQuery concepts and constructs being discussed culminating in one big example program at the end of the chapter that brings together everything discussed in that particular chapter finally ending with a quick question exercise to make sure that the keywords and constructs discussed have truly sunk in. This is an excellent way for a beginners book to be constructed as it really hammers home what has been discussed during each chapter.

    One major annoyance I have with Richards writing style however is that he comes across as a Mac snob and throughout the book takes snipes at Microsoft and especially Internet Explorer. Whilst some of this may be deserving it is off-putting and a detraction from what is ultimately a good book.

    If you can gloss over the snobbishness I would actually recommend this book for beginners of JQuery. The full color screenshots highlight the various examples superbly and Richard does give you a lot of useful information without overwhelming you with every nuance of JQuery.


    Digg This
    May 22

    Windows Live Web Toolbar Mashup – MessyTwit

    A lot of people nowadays have Twitter accounts, a Facebook account etc. and if you’re reading this then I’m also assuming you have a Windows Live account and some interest in Windows Live Services. Each of these have their own “Personal Message” where you can tell people what you are currently doing and there-in lies the problem. You have to visit each of these places to update them individually. Why not have a central place where you can update them all?

    The good news is that you can. There are various ways of doing this, whether through a website or a Silverlight application. Basically anything that can use web services. With Microsoft’s recent introduction of the Windows Live Web Toolbar, I thought I’d do just that and show you how easy it is.  I will be building upon my previous articles regarding the new Windows Live controls so please go check them out if you haven’t already as I’ve discussed a lot of the code present in this mashup in previous articles.

    So first up, lets take a look at our actual web page :-

    MessyTwitBlank

    Here you can see that I’ve sectioned off the page. At the top of the page we will display the users Windows Live login picture along with their personal message that is tied to that account. Just below that will be the list of their contacts. This is an easy way to display the personal messages of their Windows Live contacts. The next section will be their Twitter account showing their own personal messages that they have sent to Twitter and at the bottom you will see the Windows Live Web Toolbar that we will use to sign people into their Windows Live accounts and hook in with the other Windows Live Web Controls that we display on the page.

    <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:msgr="http://messenger.live.com/2009/ui-tags">
    <head runat="server">
        <title>MessyTwit</title>
        <link type="text/css" rel="Stylesheet" href="MessyTwit.css" />
        <script type="text/javascript" src="http://www.wlmessenger.net/api/3.0/loader.js"></script>
        <script type="text/javascript" src="JScript/JQuery.js"></script>
        <script type="text/javascript" src="JScript/Messenger.js"></script>
        <script type="text/javascript" src="JScript/Twit.js"></script>
        <script type="text/javascript">
            Microsoft.Live.Core.Loader.load(['Messenger.UI', 'Messenger.UI.Styles.Core'], null);
        </script>
    </head>
    <body>
        <msgr:app 
                privacy-url="Privacy.html" 
                channel-url="Channel.htm" 
                application-verifier-token="<%= appVerifier %>" 
                token-url="RefreshMessengerToken.aspx"
                onauthenticated="onAuthenticated"></msgr:app> 
        <form id="form1" runat="server">
        <div id="msgrDisplayPic">
        </div>
        <hr />
        <div>
                <msgr:contact-list word-wheel-enabled="false"></msgr:contact-list>
            </div>
            <hr />
    <%--    <div id="ctrls">
                <msgr:personal-message cid='$user' id='persmsg' editable='true'></msgr:personal-message>
        </div> 
    --%>    
            <div id="msgs">
                <div id="TwitCreds" class="msgHidden">
                    <span>Twitter Username&nbsp;&nbsp;</span>
                    <input type="text" id="acct" /><br />
                    <span>Twitter Password&nbsp;&nbsp;</span>
                    <input type="password" id="pwd" /><br />
                    <span id="TwitLogin">Login to Twitter</span>
                </div>
        </div>
        <hr />
            <div id="persMsg" class="msgHidden">
                <input type="text" id="msg" value="Enter a personal message" size="80" />
                <span id="msgsend">Send</span>
            </div>
        <div>
                <msgr:bar sign-in-enabled="true"></msgr:bar>
        </div> 
    </form>
    </body>
    </html>

    Above is the default.aspx page. As you can see, it’s not very complicated at all. Most of this was covered in my previous articles so I’ll just give a quick rundown here.

    At the top we include various Javascript files which we’ll cover later and we tell the page to load the messenger controls when the xhtml page has loaded.

    Next we have the messenger application section in which we supply various required variables such as where our privacy and channel pages are and we also set an event for when the user has authenticated (logged in to) their Windows Live Account.

    After that there is a placeholder for where we will put the users display picture and Windows Live personal message. Following the horizontal rule (I’ve only put that in the display physically break the page into sections) we have the Windows Live Contact List control. It’s as simple as that one line of markup to display a very nice list of the users contacts.

    The next section on the page is where we will gather the users’ Twitter credentials so that we can interact with their Twitter account.  Towards the bottom we have a simple input box that the user will type their personal message in to and finally we display the Windows Live Web Toolbar at the bottom of the page.

    For completeness here is the code behind for the default.aspx page :-

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using WindowsLive;
    using System.Diagnostics;
     
    public partial class _Default : System.Web.UI.Page 
    {
        WindowsLiveLogin wll = new WindowsLiveLogin(true);
        public string appVerifier
        {
            get
            {
                return wll.GetAppVerifier();
            }
        }
    }

    I’ve covered this before so won’t go into it here.

    The corresponding style sheet associated with this page is very basic. Here is MessyTwit.css :-

    input#msg
    {
        border-width: 0px;
    }
     
    .msgHidden
    {
        display: none;
    }
     
    .msgShow
    {
        display: block;
    }

    We hide the border around the personal message input box and we define two classes to hide or show various elements of our page.

    There are two main Javascript files that cover all of the functionality on the page. The Messenger.js file I’ve basically covered before :-

    var userToken = null;
    var msgrUser = null;
    function onAuthenticated(e)
    {
        msgrUser = e.get_user();
        msgrUser.add_signInCompleted(SignInCompleted);
    }
    function onUserConsentCompleted(e)
    {
        userToken = e.get_consentToken();
    }
    function SignInCompleted(sender, e)
    {
        if (e.get_resultCode() === Microsoft.Live.Messenger.SignInResultCode.success)
        {
            if (typeof (InvokeOnUserSignIn) === 'function')
            {
                InvokeOnUserSignIn();
            }
        }
        else
        {
            OnUserSignedOut();
        }
        var userAddress = msgrUser.get_address().get_address();
        var usercid = msgrUser.get_identity().get_cid();
        var signinframe = document.getElementById("msgrDisplayPic");
        var tag = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('display-picture', 
        { 'cid': usercid, 'presence-enabled': 'true', 'size': 'Large', 'logo-enabled': 'true' });
        $("#msgrDisplayPic").append(tag);
        var tag2 = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('personal-message', { 'cid': '$user', 'editable': 'false', 'id':'Persmsg2'});
        $("#msgrDisplayPic").append(tag2);
        $("div#TwitCreds").removeClass("msgHidden");
        $("div#TwitCreds").addClass("msgShow");
    }
    function OnUserSignedOut()
    {
        //add code for sign-out.
    }

    As a quick overview we have the onAuthenticated event handler that we tied up in the messenger application block on the default.aspx page. As mentioned this gets fired when the user logs in to their Windows Live account. Once they login we capture that event and extract the user object then setup another event to capture when sign-in has been completed. The API fires off multiple events at differing stages of login. Another one of those events is when the user gives consent to send information back to our web site. In this event handler we simply capture the consent token that is sent.

    Once the user has completed sign-in we make sure that sign-in was successful (i.e. the correct username and password were supplied). Next we create the users display picture and also their personal message. These are two different Windows Live controls.

    The documentation for the Personal Message control says that it must have the CID of the user in order to display their personal message. This makes sense. However if you pass in the CID as we do for the display picture, the Personal Message control does not work. You HAVE to pass the $user string that is a reserved variable created by the Windows Live API.

    Next we simply use some jQuery to insert these controls onto our page. We also now use some jQuery to show the Twitter credentials portion of our web page which is hidden until after the user signs in to their Windows Live account.

    MessytwitAfterLogin

    After the user has signed into their Windows Live account, this is what you will see. On this screenshot, my personal message is not displayed as I don’t have a personal message currently tied to this account however the control is present as you’ll see later.

    The second of the two main Javascript files, twit.js, contains the jQuery functions for manipulating the page. This is all new so I’ll break it down a bit :-

    $(document).ready
    (
        function()
        {
            $('span#msgsend').click
        (
            function()
            {
                var acct = $("input#acct").val();
                var pwd = $("input#pwd").val();
                var msg = $("input#msg").val();

    Everything in this Javascript file is done using event handlers. We attach the event handlers to the default.aspx document on ready. This is slightly different than onLoad. With onLoad you need to wait until the page has fully loaded, including the images that are displayed on the page. With jQuery’s ready handler the page has basically loaded, we have access to the page DOM, script etc. but we don’t have to wait until all the images are loaded.
    So in the ready section we attach an event handler to the “send” text next to the personal message input. I just used text here but it could just have easily been a button.
    When the text gets clicked we first get the username and password for the users Twitter account and we also get the personal message they want to send.
     
    $.post("/MessyTwit/TwitterService.asmx/SendTweet",
    { 'account': acct, 'pass': pwd, 'msg': msg },

    Next we have an AJAX call to a web service that we have created to send the personal to the users Twitter account.

    function(_xml)
    {
        $('div#msgs').text('');
        $xml = $(_xml);
        $xml.find("status").each
    (
        function()
        {
            $('div#msgs').append("<div><img src='" + $(this).find("profile_image_url").text() + "'/>" +
            "<span>&nbsp;&nbsp;" + $(this).find('text').text() + "</span></div>");
        }
    );
    }
            , 'xml');

    To finish off this AJAX call we define an anonymous function that gets called once the call returns to our script. Here we first blank out any Twitter messages that may already be displayed on the screen. Then we take the XML that is returned by the AJAX call and parse it. We loop through the XML parsing each individual message. For each message we take the display picture of the user and also the text of the message and display it in the placeholder we marked out in our default.aspx page.  The final part to this is just saying that the AJAX call will use XML rather than JSON or some other format.

            if (msgrUser)
            {
                msgrUser.get_presence().set_personalMessage(msg);
            }
     

    So we have posted the users personal message to their Twitter account, next we need to do the same for their Windows Live account. In the code above, this is exactly what we do. We first check to see that the user object isn’t null and if it’s not then we simply call the set_personalMessage method to update their Windows Live personal message.

            $('input#msg').val('');
     
        }
    );

    Finally for this event handler we do some cleanup. Here I’m blanking out the personal message input box ready for their next message.

     

    $('input#msg').focus
    (
        function()
        {
            $(this).val('');
        }
    );
     
    $('input#msg').blur
    (
        function()
        {
            if (this.value == '')
            {
                this.value = 'Enter your personal Message';
            }
        }
    );
     

    Here is the personal message input box before the user has clicked on it :-

    MessyTwitInput1

    and after they have clicked on it :-

    Messytwitinput2

    The next two event handlers we define are tied to the personal message input box. All that this does is blank the input box when the user focuses on it (clicks or tabs into it). If the user clicks or tabs away from it and the input box is blank then we insert the message “Enter your personal Message” into it so the user knows where to type.

            $('span#TwitLogin').click
            (
                function()
                {
                    $('div#persMsg').removeClass('msgHidden');
                    $('div#persMsg').addClass('msgShow');
                    $('div#TwitCreds').removeClass('msgShow');
                    $('div#TwitCreds').addClass('msgHidden');
                    var acct = $("input#acct").val();
                    $.post("/MessyTwit/TwitterService.asmx/GetTweet",
                { 'account': acct },
        function(_xml)
        {
            $xml = $(_xml);
            $xml.find("status").each
        (
            function()
            {
                $('div#msgs').append("<div><img src='" + $(this).find("profile_image_url").text() + "'/>" +
                "<span>&nbsp;&nbsp;" + $(this).find('text').text() + "</span></div>");
            }
        );
        }
                , 'xml');
                }
            );
     
        }
    );

    The final event handler is tied to the text I’ve displayed on the page for logging in to their Twitter account. Again, I’ve just used some text but it could just as well be a button control.

    When the user clicks on the login text we hide the twitter login credentials area and display the personal message input box. Next we get the users username and again make an AJAX call. This time only to retrieve the users’ own Twitter messages. Finally we use the same anonymous function as we had above to parse through the returned XML and extract the display picture and message from each message returned and display them onscreen. As soon as the user enters their Twitter credentials you should see the following :-

    MessyTwitTwitSignin

    Now you can take this code and expand on it so that when the user clicks on the login text you actually do a check against their Twitter credentials and display an error message if they are not correct. Twitter has lots of web service calls that you can use to make this code more robust. See the Twitter API for more details.

    This really only leaves one piece left, our web service :-

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Xml;
    using System.Xml.Linq;
    using System.IO;
    using System.Net;
     
    /// <summary>
    /// Summary description for TwitterService
    /// </summary>
    [WebService(Namespace = "blah")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class TwitterService : System.Web.Services.WebService {
     
        public TwitterService () {
     
            //Uncomment the following line if using designed components 
            //InitializeComponent(); 
        }
     
        [WebMethod]
        public XmlDocument GetTweet(string account) 
            {
                string url = "http://www.twitter.com/statuses/user_timeline/" + account + ".xml?count=5";
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
                Request.Method = "GET";
                WebResponse Response = Request.GetResponse();
                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                string Result = Reader.ReadToEnd();
                Reader.Close();
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(Result);
                return doc;
        }
     
            [WebMethod]
            public XmlDocument SendTweet(string account, string pass, string msg)
            {
                string url = "http://www.twitter.com/statuses/update.json";
                NetworkCredential creds = new NetworkCredential(account, pass);
                string EncodedText = "status=" + HttpUtility.UrlEncode(msg);
                HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
                Request.Method = "POST";
                Request.Credentials = creds;
                Request.ContentType = "application/x-www-form-urlencoded";
                Request.ContentLength = EncodedText.Length;
                Request.UserAgent = "MessyTwit";
                Request.Timeout = 10000;
     
                System.Net.ServicePointManager.Expect100Continue = false;
     
                Stream reqStream = Request.GetRequestStream();
                StreamWriter Writer = new StreamWriter(reqStream);
                Writer.Write(EncodedText);
                Writer.Close();
     
                WebResponse Response = Request.GetResponse();
                StreamReader Reader = new StreamReader(Response.GetResponseStream());
                string Results = Reader.ReadToEnd();
     
                Reader.Close();
                Response.Close();
                reqStream.Close();
                XmlDocument doc = GetTweet(account);
                return doc;
            }
    }
     

    This is a standard .Net web service except that we need to un-comment the line that reads :-

    [System.Web.Script.Services.ScriptService]

    This is so that our Javascript can actually make calls to it. The first method that we have simply calls the Twitter web service and gets the top 5 messages the user has posted and returns that as XML back to our AJAX call.

    The second method is the one that actually posts the message to Twitter. After we have posted our message to using the Twitter API we make the call to the first method to retrieve the new updated top 5 messages. The main line to take note of in this method is :-

    System.Net.ServicePointManager.Expect100Continue = false;

    Without this line any posts to Twitter will fail with a 417 return code. This only applies to posts, not to gets.

    And there you have it. One web page that updates both a users’ Windows Live personal message and also their Twitter account as can be seen in the screenshot below. The Windows Live Personal-Message control now contains my latest message at the top of the page and also my latest Twitter entry has the same message :-

    MessyTwitFinal

    This should give you an idea of the kind of mashups that you can do using the new Windows Live Messenger UI controls. I’ve expanded this example to include Facebook although I didn’t put the code here but it’s fairly easy to do and the above code will give you all the basics you need. You can expand it to include any other site that does some kind of personal message you wish.

    One final point should be noted. The Windows Live Web Toolbar includes it’s own area in which a user can type their personal message. When the personal message gets posted you can capture the event using the following :-

    // attach event for future changes
    user.get_presence().add_propertyChanged(function (sender, e) {
      if (e.get_propertyName() == "PersonalMessage")  {
        var msg = user.get_presence().get_personalMessage();
      }
    });

    This also applies to the Personal Message UI control if you allow it to be edited. This way you can handle whether the user types their personal message into the Web Toolbar or using a control that you’ve specifically placed on the page.

    Digg This
    May 13

    New Computer

    Well I received my new computer last week. Everybody seems to be doing some kind of unboxing thing on the web nowadays so here is mine :-

    DSC00002

    Here it is. Two absolutely massive boxes just waiting to be opened.

    DSC00003

    Lets start with the smaller box

    DSC00004

    DSC00005

    DSC00006

    It turned out to be the monitor. It’s a massive 24 inch display and as you can see can display resolutions up to 1920x1200 widescreen format. Built into the monitor are a couple of DVI ports, VGA, RCI and even an HDMI port that can display full hi-def 1080p television. As well as this there are a few usb ports and also two multi-function card readers.

    DSC00007

    DSC00008

    DSC00018

    Next up the other box which should be the computer, even though it is the bigger of the two boxes :-

    DSC00009

    DSC00010

    DSC00011

    DSC00012

    DSC00013

    DSC00014

    The black box that came packaged contained the manuals, install DVDs, mouse, keyboard etc.

    DSC00015

    DSC00016

    Get it set up and ready to turn on for the first time.

    DSC00019

    DSC00020

    DSC00021

    DSC00022

    Yep, appears to work. Now whenever you get a new computer, what’s the first thing you do (apart from test to see if it works)? Install software? Configure it? Nope, take it apart :-

    DSC00024

    DSC00025

    I wanted to take it apart to add another Hard Drive to it. A 1Tb Western Digital Black drive.

    DSC00026

    DSC00027

    There we go. I also got a new 1Tb Cavalry External hard drive as well with USB and eSATA connections.

    This is a monster of a machine. Here are just a few of the specs :-

    1. Intel i7 quad core processor
    2. 12Gb tri-channel memory
    3. 2.6 Tb Hard Drive space
    4. 1Gb ATI 4870 DDR5 graphics card
    5. Soundblaster X-Fi PCI sound card
    6. Multiple USB and Firewire slots, eSATA, Gigabit ethernet, DVD+-RW, Multi-card reader etc. etc.

    I upgraded from the Vista 64 Home Premium that came with the machine to Vista 64 Ultimate edition and ran the system rating tool topping it out at 5.9 for every reading. As you can see, not a bad system :)

    Windows Live UI Controls

    Following on from my previous tutorial on how to integrate the Windows Live Web Bar into your site, we’ll build upon this and show you some of the other UI controls that you can use in your site.

    One thing that a lot of people might want to do is display the signed-on users’ display picture somewhere on the site other than in the web-bar.

    MessytwitDisplayPic

    As with most everything Microsoft does in the web space there are a couple of ways of doing this. Lets start by doing it the easy way. Take the default.aspx page from the last tutorial and add a new <div> element under the <form> tag :-

    <form id="form1" runat="server">
    <div id="msgrDisplayPic"></div>

    Into the div tag we will add the display picture UI control. This control has a few different options you can specify but only one is actually required, the cid of the user who’s image you wish to display. How do you get the cid of the signed-in user? Again there are a couple of ways of doing this but we’ll take the easy route again. For use with their tags on the aspx page, Microsoft has thoughtfully provided a variable that automatically gets populated with the users’ cid, $user. So the base tag that we need to enter into our div looks like this :-

    <msgr:display-picture cid='$user'></msgr:display-picture>

    When you run the page you’ll notice the default “blank” user image as nobody has signed in yet :-

    MessytwitDisplayPic1

    When a user signs in then this image will change to the users’ display picture as seen above.

    There are a couple of options that you can add to the control. You can adjust it’s size by supplying it with a size attribute. Size can take three pre-defined values, Small, Medium and Large. By default the control is set to Medium size. You can also tell it whether to enable or disable presence information (the “glow” around the border of the image). By default this is set to true so presence information is displayed. Finally you can also state whether a logo is displayed in the bottom right of the image or not by setting the logo-enabled attribute. The default is set to false. When set to true, a small logo is displayed :-

    messytwitDisplayPic3

    So here is our final display-picture tag :-

    <msgr:display-picture cid='$user' presence-enabled='true' size='Large' logo-enabled='true'></msgr:display-picture>

    Microsoft also allow you to override their default style sheets for this control giving you a range of options :-

    • DisplayPictureControl: The outermost container of the display-picture tag.
    • DisplayPictureControl Border: Specified when presence is enabled.
    • DisplayPictureControl Large: Specified when the size is "large".
    • DisplayPictureControl Medium: Specified when the size is "medium".
    • DisplayPictureControl Small: Specified when the size is "small".
    • DisplayPictureControl_Icon: The logo if the logo is enabled.
    • DisplayPictureControl_Image: The display picture.
    • DisplayPictureControl_Image Online: Specified when the status is Online.
    • DisplayPictureControl_Image BeRightBack: Specified when the status is Be Right Back.
    • DisplayPictureControl_Image Busy: Specified when the status is Busy.
    • DisplayPictureControl_Image Away: Specified when the status is Away.
    • DisplayPictureControl_Image InACall: Specified when the status is In A Call.
    • DisplayPictureControl_Image OutToLunch: Specified when the status is Out To Lunch.
    • DisplayPictureControl_Image AppearOffline: Specified when the status is Appear Offline.
    • DisplayPictureControl_Image Offline: Specified when the status is Offline.

    And that’s it, you can now add the users’ display picture to anywhere on your site with one tag.

    If you want more fine grained control over the process or you wish to do all this programmatically Microsoft also allows you to do this.

    First remove the <msgr:display-picture> tag from the default.aspx, but keep the <div> tag in place. Next create a Javascript file and add a reference to it at the top of the default.aspx :-

    <script type="text/javascript" src="JScript/Messenger.js"></script>

    In this Javascript file we will programmatically insert the users’ display picture control onto the site. I’ve added a couple of extra event handlers to this file that you don’t necessarily need but are very handy to have as well. First off we want to declare a couple of global variables, one to hold the users’ token that gets generated when they give their consent to sign-in to your site, and the second is to hold the actual user object :-

    var userToken = null;
    var msgrUser = null;

    Our first event handler gets fired once the user gives his permission to sign into your site :-

    function onUserConsentCompleted(e)
    {
        userToken = e.get_consentToken();
    }

    All that we’re doing here is getting the consent token that gets generated and storing it in our global variable for use later.

    The next event handler gets fired once the user has authenticated (i.e. the windows live credentials are correct) :-

    function onAuthenticated(e)
    {
        msgrUser = e.get_user();
        msgrUser.add_signInCompleted(SignInCompleted);
    }

    Here we capture the actual user object (the most important object you use when dealing programmatically with Windows Live Web Messenger) and store it in our global variable. Then we add an event handler for when the sign-in process has completed.

    function SignInCompleted(sender, e)
    {
        if (e.get_resultCode() === Microsoft.Live.Messenger.SignInResultCode.success)
        {
            if (typeof (InvokeOnUserSignIn) === 'function')
            {
                InvokeOnUserSignIn();
            }
        }
        else
        {
            OnUserSignedOut();
        }
        var usercid = msgrUser.get_identity().get_cid();
        var signinframe = document.getElementById("msgrDisplayPic");
        var tag = Microsoft.Live.Messenger.UI.Tags.TagsFactory.createTag('display-picture', 
        { 'cid': usercid, 'presence-enabled': 'true', 'size': 'Large', 'logo-enabled': 'true' });
        signinframe.appendChild(tag);
    }

    The SignInCompleted handler first of all checks to see if authorization was correct (did the user really sign in or did they perhaps have a typo and sign-in wasn’t completed successfully). If sign-in was not correct then we make sure our page reflects that by calling our sign-out routine which should house any clean-up code.

    If the user has successfully signed in then we grab their cid. Remember, this is the one required field for the display-picture control (and most other controls as well). Next we get a reference to our <div> element where we want to place the display-picture control. All Windows Live Messenger UI Controls are instantiated through the TagFactory object. Here we simply call the method createTag and pass into it two values. The first is the type of control that we wish to create, in this case the display-picture control. The second value is a set of key:value pairs containing any attributes that we wish to supply. In the example code above we are simply re-creating the <msgr:display-picture> tag we created earlier on the page itself. The only difference here is that we are passing in the cid manually. Finally we simply add this control into the <div> tag we got a reference for earlier.

    The final entry in our Javascript file is the event handler for when the user signs out :-

    function OnUserSignedOut()
    {
        //add code for sign-out.
    }

    And that’s it, you will end up with exactly the same screen as we did earlier, only this time you have gained knowledge in how to do it programmatically.

    The basics on what we have covered here applies to all the other Web Messnger UI controls. For example, if we wanted to add the contact-list control to our page we simply add the appropriate tag within our page or do it programmatically :-

    <msgr:contact-list word-wheel-enabled="false"></msgr:contact-list>

    And this results in the following :-

    MessytwitContacts

    There are a lot of UI controls to explore. You can find more information about what’s available, their methods and parameters etc. over on msdn :- http://msdn.microsoft.com/en-us/library/microsoft.live.messenger.ui.tags.aspx

    Digg This
    April 28

    Windows Live Web Toolbar – How to integrate into your site

    A few months ago at Mix 09, the Windows Live Team launched a number of exciting new additions under the Windows Live Web Toolkit. One of which was the Windows Live Web Toolbar. This toolbar allows you include presence information into your site as well as other social experiences.

    Unfortunately due to the limitations of Windows Live Spaces I cannot post the article on here.  I’ve posted the article on Liveside.Net, so please hop over and see the article in full there.

    http://liveside.net/developer/archive/2009/04/27/windows-live-web-toolbar-how-to-integrate-into-your-site.aspx

    Digg This
    April 21

    UI Controls for Web Messenger

    Microsoft have now made your job even easier if you are developing your own Messenger application on your website. Not only have they produced an excellent API that I have written about before but they have now released a whole bunch of controls.

    If you head over to http://msdn.microsoft.com/en-us/library/dd570052.aspx you will find all the new controls listed by section.

    Examples of some of these controls are :-

    MessengerContactPicker

    The Messenger Contact Picker control

     

    MessengerDisplayName

    The Messenger Display Name control

     

    MessengerProfileControl

    The Messenger Profile control

     

    MessengerWebBar

    and of course the new Messenger Web Bar. 

    There are lots more controls to be had. Go check them out and look here in the coming weeks on tutorials on how to use them in your own sites.

    Digg This

    April 06

    Data-Driven Services with Silverlight 2 - Review

    Title : Data-Driven Services with Silverlight 2
    Author : John Papa
    ISBN : 0596523092
    Price : $44.99
    Rating : 83 out of 100


    Developers and businesses alike are starting to see the benefits of Silverlight 2 and more and more are starting to take advantage of it’s capabilities. Most web-developers have a good knowledge of Microsoft’s .Net platform, they also have good knowledge of HTML, CSS and all the other technologies surrounding the web. However presentation fairly much still is lacking on the web front, even with the acceptance of AJAX, it’s still like an amateurs representation of the Mona Lisa compared with the desktop cousins.  The first version of Silverlight was mainly geared towards video and audio and was restricted to the Javascript language. With the introduction of Silverlight 2, you now have pre-built controls at your disposal, C# and VB.Net programming access and a whole lot more. The painting has now gone from being amateurish to professional but still not quite the original. Now however developers can re-use their existing .Net Framework knowledge without having to learn another language like Flash and have a rich user experience. One thing that you will definitely need is data. Data is king in any application and gaining access to your data is what this book is all about.

    Silverlight 2 introduced various ways in which you can gain access to your data, through RESTful web services, SOAP, RSS, AtomPub, POX, JSON, direct from a backend database etc. etc. You can write your own data layers or bind directly to controls and can even use LINQ.

    John Papa takes you by the hand and shows you how to do all of the above scenarios and more. The book is very well written, easy to read and understand and no filler (something I’m really disliking about certain books, putting filler in just to increase page count).

    There are whole chapters dedicated to each of the main ways to gain access to your data and bind it to your front end application with numerous examples throughout including how to read Tweets, access and consume Amazon RESTful services, the ADO.Net Entity Framework etc. If there is a way to access data you will find out how to incorporate that into your Silverlight 2 application with this book. And of course, you can also take the techniques John has so masterfully expounded on in this book and use them in your standard ASP.Net web sites as well.

    If you’re a Silverlight developer, this is one of those must have books. You’ll refer to it over and over. Even if you’re a standard ASP.Net developer it is worth taking a look through this book as most of the content can very easily be applied to a normal ASP.Net site.

    March 20

    Using Linq to amend a Word document

    I got handed an interesting little problem as an emergency project yesterday.  The basis of it was that I had to dynamically insert content into a word document (user name, email address, phone number, physical address etc.). This had to be done from a web site so I couldn’t just add some code to word and distribute the word document.

    So the basis of my solution was to get hold of the word document that needed to be amended and insert bookmarks where ever the data had to be inserted. Then split out the word document into it’s constituent parts (a docx file is really just a zip document). When you unzip a word document (by renaming the extension from docx to zip then unzipping with something like winzip) you end up with the following documents and folders :-

    Word1

    What we’re really interested in however is what’s in the word folder :-

    word2

    In this folder you’ll find document.xml which is the file that actually contains all the text etc. for the word document.  So what we want to do is create a little program that parses the document.xml file for all of our bookmarks, insert the appropriate content and save the new file out.

    It’s not as hard as what it seems.  Here’s where Linq comes in very handy. Just copy the unzipped word document files into a folder under the website root :-

    word3

    Here’s the code from my quick test program :-

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.IO;
    using System.Xml;
    using System.Xml.Linq;
     
    /// <summary>
    /// Summary description for WordDocx
    /// </summary>
    public class WordDocx
    {
        public WordDocx()
        {
        }
        public void AmmendDocx(string username)
        {
            IEnumerable<XElement> bookmarks;
            //List<XElement> bookmarks = new List<XElement>();
            XDocument doc = XDocument.Load("E:\\WordDocSite\\Docx\\word\\document.xml");
            XNamespace namesp = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
            bookmarks = doc.Descendants(namesp + "bookmarkStart");
            int count = bookmarks.Count();
            foreach (XElement el in bookmarks)
            {
                string attr = el.Attribute(namesp + "name").Value;
                if (attr.ToLower() == "username")
                {
                    el.AddAfterSelf(new XElement(namesp + "r", new XElement(namesp + "t", "value")));
                }
            }
            doc.Save("E:\\WordDocSite\\Docx\\word\\document2.xml");
        }
    }

    This isn’t the final code that I wrote, just a quick proof of concept for manipulating the content of the word document.
    First off you load the document.xml into a XDocument class. Next you need to declare the appropriate namespace then we simply query the document.xml to extract all the “w:bookmarkStart” tags, “w” being the namespace prefix. Once you have all the bookmarks in your IEnumerable collection you can simply run through them with a foreach, query the “w:name” attribute which tells you which bookmark is which, insert your text required by creating a couple of XML Elements and finally save out the file.

    In the final code you simply do a select…case statement against the “w:name” attribute and have routines for adding the appropriate content.

    Once all of this is done you simply need to zip up all the files within the Docx folder. For this I used the NSoftware IP*Works Zip library (which is excellent and very easy to use. NSoftware has a whole range of tools to help you with things like this. I would recommend that you go check out what they have to offer).

    nsoftware

    Once it’s zipped up, rename the extension back to docx and do a simple response.redirect to point to the file so that the end user can download it.