April 30, 2007

Serializing a generic dictionary in .NET 2.0 using the BinaryFormatter

When using the BinaryFormatter to serialize a strongly-typed dictionary that extends System.Collections.Generic.Dictionary<>, I found out that one must add a constructor that accepts SerializationInfo and StreamingContext parameters, then just passes those on to the base class:

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MyNamespace.DataTypes {
public class MyDictionary: Dictionary {
public MyDictionary()
: base() {
public MyDictionary(SerializationInfo info, StreamingContext context)
: base(info, context) {

The error I was getting was, "System.Runtime.Serialization.SerializationException: The constructor to deserialize an object of type 'MyNamespace.DataTypes.MyDictionary' was not found."

I got the idea here: http://www.vbforums.com/showthread.php?t=314430, which has the code example in VB.NET.

To serialize Dictionary objects using an XML serializer, you have to implement a custom dictionary as described here: http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx.

Posted by Peter at 11:35 AM | Comments (2)

September 19, 2006

MS Word - VBA - StoryRanges - Odd-page headers

Daily trivia:
Document.StoryRanges does not explicitly return odd-page headers/footers. Instead, they're linked from the even-page ones. One has to use Range.NextStoryRange on the even-page headers/footers to get the odd-page ones.

Because example code is always nice, here's my function to grab _all_ of the ranges in a document, updated with this knowledge:

' Builds a collection of all the ranges in this document.
' (StoryRanges, which include the headers and footers, augmented with any text box ranges)
' also include linked ranges via NextStoryRange to grab the odd page header/footers
Private Function AllRanges(Optional Doc As Document) As Collection
Dim Rng As Range
Dim Sh As Shape
Set AllRanges = New Collection
If Doc Is Nothing Then Set Doc = ActiveDocument
For Each Rng In Doc.StoryRanges
While Not Rng Is Nothing
AllRanges.Add Rng
Set Rng = Rng.NextStoryRange
Next Rng
' Grab all of the text boxes in the document, too.
' Use .ContainingRange to return the entire story that flows between linked text frames,
' but examine .Previous to make sure I grab it only once - from the first box in the chain.
For Each Sh In Doc.Shapes
With Sh.TextFrame
If .HasText And .Previous Is Nothing Then AllRanges.Add .ContainingRange
End With
Next Sh
End Function

Posted by Peter at 02:08 PM | Comments (0)