Inheritance: IDisposable, IEnumerable
Esempio n. 1
0
   public static Dictionary<String, Bitmap> CreateIconSetBitmaps(ResourceSet resSet, Boolean invert)
   {
      Dictionary<String, Bitmap> icons = new Dictionary<String, Bitmap>();

      if (resSet != null)
      {
         foreach (System.Collections.DictionaryEntry e in resSet)
         {
            if (e.Key is String && e.Value is Bitmap)
            {
               Bitmap b = (Bitmap)e.Value;
               if (invert)
               {
                  BitmapProcessing.Desaturate(b);
                  BitmapProcessing.Invert(b);
                  BitmapProcessing.AdjustBrightness(b, 101);
               }

               Bitmap b_hidden = new Bitmap(b);
               BitmapProcessing.AdjustOpacity(b_hidden, 100);

               Bitmap b_filtered = new Bitmap(b);
               BitmapProcessing.AdjustOpacity(b_filtered, Outliner.Controls.Tree.TreeNode.FilteredNodeOpacity);

               icons.Add((String)e.Key, b);
               icons.Add((String)e.Key + "_hidden", b_hidden);
               icons.Add((String)e.Key + "_filtered", b_filtered);
            }
         }
      }

      return icons;
   }
        protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            ResourceSet resourceSet = (ResourceSet)ResourceSets[culture];
            if (resourceSet == null)
            {
                // Lazy-load default language (without caring about duplicate assignment in race conditions, no harm done);
                if (neutralResourcesCulture == null)
                {
                    neutralResourcesCulture = GetNeutralResourcesLanguage(MainAssembly);
                }

                // If we're asking for the default language, then ask for the invariant (non-specific) resources.
                if (neutralResourcesCulture.Equals(culture))
                {
                    culture = CultureInfo.InvariantCulture;
                }

                string resourceFileName = GetResourceFileName(culture);
                Stream store = MainAssembly.GetManifestResourceStream(contextTypeInfo, resourceFileName);

                // If we found the appropriate resources in the local assembly...
                if (store != null)
                {
                    resourceSet = new ResourceSet(store);
                    // Save for later.
                    AddResourceSet(ResourceSets, culture, ref resourceSet);
                }
                else
                {
                    resourceSet = base.InternalGetResourceSet(culture, createIfNotExists, tryParents);
                }
            }
            return resourceSet;
        }
Esempio n. 3
0
        public MyResourceDataFile(string fileName)
        {
#if DOTNETCORE
            var reader = new System.Resources.Extensions.DeserializingResourceReader(fileName);
#else
            var reader = new System.Resources.ResourceReader(fileName);
#endif

            this.FileName = fileName;
            this.Name     = Path.GetFileNameWithoutExtension(fileName);
            var  objValues   = new Dictionary <string, object>();
            var  strValues   = new Dictionary <string, string>();
            var  resouceSet  = new System.Resources.ResourceSet(reader);
            var  enumer      = resouceSet.GetEnumerator();
            var  lstData     = new List <byte>();
            bool hasBmpValue = false;
            while (enumer.MoveNext())
            {
                string itemName = (string)enumer.Key;
                var    item     = new MyResourceDataItem();
                item.Name       = itemName;
                item.StartIndex = lstData.Count;
                item.Key        = _Random.Next(1000, int.MaxValue - 1000);
                item.Value      = enumer.Value;
                if (enumer.Value is string)
                {
                    item.IsBmp = false;
                    string str = (string)item.Value;
                    int    key = item.Key;
                    for (int iCount = 0; iCount < str.Length; iCount++, key++)
                    {
                        var v = str[iCount] ^ key;
                        lstData.Add((byte)(v >> 8));
                        lstData.Add((byte)(v & 0xff));
                    }
                }
                else if (enumer.Value is System.Drawing.Bitmap)
                {
                    item.IsBmp  = true;
                    hasBmpValue = true;
                    var ms = new System.IO.MemoryStream();
                    ((System.Drawing.Bitmap)item.Value).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    var  bs2 = ms.ToArray();
                    byte key = (byte)item.Key;
                    for (int iCount = 0; iCount < bs2.Length; iCount++, key++)
                    {
                        bs2[iCount] = (byte)(bs2[iCount] ^ key);
                    }
                    lstData.AddRange(bs2);
                }
                else
                {
                    throw new NotSupportedException(item.Value.GetType().FullName);
                }
                item.BsLength = lstData.Count - item.StartIndex;
                this.Items.Add(item);
            }
            resouceSet.Close();
            this.Datas = lstData.ToArray();
        }
        public void Init()
        {
            // Determine if the Preset settings files exist for the routine //
            // This has been changed so that the XML files are now embedded resources //

            var presetResourceSet =
                new ResourceSet(
                    Assembly.GetExecutingAssembly().GetManifestResourceStream("Paws.Properties.Resources.resources"));

            // Determine if the Preset settings files exist for the current character //
            var characterSettingsDirectory = Path.Combine(CharacterSettingsDirectory, "Paws");
            if (!Directory.Exists(characterSettingsDirectory))
            {
                Directory.CreateDirectory(characterSettingsDirectory);
                Log.Diagnostics("Character Settings Directory Established... generating default presets.");


                var resourceCount = 0;
                foreach (DictionaryEntry entry in presetResourceSet)
                {
                    using (
                        var streamWriter =
                            new StreamWriter(
                                Path.Combine(characterSettingsDirectory, entry.Key.ToString().Replace("_", " ") + ".xml"),
                                false))
                    {
                        streamWriter.Write(entry.Value);
                        resourceCount++;
                    }
                }

                Log.Diagnostics(string.Format("...Finished generating {0} preset files", resourceCount));
            }
        }
        protected override ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            ResourceSet rs = (ResourceSet)this.ResourceSets[culture];
            if (rs == null)
            {
                Stream store = null;
                string resourceFileName = null;

                //lazy-load default language;
                if (this._neutralResourcesCulture == null)
                {
                    this._neutralResourcesCulture = GetNeutralResourcesLanguage(this.MainAssembly);
                }

                //if we're asking for the default language, then ask for the invaliant (non-specific) resources.
                if (_neutralResourcesCulture.Equals(culture))
                    culture = CultureInfo.InvariantCulture;
                resourceFileName = GetResourceFileName(culture);

                store = this.MainAssembly.GetManifestResourceStream(this._contextTypeInfo, resourceFileName);

                //If we found the appropriate resources in the local assembly
                if (store != null)
                {
                    rs = new ResourceSet(store);
                    //save for later.
                    AddResourceSet(this.ResourceSets, culture, ref rs);
                }
                else
                {
                    rs = base.InternalGetResourceSet(culture, createIfNotExists, tryParents);
                }
            }
            return rs;
        }
 private static void AddResources(Dictionary<String, String> resources,
     ResourceManager resourceManager, ResourceSet neutralSet) {
     foreach (DictionaryEntry res in neutralSet) {
         string key = (string)res.Key;
         string value = resourceManager.GetObject(key) as string;
         if (value != null) {
             resources[key] = value;
         }
     }
 }
 protected override void BeforeLocalizeType(Type controlType)
 {
     if (this.FIniSource != null)
     {
         this.ResourceSet = new IniResourceSet(this.FIniSource, controlType);
     }
     else if (this.FIniPath != null)
     {
         this.ResourceSet = new IniResourceSet(this.FIniPath, controlType);
     }
 }
        private static IEnumerable<DictionaryEntry> ConvertResourceSetToDictionaryEntries( ResourceSet resourceSet )
        {
            var dictionaryEntries = new List<DictionaryEntry>();

            foreach ( DictionaryEntry entry in resourceSet )
            {
                dictionaryEntries.Add( entry );
            }

            return dictionaryEntries;
        }
 public IconPackImageProvider(string iconPackPath)
 {
     this.IconPack = new ResourceSet(iconPackPath);
     foreach (DefaultIcon icon in Enum.GetValues(typeof(DefaultIcon)))
     {
         this.DefaultIconMap.Add(icon, string.Intern("DefaultIcon." + icon.ToString()));
     }
     foreach (VolumeType type in Enum.GetValues(typeof(VolumeType)))
     {
         this.VolumeTypeMap.Add(type, string.Intern("VolumeType." + type.ToString()));
     }
 }
 public void Dispose()
 {
     if (this.IconPack != null)
     {
         this.IconPack.Dispose();
     }
     this.IconPack = null;
     this.DefaultIconMap = null;
     this.VolumeTypeMap = null;
     this.DefaultIconSize = null;
     this.IconCache = null;
 }
