Inheritance: XamlWriter, IXamlLineInfoConsumer
Exemple #1
0
        public void Parse(string input, string[] args = null)
        {
            var xxr = new XamlXmlReader(new StringReader(input), new XamlSchemaContext());
            var graphReader = new XamlObjectWriter(xxr.SchemaContext);

            while (xxr.Read())
                graphReader.WriteNode(xxr);

            var page = (Page)graphReader.Result;

            // Map our generators
            var g = new Generator();
            g.Map<Page, PageGeneratorBlock>();
            g.Map<Button, ButtonGeneratorBlock>();
            g.Map<StackPanel, StackPanelGeneratorBlock>();

            var doc = new HtmlDocument();
            var html = doc.CreateElement("html");

            g.Generate(html, page);
            // HTML5 Doc type
            doc.DocumentNode.AppendChild(doc.CreateComment("<!DOCTYPE html>"));
            doc.DocumentNode.AppendChild(html);

            doc.Save("test.htm");

            var cssContents = g.GenerateStyles(page);
            File.WriteAllText("XamlCore.css", cssContents);
        }
Exemple #2
0
        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);
            }
        }
        private static void InternalPrepareForUpdate(object definitionToBeUpdated, bool forImplementation)
        {
            // Clone the definition
            object clone;
            using (XamlObjectReader reader = new XamlObjectReader(definitionToBeUpdated))
            {
                using (XamlObjectWriter writer = new XamlObjectWriter(reader.SchemaContext))
                {
                    XamlServices.Transform(reader, writer);
                    clone = writer.Result;
                }
            }

            // Calculate the match info
            // Set the match info as attached properties so it is serializable,
            // and available when the user calls CreateUpdateMap

            IDictionary<object, DynamicUpdateMapItem> mapItems;
            if (!forImplementation)
            {
                DynamicUpdateInfo.SetOriginalDefinition(definitionToBeUpdated, (Activity)clone);
                mapItems = DynamicUpdateMap.CalculateMapItems((Activity)definitionToBeUpdated);
            }
            else
            {
                DynamicUpdateInfo.SetOriginalActivityBuilder(definitionToBeUpdated, (ActivityBuilder)clone);
                mapItems = DynamicUpdateMap.CalculateImplementationMapItems(GetDynamicActivity((ActivityBuilder)definitionToBeUpdated));                
            }

            foreach (KeyValuePair<object, DynamicUpdateMapItem> objectInfo in mapItems)
            {
                DynamicUpdateInfo.SetMapItem(objectInfo.Key, objectInfo.Value);
            }
        }
Exemple #4
0
		public static Object Load (XamlReader xamlReader)
		{
			if (xamlReader == null)
				throw new ArgumentNullException ("xamlReader");
			var w = new XamlObjectWriter (xamlReader.SchemaContext);
			Transform (xamlReader, w);
			return w.Result;
		}
 public static object Load(XamlReader xamlReader)
 {
     if (xamlReader == null)
     {
         throw new ArgumentNullException("xamlReader");
     }
     XamlObjectWriter xamlWriter = new XamlObjectWriter(xamlReader.SchemaContext);
     Transform(xamlReader, xamlWriter);
     return xamlWriter.Result;
 }
Exemple #6
0
        public static object Load(System.Xaml.XamlReader reader)
        {
            XamlObjectWriter writer = new XamlObjectWriter(
                new XamlSchemaContext(),
                new XamlObjectWriterSettings
                {
                    XamlSetValueHandler = SetValue,
                });

            while (reader.Read())
            {
                writer.WriteNode(reader);
            }
            object result = writer.Result;

            return result;
        }
        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();
        }
Exemple #8
0
        public static object DeserializeString(string text)
        {
            var xamlSchemaContextCWithFullyQualifiedNameSupport =
              new XamlSchemaContext(new XamlSchemaContextSettings { FullyQualifyAssemblyNamesInClrNamespaces = false });

            using (XamlXmlReader xamlXmlReader =
                new XamlXmlReader(XmlReader.Create(new StringReader(text)),
                        xamlSchemaContextCWithFullyQualifiedNameSupport,
                        new XamlXmlReaderSettings { ProvideLineInfo = true }))
            {
                using (System.Xaml.XamlReader activityBuilderReader = ActivityXamlServices.CreateBuilderReader(xamlXmlReader, xamlSchemaContextCWithFullyQualifiedNameSupport))
                {
                    XamlObjectWriter objectWriter = new XamlObjectWriter(activityBuilderReader.SchemaContext);
                    XamlServices.Transform(activityBuilderReader, objectWriter);
                    return objectWriter.Result;
                }
            }
        }
Exemple #9
0
        public static void Load(Stream stream, object component)
        {
            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);
            }
        }
		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.System.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");
		}
		public void GetService ()
		{
			var obj = new TestValueSerialized ();
			var xr = new XamlObjectReader (obj);
			while (!xr.IsEof)
				xr.Read ();
			Assert.IsNotNull (Context, "premise#1");
			GetServiceCoreReader ();

			Context = null;
			var ctx = new XamlSchemaContext ();
			var xw = new XamlObjectWriter (ctx);
			var xt = ctx.GetXamlType (obj.GetType ());
			xw.WriteStartObject (xt);
			xw.WriteStartMember (XamlLanguage.Initialization);
			xw.WriteValue ("v");
			xw.WriteEndMember ();
			xw.Close ();
			Assert.IsNotNull (Provider, "premise#2"); // cannot get Context, it does not give IValueSerializerContext in the test.
			GetServiceCoreWriter ();
		}
        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(
        }
Exemple #13
0
        public static object Load(System.Xaml.XamlReader reader)
        {
            XamlObjectWriter writer = new XamlObjectWriter(
                new XamlSchemaContext(),
                new XamlObjectWriterSettings
                {
                    XamlSetValueHandler = SetValue,
                });

            while (reader.Read())
            {
                writer.WriteNode(reader);
            }

            object result = writer.Result;
            DependencyObject dependencyObject = result as DependencyObject;

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

            return result;
        }
Exemple #14
0
 private void LoadTemplateXaml(XamlObjectWriter objectWriter)
 {
     System.Xaml.XamlReader templateReader = _templateHolder.PlayXaml();
     Debug.Assert(templateReader != null, "PlayXaml returned null");
     if (_templateHolder.LoadPermission != null)
     {
         _templateHolder.LoadPermission.Assert();
         try
         {
             LoadTemplateXaml(templateReader, objectWriter);
         }
         finally
         {
             CodeAccessPermission.RevertAssert();
         }
     }
     else
     {
         LoadTemplateXaml(templateReader, objectWriter);
     }
 }
