Scott Hanselman

Firefox, WPF and XBAP

February 02, 2008 Comment on this post [27] Posted in Microsoft | Programming | Windows Client
Sponsored By

WoodGrove Finance Explorer - Mozilla FirefoxI finally got around to trying a .NET 3.5 XBAP (XAML Browser App or "WPF Browser Apps") in Firefox, and it works just as advertised. I put together an incredibly useful and powerful application consisting of a picture of me and a button. I think everyone will want to run it. ;)

Seriously though, it's very easy to deploy apps like this. This reminds me of the year I spent working for Aurum (then a division of Baan) creating a large application using VBPs - ActiveX Documents.

These were the same basic idea. Your application would run - then IE4, methinks - using the Browser as it's Window Frame, much the way Word or Acrobat can open up a document inside the Browser. This is all still very old-school ISite COM stuff.

Anyway, XBAPs aren't Silverlight, they are the Full .NET Framework in your browser. With .NET 3.5 that means IE or Firefox. Think of XBAPs as ClickOnce applications that never jump out of the browser.

Keep in mind that mine is a silly example, and yes, this one could be done with DHTML, however the Woodgrove Finance Application (a .NET 3.0 WPF Application, seen above in Firefox) would be more challenging, hence the idea behind WPF Browser Apps.

I fire up VS2008 and hit File | New Project | WPF Browser Application.

image

Then, I drag an image on the Page and a Button. I use Split Screen View so I can see the XAML being written a the same time. I double-click on the surface, then go back and double-click on the button. That adds the Loaded= and Click= event handlers you see below. I could have typed this manually also.

<Page x:Class="WpfBrowserApplication1.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1" Loaded="Page_Loaded">
    <Grid>
        <Button Height="57" Margin="70,0,70,24" Name="button1" 
VerticalAlignment="Bottom" Click="button1_Click">What a great App!</Button> <Image Name="image1" Margin="50,18,48,96" > <Image.RenderTransform> <RotateTransform Angle="0" CenterX="100" CenterY="100" /> </Image.RenderTransform> </Image> </Grid> </Page>

I'm going to do two things. One, I'll load a picture from an Embedded Resource. I could have loaded it from a location like my web server, but this is harder and educational for me. Then, two, I'll make the picture turn when I push the button. I could add an Animation declaratively but again, this is a little harder and more interesting.

First, getting the embedded graphical resource. This might look familiar if you've done it with WinForms.

System.IO.Stream stream = this.GetType().Assembly.
GetManifestResourceStream("WpfBrowserApplication1.MyFile.jpg"); JpegBitmapDecoder bitmapDecoder =
new JpegBitmapDecoder(stream,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.Default); ImageSource imageSource = bitmapDecoder.Frames[0]; image1.Source = imageSource;

I've made it more lines than is needed, but basically, get the stream, decode the graphic (Gif, Jpeg, PNG) and grab the Frame. If it were a Gif, it might be animated, hence Frames[0].

Ok, easy. Now to make it spin. And not just turn in a chunky way, but smoothly turn 60 degrees with each button press. I make an animation, set a From and To value as a double and tell it to last a half second. Then I grab the RotateTransform off the image and begin the animation.

private int angle = 0;
private void button1_Click(object sender, RoutedEventArgs e)
{
  DoubleAnimation ani = new DoubleAnimation();
  ani.From = angle;
  angle += 60;
  ani.To = angle;
  if (angle >= 360) angle = 0;
  ani.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));

  RotateTransform tran = (RotateTransform)image1.RenderTransform;
  tran.BeginAnimation(RotateTransform.AngleProperty, ani);
}

There's a pile of good articles and books out there on WPF. What strikes me is how many high level it is. It's nice to think of constructs like angle and RotateTransform rather than doing the math.

The silly result of this code is at http://www.hanselman.com/clickonce/takethree/WpfBrowserApplication1.xbap and it works in both Firefox and IE if you have .NET 3.5 installed.

Related Posts

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

First Half 2008 Conference Speaking Schedule

February 01, 2008 Comment on this post [28] Posted in ASP.NET | Speaking
Sponsored By

image Well, I think I've got my schedule down for the first half of this year. Here's what I've got so far.

