Parsing class used to create an Windows Presentation Platform Tree
Exemplo n.º 1
0
        private async Task DownloadFileAsync2(Uri uri, string name)
        {
            try
            {
                var file = Path.Combine(Dispatcher.Invoke(() => TempPath), name);

                if (File.Exists(file))
                    File.Delete(file);

                using (var webClient = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials })
                    await webClient.DownloadFileTaskAsync(uri, file);

                //Saves the template for later, when exporting the translation.
                if (name.EndsWith("en.xaml"))
                    _resourceTemplate = File.ReadAllText(file);

                using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var dictionary = (ResourceDictionary)XamlReader.Load(fs, new ParserContext { XmlSpace = "preserve" });
                    //var dictionary = new ResourceDictionary();
                    dictionary.Source = new Uri(Path.GetFullPath(file), UriKind.Absolute);

                    _resourceList.Add(dictionary);

                    if (name.EndsWith("en.xaml"))
                        Application.Current.Resources.MergedDictionaries.Add(dictionary);
                }
            }
            catch (Exception ex)
            {
                Dispatcher.Invoke(() => Dialog.Ok("Translator", "Translator - Downloading File", ex.Message));
            }
        }
Exemplo n.º 2
0
		/// <summary>
		/// Parses an object from XAML
		/// </summary>
		/// <param name="xaml">Xaml.</param>
		public static object Parse (string xaml) {
			var xdoc = XDocument.Parse (xaml);
			var reader = new XamlReader ();
			reader.Document = xdoc;
			reader.ReadNamespaces ();
			return reader.ReadElement (xdoc.Root, null, null, null,null);
		}
        // <summary>
        // Creates an object instance from a Baml stream and it's Uri 
        // </summary>
        internal static object BamlConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter) 
        { 
            asyncObjectConverter = null;
 
            // If this stream comes from outside the application throw
            //
            if (!BaseUriHelper.IsPackApplicationUri(baseUri))
            { 
                throw new InvalidOperationException(SR.Get(SRID.BamlIsNotSupportedOutsideOfApplicationResources));
            } 
 
            // If this stream comes from a content file also throw
            Uri partUri = PackUriHelper.GetPartUri(baseUri); 
            string partName, assemblyName, assemblyVersion, assemblyKey;
            BaseUriHelper.GetAssemblyNameAndPart(partUri, out partName, out assemblyName, out assemblyVersion, out assemblyKey);
            if (ContentFileHelper.IsContentFile(partName))
            { 
                throw new InvalidOperationException(SR.Get(SRID.BamlIsNotSupportedOutsideOfApplicationResources));
            } 
 
            ParserContext pc = new ParserContext();
 
            pc.BaseUri = baseUri;
            pc.SkipJournaledProperties = isJournalNavigation;

            return Application.LoadBamlStreamWithSyncInfo(stream, pc); 
        }
Exemplo n.º 4
0
        //private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        public static ResourceDictionary GetDictionary(string relativePath = @"Resources\Dictionaries")
        {
            var mergedDictionary = new ResourceDictionary();
            string path = Path.Combine(HttpRuntime.AppDomainAppPath, relativePath);

            if (Directory.Exists(path))
                foreach (string fileName in Directory.GetFiles(path).Where(f => f.EndsWith(".xaml")))
                    using (var fs = new FileStream(fileName, FileMode.Open))
                    {
                        try
                        {
                            var xr = new XamlReader();

                            var tmp = (ResourceDictionary)XamlReader.Load(fs);
                            foreach (string key in tmp.Keys)
                                if (tmp[key] is Canvas)
                                {
                                    mergedDictionary.Add(key, tmp[key]);
                                }

                        }
                        catch (Exception)
                        {
                            //_logger.Error(ex.Message);
                        }
                    }
            else
                Directory.CreateDirectory(path);

            return mergedDictionary;
        }
