Scott Hanselman

XmlFragmentWriter - Omiting the Xml Declaration and the XSD and XSI namespaces

August 4, '05 Comments [12] Posted in ASP.NET | Learning .NET | XmlSerializer
Sponsored By

There' s a pretty nasty XmlFragmentWriter example up on GDN that uses reflection to mess with the internal state of an XmlTextWriter in order to omit the XML declaration. Yikes.

This is an alternate (better) XmlFragmentWriter that's breaks fewer Commandments. It takes code from Sairama, one of our platform engineers at Corillian, to omit the XmlDecl. I took Sai's stuff and added Kzu's xsi/xsd trick to create XML fragments. Here's XmlFragmentWriter.

Given a class (just an example, don't serialize passwords!):

public class AuthenticationInfo

{

    public string Username;

    public string Password;

}

Here's the code and an instance serialized using the standard XmlSerializer. Note the Xml Declaration and the XML schema and instance namespace:

<?xml version="1.0"?>
<AuthenticationInfo
      xmlns:xsd="
http://www.w3.org/2001/XMLSchema
      xmlns:xsi="
http://www.w3.org/2001/XMLSchema-instance">
  <Username>user1</Username>
  <Password>pass1</Password>
</AuthenticationInfo>

Standard XmlSerializer fare: 

AuthenticationInfo a = new AuthenticationInfo();

a.Username = "user1";

a.Password = "pass1";

 

XmlSerializer x = new XmlSerializer( typeof(AuthenticationInfo));

XmlTextWriter w2 = new XmlTextWriter(@"c:\bar.xml",null);

w2.Formatting = Formatting.Indented;

x.Serialize( w2, a );

w2.Close();

Here's the same object serialized using our XmlFragmentWriter: 

<AuthenticationInfo>
  <Username>user1</Username>
  <Password>pass1</Password>
</AuthenticationInfo>

And here's how it's used:

AuthenticationInfo a = new AuthenticationInfo();

a.Username = "user1";

a.Password = "pass1";

 

XmlSerializer f = new XmlSerializer( typeof(AuthenticationInfo));

XmlFragmentWriter w = new XmlFragmentWriter(@"c:\foo.xml",null);

w.Formatting = Formatting.Indented;

f.Serialize( w, a );

w.Close();

And here's the XmlFragmentWriter class:

class XmlFragmentWriter : XmlTextWriter

{

    public XmlFragmentWriter(TextWriter w) : base(w){}

    public XmlFragmentWriter(Stream w, Encoding encoding) : base(w, encoding) {}

    public XmlFragmentWriter(string filename, Encoding encoding) :
        base(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None), encoding){}

 

    bool _skip = false;

 

    public override void WriteStartAttribute( string prefix, string localName, string ns )

    {

        // STEP 1 - Omits XSD and XSI declarations.

        // From Kzu - http://weblogs.asp.net/cazzu/archive/2004/01/23/62141.aspx

        if ( prefix == "xmlns" && ( localName == "xsd" || localName == "xsi" ) )  

        {

            _skip = true;

            return;

        }

        base.WriteStartAttribute( prefix, localName, ns );

    }

 

    public override void WriteString( string text )

    {

        if ( _skip ) return;

        base.WriteString( text );

    }

 

    public override void WriteEndAttribute()

    {

        if ( _skip )

        {

            // Reset the flag, so we keep writing.

            _skip = false;

            return;

        }

        base.WriteEndAttribute();

    }

 

    public override void WriteStartDocument()

    {

       // STEP 2: Do nothing so we omit the xml declaration.

    }

}

Thanks Kzu and Sairama for giving me these pieces to assemble. I tell you, System.Xml is slick slick slick. Updated with a cleaner solution.

