Пример #1
57
 public static string SerializeToXaml(object objectToSerialize, bool fullyQualifiedClrNamespaces = true)
 {
     var stringWriter = new StringWriter();
     var xamlSchemaContextCWithFullyQualifiedNameSupport =
         new XamlSchemaContext(new XamlSchemaContextSettings { FullyQualifyAssemblyNamesInClrNamespaces = fullyQualifiedClrNamespaces });
     using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }))
     using (var xamlWriter = new XamlXmlWriter(xmlWriter, xamlSchemaContextCWithFullyQualifiedNameSupport))
     using (var builderWriter = ActivityXamlServices.CreateBuilderWriter(xamlWriter)) // transform to x:Class representation
     using (var objectReader = new XamlObjectReader(objectToSerialize, xamlSchemaContextCWithFullyQualifiedNameSupport))
     {
         XamlServices.Transform(objectReader, builderWriter);
         return stringWriter.ToString();
     }
 }
Пример #2
1
        public static XElement TranslateString(string xamlFile)
        {
            string translatedWorkflowString = null;


            using (XamlReader xamlReader = new XamlXmlReader(
               new StringReader(xamlFile)))
            {
                TranslationResults result = ExpressionTranslator.Translate(xamlReader);
                if (result.Errors.Count == 0)
                {
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }))
                    {
                        using (XamlXmlWriter writer = new XamlXmlWriter(xmlWriter, result.Output.SchemaContext))
                        {
                            XamlServices.Transform(result.Output, writer);
                        }
                    }
                    translatedWorkflowString = sb.ToString();
                }
                else
                {
                    string error = "Translation errors";

                    for (int i = 0; i < result.Errors.Count; i++ )
                    {
                        error = error + " :::: [A:" + result.Errors[i].ActivityId + ", Line" + result.Errors[i].StartLine +"] \"" + result.Errors[i].ExpressionText + "\" (" + result.Errors[i].Message + ")";
                    }
                        throw new InvalidOperationException(error);
                }
            }

            return XElement.Parse(translatedWorkflowString);
        }
Пример #3
0
        public void EscapeCurlies()
        {
            var generated   = new StringBuilder();
            var xmlSettings = new XmlWriterSettings {
                Indent = true, OmitXmlDeclaration = true
            };
            var xamlSettings = new XamlXmlWriterSettings {
                CloseOutput = true
            };
            var xsc = new XamlSchemaContext();

            using (System.Xaml.XamlXmlWriter writer = new System.Xaml.XamlXmlWriter(XmlWriter.Create(new StringWriter(generated), xmlSettings), xsc, xamlSettings))
            {
                var developerType          = xsc.GetXamlType(typeof(Developer));
                var developerExtensionType = xsc.GetXamlType(typeof(DeveloperExtension));
                writer.WriteNamespace(new NamespaceDeclaration(XamlLanguage.Xaml2006Namespace, "x"));
                writer.WriteStartObject(developerType);
                writer.WriteStartMember(developerType.GetMember("Name"));
                writer.WriteValue("{Andrew}");
                writer.WriteEndMember();
            }
            string target = @"<Developer Name=""{}{Andrew}"" xmlns=""clr-namespace:Test.Elements;assembly=XamlTestClasses"" />";

            Assert.AreEqual(target, generated.ToString());
        }
Пример #4
0
        static void Main(string[] args)
        {
            if (2 != args.Length)
            {
                Console.WriteLine("Usage -- ViewStateCleaningWriter <infile> <outfile>");
                return;
            }
            try
            {
                XmlReader xmlReader = XmlReader.Create(args[0]);
                XamlXmlReader xamlReader = new XamlXmlReader(xmlReader);
                ActivityBuilder ab = XamlServices.Load(ActivityXamlServices.CreateBuilderReader(xamlReader)) as ActivityBuilder;

                XmlWriterSettings writerSettings = new XmlWriterSettings {  Indent = true };
                XmlWriter xmlWriter = XmlWriter.Create(File.OpenWrite(args[1]), writerSettings);
                XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
                XamlServices.Save(new ViewStateCleaningWriter(ActivityXamlServices.CreateBuilderWriter(xamlWriter)), ab);

                Console.WriteLine("{0} written without viewstate information", args[1]);

            }
            catch (Exception ex)
            {

                Console.WriteLine("Exception encountered {0}", ex);
            }
        }