Exemplo n.º 5
0
        void LoadResourceDictionary(string filePath)
        {
            var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            var dictionary = new XamlReader().LoadAsync(stream);

            Current.Resources.MergedDictionaries.Add(dictionary as ResourceDictionary);
        }
 private void LoadThemeResourceFromFile(Uri resorceUri)
 {
     //TODO: Implement external theme loading
     try
     {
         StreamResourceInfo info = Application.GetRemoteStream(resorceUri);
         System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
         ResourceDictionary resource             = (ResourceDictionary)reader.LoadAsync(info.Stream);
         AppearanceManager.Current.AddTheme(resource, true);
     }
     catch (IOException)
     {
         // do something
     }
 }
Exemplo n.º 7
0
        //----------------------------------------------------- 
        //
        //  Internal Static Methods 
        // 
        //-----------------------------------------------------
 
        #region internal static methods

        // The delegate that we are calling is responsible for closing the stream
        internal static object GetObjectAndCloseStream(Stream s, ContentType contentType, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter) 
        {
            object objToReturn = null; 
            asyncObjectConverter = null; 

            if (contentType != null) 
            {
                StreamToObjectFactoryDelegate d;
                if (_objectConverters.TryGetValue(contentType, out d))
                { 
                    objToReturn = d(s, baseUri, canUseTopLevelBrowser, sandboxExternalContent, allowAsync, isJournalNavigation, out asyncObjectConverter);
                } 
            } 

            return objToReturn; 
        }
Exemplo n.º 8
0
        public static void LoadApplicationResources()
        {
            Uri uri = new Uri("pack://application:,,,/CodeOwls.SeeShell.Visualizations;component/DataTemplates.xaml");

            try
            {
                var info = Application.GetResourceStream(uri);
                var reader = new XamlReader();

                var resources = (ResourceDictionary) reader.LoadAsync(info.Stream);

                Application.Current.Resources.MergedDictionaries.Add(resources);
            }
            catch
            {
            }
        }
Exemplo n.º 9
0
        public void TypeMapperWithNamespaceEntry()
        {
            XamlTypeMapper typeMapper = new XamlTypeMapper(new string[0], new NamespaceMapEntry[] {
                new NamespaceMapEntry("http://elements", "XamlTestClasses", "Test.Elements")
            });
            ParserContext pc = new ParserContext {
                XamlTypeMapper = typeMapper
            };

            object result = System.Windows.Markup.XamlReader.Parse(ElementXaml, pc);

            Assert.IsInstanceOfType(typeof(Element), result);

            MemoryStream stream = new MemoryStream(Encoding.Default.GetBytes(ElementXaml));

            result = new System.Windows.Markup.XamlReader().LoadAsync(stream, pc);
            Assert.IsInstanceOfType(typeof(Element), result);
        }
Exemplo n.º 10
0
        // Perform the Open action.
        private void DocumentOpen(Object sender, ExecutedRoutedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.DefaultExt = ".rects";
            dlg.Filter = "Rectangle Files (.rects)|*.rects|All Files (*.*)|*.*";

            if (dlg.ShowDialog() == true)
            {
                // Open the file.
                XamlReader reader = new XamlReader();
                FileStream fs = File.OpenRead(dlg.FileName);
                try
                {
                    // Read the Canvas stored in the file.
                    Canvas new_canvas = (Canvas)XamlReader.Load(fs);

                    // Display the new Canvas.
                    new_canvas.Name = "cvsDrawing";
                    new_canvas.MouseDown += cvsDrawing_MouseDown;
                    new_canvas.MouseMove += cvsDrawing_MouseMove;
                    new_canvas.MouseUp   += cvsDrawing_MouseUp;

                    cvsDrawing = new_canvas;
                    borDrawing.Child = new_canvas;

                    borDrawing.Visibility = Visibility.Visible;
                    m_FileName = dlg.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message,
                        "Error Reading File",
                        MessageBoxButton.OK,
                        MessageBoxImage.Error);
                }
                finally
                {
                    fs.Close();
                }
            }
        }
        internal static object XamlConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter)
        { 
            asyncObjectConverter = null;

            if (sandboxExternalContent)
            { 
                if (SecurityHelper.AreStringTypesEqual(baseUri.Scheme, BaseUriHelper.PackAppBaseUri.Scheme))
                { 
                    baseUri = BaseUriHelper.ConvertPackUriToAbsoluteExternallyVisibleUri(baseUri); 
                }
 
                stream.Close();

                WebBrowser webBrowser = new WebBrowser();
                webBrowser.Source = baseUri; 
                return webBrowser;
            } 
            else 
            {
                ParserContext pc = new ParserContext(); 

                pc.BaseUri = baseUri;
                pc.SkipJournaledProperties = isJournalNavigation;
 
                if (allowAsync)
                { 
                    XamlReader xr = new XamlReader(); 
                    asyncObjectConverter = xr;
                    xr.LoadCompleted += new AsyncCompletedEventHandler(OnParserComplete); 
                    // XamlReader.Load will close the stream.
                    return xr.LoadAsync(stream, pc);
                }
                else 
                {
                    // XamlReader.Load will close the stream. 
                    return XamlReader.Load(stream, pc); 
                }
            } 
        }