Esempio n. 11
0
        private ICollection<KeyValuePair<string, object>> GetTextResourceContent(ResourceSet set, string lang)
        {
            var resourceDictionary = set.Cast<DictionaryEntry>()
                                        .ToDictionary(r => r.Key.ToString(),
                                                      r => r.Value.ToString());
            var content = (ICollection<KeyValuePair<string, object>>)new ExpandoObject();

            foreach (var item in resourceDictionary)
            {
                content.Add(new KeyValuePair<string, object>(item.Key, item.Value));
            }

            return content;
        }
Esempio n. 12
0
        /// <summary>
        /// This method will return a resource set based on a Culture set by application.
        /// </summary>
        /// <param name="culture"></param>
        /// <param name="createIfNotExists"></param>
        /// <param name="tryParents"></param>
        /// <returns>ResourceSet</returns>
        protected override ResourceSet InternalGetResourceSet(System.Globalization.CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            ResourceSet rs = null;

            lock (this.cultureResourceSetDictionary)
            {
                if (false == this.cultureResourceSetDictionary.TryGetValue(culture.Name, out rs))
                {
                    rs = new ResourceSet(new DBResourceReader(culture, this.dataProvider));
                    this.cultureResourceSetDictionary[culture.Name] = rs;
                }
            }

            return rs;
        }
Esempio n. 13
0
        private void Form1_Load(object sender, EventArgs e)
        {
            strs = new ArrayList();

            rs = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
            foreach (DictionaryEntry entry in rs)
            {
                if (entry.Key.ToString().Contains("_"))
                    continue;
                strs.Add(entry.Key);
            }
            strs.Sort();
            foreach(string s in strs)
                comboBox1.Items.Add(s);
        }
Esempio n. 14
0
        static ResourceManager LoadLanguage(CultureInfo culture, ref ResourceSet rs)
        {
            Current = culture;
            if (rs != null) { rs.Dispose(); rs = null; }

            try
            {
                ResourceManager rManager = new ResourceManager("XPloit.Res.Res", typeof(Lang).Assembly) { IgnoreCase = true };
                rs = rManager.GetResourceSet(culture, true, true);
                return rManager;
            }
            catch { }

            return null;
        }
        private static void AddLocalizedResource(ResourceManager resourceMgr, string cultureName)
        {
            using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("ExBuddy.Localization.Localization." + cultureName + ".resources"))
            {
                if (s == null)
                {
                    Logging.WriteDiagnostic("Couldn't find {0}", "ExBuddy.Localization.Localization." + cultureName + ".resources");
                    return;
                }

                FieldInfo resourceSetsField = typeof(ResourceManager).GetField("_resourceSets", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField);
                Dictionary<string, ResourceSet> resourceSets = (Dictionary<string, ResourceSet>)resourceSetsField.GetValue(resourceMgr);

                ResourceSet resources = new ResourceSet(s);
                resourceSets.Add(cultureName, resources);
            }
        }
        protected override ResourceSet InternalGetResourceSet(CultureInfo culture,
            bool createIfNotExists, bool tryParents)
        {
            ResourceSet rs = (ResourceSet)ResourceSets[culture];
            if (rs == null)
            {
                string resourceFileName = null;

                //lazy-load default language (without caring about duplicate assignment in race conditions, no harm done);
                if (_neutralResourcesCulture == null)
                {
                    _neutralResourcesCulture =
                        GetNeutralResourcesLanguage(MainAssembly);
                }

                // if we're asking for the default language, then ask for the
                // invariant (non-specific) resources.
                if (_neutralResourcesCulture.Equals(culture))
                    culture = CultureInfo.InvariantCulture;
                
                resourceFileName = GetResourceFileName(culture);

                // Only bother to try the lookup based on the resource property if we haven't tried this language before
                if (!_prevCultures.Contains(culture.ToString()) && culture != CultureInfo.InvariantCulture)
                {
                    _prevCultures.Add(culture.ToString());
                    // The T4 template resource generator will link the culture specific resources in to the invariant culture resource
                    // We'll try and load the culture specific resource here

                    var content = GetString("Resources." + culture);
                    if (content != null)
                    {
                        using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
                        using (var reader = new ResXResourceReader(stream))
                        {
                            rs = new ResourceSet(reader);
                        }
                    }
                }

                if (rs == null)
                    rs = base.InternalGetResourceSet(culture, createIfNotExists, tryParents);
                 
            }
            return rs;
        }
Esempio n. 17
0
        private static ResourceManager GetResourceManager(ref ResourceManager field, ResourceSet name)
        {
            if (null == field)
            {
                lock (sync)
                {
                    if (null == field)
                    {
                        var t = typeof(ActionText);
                        var qualifiedName = t.Namespace + "." + Enum.GetName(typeof(ResourceSet), name);

                        field = new ResourceManager(qualifiedName, t.Assembly);
                    }
                }
            }

            return field;
        }
 void Decompile()
 {
     Stream s = resource.GetResourceStream();
     s.Position = 0;
     if (resource.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase))
     {
         IEnumerable<DictionaryEntry> rs = null;
         try { rs = new ResourceSet(s).Cast<DictionaryEntry>(); }
         catch (ArgumentException) { }
         if (rs != null && rs.All(e => e.Value is Stream))
         {
             foreach (var pair in rs)
             {
                 Stream entryStream = (Stream)pair.Value;
                 byte[] d = new byte[entryStream.Length];
                 entryStream.Position = 0;
                 if (pair.Key.ToString().EndsWith(".baml", StringComparison.OrdinalIgnoreCase))
                 {
                     MemoryStream ms = new MemoryStream();
                     entryStream.CopyTo(ms);
                     // TODO implement extension point
                     // var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
                     // string xaml = null;
                     // try {
                     //		xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
                     //	}
                     //	catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
                     //	if (xaml != null) {
                     //	File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
                     //	yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
                     //	continue;
                     //	}
                 }
                 else
                 {
                     entryStream.Read(d, 0, (int)entryStream.Length);
                 }
                 string tmp = Path.GetTempFileName();
                 File.WriteAllBytes(tmp, d);
                 Entries.Add(pair.Key.ToString(), tmp);
             }
         }
     }
 }
 //private method in framework, had to be re-specified
 private static void AddResourceSet(Hashtable localResourceSets, CultureInfo culture, ref ResourceSet rs)
 {
     lock (localResourceSets)
     {
         ResourceSet objA = (ResourceSet)localResourceSets[culture];
         if (objA != null)
         {
             if (!object.Equals(objA, rs))
             {
                 rs.Dispose();
                 rs = objA;
             }
         }
         else
         {
             localResourceSets.Add(culture, rs);
         }
     }
 }
        private List <string> ResolveKeys()
        {
            List <string> keys = new List <string>(100);

            System.IO.Stream fs = _assembly.GetManifestResourceStream(_baseName + ".resources");

            using (var streamResx = new System.Resources.ResourceSet(fs))
            {
                IDictionaryEnumerator enumerator = streamResx.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    keys.Add(enumerator.Key.ToString());
                }
            }

            keys.Sort();

            return(keys);
        }
 // Private method in framework, had to be re-implemented here.
 private static void AddResourceSet(Hashtable localResourceSets, CultureInfo culture, ref ResourceSet resourceSet)
 {
     lock (localResourceSets)
     {
         ResourceSet localResourceSet = (ResourceSet)localResourceSets[culture];
         if (localResourceSet != null)
         {
             if (!Equals(localResourceSet, resourceSet))
             {
                 resourceSet.Dispose();
                 resourceSet = localResourceSet;
             }
         }
         else
         {
             localResourceSets.Add(culture, resourceSet);
         }
     }
 }
