During the development of Package Explorer I have collected quite some experience in building an object model around the Packaging API. Up until now the object model around the Packaging API abstracted internal and external parts and provided a typed collection to access child parts instead of requiring the caller to use the relationships directly. The model was not up to one task that I am now building into the next version, adding and removing parts.
Downside to this is that the entire object model needed refactoring since removing parts is not an easy task. This is also the reason why I created this post. The object model now shields you from the difficulties of removing parts. Why is this difficult? The part you remove might still be referenced by other parts. The Packaging API only stores information about child parts. It does not maintain a list of parent parts, so that's something you need to build yourself.
The features of the sample object model:
- Load document
- Browse parts in a hierarchical model
- Create new parts
- Create relationships
- Remove relationships
- Delete parts
I can go into the code, but perhaps it is just as interesting to see how it is used.
using (Document document = new
Document(@"New.docx"))
{
// Create 3 parts
InternalDocumentPart part =
document.CreatePart("/test/t1.xml", CT_MainDoc);
InternalDocumentPart part2 =
document.CreatePart("/test/t2.xml", CT_Settings);
InternalDocumentPart part3 =
document.CreatePart("/test/t3.xml", CT_Other);
// Relate them, create circular relationship
// doc -> 1 -> 2 -> 3
document.MainParts.Add(part, RT_Doc);
part.ChildParts.Add(part2, RT_Settings);
part2.ChildParts.Add(part3, RT_Something);
// Relate some more
// doc -> 3
document.MainParts.Add(part3, RT_Doc);
// Delete some relationships
document.MainParts.Remove(part3);
part2.ChildParts.Remove(part3);
if (part3.HasParentRelationships == false)
{
document.DeletePart(part3);
}
// Remove relationship between doc and 1
document.MainParts.Remove(part);
// Create external part from 1 to web
ExternalDocumentPart externalPart =
part.CreateExternalPart(new
Uri("http://blah"), RT_Doc);
// Delete it again
part.ChildParts.Remove(externalPart);
// Done
document.Save();
}
Posted
10-05-2007 11:06
by
Anonymous