コード例 #1
0
        public static void EnumResourceItems(string resxFile, bool useDataNodes)
        {
            using (ResXResourceReader reader = new ResXResourceReader(resxFile))
            {
                reader.UseResXDataNodes = useDataNodes;

                // Enumerate using IEnumerable.GetEnumerator().
                Console.WriteLine("\n  Default enumerator:");
                foreach (DictionaryEntry entry in reader)
                {
                    ShowResourceItem(entry, useDataNodes);
                }

                // Enumerate using GetMetadataEnumerator()
                IDictionaryEnumerator metadataEnumerator = reader.GetMetadataEnumerator();

                Console.WriteLine("\n  MetadataEnumerator:");
                while (metadataEnumerator.MoveNext())
                {
                    ShowResourceItem(metadataEnumerator.Entry, useDataNodes);
                }

                // Enumerate using GetEnumerator()
                IDictionaryEnumerator enumerator = reader.GetEnumerator();

                Console.WriteLine("\n  Enumerator:");
                while (enumerator.MoveNext())
                {
                    ShowResourceItem(enumerator.Entry, useDataNodes);
                }
            }
        }
コード例 #2
0
 private Hashtable GetMetadata()
 {
     if (this.metadata == null)
     {
         IResourceService service = (IResourceService)this.manager.GetService(typeof(IResourceService));
         if (service != null)
         {
             IResourceReader resourceReader = service.GetResourceReader(CultureInfo.InvariantCulture);
             if (resourceReader != null)
             {
                 try
                 {
                     ResXResourceReader reader2 = resourceReader as ResXResourceReader;
                     if (reader2 != null)
                     {
                         this.metadata = new Hashtable();
                         IDictionaryEnumerator metadataEnumerator = reader2.GetMetadataEnumerator();
                         while (metadataEnumerator.MoveNext())
                         {
                             this.metadata[metadataEnumerator.Key] = metadataEnumerator.Value;
                         }
                     }
                 }
                 finally
                 {
                     resourceReader.Close();
                 }
             }
         }
     }
     return(this.metadata);
 }
コード例 #3
0
        public void LoadFile(FileName filename, Stream stream)
        {
            resources.Clear();
            metadata.Clear();
            switch (Path.GetExtension(filename).ToLowerInvariant())
            {
            case ".resx":
                ResXResourceReader     rx           = new ResXResourceReader(stream);
                ITypeResolutionService typeResolver = null;
                rx.BasePath         = Path.GetDirectoryName(filename);
                rx.UseResXDataNodes = true;
                IDictionaryEnumerator n = rx.GetEnumerator();
                while (n.MoveNext())
                {
                    if (!resources.ContainsKey(n.Key.ToString()))
                    {
                        ResXDataNode node = (ResXDataNode)n.Value;
                        resources.Add(n.Key.ToString(), new ResourceItem(node.Name, node.GetValue(typeResolver), node.Comment));
                    }
                }

                n = rx.GetMetadataEnumerator();
                while (n.MoveNext())
                {
                    if (!metadata.ContainsKey(n.Key.ToString()))
                    {
                        ResXDataNode node = (ResXDataNode)n.Value;
                        metadata.Add(n.Key.ToString(), new ResourceItem(node.Name, node.GetValue(typeResolver)));
                    }
                }

                rx.Close();
                break;

            case ".resources":
                ResourceReader rr = null;
                try {
                    rr = new ResourceReader(stream);
                    foreach (DictionaryEntry entry in rr)
                    {
                        if (!resources.ContainsKey(entry.Key.ToString()))
                        {
                            resources.Add(entry.Key.ToString(), new ResourceItem(entry.Key.ToString(), entry.Value));
                        }
                    }
                }
                finally {
                    if (rr != null)
                    {
                        rr.Close();
                    }
                }
                break;
            }
            InitializeListView();
        }
コード例 #4
0
 void ReadResourceFile(string resourceFile)
 {
     try {
         using (var resxReader = new ResXResourceReader(resourceFile)) {
             resxReader.UseResXDataNodes = true;
             var resxEnumerator = resxReader.GetMetadataEnumerator();
             while (resxEnumerator.MoveNext())
             {
                 var resxNode = (ResXDataNode)resxEnumerator.Entry.Value;
             }
         }
     }
     catch (Exception ex) {
         throw new Exception($"Resource File Not Valid: {resourceFile}", ex);
     }
 }