Пример #5
0
        public static XElement Translate(string xamlFile)
        {
            string translatedWorkflowString = null;

            using (XamlReader xamlReader = new XamlXmlReader(xamlFile))
            {
                TranslationResults result = ExpressionTranslator.Translate(xamlReader);
                if (result.Errors.Count == 0)
                {
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter xmlWriter = XmlWriter.Create(sb, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }))
                    {
                        using (XamlXmlWriter writer = new XamlXmlWriter(xmlWriter, result.Output.SchemaContext))
                        {
                            XamlServices.Transform(result.Output, writer);
                        }
                    }
                    translatedWorkflowString = sb.ToString();
                }
                else
                {
                    throw new InvalidOperationException("Translation errors");
                }
            }

            return XElement.Parse(translatedWorkflowString);
        }
Пример #6
0
        public static string GetDefinition(this Activity activity)
        {
            StringWriter writer = new StringWriter();
            XamlXmlWriter xamlWriter = new XamlXmlWriter(writer, new XamlSchemaContext());
            XamlServices.Save(xamlWriter, activity);

            return writer.ToString();
        }
 private void Initialize(XamlXmlWriter xamlXmlWriter)
 {
     this.xamlXmlWriter = xamlXmlWriter;
     this.settings      = xamlXmlWriter.Settings;
     this.meSettings    = this.meSettings ?? new XamlMarkupExtensionWriterSettings();
     this.currentState  = Start.State;
     this.sb            = new StringBuilder();
     this.nodes         = new Stack <Node>();
     this.failed        = false;
 }
Пример #8
0
 void Initialize(XamlXmlWriter xamlXmlWriter)
 {
     this.xamlXmlWriter = xamlXmlWriter;
     this.settings      = xamlXmlWriter.Settings; // This will clone, only want to do this once
     this.meSettings    = this.meSettings ?? new XamlMarkupExtensionWriterSettings();
     currentState       = Start.State;
     sb     = new StringBuilder();
     nodes  = new Stack <Node>();
     failed = false;
 }
 private void Initialize(XamlXmlWriter xamlXmlWriter)
 {
     this.xamlXmlWriter = xamlXmlWriter;
     this.settings = xamlXmlWriter.Settings;
     this.meSettings = this.meSettings ?? new XamlMarkupExtensionWriterSettings();
     this.currentState = Start.State;
     this.sb = new StringBuilder();
     this.nodes = new Stack<Node>();
     this.failed = false;
 }
Пример #10
0
 public static void Save(XmlWriter writer, object instance)
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     using (XamlXmlWriter writer2 = new XamlXmlWriter(writer, new XamlSchemaContext()))
     {
         Save(writer2, instance);
     }
 }
Пример #11
0
        public static Activity Clone(this Activity activity)
        {
            StringWriter writer = new StringWriter();
            XamlXmlWriter xamlWriter = new XamlXmlWriter(writer, new XamlSchemaContext());
            XamlServices.Save(xamlWriter, activity);

            StringReader reader = new StringReader(writer.ToString());
            XamlXmlReader xamlReader = new XamlXmlReader(reader);

            return XamlServices.Load(xamlReader) as Activity;
        }
        private static string CreateXamlString(XamlReader reader)
        {
            var stringBuilder = new StringBuilder();
            var xmlWriterSettings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };

            using (var xmlWriter = XmlWriter.Create(stringBuilder, xmlWriterSettings))
            using (var writer = new XamlXmlWriter(xmlWriter, reader.SchemaContext))
                XamlServices.Transform(reader, writer);

            return stringBuilder.ToString();
        }
Пример #13
0
 public static void Save(XamlDomObject rootObjectNode, string fileName)
 {
     var schemaContext = rootObjectNode.Type.SchemaContext;
     var dr = new XamlDomReader(rootObjectNode, schemaContext);
     var xws = new XmlWriterSettings();
     xws.Indent = true;
     using (var xw = XmlWriter.Create(fileName, xws))
     {
         var xxw = new XamlXmlWriter(xw, schemaContext);
         XamlServices.Transform(dr, xxw);
     }
 }
Пример #14
0
 public static String Save(IWorkflow workflow)
 {
     var output = new StringWriter();
     using (var writer = XmlWriter.Create(output, new XmlWriterSettings { Indent = true }))
     {
         var xamlSchemaContext = new CustomXamlSchemaContext();
         using (var xamlWriter = new XamlXmlWriter(writer, xamlSchemaContext))
         {
             XamlServices.Save(xamlWriter, workflow);
         }
     }
     return output.ToString();
 }
Пример #15
0
 public TemplateContent(XamlReader xamlReader)
 {
     if (xamlReader == null)
         throw new ArgumentNullException("xamlReader");
     _SchemaContext = xamlReader.SchemaContext;
     _Cache = new MemoryStream();
     XamlXmlWriter writer = new XamlXmlWriter(_Cache, xamlReader.SchemaContext);
     //writer.WriteNamespace(xamlReader.Namespace);
     while (xamlReader.Read())
     {
         writer.WriteNode(xamlReader);
     }
     writer.Close();
 }