Exemplo n.º 12
0
        // Token: 0x0600226A RID: 8810 RVA: 0x000AAE10 File Offset: 0x000A9010
        private static object Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
        {
            XamlContextStack <WpfXamlFrame> stack = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame());
            int persistId = 1;

            settings.AfterBeginInitHandler = delegate(object sender, XamlObjectEventArgs args)
            {
                if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose))
                {
                    IXamlLineInfo xamlLineInfo2 = xamlReader as IXamlLineInfo;
                    int           num           = -1;
                    int           num2          = -1;
                    if (xamlLineInfo2 != null && xamlLineInfo2.HasLineInfo)
                    {
                        num  = xamlLineInfo2.LineNumber;
                        num2 = xamlLineInfo2.LinePosition;
                    }
                    EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientParseXamlBamlInfo, EventTrace.Keyword.KeywordPerf | EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, new object[]
                    {
                        (args.Instance == null) ? 0L : PerfService.GetPerfElementID(args.Instance),
                        num,
                        num2
                    });
                }
                UIElement uielement = args.Instance as UIElement;
                if (uielement != null)
                {
                    UIElement uielement2 = uielement;
                    int       persistId  = persistId;
                    persistId++;
                    uielement2.SetPersistId(persistId);
                }
                XamlSourceInfoHelper.SetXamlSourceInfo(args.Instance, args, baseUri);
                DependencyObject dependencyObject = args.Instance as DependencyObject;
                if (dependencyObject != null && stack.CurrentFrame.XmlnsDictionary != null)
                {
                    XmlnsDictionary xmlnsDictionary = stack.CurrentFrame.XmlnsDictionary;
                    xmlnsDictionary.Seal();
                    XmlAttributeProperties.SetXmlnsDictionary(dependencyObject, xmlnsDictionary);
                }
                stack.CurrentFrame.Instance = args.Instance;
            };
            XamlObjectWriter xamlObjectWriter;

            if (writerFactory != null)
            {
                xamlObjectWriter = writerFactory.GetXamlObjectWriter(settings);
            }
            else
            {
                xamlObjectWriter = new XamlObjectWriter(xamlReader.SchemaContext, settings);
            }
            IXamlLineInfo xamlLineInfo = null;
            object        result;

            try
            {
                xamlLineInfo = (xamlReader as IXamlLineInfo);
                IXamlLineInfoConsumer xamlLineInfoConsumer = xamlObjectWriter;
                bool shouldPassLineNumberInfo = false;
                if (xamlLineInfo != null && xamlLineInfo.HasLineInfo && xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)
                {
                    shouldPassLineNumberInfo = true;
                }
                IStyleConnector styleConnector = rootObject as IStyleConnector;
                WpfXamlLoader.TransformNodes(xamlReader, xamlObjectWriter, false, skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, stack, styleConnector);
                xamlObjectWriter.Close();
                result = xamlObjectWriter.Result;
            }
            catch (Exception ex)
            {
                if (CriticalExceptions.IsCriticalException(ex) || !XamlReader.ShouldReWrapException(ex, baseUri))
                {
                    throw;
                }
                XamlReader.RewrapException(ex, xamlLineInfo, baseUri);
                result = null;
            }
            return(result);
        }
        internal static object HtmlXappConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter) 
        {
            asyncObjectConverter = null; 
 
            if (canUseTopLevelBrowser)
            { 
                return null;
            }

            if (SecurityHelper.AreStringTypesEqual(baseUri.Scheme, BaseUriHelper.PackAppBaseUri.Scheme)) 
            {
                baseUri = BaseUriHelper.ConvertPackUriToAbsoluteExternallyVisibleUri(baseUri); 
            } 

            stream.Close(); 

            WebBrowser webBrowser = new WebBrowser();
            webBrowser.Source = baseUri;
 
            return webBrowser;
        } 
        /// <summary>Reads the XAML markup in the specified text string (using a specified <see cref="T:System.Windows.Markup.ParserContext" />) and returns an object that corresponds to the root of the specified markup.</summary>
        /// <param name="xamlText">The input XAML, as a single text string.</param>
        /// <param name="parserContext">Context information used by the parser.</param>
        /// <returns>The root of the created object tree.</returns>
        // Token: 0x06002382 RID: 9090 RVA: 0x000AD6AC File Offset: 0x000AB8AC
        public static object Parse(string xamlText, ParserContext parserContext)
        {
            Stream stream = new MemoryStream(Encoding.Default.GetBytes(xamlText));

            return(XamlReader.Load(stream, parserContext));
        }
