Ejemplo n.º 1
0
        private static Style ReadDefaultStyle(Type type)
        {
            var assembly = type.Assembly;

            using (var resourceReader = new ResourceReader(assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().Single())))
            {
                foreach (DictionaryEntry entry in resourceReader)
                {
                    using (var reader = new Baml2006Reader((Stream)entry.Value))
                    {
                        using (var writer = new XamlObjectWriter(reader.SchemaContext))
                        {
                            while (reader.Read())
                            {
                                writer.WriteNode(reader);
                            }

                            var resourceDictionary = (ResourceDictionary)writer.Result;
                            if (resourceDictionary.Contains(type))
                            {
                                return((Style)resourceDictionary[type]);
                            }
                        }
                    }
                }
            }

            throw new ArgumentOutOfRangeException();
        }
Ejemplo n.º 2
0
        private XAMLFileDetails ParseXAMLFile(Assembly assembly, string resourceName, Stream stream)
        {
            XAMLFileDetails fileDetails = null;
            XDocument       document    = new XDocument();

            // Read the contents of the BAML file and decode it into a XAML document
            var reader = new Baml2006Reader(stream, new XamlReaderSettings()
            {
                ValuesMustBeString = true, LocalAssembly = assembly
            });
            var writer = new XamlXmlWriter(document.CreateWriter(), reader.SchemaContext, new XamlXmlWriterSettings()
            {
                AssumeValidInput = true
            });

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

            writer.Close();

            // Now check if it's a resource dictionary (which we ignore). If a normal view, parse it.
            XNamespace defaultNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";

            bool isResourceDictionary = (document.Root.Name == XName.Get("ResourceDictionary", defaultNamespace.NamespaceName));

            if (!isResourceDictionary)
            {
                fileDetails = new XAMLFileDetails(resourceName, document);
            }

            return(fileDetails);
        }
Ejemplo n.º 3
0
        public static TRoot LoadBaml <TRoot>(Stream stream)
        {
            Baml2006Reader baml     = new Baml2006Reader(stream);
            object         bamlRoot = XamlReader.Load(baml);

            return((TRoot)bamlRoot);
        }
Ejemplo n.º 4
0
        public static T LoadBaml <T>(Stream stream)
        {
            //For .net 3.5:
            //ParserContext parserContext = new ParserContext();
            //object[] parameters = new object[] { stream, parserContext, null, false };
            //object bamlRoot = LoadBamlMethod.Invoke(null, parameters);
            //return (T)bamlRoot;

            //For .net 4.0
            var reader = new Baml2006Reader(stream);

            var substream = reader.Value as MemoryStream;

            if (substream != null)
            {
                using (var subReader = CreateBamlFragmentReader(substream, reader.SchemaContext))
                {
                    var writer = new XamlObjectWriter(subReader.SchemaContext);
                    while (subReader.Read())
                    {
                        writer.WriteNode(subReader);
                    }
                    return((T)writer.Result);
                }
            }
            else
            {
                var writer = new XamlObjectWriter(reader.SchemaContext);
                while (reader.Read())
                {
                    writer.WriteNode(reader);
                }
                return((T)writer.Result);
            }
        }