Exemple #15
0
		public XamlObjectWriterInternal (XamlObjectWriter source, XamlSchemaContext schemaContext, XamlWriterStateManager manager)
			: base (schemaContext, manager)
		{
			this.source = source;
			this.sctx = schemaContext;
		}
 public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings)
 {
     var xamlSchemaContext = new XamlSchemaContext();
     var xamlObjectWriter = new XamlObjectWriter(xamlSchemaContext, settings);
     return xamlObjectWriter;
 }
        private static object Load(System.Xaml.XamlReader xamlReader, IXamlObjectWriterFactory writerFactory,
                                   bool skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
        {
            XamlObjectWriter xamlWriter           = null;
            XamlContextStack <WpfXamlFrame> stack = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame());
            int persistId = 1;

            settings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args)
            {
                if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose))
                {
                    IXamlLineInfo ixli = xamlReader as IXamlLineInfo;

                    int lineNumber   = -1;
                    int linePosition = -1;

                    if (ixli != null && ixli.HasLineInfo)
                    {
                        lineNumber   = ixli.LineNumber;
                        linePosition = ixli.LinePosition;
                    }

                    EventTrace.EventProvider.TraceEvent(
                        EventTrace.Event.WClientParseXamlBamlInfo,
                        EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose,
                        args.Instance == null ? 0 : PerfService.GetPerfElementID(args.Instance),
                        lineNumber,
                        linePosition);
                }

                UIElement uiElement = args.Instance as UIElement;
                if (uiElement != null)
                {
                    uiElement.SetPersistId(persistId++);
                }

                XamlSourceInfoHelper.SetXamlSourceInfo(args.Instance, args, baseUri);

                DependencyObject dObject = args.Instance as DependencyObject;
                if (dObject != null && stack.CurrentFrame.XmlnsDictionary != null)
                {
                    XmlnsDictionary dictionary = stack.CurrentFrame.XmlnsDictionary;
                    dictionary.Seal();

                    XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary);
                }

                stack.CurrentFrame.Instance = args.Instance;
            };
            if (writerFactory != null)
            {
                xamlWriter = writerFactory.GetXamlObjectWriter(settings);
            }
            else
            {
                xamlWriter = new System.Xaml.XamlObjectWriter(xamlReader.SchemaContext, settings);
            }

            IXamlLineInfo xamlLineInfo = null;

            try
            {
                //Handle Line Numbers
                xamlLineInfo = xamlReader as IXamlLineInfo;
                IXamlLineInfoConsumer xamlLineInfoConsumer = xamlWriter as IXamlLineInfoConsumer;
                bool shouldPassLineNumberInfo = false;
                if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) &&
                    (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo))
                {
                    shouldPassLineNumberInfo = true;
                }

                IStyleConnector styleConnector = rootObject as IStyleConnector;
                TransformNodes(xamlReader, xamlWriter,
                               false /*onlyLoadOneNode*/,
                               skipJournaledProperties,
                               shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer,
                               stack, styleConnector);
                xamlWriter.Close();
                return(xamlWriter.Result);
            }
            catch (Exception e)
            {
                // Don't wrap critical exceptions or already-wrapped exceptions.
                if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !XamlReader.ShouldReWrapException(e, baseUri))
                {
                    throw;
                }
                XamlReader.RewrapException(e, xamlLineInfo, baseUri);
                return(null);    // this should never be executed
            }
        }
        private void ExtractBAML(string name, Stream stream)
        {
            var reader = new Baml2006Reader(stream);
            var settings = new XamlObjectWriterSettings ();

            settings.BeforePropertiesHandler += (sender, e) =>
            {
                Trace("properties for {0}", e.Instance);
            };

            settings.XamlSetValueHandler += (sender, e) =>
            {
                //TraceTarget.Trace("set value {0} = {1}", e.Member.Name, e.Value);

                /*if (e.Member.Name == "DeferrableContent")
                {
                    e.Handled = true;
                }*/
            };

            var writer = new XamlObjectWriter(reader.SchemaContext, settings);
            while (reader.Read())
            {
                writer.WriteNode(reader);
            }
            var x = writer.Result;

            var ms = new MemoryStream();
            using (var xwriter = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true }))
            {
                System.Windows.Markup.XamlWriter.Save(x, xwriter);
            }

            var xamlname = Path.ChangeExtension(name, ".xaml");

            ms.Position = 0;
            AddResource(xamlname, ms);
        }
        /// <summary>
        /// Gets a <see cref="FrameworkTemplate"/> based on the specified parameters.
        /// </summary>
        /// <param name="xmlElement">The xml element to get template xaml from.</param>
        /// <param name="parentObject">The <see cref="XamlObject"/> to use as source for resources and contextual information.</param>
        /// <returns>A <see cref="FrameworkTemplate"/> based on the specified parameters.</returns>
        public static FrameworkTemplate GetFrameworkTemplate(XmlElement xmlElement, XamlObject parentObject)
        {
            var nav = xmlElement.CreateNavigator();

            var ns = new Dictionary<string, string>();
            while (true)
            {
                var nsInScope = nav.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml);
                foreach (var ak in nsInScope)
                {
                    if (!ns.ContainsKey(ak.Key) && ak.Key != "")
                        ns.Add(ak.Key, ak.Value);
                }
                if (!nav.MoveToParent())
                    break;
            }

            xmlElement = (XmlElement)xmlElement.CloneNode(true);

            foreach (var dictentry in ns.ToList())
            {
                var value = dictentry.Value;
                if (value.StartsWith("clr-namespace") && !value.Contains(";assembly=")) {
                    if (!string.IsNullOrEmpty(parentObject.OwnerDocument.CurrentProjectAssemblyName)) {
                        value += ";assembly=" + parentObject.OwnerDocument.CurrentProjectAssemblyName;
                    }
                }
                xmlElement.SetAttribute("xmlns:" + dictentry.Key, value);
            }

            var keyAttrib = xmlElement.GetAttribute("Key", XamlConstants.XamlNamespace);

            if (string.IsNullOrEmpty(keyAttrib)) {
                xmlElement.SetAttribute("Key", XamlConstants.XamlNamespace, "$$temp&&§§%%__");
            }

            var xaml = xmlElement.OuterXml;
            xaml = "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/netfx/2007/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" + xaml + "</ResourceDictionary>";
            StringReader stringReader = new StringReader(xaml);
            XmlReader xmlReader = XmlReader.Create(stringReader);
            var xamlReader = new XamlXmlReader(xmlReader, parentObject.ServiceProvider.SchemaContext);

            var seti = new XamlObjectWriterSettings();

            var resourceDictionary = new ResourceDictionary();
            var obj = parentObject;
            while (obj != null)
            {
                if (obj.Instance is ResourceDictionary)
                {
                    var r = obj.Instance as ResourceDictionary;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }
                else if (obj.Instance is FrameworkElement)
                {
                    var r = ((FrameworkElement)obj.Instance).Resources;
                    foreach (var k in r.Keys)
                    {
                        if (!resourceDictionary.Contains(k))
                            resourceDictionary.Add(k, r[k]);
                    }
                }

                obj = obj.ParentObject;
            }

            seti.BeforePropertiesHandler = (s, e) =>
            {
                if (seti.BeforePropertiesHandler != null)
                {
                    var rr = e.Instance as ResourceDictionary;
                    rr.MergedDictionaries.Add(resourceDictionary);
                    seti.BeforePropertiesHandler = null;
                }
            };

            var writer = new XamlObjectWriter(parentObject.ServiceProvider.SchemaContext, seti);

            XamlServices.Transform(xamlReader, writer);

            var result = (ResourceDictionary)writer.Result;

            var enr = result.Keys.GetEnumerator();
            enr.MoveNext();
            var rdKey = enr.Current;

            var template = result[rdKey] as FrameworkTemplate;

            result.Remove(rdKey);
            return template;
        }