Exemplo n.º 15
0
        // Token: 0x06002267 RID: 8807 RVA: 0x000AAD70 File Offset: 0x000A8F70
        public static object LoadDeferredContent(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, object rootObject, XamlObjectWriterSettings parentSettings, Uri baseUri)
        {
            XamlObjectWriterSettings settings = XamlReader.CreateObjectWriterSettings(parentSettings);

            return(WpfXamlLoader.Load(xamlReader, writerFactory, skipJournaledProperties, rootObject, settings, baseUri));
        }
Exemplo n.º 16
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);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Loads the given baml stream
        /// </summary>
        /// <param name="stream">input as stream</param>
        /// <param name="parent">parent owner element of baml tree</param>
        /// <param name="parserContext">parser context</param>
        /// <param name="closeStream">True if stream should be closed by the
        ///    parser after parsing is complete.  False if the stream should be left open</param>
        /// <returns>object root generated after baml parsed</returns>
        internal static object LoadBaml(
            Stream stream,
            ParserContext parserContext,
            object parent,
            bool closeStream)
        {
            object root = null;

#if DEBUG_CLR_MEM
            bool clrTracingEnabled = false;
            // Use local pass variable to correctly log nested parses.
            int pass = 0;

            if (CLRProfilerControl.ProcessIsUnderCLRProfiler &&
                (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance))
            {
                clrTracingEnabled = true;
                pass = ++_CLRBamlPass;
                CLRProfilerControl.CLRLogWriteLine("Begin_BamlParse_{0}", pass);
            }
#endif // DEBUG_CLR_MEM

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Event.WClientParseBamlBegin, parserContext.BaseUri);

            if (TraceMarkup.IsEnabled)
            {
                TraceMarkup.Trace(TraceEventType.Start, TraceMarkup.Load);
            }

            try
            {
                //
                // If the stream contains info about the Assembly that created it,
                // set StreamCreatedAssembly from the stream instance.
                //
                IStreamInfo streamInfo = stream as IStreamInfo;
                if (streamInfo != null)
                {
                    parserContext.StreamCreatedAssembly = streamInfo.Assembly;
                }

                Baml2006ReaderSettings readerSettings = XamlReader.CreateBamlReaderSettings();
                readerSettings.BaseUri       = parserContext.BaseUri;
                readerSettings.LocalAssembly = streamInfo.Assembly;
                // We do not set OwnsStream = true so the Baml2006Reader will not close the stream.
                // Calling code is responsible for disposing the stream
                if (readerSettings.BaseUri == null || String.IsNullOrEmpty(readerSettings.BaseUri.ToString()))
                {
                    readerSettings.BaseUri = BaseUriHelper.PackAppBaseUri;
                }

                var reader = new Baml2006ReaderInternal(stream, new Baml2006SchemaContext(readerSettings.LocalAssembly), readerSettings, parent);

                // We don't actually use the GeneratedInternalTypeHelper any more.
                // But for v3 compat, don't allow loading of internals in PT unless there is one.
                Type internalTypeHelper = null;
                if (streamInfo.Assembly != null)
                {
                    try
                    {
                        internalTypeHelper = XamlTypeMapper.GetInternalTypeHelperTypeFromAssembly(parserContext);
                    }
                    // This can perform attribute reflection which will fail if the assembly has unresolvable
                    // attributes. If that happens, just assume there is no helper.
                    catch (Exception e)
                    {
                        if (MS.Internal.CriticalExceptions.IsCriticalException(e))
                        {
                            throw;
                        }
                    }
                }

                if (internalTypeHelper != null)
                {
                    XamlAccessLevel    accessLevel    = XamlAccessLevel.AssemblyAccessTo(streamInfo.Assembly);
                    XamlLoadPermission loadPermission = new XamlLoadPermission(accessLevel);
                    loadPermission.Assert();
                    try
                    {
                        root = WpfXamlLoader.LoadBaml(reader, parserContext.SkipJournaledProperties, parent, accessLevel, parserContext.BaseUri);
                    }
                    finally
                    {
                        CodeAccessPermission.RevertAssert();
                    }
                }
                else
                {
                    root = WpfXamlLoader.LoadBaml(reader, parserContext.SkipJournaledProperties, parent, null, parserContext.BaseUri);
                }

                DependencyObject dObject = root as DependencyObject;
                if (dObject != null)
                {
                    dObject.SetValue(BaseUriHelper.BaseUriProperty, readerSettings.BaseUri);
                }

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

                Debug.Assert(parent == null || root == parent);
            }

            finally
            {
                if (TraceMarkup.IsEnabled)
                {
                    TraceMarkup.Trace(TraceEventType.Stop, TraceMarkup.Load, root);
                }

                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Event.WClientParseBamlEnd, parserContext.BaseUri);

                if (closeStream && stream != null)
                {
                    stream.Close();
                }

