private static List <object> GetFromClipboard(out List <object> metaData, EditingContext editingContext)
        {
            Fx.Assert(editingContext != null, "editingContext should not be null");

            MultiTargetingSupportService multiTargetingService = editingContext.Services.GetService <IMultiTargetingSupportService>() as MultiTargetingSupportService;
            DesignerConfigurationService config = editingContext.Services.GetService <DesignerConfigurationService>();
            DataObject    dataObject            = RetriableClipboard.GetDataObject() as DataObject;
            List <object> workflowData          = null;

            metaData = null;

            if (dataObject != null)
            {
                if (dataObject.GetDataPresent(WorkflowClipboardFormat))
                {
                    bool isCopyingFromHigherFrameworkToLowerFramework = false;

                    if (multiTargetingService != null && config != null)
                    {
                        isCopyingFromHigherFrameworkToLowerFramework = GetTargetFrameworkFromClipboard(dataObject).Version > config.TargetFrameworkName.Version;
                    }

                    string clipBoardString = (string)TryGetData(dataObject, WorkflowClipboardFormat);
                    using (StringReader stringReader = new StringReader(clipBoardString))
                    {
                        try
                        {
                            XamlSchemaContext schemaContext;
                            if (isCopyingFromHigherFrameworkToLowerFramework)
                            {
                                schemaContext = new MultiTargetingXamlSchemaContext(multiTargetingService);
                            }
                            else
                            {
                                schemaContext = new XamlSchemaContext();
                            }

                            using (XamlXmlReader xamlXmlReader = new XamlXmlReader(stringReader, schemaContext))
                            {
                                ClipboardData clipboardData = (ClipboardData)XamlServices.Load(xamlXmlReader);
                                metaData     = clipboardData.Metadata;
                                workflowData = clipboardData.Data;
                            }
                        }
                        catch (Exception e)
                        {
                            Trace.WriteLine(e.Message);
                        }
                    }
                }
                else if (dataObject.GetDataPresent(WorkflowCallbackClipboardFormat))
                {
                    ClipboardData localData = (ClipboardData)TryGetData(dataObject, WorkflowCallbackClipboardFormat);
                    metaData     = null;
                    workflowData = localData.Data;
                    workflowData.Add(CutCopyPasteHelper.workflowCallbackContext);
                }
            }
            return(workflowData);
        }
        public void TestBaseUri2()
        {
            string       xaml = @"
<c:ArrayList xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:s='clr-namespace:System;assembly=mscorlib'
xmlns:c='clr-namespace:System.Collections;assembly=mscorlib' xml:base='http://schemas.microsoft.com/winfx/2006/xaml'>
<s:String>Hello</s:String>
</c:ArrayList>";
            MemoryStream ms   = new MemoryStream();

            using (StreamWriter sw = new StreamWriter(ms))
            {
                sw.Write(xaml);
                sw.Flush();
                ms.Position = 0;
                XamlXmlReaderSettings settings  = new XamlXmlReaderSettings();
                XamlXmlReader         xxr       = new XamlXmlReader(ms, settings);
                XamlObjectWriter      objWriter = new XamlObjectWriter(xxr.SchemaContext);

                while (xxr.Read())
                {
                    objWriter.WriteNode(xxr);
                }

                objWriter.Clear();
                objWriter.Close();
            }
        }
Exemple #3
0
        XamlType GetRootXamlType()
        {
            try
            {
                using (Stream xamlStream = base.OpenStream())
                {
                    XmlReader     xmlReader  = XmlReader.Create(xamlStream);
                    XamlXmlReader xamlReader = new XamlXmlReader(xmlReader);

                    // Read to the root object
                    while (xamlReader.Read())
                    {
                        if (xamlReader.NodeType == XamlNodeType.StartObject)
                        {
                            return(xamlReader.Type);
                        }
                    }
                    throw FxTrace.Exception.AsError(new HttpCompileException(SR.UnexpectedEof));
                }
            }
            catch (XamlParseException ex)
            {
                throw FxTrace.Exception.AsError(new HttpCompileException(ex.Message, ex));
            }
        }
        private async Task DeserializeAsync(Stream stream, Type type, Reference reference)
        {
            InternalXamlSchemaContext xamlSchemaContext = new InternalXamlSchemaContext(this, reference);

            XamlObjectWriter writer = new XamlObjectWriter(xamlSchemaContext);
            XamlXmlReader    reader = new XamlXmlReader(stream, xamlSchemaContext);

            XamlServices.Transform(reader, writer);

            if (type == typeof(object) && writer.Result is Asset || !type.IsInstanceOfType(writer.Result))
            {
                if (!(writer.Result is Asset asset))
                {
                    throw new InvalidOperationException();
                }

                reference.Object = await asset.CreateAssetAsync(Services);
            }
            else
            {
                reference.Object = writer.Result;
            }

            loadedAssetReferences[reference.Object] = reference;
        }