Exemple #20
0
        private object LoadAsync(XmlReader reader, ParserContext parserContext)
        { 
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            } 

            if (parserContext == null) 
            { 
                parserContext = new ParserContext();
            } 

            _xmlReader = reader;
            object rootObject = null;
            if (parserContext.BaseUri == null || 
                 String.IsNullOrEmpty(parserContext.BaseUri.ToString()))
            { 
                if (reader.BaseURI == null || 
                    String.IsNullOrEmpty(reader.BaseURI.ToString()))
                { 
                    parserContext.BaseUri = BaseUriHelper.PackAppBaseUri;
                }
                else
                { 
                    parserContext.BaseUri = new Uri(reader.BaseURI);
                } 
            } 

            _baseUri = parserContext.BaseUri; 
            System.Xaml.XamlXmlReaderSettings settings = new System.Xaml.XamlXmlReaderSettings();
            settings.IgnoreUidsOnPropertyElements = true;
            settings.BaseUri = parserContext.BaseUri;
            settings.ProvideLineInfo = true; 
            XamlSchemaContext schemaContext = parserContext.XamlTypeMapper != null ?
                parserContext.XamlTypeMapper.SchemaContext : GetWpfSchemaContext(); 
 
            try
            { 
                _textReader = new System.Xaml.XamlXmlReader(reader, schemaContext, settings);

                _stack = new XamlContextStack<WpfXamlFrame>(() => new WpfXamlFrame());
 
                System.Xaml.XamlObjectWriterSettings objectSettings = XamlReader.CreateObjectWriterSettings();
                objectSettings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args) 
                    { 
                        if (rootObject == null)
                        { 
                            rootObject = args.Instance;
                            _styleConnector = rootObject as IStyleConnector;
                        }
 
                        UIElement uiElement = args.Instance as UIElement;
                        if (uiElement != null) 
                        { 
                            uiElement.SetPersistId(_persistId++);
                        } 

                        DependencyObject dObject = args.Instance as DependencyObject;
                        if (dObject != null && _stack.CurrentFrame.XmlnsDictionary != null)
                        { 
                            XmlnsDictionary dictionary = _stack.CurrentFrame.XmlnsDictionary;
                            dictionary.Seal(); 
 
                            XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary);
                        } 
                    };

                _objectWriter = new System.Xaml.XamlObjectWriter(_textReader.SchemaContext, objectSettings);
                _parseCancelled = false; 
                _skipJournaledProperties = parserContext.SkipJournaledProperties;
 
                XamlMember synchronousModeProperty = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "SynchronousMode"); 
                XamlMember synchronousRecordProperty = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "AsyncRecords");
 
                System.Xaml.XamlReader xamlReader = _textReader;

                IXamlLineInfo xamlLineInfo = xamlReader as IXamlLineInfo;
                IXamlLineInfoConsumer xamlLineInfoConsumer = _objectWriter as IXamlLineInfoConsumer; 
                bool shouldPassLineNumberInfo = false;
                if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) 
                    && (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)) 
                {
                    shouldPassLineNumberInfo = true; 
                }

                bool async = false;
                bool lastPropWasSyncMode = false; 
                bool lastPropWasSyncRecords = false;
 
                while (!_textReader.IsEof) 
                {
                    WpfXamlLoader.TransformNodes(xamlReader, _objectWriter, true /*onlyLoadOneNode*/, _skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, _stack, _styleConnector); 

                    if (xamlReader.NodeType == System.Xaml.XamlNodeType.StartMember)
                    {
                        if (xamlReader.Member == synchronousModeProperty) 
                        {
                            lastPropWasSyncMode = true; 
                        } 
                        else if (xamlReader.Member == synchronousRecordProperty)
                        { 
                            lastPropWasSyncRecords = true;
                        }
                    }
                    else if (xamlReader.NodeType == System.Xaml.XamlNodeType.Value) 
                    {
                        if (lastPropWasSyncMode == true) 
                        { 
                            if (xamlReader.Value as String == "Async")
                            { 
                                async = true;
                            }
                        }
                        else if (lastPropWasSyncRecords == true) 
                        {
                            if (xamlReader.Value is int) 
                            { 
                                _maxAsynxRecords = (int)xamlReader.Value;
                            } 
                            else if (xamlReader.Value is String)
                            {
                                _maxAsynxRecords = Int32.Parse(xamlReader.Value as String, TypeConverterHelper.InvariantEnglishUS);
                            } 
                        }
                    } 
                    else if (xamlReader.NodeType == System.Xaml.XamlNodeType.EndMember) 
                    {
                        lastPropWasSyncMode = false; 
                        lastPropWasSyncRecords = false;
                    }

                    if (async && rootObject != null) 
                        break;
                } 
            } 
            catch (Exception e)
            { 
                // Don't wrap critical exceptions or already-wrapped exceptions.
                if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !ShouldReWrapException(e, parserContext.BaseUri))
                {
                    throw; 
                }
                RewrapException(e, parserContext.BaseUri); 
            } 

            if (!_textReader.IsEof) 
            {
                Post();
                //ThreadStart threadStart = new ThreadStart(ReadXamlAsync);
                //Thread thread = new Thread(threadStart); 
                //thread.Start();
            } 
            else 
            {
                TreeBuildComplete(); 
            }

            if (rootObject is DependencyObject)
            { 
                if (parserContext.BaseUri != null && !String.IsNullOrEmpty(parserContext.BaseUri.ToString()))
                    (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, parserContext.BaseUri); 
                //else 
                //    (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, BaseUriHelper.PackAppBaseUri);
                WpfXamlLoader.EnsureXmlNamespaceMaps(rootObject, schemaContext); 
            }

            Application app = rootObject as Application;
            if (app != null) 
            {
                app.ApplicationMarkupBaseUri = GetBaseUri(settings.BaseUri); 
            } 

            return rootObject; 
        }