Esempio n. 22
0
    public static string ParseWording(string WordingID)
    {
        string sWording = "";

        /*
         * object o_LocalRs = base.GetLocalResourceObject(WordingID);
         *
         * if (o_LocalRs != null)
         * {
         *  if (o_LocalRs.GetType() == typeof(string))
         *      sWording = o_LocalRs.ToString();
         * }
         * else
         * {
         *  object o_Global = base.GetGlobalResourceObject("DMSWording", WordingID);
         *  if (o_Global != null)
         *  {
         *      if (o_Global.GetType() == typeof(string))
         *          sWording = o_Global.ToString();
         *  }
         * }
         */

        System.Resources.ResourceSet rs = Resources.DMSWording.ResourceManager.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture, true, true);

        object o = rs.GetObject(WordingID);


        if (o != null)
        {
            if (o.GetType() == typeof(string))
            {
                sWording = o.ToString();
            }
        }

        if (sWording == "")
        {
            sWording = WordingID;
        }

        return(sWording);
    }
        /// <summary>
        /// Gets the data from resource file and stores it in a JSON object.
        /// </summary>
        /// <param name="fileName">Name of resource file</param>
        /// <param name="resourceFileLocation">Location of resource file</param>
        /// <returns>
        /// JSON object which will have the data from resource file.
        /// </returns>
        public static string GetResourceData(string fileName, string resourceFileLocation)
        {
            ResourceSet resourceSet;
            StringBuilder scriptBuilder = new StringBuilder();
            try
            {
                using (ResXResourceReader resxReader = new ResXResourceReader(HttpContext.Current.Server.MapPath(@"~/" + resourceFileLocation + ConstantStrings.ForwardSlash + fileName + ConstantStrings.ResourceFileExtension)))
                {
                    resourceSet = new ResourceSet(resxReader);
                    foreach (DictionaryEntry entry in resourceSet)
                    {
                        string resourceKey = (string)entry.Key;
                        object resource = entry.Value;
                        scriptBuilder.Append("\"" + resourceKey + "\":" + "\"" + resource + "\",");
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, UIConstantStrings.LogTableName);
            }

            return string.Concat(Convert.ToString(scriptBuilder, CultureInfo.InvariantCulture).TrimEnd(','));
        }
Esempio n. 24
0
        // Looks up a resource value for a particular name.  Looks in the
        // specified CultureInfo, and if not found, all parent CultureInfos.
        // Returns null if the resource wasn't found.
        //
        public virtual string GetString(string name, CultureInfo culture)
        {
            if (null == name)
            {
                throw new ArgumentNullException(nameof(name));
            }

#if FEATURE_APPX
            if (_bUsingModernResourceManagement)
            {
                // If the caller explicitly passed in a culture that was obtained by calling CultureInfo.CurrentUICulture,
                // null it out, so that we re-compute it.  If we use modern resource lookup, we may end up getting a "better"
                // match, since CultureInfo objects can't represent all the different languages the AppX resource model supports.
                if (object.ReferenceEquals(culture, CultureInfo.CurrentUICulture))
                {
                    culture = null;
                }

                if (_PRIonAppXInitialized == false)
                {
                    // Always throw if we did not fully succeed in initializing the WinRT Resource Manager.

                    if (_PRIExceptionInfo != null && _PRIExceptionInfo.PackageSimpleName != null && _PRIExceptionInfo.ResWFile != null)
                    {
                        throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_ResWFileNotLoaded, _PRIExceptionInfo.ResWFile, _PRIExceptionInfo.PackageSimpleName));
                    }

                    throw new MissingManifestResourceException(SR.MissingManifestResource_NoPRIresources);
                }

                // Throws WinRT hresults.
                return(GetStringFromPRI(name,
                                        culture == null ? null : culture.Name,
                                        _neutralResourcesCulture.Name));
            }
            else
#endif // FEATURE_APPX
            {
                if (culture == null)
                {
                    culture = CultureInfo.CurrentUICulture;
                }

                ResourceSet last = GetFirstResourceSet(culture);

                if (last != null)
                {
                    string value = last.GetString(name, _ignoreCase);
                    if (value != null)
                    {
                        return(value);
                    }
                }


                // This is the CultureInfo hierarchy traversal code for resource
                // lookups, similar but necessarily orthogonal to the ResourceSet
                // lookup logic.
                ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
                foreach (CultureInfo currentCultureInfo in mgr)
                {
                    ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true);
                    if (rs == null)
                    {
                        break;
                    }

                    if (rs != last)
                    {
                        string value = rs.GetString(name, _ignoreCase);
                        if (value != null)
                        {
                            // update last used ResourceSet
                            if (_lastUsedResourceCache != null)
                            {
                                lock (_lastUsedResourceCache)
                                {
                                    _lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
                                    _lastUsedResourceCache.lastResourceSet = rs;
                                }
                            }
                            return(value);
                        }

                        last = rs;
                    }
                }
            }

            return(null);
        }
Esempio n. 25
0
		IEnumerable<Tuple<string, string>> WriteResourceFilesInProject(LoadedAssembly assembly, DecompilationOptions options, HashSet<string> directories)
		{
			//AppDomain bamlDecompilerAppDomain = null;
			//try {
				foreach (EmbeddedResource r in assembly.AssemblyDefinition.MainModule.Resources.OfType<EmbeddedResource>()) {
					string fileName;
					Stream s = r.GetResourceStream();
					s.Position = 0;
					if (r.Name.EndsWith(".g.resources", StringComparison.OrdinalIgnoreCase)) {
						IEnumerable<DictionaryEntry> rs = null;
						try {
							rs = new ResourceSet(s).Cast<DictionaryEntry>();
						}
						catch (ArgumentException) {
						}
						if (rs != null && rs.All(e => e.Value is Stream)) {
							foreach (var pair in rs) {
								fileName = Path.Combine(((string)pair.Key).Split('/').Select(p => TextView.DecompilerTextView.CleanUpName(p)).ToArray());
								string dirName = Path.GetDirectoryName(fileName);
								if (!string.IsNullOrEmpty(dirName) && directories.Add(dirName)) {
									Directory.CreateDirectory(Path.Combine(options.SaveAsProjectDirectory, dirName));
								}
								Stream entryStream = (Stream)pair.Value;
								entryStream.Position = 0;
								if (fileName.EndsWith(".baml", StringComparison.OrdinalIgnoreCase)) {
									MemoryStream ms = new MemoryStream();
									entryStream.CopyTo(ms);
									// TODO implement extension point
//									var decompiler = Baml.BamlResourceEntryNode.CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, assembly.FileName);
//									string xaml = null;
//									try {
//										xaml = decompiler.DecompileBaml(ms, assembly.FileName, new ConnectMethodDecompiler(assembly), new AssemblyResolver(assembly));
//									}
//									catch (XamlXmlWriterException) { } // ignore XAML writer exceptions
//									if (xaml != null) {
//										File.WriteAllText(Path.Combine(options.SaveAsProjectDirectory, Path.ChangeExtension(fileName, ".xaml")), xaml);
//										yield return Tuple.Create("Page", Path.ChangeExtension(fileName, ".xaml"));
//										continue;
//									}
								}
								using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
									entryStream.CopyTo(fs);
								}
								yield return Tuple.Create("Resource", fileName);
							}
							continue;
						}
					}
					fileName = GetFileNameForResource(r.Name, directories);
					using (FileStream fs = new FileStream(Path.Combine(options.SaveAsProjectDirectory, fileName), FileMode.Create, FileAccess.Write)) {
						s.CopyTo(fs);
					}
					yield return Tuple.Create("EmbeddedResource", fileName);
				}
			//}
			//finally {
			//    if (bamlDecompilerAppDomain != null)
			//        AppDomain.Unload(bamlDecompilerAppDomain);
			//}
		}
