Question

I am trying to save some c# source code into the database. Basically I have a RichTextBox that users can type their code and save that to the database.

When I copy and paste from the visual studio environment, I would like to preserve the formating etc. So I have chosen to save the FlowDocuments Xaml to the database and set this back to the RichTextBox.Document.

My below two function serialise and deserialise the RTB's contents.

     private string GetXaml(FlowDocument document)
    {
        if (document == null) return String.Empty;
        else{
            StringBuilder sb = new StringBuilder();
            XmlWriter xw = XmlWriter.Create(sb);
            XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw);
            sm.XamlWriterMode = XamlWriterMode.Expression;                

            XamlWriter.Save(document, sm );
            return sb.ToString();
        }
    }

    private FlowDocument GetFlowDocument(string xamlText)
    {
        var flowDocument = new FlowDocument();
        if (xamlText != null) flowDocument = (FlowDocument)XamlReader.Parse(xamlText);
        // Set return value
        return flowDocument;
    }

However when I try to serialise and deserialise the following code, I am noticing this incorrect(?) behaviour

using System;
public class TestCSScript : MarshalByRefObject
{

}

Serialised XAML is

using System; public class TestCSScript : MarshalByRefObject {}{ }

Notice the the new set of "{}"

What am I doing wrong here... Thanks in advance for the help!

Was it helpful?

Solution

I have resigned to a tardy solution for now, but if any of you finds a clean one, please post it.

I have used a Replace call of Stringbuilder to remove the undesired characters.

    private string GetXaml(FlowDocument document)
    {
        if (document == null) return String.Empty;
        else
        {

            StringBuilder sb = new StringBuilder();
            using (XmlWriter xw = XmlWriter.Create(sb))
            {
                XamlDesignerSerializationManager sm = new XamlDesignerSerializationManager(xw);
                sm.XamlWriterMode = XamlWriterMode.Expression;

                XamlWriter.Save(document, sm);
            }
            sb.Replace("{}", "");
            return sb.ToString();
        }

    }

I have a feeling that when the xamlwriter encounters "{" character - it intreprets that as a binding expression. I wonder what the escape sequence is for this character.

Note - I tried changing the

XamlWriterMode from XamlWriterMode.Expression to XamlWriterMode.Value

with no joy.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top