Exemple #5
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);
            }
        }
        public static void Load(Stream stream, object component)
        {
            DependencyObject dependencyObject = component as DependencyObject;
            NameScope        nameScope        = new NameScope();

            if (dependencyObject != null)
            {
                NameScope.SetNameScope(dependencyObject, nameScope);
            }

            XmlReader        xml    = XmlReader.Create(stream);
            XamlXmlReader    reader = new XamlXmlReader(xml);
            XamlObjectWriter writer = new XamlObjectWriter(
                new XamlSchemaContext(),
                new XamlObjectWriterSettings
            {
                RootObjectInstance = component,
                ExternalNameScope  = nameScope,
                RegisterNamesOnExternalNamescope = true,
                XamlSetValueHandler = SetValue,
            });

            while (reader.Read())
            {
                writer.WriteNode(reader);
            }
        }
Exemple #7
0
 public static object Load(TextReader textReader)
 {
     using (var reader = new XamlXmlReader(textReader, s_context))
     {
         return(Load(reader));
     }
 }
        public static Activity LoadActivityFromFile(string activityXamlPath, string activityName, string activityAssemblyPath = null)
        {
            XamlReader xamlReader;

            if (!string.IsNullOrWhiteSpace(activityAssemblyPath))
            {
                Assembly actAssembly           = Assembly.LoadFile(activityAssemblyPath);
                XamlXmlReaderSettings settings = new XamlXmlReaderSettings
                {
                    LocalAssembly = actAssembly //TODO: this needs to be checked
                };
                xamlReader = new XamlXmlReader(activityXamlPath, settings);
            }
            else
            {
                xamlReader = new XamlXmlReader(activityXamlPath);
            }

            ActivityXamlServicesSettings activitySettings = new ActivityXamlServicesSettings
            {
                CompileExpressions = true //compile C# expressions in workflow
            };
            Activity activity = ActivityXamlServices.Load(xamlReader, activitySettings);

            activity.DisplayName = activityName;

            return(activity);
        }
        public override Type GetGeneratedType(CompilerResults results)
        {
            Type type;

            try
            {
                using (Stream stream = base.OpenStream())
                {
                    XamlXmlReader reader2 = new XamlXmlReader(XmlReader.Create(stream));
                    while (reader2.Read())
                    {
                        if (reader2.NodeType == XamlNodeType.StartObject)
                        {
                            if (reader2.Type.IsUnknown)
                            {
                                StringBuilder sb = new StringBuilder();
                                this.AppendTypeName(reader2.Type, sb);
                                throw FxTrace.Exception.AsError(new TypeLoadException(System.Xaml.Hosting.SR.CouldNotResolveType(sb)));
                            }
                            return(reader2.Type.UnderlyingType);
                        }
                    }
                    throw FxTrace.Exception.AsError(new HttpCompileException(System.Xaml.Hosting.SR.UnexpectedEof));
                }
            }
            catch (XamlParseException exception)
            {
                throw FxTrace.Exception.AsError(new HttpCompileException(exception.Message, exception));
            }
            return(type);
        }
        //Event handlers

        /**
         * Sets the mod description to a markdown formatted document
         */
        private void SetModDetails(object sender, SelectionChangedEventArgs e)
        {
            Mod mod = (Mod)((DataGrid)sender).SelectedItem;

            if (mod.LogoURL == "")
            {
                LogoImage.Source = (ImageSource) new ImageSourceConverter().ConvertFrom(Properties.Resources.NotFound);
            }
            else
            {
                LogoImage.Source = new BitmapImage(new Uri(mod.LogoURL));
            }

            DownloadButton.IsEnabled = true;

            //Source: https://github.com/Kryptos-FR/markdig.wpf/blob/master/src/Markdig.Xaml.SampleApp/MainWindow.xaml.cs#L36
            //Sets the mod details view with the markdown rendered content
            using MemoryStream stream =
                      new MemoryStream(Encoding.UTF8.GetBytes(
                                           Markdown.ToXaml(mod.FullDescription, new MarkdownPipelineBuilder().UseSupportedExtensions().Build())));
            using XamlXmlReader reader = new XamlXmlReader(stream, new XamlSchemaContext());
            if (XamlReader.Load(reader) is FlowDocument document)
            {
                ModDescription.Document = document;
            }
        }
