Ejemplo n.º 1
0
        private static void Merge(ResourceDictionary resourceDictionary, FileInfo file)
        {
            ResourceDictionary targetDictionary;

            using (FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
            {
                XamlReader reader = new XamlReader();
                targetDictionary = (ResourceDictionary)reader.LoadAsync(fs);
            }

            foreach (var key in resourceDictionary.Keys)
            {
                if (!targetDictionary.Contains(key))
                {
                    Console.WriteLine($"{key.ToString()} is not found, adding to the target resource dictionary");
                    targetDictionary.Add(key, resourceDictionary[key]);
                }
            }

            using (FileStream fs = new FileStream(file.FullName, FileMode.OpenOrCreate, FileAccess.Write))
            {
                var writer = XmlWriter.Create(fs, new XmlWriterSettings()
                {
                    Indent = true
                });
                XamlWriter.Save(targetDictionary, writer);
                writer.Close();
            }
        }
Ejemplo n.º 2
0
 private void LoadCustomTheme()
 {
     if (UserSettings.PlayerConfig.HunterPie.Theme == null || UserSettings.PlayerConfig.HunterPie.Theme == "Default")
     {
         return;
     }
     if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes")))
     {
         Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Themes"));
     }
     if (!File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}")))
     {
         Debugger.Error(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_FOUND_ERROR']".Replace("{THEME_NAME}", UserSettings.PlayerConfig.HunterPie.Theme)));
         return;
     }
     try {
         using (FileStream stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}"), FileMode.Open)) {
             XamlReader         reader          = new XamlReader();
             ResourceDictionary ThemeDictionary = (ResourceDictionary)reader.LoadAsync(stream);
             Application.Current.Resources.MergedDictionaries.Add(ThemeDictionary);
             Debugger.Warn(GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_LOAD_WARN']"));
         }
     } catch (Exception err) {
         Debugger.Error($"{GStrings.GetLocalizationByXPath("/Console/String[@ID='MESSAGE_THEME_NOT_LOAD_ERROR']")}\n{err}");
     }
 }
Ejemplo n.º 3
0
        private ListBox ListBox()
        {
            var listbox = new ListBox();

            listbox.ItemsPanel      = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(WrapPanel)));
            listbox.BorderThickness = new Thickness(0);
            listbox.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
            listbox.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
            var itemTemplate = new ControlTemplate(typeof(ListBoxItem));

            itemTemplate.VisualTree    = new FrameworkElementFactory(typeof(ContentPresenter));
            listbox.ItemContainerStyle = new Style {
                TargetType = typeof(ListBoxItem)
            };
            listbox.ItemContainerStyle.Setters.Add(new Setter {
                Property = Control.TemplateProperty, Value = itemTemplate
            });
            using (var stream = GetType().Assembly.GetManifestResourceStream(TEMPLATE))
            {
                var reader = new XamlReader();
                listbox.ItemTemplate = (DataTemplate)reader.LoadAsync(stream);
            }
            listbox.Margin = new Thickness(20, 10, 10, 20);
            listbox.Width  = 800;
            return(listbox);
        }
Ejemplo n.º 4
0
        public void XamlReaderLoadAsync()
        {
            var reader = new XamlReader();

            Pattern.CreateByName(it =>
                                 reader.LoadAsync(it.IsPayloadOf <ObjectDataProvider>().Format <Xaml>()));
        }
Ejemplo n.º 5
0
        public AudioControllerPluginConfigViewModel(PluginSystem.IPlugin Plugin, PluginSystem.PluginConfig PluginConfig)
            : base(Plugin, PluginConfig)
        {
            Uri uri = new Uri("pack://application:,,,/LauncherSilo.AudioControllerPlugin;component/AudioControllerPluginResource.xaml");
            StreamResourceInfo info   = Application.GetResourceStream(uri);
            XamlReader         reader = new XamlReader();
            var dictionary            = reader.LoadAsync(info.Stream) as ResourceDictionary;

            PluginConfigControlTemplate = dictionary["AudioControllerPluginConfigView"] as ControlTemplate;

            NAudio.CoreAudioApi.MMDeviceEnumerator enumerator = new NAudio.CoreAudioApi.MMDeviceEnumerator();
            NAudio.CoreAudioApi.MMDeviceCollection endPoints  = enumerator.EnumerateAudioEndPoints(NAudio.CoreAudioApi.DataFlow.All, NAudio.CoreAudioApi.DeviceState.All);
            foreach (NAudio.CoreAudioApi.MMDevice endPoint in endPoints)
            {
                if (endPoint.State == NAudio.CoreAudioApi.DeviceState.NotPresent)
                {
                    continue;
                }
                if (endPoint.DataFlow == NAudio.CoreAudioApi.DataFlow.Render)
                {
                    AudioPlaybackDeviceVM.Add(new AudioDeviceViewModel(endPoint));
                }
                else if (endPoint.DataFlow == NAudio.CoreAudioApi.DataFlow.Capture)
                {
                    AudioCaptureDeviceVM.Add(new AudioDeviceViewModel(endPoint));
                }
            }
        }