Пример #16
0
            public override void WriteStartObject(XamlMarkupExtensionWriter writer, XamlType type)
            {
                writer.Reset();

                string prefix = writer.LookupPrefix(type);

                writer.sb.Append("{");
                WritePrefix(writer, prefix);
                writer.sb.Append(XamlXmlWriter.GetTypeName(type));

                writer.nodes.Push(new Node {
                    NodeType = XamlNodeType.StartObject, XamlType = type
                });
                writer.currentState = InObjectBeforeMember.State;
            }
        public MainWindow()
        {
            InitializeComponent();

            using (var reader = new XamlXmlReader("./Button.xaml"))
            using (var writer = new XamlXmlWriter(new FileStream("./Test.xaml", FileMode.Create), reader.SchemaContext))
            {
                while (reader.Read())
                {
                    writer.WriteNode(reader);
                }
            }

            using (var reader = new XamlObjectReader(new Button()))
            using (var writer = new XamlObjectWriter(reader.SchemaContext))
            {
                while (reader.Read())
                {
                    writer.WriteNode(reader);
                }

                var button = (Button)writer.Result;
            }

            using (var reader = new XamlXmlReader(new StringReader("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>")))
            using (var writer = new XamlObjectWriter(reader.SchemaContext))
            {
                while (reader.Read())
                {
                    writer.WriteNode(reader);
                }

                var button = (Button)writer.Result;
            }

            var button1 = (Button)XamlServices.Load("./Button.xaml");
            var button2 = XamlServices.Load(new XamlObjectReader(new Button()));
            var button3 = XamlServices.Load(new StringReader("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>"));
            var button4 = XamlServices.Parse("<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">This is a button</Button>");
            XamlServices.Save("./Test2.xaml", new Button());

            //DispatcherObject methods, hidden from intellisense via the EditorBrowsableAttribute
            button1.CheckAccess();
            button1.VerifyAccess();
        }
Пример #18
0
        public void AttachedPropertyTest()
        {
            var generated   = new StringBuilder();
            var xmlSettings = new XmlWriterSettings {
                Indent = true, OmitXmlDeclaration = true
            };
            var xamlSettings = new XamlXmlWriterSettings {
                CloseOutput = true
            };
            var xsc = new XamlSchemaContext();

            using (System.Xaml.XamlXmlWriter writer = new System.Xaml.XamlXmlWriter(XmlWriter.Create(new StringWriter(generated), xmlSettings), xsc, xamlSettings))
            {
                XamlType   mc                     = xsc.GetXamlType(typeof(MediumContainer));
                XamlMember thing                  = mc.GetAttachableMember("Thing");
                var        developerType          = xsc.GetXamlType(typeof(Developer));
                var        developerExtensionType = xsc.GetXamlType(typeof(DeveloperExtension));
                string     ns                     = "clr-namespace:Test.Elements.AnotherNamespace;assembly=XamlTestClasses";
                writer.WriteNamespace(new NamespaceDeclaration(ns, "PreferredPrefix"));
                writer.WriteStartObject(developerType);
                writer.WriteStartMember(developerType.GetMember("Name"));
                writer.WriteValue("Andrew");
                writer.WriteEndMember();

                writer.WriteStartMember(developerType.GetMember("Friend"));
                writer.WriteStartObject(developerExtensionType);
                writer.WriteStartMember(developerExtensionType.GetMember("Name"));
                writer.WriteValue("");
                writer.WriteEndMember();
                writer.WriteEndObject();
                writer.WriteEndMember();

                writer.WriteStartMember(thing);
                writer.WriteValue("attached");
                writer.WriteEndMember();

                writer.WriteEndObject();
            }

            var target = @"<Developer Name=""Andrew"" Friend=""{Developer Name=&quot;&quot;}"" PreferredPrefix:MediumContainer.Thing=""attached"" xmlns=""clr-namespace:Test.Elements;assembly=XamlTestClasses"" xmlns:PreferredPrefix=""clr-namespace:Test.Elements.AnotherNamespace;assembly=XamlTestClasses"" />";

            Assert.AreEqual(target, generated.ToString());
        }
Пример #19
0
            public override void WriteStartObject(XamlMarkupExtensionWriter writer, XamlType type)
            {
                if (!type.IsMarkupExtension)
                {
                    // can not write a non-ME object in this state in curly form
                    writer.failed = true;
                    return;
                }
                string prefix = writer.LookupPrefix(type);

                writer.sb.Append("{");
                WritePrefix(writer, prefix);
                writer.sb.Append(XamlXmlWriter.GetTypeName(type));

                writer.nodes.Push(new Node {
                    NodeType = XamlNodeType.StartObject, XamlType = type
                });
                writer.currentState = InObjectBeforeMember.State;
            }
Пример #20
0
        public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile)
        {
            bamlCode.Position = 0;
            TextWriter w = new StringWriter();

            Assembly assembly = Assembly.LoadFile(containingAssemblyFile);

            Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly });
            XamlXmlWriter writer = new XamlXmlWriter(new XmlTextWriter(w) { Formatting = Formatting.Indented }, reader.SchemaContext);
            while (reader.Read()) {
                switch (reader.NodeType) {
                    case XamlNodeType.None:

                        break;
                    case XamlNodeType.StartObject:
                        writer.WriteStartObject(reader.Type);
                        break;
                    case XamlNodeType.GetObject:
                        writer.WriteGetObject();
                        break;
                    case XamlNodeType.EndObject:
                        writer.WriteEndObject();
                        break;
                    case XamlNodeType.StartMember:
                        writer.WriteStartMember(reader.Member);
                        break;
                    case XamlNodeType.EndMember:
                        writer.WriteEndMember();
                        break;
                    case XamlNodeType.Value:
                        // requires XamlReaderSettings.ValuesMustBeString = true to work properly
                        writer.WriteValue(reader.Value);
                        break;
                    case XamlNodeType.NamespaceDeclaration:
                        writer.WriteNamespace(reader.Namespace);
                        break;
                    default:
                        throw new Exception("Invalid value for XamlNodeType");
                }
            }
            return w.ToString();
        }
 public override void WriteStartObject(XamlMarkupExtensionWriter writer, XamlType type)
 {
     if (!type.IsMarkupExtension)
     {
         writer.failed = true;
     }
     else
     {
         string prefix = writer.LookupPrefix(type);
         writer.sb.Append("{");
         base.WritePrefix(writer, prefix);
         writer.sb.Append(XamlXmlWriter.GetTypeName(type));
         XamlMarkupExtensionWriter.Node item = new XamlMarkupExtensionWriter.Node {
             NodeType = XamlNodeType.StartObject,
             XamlType = type
         };
         writer.nodes.Push(item);
         writer.currentState = XamlMarkupExtensionWriter.InObjectBeforeMember.State;
     }
 }
