Exemple #1
0
        private static void SetIconFromImageSource(TaskbarIcon taskbarIcon, ImageSource imageSource)
        {
            // Copied from Hardcodet.Wpf.TaskbarNotification.Util.ToIcon
            Icon icon = null;

            if (imageSource != null)
            {
                Uri uri = new Uri(imageSource.ToString());
                StreamResourceInfo streamInfo = Application.GetResourceStream(uri);

                if (streamInfo == null)
                {
                    string msg = "The supplied image source '{0}' could not be resolved.";
                    msg = String.Format(msg, imageSource);
                    throw new ArgumentException(msg);
                }

                icon = new Icon(streamInfo.Stream, idealIconSize, idealIconSize);
            }

            taskbarIcon.Icon?.Dispose();
            taskbarIcon.Icon = icon;
        }
Exemple #2
0
        private string GetErrorMessage()
        {
            StreamResourceInfo xml    = App.GetResourceStream(new Uri("Config.xml", UriKind.Relative));
            XmlReader          reader = XmlReader.Create(xml.Stream);

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "ErrorMessages")
                    {
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.Name == "ErrorMessage")
                            {
                                _errorMessage = reader.Value;
                            }
                        }
                    }
                }
            }
            return(_errorMessage);
        }
Exemple #3
0
        /// <summary>
        /// Loads a wav file into an XNA Framework SoundEffect.
        /// </summary>
        /// <param name="SoundFilePath">Relative path to the wav file.</param>
        /// <param name="Sound">The SoundEffect to load the audio into.</param>
        private void LoadSound(String SoundFilePath, out SoundEffectInstance sound)
        {
            // For error checking, assume we'll fail to load the file.
            sound = null;
            SoundEffect soundEffect = null;

            try
            {
                // Holds informations about a file stream.
                StreamResourceInfo SoundFileInfo =
                    App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));

                // Create the SoundEffect from the Stream
                soundEffect = SoundEffect.FromStream(SoundFileInfo.Stream);

                // Create sound instance
                sound = soundEffect.CreateInstance();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #4
0
        private string GetDeveloperEmailTo()
        {
            StreamResourceInfo xml    = App.GetResourceStream(new Uri("Config.xml", UriKind.Relative));
            XmlReader          reader = XmlReader.Create(xml.Stream);

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "Emails")
                    {
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.Name == "DeveloperEmailTo")
                            {
                                _developerEmailTo = reader.Value;
                            }
                        }
                    }
                }
            }
            return(_developerEmailTo);
        }
Exemple #5
0
        private string GetApplicationIdForTransparenciaBrasil()
        {
            StreamResourceInfo xml    = App.GetResourceStream(new Uri("Config.xml", UriKind.Relative));
            XmlReader          reader = XmlReader.Create(xml.Stream);

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "App")
                    {
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.MoveToAttribute("ApplicationId"))
                            {
                                _applicationIdForTransparenciaBrasil = reader.Value;
                            }
                        }
                    }
                }
            }
            return(_applicationIdForTransparenciaBrasil);
        }
Exemple #6
0
        private string GetAppDeveloper()
        {
            StreamResourceInfo xml    = App.GetResourceStream(new Uri("WMAppManifest.xml", UriKind.Relative));
            XmlReader          reader = XmlReader.Create(xml.Stream);

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "App")
                    {
                        while (reader.MoveToNextAttribute())
                        {
                            if (reader.Name == "Author")
                            {
                                _appDeveloper = reader.Value;
                            }
                        }
                    }
                }
            }
            return(_appDeveloper);
        }