Esempio n. 26
0
        internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
        {
            if (store.CanSeek && store.Length > 4L)
            {
                long         position     = store.Position;
                BinaryReader binaryReader = new BinaryReader(store);
                int          num          = binaryReader.ReadInt32();
                if (num == ResourceManager.MagicNumber)
                {
                    int    num2 = binaryReader.ReadInt32();
                    string text;
                    string text2;
                    if (num2 == ResourceManager.HeaderVersionNumber)
                    {
                        binaryReader.ReadInt32();
                        text  = binaryReader.ReadString();
                        text2 = binaryReader.ReadString();
                    }
                    else
                    {
                        if (num2 <= ResourceManager.HeaderVersionNumber)
                        {
                            throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", new object[]
                            {
                                this._mediator.MainAssembly.GetSimpleName()
                            }));
                        }
                        int  num3   = binaryReader.ReadInt32();
                        long offset = binaryReader.BaseStream.Position + (long)num3;
                        text  = binaryReader.ReadString();
                        text2 = binaryReader.ReadString();
                        binaryReader.BaseStream.Seek(offset, SeekOrigin.Begin);
                    }
                    store.Position = position;
                    if (this.CanUseDefaultResourceClasses(text, text2))
                    {
                        return(new RuntimeResourceSet(store));
                    }
                    Type            type           = Type.GetType(text, true);
                    IResourceReader resourceReader = (IResourceReader)Activator.CreateInstance(type, new object[]
                    {
                        store
                    });
                    object[] args = new object[]
                    {
                        resourceReader
                    };
                    Type type2;
                    if (this._mediator.UserResourceSet == null)
                    {
                        type2 = Type.GetType(text2, true, false);
                    }
                    else
                    {
                        type2 = this._mediator.UserResourceSet;
                    }
                    return((ResourceSet)Activator.CreateInstance(type2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, args, null, null));
                }
                else
                {
                    store.Position = position;
                }
            }
            if (this._mediator.UserResourceSet == null)
            {
                return(new RuntimeResourceSet(store));
            }
            object[] args2 = new object[]
            {
                store,
                assembly
            };
            ResourceSet result;

            try
            {
                try
                {
                    return((ResourceSet)Activator.CreateInstance(this._mediator.UserResourceSet, args2));
                }
                catch (MissingMethodException)
                {
                }
                args2 = new object[]
                {
                    store
                };
                ResourceSet resourceSet = (ResourceSet)Activator.CreateInstance(this._mediator.UserResourceSet, args2);
                result = resourceSet;
            }
            catch (MissingMethodException innerException)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", new object[]
                {
                    this._mediator.UserResourceSet.AssemblyQualifiedName
                }), innerException);
            }
            return(result);
        }
Esempio n. 27
0
        private static bool WriteResource(
            ResourceManager resourceManager,
            ResourceSet neutralSet,
            StreamWriter writer,
            bool debug,
            bool first) {

            foreach (DictionaryEntry res in neutralSet) {
                string key = (string)res.Key;
                string value = resourceManager.GetString(key);
                if (value != null) {
                    if (first) {
                        first = false;
                    }
                    else {
                        writer.Write(',');
                    }
                    if (debug) writer.WriteLine();
                    writer.Write('\'');
                    writer.Write(QuoteString(key));
                    writer.Write("':'");
                    writer.Write(QuoteString(value));
                    writer.Write('\'');
                }
            }
            return first;
        }
        /// <summary>
        ///     Recursive routine that creates a resource hashtable
        ///     populated with resources for culture and all parent
        ///     cultures.
        /// </summary>
        private SortedList<string, object> FillResources(CultureInfo culture, out ResourceSet resourceSet)
        {
            SortedList<string, object> sd;
            ResourceSet parentResourceSet = null;

            // Traverse parents first, so we always replace more
            // specific culture values with less specific.
            //
            if (!culture.Equals(CultureInfo.InvariantCulture) && !culture.Equals(NeutralResourcesCulture))
            {
                sd = FillResources(culture.Parent, out parentResourceSet);
            }
            else
            {
                // We're at the bottom, so create the sorted dictionary
                // 
                // TODO: NETSTANDARD2.0
                if (System.Stub.ResourceManager_IgnoreCase())
                {
                    sd = new SortedList<string, object>(StringComparer.OrdinalIgnoreCase);
                }
                else
                {
                    sd = new SortedList<string, object>(StringComparer.Ordinal);
                }
            }

            // Now walk culture's resource set.  Another thing we
            // do here is ask ResourceManager to traverse up the 
            // parent chain.  We do NOT want to do this because
            // we are trawling up the parent chain ourselves, but by
            // passing in true for the second parameter the resource
            // manager will cache the culture it did find, so when we 
            // do recurse all missing resources will be filled in
            // so we are very fast.  That's why we remember what our
            // parent resource set's instance was -- if they are the
            // same, we're looking at a cache we've already applied.
            //
            //NETSTANDARD2.0 - GetResourceSet(culture, true, true);
            resourceSet = System.Stub.ResourceManager_GetResourceSet(culture, true, true);
            if (resourceSet != null && !object.ReferenceEquals(resourceSet, parentResourceSet))
            {
                foreach (DictionaryEntry de in resourceSet)
                {
                    sd[(string)de.Key] = de.Value;
                }
            }

            return sd;
        }
Esempio n. 29
0
 [System.Security.SecurityCritical]  // auto-generated
 private static bool IsResourcePresent(String resourceKey)
 {
     if (MscorlibResourceSet == null)
     {
         MscorlibResourceSet = new ResourceSet(typeof(Environment).Assembly.GetManifestResourceStream("mscorlib.resources"));
     }
     return MscorlibResourceSet.GetString(resourceKey) != null;
 }
 private static void AddResourceSet(Dictionary <string, ResourceSet> localResourceSets, string cultureName, ref ResourceSet rs)
 {
     lock (localResourceSets)
     {
         ResourceSet set;
         if (localResourceSets.TryGetValue(cultureName, out set))
         {
             if (!object.ReferenceEquals(set, rs))
             {
                 if (!localResourceSets.ContainsValue(rs))
                 {
                     rs.Dispose();
                 }
                 rs = set;
             }
         }
         else
         {
             localResourceSets.Add(cultureName, rs);
         }
     }
 }
Esempio n. 31
0
 // Simple helper to ease maintenance and improve readability.
 private static void AddResourceSet(Dictionary<String,ResourceSet> localResourceSets, String cultureName, ref ResourceSet rs)
 {
     // InternalGetResourceSet is both recursive and reentrant - 
     // assembly load callbacks in particular are a way we can call
     // back into the ResourceManager in unexpectedly on the same thread.
     lock(localResourceSets) {
         // If another thread added this culture, return that.
         ResourceSet lostRace;
         if (localResourceSets.TryGetValue(cultureName, out lostRace)) {
             if (!Object.ReferenceEquals(lostRace, rs)) {
                 // Note: In certain cases, we can be trying to add a ResourceSet for multiple
                 // cultures on one thread, while a second thread added another ResourceSet for one
                 // of those cultures.  If there is a race condition we must make sure our ResourceSet 
                 // isn't in our dictionary before closing it.
                 if (!localResourceSets.ContainsValue(rs))
                     rs.Dispose();
                 rs = lostRace;
             }
         }
         else {
             localResourceSets.Add(cultureName, rs);
         }
     }
 }