Ejemplo n.º 6
0
        internal static object XamlConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter)
        {
            asyncObjectConverter = null;
            if (sandboxExternalContent)
            {
                if (SecurityHelper.AreStringTypesEqual(baseUri.Scheme, BaseUriHelper.PackAppBaseUri.Scheme))
                {
                    baseUri = BaseUriHelper.ConvertPackUriToAbsoluteExternallyVisibleUri(baseUri);
                }
                stream.Close();
                return(new WebBrowser
                {
                    Source = baseUri
                });
            }
            ParserContext parserContext = new ParserContext();

            parserContext.BaseUri = baseUri;
            parserContext.SkipJournaledProperties = isJournalNavigation;
            if (allowAsync)
            {
                XamlReader xamlReader = new XamlReader();
                asyncObjectConverter      = xamlReader;
                xamlReader.LoadCompleted += AppModelKnownContentFactory.OnParserComplete;
                return(xamlReader.LoadAsync(stream, parserContext));
            }
            return(XamlReader.Load(stream, parserContext));
        }
Ejemplo n.º 7
0
        public static async Task <UIElement> FromXamlStreamAsync(Stream xamlStream)
        {
            try
            {
                var tcs = new TaskCompletionSource <UIElement>();
                XmlReaderSettings settings = new XmlReaderSettings
                {
                    DtdProcessing             = DtdProcessing.Parse,
                    MaxCharactersFromEntities = 1024
                };

                var xr = new XamlReader();


                object obj = null;

                xr.LoadCompleted += (o, e) =>
                {
                    if (obj is not UIElement icon)
                    {
                        return;
                    }
                    tcs.SetResult(icon);
                };

                obj = xr.LoadAsync(xamlStream);

                return(await tcs.Task.ConfigureAwait(false));
            }
            catch (XamlParseException e)
            {
                return(new Viewbox
                {
                    Stretch = Stretch.Uniform,
                    Child = new Canvas
                    {
                        Height = 100,
                        Width = 100,
                        Children = { new Rectangle()
                                     {
                                         Height = 100, Width = 100,
                                         Fill = new SolidColorBrush(Colors.Red)
                                     } }
                    },
                    ToolTip = e.Message
                });
            }
            catch (IOException e)
            {
                return(new Viewbox
                {
                    Stretch = Stretch.Uniform,
                    Child = new Canvas {
                        Height = 100, Width = 100
                    },
                    ToolTip = e.Message
                });
            }
        }
Ejemplo n.º 8
0
        public static ResourceDictionary LoadResourceDictionary(string name)
        {
            var s      = GetEntry(name) as Stream;
            var reader = new XamlReader();

            return((ResourceDictionary)reader.LoadAsync(s));

            //Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
        }