Exemple #11
0
        private string RemoveViewState(string xaml)
        {
            string xamlString = "";

            try
            {
                StringReader    stringReader  = new StringReader(xaml);
                XamlXmlReader   xamlXmlReader = new XamlXmlReader(stringReader);
                XamlReader      xamlReader    = ActivityXamlServices.CreateBuilderReader(xamlXmlReader);
                ActivityBuilder ab            = XamlServices.Load(ActivityXamlServices.CreateBuilderReader(xamlReader)) as ActivityBuilder;

                XmlWriterSettings writerSettings = new XmlWriterSettings {
                    Indent = true, Encoding = new UTF8Encoding(false)
                };

                using (MemoryStream ms = new MemoryStream())
                {
                    using (XmlWriter xmlWriter = XmlWriter.Create(ms, writerSettings))
                    {
                        XamlXmlWriter xamlWriter = new XamlXmlWriter(xmlWriter, new XamlSchemaContext());
                        XamlServices.Save(new ViewStateCleaningWriter(ActivityXamlServices.CreateBuilderWriter(xamlWriter)), ab);

                        xamlString = Encoding.UTF8.GetString(ms.ToArray());
                    }
                }
                return(xamlString);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("去除ViewState异常:{0}", ex.Message));
            }
        }
Exemple #12
0
        public XamlAnalysis(TextReader textReader)
        {
            try
            {
                var settings = new XamlXmlReaderSettings
                {
                    ProvideLineInfo = true
                };

                var context = new XamlSchemaContext(new XamlSchemaContextSettings()
                {
                    FullyQualifyAssemblyNamesInClrNamespaces = true
                });

                using (XamlXmlReader reader = new XamlXmlReader(textReader, context, settings))
                {
                    Analyze(reader);
                }
            }
            catch
            {
                // ignore malformed XAML - XamlReader does a bad job of documenting what it throws
                // so we just need to try/catch here.
            }
        }
Exemple #13
0
        /// <summary>
        /// Parses a well-formed XAML fragment and creates a corresponding Silverlight object tree,
        /// and returns the root of the object tree.
        /// </summary>
        /// <returns>The root object of the Silverlight object tree.</returns>
        /// <param name="xaml">A string that contains a valid XAML fragment.</param>
        public static object Load(string xaml)
        {
            var textReader = new StringReader(xaml);

            var xamlReader = new XamlXmlReader(textReader);
            var xamlWriter = new XamlObjectWriter(xamlReader.SchemaContext);

            if (xamlReader.NodeType == XamlNodeType.None)
            {
                xamlReader.Read();
            }

            var xamlLineInfo      = xamlReader as IXamlLineInfo;
            var xamlLineConsumer  = xamlWriter as IXamlLineInfoConsumer;
            var shouldSetLineInfo = xamlLineInfo != null && xamlLineConsumer != null && xamlLineConsumer.ShouldProvideLineInfo && xamlLineInfo.HasLineInfo;

            while (!xamlReader.IsEof)
            {
                if (shouldSetLineInfo)
                {
                    xamlLineConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition);
                }
                xamlWriter.WriteNode(xamlReader);
                xamlReader.Read();
            }

            return(xamlWriter.Result);
        }
Exemple #14
0
        /// <summary>
        /// Validates well-formedness of the Xaml
        /// </summary>
        /// <exception cref="System.IO.FileNotFoundException">If the <code>inputFile</code> was not found</exception>
        private void ValidateXaml()
        {
            XmlReader     xmlReader  = null;
            XamlXmlReader xamlReader = null;

            try
            {
                log.Debug("Validating XAML.");

                xmlReader  = XmlReader.Create(inputFile);
                xamlReader = new XamlXmlReader(xmlReader);
                ActivityBuilder activity = XamlServices.Load(ActivityXamlServices.CreateBuilderReader(xamlReader)) as ActivityBuilder;

                log.Info("XAML successfully validated.");
            }
            catch (XamlException)
            {
                // Only notify user
                log.Warn("XAML could not be validated. This may also be caused by Custom Activities or WorkflowServices.");
            }
            finally
            {
                // Cleanup
                if (xmlReader != null)
                {
                    xmlReader.Close();
                }
                if (xamlReader != null)
                {
                    xamlReader.Close();
                }
            }
        }