Exemple #7
0
        /// <summary>
        /// 將網頁字串儲存至 IsolatedStorage
        /// </summary>
        /// <param name="strWebContent"></param>
        private void SaveStringToIsolatedStorage(string fileName, string strWebContent)
        {
            //取得使用者範圍隔離儲存區
            IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

            //刪除先前的檔案
            if (isolatedStorageFile.FileExists(fileName))
            {
                isolatedStorageFile.DeleteFile(fileName);
            }

            // 儲存至 isolated Storage
            StreamResourceInfo streamResourceInfo = new StreamResourceInfo(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(strWebContent)), "html/text");

            using (BinaryReader binaryReader = new BinaryReader(streamResourceInfo.Stream))
            {
                var data = binaryReader.ReadBytes((int)streamResourceInfo.Stream.Length);
                using (BinaryWriter binaryWriter = new BinaryWriter(isolatedStorageFile.CreateFile(fileName)))
                {
                    binaryWriter.Write(data);
                }
            }
        }
        private void SaveStringToIsoStore(string strWebContent)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            //remove the file if exists to allow each run to independently write to
            // the Isolated Storage
            if (isoStore.FileExists("web.htm") == true)
            {
                isoStore.DeleteFile("web.htm");
            }
            StreamResourceInfo sr = new StreamResourceInfo(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(strWebContent)), "html/text");

            using (BinaryReader br = new BinaryReader(sr.Stream))
            {
                byte[] data = br.ReadBytes((int)sr.Stream.Length);
                //save file to Isolated Storage
                using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile("web.htm")))
                {
                    bw.Write(data);
                    bw.Close();
                }
            }
        }
Exemple #9
0
        private void Btn_Repeat_Click(object sender, RoutedEventArgs e)
        {
            Uri resourceUri;

            if (!Repeat)
            {
                resourceUri = new Uri("Images/RepeatOnHD.png", UriKind.Relative);
                Repeat      = true;
            }
            else
            {
                resourceUri = new Uri("Images/RepeatHD.png", UriKind.Relative);
                Repeat      = false;
            }
            StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(resourceUri);

            BitmapFrame temp  = BitmapFrame.Create(streamInfo.Stream);
            var         brush = new ImageBrush();

            brush.ImageSource = temp;

            Btn_Repeat.Background = brush;
        }
Exemple #10
0
 private void ButtonNormal_Click(object sender, RoutedEventArgs e)
 {
     if (WindowState == WindowState.Normal)
     {
         WindowState = WindowState.Maximized;
         var resourceUri = new Uri("/AutinPower.WPF;component/Images/opNormalize.png", UriKind.Relative);
         StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
         BitmapFrame        temp       = BitmapFrame.Create(streamInfo.Stream);
         ImageBrush         brush      = new ImageBrush();
         brush.ImageSource          = temp;
         buttonMaxNormal.Background = brush;
     }
     else
     {
         WindowState = WindowState.Normal;
         var resourceUri = new Uri("/AutinPower.WPF;component/Images/opMaximize.png", UriKind.Relative);
         StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
         BitmapFrame        temp       = BitmapFrame.Create(streamInfo.Stream);
         ImageBrush         brush      = new ImageBrush();
         brush.ImageSource          = temp;
         buttonMaxNormal.Background = brush;
     }
 }
        private void CreateTaskbarButtons()
        {
            for (int i = 0; i < 4; i++)
            {
                var thumbbarButton = TaskbarButton.Current.CreateThumbbarButton((uint)(i + 1));
                thumbbarButton.Flags = THUMBBUTTONFLAGS.THBF_ENABLED;

                thumbbarButton.ImageDataType = ButtonImageDataType.PNG;
                StreamResourceInfo resourceInfo = Application.GetResourceStream(new Uri(string.Format("images/{0}.png", i), UriKind.Relative));
                using (var br = new BinaryReader(resourceInfo.Stream))
                {
                    thumbbarButton.Image = br.ReadBytes((int)resourceInfo.Stream.Length);
                }

                taskbarButtons.Add(thumbbarButton);
            }

            taskbarButtons[0].Tooltip = "First Image";
            taskbarButtons[1].Tooltip = "Previous Image";
            taskbarButtons[2].Tooltip = "Next Image";
            taskbarButtons[3].Tooltip = "Last Image";
            TaskbarButton.Current.ShowThumbbarButtons();
        }