Esempio n. 32
0
 // Simple helper to ease maintenance and improve readability.
 private static void AddResourceSet(Dictionary <string, ResourceSet> localResourceSets, string cultureName, ref ResourceSet rs)
 {
     // InternalGetResourceSet is both recursive and reentrant -
     // assembly load callbacks in particular are a way we can call
     // back into the ResourceManager in unexpectedly on the same thread.
     lock (localResourceSets)
     {
         // If another thread added this culture, return that.
         ResourceSet lostRace;
         if (localResourceSets.TryGetValue(cultureName, out lostRace))
         {
             if (!object.ReferenceEquals(lostRace, rs))
             {
                 // Note: In certain cases, we can be trying to add a ResourceSet for multiple
                 // cultures on one thread, while a second thread added another ResourceSet for one
                 // of those cultures.  If there is a race condition we must make sure our ResourceSet
                 // isn't in our dictionary before closing it.
                 if (!localResourceSets.ContainsValue(rs))
                 {
                     rs.Dispose();
                 }
                 rs = lostRace;
             }
         }
         else
         {
             localResourceSets.Add(cultureName, rs);
         }
     }
 }
Esempio n. 33
0
        public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary <string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
        {
            ResourceSet     resourceSet     = null;
            Stream          stream          = null;
            RuntimeAssembly runtimeAssembly = null;
            CultureInfo     cultureInfo     = this.UltimateFallbackFixup(culture);

            if (cultureInfo.HasInvariantCultureName && this._mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
            {
                runtimeAssembly = this._mediator.MainAssembly;
            }
            else if (!cultureInfo.HasInvariantCultureName && !this._mediator.TryLookingForSatellite(cultureInfo))
            {
                runtimeAssembly = null;
            }
            else
            {
                runtimeAssembly = this.GetSatelliteAssembly(cultureInfo, ref stackMark);
                if (runtimeAssembly == null)
                {
                    bool flag = culture.HasInvariantCultureName && this._mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite;
                    if (flag)
                    {
                        this.HandleSatelliteMissing();
                    }
                }
            }
            string resourceFileName = this._mediator.GetResourceFileName(cultureInfo);

            if (runtimeAssembly != null)
            {
                lock (localResourceSets)
                {
                    if (localResourceSets.TryGetValue(culture.Name, out resourceSet) && FrameworkEventSource.IsInitialized)
                    {
                        FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(this._mediator.BaseName, this._mediator.MainAssembly, culture.Name);
                    }
                }
                stream = this.GetManifestResourceStream(runtimeAssembly, resourceFileName, ref stackMark);
            }
            if (FrameworkEventSource.IsInitialized)
            {
                if (stream != null)
                {
                    FrameworkEventSource.Log.ResourceManagerStreamFound(this._mediator.BaseName, this._mediator.MainAssembly, culture.Name, runtimeAssembly, resourceFileName);
                }
                else
                {
                    FrameworkEventSource.Log.ResourceManagerStreamNotFound(this._mediator.BaseName, this._mediator.MainAssembly, culture.Name, runtimeAssembly, resourceFileName);
                }
            }
            if (createIfNotExists && stream != null && resourceSet == null)
            {
                if (FrameworkEventSource.IsInitialized)
                {
                    FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(this._mediator.BaseName, this._mediator.MainAssembly, culture.Name, resourceFileName);
                }
                resourceSet = this.CreateResourceSet(stream, runtimeAssembly);
            }
            else if (stream == null && tryParents)
            {
                bool hasInvariantCultureName = culture.HasInvariantCultureName;
                if (hasInvariantCultureName)
                {
                    this.HandleResourceStreamMissing(resourceFileName);
                }
            }
            if (!createIfNotExists && stream != null && resourceSet == null && FrameworkEventSource.IsInitialized)
            {
                FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(this._mediator.BaseName, this._mediator.MainAssembly, culture.Name);
            }
            return(resourceSet);
        }
        private ResourceSet GetResourceSet(CultureInfo culture, bool custom) {
            ResourceSet resource;
            String resourceKey = GetResourceKey(culture, custom);
            lock(_resourceLock) {

                // if the resource data for this culture has not yet been loaded, load it
                if(!ResourceData.TryGetValue(resourceKey, out resource)) {

                    // set the filename according to the cuture
                    String filename;
                    if(null == culture) {
                        filename = "resources.custom.txt";
                    } else if(culture.Equals(CultureInfo.InvariantCulture)) {
                        filename = "resources.txt";
                    } else {
                        filename = "resources.";
                        if(custom) {
                            filename += "custom.";
                        }
                        filename += culture.Name.ToLowerInvariant() + ".txt";
                    }
                    filename = Path.Combine(_resourcePath, filename);

                    // load the resource set and add it into the resource table
                    resource = new ResourceSet(new PlainTextResourceReader(filename));

                    // Note (arnec): We call GetString to force the lazy loading of the resource stream, thereby making
                    // GetString(), at least theoretically, thread-safe for subsequent calls.
                    resource.GetString("", true);
                    ResourceData.Add(resourceKey, resource);
                }
            }
            return resource;
        }
Esempio n. 35
0
        public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary <string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists)
        {
            Debug.Assert(culture != null, "culture shouldn't be null; check caller");
            Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");

            ResourceSet rs        = null;
            Stream      stream    = null;
            Assembly    satellite = null;

            // 1. Fixups for ultimate fallbacks
            CultureInfo lookForCulture = UltimateFallbackFixup(culture);

            // 2. Look for satellite assembly or main assembly, as appropriate
            if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
            {
                // don't bother looking in satellites in this case
                satellite = _mediator.MainAssembly;
            }
            else
            {
                satellite = GetSatelliteAssembly(lookForCulture);

                if (satellite == null)
                {
                    bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
                    // didn't find satellite, give error if necessary
                    if (raiseException)
                    {
                        HandleSatelliteMissing();
                    }
                }
            }

            // get resource file name we'll search for. Note, be careful if you're moving this statement
            // around because lookForCulture may be modified from originally requested culture above.
            string fileName = _mediator.GetResourceFileName(lookForCulture);

            // 3. If we identified an assembly to search; look in manifest resource stream for resource file
            if (satellite != null)
            {
                // Handle case in here where someone added a callback for assembly load events.
                // While no other threads have called into GetResourceSet, our own thread can!
                // At that point, we could already have an RS in our hash table, and we don't
                // want to add it twice.
                lock (localResourceSets)
                {
                    localResourceSets.TryGetValue(culture.Name, out rs);
                }

                stream = GetManifestResourceStream(satellite, fileName);
            }

            // 4a. Found a stream; create a ResourceSet if possible
            if (createIfNotExists && stream != null && rs == null)
            {
                rs = CreateResourceSet(stream, satellite);
            }
            else if (stream == null && tryParents)
            {
                // 4b. Didn't find stream; give error if necessary
                bool raiseException = culture.HasInvariantCultureName;
                if (raiseException)
                {
                    HandleResourceStreamMissing(fileName);
                }
            }

            return(rs);
        }
        [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
        public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary <String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
        {
            Contract.Assert(culture != null, "culture shouldn't be null; check caller");
            Contract.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");

            ResourceSet     rs        = null;
            Stream          stream    = null;
            RuntimeAssembly satellite = null;

            // 1. Fixups for ultimate fallbacks
            CultureInfo lookForCulture = UltimateFallbackFixup(culture);

            // 2. Look for satellite assembly or main assembly, as appropriate
            if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
            {
                // don't bother looking in satellites in this case
                satellite = _mediator.MainAssembly;
            }
#if RESOURCE_SATELLITE_CONFIG
            // If our config file says the satellite isn't here, don't ask for it.
            else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture))
            {
                satellite = null;
            }