Ejemplo n.º 5
0
        static SpreadTraderWindow CreateFromBaml(Assembly localAssembly)
        {
            SpreadTraderWindow obj = null;

            try

            {
                string       assname = localAssembly.FullName;
                MemoryStream ms      = new MemoryStream();
                using (MemoryStream fstream = new MemoryStream(baml, false))
                //using (FileStream fstream = new FileStream(@"Properties\\SpreadTraderWindow.baml", FileMode.Open))
                {
                    long   len    = fstream.Length;
                    byte[] buffer = new byte[1024];
                    len -= fstream.Read(buffer, 0, 40);
                    ms.Write(buffer, 0, 39);
                    int i = buffer[39];
                    len -= fstream.Read(buffer, 0, i);
                    byte[] bytes = Encoding.Default.GetBytes(assname);
                    byte   b     = (byte)bytes.Length;
                    ms.WriteByte(b);
                    ms.Write(bytes, 0, bytes.Length);
                    while (len > 0)
                    {
                        long chunk = (len > 1024L) ? 1024L : len;
                        len -= fstream.Read(buffer, 0, (int)chunk);
                        ms.Write(buffer, 0, (int)chunk);
                    }
                }
                ms.Seek(0, SeekOrigin.Begin);

                XamlReaderSettings settings = new XamlReaderSettings();
                settings.LocalAssembly = localAssembly;
                Baml2006Reader reader = new Baml2006Reader(ms, settings);
                obj = System.Windows.Markup.XamlReader.Load(reader) as SpreadTraderWindow;


                LinearGradientBrush btnbackgroundBrush = Application.Current.TryFindResource("SuperDom.ButtonBackground") as LinearGradientBrush;

                obj.btnReverse.Background = btnbackgroundBrush;
                obj.btnClose.Background   = btnbackgroundBrush;
                obj.btnGoLong.Background  = btnbackgroundBrush;
                obj.btnGoShort.Background = btnbackgroundBrush;
                QtyLongBackgroundBrush    = Application.Current.TryFindResource("BasicEntry.PositionQtyLongBackground") as SolidColorBrush;
                QtyShortBackgroundBrush   = Application.Current.TryFindResource("BasicEntry.PositionQtyShortBackground") as SolidColorBrush;
                SolidColorBrush PnLBackgroundBrush = Application.Current.TryFindResource("BasicEntry.PnLBackground") as SolidColorBrush;
                obj.unrealizedPNL.Background = PnLBackgroundBrush;

                obj.btnAddTicket.IsEnabled = false;
            }
            catch (Exception ex) {
                Zweistein.Diagnostics.Trace(ex.Message);
            }


            return(obj);
        }
Ejemplo n.º 6
0
        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());
        }
Ejemplo n.º 7
0
        public BamlToXamlReader(Stream bamlStream, Assembly localAssembly)
        {
            XamlReaderSettings readerSettings = new XamlReaderSettings
            {
                LocalAssembly      = localAssembly,
                ValuesMustBeString = true
            };

            _bamlReader = new Baml2006Reader(bamlStream, readerSettings);
        }
Ejemplo n.º 8
0
        public BamlNodeStreamReader(Stream bamlStream, Assembly localAssembly)
        {
            XamlReaderSettings readerSettings = new XamlReaderSettings
            {
                LocalAssembly      = localAssembly,
                ValuesMustBeString = true
            };

            _bamlReader    = new Baml2006Reader(bamlStream, readerSettings);
            _displayWriter = new DiagnosticWriter(_bamlReader.SchemaContext);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Load xaml resource stream
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static object Load(Stream stream)
        {
            var reader = new Baml2006Reader(stream);
            var writer = new XamlObjectWriter(reader.SchemaContext);

            while (reader.Read())
            {
                writer.WriteNode(reader);
            }
            return(writer.Result);
        }
Ejemplo n.º 10
0
        private static T LoadBaml <T>(Stream stream, bool keepStreamOpen = false)
        {
            var reader = new Baml2006Reader(stream);
            var result = (T)XamlReader.Load(reader);

            if (!keepStreamOpen)
            {
                stream.Dispose();
            }
            return(result);
        }
Ejemplo n.º 11
0
        private static T ReadBaml <T>(Stream stream)
        {
            var bamlReader = new Baml2006Reader(stream);
            var writer     = new XamlObjectWriter(bamlReader.SchemaContext);

            while (bamlReader.Read())
            {
                writer.WriteNode(bamlReader);
            }
            return((T)writer.Result);
        }
Ejemplo n.º 12
0
        /// <summary>Loads the baml.</summary>
        /// <typeparam name="TRoot">The type of the root.</typeparam>
        /// <param name="stream">The <paramref name="stream"/>.</param>
        /// <returns>the loaded <see langword="object"/> parameter</returns>
        /// <exception cref="ArgumentNullException"><paramref>
        ///         <name>reader</name>
        ///     </paramref>
        ///     is null.</exception>
        /// <exception cref="NotImplementedException">The default implementation encountered a <see cref="T:System.Xaml.XamlNodeType" /> that is not in the default enumeration.</exception>
        internal static TRoot LoadBaml <TRoot>(Stream stream)
        {
            var reader = new Baml2006Reader(stream);
            var writer = new XamlObjectWriter(reader.SchemaContext);

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

            return((TRoot)writer.Result);
        }
Ejemplo n.º 13
0
        private static ResourceDictionary CreateEmptyResourceDictionaryInstance(Uri uri)
        {
            try
            {
                var streamInfo = Application.GetResourceStream(RebuildBamlUri(uri));

                if (streamInfo == null)
                {
                    return(null);
                }

#if !SILVERLIGHT
                if (IsBamlResource(uri))
                {
                    using (var bamlReader = new Baml2006Reader(streamInfo.Stream))
                    {
                        while (bamlReader.Read())
                        {
                            if (bamlReader.NodeType != XamlNodeType.StartObject)
                            {
                                continue;
                            }

                            if (bamlReader.Type == null)
                            {
                                return(null);
                            }

                            var objectType = bamlReader.Type.UnderlyingType;
                            if (objectType == typeof(ResourceDictionary) || objectType.IsSubclassOf(typeof(ResourceDictionary)))
                            {
                                return((ResourceDictionary)Activator.CreateInstance(objectType));
                            }
                        }
                    }
                    return(null);
                }
#endif

                using (var streamReader = new StreamReader(streamInfo.Stream, Encoding.UTF8))
                    return(GetResourceDictionary(XElement.Parse(streamReader.ReadToEnd()).Name));
            }
            catch (Exception e)
            {
                LogService.LogError(e);
            }

            return(null);
        }
Ejemplo n.º 14
0
        /// <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();
        }
