private static IDataObject LoadResources(object state1) { var st = (TaskState <RootNode1>)state1; var node = st.Node; try { var dta = new List <SubnodeData>(); using (var stream = node.Assembly.GetManifestResourceStream(node.Name.ToString())) { if (stream != null && node.Name.ToString().EndsWith(".resources")) { using (var reader = new ResourceReader(stream)) { foreach (var dictionaryEntry in reader.Cast <DictionaryEntry>()) { var value = dictionaryEntry.Value; if (((string)dictionaryEntry.Key).EndsWith(".png")) { Debug.WriteLine(dictionaryEntry.Value.ToString()); } try { var data = new SubnodeData { Name = dictionaryEntry.Key as string, Value = value, ResourceName = node.Name, Assembly = node.Assembly }; dta.Add(data); } catch (Exception ex) { // DebugUtils.WriteLine(ex.ToString()); } } } } } return(new DataObject(typeof(IEnumerable), dta)); } catch (Exception ex) { // DebugUtils.WriteLine(ex.ToString()); throw; } }
/// <summary> /// Checks whether the specified resource dictionary is available as resource. /// </summary> /// <param name="resourceDictionaryUri">The resource dictionary uri.</param> /// <returns></returns> public virtual bool IsResourceDictionaryAvailable(string resourceDictionaryUri) { var expectedResourceNames = resourceDictionaryUri.Split(new[] { ";component/" }, StringSplitOptions.RemoveEmptyEntries); if (expectedResourceNames.Length == 2) { // Part 1 is assembly #pragma warning disable CA1307 // Specify StringComparison var assemblyName = expectedResourceNames[0].Replace("/", string.Empty); #pragma warning restore CA1307 // Specify StringComparison var assembly = (from x in AppDomain.CurrentDomain.GetAssemblies() where x.GetName().Name.EqualsIgnoreCase(assemblyName) select x).FirstOrDefault(); if (assembly != null) { // Orchestra.Core.g.resources var generatedResourceName = $"{assembly.GetName().Name}.g.resources"; using (var resourceStream = assembly.GetManifestResourceStream(generatedResourceName)) { if (resourceStream is null) { Log.Debug($"Could not find generated resources @ '{generatedResourceName}', assuming the resource dictionary '{resourceDictionaryUri}' does not exist"); return(false); } #pragma warning disable CA1307 // Specify StringComparison var relativeResourceName = expectedResourceNames[1].Replace(".xaml", ".baml"); #pragma warning restore CA1307 // Specify StringComparison using (var reader = new ResourceReader(resourceStream)) { var exists = (from x in reader.Cast <DictionaryEntry>() where ((string)x.Key).EqualsIgnoreCase(relativeResourceName) select x).Any(); if (exists) { Log.Debug($"Resource '{resourceDictionaryUri}' exists"); return(true); } } } } } Log.Debug($"Failed to confirm that resource '{resourceDictionaryUri}' exists"); return(false); }
/// <summary> /// Static constructor /// </summary> /// <inheritdoc/> static PixelShaderEffectBase() { Assembly asm = typeof(PixelShaderEffectBase).Assembly; string resname = asm.GetManifestResourceNames().FirstOrDefault(s => s.Contains("g.resources")) ?? $"{asm.GetName().Name}.g.resources"; Match m = null; using (Stream str = asm.GetManifestResourceStream(resname)) using (ResourceReader rd = new ResourceReader(str)) AvailableEffects = (from e in rd.Cast <DictionaryEntry>() let name = e.Key as string where name.Match(@"(.*(\\|\/))?(?<name>.+)\.ps", out m) let res = m?.Groups["name"]?.ToString() where res != null select res).ToArray(); }
private static IEnumerable <string> GetResourceNames() { Assembly assembly = Assembly.GetExecutingAssembly(); string resName = assembly.GetName().Name + ".g.resources"; using (Stream stream = assembly.GetManifestResourceStream(resName)) { if (stream == null) { return(null); } using (ResourceReader reader = new ResourceReader(stream)) { return(reader.Cast <DictionaryEntry>().Select(entry => (string)entry.Key).ToArray()); } } }
/// <summary> /// Find all resources in asssembly /// </summary> /// <param name="assembly"></param> /// <returns></returns> internal static IEnumerable <AssemblyResource> FindAll(Assembly assembly) { var result = new List <AssemblyResource>(); var genPath = assembly.GetName().Name + ".g.resources"; using (var genStream = assembly.GetManifestResourceStream(genPath)) { var genReader = new ResourceReader(genStream); foreach (var entry in genReader.Cast <DictionaryEntry>()) { var key = (string)entry.Key; result.Add(new AssemblyResource(assembly, key)); } } return(result.ToArray()); }
private static Tuple <String, Stream>[] GetResourceNames() { var asm = Assembly.GetEntryAssembly(); var resName = asm.GetName().Name + ".g.resources"; using (var stream = asm.GetManifestResourceStream(resName)) { if (stream != null) { using (var reader = new ResourceReader(stream)) { return(reader.Cast <DictionaryEntry>().Select(entry => new Tuple <String, Stream>((String)entry.Key, (Stream)entry.Value)).ToArray()); } } } return(Enumerable.Empty <Tuple <String, Stream> >().ToArray()); }
/// <summary> /// /// </summary> /// <param name="resource"></param> /// <param name="assembly"></param> /// <returns></returns> private static List <ScriptMetadata> GetScripts(string resource, Assembly assembly) { if (string.IsNullOrEmpty(resource)) { return(new List <ScriptMetadata>()); } var stream = assembly.GetManifestResourceStream(resource); if (stream == null) { return(new List <ScriptMetadata>()); } var resourceReader = new ResourceReader(stream); var entrys = resourceReader.Cast <DictionaryEntry>().ToList(); return(entrys.Select(GetScript).Where(w => w != null).ToList()); }
/// <summary> /// Open stream for read /// </summary> /// <returns></returns> public Stream OpenRead() { var genPath = Assembly.GetName().Name + ".g.resources"; using (var genStream = Assembly.GetManifestResourceStream(genPath)) { var genReader = new ResourceReader(genStream); foreach (var entry in genReader.Cast <DictionaryEntry>()) { var key = (string)entry.Key; if (key.EqualsNoCase(ResourcePath)) { return((Stream)entry.Value); } } } throw ExceptionBuilder.Resource(FrameworkStrings.ErrorResourceNotFound, Assembly.GetName().Name, ResourcePath); }
protected override void LoadChildren() { EmbeddedResource er = this.Resource as EmbeddedResource; if (er != null) { Stream s = er.GetResourceStream(); s.Position = 0; ResourceReader reader; try { reader = new ResourceReader(s); } catch (ArgumentException) { return; } foreach (DictionaryEntry entry in reader.Cast <DictionaryEntry>().OrderBy(e => e.Key.ToString())) { ProcessResourceEntry(entry); } } }
private static IReadOnlyList <int> FillStrings(IDictionary <int, IDictionary <string, string> > strings, Stream resStream, string prefix) { var locales = new List <int>(); var regexString = _resNameRegex; if (!String.IsNullOrEmpty(prefix)) { if (!prefix.EndsWith(_resSeparator)) { prefix += _resSeparator; } regexString = Regex.Escape(prefix) + _resNameRegex; } var regex = new Regex(regexString, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); using (var resReader = new ResourceReader(resStream)) { foreach (var(name, stream) in resReader.Cast <DictionaryEntry>().Select(de => (de.Key as string, de.Value as Stream))) { var match = regex.Match(name); if (match.Success) { try { var lcid = new CultureInfo(match.Groups[1].Value).LCID; locales.Add(lcid); strings[lcid] = GetStringsFromJson(stream); } catch (CultureNotFoundException) { } } } } return(locales.AsReadOnly()); }
/// <summary> /// Retrieves the list of themes from the assembly. /// </summary> /// <returns>The list of theme names.</returns> private List <string> RetrieveThemeList() { // Get the assembly that we are currently in. Assembly assembly = Assembly.GetEntryAssembly(); // Get the name of the resources file that we will load. string resourceFileName = assembly.GetName().Name + ".g.resources"; // Open the manifest stream. using (Stream stream = assembly.GetManifestResourceStream(resourceFileName)) { // Open a resource reader to get all the resource files. using (ResourceReader reader = new ResourceReader(stream)) { // Returns just the resources that start in the themes folder return(new List <string>(reader.Cast <DictionaryEntry>() .Where(entry => entry.Key.ToString().StartsWith("themes/")) // Get all files that are in the themes folder. .Select(entry => entry.Key.ToString().Replace(".baml", "").Replace("themes/", "")) // select the name without .baml or themes/ .OrderBy(entry => entry.ToString()).ToArray())); // put it in alpha order. } } }
public static string[] GetResourceNames() { var assembly = Assembly.GetCallingAssembly(); var assemblyName = assembly.GetName().Name; var assemblyResources = assemblyName + ".g.resources"; using (var stream = assembly.GetManifestResourceStream(assemblyResources)) { if (stream != null) { using (var reader = new ResourceReader(stream)) { return(reader.Cast <DictionaryEntry>() .Select( entry => string.Format("pack://application:,,,/{0};component/{1}", assemblyName, entry.Key)) .ToArray()); } } } return(new string[] {}); }
private List <TranslateUnit> ParsePEFile() { PEUtil.ResetPEResourceIndex(); List <TranslateUnit> result = new List <TranslateUnit>(); int number = 0; byte[] binary = null; using (FileStream fs = new FileStream(m_peFileName, FileMode.Open)) { BinaryReader br = new BinaryReader(fs); binary = br.ReadBytes(System.Convert.ToInt32(fs.Length)); } // check if this file is PE file string startFlag = PEUtil.ConvertByteArrayToHexString(binary, 0, 2); // dos MZ header if (!"4D5A".Equals(startFlag)) { throw new Exception("This file is not a valid PE file (not start with 4D5Ah)"); } // PE signature PE00 string allHex = PEUtil.ConvertByteArrayToHexString(binary); if (!allHex.Contains("50450000")) { throw new Exception("This file is not a valid PE file (not contain with 50450000h)"); } // get pe header information PEReader peReader = new PEReader(m_peFileName); string name1 = PEUtil.GetSectionName(peReader.ImageSectionHeader[0]); PEResourceDataList resDataList = new PEResourceDataList(); PEResourceEntries[] ResourceEntriesAll = peReader.ResourceEntriesAll; for (int i = 0; i < ResourceEntriesAll.Length; i++) { PEResourceEntries resourceEntries = ResourceEntriesAll[i]; // which resouce should be extracted // first version information : 0Eh if (resourceEntries.level1Entry.Name_l >= 0) { int vCount = resourceEntries.level2Entries.Length; for (int j = 0; j < vCount; j++) { PEReader.IMAGE_RESOURCE_DIRECTORY_ENTRY level2 = resourceEntries.level2Entries[j]; object obj = resourceEntries.level2Map3Entries[level2]; PEReader.IMAGE_RESOURCE_DIRECTORY_ENTRY[] level3Array = (PEReader.IMAGE_RESOURCE_DIRECTORY_ENTRY[])obj; for (int k = 0; k < level3Array.Length; k++) { PEResourceData resData = new PEResourceData(); PEReader.IMAGE_RESOURCE_DIRECTORY_ENTRY level3 = level3Array[k]; PEReader.IMAGE_RESOURCE_DATA_ENTRY data = (PEReader.IMAGE_RESOURCE_DATA_ENTRY)resourceEntries.level3DATA[level3]; uint dataRVA = data.OffsetToData; uint dataSize = data.Size; uint resRVA = peReader.ResourceRVA; if (dataRVA < resRVA) { continue; } uint dataOffset = peReader.ResourceOffSet + (dataRVA - resRVA); if (dataOffset + dataSize > binary.Length) { continue; } byte[] resourceData = new byte[dataSize]; Array.Copy(binary, dataOffset, resourceData, 0, dataSize); string content = Encoding.Unicode.GetString(resourceData); resData.ResourceType = resourceEntries.level1Entry.Name_l; resData.FileOffset = dataOffset; resData.Size = dataSize; resData.Data = resourceData; resData.Content = content; resData.PEFileName = m_peFileName; resDataList.Add(resData); } } } } foreach (PEResourceData resData in resDataList) { resData.ParseData(number); List <TranslateUnit> tus = resData.GetTus(); result.AddRange(tus); if (tus.Count != 0) { byte[] ddd = resData.GetSrcData(); int lll = ddd.Length; } } string peOffset = PEUtil.GetPEHeaderAddress(allHex); int h_peOffset = PEUtil.ConvertHexToInt(peOffset); bool isDotNet = true; Assembly ass = null; try { ass = Assembly.Load(binary); isDotNet = true; m_log.Log("Loading " + m_peFileName + " with Microsoft .Net parser."); } catch (BadImageFormatException) { string name = peReader.Is32BitHeader ? "Win32" : "Win32+"; isDotNet = false; m_log.Log("Loading " + m_peFileName + " with " + name + " parser."); } if (isDotNet) { // mono AssemblyDefinition asm = MonoUtil.LoadAssembly(m_peFileName); ModuleDefinition module = asm.MainModule; foreach (Resource r in module.Resources.OrderBy(m => m.Name)) { if (r is EmbeddedResource) { EmbeddedResource er = r as EmbeddedResource; if (er != null) { Stream s = er.GetResourceStream(); s.Position = 0; ResourceReader reader; try { reader = new ResourceReader(s); } catch (ArgumentException ae) { throw ae; } foreach (DictionaryEntry entry in reader.Cast <DictionaryEntry>().OrderBy(e => e.Key.ToString())) { var keyString = entry.Key.ToString(); if (entry.Value is String) { TranslateUnit unit = new TranslateUnit("" + (++number), keyString, "0", "0", (string)entry.Value); unit.Category = er.Name; result.Add(unit); continue; } if (entry.Value is byte[]) { Stream ms = new MemoryStream((byte[])entry.Value); } if (entry.Value is Stream && keyString.ToLower().EndsWith(".baml")) { Stream ps = entry.Value as Stream; ps.Position = 0; string textContent = ""; string id = ""; XDocument xdoc = BamlUtil.LoadIntoDocument(new MyAssemblyResolver(), asm, ps); string xxx = xdoc.ToString(); IEnumerable <XElement> elements = xdoc.Elements(); XElement xroot = elements.First <XElement>(); // get TextBlock //XName name = XName.Get("TextBlock", baml_xmlns); elements = XmlUtil.SelectElementsByName(xroot, "TextBlock"); foreach (XElement element in elements) { XAttribute xatt = XmlUtil.SelectAttributeByName(element, "Text", "Text"); if (xatt != null) { textContent = xatt.Value; id = BamlUtil.GetTUID("Uid", XmlUtil.SelectAttributeByName(element, "Uid", "x:Uid").Value); } else { textContent = element.Value; XElement parent = element.Parent; if (parent.Name.LocalName.Equals("Button")) { id = BamlUtil.GetButtonId(parent) + ".TextBlock"; } } TranslateUnit unit = new TranslateUnit("" + (++number), id, "0", "0", textContent); unit.Category = keyString; result.Add(unit); } // get Button and CheckBox : ContentControl.Content , Name //name = XName.Get("Button", baml_xmlns); //elements = xdoc.Descendants(name); elements = XmlUtil.SelectElementsByName(xroot, "Button"); foreach (XElement element in elements) { XAttribute xatt = XmlUtil.SelectAttributeByName(element, "Content", "ContentControl.Content"); if (xatt != null) { textContent = xatt.Value; id = BamlUtil.GetButtonId(element) + ".Content"; TranslateUnit unit = new TranslateUnit("" + (++number), id, "0", "0", textContent); unit.Category = keyString; result.Add(unit); } } //name = XName.Get("CheckBox", baml_xmlns); //elements = xdoc.Descendants(name); elements = XmlUtil.SelectElementsByName(xroot, "CheckBox"); foreach (XElement element in elements) { XAttribute xatt = XmlUtil.SelectAttributeByName(element, "Content", "ContentControl.Content"); if (xatt != null) { textContent = xatt.Value; id = BamlUtil.GetButtonId(element) + ".Content";; TranslateUnit unit = new TranslateUnit("" + (++number), id, "0", "0", textContent); unit.Category = keyString; result.Add(unit); } XAttribute xatt2 = XmlUtil.SelectAttributeByName(element, "ToolTip", "FrameworkElement.ToolTip"); if (xatt2 != null) { textContent = xatt2.Value; id = BamlUtil.GetButtonId(element) + ".ToolTip";; TranslateUnit unit = new TranslateUnit("" + (++number), "0", "0", id, textContent); unit.Category = keyString; result.Add(unit); } } // others, add later } } } } } } return(result); }
/// <summary> /// 获取所有多语言资源文件路径 /// </summary> /// <returns></returns> private void CacheResourceNames() { LanguageResourceTypes resourceType = this._resourceType; string dirPath = this._resourceDirectoryPath; if (resourceType == LanguageResourceTypes.File) { // 如果是外部文件则直接获取所有文件路径 this._resourceNames = Directory.GetFiles(dirPath, "*.*", SearchOption.TopDirectoryOnly) .Select(p => Path.GetFileName(p)) .ToList(); return; } // 如果是Resource和Content文件则需要从_sourceDefaultDirectoryPath中获取到Assembly和路径,并通过Assembly // 读取对应路径下的资源文件 Regex pathRegex = new Regex(@"^(?<prefix>pack://application:,,,)?(/(?<assemblyName>[^;]+)(;[^;]+){0,2};component)?/(?<path>.*)$", RegexOptions.IgnoreCase); var mh = pathRegex.Match(dirPath); if (!mh.Success) { throw new InvalidOperationException(string.Format("The SourceDefaultDirectoryPath is invalid: [path:{0}]", dirPath)); } Assembly asm = null; var assemblyNameGroup = mh.Groups["assemblyName"]; if (!assemblyNameGroup.Success) { // 没有AssemblyName说明这个路径表示主Assembly asm = Assembly.GetEntryAssembly(); } else { // 通过AssemblyName获取程序集 string assemblyName = assemblyNameGroup.Value; asm = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(p => p.GetName().Name == assemblyName); if (asm == null) { throw new InvalidOperationException(string.Format("Can not find resource assembly: [assembly:{0}]", assemblyName)); } } string path = mh.Groups["path"].Value; if (resourceType == LanguageResourceTypes.Content && asm == Assembly.GetEntryAssembly()) { // 当Assembly为WPF工程时,并且资源类型为Content时,必须用AssemblyAssociatedContentFileAttribute // 才能获取资源文件列表 this._resourceNames = asm.GetCustomAttributes(typeof(AssemblyAssociatedContentFileAttribute), true) .Cast <AssemblyAssociatedContentFileAttribute>() .Where(p => p.RelativeContentFilePath.TrimStart('/').StartsWith(path, StringComparison.InvariantCultureIgnoreCase)) .Select(attr => Path.GetFileName(attr.RelativeContentFilePath)) .ToList(); } else { // 当Assembly不是WPF工程时获取资源文件列表需要用GetManifestResourceStream string resName = asm.GetName().Name + ".g.resources"; using (var stream = asm.GetManifestResourceStream(resName)) using (var reader = new ResourceReader(stream)) { this._resourceNames = reader.Cast <DictionaryEntry>() .Where(p => ((string)p.Key).TrimStart('/').StartsWith(path, StringComparison.InvariantCultureIgnoreCase)) .Select(p => Path.GetFileName((string)p.Key)) .ToList(); } }// else }
public static Icon LoadIconFrom(string dllPath, string resourceName) { var uri = new Uri(dllPath); if (uri.Scheme == "file") { dllPath = uri.LocalPath; } if (IOExtensions.IsClrImage(dllPath)) { var assm = Assembly.LoadFile(dllPath); var stream = assm.GetManifestResourceStream(resourceName); if (stream == null) { var names = assm.GetManifestResourceNames(); foreach (var name in names) { try { stream = assm.GetManifestResourceStream(name); var resourceReader = new ResourceReader(stream); var nameFind = resourceReader.Cast <DictionaryEntry>().SingleOrDefault(k => ((string)k.Key) == resourceName); if (nameFind.Key != null) { return((Icon)nameFind.Value); } } catch { } } } } else { var buffer = new StringBuilder(MAX_PATH); var hInst = LoadLibrary(dllPath); if (hInst != IntPtr.Zero) { var hIcon = LoadIcon(hInst, resourceName); if (hIcon != IntPtr.Zero) { return(Icon.FromHandle(hIcon)); } else { var id = 0; if (resourceName.StartsWith("#")) { id = int.Parse(resourceName.RemoveStart(1)); } else { id = int.Parse(resourceName); } hIcon = LoadIcon(hInst, id); if (hIcon != IntPtr.Zero) { return(Icon.FromHandle(hIcon)); } } } } return(null); }