Update: This is a confirmed bug in Silverlight 4 beta. http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=523052
I solved this issue by switching to a full blown WPF application and using regular old Microsoft.Office.Interop.Word. But I'm still very interested in how to get this to work using the dynamic values from ComAutomationFactory.
This may be more of a C# 4.0 question, but what I'm trying to do is leverage the ComAutomationFactory class in a trusted SL4 app to load up a Word doc, change some text, and print it.
Using a regular windows app, it's pretty easy:
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
Application oWord = new Application();
Document oWordDoc = new Document();
oWord.Visible = false;
object oTemplatePath = "C:\\Users\\jwest\\Desktop\\DocumentTemplate.dotx";
oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
foreach (Field myMergeField in oWordDoc.Fields)
However, in SL4 you have to use the dynamic keyword. It works fine until I try to iterate over my fields:
Object oMissing = System.Reflection.Missing.Value;
Object oTrue = true;
Object oFalse = false;
dynamic oWord = ComAutomationFactory.CreateObject("Word.Application");
oWord.Visible = false;
object oTemplatePath = "C:\\Users\\jwest\\Desktop\\DocumentTemplate.dotx";
dynamic oWordDoc = oWord.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
dynamic fields = oWordDoc.Fields;
foreach (var myMergeField in fields)
In which case I get a runtime error saying that I cannot implicitly convert a ComAutomationMetaObjectProvider to IEnumerable. No matter what I do, any properties related to my Word com object are of type ComAutomationMetaObjectProvider and I cannot iterate over them.
It has been mentioned that I should try getting the field as a String from a member.
for (int i = 0; i < oWordDoc.Fields.Count; i++)
{
String field = oWordDoc.Fields.Item[i].Result.Text;
}
This results in an interesting exception of: HRESULT: 0x800A16E6 which when Googled, brings up absolutely nothing.