Пример #22
0
        }//end

        //从[xaml]字串得到[ActivityBuilder]对象
        public static string xamlFromActivityBuilder(ActivityBuilder activityBuilder)
        {
            string xamlString = "";

            StringBuilder stringBuilder = new StringBuilder();

            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);

            System.Xaml.XamlSchemaContext xamlSchemaContext = new System.Xaml.XamlSchemaContext();

            System.Xaml.XamlXmlWriter xamlXmlWriter = new System.Xaml.XamlXmlWriter(stringWriter, xamlSchemaContext);


            System.Xaml.XamlWriter xamlWriter = System.Activities.XamlIntegration.ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);

            System.Xaml.XamlServices.Save(xamlWriter, activityBuilder);

            xamlString = stringBuilder.ToString();

            return(xamlString);
        }
Пример #23
0
        private void OnLoadXaml(object sender, RoutedEventArgs e)
        {
            Person p1 = new Person { FirstName = "Stephanie", LastName = "Nagel" };
            string s = XamlServices.Save(p1);
            XamlServices.Save("person.xaml", p1);

            var writer = new XamlObjectWriter(new XamlSchemaContext());
            FileStream fStream = File.OpenRead("LoadXAML.exe");
            var bamlReader = new Baml2006Reader(fStream, new XamlReaderSettings { LocalAssembly = Assembly.GetExecutingAssembly() });

            // Baml2006Reader bamlReader = new Baml2006Reader("../../../XAMLIntro/bin/debug/XAMLIntro.exe");
            FileStream stream = File.Create("myfile.xaml");
            XamlSchemaContext schemaContext = new XamlSchemaContext(
                    new XamlSchemaContextSettings
                    {
                        FullyQualifyAssemblyNamesInClrNamespaces = true,
                        SupportMarkupExtensionsWithDuplicateArity = true
                    });
            XamlXmlWriter xmlWriter = new XamlXmlWriter(stream, schemaContext);
            XamlServices.Transform(bamlReader, xmlWriter, true);

            XamlServices.Transform(new XamlXmlReader("person.xaml"), writer, true);
            // string s2 = XamlServices.Save(this);

            //OpenFileDialog dlg = new OpenFileDialog();
            //if (dlg.ShowDialog() == true)
            //{
            //    object xaml = XamlServices.Load(dlg.FileName);
            //    XamlSchemaContext schema = new XamlSchemaContext(
            //        new XamlSchemaContextSettings
            //        {
            //            FullyQualifyAssemblyNamesInClrNamespaces = true,
            //            SupportMarkupExtensionsWithDuplicateArity = true
            //        });
            //    XamlWriter writer = new XamlXmlWriter(stream, schema);
            //    XamlServices.Save(
        }