Exemple #21
0
        public static Settings Load()
        {
            var fn = filename();
            if (!File.Exists(fn))
                return new Settings();

            Settings ret;

            using (var sr = new StreamReader(fn))
            using (var xr = new XamlXmlReader(sr, App.ctx))
            using (var xw = new XamlObjectWriter(App.ctx))
            {
                XamlServices.Transform(xr, xw);

                ret = (Settings)xw.Result;
            }
            return ret;
        }
Exemple #22
0
			public XamlObjectWriterServiceProvider (XamlObjectWriter writer)
			{
				namespace_resolver = new NamespaceResolver (writer.namespaces);
				type_resolver = new XamlTypeResolver (namespace_resolver, writer.SchemaContext);
			}
Exemple #23
0
        private void LoadTemplateXaml(System.Xaml.XamlReader templateReader, XamlObjectWriter currentWriter)
        {
            try
            {
                int nestedTemplateDepth = 0;

                // Prepare to provide source info if needed
                IXamlLineInfoConsumer lineInfoConsumer = null;
                IXamlLineInfo lineInfo = null;
                if (XamlSourceInfoHelper.IsXamlSourceInfoEnabled)
                {
                    lineInfo = templateReader as IXamlLineInfo;
                    if (lineInfo != null)
                    {
                        lineInfoConsumer = currentWriter as IXamlLineInfoConsumer;
                    }
                }

                while (templateReader.Read())
                {
                    if (lineInfoConsumer != null)
                    {
                        lineInfoConsumer.SetLineInfo(lineInfo.LineNumber, lineInfo.LinePosition);
                    }

                    // We need to call the ObjectWriter first because x:Name & RNPA needs to be registered
                    // before we call InvalidateProperties.
                    currentWriter.WriteNode(templateReader);

                    switch (templateReader.NodeType)
                    {
                        case System.Xaml.XamlNodeType.None:
                        case System.Xaml.XamlNodeType.NamespaceDeclaration:
                            break;
                        case System.Xaml.XamlNodeType.StartObject:
                            {
                                // If parent is a namescope or was inside a nested namescope, make the new frame inside a nested namescope
                                // See usage in HandleAfterBeginInit()
                                bool isInsideNameScope = Names.Depth > 0 && (IsNameScope(Names.CurrentFrame.Type) || Names.CurrentFrame.InsideNameScope);
                                Names.PushScope();
                                Names.CurrentFrame.Type = templateReader.Type;
                                if (isInsideNameScope)
                                {
                                    Names.CurrentFrame.InsideNameScope = true;
                                }
                            }
                            break;

                        case System.Xaml.XamlNodeType.GetObject:
                            {
                                // If parent is a namescope or was inside a nested namescope, make the new frame inside a nested namescope
                                bool isInsideNameScope = IsNameScope(Names.CurrentFrame.Type) || Names.CurrentFrame.InsideNameScope;
                                Names.PushScope();
                                Names.CurrentFrame.Type = Names.PreviousFrame.Property.Type;
                                if (isInsideNameScope)
                                {
                                    Names.CurrentFrame.InsideNameScope = true;
                                }
                            }
                            break;

                        case System.Xaml.XamlNodeType.StartMember:
                            Names.CurrentFrame.Property = templateReader.Member;
                            if (templateReader.Member.DeferringLoader != null)
                            {
                                nestedTemplateDepth += 1;
                            }
                            break;

                        case System.Xaml.XamlNodeType.EndMember:
                            if (Names.CurrentFrame.Property.DeferringLoader != null)
                            {
                                nestedTemplateDepth -= 1;
                            }
                            Names.CurrentFrame.Property = null;
                            break;

                        case System.Xaml.XamlNodeType.EndObject:
                            Names.PopScope();
                            break;

                        case System.Xaml.XamlNodeType.Value:
                            if (nestedTemplateDepth == 0)
                            {
                                if (Names.CurrentFrame.Property == XamlLanguage.ConnectionId)
                                {
                                    if (_styleConnector != null)
                                    {
                                        _styleConnector.Connect((int)templateReader.Value, Names.CurrentFrame.Instance);
                                    }
                                }
                            }
                            break;

                        default:
                            Debug.Assert(false, "Unknown enum value");
                            break;
                    }
                }
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e) || e is System.Windows.Markup.XamlParseException)
                {
                    throw;
                }
                System.Windows.Markup.XamlReader.RewrapException(e, null);
            }
        }
