Thursday, May 15, 2008

wpf: key concepts

databinding and itemtemplate

databinding is key to writing less code for populating fields. you can databind to anything that implements INotifyPropertyChanged (for objects) or INotifyCollectionChanged (such as ObservableCollection, for collections). the syntax uses “{}” brackets and the keyword “Binding” and looks like this:

<TextBox Text={Binding Path=Name} />

elements in your xaml inherit the DataContext (the object or collection that you’re binding to) from their parent object(s). you can set the DataContext in code or via markup with the Source attribute of a Binding markup that generally points to a static resource:

<TextBox Text={Binding Path=Name, Source={StaticResource MyCollection}} />

the syntax definitely feels weird at first, but it gets easier as you start using it, and it lets you have nice MVC-style UI/business logic separation.

ItemTemplate works like a repeater or grid template in asp.net. you define exactly how you want the items in your ItemsContainer (e.g. a listbox) to be displayed:

<ListBox ItemsSource="{Binding Conferences, Source={StaticResource ConferenceManagerDS}}" SelectionChanged="ConferencesListBox_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Id}"></TextBlock>
<ListBox ItemsSource="{Binding Members}"></ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

see here for a good overview: http://www.vsj.co.uk/dotnet/display.asp?id=500

dependency properties

the idea here is that the property owner doesn’t necessarily know the value of his own property, since it “depends” on external factors, like whether or not an animation is occurring. so instead of creating a normal {get; set;} property, you “register” your property with the global, static “PropertyManager”, and then you access the value of your property via the instance method DependencyObject.GetValue(). so if you have a Button, you access it’s FontStyle property like this:

b.GetValue(Button.FontStyleProperty)

almost always the property author will implement a normal C#-style property accessor as well, which just calls the GetValue() and SetValue() dependency methods for you, so you can still say b.FontStyle = new Font() or in this example canvas.InkThickness = 4:

public int InkThickness
{
get { return (int)GetValue(InkThicknessProperty); }
set { SetValue(InkThicknessProperty, value); }
}

use the snippet "propdp" and most of the magic will be taken care of for you.

attached properties

attached properties are a special type of dependency property that allow a child element to set a property value that its parent reads.

as an example of why this is useful, think of how in WinForms every UI component derives from “Control”, and “Control” has properties like “Left” and “Top”. when a container goes to layout its children, it uses Control.Left. this means that the container has to have hard-coded logic that only something that derives from “Control” can be one of its children. this works out ok for core properties like Left and Top, but if you want to add another property that some UI components need, you either need to derive from Control and then have your custom controls derive from that derivation, or you need to edit the source for Control (if you have it) and add the property there. the problem is that the new property may or may not be relevant to all derived classes, and it may even interfere with a property that the derived class has added to itself.

attached properties let the container specify “i have these properties that are impt to me but may or may not be of interest to you”, and then the child can optionally “attach” a value to them. for example, to specify that a textbox in a canvas should have a left of 40, you write:

<TextBox Canvas.Left=”40” />

and to specify the row an element should be in inside a grid, you write:

<TextBox Grid.Row=”1” />

this allows a container to contain any type of child, not just those that derive from an expected type.

use the snippet “propa” and most of the magic will be taken care of for you.

routed events

this is just an elegant way of having Preview and non-Preview events. Preview events go top-down (they “tunnel”), and allow a parent to handle the event before it gets to a child. non-Preview events (they “bubble”) go from the child up. you register your events with the EventManager in a similar way that you do with dependency properties and the PropertyManager.

commands

these are WPF-only (i.e. they don’t exist in Silverlight 2 Beta 1). commands enable a MVC-type of design pattern, where the view (xaml) just asks the Controller (who implements ICommand) to perform an action or if an action is performable. josh smith has a good article on using commands here: http://www.codeproject.com/KB/WPF/MVCtoUnitTestinWPF.aspx.

triggers

another WPF-only feature, triggers do what you’d imagine: they let you specify a condition that causes an action. these are used extensively in styles when you want to have the style change on some event, for example:

<Style x:Key="MyContainer" TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Blue" />
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</Style.Triggers>
</Style>

Monday, April 28, 2008

row concatenation in sql2005

just reading about a new “FOR XML PATH” operator in sql2005 that apparently gives us a better way to do row concatenation than what we’ve been doing. instead of something like:

DECLARE @categories varchar(200)
SET @categories = NULL

SELECT @categories = COALESCE(@categories + ',','') + Name
FROM Production.ProductCategory
ORDER BY LEN(Name)

SELECT @categories

you write this (you’ll need to strip out leading ‘,’):

SELECT ',' + Name
FROM Production.ProductCategory
ORDER BY LEN(Name)
FOR XML PATH('')

one author saw up to a 10x speed improvement, but this will depend on the specifics of your query, so double-check the execution times if you use it. articles are here:

http://www.sqlmag.com/Article/ArticleID/96784/sql_server_96784.html

http://msmvps.com/blogs/robfarley/archive/2007/04/08/coalesce-is-not-the-answer-to-string-concatentation-in-t-sql.aspx