I'm trying to work out a way to get over to the Middle East to see and talk to Developers over there, unfortunately the flights from here usually take between 21 and 29 hours, as opposed to less than 10 to use Norway as an example. This is really hard on my diabetes (and Norway will be also but it's 1/3 as long) but it's also hard on the family and I need to keep balance. That said, I'm actively working on a way to hang out in EMEA for some time, maybe bring the family along.

I hope I'll see some of you at one of these events!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

The Weekly Source Code 14 - Fluent Interface Edition

January 31, 2008 Comment on this post [20] Posted in ASP.NET | Learning .NET | Programming | Ruby | Source Code
Sponsored By

iStock_000000237891XSmall5 If you're new to this, each week I post some snippets of particularly interesting (read: beautiful, ugly, clever, obscene) source and the project it came from. This started from a belief that reading source is as important (or more so) as writing it. We read computer books to become better programmers, but unless you're reading books like Programming Pearls, you ought to peruse some Open Source projects for inspiration.

And so, Dear Reader, I present to you fourteenth in a infinite number of posts of "The Weekly Source Code." Here's some source I was reading this week.

Over the last year or so I've seen an increase in discussion around so-called "fluent interfaces" in many languages. The addition of extension methods (mixins) to C# 3.0 has caused a flood of interesting (weird?) interface as we as a collective to attempt to make programming as easy as writing prose.

Martin Fowler talked about this in 2005 after a workshop with Eric Evans when they first named them "fluent interfaces." He gives this example:

The simplest example is probably from Eric's timeAndMoney library. To make a time interval in the usual way we might see something like this:

TimePoint fiveOClock, sixOClock;
...
TimeInterval meetingTime = new TimeInterval(fiveOClock, sixOClock);

The timeAndMoney library user would do it this way:

   TimeInterval meetingTime = fiveOClock.until(sixOClock);

Of course, the ubiquitous Ruby example is

20.minutes.ago

Martin makes a great point when trying to put "fluent" APIs in a common OOP context, like that of an object browser with emphasis mine:

One of the problems of methods in a fluent interface is that they don't make much sense on their own. Looking at a method browser of method by method documentation doesn't show much sense to with. Indeed sitting there on its own I'd argue that it's a badly named method that doesn't communicate its intent at all well. It's only in the context of the fluent action that it shows its strengths. One way around this may be to use builder objects that are only used in this context. - Martin Fowler

Piers Cawley follows up and offers a number of guidelines for use when one is designing these things. See his post for the complete annotated list.

  1. Hide your working.
  2. Keep your state to yourself.
  3. Think really hard about names.
  4. Take advantage of your implementation language.
  5. If you have them, blocks are you friends.
  6. Test first design can be a useful way of exploring what your interface should be.
  7. Reasonable defaults.

In the .NET space, Ayende's Rhino Mocks are, I think, the first and best example before LINQ that really got it right with syntax like.

  Expect
.Call(mock.GetID(1))
.IgnoreArguments()
.Repeat
.Once()
.Return(something);

Similar things are done in Java with their support for mixins, called Static Imports in Java 5.

When fluent interfaces get larger and more complex, they suddenly get called Domain Specific Languages as Peirs points out. But, a true DSL is even easier and might not be fluent at all, but rather customized to the domain:

"It seems that every time someone writes a Ruby library that uses class methods, symbols and hashes reasonably sensibly they get delusions of grandeur and call the result a Domain Specific Language (or maybe an ‘embedded’ DSL)."

Two good examples of libraries as DSLs with some fluent aspects are Why's Hpricot, an HTML Parser for Ruby that looks like this:

 #!ruby
 require 'hpricot'
 require 'open-uri'
 # load the RedHanded home page
 doc = Hpricot(open("http://redhanded.hobix.com/index.html"))
 # change the CSS class on links
 (doc/"span.entryPermalink").set("class", "newLinks")
 # remove the sidebar
 (doc/"#sidebar").remove
 # print the altered HTML
 puts doc

And Python's Beautiful Soup, also an HTML Parser.

 from BeautifulSoup import BeautifulSoup, Tag
 soup = BeautifulSoup("Argh!FooBlah!")
 tag = Tag(soup, "newTag", [("id", 1)])
 tag.insert(0, "Hooray!")
 soup.a.replaceWith(tag)
 print soup
 # Argh!Hooray!Blah!