Пример #24
0
        public void EmptyStringTest()
        {
            var generated   = new StringBuilder();
            var xmlSettings = new XmlWriterSettings {
                Indent = true, OmitXmlDeclaration = true
            };
            var xamlSettings = new XamlXmlWriterSettings {
                CloseOutput = true
            };
            var xsc = new XamlSchemaContext();

            using (System.Xaml.XamlXmlWriter writer = new System.Xaml.XamlXmlWriter(XmlWriter.Create(new StringWriter(generated), xmlSettings), xsc, xamlSettings))
            {
                var developerType          = xsc.GetXamlType(typeof(Developer));
                var developerExtensionType = xsc.GetXamlType(typeof(DeveloperExtension));
                writer.WriteNamespace(new NamespaceDeclaration(XamlLanguage.Xaml2006Namespace, "x"));
                writer.WriteStartObject(developerType);
                writer.WriteStartMember(developerType.GetMember("Name"));
                writer.WriteValue("Andrew");
                writer.WriteEndMember();

                writer.WriteStartMember(developerType.GetMember("Friend"));
                writer.WriteStartObject(developerExtensionType);
                writer.WriteStartMember(developerExtensionType.GetMember("Name"));
                writer.WriteValue("");
                writer.WriteEndMember();
                writer.WriteEndObject();
                writer.WriteEndMember();

                writer.WriteEndObject();
            }

            var target = @"<Developer Name=""Andrew"" Friend=""{Developer Name=&quot;&quot;}"" xmlns=""clr-namespace:Test.Elements;assembly=XamlTestClasses"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" />";

            Assert.AreEqual(target, generated.ToString());
        }