#if DEBUG_CLR_MEM
                if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance))
                {
                    CLRProfilerControl.CLRLogWriteLine("End_BamlParse_{0}", pass);
                }
#endif // DEBUG_CLR_MEM
            }

            return(root);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Reads XAML from the passed stream, building an object tree and returning the
        /// root of that tree.  Wrap a CompatibilityReader with another XmlReader that
        /// uses the passed reader settings to allow validation of xaml.
        /// </summary>
        /// <param name="reader">XmlReader to use.  This is NOT wrapped by any
        ///  other reader</param>
        /// <param name="context">Optional parser context.  May be null </param>
        /// <param name="parseMode">Sets synchronous or asynchronous parsing</param>
        /// <param name="useRestrictiveXamlReader">Whether or not this method should use
        /// RestrictiveXamlXmlReader to restrict instantiation of potentially dangerous types</param>
        /// <returns>object root generated after xml parsed</returns>
        internal static object Load(
            XmlReader reader,
            ParserContext parserContext,
            XamlParseMode parseMode,
            bool useRestrictiveXamlReader)
        {
            if (parseMode == XamlParseMode.Uninitialized ||
                parseMode == XamlParseMode.Asynchronous)
            {
                XamlReader xamlReader = new XamlReader();
                return(xamlReader.LoadAsync(reader, parserContext));
            }

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

#if DEBUG_CLR_MEM
            bool clrTracingEnabled = false;
            // Use local pass variable to correctly log nested parses.
            int pass = 0;

            if (CLRProfilerControl.ProcessIsUnderCLRProfiler &&
                (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance))
            {
                clrTracingEnabled = true;
                pass = ++_CLRXamlPass;
                CLRProfilerControl.CLRLogWriteLine("Begin_XamlParse_{0}", pass);
            }
#endif // DEBUG_CLR_MEM

            EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Event.WClientParseXmlBegin, parserContext.BaseUri);

            if (TraceMarkup.IsEnabled)
            {
                TraceMarkup.Trace(TraceEventType.Start, TraceMarkup.Load);
            }
            object root = null;
            try
            {
                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);
                    }
                }

                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();
                System.Xaml.XamlXmlReader xamlXmlReader = (useRestrictiveXamlReader) ? new RestrictiveXamlXmlReader(reader, schemaContext, settings):
                                                          new System.Xaml.XamlXmlReader(reader, schemaContext, settings);
                root = Load(xamlXmlReader, parserContext);
                reader.Close();
            }
            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);
            }
            finally
            {
                if (TraceMarkup.IsEnabled)
                {
                    TraceMarkup.Trace(TraceEventType.Stop, TraceMarkup.Load, root);
                }

                EventTrace.EasyTraceEvent(EventTrace.Keyword.KeywordXamlBaml, EventTrace.Event.WClientParseXmlEnd, parserContext.BaseUri);

#if DEBUG_CLR_MEM
                if (clrTracingEnabled && (CLRProfilerControl.CLRLoggingLevel >= CLRProfilerControl.CLRLogState.Performance))
                {
                    CLRProfilerControl.CLRLogWriteLine("End_XamlParse_{0}", pass);
                }
#endif // DEBUG_CLR_MEM
            }
            return(root);
        }