Back on the C# side, Garry Shutler is creating more fluent assertions using extension methods and lambdas for MBUnit like:

testObject.ShouldBeTheSameObjectAs(targetObject).And.ShouldBeEqualTo(testObject).And.ShouldSatisfy(x => x is Object);

But what's a DSL and what's a Fluent Interface and what's just an API? Martin adds in 2006 (as he continues to write his DSL Book):

For me, a key element is that DSLs are limited both in scope (they refer to a particular domain) and capability (they lack features that are basic for general purpose languages). As a result good DSLs are usually small and simple: hence terms like 'little languages' and 'mini-languages'.

For internal DSLs, the fuzzy boundary is what is an API and what is a DSL. Fundamentally there is no difference, an internal DSL is just an API with a fancy name (as the old Bell labs saying goes: "library design is language design"). Despite this, however, I think there is a different feel when you are working with an API that's written with a DSL feel. Things like a FluentInterface can make working with an API a qualitatively different experience. Thinking in DSL terms makes you think about readability in a different way, exploiting the syntax of the host language to create something that seems to stand on its own - rake is a great example of this. - Martin Fowler

Even scripting languages like PHP are getting on board with fluent interfaces, assuming that "with" in this context makes sense to you.

<?php
private function makeFluent(Customer $customer) {
    $customer->  newOrder()
         ->with(6, 'TAL')
         ->with(5, 'HPK')->skippable()
         ->with(3, 'LGV')
         ->priorityRush();           

Ultimately I think Paul Jones nails it when he says "Fluent Interfaces Require Fluent Situations":

"I think, for a fluent interface to be effective, you need situations where you actually have all that information at one time so that you can chain the methods in a fluid way" - Paul M. Jones

Scott Bellware said matter of factly:

"Whether fluent interface is a form of DSL or not, it's obviously a form of fluent interface." - Scott Bellware

Are you exploring Fluent Interfaces?


Shameless Plug: As an aside, one addition thing I'd like to mention is our little Forums over at http://hanselman.com/forum. They are run on excellent JitBit's AspNetForum application, the "little forum that could" in my opinion. There's lots of interesting discussions on many diverse topics, and you can look at just the most recent posts, and every page has an RSS Feed.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

February 13th - Seattle/Redmond/Bellevue Nerd Dinner

January 31, 2008 Comment on this post [19] Posted in ASP.NET | Microsoft | Musings
Sponsored By

iStock_000002684567XSmall Are you in King County/Seattle/Redmond/Bellevue Washington and surrounding areas? Are you a huge nerd? Perhaps a geek? No? Maybe a spaz, dork, dweeb or wonk. Maybe you're in town for an SDR (Software Design Review) or TechReady6. Quite possibly you're just a normal person.

Regardless, why not join us for some Mall Food at the Crossroads Bellevue Mall Food Court on Wednesday, February 13th around 6:30pm?

Here's some links to help you remember and add this to your calendar, or head over to http://nerddinner.events.live.com. There's photos of previous Nerd Dinners up on Flickr thanks to Orcmid.

Add to your calendar

I hope to see you there!

NOTE: Even though I told Live Events this was an Open To Anyone Event, it seems to want invitations. Just leave a comment here and show up on February 13th at 6:30pm!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Troubleshooting Expired ASP.NET Session State and Your Options

January 31, 2008 Comment on this post [23] Posted in ASP.NET | Bugs
Sponsored By

I have a love/hate relationship with the ASP.NET Session. It's such a convenient place to put things, but when you start putting applications into production there are a number of less-than-obvious edge cases that can come up and bite you.

Most often the Session is used when managing state over a long process like a multi-step wizard or questionnaire. However, when people use the Session, they often lean on it a little. They'll bake it into their design so deep that when it doesn't work, they're screwed. That's not to say they shouldn't be able to lean on it, I'm just saying that there's a lot of things going on with Session (not just on ASP.NET, but other frameworks as well) in order to get it to look seamless.

Built in Options

ASP.NET offers three options (four if you count rolling your own).

  • Inproc - The default, and usually works fine. However, you can get into trouble in a few scenarios.
    • Web Farms - If you have more than one web server, it's important to remember that your users may not "stick" to the same webserver with each request. Some routers offer Sticky-Sessions or the ability to "pin" a user to a server. This works well if the router uses cookies as its key, but it's less reliable if the router uses IP address/source port as the key as these may change, especially if the user is behind a mega-proxy.
    • Web Gardening - If you've setup IIS to run multiple instances of the IIS Worker Process on a single multi-proc machine, this is the equivalent of running a Web Farm, just on one machine. This technique is usually only useful when you've got a very CPU-intensive application - in other words, don't just turn on Web Gardening and expect your problems to get better instantly. It's subtle.
    • Unexpected Process Recycling - IIS6 had some wonky defaults and would recycle the AppPool or Process when some certain limits were hit, like after x number of requests or after 20 minutes. This is the classic "flaky session state is expiring" issue that lots of folks hit. You'll be more likely to see this if you've got really long running processes where users are logged in for long periods of time.
  • Out of proc - A good next step, this moves session out to a Windows Service. You can run one per Web Farm (meaning, you've got multiple machines but one instance of this service) and your session data will survive process recycles, but not system reboots. This is useful for both Web-Gardening and Web-Farming.
    • Folks usually forget to mark their objects as [Serializable] which basically gives your objects "permission" to leave their process space and be stored in memory in the State Service. If you've got a high-traffic site you might want to avoid storing complex objects and object graphs as you'll pay for it on the serialization. Of course, with all things, measure everything! You'll get best performance if you stick with basic types like strings, ints, etc.
    • UPDATE: I wanted to update this post and point folks to Maarten Balliauw's most excellent series on Out of Proc Session State (StateServer). He covers the basic setup, which is unremarkable, but then digs into the advanced stuff including "partitionResolvers" which I am ashamed to say I hadn't heard of! Recommend.
  • SQL Server - The most robust, but now you'll pay for not only serialization, but storage. However, SQL Server is a highly tuned system and if you've got a site with any significant traffic I really recommend just skipping out-of-proc and putting your session state into a SQL Server with a lot of memory. Rather than trusting ASP.NET out of proc Session State Server to be a small database, leave the database work to the databases.
    • The benefits of SQL Server for your Session State include surviving process recycles and reboots.  but more importantly using removes a lot of variables from your troubleshooting in the sense that you no longer worry about the storage of your Session, now you just need to worry if your Session Cookies are getting passed back and forth from browser to server.
    • Make sure you're using Windows Integrated Security and that you decide if you want ASP.NET to store Session in tempdb (which won't survive a SQL recycle) or a dedicated database (my recommendation).

Troubleshooting

There's a number of things that can go wrong, some of which I mention above, but here's what I usually run through when troubleshooting things.

  • Is the ASP.NET SessionID Cookie actually moving back and forth between browser and server. This can be confirmed by:
    • Using an HTTP Sniffer like ieHttpHeaders or HttpWatch or Fiddler and confirming that the Session ID cookie's value isn't changing between requests.
    • Confirming that the cookie isn't being blocked by IE, privacy settings, lack of a P3P policy document, local firewall like ZoneAlarm or Symantec, or a corporate proxy with an attitude problem.
  • Is IIS recycling  the AppPool or Worker Process? Confirm the settings in IIS manager and make sure they are right for what you're doing.
  • Is the session timing out? Are you sure you're hitting the same VDir from whence you came and successfully resetting the sliding expiration on the Session ID?
  • Is some other thing like an Ajax call or IE's Content Advisor simultaneously hitting the default page or login page and causing a race condition that calls Session.Abandon? (It's happened before!)

At my last company Session became such a hassle for large high traffic applications that we just stopped using in-proc and started exploring alternatives.

Some 3rd Party Session State Options

  • NCache from Alachisoft - An in-memory object cache that's distributed across your web farm. Think of it like Out of Process Session State, but distributed/clustered in their Enterprise Edition.
  • ScaleOut Software SessionServer - Fast, scalable in-memory storage that is distributed across machines. Full Disclosure: we worked with these guys while I was at Corillian, but never put them into production.
  • Memcached Session State Provider - Fahad has created ASP.NET Session State providers that will talk to memcached, a very popular distributed memory caching system originally created for LiveJournal.com and now used all over.

Related Links you might enjoy

How do you manage state at your company?

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook bluesky subscribe
About   Newsletter
Hosting By
Hosted on Linux using .NET in an Azure App Service

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.