Exemple #15
0
        private static ActivityBuilder StartUpdate(string name)
        {
            // Create the XamlXmlReaderSettings.
            XamlXmlReaderSettings readerSettings = new XamlXmlReaderSettings()
            {
                // In the XAML the "local" namespace referes to artifacts that come from
                // the same project as the XAML. When loading XAML if the currently executing
                // assembly is not the same assembly that was referred to as "local" in the XAML
                // LocalAssembly must be set to the assembly containing the artifacts.
                // Assembly.LoadFile requires an absolute path so convert this relative path
                // to an absolute path.
                LocalAssembly = Assembly.LoadFile(
                    Path.GetFullPath(Path.Combine(mapPath, "NumberGuessWorkflowActivities_v1.dll")))
            };

            string        path       = Path.Combine(definitionPath, name);
            XamlXmlReader xamlReader = new XamlXmlReader(path, readerSettings);

            // Load the workflow definition into an ActivityBuilder.
            ActivityBuilder wf = XamlServices.Load(
                ActivityXamlServices.CreateBuilderReader(xamlReader))
                                 as ActivityBuilder;

            // PrepareForUpdate makes a copy of the workflow definition in the
            // ActivityBuilder that is used for comparison when the update
            // map is created.
            DynamicUpdateServices.PrepareForUpdate(wf);

            return(wf);
        }
Exemple #16
0
        private void LoadWorkspace(string workspaceFile)
        {
            try
            {
                using (XamlXmlReader reader = new XamlXmlReader(workspaceFile))
                {
                    using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
                    {
                        while (reader.Read())
                        {
                            writer.WriteNode(reader);
                        }

                        Workspace      = (MdiDemoWorkspace)writer.Result;
                        _workspaceFile = workspaceFile;
                    }
                }

                GC.Collect(); // lame!  The XamlXmlReader will leave the file open until the next GC.
                GC.WaitForPendingFinalizers();
            }
            catch (Exception)
            {
                MessageBox.Show(String.Format("An error occured opening MDI workspace file '{0}'.", workspaceFile));
            }
        }
Exemple #17
0
        private void OnLoaded(object sender, RoutedEventArgs e)
        {
            string language      = UserSettings.PlayerConfig.HunterPie.Language.Split('\\').LastOrDefault().Replace(".xml", "");
            string changelogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Changelog\\changelog-{language}.md");

            if (!File.Exists(changelogPath))
            {
                changelogPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"Changelog\\changelog-en-us.md");
            }

            if (!File.Exists(changelogPath))
            {
                return;
            }

            var markdown = File.ReadAllText(changelogPath);
            var xaml     = Markdig.Wpf.Markdown.ToXaml(markdown, BuildPipeline());

            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml)))
            {
                using (var reader = new XamlXmlReader(stream, new MyXamlSchemaContext()))
                {
                    if (XamlReader.Load(reader) is FlowDocument document)
                    {
                        Viewer.Document = document;
                    }
                }
            }
        }
Exemple #18
0
 /// <summary>
 /// Get an DynamicActivity by Id and stream
 /// </summary>
 /// <param name="id">The workflow id</param>
 /// <param name="getStream">The stream defined workflow</param>
 /// <returns>The Compiled DynamicActivity</returns>
 public static Activity Create(string id, Func <string, Stream> getStream, bool safe = true)
 {
     using (XamlXmlReader reader = new XamlXmlReader(getStream(id)))
     {
         return(Create(id, reader, safe));
     }
 }
