Scott Hanselman

XmlSerializers Part II: Am I Insane?

December 05, 2003 Comment on this post [2] Posted in XmlSerializer | Web Services
Sponsored By

Simon Fell's comment regarding my XmlSerializer quandry got me thinking.  He said the obvious:

Only creating the first instance for a particular type is expensive after the first instance there is no overhead.

However, I SWEAR I saw different performance under 1.0.  Has something changed in 1.1?  Time to pull out a copy of .NET 1.0 and run my tests again.

Running with .NET runtime version 1.1.4322.573.
Took 00:00:00.4531163 ms to create 10000 serializers without pre-initializing.
Took 00:00:00.2499952 ms to create the first serializer.
Took 00:00:00.0312494 ms to create 10000 serializers after pre-initializing the first one.

So, perhaps my whole caching XmlSerializerFactory was sillyness, and I was trying to work around some odd behavior that existed in 1.0.  OR, some behavior that existed purely as an artifact of my previous app.

BUT: Joseph Cooney says:

The XmlSerializer has a number of constructors. If you use any of the constructors other than the one that takes a type (for example specify a type and a default namespace) then a new temporary assembly is created EVERY TIME you create a serializer, rather than only once. I can post some code to demonstrate this if you like.

Maybe that's it, and it would make sense.  The basic constructors would allow the generated type & assembly to hang out.  The others would mean that namespace passed in could come from anywhere (it could be highly variable, while the type wouldn't be)...so, they'd just punt and make a new assembly each time.

Either way, this GOOF goes to show - measure.  Don't assume like I did.  I'm off to figure this out...

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

Are XmlSerializers ThreadSafe?

December 05, 2003 Comment on this post [2] Posted in Web Services | XmlSerializer
Sponsored By

Here's the deal:

  1. It's expensive to make XmlSerializers (until .NET 2.0 when sgen.exe comes out and I can pre-created and compile Serializers.
  2. I made an XmlSerializer Factory:

    public class XmlSerializerFactory
    {
       private XmlSerializerFactory(){}
       private static Hashtable serializers = new Hashtable();
       public static XmlSerializer GetSerializer(Type t)
       {
          XmlSerializer xs =
    null;
          lock(serializers.SyncRoot)
          {
              xs = serializers[t]
    as XmlSerializer;
              if(xs == null)
              { 
                 xs =
    new XmlSerializer(t);
                 serializers.Add(t,xs);
              }
          }
          return xs;
        }
    }

  3. This Factory is thread safe (right?) BUT Are XmlSerializer instances ThreadSafe?  The MSDN Documentation gives the standard cop-out answer "They aren't explicitly Thread Safe..." (which means they weren't written to be, but also weren't written NOT to be)

So, to make sure I cover the case when someone is deserializing the same type of object using the SAME instance of a deserializer on multiple threads, I've been doing this:

XmlSerializer xs2 = XmlSerializerFactory.GetSerializer(typeof(MyNamedType));
lock(xs2)
{
   mynameInstance = (MyNamedType)xs2.Deserialize(someStringReader);
}

Is the lock{} needed? Am I being paranoid? Mr. Purdy?  Bueller?

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

Bringing data "along for the ride" with CheckBoxes and the ASP.NET DataGrid

December 04, 2003 Comment on this post [5] Posted in ASP.NET | XML
Sponsored By

Recently I needed to have a DataGrid that had multiple checkboxes to activate and deactivate something.  So, you could check a whole slew of checkboxes in a big grid, and depending on the NEW state of the checkbox (checked or not), cause an operation on a theorectical back end.