Ejemplo n.º 15
0
        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(
        }
Ejemplo n.º 16
0
        private void ScanPages()
        {
            // KsWare.Presentation.UITestApp.g.resources
            var asm     = Assembly.GetEntryAssembly();
            var resName = asm.GetName().Name + ".g.resources";

            using (var stream = asm.GetManifestResourceStream(resName))
                using (var reader = new System.Resources.ResourceReader(stream)) {
                    var resources = reader.Cast <DictionaryEntry>().Select(entry => (string)entry.Key).ToArray();
                    foreach (var resource in resources)
                    {
                        if (!resource.StartsWith("pages/"))
                        {
                            continue;
                        }
                        var uri        = new Uri(resource.Substring(0, resource.Length - 5) + ".xaml", UriKind.Relative);
                        var restream   = Application.GetResourceStream(uri).Stream;
                        var bamlReader = new Baml2006Reader(restream);
                        var writer     = new XamlObjectWriter(bamlReader.SchemaContext);
                        try {
                            while (bamlReader.Read())
                            {
                                writer.WriteNode(bamlReader);
                            }
                        }
                        catch (Exception ex) {
                            var lineInfo = (IXamlLineInfo)bamlReader;
                            Debug.WriteLine($"Error loading {resource}: {lineInfo.LineNumber},{lineInfo.LinePosition}. Message: {ex.Message}");
                            MessageBox.Show($"Error loading {resource}: {lineInfo.LineNumber},{lineInfo.LinePosition}. \nMessage: \n{ex.Message}", "Error");
                            continue;
                        }
                        var xamlObject = writer.Result;
                        var name       = xamlObject.GetType().Name;

                        Pages.Add(new PageInfoVM()
                        {
                            DisplayName = name,
                            Uri         = uri,
                            View        = (FrameworkElement)xamlObject
                        });
                    }
                }
        }
Ejemplo n.º 17
0
        private IDataObject TempLoadDat()
        {
            {
                object object1;
                using (Baml2006Reader reader1 = new Baml2006Reader(this.MemoryStream))
                {
                    try
                    {
                        object1 = XamlReader.Load(reader1);
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex);
                        throw;
                    }
                }

                return(new DataObject("BAML", object1));
            }
        }
