public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile) { bamlCode.Position = 0; TextWriter w = new StringWriter(); Assembly assembly = Assembly.LoadFile(containingAssemblyFile); Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly }); XamlXmlWriter writer = new XamlXmlWriter(new XmlTextWriter(w) { Formatting = Formatting.Indented }, reader.SchemaContext); while (reader.Read()) { switch (reader.NodeType) { case XamlNodeType.None: break; case XamlNodeType.StartObject: writer.WriteStartObject(reader.Type); break; case XamlNodeType.GetObject: writer.WriteGetObject(); break; case XamlNodeType.EndObject: writer.WriteEndObject(); break; case XamlNodeType.StartMember: writer.WriteStartMember(reader.Member); break; case XamlNodeType.EndMember: writer.WriteEndMember(); break; case XamlNodeType.Value: // requires XamlReaderSettings.ValuesMustBeString = true to work properly writer.WriteValue(reader.Value); break; case XamlNodeType.NamespaceDeclaration: writer.WriteNamespace(reader.Namespace); break; default: throw new Exception("Invalid value for XamlNodeType"); } } return w.ToString(); }
private void OnLoadXaml(object sender, RoutedEventArgs e) { Person p1 = new Person { FirstName = "Stephanie", LastName = "Nagel" }; string s = XamlServices.Save(p1); XamlServices.Save("person.xaml", p1); var writer = new XamlObjectWriter(new XamlSchemaContext()); FileStream fStream = File.OpenRead("LoadXAML.exe"); var bamlReader = new Baml2006Reader(fStream, new XamlReaderSettings { LocalAssembly = Assembly.GetExecutingAssembly() }); // Baml2006Reader bamlReader = new Baml2006Reader("../../../XAMLIntro/bin/debug/XAMLIntro.exe"); FileStream stream = File.Create("myfile.xaml"); XamlSchemaContext schemaContext = new XamlSchemaContext( new XamlSchemaContextSettings { FullyQualifyAssemblyNamesInClrNamespaces = true, SupportMarkupExtensionsWithDuplicateArity = true }); XamlXmlWriter xmlWriter = new XamlXmlWriter(stream, schemaContext); XamlServices.Transform(bamlReader, xmlWriter, true); XamlServices.Transform(new XamlXmlReader("person.xaml"), writer, true); // string s2 = XamlServices.Save(this); //OpenFileDialog dlg = new OpenFileDialog(); //if (dlg.ShowDialog() == true) //{ // object xaml = XamlServices.Load(dlg.FileName); // XamlSchemaContext schema = new XamlSchemaContext( // new XamlSchemaContextSettings // { // FullyQualifyAssemblyNamesInClrNamespaces = true, // SupportMarkupExtensionsWithDuplicateArity = true // }); // XamlWriter writer = new XamlXmlWriter(stream, schema); // XamlServices.Save( }
public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile) { bamlCode.Position = 0; TextWriter w = new StringWriter(); Assembly assembly = Assembly.LoadFile(containingAssemblyFile); Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly }); XDocument doc = new XDocument(); XamlXmlWriter writer = new XamlXmlWriter(doc.CreateWriter(), reader.SchemaContext); while (reader.Read()) { switch (reader.NodeType) { case XamlNodeType.None: break; case XamlNodeType.StartObject: writer.WriteStartObject(reader.Type); break; case XamlNodeType.GetObject: writer.WriteGetObject(); break; case XamlNodeType.EndObject: writer.WriteEndObject(); break; case XamlNodeType.StartMember: writer.WriteStartMember(reader.Member); break; case XamlNodeType.EndMember: writer.WriteEndMember(); break; case XamlNodeType.Value: // requires XamlReaderSettings.ValuesMustBeString = true to work properly writer.WriteValue(reader.Value); break; case XamlNodeType.NamespaceDeclaration: writer.WriteNamespace(reader.Namespace); break; default: throw new Exception("Invalid value for XamlNodeType"); } } writer.Close(); // Fix namespace references string suffixToRemove = ";assembly=" + assembly.GetName().Name; foreach (XAttribute attrib in doc.Root.Attributes()) { if (attrib.Name.Namespace == XNamespace.Xmlns) { if (attrib.Value.EndsWith(suffixToRemove, StringComparison.Ordinal)) { string newNamespace = attrib.Value.Substring(0, attrib.Value.Length - suffixToRemove.Length); ChangeXmlNamespace(doc, attrib.Value, newNamespace); attrib.Value = newNamespace; } } } // Convert x:Key into an attribute where possible XName xKey = XName.Get("Key", "http://schemas.microsoft.com/winfx/2006/xaml"); foreach (XElement e in doc.Descendants(xKey).ToList()) { if (e.Nodes().Count() != 1) continue; XText text = e.Nodes().Single() as XText; if (text != null) { e.Parent.SetAttributeValue(xKey, text.Value); e.Remove(); } } return doc.ToString(); }
private ResourceDictionary LoadDictionary(Assembly assembly, string assemblyName, string resourceName, bool isTraceEnabled) { ResourceDictionary dictionary = null; // Create the resource manager that will load the byte array ResourceManager rm = new ResourceManager(assemblyName + ".g", assembly); resourceName = resourceName + ".baml"; // Load the resource stream Stream stream = null; try { stream = rm.GetStream(resourceName, CultureInfo.CurrentUICulture); } // There is no ResourceManager.HasManifest in order to detect this case before an exception is thrown. // Likewise, there is no way to know if loading a resource will fail prior to loading it. // So, the exceptions must be caught. stream will continue to be null and handled accordingly later. #pragma warning disable 6502 catch (MissingManifestResourceException) { // No usable resources in the assembly } #if !DEBUG catch (InvalidOperationException) { // Object not stored correctly } #endif #pragma warning restore 6502 if (stream != null) { Baml2006ReaderSettings settings = new Baml2006ReaderSettings(); settings.OwnsStream = true; settings.LocalAssembly = assembly; Baml2006Reader bamlReader = new Baml2006Reader(stream, new Baml2006SchemaContext(settings.LocalAssembly), settings); System.Xaml.XamlObjectWriterSettings owSettings = XamlReader.CreateObjectWriterSettingsForBaml(); if (assembly != null) { owSettings.AccessLevel = XamlAccessLevel.AssemblyAccessTo(assembly); } System.Xaml.XamlObjectWriter writer = new System.Xaml.XamlObjectWriter(bamlReader.SchemaContext, owSettings); if (owSettings.AccessLevel != null) { XamlLoadPermission loadPermission = new XamlLoadPermission(owSettings.AccessLevel); loadPermission.Assert(); try { System.Xaml.XamlServices.Transform(bamlReader, writer); } finally { CodeAccessPermission.RevertAssert(); } } else { System.Xaml.XamlServices.Transform(bamlReader, writer); } dictionary = (ResourceDictionary)writer.Result; if (isTraceEnabled && (dictionary != null)) { EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientResourceBamlAssembly, EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose, assemblyName); } } return dictionary; }
public string DecompileBaml(MemoryStream bamlCode, string containingAssemblyFile, ConnectMethodDecompiler connectMethodDecompiler, AssemblyResolver asmResolver) { this.asmResolver = asmResolver; AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; bamlCode.Position = 0; TextWriter w = new StringWriter(); Assembly assembly = Assembly.LoadFile(containingAssemblyFile); Baml2006Reader reader = new Baml2006Reader(bamlCode, new XamlReaderSettings() { ValuesMustBeString = true, LocalAssembly = assembly }); var xamlDocument = Parse(reader); string bamlTypeName = xamlDocument.OfType<XamlObjectNode>().First().Type.UnderlyingType.FullName; var eventMappings = connectMethodDecompiler.DecompileEventMappings(bamlTypeName); foreach (var xamlNode in xamlDocument) { RemoveConnectionIds(xamlNode, eventMappings, reader.SchemaContext); AvoidContentProperties(xamlNode); MoveXKeyToFront(xamlNode); } XDocument doc = new XDocument(); XamlXmlWriter writer = new XamlXmlWriter(doc.CreateWriter(), reader.SchemaContext, new XamlXmlWriterSettings { AssumeValidInput = true }); foreach (var xamlNode in xamlDocument) xamlNode.WriteTo(writer); writer.Close(); // Fix namespace references string suffixToRemove = ";assembly=" + assembly.GetName().Name; foreach (XAttribute attrib in doc.Root.Attributes()) { if (attrib.Name.Namespace == XNamespace.Xmlns) { if (attrib.Value.EndsWith(suffixToRemove, StringComparison.Ordinal)) { string newNamespace = attrib.Value.Substring(0, attrib.Value.Length - suffixToRemove.Length); ChangeXmlNamespace(doc, attrib.Value, newNamespace); attrib.Value = newNamespace; } } } return doc.ToString(); }
private void ExtractBAML(string name, Stream stream) { var reader = new Baml2006Reader(stream); var settings = new XamlObjectWriterSettings (); settings.BeforePropertiesHandler += (sender, e) => { Trace("properties for {0}", e.Instance); }; settings.XamlSetValueHandler += (sender, e) => { //TraceTarget.Trace("set value {0} = {1}", e.Member.Name, e.Value); /*if (e.Member.Name == "DeferrableContent") { e.Handled = true; }*/ }; var writer = new XamlObjectWriter(reader.SchemaContext, settings); while (reader.Read()) { writer.WriteNode(reader); } var x = writer.Result; var ms = new MemoryStream(); using (var xwriter = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true })) { System.Windows.Markup.XamlWriter.Save(x, xwriter); } var xamlname = Path.ChangeExtension(name, ".xaml"); ms.Position = 0; AddResource(xamlname, ms); }
//[CodeAnalysis("AptcaMethodsShouldOnlyCallAptcaMethods")] //Tracking Bug: 29647 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 Baml2006Reader(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); }
private void SetDeferrableContent(DeferrableContent deferrableContent) { Debug.Assert(deferrableContent.Stream != null); Debug.Assert(deferrableContent.SchemaContext != null); Debug.Assert(deferrableContent.ObjectWriterFactory != null); Debug.Assert(deferrableContent.ServiceProvider != null); Debug.Assert(deferrableContent.RootObject != null); Baml2006ReaderSettings settings = new Baml2006ReaderSettings(deferrableContent.SchemaContext.Settings); settings.IsBamlFragment = true; settings.OwnsStream = true; settings.BaseUri = null; // Base URI can only be set on the root object, not on deferred content. Baml2006Reader reader = new Baml2006Reader(deferrableContent.Stream, deferrableContent.SchemaContext, settings); _objectWriterFactory = deferrableContent.ObjectWriterFactory; _objectWriterSettings = deferrableContent.ObjectWriterParentSettings; _deferredLocationList = new List<KeyRecord>(); _rootElement = deferrableContent.RootObject; IList<KeyRecord> keys = reader.ReadKeys(); // If we already have the Source set then we can ignore // this deferable content section if (_source == null) { if (_reader == null) { _reader = reader; _xamlLoadPermission = deferrableContent.LoadPermission; SetKeys(keys, deferrableContent.ServiceProvider); } else { throw new InvalidOperationException(SR.Get(SRID.ResourceDictionaryDuplicateDeferredContent)); } } else if (keys.Count > 0) { throw new InvalidOperationException(SR.Get(SRID.ResourceDictionaryDeferredContentFailure)); } }
/// <summary> /// Устанавливает Baml скин приложения /// </summary> /// <param name="skinPath"></param> protected void ApplySkinBaml(string skinPath) { FileStream fstream = new FileStream(skinPath, FileMode.Open); Baml2006Reader reader = new Baml2006Reader(fstream); ResourceDictionary rd = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(reader); //ResourceDictionary rd = (ResourceDictionary)System.Windows.Markup.XamlReader.Load(fstream); App.Current.Resources.MergedDictionaries.Add(rd); //reader.Close(); fstream.Close(); }