Exemple #24
0
        internal static void TransformNodes(System.Xaml.XamlReader xamlReader, System.Xaml.XamlObjectWriter xamlWriter,
                                            bool onlyLoadOneNode,
                                            bool skipJournaledProperties,
                                            bool shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer,
                                            XamlContextStack <WpfXamlFrame> stack,
                                            IStyleConnector styleConnector)
        {
            while (xamlReader.Read())
            {
                if (shouldPassLineNumberInfo)
                {
                    if (xamlLineInfo.LineNumber != 0)
                    {
                        xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition);
                    }
                }

                switch (xamlReader.NodeType)
                {
                case System.Xaml.XamlNodeType.NamespaceDeclaration:
                    xamlWriter.WriteNode(xamlReader);
                    if (stack.Depth == 0 || stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                        // Need to create an XmlnsDictionary.
                        // Look up stack to see if we have one earlier
                        //  If so, use that.  Otherwise new a xmlnsDictionary
                        WpfXamlFrame iteratorFrame = stack.CurrentFrame;
                        while (iteratorFrame != null)
                        {
                            if (iteratorFrame.XmlnsDictionary != null)
                            {
                                stack.CurrentFrame.XmlnsDictionary =
                                    new XmlnsDictionary(iteratorFrame.XmlnsDictionary);
                                break;
                            }
                            iteratorFrame = (WpfXamlFrame)iteratorFrame.Previous;
                        }
                        if (stack.CurrentFrame.XmlnsDictionary == null)
                        {
                            stack.CurrentFrame.XmlnsDictionary =
                                new XmlnsDictionary();
                        }
                    }
                    stack.CurrentFrame.XmlnsDictionary.Add(xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace);
                    break;

                case System.Xaml.XamlNodeType.StartObject:
                    xamlWriter.WriteNode(xamlReader);
                    // If there's a frame but no Type, that means there
                    // was a namespace. Just set the Type
                    if (stack.Depth != 0 && stack.CurrentFrame.Type == null)
                    {
                        stack.CurrentFrame.Type = xamlReader.Type;
                    }
                    else
                    {
                        // Propagate the FreezeFreezable property from the current stack frame
                        stack.PushScope();
                        stack.CurrentFrame.Type = xamlReader.Type;
                        if (stack.PreviousFrame.FreezeFreezable)
                        {
                            stack.CurrentFrame.FreezeFreezable = true;
                        }
                    }
                    break;

                case System.Xaml.XamlNodeType.GetObject:
                    xamlWriter.WriteNode(xamlReader);
                    // If there wasn't a namespace node before this get object, need to pushScope.
                    if (stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                    }
                    stack.CurrentFrame.Type = stack.PreviousFrame.Property.Type;
                    break;

                case System.Xaml.XamlNodeType.EndObject:
                    xamlWriter.WriteNode(xamlReader);
                    // Freeze if required
                    if (stack.CurrentFrame.FreezeFreezable)
                    {
                        Freezable freezable = xamlWriter.Result as Freezable;
                        if (freezable != null && freezable.CanFreeze)
                        {
                            freezable.Freeze();
                        }
                    }
                    DependencyObject dependencyObject = xamlWriter.Result as DependencyObject;
                    if (dependencyObject != null && stack.CurrentFrame.XmlSpace.HasValue)
                    {
                        XmlAttributeProperties.SetXmlSpace(dependencyObject, stack.CurrentFrame.XmlSpace.Value ? "default" : "preserve");
                    }
                    stack.PopScope();
                    break;

                case System.Xaml.XamlNodeType.StartMember:
                    // ObjectWriter should NOT process PresentationOptions:Freeze directive since it is Unknown
                    // The space directive node stream should not be written because it induces object instantiation,
                    // and the Baml2006Reader can produce space directives prematurely.
                    if (!(xamlReader.Member.IsDirective && xamlReader.Member == XamlReaderHelper.Freeze) &&
                        xamlReader.Member != XmlSpace.Value &&
                        xamlReader.Member != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }

                    stack.CurrentFrame.Property = xamlReader.Member;
                    if (skipJournaledProperties)
                    {
                        if (!stack.CurrentFrame.Property.IsDirective)
                        {
                            System.Windows.Baml2006.WpfXamlMember wpfMember = stack.CurrentFrame.Property as System.Windows.Baml2006.WpfXamlMember;
                            if (wpfMember != null)
                            {
                                DependencyProperty prop = wpfMember.DependencyProperty;

                                if (prop != null)
                                {
                                    FrameworkPropertyMetadata metadata = prop.GetMetadata(stack.CurrentFrame.Type.UnderlyingType) as FrameworkPropertyMetadata;
                                    if (metadata != null && metadata.Journal == true)
                                    {
                                        //
                                        int count = 1;
                                        while (xamlReader.Read())
                                        {
                                            switch (xamlReader.NodeType)
                                            {
                                            case System.Xaml.XamlNodeType.StartMember:
                                                count++;
                                                break;

                                            case System.Xaml.XamlNodeType.EndMember:
                                                count--;
                                                if (count == 0)
                                                {
                                                    xamlWriter.WriteNode(xamlReader);
                                                }
                                                break;
                                            }
                                            if (count == 0)
                                            {
                                                break;
                                            }
                                        }
                                        // shouldn't this have been a XamlReader.Skip()?
                                        System.Diagnostics.Debug.Assert(count == 0, "Mismatch StartMember/EndMember");
                                    }
                                }
                            }
                        }
                    }
                    break;

                case System.Xaml.XamlNodeType.EndMember:
                    WpfXamlFrame currentFrame    = stack.CurrentFrame;
                    XamlMember   currentProperty = currentFrame.Property;
                    // ObjectWriter should not process PresentationOptions:Freeze directive nodes since it is unknown
                    // The space directive node stream should not be written because it induces object instantiation,
                    // and the Baml2006Reader can produce space directives prematurely.
                    if (!(currentProperty.IsDirective && currentProperty == XamlReaderHelper.Freeze) &&
                        currentProperty != XmlSpace.Value &&
                        currentProperty != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }
                    currentFrame.Property = null;
                    break;

                case System.Xaml.XamlNodeType.Value:
                    if (stack.CurrentFrame.Property.IsDirective && stack.CurrentFrame.Property == XamlLanguage.Shared)
                    {
                        bool isShared;
                        if (bool.TryParse(xamlReader.Value as string, out isShared))
                        {
                            if (!isShared)
                            {
                                if (!(xamlReader is Baml2006Reader))
                                {
                                    throw new XamlParseException(SR.Get(SRID.SharedAttributeInLooseXaml));
                                }
                            }
                        }
                    }
                    // ObjectWriter should not process PresentationOptions:Freeze directive nodes since it is unknown
                    if (stack.CurrentFrame.Property.IsDirective && stack.CurrentFrame.Property == XamlReaderHelper.Freeze)
                    {
                        bool freeze = Convert.ToBoolean(xamlReader.Value, TypeConverterHelper.InvariantEnglishUS);
                        stack.CurrentFrame.FreezeFreezable = freeze;
                        var bamlReader = xamlReader as System.Windows.Baml2006.Baml2006Reader;
                        if (bamlReader != null)
                        {
                            bamlReader.FreezeFreezables = freeze;
                        }
                    }
                    // The space directive node stream should not be written because it induces object instantiation,
                    // and the Baml2006Reader can produce space directives prematurely.
                    else if (stack.CurrentFrame.Property == XmlSpace.Value || stack.CurrentFrame.Property == XamlLanguage.Space)
                    {
                        if (typeof(DependencyObject).IsAssignableFrom(stack.CurrentFrame.Type.UnderlyingType))
                        {
                            System.Diagnostics.Debug.Assert(xamlReader.Value is string, "XmlAttributeProperties.XmlSpaceProperty has the type string.");
                            stack.CurrentFrame.XmlSpace = (string)xamlReader.Value == "default";
                        }
                    }
                    else
                    {
                        // Ideally we should check if we're inside FrameworkTemplate's Content and not register those.
                        // However, checking if the instance is null accomplishes the same with a much smaller perf impact.
                        if (styleConnector != null &&
                            stack.CurrentFrame.Instance != null &&
                            stack.CurrentFrame.Property == XamlLanguage.ConnectionId &&
                            typeof(Style).IsAssignableFrom(stack.CurrentFrame.Type.UnderlyingType))
                        {
                            styleConnector.Connect((int)xamlReader.Value, stack.CurrentFrame.Instance);
                        }

                        xamlWriter.WriteNode(xamlReader);
                    }
                    break;

                default:
                    xamlWriter.WriteNode(xamlReader);
                    break;
                }

                //Only do this loop for one node if loadAsync
                if (onlyLoadOneNode)
                {
                    return;
                }
            }
        }
        internal static void TransformNodes(System.Xaml.XamlReader xamlReader, System.Xaml.XamlObjectWriter xamlWriter,
                                            bool onlyLoadOneNode,
                                            bool skipJournaledProperties,
                                            bool shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer,
                                            XamlContextStack <WpfXamlFrame> stack,
                                            IStyleConnector styleConnector)
        {
            while (xamlReader.Read())
            {
                if (shouldPassLineNumberInfo)
                {
                    if (xamlLineInfo.LineNumber != 0)
                    {
                        xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition);
                    }
                }

                switch (xamlReader.NodeType)
                {
                case System.Xaml.XamlNodeType.NamespaceDeclaration:
                    xamlWriter.WriteNode(xamlReader);
                    if (stack.Depth == 0 || stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                        // Need to create an XmlnsDictionary.
                        // Look up stack to see if we have one earlier
                        //  If so, use that.  Otherwise new a xmlnsDictionary
                        WpfXamlFrame iteratorFrame = stack.CurrentFrame;
                        while (iteratorFrame != null)
                        {
                            if (iteratorFrame.XmlnsDictionary != null)
                            {
                                stack.CurrentFrame.XmlnsDictionary =
                                    new XmlnsDictionary(iteratorFrame.XmlnsDictionary);
                                break;
                            }
                            iteratorFrame = (WpfXamlFrame)iteratorFrame.Previous;
                        }
                        if (stack.CurrentFrame.XmlnsDictionary == null)
                        {
                            stack.CurrentFrame.XmlnsDictionary =
                                new XmlnsDictionary();
                        }
                    }
                    stack.CurrentFrame.XmlnsDictionary.Add(xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace);
                    break;

                case System.Xaml.XamlNodeType.StartObject:
                    WriteStartObject(xamlReader, xamlWriter, stack);
                    break;

                case System.Xaml.XamlNodeType.GetObject:
                    xamlWriter.WriteNode(xamlReader);
                    // If there wasn't a namespace node before this get object, need to pushScope.
                    if (stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                    }
                    stack.CurrentFrame.Type = stack.PreviousFrame.Property.Type;
                    break;

                case System.Xaml.XamlNodeType.EndObject:
                    xamlWriter.WriteNode(xamlReader);
                    // Freeze if required
                    if (stack.CurrentFrame.FreezeFreezable)
                    {
                        Freezable freezable = xamlWriter.Result as Freezable;
                        if (freezable != null && freezable.CanFreeze)
                        {
                            freezable.Freeze();
                        }
                    }
                    DependencyObject dependencyObject = xamlWriter.Result as DependencyObject;
                    if (dependencyObject != null && stack.CurrentFrame.XmlSpace.HasValue)
                    {
                        XmlAttributeProperties.SetXmlSpace(dependencyObject, stack.CurrentFrame.XmlSpace.Value ? "default" : "preserve");
                    }
                    stack.PopScope();
                    break;

                case System.Xaml.XamlNodeType.StartMember:
                    // ObjectWriter should NOT process PresentationOptions:Freeze directive since it is Unknown
                    // The space directive node stream should not be written because it induces object instantiation,
                    // and the Baml2006Reader can produce space directives prematurely.
                    if (!(xamlReader.Member.IsDirective && xamlReader.Member == XamlReaderHelper.Freeze) &&
                        xamlReader.Member != XmlSpace.Value &&
                        xamlReader.Member != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }

                    stack.CurrentFrame.Property = xamlReader.Member;
                    if (skipJournaledProperties)
                    {
                        if (!stack.CurrentFrame.Property.IsDirective)
                        {
                            System.Windows.Baml2006.WpfXamlMember wpfMember = stack.CurrentFrame.Property as System.Windows.Baml2006.WpfXamlMember;
                            if (wpfMember != null)
                            {
                                DependencyProperty prop = wpfMember.DependencyProperty;

                                if (prop != null)
                                {
                                    FrameworkPropertyMetadata metadata = prop.GetMetadata(stack.CurrentFrame.Type.UnderlyingType) as FrameworkPropertyMetadata;
                                    if (metadata != null && metadata.Journal == true)
                                    {
                                        // Ignore the BAML for this member, unless it declares a value that wasn't journaled - namely a binding or a dynamic resource
                                        int count = 1;
                                        while (xamlReader.Read())
                                        {
                                            switch (xamlReader.NodeType)
                                            {
                                            case System.Xaml.XamlNodeType.StartMember:
                                                count++;
                                                break;

                                            case System.Xaml.XamlNodeType.StartObject:
                                                XamlType xamlType            = xamlReader.Type;
                                                XamlType bindingBaseType     = xamlType.SchemaContext.GetXamlType(typeof(BindingBase));
                                                XamlType dynamicResourceType = xamlType.SchemaContext.GetXamlType(typeof(DynamicResourceExtension));
                                                if (count == 1 && (xamlType.CanAssignTo(bindingBaseType) || xamlType.CanAssignTo(dynamicResourceType)))
                                                {
                                                    count = 0;
                                                    WriteStartObject(xamlReader, xamlWriter, stack);
                                                }
                                                break;

                                            case System.Xaml.XamlNodeType.EndMember:
                                                count--;
                                                if (count == 0)
                                                {
                                                    xamlWriter.WriteNode(xamlReader);
                                                    stack.CurrentFrame.Property = null;
                                                }
                                                break;

                                            case System.Xaml.XamlNodeType.Value:
                                                DynamicResourceExtension value = xamlReader.Value as DynamicResourceExtension;
                                                if (value != null)
                                                {
                                                    WriteValue(xamlReader, xamlWriter, stack, styleConnector);
                                                }
                                                break;
                                            }
                                            if (count == 0)
                                            {
                                                break;
                                            }
                                        }

                                        System.Diagnostics.Debug.Assert(count == 0, "Mismatch StartMember/EndMember");
                                    }
                                }
                            }
                        }
                    }
                    break;

                case System.Xaml.XamlNodeType.EndMember:
                    WpfXamlFrame currentFrame    = stack.CurrentFrame;
                    XamlMember   currentProperty = currentFrame.Property;
                    // ObjectWriter should not process PresentationOptions:Freeze directive nodes since it is unknown
                    // The space directive node stream should not be written because it induces object instantiation,
                    // and the Baml2006Reader can produce space directives prematurely.
                    if (!(currentProperty.IsDirective && currentProperty == XamlReaderHelper.Freeze) &&
                        currentProperty != XmlSpace.Value &&
                        currentProperty != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }
                    currentFrame.Property = null;
                    break;

                case System.Xaml.XamlNodeType.Value:
                    WriteValue(xamlReader, xamlWriter, stack, styleConnector);
                    break;

                default:
                    xamlWriter.WriteNode(xamlReader);
                    break;
                }

                //Only do this loop for one node if loadAsync
                if (onlyLoadOneNode)
                {
                    return;
                }
            }
        }