Пример #25
0
        public static string GetXamlString(ActivityBuilder activityBuilder)
        {
            var stringBuilder = new StringBuilder();
            var stringWriter = new StringWriter(stringBuilder);
            var xamlSchemaContext = new XamlSchemaContext();
            var xamXmlWriter = new XamlXmlWriter(stringWriter, xamlSchemaContext);
            var xamlWriter = System.Activities.XamlIntegration.ActivityXamlServices.CreateBuilderWriter(xamXmlWriter);

            XamlServices.Save(xamlWriter, activityBuilder);

            return stringBuilder.ToString();
        }
 public static void Save(XmlWriter writer, object instance)
 {
     if (writer == null)
     {
         throw new ArgumentNullException("writer");
     }
     using (XamlXmlWriter writer2 = new XamlXmlWriter(writer, new XamlSchemaContext()))
     {
         Save(writer2, instance);
     }
 }
 public XamlMarkupExtensionWriter(XamlXmlWriter xamlXmlWriter, XamlMarkupExtensionWriterSettings meSettings)
 {
     this.meSettings = meSettings;
     this.Initialize(xamlXmlWriter);
 }
 public XamlMarkupExtensionWriter(XamlXmlWriter xamlXmlWriter)
 {
     this.Initialize(xamlXmlWriter);
 }
        bool ProcessMarkupItem(ITaskItem markupItem, CodeDomProvider codeDomProvider)
        {
            string markupItemFileName = markupItem.ItemSpec;
            XamlBuildTaskServices.PopulateModifiers(codeDomProvider);

            XamlNodeList xamlNodes = ReadXamlNodes(markupItemFileName);
            if (xamlNodes == null)
            {
                return false;
            }

            ClassData classData = ReadClassData(xamlNodes, markupItemFileName);

            string outputFileName = GetFileName(markupItemFileName);
            string codeFileName = Path.ChangeExtension(outputFileName, GetGeneratedSourceExtension(codeDomProvider));
            string markupFileName = Path.ChangeExtension(outputFileName, GeneratedSourceExtension + XamlBuildTaskServices.XamlExtension);
            classData.EmbeddedResourceFileName = Path.GetFileName(markupFileName);
            classData.HelperClassFullName = this.HelperClassFullName;

            // Check if code file with partial class exists
            classData.SourceFileExists = UserProvidedFileExists(markupItemFileName, codeDomProvider);

            // Store the full type name as metadata on the markup item
            string rootNamespacePrefix = null;
            string namespacePrefix = null;
            string typeFullName = null;
            if (this.Language.Equals("VB") && !String.IsNullOrWhiteSpace(classData.RootNamespace))
            {
                rootNamespacePrefix = classData.RootNamespace + ".";
            }

            if (!String.IsNullOrWhiteSpace(classData.Namespace))
            {
                namespacePrefix = classData.Namespace + ".";
            }

            if (rootNamespacePrefix != null)
            {
                if (namespacePrefix != null)
                {
                    typeFullName = rootNamespacePrefix + namespacePrefix + classData.Name;
                }
                else
                {
                    typeFullName = rootNamespacePrefix + classData.Name;
                }
            }
            else
            {
                if (namespacePrefix != null)
                {
                    typeFullName = namespacePrefix + classData.Name;
                }
                else
                {
                    typeFullName = classData.Name;
                }
            }

            markupItem.SetMetadata("typeName", typeFullName);

            // Execute extensions here to give them a chance to mutate the ClassData before we generate code.
            if (this.SupportExtensions)
            {
                if (!ExecuteExtensions(classData, markupItem))
                {
                    return false;
                }
            }

            // Generate code file
            CodeCompileUnit codeUnit = new ClassGenerator(this.BuildLogger, codeDomProvider, this.Language).Generate(classData);         
            WriteCode(codeDomProvider, codeUnit, codeFileName);
            this.GeneratedCodeFiles.Add(codeFileName);

            // Generate resource file
            if (!string.IsNullOrEmpty(this.AssemblyName))
            {
                // Generate xaml "implementation" file
                XmlWriterSettings xmlSettings = new XmlWriterSettings { Indent = true, IndentChars = "  ", CloseOutput = true };
                using (XmlWriter xmlWriter = XmlWriter.Create(File.Open(markupFileName, FileMode.Create), xmlSettings))
                {
                    XamlXmlWriterSettings xamlSettings = new XamlXmlWriterSettings() { CloseOutput = true };
                    
                    // Process EmbeddedResourceXaml to remove xml:space="preserve"
                    // due to a 




                    RemoveXamlSpaceAttribute(classData);

                    using (XamlReader reader = classData.EmbeddedResourceXaml.GetReader())
                    {
                        using (XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, reader.SchemaContext, xamlSettings))
                        {
                            XamlServices.Transform(reader, xamlWriter);                                                     
                        }
                    }
                }
                this.GeneratedResources.Add(markupFileName);
            }

            if (classData.RequiresCompilationPass2)
            {
                this.RequiresCompilationPass2 = true;
            }
            else
            {
                if (!this.SupportExtensions)
                {
                    if (!ValidateXaml(xamlNodes, markupItemFileName))
                    {
                        this.RequiresCompilationPass2 = true;
                    }
                }
                else
                {
                    // skip validation if we are doing in-proc compile
                    // OR if we have pass 2 extensions hooked up 
                    // as we anyway need to run pass 2 in that case
                    if (!this.IsInProcessXamlMarkupCompile && !this.MarkupCompilePass2ExtensionsPresent)
                    {
                        if (!ValidateXaml(xamlNodes, markupItemFileName))
                        {
                            this.RequiresCompilationPass2 = true;
                        }
                    }
                }
            }
            return true;
        }
Пример #30
0
 public XamlMarkupExtensionWriter(XamlXmlWriter xamlXmlWriter, XamlMarkupExtensionWriterSettings meSettings)
 {
     this.meSettings = meSettings;
     Initialize(xamlXmlWriter);
 }
Пример #31
0
 public XamlMarkupExtensionWriter(XamlXmlWriter xamlXmlWriter)
 {
     Initialize(xamlXmlWriter);
 }