(You can also get rid of the namespaces with another trick but it smells hacky and I don't know what the side effects would be if your document had other namespaces)

Now playing: Akon - Show 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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Visual Studio 2005 Keyboard Locks Up

August 3, '05 Comments [14] Posted in Bugs
Sponsored By

I've been using Visual Studio 2005 for the last months without many problems. Last week during the CodeCamp the keyboard totally locked up. Brad Wilson said that this was a totally known bug.

Now, suddenly I can't run Visual Studio 2005 Beta 2 for more than 30 seconds without the editor becoming completely unresponsive to the keyboard. Certainly this is a weird bug, but the weirdest thing, to me, is that it started suddenly and now the whole environment is totally unusable. I mean, I've used Beta 2 to every day since it was released and this keyboard thing JUST started.

It's totally soured me. It may be related to the AutoHide Windows. The VS Editor Blog confirms it. Madness.

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

WatirMaker Version 0.01 Source

August 3, '05 Comments [10] Posted in ASP.NET | Ruby | Watir | DasBlog
Sponsored By

Well, a few kind people offered to help test, but no one stepped up to help me fully develop WatirMaker. I'm a little surprised and slightly bummed, actually, as I thought this was an ideavirus that would generate enough enthusiasm that I could put together a team (maybe a half-dozen) and start up a SourceForce project. I'd be happy to do that, but with work for the first 12 hours of the day and life for the other 12 hours with DasBlog for the final 12 hours of the day, I can't do it by myself. :)

But, alas, nope, so here's the source to my sad little 0.01 version. It sucks and was powered by Diet Rite. Remember it's a prototype if anything. However, do please let me know if you do turn it into anything.

In the meantime, Michael Kelly and I are looking at rewriting WatirMaker entirely in Ruby, thinking that the Ruby/Watir community might dig that idea more.

File Attachment: WatirMaker.zip (62 KB)

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

The Day I Met Uhura

August 2, '05 Comments [7] Posted in Movies
Sponsored By

We've been cleaning and painting in anticipation of the baby's arrival. I found this in a pile of old photos. I'm the big-headed child on the right. That's Uhura (the actress Nichelle Nichols) on the left. My dad pulled me out of school that day to meet her at the opening of the movie. This is at the Portland, OR opening of Star Trek IV in 1986. My dad's pretty cool like that. I remember planning what I was going to say for days before and completely fuzzing out in person. She's a pretty stunning woman. Anyway, finding the picture made me smile and think of the stuff my (upcoming) son and I will do.

Uhura-with-scott

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

DasBlog 1.8 RC1

July 30, '05 Comments [21] Posted in ASP.NET | Movies | DasBlog | XML | Bugs
Sponsored By

UPDATE: Lots of testers and readers installed this RC and found some good bugs. Image uploading was slightly broken in this build, so if you haven't upgraded, hang back a bit. Remember that all bug reports should be filed on SourceForge, not sent to Omar and I directly. Feature requests should be filed also. We'll do another RC and/or possibly the 1.8 Gold Release later this week. There are also a few more features sneaking in, including 'pluggable' pings to blog sites like Technorati.

What are you doing this weekend? Why not install DasBlog 1.8 RC1? (as always back up your data!)

New Features of Note

  • Anti-Spam Features
    • Automatic Referral and Trackback blacklist update
    • CAPTCHA for non-admin users
    • Logging and display of Comment IP addresses and resolved Hostnames for Admins
    • DasBlogUpgrader can strip spam from existing content folders
    • Support for rel="nofollow"
    • Ability to delete referrals and trackbacks directly from the Admin UI
  • Security Features
    • HttpOnly cookies
    • Admin access auditing
    • SMTP Authentication for outgoing mail
  • Syndication Features
    • Improved RSS Comments support for SharpReader and RSS Bandit
    • Upgraded Atom support from 0.3 to Valid Atom 1.0. Syndication permalink changes but 301 is issued.
    • RSS 2.0 validates via FeedValidator.
    • Ability to mark entries as "syndicated" or not. Entries can appear on the site but not in RSS/Atom.
  • Performance Features
    • Search Highlighting is optional now
    • Referrals are logged but not stored in XML by default. Configurable.
      (This has huge performance benefits for high traffic sites.)
    • DasBlog Upgrader can optionally remove all referrals.
      (Again with high traffic sites some folks had 5meg XML files full of referrals)
    • Theme templates are now cached in memory.
  • Content Features
    • Ability to pre- and post-date entries
    • Permalinks based on Title and Date optional: 2005/06/06/title.aspx
    • Latest build of Free Text Box including ability to upgrade FTB without upgrading DasBlog.
    • Text Editor (FTB) supports FireFox
    • Blog Statistics macro
    • Mail-To-Weblog continues to improves. Works with Thunderbird.
  • Extensibility Features
    • Custom Macro Plugin model without recompiling DasBlog
  • Theme Features
    • DasBlog now ships with 16 themes and a Theme Combo to change between them.
    • New theme.manifest file makes themes and image assets more portable.

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 twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

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