Ejemplo n.º 18
0
        // Token: 0x0600226C RID: 8812 RVA: 0x000AB378 File Offset: 0x000A9578
        private static void WriteValue(XamlReader xamlReader, XamlObjectWriter xamlWriter, XamlContextStack <WpfXamlFrame> stack, IStyleConnector styleConnector)
        {
            bool flag;

            if (stack.CurrentFrame.Property.IsDirective && stack.CurrentFrame.Property == XamlLanguage.Shared && bool.TryParse(xamlReader.Value as string, out flag) && !flag && !(xamlReader is Baml2006Reader))
            {
                throw new XamlParseException(SR.Get("SharedAttributeInLooseXaml"));
            }
            if (stack.CurrentFrame.Property.IsDirective && stack.CurrentFrame.Property == XamlReaderHelper.Freeze)
            {
                bool flag2 = Convert.ToBoolean(xamlReader.Value, TypeConverterHelper.InvariantEnglishUS);
                stack.CurrentFrame.FreezeFreezable = flag2;
                Baml2006Reader baml2006Reader = xamlReader as Baml2006Reader;
                if (baml2006Reader != null)
                {
                    baml2006Reader.FreezeFreezables = flag2;
                    return;
                }
            }
            else if (stack.CurrentFrame.Property == WpfXamlLoader.XmlSpace.Value || stack.CurrentFrame.Property == XamlLanguage.Space)
            {
                if (typeof(DependencyObject).IsAssignableFrom(stack.CurrentFrame.Type.UnderlyingType))
                {
                    stack.CurrentFrame.XmlSpace = new bool?((string)xamlReader.Value == "default");
                    return;
                }
            }
            else
            {
                if (styleConnector != null && stack.CurrentFrame.Instance != null && stack.CurrentFrame.Property == XamlLanguage.ConnectionId && typeof(Style).IsAssignableFrom(stack.CurrentFrame.Type.UnderlyingType))
                {
                    styleConnector.Connect((int)xamlReader.Value, stack.CurrentFrame.Instance);
                }
                xamlWriter.WriteNode(xamlReader);
            }
        }
Ejemplo n.º 19
0
        //[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);
        }