Exemple #19
0
        private void Visit(XamlXmlReader reader, XamlObjectDefinition xamlObject)
        {
            while (reader.Read())
            {
                WriteState(reader);

                switch (reader.NodeType)
                {
                case XamlNodeType.StartMember:
                    _depth++;
                    xamlObject.Members.Add(VisitMember(reader, xamlObject));
                    break;

                case XamlNodeType.StartObject:
                    _depth++;
                    xamlObject.Objects.Add(VisitObject(reader, xamlObject));
                    break;

                case XamlNodeType.Value:
                    xamlObject.Value = reader.Value;
                    break;

                case XamlNodeType.EndObject:
                    _depth--;
                    return;

                case XamlNodeType.EndMember:
                    _depth--;
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }
        }
Exemple #20
0
        private XamlFileDefinition ParseFile(string file)
        {
            try
            {
                this.Log().InfoFormat("Pre-processing XAML file: {0}", file);

                var document = ApplyIgnorables(file);

                // Initialize the reader using an empty context, because when the tasl
                // is run under the BeforeCompile in VS IDE, the loaded assemblies are used
                // to interpret the meaning of objects, which is not correct in Uno.UI context.
                var context = new XamlSchemaContext(Enumerable.Empty <Assembly>());

                // Force the line info, otherwise it will be enabled only when the debugger is attached.
                var settings = new XamlXmlReaderSettings()
                {
                    ProvideLineInfo = true
                };

                using (var reader = new XamlXmlReader(document, context, settings))
                {
                    if (reader.Read())
                    {
                        return(Visit(reader, file));
                    }
                }

                return(null);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException($"Failed to parse file {file}", e);
            }
        }
Exemple #21
0
        public XamlFileDefinition Parse(string content)
        {
            var document = XmlReader.Create(new StringReader(content));

            // Initialize the reader using an empty context, because when the tasl
            // is run under the BeforeCompile in VS IDE, the loaded assemblies are used
            // to interpret the meaning of objects, which is not correct in Uno.UI context.
            var context = new XamlSchemaContext(Enumerable.Empty <Assembly>());

            // Force the line info, otherwise it will be enabled only when the debugger is attached.
            var settings = new XamlXmlReaderSettings()
            {
                ProvideLineInfo = true
            };

            using (var reader = new XamlXmlReader(document, context, settings))
            {
                if (reader.Read())
                {
                    return(Visit(reader));
                }
            }

            return(null);
        }
Exemple #22
0
        private XamlFileDefinition Visit(XamlXmlReader reader, string file)
        {
            WriteState(reader);

            var xamlFile = new XamlFileDefinition(file);

            do
            {
                switch (reader.NodeType)
                {
                case XamlNodeType.StartObject:
                    _depth++;
                    xamlFile.Objects.Add(VisitObject(reader, null));
                    break;

                case XamlNodeType.NamespaceDeclaration:
                    xamlFile.Namespaces.Add(reader.Namespace);
                    break;

                default:
                    throw new InvalidOperationException();
                }
            }while (reader.Read());

            return(xamlFile);
        }
Exemple #23
0
        /// <summary>
        /// Loads the specified type from the specified xaml stream
        /// </summary>
        /// <typeparam name="T">Type of object to load from the specified xaml</typeparam>
        /// <param name="stream">Xaml content to load (e.g. from resources)</param>
        /// <param name="instance">Instance to use as the starting object</param>
        /// <returns>A new or existing instance of the specified type with the contents loaded from the xaml stream</returns>
        public static T Load <T> (Stream stream, T instance)
            where T : InstanceWidget
        {
            var type           = typeof(T);
            var context        = new EtoXamlSchemaContext(new Assembly[] { typeof(XamlReader).Assembly });
            var reader         = new XamlXmlReader(stream, context);
            var writerSettings = new XamlObjectWriterSettings {
                RootObjectInstance = instance
            };

            writerSettings.AfterPropertiesHandler += delegate(object sender, XamlObjectEventArgs e) {
                var obj = e.Instance as InstanceWidget;
                if (obj != null && !string.IsNullOrEmpty(obj.ID))
                {
                    var property = type.GetProperty(obj.ID, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                    if (property != null)
                    {
                        property.SetValue(instance, obj, null);
                    }
                    else
                    {
                        var field = type.GetField(obj.ID, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
                        if (field != null)
                        {
                            field.SetValue(instance, obj);
                        }
                    }
                }
            };

            var writer = new XamlObjectWriter(context, writerSettings);

            XamlServices.Transform(reader, writer);
            return(writer.Result as T);
        }
Exemple #24
0
        /// <summary>
        /// 2-phase initialization to parse parameters
        /// </summary>
        /// <returns></returns>
        public bool Initialize()
        {
            XamlXmlReader reader = new XamlXmlReader(_filename, new XamlXmlReaderSettings {
                LocalAssembly = typeof(MainViewModel).Assembly
            });

            _workflow = ActivityXamlServices.Load(reader);

            var argumentViewModel = new ArgumentCollectorViewModel(_workflow as DynamicActivity);

            if (argumentViewModel.HasArguments)
            {
                IUIVisualizer uiVisualizer = Resolve <IUIVisualizer>();
                if (uiVisualizer.ShowDialog("WorkflowArgumentsView", argumentViewModel) == false)
                {
                    return(false);
                }
            }

            _inputs = argumentViewModel.CollectArguments();

            //_inputs.Add("img",typeof(Image<Bgr,Byte>));
            //_inputs.Add("gimg", typeof(Image<Gray, Byte>));

            return(true);
        }
Exemple #25
0
        /// <summary>
        /// Loads XAML from a stream.
        /// </summary>
        /// <param name="stream">The stream containing the XAML.</param>
        /// <param name="localAssembly">Default assembly for clr-namespace</param>
        /// <param name="rootInstance">
        /// The optional instance into which the XAML should be loaded.
        /// </param>
        /// <param name="uri">The URI of the XAML</param>
        /// <returns>The loaded object.</returns>
        public object Load(Stream stream, Assembly localAssembly, object rootInstance = null, Uri uri = null)
        {
            var readerSettings = new XamlXmlReaderSettings()
            {
                BaseUri         = uri,
                LocalAssembly   = localAssembly,
                ProvideLineInfo = true,
            };

            var context = IsDesignMode ? AvaloniaXamlSchemaContext.DesignInstance : AvaloniaXamlSchemaContext.Instance;
            var reader  = new XamlXmlReader(stream, context, readerSettings);

            object result = LoadFromReader(
                reader,
                AvaloniaXamlContext.For(readerSettings, rootInstance));

            var topLevel = result as TopLevel;

            if (topLevel != null)
            {
                DelayedBinding.ApplyBindings(topLevel);
            }

            return(result);
        }
Exemple #26
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));
        }
        bool ProcessMarkupItem(string markupItem, XamlNsReplacingContext wxsc, Assembly localAssembly)
        {
            XamlXmlReaderSettings settings = new XamlXmlReaderSettings()
            {
                LocalAssembly = localAssembly, ProvideLineInfo = true, AllowProtectedMembersOnRoot = true
            };

            using (StreamReader streamReader = new StreamReader(markupItem))
            {
                var             xamlReader       = new XamlXmlReader(XmlReader.Create(streamReader), wxsc, settings);
                ClassValidator  validator        = new ClassValidator(markupItem, localAssembly, this.RootNamespace);
                IList <LogData> validationErrors = null;
                if (validator.ValidateXaml(xamlReader, false, this.AssemblyName, out validationErrors))
                {
                    return(true);
                }
                else
                {
                    foreach (LogData logData in validationErrors)
                    {
                        this.LogData.Add(logData);
                    }
                    return(false);
                }
            }
        }