Ejemplo n.º 9
0
        public FileFinderPluginConfigViewModel(PluginSystem.IPlugin Plugin, PluginSystem.PluginConfig PluginConfig) : base(Plugin, PluginConfig)
        {
            Uri uri = new Uri("pack://application:,,,/LauncherSilo.FileFinderPlugin;component/FileFinderPluginResource.xaml");
            StreamResourceInfo info   = Application.GetResourceStream(uri);
            XamlReader         reader = new XamlReader();
            var dictionary            = reader.LoadAsync(info.Stream) as ResourceDictionary;

            PluginConfigControlTemplate = dictionary["FileFinderPluginConfigView"] as ControlTemplate;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// リソースディレクトリを読み込む
        /// </summary>
        /// <param name="path">ファイルパス</param>
        /// <returns>読み込んだリソースディレクトリ</returns>
        public static ResourceDictionary LoadEmbededResourceDictionary(string path)
        {
            var uri = new Uri(path);
            StreamResourceInfo info = Application.GetResourceStream(uri);
            var reader = new XamlReader();

            //読み込んだファイルをResourceDictionaryとして返す
            return(reader.LoadAsync(info.Stream) as ResourceDictionary);
        }
Ejemplo n.º 11
0
        static void Load()
        {
            var reader = new XamlReader();
            var sr     = new StreamReader(XamlFile,
                                          Encoding.Default);

            var d = reader.LoadAsync(new MemoryStream(Encoding.UTF8.GetBytes(sr.ReadToEnd()))) as ResourceDictionary;

            _dictionary = new Dictionary <string, string>();
            foreach (DictionaryEntry v in d)
            {
                _dictionary.Add(v.Value.ToString(), v.Key.ToString());
            }
        }
Ejemplo n.º 12
0
        private void SetDocument(string html)
        {
            var xaml         = HtmlToXamlConverter.ConvertHtmlToXaml(html, true);
            var stringReader = new StringReader(xaml);
            var xmlReader    = XmlReader.Create(stringReader);
            var xamlReader   = new XamlReader();
            var flowDocument = xamlReader.LoadAsync(xmlReader);
            var doc          = flowDocument as FlowDocument;

            if (doc != null)
            {
                SubscribeToAllHyperlinks(doc);
                doc.PagePadding = new Thickness(0d);
            }
            Document = doc;
        }
Ejemplo n.º 13
0
        private static void LoadDefaultTheme()
        {
            var themePath = Path.Combine(Path.GetDirectoryName(typeof(MonsterSizeBarPlugin).Assembly.Location), "DefaultTheme.xaml");

            if (!File.Exists(themePath))
            {
                Debugger.Error("[Monster Size Bar] DefaultTheme.xaml doesn't exist, bars will not work correctly!");
                return;
            }

            var reader = new XamlReader();

            using var stream = File.OpenRead(themePath);
            var themeDict = (ResourceDictionary)reader.LoadAsync(stream);

            Application.Current.Resources.MergedDictionaries.Insert(0, themeDict);
        }
Ejemplo n.º 14
0
        private void App_Startup(object sender, StartupEventArgs e)
        {
            Thread.CurrentThread.CurrentCulture   = CultureInfo.CurrentCulture;
            Thread.CurrentThread.CurrentUICulture = Config.Localization;

            this.Resources.MergedDictionaries.Add((ResourceDictionary)Application.LoadComponent(new Uri("BaseTheme.xaml", UriKind.Relative)));
            this.Resources.MergedDictionaries.Add((ResourceDictionary)Application.LoadComponent(new Uri("ControlTemplates.xaml", UriKind.Relative)));

            Config config;

            try
            {
                config = new Config(true);
            }
            catch (ConfigurationErrorsException)
            {
                // Show PhotoKiosk style error message on MainWindow load.
                return;
            }
            catch (XmlException)
            {
                // Show PhotoKiosk style error message on MainWindow load.
                return;
            }

            if (config.ThemeFile.Value != "")
            {
                if (!File.Exists(config.ThemeFile.Value))
                {
                    // Show PhotoKiosk style error message on MainWindow load.
                    return;
                }
                try
                {
                    var fileStream           = new FileStream(config.ThemeFile.Value, FileMode.Open, FileAccess.Read);
                    var reader               = new XamlReader();
                    ResourceDictionary theme = (ResourceDictionary)reader.LoadAsync(fileStream);
                    this.Resources.MergedDictionaries.Add(theme);
                }
                catch
                {
                    return;
                }
            }
        }
Ejemplo n.º 15
0
        public static void LoadApplicationResources()
        {
            Uri uri = new Uri("pack://application:,,,/CodeOwls.SeeShell.Visualizations;component/DataTemplates.xaml");


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

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

                Application.Current.Resources.MergedDictionaries.Add(resources);
            }
            catch
            {
            }
        }