Exemple #12
0
        /// <summary>
        /// Reads a given image resource into a WinForms icon.
        /// </summary>
        /// <param name="imageSource">Image source pointing to
        /// an icon file (*.ico).</param>
        /// <returns>An icon object that can be used with the
        /// taskbar area.</returns>
        public static Icon ToIcon(this ImageSource imageSource)
        {
            if (imageSource == null)
            {
                return(null);
            }
            if (imageSource is DrawingImage)
            {
                return(FromDrawImage((DrawingImage)imageSource));
            }

            Uri uri = new Uri(imageSource.ToString());
            StreamResourceInfo streamInfo = Application.GetResourceStream(uri);

            if (streamInfo == null)
            {
                string msg = "The supplied image source '{0}' could not be resolved.";
                msg = string.Format(msg, imageSource);
                throw new ArgumentException(msg);
            }

            return(new Icon(streamInfo.Stream));
        }
 private void GetGameHelperFromResourceFile()
 {
     try
     {
         Uri uri = new Uri("Resources\\Server2GameHelper.txt", UriKind.Relative);//这个就是所以的pack uri。
         StreamResourceInfo info = Application.GetContentStream(uri);
         if (info == null)
         {
             return;
         }
         Stream s      = info.Stream;
         byte[] buffer = new byte[s.Length];
         s.Read(buffer, 0, buffer.Length);
         string x = Encoding.GetEncoding("gb2312").GetString(buffer);
         this.txtHelperInfo.Text = x;
         s.Close();
         s.Dispose();
     }
     catch (Exception exc)
     {
         LogHelper.Instance.AddErrorLog("Load Game Helper Exception", exc);
     }
 }
Exemple #14
0
        public static IEnumerable <Assembly> LoadPackagedAssemblies(Stream packageStream)
        {
            if (packageStream == null)
            {
                throw new ArgumentNullException("packageStream");
            }

            var assemblies        = new List <Assembly>();
            var packageStreamInfo = new StreamResourceInfo(packageStream, null);
            var parts             = GetDeploymentParts(packageStreamInfo);

            foreach (AssemblyPart ap in parts)
            {
                StreamResourceInfo sri = Application.GetResourceStream(
                    packageStreamInfo,
                    new Uri(ap.Source, UriKind.Relative));

                assemblies.Add(ap.Load(sri.Stream));
            }

            packageStream.Close();
            return(assemblies);
        }
    public override Stream OpenInputFileStream(string path)
    {
        System.Diagnostics.Debug.WriteLine("open_file: " + path, "");

        if (!path.StartsWith("/rho"))
        {
            path = "rho/" + path;
        }

        if (path.StartsWith("/"))
        {
            path = path.Substring(1);
        }

        StreamResourceInfo sr = Application.GetResourceStream(new Uri(path, UriKind.Relative));

        if (sr == null)
        {
            throw new System.IO.FileNotFoundException();
        }

        return(sr.Stream);
    }
        public MainWindow()
        {
            InitializeComponent();

            pictureArray.Add("/Images/lilies.jpeg");
            pictureArray.Add("/Images/swans_on_lake.jpeg");
            pictureArray.Add("/Images/tree_by_water.jpeg");
            pictureArray.Add("/Images/wave.jpeg");
            pictureArray.Add("/Images/tree_lined_lane.jpeg");
            pictureArray.Add("/Images/tree_in_field.jpeg");
            pictureArray.Add("/Images/mountain_lake.jpeg");

            userName.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);

            BitmapFrame temp  = BitmapFrame.Create(streamInfo.Stream);
            var         brush = new ImageBrush();

            brush.ImageSource = temp;

            picture.Background = brush;
        }
        public void AsDataSet_ValidFile_ReturnsPopulatedDataSet()
        {
            StreamResourceInfo sri        = Application.GetResourceStream(new Uri("Resources/OpenXmlFile.xlsx", UriKind.Relative));
            Stream             fileStream = sri.Stream;

            var reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream) as ExcelOpenXmlReader;

            reader.WorkBookFactory = new WorkBookFactory();

            var dataSet = reader.AsWorkBook();

            Assert.AreEqual(dataSet.WorkSheets.Count, 2);

            var firstTable = dataSet.WorkSheets.First();

            Assert.AreEqual(firstTable.Columns.Count, 2);
            Assert.AreEqual(firstTable.Rows.Count, 2);
            var firstRowValues = firstTable.Rows.ElementAt(0).Values.OfType <object>();

            Assert.AreEqual(firstRowValues.ElementAt(0).ToString(), "Sheet1.A1");
            Assert.AreEqual(firstRowValues.ElementAt(1).ToString(), "Sheet1.B1");
            var secondRowValues = firstTable.Rows.ElementAt(1).Values.OfType <object>();

            Assert.AreEqual(secondRowValues.ElementAt(0).ToString(), "Sheet1.A2");
            Assert.AreEqual(secondRowValues.ElementAt(1).ToString(), "Sheet1.B2");

            var secondTable = dataSet.WorkSheets.ElementAt(1);

            Assert.AreEqual(secondTable.Columns.Count, 2);
            Assert.AreEqual(secondTable.Rows.Count, 2);
            firstRowValues = secondTable.Rows.ElementAt(0).Values.OfType <object>();
            Assert.AreEqual(firstRowValues.ElementAt(0).ToString(), "Sheet2.A1");
            Assert.AreEqual(firstRowValues.ElementAt(1).ToString(), "Sheet2.B1");
            secondRowValues = secondTable.Rows.ElementAt(1).Values.OfType <object>();
            Assert.AreEqual(secondRowValues.ElementAt(0).ToString(), "Sheet2.A2");
            Assert.AreEqual(secondRowValues.ElementAt(1).ToString(), "Sheet2.B2");
        }