Ejemplo n.º 20
0
        private BamlControl LoadBaml(string name)
        {
            if (assembly == null)
            {
                assembly = Assembly.GetCallingAssembly();
            }

            if (assemblyName == "")
            {
                assemblyName = Language.GetAssemblyName(Assembly.GetCallingAssembly());
            }

            string language = Language.Id;

            if (language == "")
            {
                language = Thread.CurrentThread.CurrentUICulture.ToString();
            }

            string bamlName = name.ToLower() + ".baml";

            // Get the name of g-resource
            string resourceName = assemblyName + ".g";

            if ((language != "") && (language != Language.OriginalId))
            {
                resourceName = resourceName + "." + language;
            }

            resourceName = resourceName + ".resources";

            Stream      stream  = assembly.GetManifestResourceStream(resourceName);
            BamlControl current = null;

            using (var resourceReader = new ResourceReader(stream))
            {
                foreach (DictionaryEntry entry in resourceReader)
                {
                    if (entry.Key.ToString() == bamlName)
                    {
                        Stream bamlStream = entry.Value as Stream;

                        var    bamlReader = new Baml2006Reader(bamlStream);
                        string memberName = "";

                        var baml = new BamlControl();
                        current = null;

                        while (bamlReader.Read())
                        {
                            XamlNodeType nodeType = bamlReader.NodeType;

                            switch (bamlReader.NodeType)
                            {
                            case XamlNodeType.StartObject:
                                if (current == null)
                                {
                                    current = baml;
                                }
                                else
                                {
                                    current = current.Add(new BamlControl());
                                }

                                if (bamlReader.Type != null)
                                {
                                    current.ElementName = bamlReader.Type.ToString();
                                }

                                break;

                            case XamlNodeType.GetObject:
                                current            = current.Add(new BamlControl());
                                current.MemberName = memberName;
                                break;

                            case XamlNodeType.EndObject:
                                if (current != null)
                                {
                                    current = current.Parent;
                                }

                                break;

                            case XamlNodeType.StartMember:
                                memberName = bamlReader.Member.Name;
                                break;

                            case XamlNodeType.EndMember:
                                memberName = "";
                                break;

                            case XamlNodeType.Value:
                                if (memberName == "Name")
                                {
                                    current.Name = bamlReader.Value.ToString();
                                }
                                else if (memberName == "Uid")
                                {
                                    current.Uid = bamlReader.Value.ToString();
                                }
                                else if (memberName == "Content")
                                {
                                    current.Value = bamlReader.Value;
                                }
                                else if (memberName != "")
                                {
                                    current.AddProperty(memberName, bamlReader.Value);
                                }

                                break;
                            }
                        }

                        return(baml);
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 21
0
        /* Usage A
         *
         *      <ContentPresenter Content="{Binding Source, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:ResourcePresenter}}, Converter={x:Static Converters:UIElementConverter.Default}}"/>
         *      - or more easy width intellisense support -
         *      <Controls:ResourcePresenter Source="pack://application:,,,/Folder/FileName.Ext"/>
         */

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (culture == null)
            {
                culture = Thread.CurrentThread.CurrentUICulture;
            }
            Uri ressourceUri;

            if (parameter != null)
            {
                if (parameter is string)
                {
                    ressourceUri = new Uri((string)parameter);
                }
                else
                {
                    Debug.WriteLine("=>WARNING: Parameter not supported! " +
                                    "\r\n\t" + "Parameter:" + (value == null?"{NULL}":value.ToString()) +
                                    "\r\n\t" + "UniqueID: {22C20F20-E9CA-4586-8928-0A080BAAEA83}");
                    return(null);
                }
            }
            else
            {
                if (value is Uri)
                {
                    //->  pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
                    //->  /ReferencedAssembly;component/Subfolder/ResourceFile.xaml
                    ressourceUri = (Uri)value;
                }
                else
                {
                    Debug.WriteLine("=>WARNING: Value not supported! " +
                                    "\r\n\t" + "Value:" + (value == null?"{NULL}":value.ToString()) +
                                    "\r\n\t" + "UniqueID: {5ED3F3D1-8AA8-4BF2-885B-5834DA371F12}");
                    return(null);
                }
            }

            // make pack uri (ImageSourceConverter need this)
            if (!ressourceUri.IsAbsoluteUri)
            {
                ressourceUri = new Uri("pack://application:,,," + ressourceUri.ToString());               //TODO add some checks
            }

            // extract the extension
            var ext = Path.GetExtension(ressourceUri.ToString().ToLower(CultureInfo.InvariantCulture));

            var uiElement = (object)null;

            switch (ext)
            {
            case ".ico":
            case ".jpg":
            case ".png":
            case ".gif":
            case ".bmp":
                //TODO possible NullReferenceException if resource not exists
                var imageSource = (ImageSource)ImageSourceConverter.ConvertFrom(ressourceUri);
                uiElement = new Image {
                    Source = imageSource
                };
                break;

            case ".baml":
            case ".xaml":
                var stream = GetResourceStream(ressourceUri, culture, ref ext);
                if (ext == ".baml")
                {
                    using (var bamlReader = new Baml2006Reader(stream)) uiElement = XamlReader.Load(bamlReader);
                }
                else if (ext == ".xaml")
                {
                    uiElement = XamlReader.Load(stream);
                }
                break;

            default:
                Debug.WriteLine("=>ERROR: Type of resource not supported!" +
                                "\r\n\t" + "Extension: " + ext +
                                "\r\n\t" + "Resource: " + ressourceUri.ToString() +
                                "\r\n\t" + "UniqueID: {66CC87C5-2A06-4424-9797-0F931ED533C0}");
                break;
            }

            return(uiElement);
        }
Ejemplo n.º 22
0
        SelectResourceDictionaries(this Assembly assembly, Predicate <DictionaryEntry>?predicate = null, bool ignoreXamlReaderExceptions = false)
        {
            // Only interested in main resource file
            return(GetResourceNames().SelectMany(GetDictionaries));

            IEnumerable <(DictionaryEntry, ResourceDictionary)> GetDictionaries(string resourceName)
            {
                Stream?resourceStream = assembly.GetManifestResourceStream(resourceName);

                if (resourceStream == null)
                {
                    throw new Exception("dsf33211..33");
                }
                using (ResourceReader reader = new ResourceReader(resourceStream))
                {
                    var entries = GetDictionaryEntries(reader);
                    foreach (DictionaryEntry entry in entries)
                    {
                        if (predicate?.Invoke(entry) == false)
                        {
                            continue;
                        }

                        ResourceDictionary dictionary;
                        var                readStream   = entry.Value as Stream;
                        Baml2006Reader     bamlReader   = new Baml2006Reader(readStream);
                        ResourceDictionary?loadedObject = null;
                        try
                        {
                            loadedObject = System.Windows.Markup.XamlReader.Load(bamlReader) as ResourceDictionary;
                        }
                        catch (Exception ex)
                        {
                            if (ignoreXamlReaderExceptions == false)
                            {
                                throw;
                            }
                        }

                        if (loadedObject != null)
                        {
                            dictionary = loadedObject;
                        }
                        else
                        {
                            continue;
                        }
                        yield return(entry, dictionary);
                    }
                }
            }

            DictionaryEntry[] GetDictionaryEntries(ResourceReader reader)
            {
                var entries = reader.OfType <DictionaryEntry>()
                              // only interested in baml(xaml) files not images or similar
                              .Where(entry => entry.Key.ToString()?.EndsWith("baml") == true &&
                                     entry.Key.ToString()?.ToLowerInvariant().Contains("generic") != true)
                              .ToArray();

                return(entries);
            }

            IEnumerable <string> GetResourceNames()
            {
                IEnumerable <string> allNames = assembly.GetManifestResourceNames();

                string[] resourceNames = assembly.GetManifestResourceNames().Where(a => a.EndsWith("g.resources")).ToArray();
                foreach (string resourceName in resourceNames)
                {
                    ManifestResourceInfo?info = assembly.GetManifestResourceInfo(resourceName);
                    if (info?.ResourceLocation != ResourceLocation.ContainedInAnotherAssembly)
                    {
                        yield return(resourceName);
                    }
                }
            }
        }
Ejemplo n.º 23
0
        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());
        }
Ejemplo n.º 24
0
        static void Main(string[] args)
        {
            XmlConfigurator.Configure();

            string        oldFolder = @"C:\";
            string        newFolder = @"C:\";
            DirectoryInfo oldDi     = new DirectoryInfo(oldFolder);
            DirectoryInfo newDi     = new DirectoryInfo(newFolder);

            if (oldDi.Exists && newDi.Exists)
            {
                FileInfo[] oldGenDll = oldDi.GetFiles(FILTER);
                FileInfo[] newGenDll = newDi.GetFiles(FILTER);

                if (oldGenDll.Length != newGenDll.Length)
                {
                    log.Info(string.Format("oldGenDll.Length = {0}, newGenDll.Length = {1}", oldGenDll.Length, newGenDll.Length));

                    // Compare names:
                    throw new NotImplementedException();
                }

                foreach (FileInfo fiOld in oldGenDll)
                {
                    FileInfo fiNew = newGenDll.Where(t => t.Name.Equals(fiOld.Name)).FirstOrDefault();

                    ModuleDefinition oldModule = ModuleDefinition.ReadModule(fiOld.FullName);
                    var oldTypes = oldModule.Types;
                    ModuleDefinition newModule = ModuleDefinition.ReadModule(fiNew.FullName);
                    var newTypes = newModule.Types;

                    if (oldTypes.Count != newTypes.Count)
                    {
                        Append2Dictionary(fiOld.Name, string.Format("oldTypes.Count = {0}, newTypes.Count = {1}", oldTypes.Count, newTypes.Count));

                        // Compare names:
                        var oldNames = oldTypes.Select(t => t.Name).ToList();
                        var newNames = newTypes.Select(t => t.Name).ToList();

                        CompareNames(fiOld.Name, oldNames, newNames, "Types Added", "Types Removed");
                    }

                    foreach (TypeDefinition oldType in oldTypes)
                    {
                        if (!oldType.IsInterface && !IsClassImplementInterfaceInList(oldType, MyInterfaces))
                        {
                            continue;
                        }

                        TypeDefinition newType = newTypes.Where(t => t.Name.Equals(oldType.Name)).FirstOrDefault();
                        if (newType == null)
                        {
                            continue;
                        }

                        //if (!MyInterfaces.Contains(oldType.Name))
                        //    continue;

                        var allOldMethods = oldType.Methods;
                        var allnewMethods = newType.Methods;

                        if (allOldMethods.Count != allnewMethods.Count)
                        {
                            Append2Dictionary(oldType.Name, string.Format("allOldMethods.Count = {0}, allnewMethods.Count = {1}", allOldMethods.Count, allnewMethods.Count));

                            // Compare names:
                            var oldNames = allOldMethods.Select(t => t.Name).ToList();
                            var newNames = allnewMethods.Select(t => t.Name).ToList();
                            CompareNames(oldType.Name, oldNames, newNames, "Methods Added", "Methods Removed");
                        }

                        foreach (MethodDefinition oldMdef in allOldMethods)
                        {
                            MethodDefinition newMdef = allnewMethods.Where(t => t.Name.Equals(oldMdef.Name)).FirstOrDefault();
                            if (newMdef == null)
                            {
                                continue;
                            }

                            string cSharpCodeDisAssembOld = getSourceCode(oldMdef);
                            if (string.IsNullOrWhiteSpace(cSharpCodeDisAssembOld))
                            {
                                continue;
                            }
                            string cSharpCodeDisAssembNew = getSourceCode(newMdef);
                            if (cSharpCodeDisAssembOld != cSharpCodeDisAssembNew)
                            {
                                Append2Dictionary(oldType.Name, TAB + oldMdef.Name + " are differents.");
                            }
                        }
                    }


                    // xaml
                    if (oldModule.Resources.Count > 0)
                    {
                        EmbeddedResource rOld      = (EmbeddedResource)oldModule.Resources.Where(r => r.Name.Contains(".g.")).FirstOrDefault();
                        ResourceReader   readerOld = null;
                        using (var stream = rOld.GetResourceStream())
                        {
                            using (readerOld = new ResourceReader(stream))
                            {
                                EmbeddedResource rNew      = (EmbeddedResource)newModule.Resources.Where(r => r.Name.Contains(".g.")).FirstOrDefault();
                                ResourceReader   readerNew = null;
                                using (var stream2 = rNew.GetResourceStream())
                                {
                                    using (readerNew = new ResourceReader(stream2))
                                    {
                                        foreach (DictionaryEntry entry in readerOld)
                                        {
                                            ///Read the values in the entry
                                            if (!entry.Key.ToString().Contains(BAML_EXTENSION))
                                            {
                                                continue;
                                            }
                                            string fullName         = entry.Key.ToString();
                                            int    indexOfLastSlash = fullName.LastIndexOf(@"/");
                                            int    indexOfDotBaml   = fullName.IndexOf(BAML_EXTENSION);
                                            string className        = entry.Key.ToString().Substring(indexOfLastSlash + 1, indexOfDotBaml - indexOfLastSlash - 1);

                                            var classOfThisBaml = oldTypes.Where(t => t.Name.ToLower().Equals(className)).FirstOrDefault();

                                            if (classOfThisBaml == null || (!classOfThisBaml.IsInterface && !IsClassImplementInterfaceInList(classOfThisBaml, MyInterfaces)))
                                            {
                                                continue;
                                            }

                                            //var newClassOfThisBaml = newTypes.Where(t => t.Name.ToLower().Equals(className)).FirstOrDefault();
                                            System.IO.MemoryStream codeofOldBaml = entry.Value as MemoryStream;
                                            string oldCode = string.Empty;
                                            using (StreamReader oldStreamR = new StreamReader(codeofOldBaml as Stream, Encoding.UTF8))
                                            {
                                                oldCode = oldStreamR.ReadToEnd();
                                                oldStreamR.Close();
                                            }

                                            Baml2006Reader reader = new Baml2006Reader(codeofOldBaml as Stream);
                                            while (!reader.IsEof)
                                            {
                                                var noeud = reader.Value;
                                                reader.Read();
                                            }
                                            //var writer = new XamlObjectWriter(reader.SchemaContext);
                                            //while (reader.Read())
                                            //    writer.WriteNode(reader);

                                            string typeofNewBaml = string.Empty;
                                            byte[] codeofNewBaml = null;
                                            readerNew.GetResourceData(fullName, out typeofNewBaml, out codeofNewBaml);
                                            // en fait le baml est un code précompilé, reste à trouver comment le décompiler en xaml
                                            string newcode = Encoding.UTF8.GetString(codeofNewBaml);
                                        }
                                        stream2.Close();
                                    }
                                    readerNew.Close();
                                }
                            }
                            readerOld.Close();

                            stream.Close();
                        }
                    }

                    // print
                    //if (bufferInfo.Count > 1)
                    {
                        foreach (var item in bufferInfo)
                        {
                            log.Info(item.Key);
                            foreach (var line in item.Value)
                            {
                                log.Info(line);
                            }
                        }
                        if (bufferInfo.Count > 0)
                        {
                            NewLine();
                        }
                    }

                    bufferInfo.Clear();
                }
            }
        }