#endif
            else
            {
                satellite = GetSatelliteAssembly(lookForCulture, ref stackMark);

                if (satellite == null)
                {
                    bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
                    // didn't find satellite, give error if necessary
                    if (raiseException)
                    {
                        HandleSatelliteMissing();
                    }
                }
            }

            // get resource file name we'll search for. Note, be careful if you're moving this statement
            // around because lookForCulture may be modified from originally requested culture above.
            String fileName = _mediator.GetResourceFileName(lookForCulture);

            // 3. If we identified an assembly to search; look in manifest resource stream for resource file
            if (satellite != null)
            {
                // Handle case in here where someone added a callback for assembly load events.
                // While no other threads have called into GetResourceSet, our own thread can!
                // At that point, we could already have an RS in our hash table, and we don't
                // want to add it twice.
                lock (localResourceSets)
                {
                    if (localResourceSets.TryGetValue(culture.Name, out rs))
                    {
#if !FEATURE_CORECLR && !MONO
                        if (FrameworkEventSource.IsInitialized)
                        {
                            FrameworkEventSource.Log.ResourceManagerFoundResourceSetInCacheUnexpected(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
                        }
#endif
                    }
                }

                stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
            }

#if !FEATURE_CORECLR && !MONO
            if (FrameworkEventSource.IsInitialized)
            {
                if (stream != null)
                {
                    FrameworkEventSource.Log.ResourceManagerStreamFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
                }
                else
                {
                    FrameworkEventSource.Log.ResourceManagerStreamNotFound(_mediator.BaseName, _mediator.MainAssembly, culture.Name, satellite, fileName);
                }
            }
#endif

            // 4a. Found a stream; create a ResourceSet if possible
            if (createIfNotExists && stream != null && rs == null)
            {
#if !FEATURE_CORECLR && !MONO
                if (FrameworkEventSource.IsInitialized)
                {
                    FrameworkEventSource.Log.ResourceManagerCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name, fileName);
                }
#endif
                rs = CreateResourceSet(stream, satellite);
            }
            else if (stream == null && tryParents)
            {
                // 4b. Didn't find stream; give error if necessary
                bool raiseException = culture.HasInvariantCultureName;
                if (raiseException)
                {
                    HandleResourceStreamMissing(fileName);
                }
            }

#if !FEATURE_CORECLR && !MONO
            if (!createIfNotExists && stream != null && rs == null)
            {
                if (FrameworkEventSource.IsInitialized)
                {
                    FrameworkEventSource.Log.ResourceManagerNotCreatingResourceSet(_mediator.BaseName, _mediator.MainAssembly, culture.Name);
                }
            }
#endif

            return(rs);
        }