Пример #32
0
		public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile, ConnectMethodDecompiler connectMethodDecompiler, AssemblyResolver asmResolver)
		{
			this.asmResolver = asmResolver;
			AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve;
			
			bamlCode.Position = 0;
			TextWriter w = new StringWriter();
			
			Assembly assembly = Assembly.LoadFile(containingAssemblyFile);
			
			Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly });
			var xamlDocument = Parse(reader);
			
			string bamlTypeName = xamlDocument.OfType<XamlObjectNode>().First().Type.UnderlyingType.FullName;
			
			var eventMappings = connectMethodDecompiler.DecompileEventMappings(bamlTypeName);

			foreach (var xamlNode in xamlDocument) {
				RemoveConnectionIds(xamlNode, eventMappings, reader.SchemaContext);
				AvoidContentProperties(xamlNode);
				MoveXKeyToFront(xamlNode);
			}
			
			XDocument doc = new XDocument();
			XamlXmlWriter writer = new XamlXmlWriter(doc.CreateWriter(), reader.SchemaContext, new XamlXmlWriterSettings { AssumeValidInput = true });
			foreach (var xamlNode in xamlDocument)
				xamlNode.WriteTo(writer);
			writer.Close();
			
			// Fix namespace references
			string suffixToRemove = ";assembly=" + assembly.GetName().Name;
			foreach (XAttribute attrib in doc.Root.Attributes()) {
				if (attrib.Name.Namespace == XNamespace.Xmlns) {
					if (attrib.Value.EndsWith(suffixToRemove, StringComparison.Ordinal)) {
						string newNamespace = attrib.Value.Substring(0, attrib.Value.Length - suffixToRemove.Length);
						ChangeXmlNamespace(doc, attrib.Value, newNamespace);
						attrib.Value = newNamespace;
					}
				}
			}

			return doc.ToString();
		}
 public void SaveActivityBuilder(ActivityBuilder builder, string path)
 {
     var actualpath = System.IO.Path.GetDirectoryName(path) + "\\wfReadytoUpdate.xaml";
     txtWorkflowSnapshot.Text = actualpath;
     using (var writer = File.CreateText(actualpath))
     {
         var xmlWriter = new XamlXmlWriter(writer, new XamlSchemaContext());
         using (var xamlWriter = ActivityXamlServices.CreateBuilderWriter(xmlWriter))
         {
             XamlServices.Save(xamlWriter, builder);
         }
     }
 }
        /// <summary>
        /// Save the activity template into its XAML representation.
        /// </summary>
        /// <param name="activityTemplate">The activity template to be saved.</param>
        /// <returns>The XAML representation of the activity template.</returns>
        public static string SaveActivityTemplate(ActivityTemplateFactoryBuilder activityTemplate)
        {
            XamlSchemaContext xsc = new XamlSchemaContext();
            using (XamlReader reader = new XamlObjectReader(activityTemplate, xsc))
            {
                using (StringWriter textWriter = new StringWriter(CultureInfo.InvariantCulture))
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, new XmlWriterSettings { Indent = true }))
                    {
                        using (XamlWriter xamlWriter = new XamlXmlWriter(xmlWriter, xsc))
                        {
                            using (ActivityTemplateFactoryBuilderWriter builderWriter = new ActivityTemplateFactoryBuilderWriter(xamlWriter, xsc))
                            {
                                XamlServices.Transform(reader, builderWriter);
                            }
                        }
                    }

                    return textWriter.ToString();
                }
            }
        }
Пример #35
0
        private static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: Xib2Xaml XibFile");
                return;
            }

            if (args.Length == 3)
            {
                XamlXibReader.WIDTH = int.Parse(args[1]);
                XamlXibReader.HEIGHT = int.Parse(args[2]);
            }

            using (var xamlReader = new XamlXibReader(args[0]))
            using (var xmlWriter = XmlWriter.Create(args[0].Replace(".xib", ".xaml"), new XmlWriterSettings {Indent = true}))
            using (var xamlWriter = new XamlXmlWriter(xmlWriter, xamlReader.SchemaContext))
            {
                XamlServices.Transform(xamlReader, xamlWriter);
            }

            // Create boilerplate code-behind files (.cpp, .h) to accompany the newly created XAML file
            var className = Path.GetFileNameWithoutExtension(args[0]);
            GenerateXAMLCodeBehindFromResource(className, PlaceHolderCPPFile, args[0].Replace(".xib", ".xaml.cpp"));
            GenerateXAMLCodeBehindFromResource(className, PlaceHolderHeaderFile, args[0].Replace(".xib", ".xaml.h"));
        }
Пример #36
0
 public void Save()
 {
     using (var sw = XmlWriter.Create(filename(), new XmlWriterSettings
     {
         Indent = true,
         NewLineOnAttributes = true,
         NamespaceHandling = NamespaceHandling.OmitDuplicates,
         OmitXmlDeclaration = true,
     }))
     using (var xr = new XamlObjectReader(this, App.ctx))
     using (var xw = new XamlXmlWriter(sw, App.ctx))
     {
         XamlServices.Transform(xr, xw);
     }
 }