Here's some opinion/thought/zen on the DataGrid, and DataGridGirl will have to tell you if I'm wrong or not.

  • Work WITH the Grid, not against it: If you find yourself filling up the Grid via DataBinding, THEN running around in the rendered grid with foreach this and foreach that looking for HTML controls, you probably want to rethink things.  Look to the Events, my son.
  • Listen to the Events and Nudge/Influence the Grid: Between OnItemCreated and OnItemDataBound, you've got some serious influence on the grid.  If you can't get things to happen declaratively in the ItemTemplate, get them to happen Programmatically in these events.
  • Avoid Hidden Columns with IDs of things: In my case, I needed to hear when a checkbox's state changed, and at that time, I needed to know the ProductID associated with that checkbox.  Rather than wadnering around in the Control Tree (ala DataItem[x].Parent.Parent.Parent, etc.FindControl("yousuck"), just bring the data along for the ride.  See my solution below.
  • Just because code is on CodeProject or in Google Groups doesn't mean the writer knows the DataGrid from his Ass:  <rant>If I see one more solution in CodeProject or Google where someone says, "ya, just (DataTime)(((TextBox)Whatever.Item.Parent.Parent.Child[0].Parent.BrotherInLaw).Text).IntValue.ParseExact('yyyy/mm/dd')) and you're there" I will seriously hurt someone.  The DataGrid has it's faults, sure, but it's a lot more subtle that .DataBind and brute force it.  This some problem has happened with the XML DOM, and it's all the fault of QuickWatch.  "Gosh, I can SEE the data, so it must be OK for me to spelunk for it."  </rant>

I needed to know when the checkbox changed, then act on it.  So I remembered the order of events during a postback (and you should too):

  • Events fire in control tree order
  • THEN the control that CAUSED the PostBack fires it's event LAST.

So, I'd get a bunch of CheckBox_Changed events, and finally a Button_Click (from an 'Update' button).

In the Changed events I loaded a page-scoped ArrayList of things to act on, like, ProductIdsToActivateArrayList or ProductIdsToDeleteArrayList, depending on how many columns in my grid had checkboxes.  As the Changed events fire, I just wanted to load up the ProductIDs for that CheckBox's row.  But, how to avoid running around in the control tree? (which is, as I said before, gross)

I needed the data to come 'along for the ride' with the CheckBox_Changed Events.  So in the .ASPX page:

<ItemTemplate><asp:CheckBox id='checkbox' ProductId='<%#DataBinder.Eval(Container.DataItem, "ProductID")%> OnChecked='CheckBoxChanged'>

Notice that!  A totally random and unknown attribute in the CheckBox's statement.  Is that allowed? How will it render?  Well, it is allowed (although VS.NET's Designer will complain).

It renders, interestingly enough, like this:

<span ProductId="4"><input type="checkbox" id="checkbox" name="checkbox"></span>

Look at the extra span!  Crazay.  Then in the CheckBoxChanged event on the server-side after someone clicks a bunch of CheckBoxes and clicks Update:

public void CheckBoxChanged(object sender, EventArgs e)
{
     string ProductID = ((CheckBox)sender).Attributes["ProductID"]).ToString();
     ProductsToDeleteArrayList.Add(ProductID);
}

Then in the Button_Click event (remember, that happens AFTER all this) I spin through the ArrayLists (there are several, one for each action) and perform the actions in a batch.  This makes the Button_Click code CLEAN.  It makes the CheckBoxChanged code CLEAN, and it bypasses a whole lot of running around in the control tree.

Also, before I forget: Congratulations to Robert for the birth of the definitive Scrolling Data Grid.  Kudos.

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

Pentium 4s, DVD Burning, ASP.NET, and Longhorn...oy...what a day.

December 04, 2003 Comment on this post [2] Posted in ASP.NET | Web Services
Sponsored By

Been out of the loop for a few days.  It's the holiday season, and it's just hard to blog when it's so darn crappy outside. :)

Anyway, there's lots of stuff going on and I assure you I will blog the crap out of it soon.