Exemple #18
0
        void FillEvents()
        {
            try
            {
                if (selectedYear == calDate.Year)
                {
                    return;
                }
                selectedYear = calDate.Year;

                events = new List <EventItem>();
                string             path = string.Format("IndianCalendarApp;component/{0}.xml", calDate.Year);
                StreamResourceInfo xml  =
                    Application.GetResourceStream(new Uri(path, UriKind.Relative));
                if (xml != null)
                {
                    var           appDataXml   = XDocument.Load(xml.Stream);
                    XDocument     xdoc         = appDataXml;
                    var           rootCategory = xdoc.Root.Element("Events");
                    List <string> list         = new List <string>();

                    foreach (XElement item in appDataXml.Descendants("item"))
                    {
                        int    day     = (int)item.Attribute("day");
                        int    month   = (int)item.Attribute("month");
                        string title   = (string)item;
                        string details = Convert.ToString(item.Attribute("description") != null ? item.Attribute("description").Value : string.Empty);
                        events.Add(new EventItem {
                            Day = day, Month = month, Title = title, Details = details
                        });
                    }
                }
            }
            catch (Exception)
            {
            }
        }
Exemple #19
0
        public App()
        {
            try
            {
                var testFont = new Font("Monotype Corsiva", 16.0f, FontStyle.Italic);
                if (testFont.Name != "Monotype Corsiva")
                {
                    string windir = Environment.GetEnvironmentVariable("windir");
                    if (windir != null)
                    {
                        string fontsDir = Path.Combine(windir, "fonts");
                        if (Directory.Exists(fontsDir))
                        {
                            string dest = Path.Combine(fontsDir, "MTCORSVA.TTF");
                            if (!File.Exists(dest))
                            {
                                StreamResourceInfo sri =
                                    GetResourceStream(new Uri("pack://application:,,,/Resources/MTCORSVA.TTF"));
                                if (sri != null)
                                {
                                    var buffer = new byte[sri.Stream.Length];
                                    sri.Stream.Read(buffer, 0, (int)sri.Stream.Length);
                                    File.WriteAllBytes(dest, buffer);
                                    PInvoke.AddFontResource(dest);
                                    PInvoke.FontsAdded();
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }

            DispatcherUnhandledException += AppDispatcherUnhandledException;
        }
Exemple #20
0
        public void Extract()
        {
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // If target folder does not exists, we create it. Target folder is "html";
                if (false == storage.DirectoryExists(TargetFolder))
                {
                    storage.CreateDirectory(TargetFolder);
                }

                // Files returned have source folder path appended to the beginning.
                foreach (String sourceFile in Directory.GetFiles(SourceFolder))
                {
                    // file in target folder, with target folder path appended to the beginning
                    String targetFile = TargetFolder + "\\" + Path.GetFileName(sourceFile);

                    // In debug, if target file exists, we replace it with current. In release, we just skip it.
                    if (storage.FileExists(targetFile))
                    {
                        storage.DeleteFile(targetFile);
                    }

                    // Get resource stream from source file.
                    StreamResourceInfo resource = Application.GetResourceStream(new Uri(sourceFile, UriKind.Relative));
                    using (IsolatedStorageFileStream fileStream = storage.CreateFile(targetFile))
                    {
                        int    chunkSize = 4096;
                        byte[] bytes     = new byte[chunkSize];
                        int    byteCount;
                        while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
                        {
                            fileStream.Write(bytes, 0, byteCount);
                        }
                    }
                }
            }
        }
        private void ParsePreferences()
        {
            try
            {
                StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative));

                if (streamInfo != null)
                {
                    StreamReader reader   = new StreamReader(streamInfo.Stream);
                    XDocument    document = XDocument.Parse(reader.ReadToEnd());

                    var preferences = from results in document.Descendants()
                                      where results.Name.LocalName == "preference"
                                      select new
                    {
                        name  = (string)results.Attribute("name"),
                        value = (string)results.Attribute("value")
                    };

                    foreach (var preference in preferences)
                    {
                        if (preference.name == "defaultPushSystem")
                        {
                            MessageProviderFactory.Instance.DefaultProviderName = preference.value;

                            Logger.InfoFormat("Set default push system to {0}", preference.value);
                        }
                    }
                }

                AttachHandlersToStores();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Cannot parse preferences: {0}", e.Message);
            }
        }
Exemple #22
0
        private void ApplyFontSource(FrameworkElement element, Dictionary <string, FontData> fonts)
        {
            TextBlock text = element as TextBlock;

            if (text != null)
            {
                string fontUri = (string)text.Tag; // font uri temp stored in tag
                text.Tag = null;                   // clear tag

                FontData font;
                if (!fonts.TryGetValue(fontUri, out font))
                {
                    StreamResourceInfo resource = Load(fontUri);
                    if (resource != null)
                    {
                        FontParser parser   = new FontParser();
                        FontInfo   fontInfo = parser.ParseFont(resource.Stream, Path.GetFileName(fontUri));
                        if (fontInfo != null)
                        {
                            font = new FontData()
                            {
                                FamilyName = fontInfo.FamilyName,
                                Source     = new FontSource(fontInfo.FontStream),
                                Stream     = fontInfo.FontStream
                            };
                        }
                    }
                    fonts[fontUri] = font;
                }

                if (font != null)
                {
                    text.FontFamily = new FontFamily(font.FamilyName);
                    text.FontSource = font.Source;
                }
            }
        }
Exemple #23
0
        public void alarm_button(int id_num)
        {
            Uri resourceUri = new Uri("Resources/red_button.png", UriKind.Relative);
            StreamResourceInfo streamInfo = System.Windows.Application.GetResourceStream(resourceUri);

            BitmapFrame temp  = BitmapFrame.Create(streamInfo.Stream);
            var         brush = new ImageBrush();

            brush.ImageSource = temp;
            brush.Stretch     = Stretch.None;

            switch (id_num)
            {
            case 0:
                PanicButton1.Background = brush;
                Alerted[0] = true;
                break;

            case 1:
                PanicButton2.Background = brush;
                Alerted[1] = true;
                break;

            case 2:
                PanicButton3.Background = brush;
                Alerted[2] = true;
                break;

            case 3:
                PanicButton4.Background = brush;
                Alerted[3] = true;
                break;
            }

            //ShirenPlayer.PlayLooping();
            AlarmOut();
        }
Exemple #24
0
        private static void Main(string[] args)
        {
            try
            {
//				if (IsWriteAccess() == false)
//					return;
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                StreamResourceInfo sri = System.Windows.Application.GetResourceStream(
                    new Uri("App.xaml", UriKind.Relative));
                var resources = (System.Windows.ResourceDictionary)Load(sri.Stream);
                var app       = new System.Windows.Application();
                app.Resources.MergedDictionaries.Add(resources);
                Starter(args);
                ClearTypeOn();
                //new SettingsWpfForm().ShowDialog();
                //var controller = new TaskShowController(new Task());
                //controller.Window.ShowDialog();

                Application.Run();
            }
            catch (Exception e)
            {
                new ErrorBox("We are very sorry, but the program crashed. Please contact support at " +
                             "http://code.google.com/p/minder/issues/list. Thank you for your patience.\n\n" +
                             "P.S. you can copy error message by pressing clr + C. Have a nice day.");                 // This shows error box and writes to log.
                try
                {
                    log4net.ILog log = log4net.LogManager.GetLogger(typeof(BootStrap));
                    log.Fatal(e);
                }
                catch {}                //Jei konfigai neužkrauti

                Application.Exit();
            }
        }
        private bool ExtractFile(StreamResourceInfo xapStream, IsolatedStorageFile isf, string fileName)
        {
            try
            {
                if (!isf.DirectoryExists("Temp"))
                {
                    isf.CreateDirectory("Temp");
                }
                if (!isf.DirectoryExists(IsoTempFolderPath))
                {
                    isf.CreateDirectory(IsoTempFolderPath);
                }

                var streamResource = Application.GetResourceStream(xapStream, new Uri(fileName, UriKind.Relative));

                if (streamResource == null)
                {
                    return(false);
                }

                string shortFileName = ShortenFileName(fileName);

                var fs = new IsolatedStorageFileStream(IsoTempFolderPath + "\\" + shortFileName, FileMode.Create, isf);

                Byte[] bytes = new Byte[streamResource.Stream.Length];
                streamResource.Stream.Read(bytes, 0, bytes.Length);
                fs.Write(bytes, 0, bytes.Length);
                fs.Close();

                streamResource.Stream.Close();
                return(true);
            }
            catch (Exception ex)
            {
            }
            return(false);
        }
Exemple #26
0
        /// <summary>
        /// Loads and applies a theme from a specified Uri.
        /// </summary>
        /// <param name="themeUri">Theme Uri.</param>
        /// <param name="currentTheme">Current theme.</param>
        /// <param name="owner">ResourceDictionary owner.</param>
        /// <param name="onNewThemeAvailable">Action called when the new theme instance is available.</param>
        private static void LoadAndApplyThemeFromUri(Uri themeUri, ResourceDictionary currentTheme, ResourceDictionary owner, Action <ResourceDictionary> onNewThemeAvailable)
        {
            if (null != themeUri)
            {
                try
                {
                    // Try to load the URI as a resource stream
                    StreamResourceInfo streamResourceInfo = Application.GetResourceStream(themeUri);
                    if (null != streamResourceInfo)
                    {
                        onNewThemeAvailable(LoadAndApplyThemeFromStream(streamResourceInfo.Stream, currentTheme, owner));
                        return;
                    }
                }
                catch (ArgumentException)
                {
                    // Not a resource stream; ignore
                }

                // Try to load the URI by downloading it
                WebClient webClient = new WebClient();
                webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
                {
                    if (null == e.Error)
                    {
                        onNewThemeAvailable(LoadAndApplyThemeFromStream(e.Result, currentTheme, owner));
                    }
                };
                webClient.OpenReadAsync(themeUri);
            }
            else if (null != currentTheme)
            {
                // themeUri is null; unload current theme (if any)
                UnloadThemeResources(currentTheme, owner);
                onNewThemeAvailable(null);
            }
        }
        public BitmapImage SetImageData(Uri uri)
        {
            StreamResourceInfo imageInfo = System.Windows.Application.GetResourceStream(uri);
            var bitmap = new BitmapImage();

            try
            {
                logger.Debug("StatisticsSupport : SetImageData Method : Entry");
                byte[] imageBytes = ReadFully(imageInfo.Stream);
                using (Stream stream = new MemoryStream(imageBytes))
                {
                    bitmap.BeginInit();
                    bitmap.StreamSource = stream;
                    bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                    bitmap.EndInit();
                    bitmap.UriSource = uri;
                    if (bitmap.CanFreeze)
                    {
                        bitmap.Freeze();
                    }
                }
                imageBytes = null;
                return(bitmap);
            }
            catch (Exception generalException)
            {
                return(null);

                logger.Error("StatisticsSupport : SetImageData Method : Exception caught" + generalException.Message.ToString());
            }
            finally
            {
                imageInfo = null;
                bitmap    = null;
            }
            logger.Debug("StatisticsSupport : SetImageData Method : Exit");
        }
Exemple #28
0
        // Get a resource file stream info from an assembly or the XAP
        internal static StreamResourceInfo GetStreamInfo(string relativeUri, Assembly assembly)
        {
            StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri(relativeUri, UriKind.Relative));

            if (streamInfo != null)             // found in the XAP
            {
                return(streamInfo);
            }

            string componentFormat = assembly.Name() + ";component/{0}";
            string assemblyUri     = string.Format(componentFormat, relativeUri);

            streamInfo = Application.GetResourceStream(new Uri(assemblyUri, UriKind.Relative));
            if (streamInfo != null)             // found in the assembly
            {
                return(streamInfo);
            }

            // Last chance!
            // Resource files added to a VS project as "links" (Add / Existing Item / Add As Link)
            // must be accessed without a path
            int pathMarker = relativeUri.LastIndexOf('/');

            if (pathMarker < 0)
            {
                return(null);
            }

            assemblyUri = string.Format(componentFormat, relativeUri.Substring(pathMarker + 1));
            streamInfo  = Application.GetResourceStream(new Uri(assemblyUri, UriKind.Relative));
            if (streamInfo != null)             // found in the assembly
            {
                return(streamInfo);
            }

            return(null);            // not found
        }
Exemple #29
0
        private static GifFile DecodeGifFile(Uri uri)
        {
            Stream stream = (Stream)null;

            if (uri.Scheme == PackUriHelper.UriSchemePack)
            {
                StreamResourceInfo streamResourceInfo = !(uri.Authority == "siteoforigin:,,,") ? Application.GetResourceStream(uri) : Application.GetRemoteStream(uri);
                if (streamResourceInfo != null)
                {
                    stream = streamResourceInfo.Stream;
                }
            }
            else
            {
                using (WebClient webClient = new WebClient())
                    stream = webClient.OpenRead(uri);
            }
            if (stream == null)
            {
                return((GifFile)null);
            }
            using (stream)
                return(GifFile.ReadGifFile(stream, true));
        }
Exemple #30
0
        private SupportedPageOrientation LoadOrientationFromConfig()
        {
            StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri("config.xml", UriKind.Relative));

            if (streamInfo != null)
            {
                StreamReader sr = new StreamReader(streamInfo.Stream);

                //This will Read Keys Collection for the xml file
                XDocument document = XDocument.Parse(sr.ReadToEnd());

                var preferences = from results in document.Descendants("preference")
                                  select new
                {
                    name  = (string)results.Attribute("name"),
                    value = (string)results.Attribute("value")
                };

                foreach (var pref in preferences)
                {
                    if (pref.name == "orientation")
                    {
                        if (pref.value == "portrait")
                        {
                            return(SupportedPageOrientation.Portrait);
                        }
                        if (pref.value == "landscape")
                        {
                            return(SupportedPageOrientation.Landscape);
                        }
                    }
                }
            }

            return(SupportedPageOrientation.PortraitOrLandscape);
        }