Sunday, March 30, 2008

msft wpf bootcamp

http://www.visitmix.com/university/wpf/bc08/

IE-only for some reason, but these video recordings of the presentations at Microsoft’s WPF Bootcamp look like a great starting point if WPF/Silverlight is new to you. WPF and Silverlight (v2) are going to be a big part of the work we do this summer and going forward, so start reading, learning, and playing with these technologies whenever you have some time--

Wednesday, March 26, 2008

silverlight 2 and IIS

if you want to access your silverlight 2 app from IIS, make sure you add a mime type in IIS for “.xap”:

Extension: .xap

MIME Type: application/x-msdownload


took me forever to figure out why it was working fine when running via the development server but not via IIS…

Wednesday, March 19, 2008

getting VS to launch in admin mode when double-clicking .sln file

this has been bugging me forever, finally got it worked out: the trick is that .sln files are associated with the ‘Visual Studio Version Selector’, not with Visual Studio itself. so you have to set the version selector, not visual studio, to run in administrator mode by default. first you have to find it:

C:\Program Files\Common Files\microsoft shared\MSEnv\VSLauncher.exe

then you just go to the .exe’s Properties window -> Compatibility tab -> Privilege Level frame and check 'Run this program as an administrator'.

Friday, March 7, 2008

Mix08 days 2 and 3

Mix08 finished up today, lots more good stuff. especially want to call out the "Story of the Office Ribbon" presentation, the speaker (jensen harris) was awesome as he showed various Ribbon prototypes, and it was super-interesting to see the evolution and all the thinking that went into it. you can watch it here:

http://msstudios.vo.llnwd.net/o21/mix08/08_WMVs/UX09.wmv