Exemplo n.º 19
0
        /// <summary>
        /// called when in async mode when get a time slice to read and load the Tree
        /// </summary>
        internal virtual void HandleAsyncQueueItem()
        {
            try
            {
                int startTickCount = MS.Win32.SafeNativeMethods.GetTickCount();
                //bool moreData = true;

                // for debugging, can set the Maximum Async records to
                // read via markup
                // x:AsyncRecords="3" would loop three times
                int maxRecords = _maxAsynxRecords;

                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;
                }

                XamlMember synchronousRecordProperty = _textReader.SchemaContext.GetXamlDirective(XamlLanguage.Xaml2006Namespace, "AsyncRecords");

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

                    if (xamlReader.NodeType == System.Xaml.XamlNodeType.Value && _stack.CurrentFrame.Property == synchronousRecordProperty)
                    {
                        if (xamlReader.Value is int)
                        {
                            _maxAsynxRecords = (int)xamlReader.Value;
                        }
                        else if (xamlReader.Value is String)
                        {
                            _maxAsynxRecords = Int32.Parse(xamlReader.Value as String, TypeConverterHelper.InvariantEnglishUS);
                        }
                        maxRecords = _maxAsynxRecords;
                    }

                    //Debug.Assert (1 >= RootList.Count, "Multiple roots not supported in async mode");

                    // check the timeout
                    int elapsed = MS.Win32.SafeNativeMethods.GetTickCount() - startTickCount;

                    // check for rollover
                    if (elapsed < 0)
                    {
                        startTickCount = 0; // reset to 0,
                    }
                    else if (elapsed > AsyncLoopTimeout)
                    {
                        break;
                    }

                    // decrement and compare with zero so the unitialized -1  and zero case
                    // doesn't break the loop.
                    if (--maxRecords == 0)
                    {
                        break;
                    }
                }
            }
            catch (XamlParseException e)
            {
                _parseException = e;
            }
            catch (Exception e)
            {
                if (CriticalExceptions.IsCriticalException(e) || !XamlReader.ShouldReWrapException(e, _baseUri))
                {
                    _parseException = e;
                }
                else
                {
                    _parseException = XamlReader.WrapException(e, null, _baseUri);
                }
            }
            finally
            {
                if (_parseException != null || _parseCancelled)
                {
                    TreeBuildComplete();
                }
                else
                {
                    // if not at the EndOfDocument then post another work item
                    if (false == _textReader.IsEof)
                    {
                        Post();
                    }
                    else
                    {
                        // Building of the Tree is complete.
                        TreeBuildComplete();
                    }
                }
            }
        }
Exemplo n.º 20
0
 private void DispatchParserQueueEvent(XamlReader xamlReader)
 {
     xamlReader.HandleAsyncQueueItem();
 }