コード例 #5
0
        internal static ResXData FromFile(FilePath path)
        {
            List <ResXNode> nodes, metadata;

            using (var reader = new ResXResourceReader(path)
            {
                UseResXDataNodes = true,
            }) {
                nodes    = reader.Cast <DictionaryEntry>().Select(x => (ResXNode)(ResXDataNode)x.Value).ToList();
                metadata = new List <ResXNode>();

                var enumerator = reader.GetMetadataEnumerator();
                while (enumerator.MoveNext())
                {
                    metadata.Add((ResXNode)(ResXDataNode)enumerator.Value);
                }
            }

            return(new ResXData(path)
            {
                Nodes = nodes,
                Metadata = metadata,
            });
        }
コード例 #6
0
        /// <summary>
        ///     Save one resource file
        /// </summary>
        private void UpdateFile(string filename, string valueColumnId, bool skipNontranslatableData, bool saveComments)
        {
            // Read the entire resource file to a buffer
            var originalMetadatas = new Dictionary <string, object>();
            var originalResources = new Dictionary <string, ResXDataNode>();

            var fileExists = filename != null && File.Exists(filename);

            if (fileExists)
            {
                using (var reader = new ResXResourceReader(filename,
                                                           AppDomain.CurrentDomain.GetAssemblies().Select(x => x.GetName()).ToArray()))
                {
                    // Set base path so that relative paths work
                    reader.BasePath = Path.GetDirectoryName(filename);

                    // If UseResXDataNodes == true before you call GetMetadataEnumerator, no resource nodes are retrieved
                    var metadataEnumerator = reader.GetMetadataEnumerator();
                    while (metadataEnumerator.MoveNext())
                    {
                        originalMetadatas.Add((string)metadataEnumerator.Key, metadataEnumerator.Value);
                    }
                }

                using (var reader = new ResXResourceReader(filename))
                {
                    // If GetMetadataEnumerator was already called setting the UseResXDataNodes to true will have no effect
                    // Because of this creating a new reader is necessary
                    reader.UseResXDataNodes = true;
                    var dataEnumerator = reader.GetEnumerator();
                    while (dataEnumerator.MoveNext())
                    {
                        var key = (string)dataEnumerator.Key;
                        // GetEnumerator will also get metadata items, filter them out
                        if (!originalMetadatas.ContainsKey(key))
                        {
                            originalResources.Add(key, (ResXDataNode)dataEnumerator.Value);
                        }
                    }
                }

                // Get rid of keys marked as deleted. If they have been restored they will be re-added later
                // Only support localizable strings to avoid removing other resources by mistake
                // BUG Clear the _deletedKeys?
                foreach (var originalResource in originalResources
                         .Where(originalResource => _deletedKeys.Contains(originalResource.Key))
                         .Where(originalResource => IsLocalizableString(originalResource.Key, originalResource.Value))
                         .ToList())
                {
                    originalResources.Remove(originalResource.Key);
                }
            }

            // Precache the valid keys
            var localizableResourceKeys = originalResources
                                          .Where(originalResource => IsLocalizableString(originalResource.Key, originalResource.Value))
                                          .Select(x => x.Key).ToList();

            // Update originalResources with information stored in _stringsTable.
            // Adds keys if they are missing in originalResources
            foreach (DataRow dataRow in _stringsTable.Rows)
            {
                var key = (string)dataRow[Properties.Resources.ColNameKey];

                var valueData       = dataRow[valueColumnId] == DBNull.Value ? null : dataRow[valueColumnId];
                var stringValueData = valueData?.ToString() ?? string.Empty;

                var stringCommentData = saveComments ? TryGetCommentFromRow(dataRow) : string.Empty;

                if (localizableResourceKeys.Contains(key))
                {
                    // Skip if the original value and comment is the same as the new one
                    if (stringCommentData.Equals(originalResources[key].Comment, StringComparison.InvariantCulture) &&
                        stringValueData.Equals(originalResources[key].GetValueAsString(), StringComparison.InvariantCulture))
                    {
                        continue;
                    }

                    originalResources[key] = new ResXDataNode(originalResources[key].Name, stringValueData)
                    {
                        Comment = stringCommentData
                    };
                }
                else
                {
                    originalResources.Add(key, new ResXDataNode(key, stringValueData)
                    {
                        Comment = stringCommentData
                    });
                    localizableResourceKeys.Add(key);
                }
            }

            // Write the cached resources to the drive
            using (var writer = new ResXResourceWriter(filename))
            {
                foreach (var originalResource in originalResources)
                {
                    // Write localizable resource only if it is not empty, unless we are saving the default file
                    if (valueColumnId.Equals(Properties.Resources.ColNameNoLang) ||
                        !localizableResourceKeys.Contains(originalResource.Key) ||
                        !string.IsNullOrWhiteSpace(originalResource.Value.GetValueAsString()))
                    {
                        if (!skipNontranslatableData || IsLocalizableString(originalResource.Key, originalResource.Value))
                        {
                            writer.AddResource(originalResource.Value);
                        }
                    }
                }
                foreach (var originalMetadata in originalMetadatas)
                {
                    writer.AddMetadata(originalMetadata.Key, originalMetadata.Value);
                }

                writer.Generate();
            }
        }
