private static object Load(Stream stream) { var pc = new ParserContext(); MethodInfo loadBamlMethod = typeof (XamlReader).GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static); return loadBamlMethod.Invoke(null, new object[] {stream, pc, null, false}); }
// <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); }
public static ResourceDictionary LoadFromPng( string FileName ) { // read all file PngReader pngr = FileHelper.CreatePngReader(FileName); pngr.ReadSkippingAllRows(); pngr.End(); // we assume there can be at most one chunk of this type... PngChunk chunk = pngr.GetChunksList().GetById1(PngChunkSKIN.ID); // This would work even if not registered, but then PngChunk would be of type PngChunkUNKNOWN if (chunk != null) { // the following would fail if we had not register the chunk PngChunkSKIN chunkprop = (PngChunkSKIN)chunk; ParserContext pc = new ParserContext(); pc.XamlTypeMapper = XamlTypeMapper.DefaultMapper; // pc.XmlSpace //MimeObjectFactory s; var rd1 = (ResourceDictionary)XamlReader.Parse(chunkprop.Content); // Application.Current.Resources.MergedDictionaries.Add(rd1); // var rd2 = (ResourceDictionary)XamlReader.Parse(chunkprop.Content); //// Application.Current.Resources.MergedDictionaries.Add(rd2); // if (rd1 == rd2) { // } return rd1; } else { return null; } }
public static object DeSerializeObjectTree(string xaml) { Stream stream = ConvertTextToStream(xaml); ParserContext parserContext = new ParserContext(); parserContext.BaseUri = new Uri("pack://siteoforigin:,,,/"); return XamlReader.Load(stream, parserContext); }
// --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods public static FlowDocument DeserializeFlowDocument(string strFlowDocumentXML) { Debug.WriteLine("DeserializeFlowDocument: " + strFlowDocumentXML); try { MemoryStream memoryStream = new MemoryStream(strFlowDocumentXML.Length); using (StreamWriter streamWriter = new StreamWriter(memoryStream)) { streamWriter.Write(strFlowDocumentXML); streamWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); ParserContext parserContext = new ParserContext(); parserContext.BaseUri = new Uri(System.Environment.CurrentDirectory + "/"); return XamlReader.Load(memoryStream, parserContext) as FlowDocument; } } catch (Exception ex) { Debug.Assert(false, "Load flow document failed! :" +ex); //return new FlowDocument(); throw ex; } }
/// <summary> /// Create a BamlWriter on the passed stream. The stream must be writable. /// </summary> public BamlWriter( Stream stream) { if (null == stream) { throw new ArgumentNullException( "stream" ); } if (!stream.CanWrite) { throw new ArgumentException(SR.Get(SRID.BamlWriterBadStream)); } _parserContext = new ParserContext(); if (null == _parserContext.XamlTypeMapper) { _parserContext.XamlTypeMapper = new BamlWriterXamlTypeMapper(XmlParserDefaults.GetDefaultAssemblyNames(), XmlParserDefaults.GetDefaultNamespaceMaps()); } _xamlTypeMapper = _parserContext.XamlTypeMapper; _bamlRecordWriter = new BamlRecordWriter(stream, _parserContext, true); _startDocumentWritten = false; _depth = 0; _closed = false; _nodeTypeStack = new ParserStack(); _assemblies = new Hashtable(7); _extensionParser = new MarkupExtensionParser((IParserHelper)this, _parserContext); _markupExtensionNodes = new ArrayList(); }
private static void OnBoundDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RichTextBox box = d as RichTextBox; if (box == null) return; RemoveEventHandler(box); string newXAML = GetBoundDocument(d); box.Document.Blocks.Clear(); if (!string.IsNullOrEmpty(newXAML)) { using (MemoryStream xamlMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(newXAML))) { ParserContext parser = new ParserContext(); parser.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); FlowDocument doc = new FlowDocument(); Section section = XamlReader.Load(xamlMemoryStream, parser) as Section; box.Document.Blocks.Add(section); } } AttachEventHandler(box); }
public static object LoadBaml(Stream stream) { var presentationFrameworkAssembly = Assembly.GetAssembly(typeof(Button)); if( Environment.Version.Major == 4) { var xamlAssembly = Assembly.Load("System.Xaml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); var readerType = presentationFrameworkAssembly.GetType("System.Windows.Baml2006.Baml2006Reader"); var reader = Activator.CreateInstance(readerType, stream); var schemaContextProperty = readerType.GetProperty("SchemaContext"); var schemaContext = schemaContextProperty.GetGetMethod().Invoke(reader, null); var writerType = xamlAssembly.GetType("System.Xaml.XamlObjectWriter"); var writer = Activator.CreateInstance(writerType, schemaContext); var readerReadMethod = readerType.GetMethod("Read"); var writerWriteMethod = writerType.GetMethod("WriteNode"); while( (bool)readerReadMethod.Invoke(reader, null)) { writerWriteMethod.Invoke(writer, new[] {reader}); } var writerResultProperty = writerType.GetProperty("Result"); return writerResultProperty.GetGetMethod().Invoke(writer, null); } else { var pc = new ParserContext(); var readerType = presentationFrameworkAssembly.GetType("System.Windows.Markup.XamlReader"); var method = readerType.GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static); return method.Invoke(null, new object[] {stream, pc, null, false}); } }
public static FrameworkElement Parse(string xaml) { var context = new ParserContext(); context.XmlnsDictionary.Add(string.Empty, "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); var element = (FrameworkElement)XamlReader.Parse(xaml, context); return element; }
public WpfContainer(string xamlPath) { Context = new ParserContext(); Context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); Context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); XamlFile = new FrameworkElementWrapper((FrameworkElement)XamlReader.Load(new FileStream(xamlPath, FileMode.Open), Context)); }
public WpfContainer(Stream xamlStream) { Context = new ParserContext(); Context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); Context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); XamlFile.Element = (FrameworkElement)XamlReader.Load(xamlStream, Context); }
public WpfContainer() { Context = new ParserContext(); Context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); Context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); XamlFile = null; }
static XamlToObjectConverter() { // Initialize the parser context, which provides xml namespace mappings used when // the loose XAML is loaded and converted into a .NET object. parserContext = new ParserContext(); parserContext.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); parserContext.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); }
public static FlexDocument ParseDocument(string configFilePath) { //try //{ var parserContext = new ParserContext(); var configFileStream = new FileStream(configFilePath, FileMode.Open); var configObject = XamlReader.Load(configFileStream, parserContext); var chartConfigObject = (FlexDocument)configObject; return chartConfigObject; //} //catch// (Exception ex) //{ // throw;// ex;// new Exception("Parser fail"); //} }
/// <summary> /// Parse a string to WPF object. /// </summary> /// <param name="str">string to be parsed</param> /// <returns>return an object</returns> public static object ParseXaml(string str) { MemoryStream ms = new MemoryStream(str.Length); StreamWriter sw = new StreamWriter(ms); sw.Write(str); sw.Flush(); ms.Seek(0, SeekOrigin.Begin); ParserContext pc = new ParserContext(); pc.BaseUri = new Uri(System.Environment.CurrentDirectory + "/"); return XamlReader.Load(ms, pc); }
/// <summary> /// Creates a new instance. /// </summary> public EnumComboBox() { var context = new ParserContext(); context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); context.XmlnsDictionary.Add("lex", "http://wpflocalizeextension.codeplex.com"); var xaml = "<DataTemplate><TextBlock><lex:EnumRun EnumValue=\"{Binding}\""; xaml += " PrependType=\"{Binding PrependType, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lex:EnumComboBox}}\""; xaml += " Separator=\"{Binding Separator, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lex:EnumComboBox}}\""; xaml += " Prefix=\"{Binding Prefix, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lex:EnumComboBox}}\""; xaml += " /></TextBlock></DataTemplate>"; ItemTemplate = (DataTemplate)XamlReader.Parse(xaml, context); }
public static ControlTemplate GetTemplate() { if (m_TemplateCache == null) { //m_TemplateCache = new ControlTemplate(); //m_TemplateCache.VisualTree = new System.Windows.FrameworkElementFactory(typeof(TextErrorTemplateVisualtree)); MemoryStream sr = new MemoryStream(Encoding.ASCII.GetBytes(c_TemplateXaml)); 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"); m_TemplateCache = (ControlTemplate)XamlReader.Load(sr, pc); } return m_TemplateCache; }
private static DataTemplate CreateTemplate(Type viewModelType, Type viewType) { var xaml = $"<DataTemplate DataType=\"{{x:Type vm:{viewModelType.Name}}}\"><v:{viewType.Name} /></DataTemplate>"; var context = new ParserContext(); context.XamlTypeMapper = new XamlTypeMapper(new string[0]); context.XamlTypeMapper.AddMappingProcessingInstruction("vm", viewModelType.Namespace, viewModelType.Assembly.FullName); context.XamlTypeMapper.AddMappingProcessingInstruction("v", viewType.Namespace, viewType.Assembly.FullName); context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); context.XmlnsDictionary.Add("vm", "vm"); context.XmlnsDictionary.Add("v", "v"); var template = (DataTemplate)XamlReader.Parse(xaml, context); return template; }
private DataTemplate CreateTemplate() { const string xamlTemplate = "<DataTemplate x:Name=\"Tpl\">" + " <TextBox Background=\"{{Binding Background, ElementName=Txt}}\"" + " Text=\"{{Binding Value}}\" />" + "</DataTemplate>"; var xaml = string.Format(xamlTemplate); var context = new ParserContext(); var type = typeof(DataTemplateSampleView); context.XamlTypeMapper = new XamlTypeMapper(new string[0]); context.XamlTypeMapper.AddMappingProcessingInstruction("v", type.Namespace, type.Assembly.FullName); context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); context.XmlnsDictionary.Add("v", "v"); var template = (DataTemplate) XamlReader.Parse(xaml, context); return template; }
public override void Run() { String xamlFile = null; using (var writer = new System.IO.StringWriter()) { using (var ofd = new System.Windows.Forms.OpenFileDialog() { Filter = "XAML File|*.xaml" }) { if (ofd.ShowDialog() != DialogResult.OK) return; xamlFile = ofd.FileName; } } var xamlStr = System.IO.File.ReadAllText(xamlFile); var pc = new ParserContext(); // pc.XamlTypeMapper = new XamlTypeMapper(new string[] { }); // pc.XamlTypeMapper.AddMappingProcessingInstruction("ad", "AvalonDock", "AvalonDock"); pc.XamlTypeMapper.AddMappingProcessingInstruction("adRes", "AvalonDock.Properties", "AvalonDock"); pc.XamlTypeMapper.AddMappingProcessingInstruction("sys", "System", "mscorlib"); pc.XamlTypeMapper.AddMappingProcessingInstruction("th", "ThemeTool","AnotherThemeTool"); // pc.XmlnsDictionary.Add("ad", "ad"); pc.XmlnsDictionary.Add("adRes", "adRes"); pc.XmlnsDictionary.Add("sys", "sys"); pc.XmlnsDictionary.Add("th", "th"); Assembly.LoadWithPartialName("AnotherThemeTool"); // pc.BaseUri = new Uri(@"clr-namespace:AnotherThemeTool",UriKind.RelativeOrAbsolute); var rd = (ResourceDictionary)XamlReader.Parse(xamlStr); // AvalonDock.ThemeFactory.ResetTheme(); // System.Windows.Application.Current.Resources.MergedDictionaries.Add( // new ResourceDictionary{Source=new Uri(@"/AvalonDock;component/themes/generic.xaml",UriKind.RelativeOrAbsolute)} // ); System.Windows.Application.Current.Resources.MergedDictionaries.Add(rd); }
// // Give the template its own copy of the parser context. It needs a copy, because it's // going to use it later on every application. // internal void CopyParserContext(ParserContext parserContext) { _parserContext = parserContext.ScopedCopy(false /*copyNameScopeStack*/ ); // We need to clear the Journal bit, because we know we won't be able to honor it correctly. // Journaling journals the properties in the logical tree, so doesn't journal properties in the // Template/Resources. This shouldn't be hard-coded here, but is an internal solution for V1. _parserContext.SkipJournaledProperties = false; }
public int SaveAsXps(string fileName) { object doc; FileInfo fileInfo = new FileInfo(fileName); using (FileStream file = fileInfo.OpenRead()) { System.Windows.Markup.ParserContext context = new System.Windows.Markup.ParserContext(); context.BaseUri = new Uri(fileInfo.FullName, UriKind.Absolute); doc = System.Windows.Markup.XamlReader.Load(file, context); } if (!(doc is IDocumentPaginatorSource)) { Console.WriteLine("DocumentPaginatorSource expected"); return(-1); } using (Package container = Package.Open(fileName + ".xps", FileMode.Create)) { using (XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.Maximum)) { xpsDoc.AddFixedDocumentSequence(); FixedDocumentSequence seq = xpsDoc.GetFixedDocumentSequence(); DocumentReference reference = new DocumentReference(); //reference.SetDocument(doc); seq.References.Add(reference); FixedDocument abc = new FixedDocument(); PageContent pagecnt = new PageContent(); abc.Pages.Add(pagecnt); XpsSerializationManager rsm = new XpsSerializationManager(new XpsPackagingPolicy(xpsDoc), false); xpsDoc.AddFixedDocumentSequence(); FixedDocumentSequence aaa = xpsDoc.GetFixedDocumentSequence(); DocumentPaginator paginator = ((IDocumentPaginatorSource)doc).DocumentPaginator; // 8 inch x 6 inch, with half inch margin //paginator = new DocumentPaginatorWrapper(paginator, new Size(21*96/2.54, 29.7*96/2.54), new Size(0*96/2.54, 0*96/2.54)); //PrintDialog ptdlg = new PrintDialog(); //ptdlg.ShowDialog(); //((IDocumentPaginatorSource)doc).DocumentPaginator.PageSize = new Size(ptdlg.PrintableAreaWidth, ptdlg.PrintableAreaHeight); //paginator = new DocumentPaginatorWrapper(paginator, new Size(ptdlg.PrintableAreaWidth, ptdlg.PrintableAreaHeight), new Size(0 * 96 / 2.54, 0 * 96 / 2.54)); rsm.SaveAsXaml(paginator); rsm.Commit(); xpsDoc.Close(); container.Close(); XpsDocument tempdoc = new XpsDocument(fileName + ".xps", FileAccess.Read); //viewer.Document = tempdoc.GetFixedDocumentSequence(); } } Console.WriteLine("{0} generated.", fileName + ".xps"); return(0); }
// Construction internal ProvideValueServiceProvider(ParserContext context) { _context = context; }
// Token: 0x06002265 RID: 8805 RVA: 0x000AAD32 File Offset: 0x000A8F32 public TypeConvertContext(ParserContext parserContext) { this._parserContext = parserContext; }
private static DataTemplate CreateContentTemplate() { const string xaml = "<DataTemplate><Border b:TabContent.InternalTabControl=\"{Binding RelativeSource={RelativeSource AncestorType=TabControl}}\" /></DataTemplate>"; var context = new ParserContext(); context.XamlTypeMapper = new XamlTypeMapper(new string[0]); context.XamlTypeMapper.AddMappingProcessingInstruction("b", typeof (TabContent).Namespace, typeof (TabContent).Assembly.FullName); context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); context.XmlnsDictionary.Add("b", "b"); var template = (DataTemplate) XamlReader.Parse(xaml, context); return template; }
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); }
/// <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); }
/// <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); }
/// <summary> /// Reads XAML using the passed xamlText, building an object tree and returning the /// root of that tree. /// </summary> /// <param name="xamlText">XAML text as a string</param> /// <param name="parserContext">parser context</param> /// <returns>object root generated after xaml is parsed</returns> public static object Parse(string xamlText, ParserContext parserContext) { Stream xamlStream = new MemoryStream(UTF8Encoding.Default.GetBytes(xamlText)); return(Load(xamlStream, parserContext)); }
}// end:GetContentFolder() // ----------------------------- OpenFile ----------------------------- private bool OpenFile(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // Check file existence if (!System.IO.File.Exists(fileName)) { MessageBox.Show( "File not found: " + fileName, this.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); return false; } object newDocument = null; // Apply appropriate converter to a file content try { if (fileName.EndsWith(".xaml")) { using (FileStream inputStream = File.OpenRead(fileName)) { ParserContext pc = new ParserContext(); pc.BaseUri = new Uri(System.Environment.CurrentDirectory + "/"); newDocument = XamlReader.Load(inputStream, pc) as object; if (newDocument == null) { MessageBox.Show( "Invalid Xaml File. Could not be parsed" + fileName, this.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); return false; } } } } catch (Exception e) { MessageBox.Show( "Error occurred during conversion from this file format: " + fileName + "\n" + e.ToString(), this.GetType().Name, MessageBoxButton.OK, MessageBoxImage.Error); return false; } if (newDocument is IDocumentPaginatorSource) { if (this.Document != null) { Debug.Assert(FDPV.Document.DocumentPaginator is DynamicDocumentPaginator); (FDPV.Document.DocumentPaginator as DynamicDocumentPaginator).PaginationCompleted -= PaginationCompleted; } this.Document = (IDocumentPaginatorSource)newDocument; Util.FlushDispatcher(); Debug.Assert(FDPV.Document.DocumentPaginator is DynamicDocumentPaginator); (FDPV.Document.DocumentPaginator as DynamicDocumentPaginator).PaginationCompleted += new EventHandler(PaginationCompleted); SaveAsMenu.IsEnabled = true; SaveAsToolbarButton.IsEnabled = true; _fileName = fileName; } else // if !(newDocument is IDocumentPaginatorSource) { throw new InvalidDataException( "Thumbnail viewer only supports IDocumentPaginatorSource"); //return false; } return true; }// end:OpenFile()
/// <summary> /// Generates the code. /// </summary> /// <param name="inputFileName">Name of the input file.</param> /// <param name="inputFileContent">Content of the input file.</param> /// <param name="renderMode">The render mode.</param> /// <param name="desiredNamespace">The desired namespace.</param> /// <returns></returns> public string GenerateCode(string inputFileName, string inputFileContent, RenderMode renderMode, string desiredNamespace) { inputFileContent = RemoveClass(inputFileContent); var parserContext = new ParserContext { BaseUri = new Uri(inputFileName, UriKind.Absolute) }; object source = null; try { //source = XamlReader.Parse(inputFileContent); //, parserContext); using (Stream stream = new MemoryStream(Encoding.UTF8.GetBytes(inputFileContent))) { source = XamlReader.Load(stream, parserContext); } } catch (Exception ex) { Console.WriteLine(ex); throw; } if (source == null) { return "Source is empty. XAML file is not valid."; } Console.WriteLine(); Console.WriteLine("Generating " + inputFileName); string resultCode = string.Empty; string className = Path.GetFileNameWithoutExtension(inputFileName); CodeNamespace ns = new CodeNamespace(desiredNamespace); ns.Imports.Add(new CodeNamespaceImport("System")); ns.Imports.Add(new CodeNamespaceImport("System.CodeDom.Compiler")); ns.Imports.Add(new CodeNamespaceImport("System.Collections.ObjectModel")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Data")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Controls.Primitives")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Input")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Animation")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Media.Imaging")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Shapes")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Renderers")); ns.Imports.Add(new CodeNamespaceImport("EmptyKeys.UserInterface.Themes")); /* switch (renderMode) { case RenderMode.SunBurn: ns.Imports.Add(new CodeNamespaceImport("SynapseGaming.SunBurn.Framework.Primitives")); break; case RenderMode.MonoGame: ns.Imports.Add(new CodeNamespaceImport("Microsoft.Xna.Framework")); ns.Imports.Add(new CodeNamespaceImport("Microsoft.Xna.Framework.Graphics")); break; default: break; } */ CodeTypeDeclaration classType = new CodeTypeDeclaration(className); GeneratedCodeAttribute generatedCodeAttribute = new GeneratedCodeAttribute("Empty Keys UI Generator", Assembly.GetExecutingAssembly().GetName().Version.ToString()); CodeAttributeDeclaration codeAttrDecl = new CodeAttributeDeclaration(generatedCodeAttribute.GetType().Name, new CodeAttributeArgument( new CodePrimitiveExpression(generatedCodeAttribute.Tool)), new CodeAttributeArgument( new CodePrimitiveExpression(generatedCodeAttribute.Version))); classType.CustomAttributes.Add(codeAttrDecl); ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false)); ns.Comments.Add(new CodeCommentStatement(" ", false)); ns.Comments.Add(new CodeCommentStatement(" This file was generated, please do not modify.", false)); ns.Comments.Add(new CodeCommentStatement(" ", false)); ns.Comments.Add(new CodeCommentStatement("-----------------------------------------------------------", false)); CodeMemberMethod initMethod = null; if (source is UIRoot) { initMethod = CreateUIRootClass(ns, classType, renderMode); generator.ProcessGenerators(source, classType, initMethod, true); } else if (source is UserControl) { initMethod = CreateUserControlClass(ns, classType); generator.ProcessGenerators(source, classType, initMethod, true); } else if (source is ResourceDictionary) { initMethod = CreateDictionaryClass(ns, classType); ResourceDictionary dictionary = source as ResourceDictionary; if (dictionary != null) { ResourceDictionaryGenerator resourcesGenerator = new ResourceDictionaryGenerator(); resourcesGenerator.Generate(dictionary, classType, initMethod, new CodeThisReferenceExpression()); } } else { string errorText = "#error This type is not supported - " + source.GetType(); Console.WriteLine(errorText); return errorText; } ImageAssets.Instance.GenerateManagerCode(initMethod); ImageAssets.Instance.ClearAssets(); FontGenerator.Instance.GenerateManagerCode(initMethod); using (CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider()) { string mappedFileName = memoryMappedFileName + className; using (MemoryMappedFile mappedFile = MemoryMappedFile.CreateNew(mappedFileName, nemoryMappedFileCapacity)) { MemoryMappedViewStream stream = mappedFile.CreateViewStream(); using (StreamWriter sw = new StreamWriter(stream)) { provider.GenerateCodeFromNamespace(ns, sw, new CodeGeneratorOptions()); } stream = mappedFile.CreateViewStream(); TextReader tr = new StreamReader(stream); resultCode = tr.ReadToEnd(); resultCode = resultCode.Trim(new char()); tr.Close(); } } return resultCode; }
// Create columns for the GridView of the ListViewResults private void createGridViewResultsColumns(int numberProcessAlgorithm) { // XAML from a string or a memory stream using the Load method of the XamlReader class gridViewResults.Columns.Clear(); // Clear the previous columns configuration MemoryStream sr = null; ParserContext pc = null; string xaml = string.Empty; // Name Column xaml = "<GridViewColumn Header=\"Name\" DisplayMemberBinding=\"{Binding XPath=@Name}\"/>"; sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml)); 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"); GridViewColumn col = (GridViewColumn)XamlReader.Load(sr, pc); gridViewResults.Columns.Add(col); // Original Column image first xaml = "<GridViewColumn Header=\"Original\">" + "<GridViewColumn.CellTemplate>" + "<DataTemplate>" + "<StackPanel Width=\"50\">" + "<Image Source=\"{Binding XPath=@Original}\">" + "</Image>" + "</StackPanel>" + "</DataTemplate>" + "</GridViewColumn.CellTemplate>" + "</GridViewColumn>"; sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml)); 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"); col = (GridViewColumn)XamlReader.Load(sr, pc); gridViewResults.Columns.Add(col); // The rest of Columns for the results for (int i = 1; i <= numberProcessAlgorithm; i++) { xaml = "<GridViewColumn Header=\"" + "Process " + i.ToString() + "\">" + "<GridViewColumn.CellTemplate>" + "<DataTemplate>" + "<StackPanel Width=\"50\">" + "<Image Source=\"{Binding XPath=@" + "Process" + i.ToString() + "}\">" // The XPath without spaces + "</Image>" + "</StackPanel>" + "</DataTemplate>" + "</GridViewColumn.CellTemplate>" + "</GridViewColumn>"; sr = new MemoryStream(Encoding.ASCII.GetBytes(xaml)); 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"); col = (GridViewColumn)XamlReader.Load(sr, pc); gridViewResults.Columns.Add(col); } }
public object LoadAsync (Stream stream, ParserContext context) { if (stream == null || context == null) throw new ArgumentNullException (); throw new NotImplementedException (); }
// Returns an Id for a static property or field member whose Type could be // a known SystemResourceKey or DepenencyProperty or other custom value. internal short GetStaticMemberId(BinaryWriter binaryWriter, ParserContext pc, short extensionTypeId, string memberValue, Type defaultTargetType) { short memberId = 0; Type targetType = null; string memberName = null; switch (extensionTypeId) { case (short)KnownElements.StaticExtension: targetType = XamlTypeMapper.GetTargetTypeAndMember(memberValue, pc, true, out memberName); Debug.Assert(targetType != null && memberName != null); MemberInfo memberInfo = XamlTypeMapper.GetStaticMemberInfo(targetType, memberName, false); if (memberInfo is PropertyInfo) { // see if the value is a static SystemResourceKey property from the themes memberId = SystemResourceKey.GetSystemResourceKeyId(targetType, memberName); } break; case (short)KnownElements.TemplateBindingExtension: targetType = XamlTypeMapper.GetDependencyPropertyOwnerAndName(memberValue, pc, defaultTargetType, out memberName); break; } if (memberId == 0) { // if not a known member, add it to the attributeInfo Map. // This will automatically account for known DPs. memberId = AddAttributeInfoMap(binaryWriter, targetType.Assembly.FullName, targetType.FullName, targetType, memberName, null, BamlAttributeUsage.Default); } return memberId; }
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); }
// Return an instance of a TypeConverter object, given the type id of the object. // This may be a known element, or one that is stored in a type record internal TypeConverter GetConverterFromId ( short typeId, Type propType, ParserContext pc) { TypeConverter tc = null; if (typeId < 0) { // The EnumConverter and NullableConverter need to be created specially, since // they need the type of the Enum or Nullable in their constructor. switch((KnownElements)(-typeId)) { case KnownElements.EnumConverter: Debug.Assert(propType.IsEnum); tc = GetConverterFromCache(propType); if (tc == null) { tc = new System.ComponentModel.EnumConverter(propType); ConverterCache.Add(propType, tc); } break; case KnownElements.NullableConverter: Debug.Assert(ReflectionHelper.IsNullableType(propType)); tc = GetConverterFromCache(propType); if (tc == null) { tc = new System.ComponentModel.NullableConverter(propType); ConverterCache.Add(propType, tc); } break; default: tc = GetConverterFromCache(typeId); if (tc == null) { tc = CreateKnownTypeFromId(typeId) as TypeConverter; ConverterCache.Add(typeId, tc); } break; } } else { Type t = GetTypeFromId(typeId); tc = GetConverterFromCache(t); if (tc == null) { if (ReflectionHelper.IsPublicType(t)) { tc = Activator.CreateInstance(t) as TypeConverter; } else { tc = XamlTypeMapper.CreateInternalInstance(pc, t) as TypeConverter; } if (tc == null) { ThrowException(SRID.ParserNoTypeConv, propType.Name); } else { ConverterCache.Add(t, tc); } } } return tc; }