Exemplo n.º 21
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++);
                }

                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
            }
        }
        // Token: 0x0600238A RID: 9098 RVA: 0x000AD808 File Offset: 0x000ABA08
        private object LoadAsync(XmlReader reader, ParserContext parserContext)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (parserContext == null)
            {
                parserContext = new ParserContext();
            }
            this._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);
                }
            }
            this._baseUri = parserContext.BaseUri;
            XamlXmlReaderSettings xamlXmlReaderSettings = new XamlXmlReaderSettings();

            xamlXmlReaderSettings.IgnoreUidsOnPropertyElements = true;
            xamlXmlReaderSettings.BaseUri         = parserContext.BaseUri;
            xamlXmlReaderSettings.ProvideLineInfo = true;
            XamlSchemaContext schemaContext = (parserContext.XamlTypeMapper != null) ? parserContext.XamlTypeMapper.SchemaContext : XamlReader.GetWpfSchemaContext();

            try
            {
                this._textReader = new XamlXmlReader(reader, schemaContext, xamlXmlReaderSettings);
                this._stack      = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame());
                XamlObjectWriterSettings xamlObjectWriterSettings = XamlReader.CreateObjectWriterSettings();
                xamlObjectWriterSettings.AfterBeginInitHandler = delegate(object sender, XamlObjectEventArgs args)
                {
                    if (rootObject == null)
                    {
                        rootObject           = args.Instance;
                        this._styleConnector = (rootObject as IStyleConnector);
                    }
                    UIElement uielement = args.Instance as UIElement;
                    if (uielement != null)
                    {
                        UIElement uielement2 = uielement;
                        XamlReader < > 4__this = this;
                        int persistId = this._persistId;
                        < > 4__this._persistId = persistId + 1;
                        uielement2.SetPersistId(persistId);
                    }
                    DependencyObject dependencyObject = args.Instance as DependencyObject;
                    if (dependencyObject != null && this._stack.CurrentFrame.XmlnsDictionary != null)
                    {
                        XmlnsDictionary xmlnsDictionary = this._stack.CurrentFrame.XmlnsDictionary;
                        xmlnsDictionary.Seal();
                        XmlAttributeProperties.SetXmlnsDictionary(dependencyObject, xmlnsDictionary);
                    }
                };
Exemplo n.º 23
0
        private void Parse()
        {
            if (String.IsNullOrEmpty(BBCode)) return;
            if (String.IsNullOrEmpty(RootElementName)) return;
            if (String.IsNullOrEmpty(DefaultElementName)) return;

            Debug.Print("PARSING: {0}", BBCode);
            string xaml = BBCode;
            string xamlFormat = "<" + RootElementName + ">{0}</" + RootElementName + ">";
            foreach (var tag in Tags)
                xaml = tag.DoFormating(xaml);

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(string.Format(xamlFormat, xaml));
            xaml = "";
            foreach (XmlNode i in doc.FirstChild)
            {
                if (i.NodeType == XmlNodeType.Text)
                    xaml += "<" + DefaultElementName + ">" + i.OuterXml + "</" + DefaultElementName + "> ";
                else
                    xaml += i.OuterXml;
            }

            xaml = string.Format(xamlFormat, xaml);

            System.Windows.Markup.ParserContext pc = new ParserContext();
            pc.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
            pc.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
            XamlReader rdr = new XamlReader();
            this.Content = XamlReader.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)), pc);
        }