Пример #37
0
		public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile)
		{
			bamlCode.Position = 0;
			TextWriter w = new StringWriter();
			
			Assembly assembly = Assembly.LoadFile(containingAssemblyFile);
			
			Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly });
			XDocument doc = new XDocument();
			XamlXmlWriter writer = new XamlXmlWriter(doc.CreateWriter(), reader.SchemaContext);
			while (reader.Read()) {
				switch (reader.NodeType) {
					case XamlNodeType.None:

						break;
					case XamlNodeType.StartObject:
						writer.WriteStartObject(reader.Type);
						break;
					case XamlNodeType.GetObject:
						writer.WriteGetObject();
						break;
					case XamlNodeType.EndObject:
						writer.WriteEndObject();
						break;
					case XamlNodeType.StartMember:
						writer.WriteStartMember(reader.Member);
						break;
					case XamlNodeType.EndMember:
						writer.WriteEndMember();
						break;
					case XamlNodeType.Value:
						// requires XamlReaderSettings.ValuesMustBeString = true to work properly
						writer.WriteValue(reader.Value);
						break;
					case XamlNodeType.NamespaceDeclaration:
						writer.WriteNamespace(reader.Namespace);
						break;
					default:
						throw new Exception("Invalid value for XamlNodeType");
				}
			}
			writer.Close();
			
			// Fix namespace references
			string suffixToRemove = ";assembly=" + assembly.GetName().Name;
			foreach (XAttribute attrib in doc.Root.Attributes()) {
				if (attrib.Name.Namespace == XNamespace.Xmlns) {
					if (attrib.Value.EndsWith(suffixToRemove, StringComparison.Ordinal)) {
						string newNamespace = attrib.Value.Substring(0, attrib.Value.Length - suffixToRemove.Length);
						ChangeXmlNamespace(doc, attrib.Value, newNamespace);
						attrib.Value = newNamespace;
					}
				}
			}
			// Convert x:Key into an attribute where possible
			XName xKey = XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml");
			foreach (XElement e in doc.Descendants(xKey).ToList()) {
				if (e.Nodes().Count() != 1)
					continue;
				XText text = e.Nodes().Single() as XText;
				if (text != null) {
					e.Parent.SetAttributeValue(xKey, text.Value);
					e.Remove();
				}
			}
			
			return doc.ToString();
		}
Пример #38
0
        /// <summary>
        /// Injects the XAML with replacement types
        /// </summary>
        private void InjectXaml()
        {
            var writerSettings = new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true };

            // using (XmlReader.Create(this.xamlFile))
            using (var xmlWriter = XmlWriter.Create(this.testXamlFile, writerSettings))
            using (this.xamlXmlReader)
            using (var xamlWriter = new XamlXmlWriter(xmlWriter, this.xamlXmlReader.SchemaContext))
            {
                var skippedLastNode = false;
                while (skippedLastNode || this.xamlXmlReader.Read())
                {
                    skippedLastNode = false;

                    Type replacementType;
                    if (this.xamlXmlReader.NodeType == XamlNodeType.StartObject
                        && this.xamlXmlReader.Type.UnderlyingType != null
                        && this.testDoubles.TryGetDouble(this.xamlXmlReader.Type.UnderlyingType, out replacementType))
                    {
                        xamlWriter.WriteStartObject(xamlWriter.SchemaContext.GetXamlType(replacementType));
                    }
                    else if (this.xamlXmlReader.NodeType == XamlNodeType.StartMember
                             &&
                             (this.xamlXmlReader.Member == XamlLanguage.Base
                              || this.xamlXmlReader.Member == XamlLanguage.Space))
                    {
                        // Skip XML members that are automatically added by the XAML stack
                        this.xamlXmlReader.Skip();
                        skippedLastNode = !this.xamlXmlReader.IsEof;
                    }
                    else
                    {
                        xamlWriter.WriteNode(this.xamlXmlReader);
                    }
                }
            }
        }
Пример #39
0
        public static string removeViewState(ActivityBuilder activityBuilder)
        {
            string xamlString = "";

            XmlWriterSettings writerSettings = new XmlWriterSettings { Indent = true };

            StringBuilder stringBuilder = new StringBuilder();

            XmlWriter xmlWriter = XmlWriter.Create(stringBuilder, writerSettings);

            XamlXmlWriter xamlXmlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());

            XamlWriter xamlWriter = ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);

            viewStateXamlWriter wfViewStateControl = new viewStateXamlWriter(xamlWriter);

            XamlServices.Save(wfViewStateControl, activityBuilder);

            xamlString = stringBuilder.ToString();

            return xamlString;
        }
Пример #40
0
        //从[xaml]字串得到[ActivityBuilder]对象
        public static string xamlFromActivityBuilder(ActivityBuilder activityBuilder)
        {
            string xamlString = "";

            StringBuilder stringBuilder = new StringBuilder();

            System.IO.StringWriter stringWriter = new System.IO.StringWriter(stringBuilder);

            System.Xaml.XamlSchemaContext xamlSchemaContext = new System.Xaml.XamlSchemaContext();

            System.Xaml.XamlXmlWriter xamlXmlWriter = new System.Xaml.XamlXmlWriter(stringWriter, xamlSchemaContext);

            System.Xaml.XamlWriter xamlWriter = System.Activities.XamlIntegration.ActivityXamlServices.CreateBuilderWriter(xamlXmlWriter);

            System.Xaml.XamlServices.Save(xamlWriter, activityBuilder);

            xamlString = stringBuilder.ToString();

            return xamlString;
        }