Esempio n. 37
0
        /// <summary>Provides the implementation for finding a <see cref="T:System.Resources.ResourceSet" />.</summary>
        /// <returns>The specified <see cref="T:System.Resources.ResourceSet" />.</returns>
        /// <param name="culture">The <see cref="T:System.Globalization.CultureInfo" /> to look for. </param>
        /// <param name="createIfNotExists">If true and if the <see cref="T:System.Resources.ResourceSet" /> has not been loaded yet, load it. </param>
        /// <param name="tryParents">If the <see cref="T:System.Resources.ResourceSet" /> cannot be loaded, try parent <see cref="T:System.Globalization.CultureInfo" /> objects to see if they exist. </param>
        /// <exception cref="T:System.Resources.MissingManifestResourceException">The main assembly does not contain a .resources file and it is required to look up a resource. </exception>
        /// <exception cref="T:System.ExecutionEngineException">There was an internal error in the runtime.</exception>
        /// <exception cref="T:System.Resources.MissingSatelliteAssemblyException">The satellite assembly associated with <paramref name="culture" /> could not be located.</exception>
        protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            if (culture == null)
            {
                throw new ArgumentNullException("key");
            }
            ResourceSet resourceSet = (ResourceSet)this.ResourceSets[culture];

            if (resourceSet != null)
            {
                return(resourceSet);
            }
            if (ResourceManager.NonExistent.Contains(culture))
            {
                return(null);
            }
            if (this.MainAssembly != null)
            {
                CultureInfo cultureInfo = culture;
                if (culture.Equals(this.neutral_culture))
                {
                    cultureInfo = CultureInfo.InvariantCulture;
                }
                Stream stream           = null;
                string resourceFileName = this.GetResourceFileName(cultureInfo);
                if (!cultureInfo.Equals(CultureInfo.InvariantCulture))
                {
                    Version satelliteContractVersion = ResourceManager.GetSatelliteContractVersion(this.MainAssembly);
                    try
                    {
                        Assembly satelliteAssemblyNoThrow = this.MainAssembly.GetSatelliteAssemblyNoThrow(cultureInfo, satelliteContractVersion);
                        if (satelliteAssemblyNoThrow != null)
                        {
                            stream = satelliteAssemblyNoThrow.GetManifestResourceStream(resourceFileName);
                            if (stream == null)
                            {
                                stream = this.GetManifestResourceStreamNoCase(satelliteAssemblyNoThrow, resourceFileName);
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    stream = this.MainAssembly.GetManifestResourceStream(this.resourceSource, resourceFileName);
                    if (stream == null)
                    {
                        stream = this.GetManifestResourceStreamNoCase(this.MainAssembly, resourceFileName);
                    }
                }
                if (stream != null && createIfNotExists)
                {
                    object[] args = new object[]
                    {
                        stream
                    };
                    resourceSet = (ResourceSet)Activator.CreateInstance(this.resourceSetType, args);
                }
                else if (cultureInfo.Equals(CultureInfo.InvariantCulture))
                {
                    throw this.AssemblyResourceMissing(resourceFileName);
                }
            }
            else if (this.resourceDir != null || this.BaseNameField != null)
            {
                string resourceFilePath = this.GetResourceFilePath(culture);
                if (createIfNotExists && File.Exists(resourceFilePath))
                {
                    object[] args2 = new object[]
                    {
                        resourceFilePath
                    };
                    resourceSet = (ResourceSet)Activator.CreateInstance(this.resourceSetType, args2);
                }
                else if (culture.Equals(CultureInfo.InvariantCulture))
                {
                    string message = string.Format("Could not find any resources appropriate for the specified culture (or the neutral culture) on disk.{0}baseName: {1}  locationInfo: {2}  fileName: {3}", new object[]
                    {
                        Environment.NewLine,
                        this.BaseNameField,
                        "<null>",
                        this.GetResourceFileName(culture)
                    });
                    throw new MissingManifestResourceException(message);
                }
            }
            if (resourceSet == null && tryParents && !culture.Equals(CultureInfo.InvariantCulture))
            {
                resourceSet = this.InternalGetResourceSet(culture.Parent, createIfNotExists, tryParents);
            }
            if (resourceSet != null)
            {
                this.ResourceSets[culture] = resourceSet;
            }
            else
            {
                ResourceManager.NonExistent[culture] = culture;
            }
            return(resourceSet);
        }
Esempio n. 38
0
        protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            if (culture == null)
            {
                throw new ArgumentNullException("key");                  // 'key' instead of 'culture' to make a test pass
            }
            ResourceSet set = null;

            /* if we already have this resource set, return it */
            set = (ResourceSet)ResourceSets [culture];
            if (set != null)
            {
                try {
                    if (!set.IsDisposed)
                    {
                        return(set);
                    }
                } catch {
                    // ignore
                }

                ResourceSets.Remove(culture);
                if (NonExistent.Contains(culture))
                {
                    NonExistent.Remove(culture);
                }
                set = null;
            }

            if (NonExistent.Contains(culture))
            {
                return(null);
            }

            if (MainAssembly != null)
            {
                /* Assembly resources */
                CultureInfo resourceCulture = culture;

                // when the specified culture matches the neutral culture,
                // then use the invariant resources
                if (culture.Equals(neutral_culture))
                {
                    resourceCulture = CultureInfo.InvariantCulture;
                }

                Stream stream = null;

                string filename = GetResourceFileName(resourceCulture);
                if (!resourceCulture.Equals(CultureInfo.InvariantCulture))
                {
                    /* Try a satellite assembly */
                    Version sat_version = GetSatelliteContractVersion(MainAssembly);
                    try {
                        Assembly a = MainAssembly.GetSatelliteAssemblyNoThrow(
                            resourceCulture, sat_version);
                        if (a != null)
                        {
                            stream = a.GetManifestResourceStream(filename);
                            if (stream == null)
                            {
                                stream = GetManifestResourceStreamNoCase(a, filename);
                            }
                        }
                    } catch (Exception) {
                        // Ignored
                    }
                }
                else
                {
                    stream = MainAssembly.GetManifestResourceStream(
                        resourceSource, filename);
                    if (stream == null)
                    {
                        stream = GetManifestResourceStreamNoCase(
                            MainAssembly, filename);
                    }
                }

                if (stream != null && createIfNotExists)
                {
                    object [] args = new Object [1] {
                        stream
                    };

                    /* should we catch
                     * MissingMethodException, or
                     * just let someone else deal
                     * with it?
                     */
                    set = (ResourceSet)Activator.CreateInstance(resourceSetType, args);
                }
                else if (resourceCulture.Equals(CultureInfo.InvariantCulture))
                {
                    throw AssemblyResourceMissing(filename);
                }
            }
            else if (resourceDir != null || BaseNameField != null)
            {
                /* File resources */
                string filename = GetResourceFilePath(culture);
                if (createIfNotExists && File.Exists(filename))
                {
                    object [] args = new Object [1] {
                        filename
                    };

                    /* should we catch
                     * MissingMethodException, or
                     * just let someone else deal
                     * with it?
                     */
                    set = (ResourceSet)Activator.CreateInstance(
                        resourceSetType, args);
                }
                else if (culture.Equals(CultureInfo.InvariantCulture))
                {
                    string msg = string.Format("Could not find any " +
                                               "resources appropriate for the specified culture " +
                                               "(or the neutral culture) on disk.{0}" +
                                               "baseName: {1}  locationInfo: {2}  fileName: {3}",
                                               Environment.NewLine, BaseNameField, "<null>",
                                               GetResourceFileName(culture));
                    throw new MissingManifestResourceException(msg);
                }
            }

            if (set == null && tryParents)
            {
                // avoid endless recursion
                if (!culture.Equals(CultureInfo.InvariantCulture))
                {
                    set = InternalGetResourceSet(culture.Parent,
                                                 createIfNotExists, tryParents);
                }
            }

            if (set != null)
            {
                ResourceSets [culture] = set;
            }
            else
            {
                NonExistent [culture] = culture;
            }

            return(set);
        }
 /// <summary>
 /// Register object definitions contained in a
 /// <see cref="System.Resources.ResourceSet"/>.
 /// </summary>
 /// <remarks>
 /// <p>
 /// Similar syntax as for an <see cref="System.Collections.IDictionary"/>.
 /// This method is useful to enable standard .NET internationalization support.
 /// </p>
 /// </remarks>
 /// <param name="rs">
 /// The <see cref="System.Resources.ResourceSet"/> containing object definitions.
 /// </param>
 /// <param name="prefix">
 /// The match or filter for object definition names, e.g. 'objects.'
 /// </param>
 /// <exception cref="Spring.Objects.ObjectsException">
 /// In case of loading or parsing errors.
 /// </exception>
 /// <returns>The number of object definitions registered.</returns>
 public int RegisterObjectDefinitions(ResourceSet rs, string prefix)
 {
     // Simply create a map and call overloaded method
     IDictionary id = new Hashtable();
     foreach (DictionaryEntry de in rs)
     {
         id.Add(de.Key, de.Value);
     }
     return RegisterObjectDefinitions(id, prefix);
 }
        public string CreateClassFromResourceSet(ResourceSet resourceSet, string nameSpace, string classname, string fileName)
        {
            IsVb = IsFileVb(fileName);

            StringBuilder sbClass = new StringBuilder();

            CreateClassHeader(classname, nameSpace, IsVb, sbClass);

            string indent = "\t\t";

            // Any resource set that contains a '.' is considered a Local Resource
            bool IsGlobalResource = !classname.Contains(".");

            // We'll enumerate through the Recordset to get all the resources
            IDictionaryEnumerator Enumerator = resourceSet.GetEnumerator();

            // We have to turn into a concrete Dictionary            
            while (Enumerator.MoveNext())
            {
                DictionaryEntry item = (DictionaryEntry)Enumerator.Current;
                if (item.Value == null)
                    item.Value = string.Empty;

                string typeName = item.Value.GetType().FullName;
                string key = item.Key as string;
                if (string.IsNullOrEmpty(key))
                    continue;

                string varName = SafeVarName(key);

                // It's a string
                if (!IsVb)
                {
                    sbClass.Append(indent + "public static " + typeName + " " + varName + "\r\n" + indent + "{\r\n");
                    sbClass.AppendFormat(indent + "\tget\r\n" +
                                         indent + "\t{{\r\n" +
                                         indent +
                                         (string.IsNullOrEmpty(typeName) || typeName == "System.String"
                                         ? "\t\t" + @"return GeneratedResourceHelper.GetResourceString(""{0}"",""{1}"",ResourceManager,GeneratedResourceSettings.ResourceAccessMode);" + "\r\n"
                                         : "\t\t" + @"return ({2}) GeneratedResourceHelper.GetResourceObject(""{0}"",""{1}"",ResourceManager,GeneratedResourceSettings.ResourceAccessMode);" + "\r\n")
                                         +
                                         indent + "\t}}\r\n",
                                         classname, key, typeName);
                    sbClass.Append(indent + "}\r\n\r\n");
                }
                else
                {
                    sbClass.Append(indent + "Public Shared Property " + varName + "() as " + typeName + "\r\n");
                    sbClass.AppendFormat(indent + "\tGet\r\n" + indent + "\t\treturn CType( HttpContext.GetGlobalResourceObject(\"{0}\",\"{1}\"), {2})\r\n",
                                         classname, key, typeName);
                    sbClass.Append(indent + "\tEnd Get\r\n");
                    sbClass.Append(indent + "End Property\r\n\r\n");
                }
            }

            if (!IsVb)
                sbClass.Append("\t}\r\n\r\n");
            else
                sbClass.Append("End Class\r\n\r\n");

            string Output = CreateNameSpaceWrapper(nameSpace, IsVb, sbClass.ToString());

            if (!string.IsNullOrEmpty(fileName))
            {
                File.WriteAllText(fileName, Output);
                return Output;
            }

            return sbClass.ToString();
        }
		object GetResource(CallExpression callExpression)
		{
			IResourceReader reader = componentCreator.GetResourceReader(CultureInfo.InvariantCulture);
			if (reader != null) {
				using (ResourceSet resources = new ResourceSet(reader)) {
					List<object> args = deserializer.GetArguments(callExpression);
					return resources.GetObject(args[0] as String);
				}
			}
			return null;
		}
Esempio n. 42
0
        // Looks up a resource value for a particular name.  Looks in the
        // specified CultureInfo, and if not found, all parent CultureInfos.
        // Returns null if the resource wasn't found.
        //
        public virtual string GetString(string name, CultureInfo culture)
        {
            if (null == name)
            {
                throw new ArgumentNullException(nameof(name));
            }

#if FEATURE_APPX || ENABLE_WINRT
            if (UseUapResourceManagement)
            {
                // Throws WinRT hresults.
                return(GetStringFromPRI(name, culture, _neutralResourcesCulture.Name));
            }
#endif

            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }

            ResourceSet last = GetFirstResourceSet(culture);

            if (last != null)
            {
                string value = last.GetString(name, _ignoreCase);
                if (value != null)
                {
                    return(value);
                }
            }

            // This is the CultureInfo hierarchy traversal code for resource
            // lookups, similar but necessarily orthogonal to the ResourceSet
            // lookup logic.
            ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
            foreach (CultureInfo currentCultureInfo in mgr)
            {
                ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true);
                if (rs == null)
                {
                    break;
                }

                if (rs != last)
                {
                    string value = rs.GetString(name, _ignoreCase);
                    if (value != null)
                    {
                        // update last used ResourceSet
                        if (_lastUsedResourceCache != null)
                        {
                            lock (_lastUsedResourceCache)
                            {
                                _lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
                                _lastUsedResourceCache.lastResourceSet = rs;
                            }
                        }
                        return(value);
                    }

                    last = rs;
                }
            }

            return(null);
        }