Exemple #28
0
 public static object Load(XmlReader xmlReader)
 {
     using (var reader = new XamlXmlReader(xmlReader, context))
     {
         return(Load(reader));
     }
 }
Exemple #29
0
 public static object Load(string path)
 {
     using (var reader = new XamlXmlReader(path, context))
     {
         return(Load(reader));
     }
 }
Exemple #30
0
 public static object Load(Stream stream)
 {
     using (var reader = new XamlXmlReader(stream, context))
     {
         return(Load(reader));
     }
 }
		public void RootObjectInstance ()
		{
			// bug #689548
			var obj = new RootObjectInstanceTestClass ();
			RootObjectInstanceTestClass result;
			
			var rsettings = new XamlXmlReaderSettings ();
			
			var xml = String.Format (@"<RootObjectInstanceTestClass Property=""Test"" xmlns=""clr-namespace:MonoTests.Portable.Xaml;assembly={0}""></RootObjectInstanceTestClass>", GetType ().Assembly.GetName ().Name);
			using (var reader = new XamlXmlReader (new StringReader (xml), rsettings)) {
				var wsettings = new XamlObjectWriterSettings ();
				wsettings.RootObjectInstance = obj;
				using (var writer = new XamlObjectWriter (reader.SchemaContext, wsettings)) {
					XamlServices.Transform (reader, writer, false);
					result = (RootObjectInstanceTestClass) writer.Result;
				}
			}
			
			Assert.AreEqual (obj, result, "#1");
			Assert.AreEqual ("Test", obj.Property, "#2");
		}