the ASP.NET MVC talk was also very interesting. MVC will live side-by-side with WebForms, and it gives a really clean (java) way to build test-driven web sites. it definitely has a future with us (it's in somewhat early beta now). you can watch or see slidedecks of it and others here:

http://sessions.visitmix.com/


-----


What's New in .NET 3.5, Rob Reylea, MSFT
- hardware-accelerated bitmap effects
- performance improvements
o cold-startup speed improvements of 15-40%
- easier install process

AOL Silverlight Mail Client Lessons Learner, AOL
- poorly attended, bad speakers, AOL irrelevant to this crowd even with ~50 million users

Silverlight 2.0, Karen Corby, MSFT
- design-ability improvements from 1.0
o user controls (encapsulation, re-use)
- derive from UserControl
o events at element level, as opposed to application level
o tabbing works automatically (like it does in html)
- custom controls - derive from Control
o use generic.xaml to specify style and template
- Parts Model for template support (override visual tree) - easy way for template designer t o say "these are the parts i'm expecting"
o ElementParts
§ Named elements in template
o StatesParts
§ Storyboard that controls the parts
o specify [TemplatePart()] attributes for each parts element
- Blend 2.5 has built-in support to build UserControls from selected set of controls


Steve Ballmer Keynote
- he's crazy and he loves developers
- silverlight is part of msft's long-term vision of web/desktop fusion
o 1.5 million silverlight downloads (did he say per day? possible?)
- in response to msft's diversity of businesses: you either broaden or you become irrelevant
- heathfall -> msft investment in healthcare

Social Networks, panel with Garret Camp (msft live) Marc Canter, Allen Hurff (MySpace), David Morin (business sn), someone from Facebook
- openId - relies on URL, not consumer friendly
o major players (facebook, msft live) are watching, but not adopting
- facebook charges $.50/app install
- privacy is the biggest issue, bigger than security and pedophiles
- lack of data portability is major issue, users need to preserve anonymity at times and share data across the web at other times
- 4/10,000 click through an ad

ASP.NET MVC, Scott Hanselman, MSFT
- implemented using HttpHandlers and HttpModules
- release expected later this year/early next
- side-by-side with WebForms
o more control over <html> output
o makes possible unit testing and test-driven development
o SEO and REST friendly url structures
o ideal separation of tiers
- request engine
o "route" is determined (routes specified in Application_Start) from specified URL (by default "/Controller/Action")
§ routing engine handles friendly url parsing and is decoupled from MVC
o controller method is invoked
o controller optionally talks to model
o controller passes off something to view
o view knows what its getting and how to render it
§ view can spit out html (WebForm, xslt, etc.), rss, json, etc.
§ view engine can be replaced (e.g. NHaml)
- to test controller, use empty view engine that implement IViewEngine

The Office Ribbon, Jensen Harris, MSFT (http://blogs.msdn.com/jensenh)
- easily the best presentation of the conference
- lots of prototyping; can we buy time in the UI lab?
- small buttons close to cursor or large buttons far away
- side vs. top
o people felt more comfortable on top in testing
o fear that sidebar would devolve into scrolling list
- evaluate
o longitudinal visibility - usage over time (i.e. 2 months, not 2 hours)
o feature affinity - how people use things together
o command loops - eliminate tab switches
o get fresh eyes!
o eye tracking - heat map, gaze tracking
- ask users where they think items should go
o some features like header/footer had 50/50% split
- iterate!
o account for iteration in dev schedule
o 5 major revisions, 4 later in the cycle
- when is a ribbon appropriate?
o real estate tradeoff, so make sure to take other things out
o lots of commands
o galleries, visual representations of features

Next Gen User Interfaces with WPF, Electric Rain
- workflow, design, build
o workflow = goals, foundation
o research, prototype, functional not pretty
- avoid monolithic specs in favor of rapid prototyping
o developers ask for product design specification when needed

Thursday, March 6, 2008

Mix08 day 1 notes

Key Note Addresses


- ray ozzie spends 30 minutes describing something we've all heard before and unfortunately have to hear more about once again, aka "cloud computing"

- msft still without a legitimate strategy to transform desktop monopoly to a web one

o connected pcs/devices

o web presence

o business apps

o virtualized servers/horizontal apps is key

- scott guthrie recounts his blog postings

- dean hachamovitch (ie8 general manager) reads too much from his script

o ie8 key focus on standard compliance and interopability (as opposed to ie7's focus on security)

§ w3c spec itself is vague and open to interpretation with regard to standards

§ css 2.1 support

§ poked fun at ie7's differences from firefox and safari

o looks more or less like ie7

o ie7 "compatability mode" controlled by developers

o html5

§ back button can work as expected with ajax

§ smooth experience when connectivity is lost

o integrated developer tools similar to firebug or webdevelopmenthelper (script debugging, css inspection)

o "activities" allow in-place right-click actions on selected text (i.e. select address, right-click, view map); very cool

o subscribe to "webslices" (slices of web pages); richer content/simpler implementation than rss

o ie8 beta 1 released

- scott guthrie returns to discuss silverlight 2.0 beta 1 release

- media and advertising

o adaptive streaming

o windows media services 2008 – scalable media hosting and delivery

o bandwidth savings: iis 7 bitrate throttling allows you to specify distinct bitrates for different downloads, so you deliver initial burst, then slower follow up

o jon harris discussed rich advertising: tracking with atlas admanager, iis7 playlists to force ads before video, ad overlays with xaml

o ari paparo from doubleclick discussed doubleclick/silverlight integration vs template

o perkins miller from nbc described silverlight for 2008 Olympics (2200 live hours plus broadcast coverage)

- wpf features

o almost full wpf control library

o sockets support

o protected isolated storage

- controls shipped with OPEN source and test code; you can modify and resell

- roy ben-yoseph and eric hoffman from aol described aol’s next mail client in silverlight 2.0


Lou Carbone, UX Guru – Experience Management

- effect vs. function: manage how users feel as opposed to what you are doing for them (fedex, airlines, rotorooter, etc.)

- think about the details! users remember how they felt more than they remember what they did



Nathan Buggia, MSFT, Live Search – SEO

- 30% of all traffic to web sites is from search engines

- html tips

o <title> and <h1> tags are the 2 most heavily weighted; <h1> is actually SUPER important on live.com since it’s used to parse organization of content

o semantic html is impt (i.e. <h1>title</h1> more easily read by robots <span class=’header’>title</span>);

o make text in href tags meaningful (i.e. not ‘click here’)

o <meta>: keywords is unused, description is used for snippet

o fqdn is important (i.e. x.y.com is higher than y.com/x) since rank is aggregated at fqdn, not at folder level (although google does consider folders)

o use RIA for spice within html pages, or at the very least have distinct urls for desired search rankings

- google is only search engine of the big 3 (google/yahoo/live) that will follow javascript redirects; need to use 301 redirect if you care

- yahoo site explorer (http://siteexplorer.search.yahoo.com) : see inbound links to your page

- prefer hyphen to underscores, since search engines are likely to interpret “_” as part of word, not as word delineators

- casing matters (since 50% of since run apache). links and links distributed to other sites need to always use the same case.

- link to the root, not to a specific page (i.e. http://www.blogger.com/exchweb/bin/redir.asp?URL=http://y.com/items not http://y.com/items/default.aspx).

- http codes

o 304 – conditional get (useful for letting engines know your page hasn’t changed to save you bandwidth)

o 503 – down for maintenance

o 302 – temporary redirect (BAD! since “temporary” is ambiguous; always use 301)

- links and tools

o http://seomoz.org/

o blogs.msdn.com/webmaster

o upcoming adcenter – msft competitor to google analytics



Silverlight 2.0, Mike Harsh, Program Manager, MSFT

- support for almost everything in WPF, plus some new controls

o MutliScaleImage – tool recursively splices a large image into 256x256 tiles, and the MutliScaleImage control automatically renders necessary tiles based on where on image the user zooms

- UserControl support!

- Local storage

o up to 1MB; if you want more, user must approve via prompt

o cross-browser “cookies on steroids”

- HTML DOM Interop

o make calls into the DOM and call javascript functions like alert()

o add items to browser’s history list

- OpenFileDialog support