Esempio n. 43
0
        // Constructs a new ResourceSet for a given file name.
        // Use the assembly to resolve assembly manifest resource references.
        // Note that is can be null, but probably shouldn't be.
        // This method could use some refactoring. One thing at a time.
        internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
        {
            Debug.Assert(store != null, "I need a Stream!");
            // Check to see if this is a Stream the ResourceManager understands,
            // and check for the correct resource reader type.
            if (store.CanSeek && store.Length > 4)
            {
                long startPos = store.Position;

                // not disposing because we want to leave stream open
                BinaryReader br = new BinaryReader(store);

                // Look for our magic number as a little endian int.
                int bytes = br.ReadInt32();
                if (bytes == ResourceManager.MagicNumber)
                {
                    int    resMgrHeaderVersion = br.ReadInt32();
                    string readerTypeName = null, resSetTypeName = null;
                    if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
                    {
                        br.ReadInt32();  // We don't want the number of bytes to skip.
                        readerTypeName = br.ReadString();
                        resSetTypeName = br.ReadString();
                    }
                    else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
                    {
                        // Assume that the future ResourceManager headers will
                        // have two strings for us - the reader type name and
                        // resource set type name.  Read those, then use the num
                        // bytes to skip field to correct our position.
                        int  numBytesToSkip = br.ReadInt32();
                        long endPosition    = br.BaseStream.Position + numBytesToSkip;

                        readerTypeName = br.ReadString();
                        resSetTypeName = br.ReadString();

                        br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
                    }
                    else
                    {
                        // resMgrHeaderVersion is older than this ResMgr version.
                        // We should add in backwards compatibility support here.

                        throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name));
                    }

                    store.Position = startPos;
                    // Perf optimization - Don't use Reflection for our defaults.
                    // Note there are two different sets of strings here - the
                    // assembly qualified strings emitted by ResourceWriter, and
                    // the abbreviated ones emitted by InternalResGen.
                    if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
                    {
                        return(new RuntimeResourceSet(store, permitDeserialization: true));
                    }
                    else
                    {
                        Type     readerType = Type.GetType(readerTypeName, throwOnError: true);
                        object[] args       = new object[1];
                        args[0] = store;
                        IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);

                        object[] resourceSetArgs = new object[1];
                        resourceSetArgs[0] = reader;

                        Type resSetType;
                        if (_mediator.UserResourceSet == null)
                        {
                            Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
                            resSetType = Type.GetType(resSetTypeName, true, false);
                        }
                        else
                        {
                            resSetType = _mediator.UserResourceSet;
                        }
                        ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
                                                                               BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
                                                                               null,
                                                                               resourceSetArgs,
                                                                               null,
                                                                               null);
                        return(rs);
                    }
                }
                else
                {
                    store.Position = startPos;
                }
            }

            if (_mediator.UserResourceSet == null)
            {
                return(new RuntimeResourceSet(store, permitDeserialization: true));
            }
            else
            {
                object[] args = new object[2];
                args[0] = store;
                args[1] = assembly;
                try
                {
                    ResourceSet rs = null;
                    // Add in a check for a constructor taking in an assembly first.
                    try
                    {
                        rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
                        return(rs);
                    }
                    catch (MissingMethodException) { }

                    args    = new object[1];
                    args[0] = store;
                    rs      = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);

                    return(rs);
                }
                catch (MissingMethodException e)
                {
                    throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
                }
            }
        }
 /// <summary>
 /// Register object definitions contained in a
 /// <see cref="System.Resources.ResourceSet"/>, using all property keys (i.e.
 /// not filtering by prefix).
 /// </summary>
 /// <param name="rs">
 /// The <see cref="System.Resources.ResourceSet"/> containing object definitions.
 /// </param>
 /// <exception cref="Spring.Objects.ObjectsException">
 /// In case of loading or parsing errors.
 /// </exception>
 /// <returns>The number of object definitions registered.</returns>
 public int RegisterObjectDefinitions(ResourceSet rs)
 {
     return RegisterObjectDefinitions(rs, string.Empty);
 }
Esempio n. 45
0
        // InternalGetResourceSet is a non-threadsafe method where all the logic
        // for getting a resource set lives.  Access to it is controlled by
        // threadsafe methods such as GetResourceSet, GetString, & GetObject.
        // This will take a minimal number of locks.
        protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
        {
            Debug.Assert(culture != null, "culture != null");

            Dictionary <string, ResourceSet> localResourceSets = _resourceSets;
            ResourceSet rs           = null;
            CultureInfo foundCulture = null;

            lock (localResourceSets)
            {
                if (localResourceSets.TryGetValue(culture.Name, out rs))
                {
                    return(rs);
                }
            }

            ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, tryParents);

            foreach (CultureInfo currentCultureInfo in mgr)
            {
                lock (localResourceSets)
                {
                    if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs))
                    {
                        // we need to update the cache if we fellback
                        if (culture != currentCultureInfo)
                        {
                            foundCulture = currentCultureInfo;
                        }
                        break;
                    }
                }

                // InternalGetResourceSet will never be threadsafe.  However, it must
                // be protected against reentrancy from the SAME THREAD.  (ie, calling
                // GetSatelliteAssembly may send some window messages or trigger the
                // Assembly load event, which could fail then call back into the
                // ResourceManager).  It's happened.

                rs = resourceGroveler.GrovelForResourceSet(currentCultureInfo, localResourceSets,
                                                           tryParents, createIfNotExists);

                // found a ResourceSet; we're done
                if (rs != null)
                {
                    foundCulture = currentCultureInfo;
                    break;
                }
            }

            if (rs != null && foundCulture != null)
            {
                // add entries to the cache for the cultures we have gone through

                // currentCultureInfo now refers to the culture that had resources.
                // update cultures starting from requested culture up to the culture
                // that had resources.
                foreach (CultureInfo updateCultureInfo in mgr)
                {
                    AddResourceSet(localResourceSets, updateCultureInfo.Name, ref rs);

                    // stop when we've added current or reached invariant (top of chain)
                    if (updateCultureInfo == foundCulture)
                    {
                        break;
                    }
                }
            }

            return(rs);
        }