I'm working on a feature for work that requires me to combine a set number of memory streams based on specific conditions.
Previous Code
Before based on documentation/examples online. In order to create a PDF to print, you have to create a Memory Stream and save that document into a Memory Stream. Here lies my old code.
PdfDocument testDocument1 = new PdfDocument(testParametersToDesignUniquePDF1);
PdfDocument testDocument2 = new PdfDocument(testParametersToDesignUniquePDF2);
PdfDocument testDocument3 = new PdfDocument(testParametersToDesignUniquePDF3);
MemoryStream testDocument1Stream = new MemoryStream();
MemoryStream testDocument2Stream = new MemoryStream();
MemoryStream testDocument3Stream = new MemoryStream();
testDocument1.Save(testDocument1Stream);
testDocument2.Save(testDocument2Stream);
testDocument3.Save(testDocument3Stream);
Stream[] source = { testDocument1, testDocument2};
if (testCondition)
{
source = { testDocument1Stream, testDocument2Stream, testDocument3Stream}
}
As you can see its only a matter of time before my code gets chunkier as for every PdfDocument, I create I have to create a new memory stream. There's also a limitation of having a static array that I have to keep initializing a new array as more condition applies. I fixed this code with the following below.
New Code
My Code Refactor is to create a dynamic List that I can add x number of streams based on x conditions. Then convert back to a static size array after I'm done. It saves a lot of extra code creating memory streams and saving my documents on it.
List<MemoryStream> memoryStreams = new List<MemoryStream>();
memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF1)));
memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF2)));
if (testCondition)
{
memoryStreams.Add(ConvertToMemoryStream(new PdfDocument(testParametersToDesignUniquePDF3)));
}
//Convert dynamic linked list back to an array of steam.
Stream[] source = memoryStreams.ToArray();
Method to convert PdfDocument to a stream.
private MemoryStream ConvertToMemoryStream(PdfDocument document)
{
MemoryStream stream = new MemoryStream();
document.Save(stream);
return stream;
}
I tested this code to have the same performance and output as the original code. However, the code has more flexibility adding more conditions and PDF's. It is also a lot more readable than the previous code. However, I am worried about a few things.
- Deallocation - I might not be taking care of disposing my streams if I manipulate it this way.
- Time of Deallocation - I'm worried that since I don't have a reference to my streams that it might get disposed on its own before actually using it when I Print the PDF's showing a blank PDF.
List<T>.ToArray()? \$\endgroup\$