Exemple #26
0
		public XamlObjectWriterInternal (XamlObjectWriter source, XamlSchemaContext schemaContext, XamlWriterStateManager manager)
			: base (schemaContext, manager)
		{
			this.source = source;
			this.sctx = schemaContext;
			var ext = source.Settings.ExternalNameScope;
			name_scope = ext != null && source.Settings.RegisterNamesOnExternalNamescope ? ext : new NameScope (ext);
		}
Exemple #27
0
        private object LoadAsync(XmlReader reader, ParserContext parserContext)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (parserContext == null)
            {
                parserContext = new ParserContext();
            }

            _xmlReader = reader;
            object rootObject = null;

            if (parserContext.BaseUri == null ||
                String.IsNullOrEmpty(parserContext.BaseUri.ToString()))
            {
                if (reader.BaseURI == null ||
                    String.IsNullOrEmpty(reader.BaseURI.ToString()))
                {
                    parserContext.BaseUri = BaseUriHelper.PackAppBaseUri;
                }
                else
                {
                    parserContext.BaseUri = new Uri(reader.BaseURI);
                }
            }
            _baseUri = parserContext.BaseUri;
            System.Xaml.XamlXmlReaderSettings settings = new System.Xaml.XamlXmlReaderSettings();
            settings.IgnoreUidsOnPropertyElements = true;
            settings.BaseUri         = parserContext.BaseUri;
            settings.ProvideLineInfo = true;
            XamlSchemaContext schemaContext = parserContext.XamlTypeMapper != null ?
                                              parserContext.XamlTypeMapper.SchemaContext : GetWpfSchemaContext();

            try
            {
                _textReader = new System.Xaml.XamlXmlReader(reader, schemaContext, settings);

                _stack = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame());

                System.Xaml.XamlObjectWriterSettings objectSettings = XamlReader.CreateObjectWriterSettings();
                objectSettings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args)
                {
                    if (rootObject == null)
                    {
                        rootObject      = args.Instance;
                        _styleConnector = rootObject as IStyleConnector;
                    }

                    UIElement uiElement = args.Instance as UIElement;
                    if (uiElement != null)
                    {
                        uiElement.SetPersistId(_persistId++);
                    }

                    DependencyObject dObject = args.Instance as DependencyObject;
                    if (dObject != null && _stack.CurrentFrame.XmlnsDictionary != null)
                    {
                        XmlnsDictionary dictionary = _stack.CurrentFrame.XmlnsDictionary;
                        dictionary.Seal();

                        XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary);
                    }
                };

                _objectWriter            = new System.Xaml.XamlObjectWriter(_textReader.SchemaContext, objectSettings);
                _parseCancelled          = false;
                _skipJournaledProperties = parserContext.SkipJournaledProperties;

                XamlMember synchronousModeProperty   = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "SynchronousMode");
                XamlMember synchronousRecordProperty = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "AsyncRecords");

                System.Xaml.XamlReader xamlReader = _textReader;

                IXamlLineInfo         xamlLineInfo         = xamlReader as IXamlLineInfo;
                IXamlLineInfoConsumer xamlLineInfoConsumer = _objectWriter as IXamlLineInfoConsumer;
                bool shouldPassLineNumberInfo = false;
                if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) &&
                    (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo))
                {
                    shouldPassLineNumberInfo = true;
                }

                bool async = false;
                bool lastPropWasSyncMode    = false;
                bool lastPropWasSyncRecords = false;

                while (!_textReader.IsEof)
                {
                    WpfXamlLoader.TransformNodes(xamlReader, _objectWriter, true /*onlyLoadOneNode*/, _skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, _stack, _styleConnector);

                    if (xamlReader.NodeType == System.Xaml.XamlNodeType.StartMember)
                    {
                        if (xamlReader.Member == synchronousModeProperty)
                        {
                            lastPropWasSyncMode = true;
                        }
                        else if (xamlReader.Member == synchronousRecordProperty)
                        {
                            lastPropWasSyncRecords = true;
                        }
                    }
                    else if (xamlReader.NodeType == System.Xaml.XamlNodeType.Value)
                    {
                        if (lastPropWasSyncMode == true)
                        {
                            if (xamlReader.Value as String == "Async")
                            {
                                async = true;
                            }
                        }
                        else if (lastPropWasSyncRecords == true)
                        {
                            if (xamlReader.Value is int)
                            {
                                _maxAsynxRecords = (int)xamlReader.Value;
                            }
                            else if (xamlReader.Value is String)
                            {
                                _maxAsynxRecords = Int32.Parse(xamlReader.Value as String, TypeConverterHelper.InvariantEnglishUS);
                            }
                        }
                    }
                    else if (xamlReader.NodeType == System.Xaml.XamlNodeType.EndMember)
                    {
                        lastPropWasSyncMode    = false;
                        lastPropWasSyncRecords = false;
                    }

                    if (async && rootObject != null)
                    {
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                // Don't wrap critical exceptions or already-wrapped exceptions.
                if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !ShouldReWrapException(e, parserContext.BaseUri))
                {
                    throw;
                }
                RewrapException(e, parserContext.BaseUri);
            }

            if (!_textReader.IsEof)
            {
                Post();
                //ThreadStart threadStart = new ThreadStart(ReadXamlAsync);
                //Thread thread = new Thread(threadStart);
                //thread.Start();
            }
            else
            {
                TreeBuildComplete();
            }

            if (rootObject is DependencyObject)
            {
                if (parserContext.BaseUri != null && !String.IsNullOrEmpty(parserContext.BaseUri.ToString()))
                {
                    (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, parserContext.BaseUri);
                }
                //else
                //    (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, BaseUriHelper.PackAppBaseUri);
                WpfXamlLoader.EnsureXmlNamespaceMaps(rootObject, schemaContext);
            }

            Application app = rootObject as Application;

            if (app != null)
            {
                app.ApplicationMarkupBaseUri = GetBaseUri(settings.BaseUri);
            }

            return(rootObject);
        }