Here's what I've been doing in the meantime, and what I think about it.

  • Longhorn.  What an install.  We all know the "10 minute hardware detection period" is really overnight, so that's OK.  I've got it on a P4 3Ghz with a Gig of RAM.  WinFS takes 170 megs of memory, and Explorer takes at least 200 megs.  I've heard people complain about this.  Geez people, it's NOT EVEN ALPHA.  It's so not Alpha, it's Zeta.  NEVER before has Microsoft given the masses such early code, so let's be happy about it. 
    • That said, when you get it installed and dig into the SDK, you see the work they've (and are) putting into it.  Very evolutionary.  Using the "stacking" features are AWESOME.  They are Outlook 2003 Search Folders on Context-Sensitive Steroids.
    • If you're interested in Longhorn: Stop by the Portland Area .NET Users Group Thursday night.  I'll be joined by Jim Blizzard and we'll be riffing on Longhorn.  I'll drag my box down there and you'll get to play with it hands on.  We'll look at the Three Pillars: Avalon, WinFS, and Indigo.  Also, Jim will be kicking off the MCSD Study Group with the arrival of the books!
  • Pentium 4.  My P4 3.2Ghz machine has been chewing inside of NeroVision Express for 8.5 hours and no end in sight.  I taught a class recently and it was taped on Hi-8.  I used my Digital-8 Camera with Firewire to 'rip' the video to my 250Gig Firewire External Drive.  Each hour is roughly 11Gigs.  Then I setup an interactive DVD Menu and I'm now transcoding the video into something I can burn to a DVD-R.  WOW. That's quite a process. 
    • The Pentium Active Monitor has been complaining as the temperature reaches in excess of 142 degrees F on the processor, and over 100 inside the case. 
    • WHY do I have to open my case (which has 4 separate fans) to recode a DVD?
  • DVD Writing.  I got the new External Firewire Sony DVD+-*.* drive that writes to every <5" disc in the world, other than 45RPM Vinyl, and it may do that soon.  The software that came with the drive sucked.  So, NERO.  Again, I say: Nero is the single greatest value in off the shelf software today.  Truly, $1000 of value for only $69.  And some places there's a $50 rebate. Oy.
  • Tablet PC. My new Toshiba M200 is NOT here yet.  Lame.  Why 'release' something when you know you only have 10 to sell?  I don't even know if it's been built.  Sigh.  Maybe before Christmas.  Anyone get yours?
  • Teaching C#The Final Approaches!  The class is stoked and so am I.  Now, do I teach next term?  Possibly a Distributed Objects or Web Services class?  Possibly Beginners Yoga.  Hm.

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

Bring out of your element breeds productivity?

November 27, 2003 Comment on this post [4] Posted in ASP.NET | XML
Sponsored By

As I look at my blog calendar (currently up and to your left) I see that I have blogged less this month and previous.  To say I have been heads down lately would be an understatement.  And let me tell you, when it rains it pours. 

Apparently I am such a complete wimp that even something as challenging as the stairs in my home have the power to crush me.  Yes, my back is out, and it happened on the 11th step.  Was I lifting something?  Something heavy?  A computer monitor?  Some new myterious hardware?  No.  Lifting my wife? Sweeping her off her feet and into the Master Bedroom.  Sadly, no.  I was holding nothing heavier than a bottle of Formula 409 to clean the can.  Long story short, this is the first day I've been able to walk without pain like you can't believe.  The prognosis?  Good.  The cause?  My sedentary lifestyle.  I am the fattest thin man you'll ever meet.  I'm like 65% fat, seriously, it's just thin and stringy.  Anyway, what doesn't kill you, makes you write more code, right?

So we've been working on this fabulous ASP.NET site for a bank that is using our glorous eFinance XML Application Server, Voyager.  We've been hitting milestones left and right, and tonight was a big one.  Over the last few months, I've been "Chief-Architecting" less, and "Programming my ass off" more.  Gotta exercise those carpal-tunnel crippled hands, right?

Anyway, I've come to this conclusion.  Working in your office is ONE kind of productive.  But, when you're in a bullpen, or more generally, when you're working ELSEWHERE, that's a different kind of productive.

If you've travelled you know this.  If you're on a plane, you can catch up on an INSANE amount of email that you'd NEVER answer in the office.  From New York to Portland can find me with 30+ emails in the outbox, tying up loose ends I'd never have otherwise. 

I work with some talented engineers at Corillian, and while there have been some great late-night coding sessions alone, there's something to be said for being shacked up in SOMEONE ELSE'S cube.  No phone, no interruptions, just pure dual-brain programming.  We got some great stuff done tonight.  I was so far out of my element that I was in the zone. 

I've decided that being off-kilter a smidge, being elsewhere, can bring on a level of creative thought that is stiffled by the home office, or the work cube.  I've gone and coded in the lobby, or in the elevator, up and down, just for a change of venue.  The results - for me - speak for themselves.

Where do you do your best work?  Home office?  Starbucks?  Always changing?  What about that/those location(s) makes your little gray cells turn better?

I've decided to stay frosty by moving around.  It makes the work fly by.

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.