Exemplo n.º 24
0
        // Token: 0x0600226B RID: 8811 RVA: 0x000AAF38 File Offset: 0x000A9138
        internal static void TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, bool onlyLoadOneNode, bool skipJournaledProperties, bool shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack <WpfXamlFrame> stack, IStyleConnector styleConnector)
        {
            while (xamlReader.Read())
            {
                if (shouldPassLineNumberInfo && xamlLineInfo.LineNumber != 0)
                {
                    xamlLineInfoConsumer.SetLineInfo(xamlLineInfo.LineNumber, xamlLineInfo.LinePosition);
                }
                switch (xamlReader.NodeType)
                {
                case XamlNodeType.StartObject:
                    WpfXamlLoader.WriteStartObject(xamlReader, xamlWriter, stack);
                    break;

                case XamlNodeType.GetObject:
                    xamlWriter.WriteNode(xamlReader);
                    if (stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                    }
                    stack.CurrentFrame.Type = stack.PreviousFrame.Property.Type;
                    break;

                case XamlNodeType.EndObject:
                {
                    xamlWriter.WriteNode(xamlReader);
                    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 != null)
                    {
                        XmlAttributeProperties.SetXmlSpace(dependencyObject, stack.CurrentFrame.XmlSpace.Value ? "default" : "preserve");
                    }
                    stack.PopScope();
                    break;
                }

                case XamlNodeType.StartMember:
                    if ((!xamlReader.Member.IsDirective || !(xamlReader.Member == XamlReaderHelper.Freeze)) && xamlReader.Member != WpfXamlLoader.XmlSpace.Value && xamlReader.Member != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }
                    stack.CurrentFrame.Property = xamlReader.Member;
                    if (skipJournaledProperties && !stack.CurrentFrame.Property.IsDirective)
                    {
                        WpfXamlMember wpfXamlMember = stack.CurrentFrame.Property as WpfXamlMember;
                        if (wpfXamlMember != null)
                        {
                            DependencyProperty dependencyProperty = wpfXamlMember.DependencyProperty;
                            if (dependencyProperty != null)
                            {
                                FrameworkPropertyMetadata frameworkPropertyMetadata = dependencyProperty.GetMetadata(stack.CurrentFrame.Type.UnderlyingType) as FrameworkPropertyMetadata;
                                if (frameworkPropertyMetadata != null && frameworkPropertyMetadata.Journal)
                                {
                                    int num = 1;
                                    while (xamlReader.Read())
                                    {
                                        switch (xamlReader.NodeType)
                                        {
                                        case XamlNodeType.StartObject:
                                        {
                                            XamlType type      = xamlReader.Type;
                                            XamlType xamlType  = type.SchemaContext.GetXamlType(typeof(BindingBase));
                                            XamlType xamlType2 = type.SchemaContext.GetXamlType(typeof(DynamicResourceExtension));
                                            if (num == 1 && (type.CanAssignTo(xamlType) || type.CanAssignTo(xamlType2)))
                                            {
                                                num = 0;
                                                WpfXamlLoader.WriteStartObject(xamlReader, xamlWriter, stack);
                                            }
                                            break;
                                        }

                                        case XamlNodeType.StartMember:
                                            num++;
                                            break;

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

                                        case XamlNodeType.Value:
                                        {
                                            DynamicResourceExtension dynamicResourceExtension = xamlReader.Value as DynamicResourceExtension;
                                            if (dynamicResourceExtension != null)
                                            {
                                                WpfXamlLoader.WriteValue(xamlReader, xamlWriter, stack, styleConnector);
                                            }
                                            break;
                                        }
                                        }
                                        if (num == 0)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;

                case XamlNodeType.EndMember:
                {
                    WpfXamlFrame currentFrame = stack.CurrentFrame;
                    XamlMember   property     = currentFrame.Property;
                    if ((!property.IsDirective || !(property == XamlReaderHelper.Freeze)) && property != WpfXamlLoader.XmlSpace.Value && property != XamlLanguage.Space)
                    {
                        xamlWriter.WriteNode(xamlReader);
                    }
                    currentFrame.Property = null;
                    break;
                }

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

                case XamlNodeType.NamespaceDeclaration:
                    xamlWriter.WriteNode(xamlReader);
                    if (stack.Depth == 0 || stack.CurrentFrame.Type != null)
                    {
                        stack.PushScope();
                        for (WpfXamlFrame wpfXamlFrame = stack.CurrentFrame; wpfXamlFrame != null; wpfXamlFrame = (WpfXamlFrame)wpfXamlFrame.Previous)
                        {
                            if (wpfXamlFrame.XmlnsDictionary != null)
                            {
                                stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary(wpfXamlFrame.XmlnsDictionary);
                                break;
                            }
                        }
                        if (stack.CurrentFrame.XmlnsDictionary == null)
                        {
                            stack.CurrentFrame.XmlnsDictionary = new XmlnsDictionary();
                        }
                    }
                    stack.CurrentFrame.XmlnsDictionary.Add(xamlReader.Namespace.Prefix, xamlReader.Namespace.Namespace);
                    break;

                default:
                    xamlWriter.WriteNode(xamlReader);
                    break;
                }
                if (onlyLoadOneNode)
                {
                    return;
                }
            }
        }