コード例 #7
0
        public void TestEnumerators()
        {
            string             path   = Path.Combine(Files.GetExecutingPath(), "Resources\\TestRes.resx");
            ResXResourceReader reader = new ResXResourceReader(path);

            // reading one element, then reset, read first element again
            var resEnumLazy = reader.GetEnumerator();

            resEnumLazy.MoveNext();
            var firstRes = resEnumLazy.Entry;

            resEnumLazy.Reset();
            resEnumLazy.MoveNext();
            Assert.AreEqual(firstRes, resEnumLazy.Entry);

            // getting enumerator again: cached
            var resEnumCached = reader.GetEnumerator();

            Assert.AreNotEqual(resEnumLazy.GetType(), resEnumCached.GetType());
            resEnumCached.MoveNext();
            Assert.AreEqual(firstRes, resEnumCached.Entry);

            // the lazy cached the rest of the elements into a buffer so they both see the second element now
            resEnumLazy.MoveNext();
            resEnumCached.MoveNext();
            Assert.AreEqual(resEnumLazy.Entry, resEnumCached.Entry);

            // getting the metadata returns a cached enumerator now
            var metaEnumCached = reader.GetMetadataEnumerator();

            Assert.AreEqual(resEnumCached.GetType(), metaEnumCached.GetType());

            // as well as alias
            var aliasEnumCached = reader.GetAliasEnumerator();

            Assert.AreEqual(resEnumCached.GetType(), aliasEnumCached.GetType());
            reader.Close();

            // alias enumerators are handled in a special way so they are tested separately
            // reader is recreated to get a lazy enumerator again
            reader = new ResXResourceReader(path);
            var aliasEnumLazy = reader.GetAliasEnumerator();

            aliasEnumLazy.MoveNext();
            var firstAlias = aliasEnumLazy.Entry;

            aliasEnumLazy.Reset();
            aliasEnumLazy.MoveNext();
            Assert.AreEqual(firstAlias, aliasEnumLazy.Entry);

            // getting enumerator again: cached
            aliasEnumCached = reader.GetAliasEnumerator();
            Assert.AreNotEqual(aliasEnumLazy.GetType(), aliasEnumCached.GetType());
            aliasEnumCached.MoveNext();
            Assert.AreEqual(firstAlias, aliasEnumCached.Entry);

            // the lazy cached the rest of the elements into a buffer so they both see the second element now
            aliasEnumLazy.MoveNext();
            aliasEnumCached.MoveNext();
            Assert.AreEqual(aliasEnumLazy.Entry, aliasEnumCached.Entry);

            // normal vs safe mode
            resEnumCached = reader.GetEnumerator();
            resEnumCached.MoveNext();
            Assert.IsNotInstanceOf <ResXDataNode>(resEnumCached.Value);
            reader.SafeMode = true;
            Assert.IsInstanceOf <ResXDataNode>(resEnumCached.Value);

            // however, aliases are always strings
            Assert.IsInstanceOf <string>(aliasEnumCached.Value);
            Assert.IsInstanceOf <string>(aliasEnumLazy.Value);
            reader.SafeMode = false;
            Assert.IsInstanceOf <string>(aliasEnumCached.Value);
            Assert.IsInstanceOf <string>(aliasEnumLazy.Value);

            reader.Close();
        }