Ejemplo n.º 16
0
        public void Hack()
        {
            var isWindows7 = Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor == 1;
            var fileName   = isWindows7 ? "ComboBoxStyleWin7.xaml" : "ComboBoxStyle.xaml";

            var assembly = Assembly.GetExecutingAssembly();

            using (var stream = assembly.GetManifestResourceStream($"RatTracker.Infrastructure.Resources.Styles.{fileName}"))
            {
                if (stream == null)
                {
                    logger.Error("Could not read ComboBox style");
                    return;
                }

                var reader = new XamlReader();
                var myResourceDictionary = (ResourceDictionary)reader.LoadAsync(stream);
                Application.Current.Resources.MergedDictionaries.Add(myResourceDictionary);
            }
        }
Ejemplo n.º 17
0
 private void LoadCustomTheme()
 {
     if (!Directory.Exists(@"Themes"))
     {
         Directory.CreateDirectory(@"Themes");
     }
     if (!File.Exists($@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}"))
     {
         return;
     }
     try {
         using (FileStream stream = new FileStream($@"Themes/{UserSettings.PlayerConfig.HunterPie.Theme}", FileMode.Open)) {
             XamlReader         reader          = new XamlReader();
             ResourceDictionary ThemeDictionary = (ResourceDictionary)reader.LoadAsync(stream);
             Application.Current.Resources.MergedDictionaries.Add(ThemeDictionary);
         }
     } catch {
         Debugger.Error("Failed to load custom theme");
     }
 }
        public override void Perform()
        {
            Stream stream = SerializeToStream();

            if (stream == null)
            {
                return;
            }

            XamlReader xamlReader = new XamlReader();

            xamlReader.LoadCompleted += new AsyncCompletedEventHandler(LoadCompleted);
            try
            {
                xamlReader.LoadAsync(stream);
            }
            catch (XamlParseException xpe)
            {
                bool isIgnorableMessage = xpe.Message.Contains("No matching constructor");

                //Fix
                isIgnorableMessage = isIgnorableMessage | xpe.Message.Contains("CancelPrint");

                //Work around
                isIgnorableMessage = isIgnorableMessage | xpe.Message.Contains("invalid character");

                // Ignoring XamlParseException with specific message, as Xaml cannot load types with no default constructor
                if (!isIgnorableMessage)
                {
                    // Context is lost for the current exception because of the catch
                    // Calling the method again so that debugger breaks at the throwing location
                    stream.Seek(0, SeekOrigin.Begin);
                    XamlReader.Load(stream);
                }
            }

            if (IsCanceled)
            {
                xamlReader.CancelAsync();
            }
        }
Ejemplo n.º 19
0
        // <summary>
        // Creates an object instance from a Xaml stream and it's Uri
        // </summary>
        internal static object XamlConverter(Stream stream, Uri baseUri, bool canUseTopLevelBrowser, bool sandboxExternalContent, bool allowAsync, bool isJournalNavigation, out XamlReader asyncObjectConverter)
        {
            asyncObjectConverter = null;

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

                stream.Close();

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

                pc.BaseUri = baseUri;
                pc.SkipJournaledProperties = isJournalNavigation;

                if (allowAsync)
                {
                    XamlReader xr = new XamlReader();
                    asyncObjectConverter = xr;
                    xr.LoadCompleted    += new AsyncCompletedEventHandler(OnParserComplete);
                    // XamlReader.Load will close the stream.
                    return(xr.LoadAsync(stream, pc));
                }
                else
                {
                    // XamlReader.Load will close the stream.
                    return(XamlReader.Load(stream, pc));
                }
            }
        }
Ejemplo n.º 20
0
        public static async Task <UIElement> FromXamlStreamAsync(Stream xamlStream)
        {
            try
            {
                var tcs = new TaskCompletionSource <UIElement>();
                var xr  = new XamlReader();

                object obj = null;

                xr.LoadCompleted += (o, e) =>
                {
                    if (obj is not UIElement icon)
                    {
                        return;
                    }
                    tcs.SetResult(icon);
                    SetBinding(icon, _foreColor, _backColor);
                };

                obj = xr.LoadAsync(xamlStream);

                return(await tcs.Task.ConfigureAwait(false));
            }
            catch (XamlParseException e)
            {
                return(new Viewbox {
                    ToolTip = e.Message
                });
            }
            catch (IOException e)
            {
                return(new Viewbox {
                    ToolTip = e.Message
                });
            }
        }