Exemple #28
0
        private static object Load(System.Xaml.XamlReader xamlReader, IXamlObjectWriterFactory writerFactory,
            bool skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) 
        {
            XamlObjectWriter xamlWriter = null; 
            XamlContextStack<WpfXamlFrame> stack = new XamlContextStack<WpfXamlFrame>(() => new WpfXamlFrame()); 
            int persistId = 1;
 
            settings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args)
            {
                if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose))
                { 
                    IXamlLineInfo ixli = xamlReader as IXamlLineInfo;
 
                    int lineNumber = -1; 
                    int linePosition = -1;
 
                    if (ixli != null && ixli.HasLineInfo)
                    {
                        lineNumber = ixli.LineNumber;
                        linePosition = ixli.LinePosition; 
                    }
 
                    EventTrace.EventProvider.TraceEvent( 
                        EventTrace.Event.WClientParseXamlBamlInfo,
                        EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, 
                        args.Instance == null ? 0 : PerfService.GetPerfElementID(args.Instance),
                        lineNumber,
                        linePosition);
                } 

                UIElement uiElement = args.Instance as UIElement; 
                if (uiElement != null) 
                {
                    uiElement.SetPersistId(persistId++); 
                }

                DependencyObject dObject = args.Instance as DependencyObject;
                if (dObject != null && stack.CurrentFrame.XmlnsDictionary != null) 
                {
                    XmlnsDictionary dictionary = stack.CurrentFrame.XmlnsDictionary; 
                    dictionary.Seal(); 

                    XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary); 
                }

                stack.CurrentFrame.Instance = args.Instance;
            }; 
            if (writerFactory != null)
            { 
                xamlWriter = writerFactory.GetXamlObjectWriter(settings); 
            }
            else 
            {
                xamlWriter = new System.Xaml.XamlObjectWriter(xamlReader.SchemaContext, settings);
            }
 
            IXamlLineInfo xamlLineInfo = null;
            try 
            { 
                //Handle Line Numbers
                xamlLineInfo = xamlReader as IXamlLineInfo; 
                IXamlLineInfoConsumer xamlLineInfoConsumer = xamlWriter as IXamlLineInfoConsumer;
                bool shouldPassLineNumberInfo = false;
                if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo)
                    && (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)) 
                {
                    shouldPassLineNumberInfo = true; 
                } 

                IStyleConnector styleConnector = rootObject as IStyleConnector; 
                TransformNodes(xamlReader, xamlWriter,
                    false /*onlyLoadOneNode*/,
                    skipJournaledProperties,
                    shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, 
                    stack, styleConnector);
                xamlWriter.Close(); 
                return xamlWriter.Result; 
            }
            catch (Exception e) 
            {
                // Don't wrap critical exceptions or already-wrapped exceptions.
                if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !XamlReader.ShouldReWrapException(e, baseUri))
                { 
                    throw;
                } 
                XamlReader.RewrapException(e, xamlLineInfo, baseUri); 
                return null;    // this should never be executed
            } 
        }
        private void LoadTemplateXaml(System.Xaml.XamlReader templateReader, XamlObjectWriter currentWriter)
        { 
            try
            {
                while (templateReader.Read())
                { 
                    // We need to call the ObjectWriter first because x:Name & RNPA needs to be registered
                    // before we call InvalidateProperties. 
                    currentWriter.WriteNode(templateReader); 

                    switch (templateReader.NodeType) 
                    {
                        case System.Xaml.XamlNodeType.None:
                        case System.Xaml.XamlNodeType.NamespaceDeclaration:
                            break; 
                        case System.Xaml.XamlNodeType.StartObject:
                            { 
                                // If parent is a namescope or was inside a nested namescope, make the new frame inside a nested namescope 
                                bool isInsideNameScope = Names.Depth > 0 && (IsNameScope(Names.CurrentFrame.Type) || Names.CurrentFrame.InsideNameScope);
                                Names.PushScope(); 
                                Names.CurrentFrame.Type = templateReader.Type;
                                if (isInsideNameScope)
                                {
                                    Names.CurrentFrame.InsideNameScope = true; 
                                }
                            } 
                            break; 
                        case System.Xaml.XamlNodeType.GetObject:
                            { 
                                // If parent is a namescope or was inside a nested namescope, make the new frame inside a nested namescope
                                bool isInsideNameScope = IsNameScope(Names.CurrentFrame.Type) || Names.CurrentFrame.InsideNameScope;
                                Names.PushScope();
                                Names.CurrentFrame.Type = Names.PreviousFrame.Property.Type; 
                                if (isInsideNameScope)
                                { 
                                    Names.CurrentFrame.InsideNameScope = true; 
                                }
                            } 
                            break;
                        case System.Xaml.XamlNodeType.StartMember:
                            Names.CurrentFrame.Property = templateReader.Member;
                            break; 
                        case System.Xaml.XamlNodeType.EndMember:
                            Names.CurrentFrame.Property = null; 
                            break; 
                        case System.Xaml.XamlNodeType.EndObject:
                            Names.PopScope(); 
                            break;
                        case System.Xaml.XamlNodeType.Value:
                            if (Names.CurrentFrame.Property == XamlLanguage.ConnectionId)
                            { 
                                if (_styleConnector != null)
                                { 
                                    _styleConnector.Connect((int)templateReader.Value, Names.CurrentFrame.Instance); 
                                }
                            } 
                            break;
                        default:
                            Debug.Assert(false, "Unknown enum value");
                            break; 
                    }
                } 
            } 
            catch (Exception e)
            { 
                if (CriticalExceptions.IsCriticalException(e) || e is System.Windows.Markup.XamlParseException)
                {
                    throw;
                } 
                System.Windows.Markup.XamlReader.RewrapException(e, null);
            } 
        } 
Exemple #30
0
 public XamlObjectWriterInternal(XamlObjectWriter source, XamlSchemaContext schemaContext, XamlWriterStateManager manager)
     : this(source, schemaContext, manager, null)
 {
 }