Beispiel #1
0
        public void Write(TzdbDatabase database, WindowsZones cldrWindowsZones)
        {
            var timeZoneMap = new Dictionary <string, string>();

            foreach (var zone in database.GenerateDateTimeZones())
            {
                timeZoneMap.Add(zone.Id, zone.Id);
                WriteTimeZone(zone);
            }

            // Normalize the aliases
            foreach (var key in database.Aliases.Keys)
            {
                var value = database.Aliases[key];
                while (database.Aliases.ContainsKey(value))
                {
                    value = database.Aliases[value];
                }
                timeZoneMap.Add(key, value);
            }
            resourceWriter.AddResource(TzdbResourceData.VersionKey, database.Version);
            WriteDictionary(TzdbResourceData.IdMapKey, timeZoneMap);
            WriteDictionary(TzdbResourceData.WindowsToPosixMapKey, cldrWindowsZones.PrimaryMapping);
            resourceWriter.AddResource(TzdbResourceData.WindowsToPosixMapVersionKey, cldrWindowsZones.Version);
            resourceWriter.Close();
        }
        /// <summary>
        /// Embeds a single resource into the assembly.
        /// </summary>
        void AddResource(ModuleBuilder moduleBuilder, ResourceFile resourceFile)
        {
            string          fileName       = resourceFile.FileName;
            IResourceWriter resourceWriter = moduleBuilder.DefineResource(Path.GetFileName(fileName), resourceFile.Name, ResourceAttributes.Public);
            string          extension      = Path.GetExtension(fileName).ToLowerInvariant();

            if (extension == ".resources")
            {
                ResourceReader resourceReader = new ResourceReader(fileName);
                using (resourceReader) {
                    IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();
                    while (enumerator.MoveNext())
                    {
                        string key            = enumerator.Key as string;
                        Stream resourceStream = enumerator.Value as Stream;
                        if (resourceStream != null)
                        {
                            BinaryReader reader = new BinaryReader(resourceStream);
                            MemoryStream stream = new MemoryStream();
                            byte[]       bytes  = reader.ReadBytes((int)resourceStream.Length);
                            stream.Write(bytes, 0, bytes.Length);
                            resourceWriter.AddResource(key, stream);
                        }
                        else
                        {
                            resourceWriter.AddResource(key, enumerator.Value);
                        }
                    }
                }
            }
            else
            {
                resourceWriter.AddResource(resourceFile.Name, File.ReadAllBytes(fileName));
            }
        }
    public CodeGenerator()
    {
        // Get the current application domain for the current thread.
        AppDomain currentDomain = AppDomain.CurrentDomain;

        AssemblyName myAssemblyName = new AssemblyName();

        myAssemblyName.Name = "TempAssembly";

        // Define 'TempAssembly' assembly in the current application domain.
        AssemblyBuilder myAssemblyBuilder =
            currentDomain.DefineDynamicAssembly
                (myAssemblyName, AssemblyBuilderAccess.RunAndSave);
        // Define 'TempModule' module in 'TempAssembly' assembly.
        ModuleBuilder myModuleBuilder =
            myAssemblyBuilder.DefineDynamicModule("TempModule",
                                                  "TempModule.netmodule", true);
        // Define the managed embedded resource, 'MyResource' in 'TempModule'.
        IResourceWriter myResourceWriter =
            myModuleBuilder.DefineResource("MyResource.resource", "Description");

        // Add resources to the resource writer.
        myResourceWriter.AddResource("String 1", "First String");
        myResourceWriter.AddResource("String 2", "Second String");
        myResourceWriter.AddResource("String 3", "Third String");
        myAssemblyBuilder.Save("MyAssembly.dll");
    }
Beispiel #4
0
        void AddResources(IResourceWriter resourceWriter, string fileName)
        {
            ResourceReader resourceReader = new ResourceReader(fileName);

            using (resourceReader) {
                IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    string key            = enumerator.Key as string;
                    Stream resourceStream = enumerator.Value as Stream;
                    if (resourceStream != null)
                    {
                        BinaryReader reader = new BinaryReader(resourceStream);
                        MemoryStream stream = new MemoryStream();
                        byte[]       bytes  = reader.ReadBytes((int)resourceStream.Length);
                        stream.Write(bytes, 0, bytes.Length);
                        resourceWriter.AddResource(key, stream);
                    }
                    else
                    {
                        resourceWriter.AddResource(key, enumerator.Value);
                    }
                }
            }
        }
 private static void WriteResourceFile(IResourceWriter resources, Dictionary <string, Image> images)
 {
     foreach (var kvp in images)
     {
         resources.AddResource(kvp.Key, kvp.Value);
     }
 }
Beispiel #6
0
 /// <summary>
 /// Save changes done to the resource content to disk.
 /// </summary>
 /// <param name="writer">The <see cref="IResourceWriter" /> to be used to save the resource content.</param>
 protected virtual void SaveContent(IResourceWriter writer)
 {
     foreach (KeyValuePair <string, object> entry in this.data)
     {
         writer.AddResource(entry.Key, entry.Value);
     }
 }
Beispiel #7
0
        public static void AddResource(this IResourceWriter writer, IResource resource)
        {
            var value = resource.Value;

            if (value is string text)
            {
                writer.AddResource(resource.Name, text);
            }
            else if (value is byte [] data)
            {
                writer.AddResource(resource.Name, data);
            }
            else
            {
                writer.AddResource(resource.Name, value);
            }
        }
Beispiel #8
0
        public void Save(IResourceWriter writer)
        {
            writer.AddResource("CULTURE" + SEPARATOR, Culture.Name);
            foreach (var entry in _translations)
            {
                writer.AddResource("VALUE" + SEPARATOR + entry.Key, entry.Value);
            }

            foreach (var entry in _arrayTranslations)
            {
                writer.AddResource("LIST" + SEPARATOR + entry.Key, MakeList(entry.Value));
            }

            // Switch from field;usage -> patterns
            // to usage;pattern* -> [fields]
            var byPattern = new Dictionary <string, List <string> >();

            foreach (var entry in _templateTranslations)
            {
                var           names = entry.Key.SplitList().ToArray();
                var           field = names[0];
                var           usage = names[1];
                var           key   = MakeList(AddPrefix(usage, entry.Value));
                List <string> fields;
                if (byPattern.TryGetValue(key, out fields))
                {
                    fields.Add(field);
                }
                else
                {
                    byPattern.Add(key, new List <string> {
                        field
                    });
                }
            }

            // Write out TEMPLATE;usage;field* -> pattern*
            foreach (var entry in byPattern)
            {
                var elements = entry.Key.SplitList().ToArray();
                var usage    = elements[0];
                var patterns = elements.Skip(1);
                var key      = "TEMPLATE" + SEPARATOR + usage + SEPARATOR + MakeList(entry.Value);
                writer.AddResource(key, MakeList(patterns));
            }
        }
        // Creates a default resource file for the current
        // CultureInfo and adds 3 strings to it.
        private void CreateResources(object sender, EventArgs e)
        {
            IResourceService rs = (IResourceService)this.Component.Site.GetService(typeof(IResourceService));

            if (rs == null)
            {
                throw new Exception("Could not obtain IResourceService.");
            }

            IResourceWriter rw = rs.GetResourceWriter(CultureInfo.CurrentUICulture);

            rw.AddResource("string1", "Persisted resource string #1");
            rw.AddResource("string2", "Persisted resource string #2");
            rw.AddResource("string3", "Persisted resource string #3");
            rw.Generate();
            rw.Close();
        }
Beispiel #10
0
		public void Save(IResourceWriter resources)
		{
			foreach (var info in _images.Values)
				resources.AddResource(info.FullName, info.Image);
			foreach (var folder in _folders)
				folder.Save(resources);

			IsChanged = false;
		}
        public override void VisitEmbeddedResource(EmbeddedResource res)
        {
            // TODO: Description?
            IResourceWriter resourceWriter = module.Builder.DefineResource(res.Name, "",
                                                                           (System.Reflection.ResourceAttributes)res.Flags);

            resourceWriter.AddResource(res.Name, res.Data);
            resourceWriter.Generate();
        }
Beispiel #12
0
 public void Build()
 {
     foreach (var i in _resourceEntries)
     {
         _resourceWriter.AddResource(i.Key, i.Value);
     }
     _resourceWriter.Generate();
     _resourceWriter.Close();
 }
Beispiel #13
0
        static void ProcessFile(FileInfo name, IResourceWriter writer, String prefix)
        {
            Properties properties = new Properties();

            properties.load(name.OpenRead());

            foreach (String key in properties.Keys)
            {
                writer.AddResource(prefix + key, properties.getProperty(key));
            }
        }
Beispiel #14
0
        protected override void OnGenerate(IResourceWriter resourceWrite, XElement element)
        {
            string id    = element.AttibuteStringValue("Id");
            string value = element.AttibuteStringValue("Value");

            if (string.IsNullOrEmpty(id))
            {
                return;
            }
            resourceWrite.AddResource(id, value);
        }
Beispiel #15
0
 // closes writer automatically
 private static void WriteResources(IResourceWriter writer)
 {
     foreach (Entry entry in resources)
     {
         string key   = entry.name;
         object value = entry.value;
         writer.AddResource(key, value);
     }
     Console.Write(SR.GetString(SR.BeginWriting));
     writer.Close();
     Console.WriteLine(SR.GetString(SR.DoneDot));
 }
Beispiel #16
0
 public void WriteResource(IResourceService service)
 {
     using (ResourceReader reader = new ResourceReader(this.FileName))
     {
         IResourceWriter       writer = service.DefineResource(this.Name, this.Description);
         IDictionaryEnumerator e      = reader.GetEnumerator();
         while (e.MoveNext())
         {
             writer.AddResource((string)e.Key, e.Value);
         }
     }
 }
Beispiel #17
0
        /// <summary>Enbdeds resource into assembly</summary>
        /// <param name="builder"><see cref="ModuleBuilder"/> to embede resource in</param>
        /// <param name="name">Name of the resource</param>
        /// <param name="path">File to obtain resource from</param>
        /// <param name="attributes">Defines resource visibility</param>

        //DefineResource
        // Exceptions:
        //   System.ArgumentException:
        //     name has been previously defined or if there is another file in the assembly
        //     named fileName.-or- The length of name is zero.-or- The length of fileName
        //     is zero.-or- fileName includes a path.
        //
        //   System.ArgumentNullException:
        //     name or fileName is null.
        //
        //   System.Security.SecurityException:
        //     The caller does not have the required permission.

        //ResourceReader
        // Exceptions:
        //   System.ArgumentException:
        //     The stream is not readable.
        //
        //   System.ArgumentNullException:
        //     The stream parameter is null.
        //
        //   System.IO.IOException:
        //     An I/O error has occurred while accessing stream.

        //AddResource
        // Exceptions:
        //   System.ArgumentNullException:
        //     The name parameter is null.

        //ReadAllBytes
        // Exceptions:
        //   System.ArgumentException:
        //     path is a zero-length string, contains only white space, or contains one
        //     or more invalid characters as defined by System.IO.Path.InvalidPathChars.
        //
        //   System.ArgumentNullException:
        //     path is null.
        //
        //   System.IO.PathTooLongException:
        //     The specified path, file name, or both exceed the system-defined maximum
        //     length. For example, on Windows-based platforms, paths must be less than
        //     248 characters, and file names must be less than 260 characters.
        //
        //   System.IO.DirectoryNotFoundException:
        //     The specified path is invalid (for example, it is on an unmapped drive).
        //
        //   System.IO.IOException:
        //     An I/O error occurred while opening the file.
        //
        //   System.UnauthorizedAccessException:
        //     path specified a file that is read-only.-or- This operation is not supported
        //     on the current platform.-or- path specified a directory.-or- The caller does
        //     not have the required permission.
        //
        //   System.IO.FileNotFoundException:
        //     The file specified in path was not found.
        //
        //   System.NotSupportedException:
        //     path is in an invalid format.
        //
        //   System.Security.SecurityException:
        //     The caller does not have the required permission.
        private void AddResourceFile(ModuleBuilder builder, string name, FullPath path, ResourceAttributes attributes)
        {
            IResourceWriter rw  = builder.DefineResource(path.FileName, name, attributes);
            string          ext = path.Extension.ToLower();

            if (ext == ".resources")
            {
                ResourceReader rr = new ResourceReader(path);
                using (rr) {
                    System.Collections.IDictionaryEnumerator de = rr.GetEnumerator();
                    while (de.MoveNext())
                    {
                        string key = de.Key as string;
                        rw.AddResource(key, de.Value);
                    }
                }
            }
            else
            {
                rw.AddResource(name, File.ReadAllBytes(path));
            }
        }
        public void Save(IResourceWriter resources)
        {
            foreach (var info in _images.Values)
            {
                resources.AddResource(info.FullName, info.Image);
            }
            foreach (var folder in _folders)
            {
                folder.Save(resources);
            }

            IsChanged = false;
        }
Beispiel #19
0
        public void AddResourceFile(string name, string file, ResourceAttributes attribute)
        {
            IResourceWriter rw = _myModule.DefineResource(Path.GetFileName(file), name, attribute);

            string ext = Path.GetExtension(file);

            if (String.Equals(ext, ".resources", StringComparison.OrdinalIgnoreCase))
            {
                ResourceReader rr = new ResourceReader(file);
                using (rr) {
                    System.Collections.IDictionaryEnumerator de = rr.GetEnumerator();

                    while (de.MoveNext())
                    {
                        string key = de.Key as string;
                        rw.AddResource(key, de.Value);
                    }
                }
            }
            else
            {
                rw.AddResource(name, File.ReadAllBytes(file));
            }
        }
// <Snippet2>
// <Snippet3>
    internal static void Main()
    {
        AssemblyBuilder myAssembly = CreateAssembly("MyEmitTestAssembly");

        // Defines a standalone managed resource for this assembly.
        IResourceWriter myResourceWriter = myAssembly.DefineResource("myResourceFile",
                                                                     "A sample Resource File", "MyAssemblyResource.resources",
                                                                     ResourceAttributes.Private);

        myResourceWriter.AddResource("AddResource Test", "Testing for the added resource");

        myAssembly.Save(myAssembly.GetName().Name + ".dll");

        // Defines an unmanaged resource file for this assembly.
        myAssembly.DefineUnmanagedResource("MyAssemblyResource.resources");
    }
 private void WriteResources(IResourceWriter writer)
 {
     try
     {
         foreach (Entry entry in this.resources)
         {
             string name = entry.name;
             object obj2 = entry.value;
             writer.AddResource(name, obj2);
         }
     }
     finally
     {
         writer.Close();
     }
 }
 private void OnSerializationComplete(object sender, EventArgs e)
 {
     if (this.writer != null)
     {
         this.writer.Close();
         this.writer = null;
     }
     if (this.invariantCultureResourcesDirty || this.metadataResourcesDirty)
     {
         IResourceService service = (IResourceService)this.manager.GetService(typeof(IResourceService));
         if (service != null)
         {
             IResourceWriter resourceWriter = service.GetResourceWriter(CultureInfo.InvariantCulture);
             try
             {
                 object obj2 = this.ResourceTable[CultureInfo.InvariantCulture];
                 IDictionaryEnumerator enumerator = ((Hashtable)obj2).GetEnumerator();
                 while (enumerator.MoveNext())
                 {
                     string key  = (string)enumerator.Key;
                     object obj3 = enumerator.Value;
                     resourceWriter.AddResource(key, obj3);
                 }
                 this.invariantCultureResourcesDirty = false;
                 ResXResourceWriter writer2 = resourceWriter as ResXResourceWriter;
                 if (writer2 != null)
                 {
                     foreach (DictionaryEntry entry in this.metadata)
                     {
                         writer2.AddMetadata((string)entry.Key, entry.Value);
                     }
                 }
                 this.metadataResourcesDirty = false;
                 return;
             }
             finally
             {
                 resourceWriter.Close();
             }
         }
         this.invariantCultureResourcesDirty = false;
         this.metadataResourcesDirty         = false;
     }
 }
Beispiel #23
0
    static int CompileResourceFile(string sname, string dname, bool useSourcePath)
    {
        FileStream      source = null;
        FileStream      dest   = null;
        IResourceReader reader = null;
        IResourceWriter writer = null;

        try {
            source = new FileStream(sname, FileMode.Open, FileAccess.Read);
            reader = GetReader(source, sname, useSourcePath);

            dest   = new FileStream(dname, FileMode.Create, FileAccess.Write);
            writer = GetWriter(dest, dname);

            int rescount = 0;
            foreach (DictionaryEntry e in reader)
            {
                rescount++;
                object val = e.Value;
                if (val is string)
                {
                    writer.AddResource((string)e.Key, (string)e.Value);
                }
                else
                {
                    writer.AddResource((string)e.Key, e.Value);
                }
            }
            Console.WriteLine("Read in {0} resources from '{1}'", rescount, sname);

            reader.Close();
            writer.Close();
            Console.WriteLine("Writing resource file...  Done.");
        } catch (Exception e) {
            Console.WriteLine("Error: {0}", e.Message);
            Exception inner = e.InnerException;

            // under 2.0 ResXResourceReader can wrap an exception into an XmlException
            // and this hides some helpful message from the original exception
            XmlException xex = (inner as XmlException);
            if (xex != null)
            {
                // message is identical to the inner exception (from MWF ResXResourceReader)
                Console.WriteLine("Position: Line {0}, Column {1}.", xex.LineNumber, xex.LinePosition);
                inner = inner.InnerException;
            }

            if (inner is System.Reflection.TargetInvocationException && inner.InnerException != null)
            {
                inner = inner.InnerException;
            }
            if (inner != null)
            {
                Console.WriteLine("Inner exception: {0}", inner.Message);
            }

            if (reader != null)
            {
                reader.Dispose();
            }
            if (source != null)
            {
                source.Close();
            }
            if (writer != null)
            {
                writer.Dispose();
            }
            if (dest != null)
            {
                dest.Close();
            }

            // since we're not first reading all entries in source, we may get a
            // read failure after we're started writing to the destination file
            // and leave behind a broken resources file, so remove it here
            try {
                File.Delete(dname);
            } catch {
            }
            return(1);
        }
        return(0);
    }
 public void AddToWriter(IResourceWriter writer)
 {
     writer.AddResource(Name, Value);
 }
Beispiel #25
0
 public void AddTo(IResourceWriter writer)
 {
     writer.AddResource(Name, Value);
 }
Beispiel #26
0
        static int CompileResourceFile(string sname, string dname, bool useSourcePath, Options options)
        {
            FileStream      source = null;
            FileStream      dest   = null;
            IResourceReader reader = null;
            IResourceWriter writer = null;

            try {
                source = new FileStream(sname, FileMode.Open, FileAccess.Read);
                reader = GetReader(source, sname, useSourcePath, options);

                dest   = new FileStream(dname, FileMode.Create, FileAccess.Write);
                writer = GetWriter(dest, dname, options, sname);

                int rescount = 0;
                foreach (DictionaryEntry e in reader)
                {
                    rescount++;
                    object val = e.Value;
                    if (val is string)
                    {
                        writer.AddResource((string)e.Key, (string)e.Value);
                    }
                    else
                    {
                        // refactoring to do: We should probably wrap the ResXResourceWriter, and replace our use of IResourceWriter with a ResourceItem based interface
                        ResourceItem item = val as ResourceItem;
                        try {
                            if (writer is ResXResourceWriter && item != null)
                            {
                                // only write if the ResourceItem can be cast to ResXDataNode
                                ResXDataNode dataNode = ((ResourceItem)val).ToResXDataNode();
                                if (dataNode != null)
                                {
                                    writer.AddResource((string)e.Key, dataNode);
                                }
                            }
                            else
                            {
                                writer.AddResource((string)e.Key, e.Value);
                            }
                        } catch {
                            if (item != null && item.Metadata_OriginalSourceLine > 0)
                            {
                                Console.WriteLine("Line: {0}", item.Metadata_OriginalSourceLine);
                            }
                            throw;
                        }
                    }
                }
                Console.WriteLine("Read in {0} resources from '{1}'", rescount, sname);

                reader.Close();
                writer.Close();
                Console.WriteLine("Writing resource file...  Done.");
            } catch (Exception e) {
                Console.WriteLine("Error: {0}", e.Message);
                Exception inner = e.InnerException;

                // under 2.0 ResXResourceReader can wrap an exception into an XmlException
                // and this hides some helpful message from the original exception
                XmlException xex = (inner as XmlException);
                if (xex != null)
                {
                    // message is identical to the inner exception (from MWF ResXResourceReader)
                    Console.WriteLine("Position: Line {0}, Column {1}.", xex.LineNumber, xex.LinePosition);
                    inner = inner.InnerException;
                }

                if (inner is TargetInvocationException && inner.InnerException != null)
                {
                    inner = inner.InnerException;
                }
                if (inner != null)
                {
                    Console.WriteLine("Inner exception: {0}", inner.Message);
                }

                if (reader != null)
                {
                    reader.Dispose();
                }
                if (source != null)
                {
                    source.Close();
                }
                if (writer != null)
                {
                    writer.Dispose();
                }
                if (dest != null)
                {
                    dest.Close();
                }

                // since we're not first reading all entries in source, we may get a
                // read failure after we're started writing to the destination file
                // and leave behind a broken resources file, so remove it here
                try {
                    File.Delete(dname);
                } catch {
                }
                return(1);
            }
            return(0);
        }
Beispiel #27
0
 public new void AddTo(IResourceWriter writer)
 {
     writer.AddResource(Name, (string)Value);
 }
        /// <summary>
        /// Write resources to an XML or binary format resources file.
        /// </summary>
        /// <remarks>Closes writer automatically</remarks>
        /// <param name="writer">Appropriate IResourceWriter</param>
        private void WriteResources(IResourceWriter writer)
        {
            try
            {
                foreach (Entry entry in resources)
                {
                    string key = entry.RawName;
                    object value = entry.Value;

                    if(writer is TinyResourceWriter)
                    {
                        ((TinyResourceWriter)writer).AddResource( entry );
                    }
                    else
                    {
                        writer.AddResource(key, value);
                    }
                }

                writer.Generate();
            }
            finally
            {
                writer.Close();
            }
        }
        private static void GenerateResourceStream(
            ResourceGenerationOptions options,              // options from the command line
            string resourceName,                            // the name of the .resources file
            IResourceReader reader,                         // the reader for the .resources
            IResourceWriter writer,                         // the writer for the output .resources
            TranslationDictionariesReader dictionaries      // the translations
            )
        {
            //options.WriteLine(StringLoader.Get("GenerateResource", resourceName));
            // enumerate through each resource and generate it
            foreach (DictionaryEntry entry in reader)
            {
                string name          = entry.Key as string;
                object resourceValue = null;

                // See if it looks like a Baml resource
                if (BamlStream.IsResourceEntryBamlStream(name, entry.Value))
                {
                    Stream targetStream = null;
                    //                    options.Write("    ");
                    //options.Write(StringLoader.Get("GenerateBaml", name));

                    // grab the localizations available for this Baml
                    string bamlName = BamlStream.CombineBamlStreamName(resourceName, name);
                    BamlLocalizationDictionary localizations = dictionaries[bamlName];
                    if (localizations != null)
                    {
                        targetStream = new MemoryStream();

                        // generate into a new Baml stream
                        GenerateBamlStream(
                            (Stream)entry.Value,
                            targetStream,
                            localizations,
                            options
                            );
                    }

                    options.WriteLine(StringLoader.Get("Done"));

                    // sets the generated object to be the generated baml stream
                    resourceValue = targetStream;
                }

                if (resourceValue == null)
                {
                    //
                    // The stream is not localized as Baml yet, so we will make a copy of this item into
                    // the localized resources
                    //

                    // We will add the value as is if it is serializable. Otherwise, make a copy
                    resourceValue = entry.Value;

                    object[] serializableAttributes = resourceValue.GetType().GetCustomAttributes(typeof(SerializableAttribute), true);
                    if (serializableAttributes.Length == 0)
                    {
                        // The item returned from resource reader is not serializable
                        // If it is Stream, we can wrap all the values in a MemoryStream and
                        // add to the resource. Otherwise, we had to skip this resource.
                        Stream resourceStream = resourceValue as Stream;
                        if (resourceStream != null)
                        {
                            Stream targetStream = new MemoryStream();
                            byte[] buffer       = new byte[resourceStream.Length];
                            resourceStream.Read(buffer, 0, buffer.Length);
                            targetStream  = new MemoryStream(buffer);
                            resourceValue = targetStream;
                        }
                    }
                }

                if (resourceValue != null)
                {
                    writer.AddResource(name, resourceValue);
                }
            }
        }
Beispiel #30
0
		void AddResources(IResourceWriter resourceWriter, string fileName)
		{
			ResourceReader resourceReader = new ResourceReader(fileName);
			using (resourceReader) {
				IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();
				while (enumerator.MoveNext()) {
					string key = enumerator.Key as string;
					Stream resourceStream = enumerator.Value as Stream;
					if (resourceStream != null) {
						BinaryReader reader = new BinaryReader(resourceStream);
						MemoryStream stream = new MemoryStream();						
						byte[] bytes = reader.ReadBytes((int)resourceStream.Length);
						stream.Write(bytes, 0, bytes.Length);
						resourceWriter.AddResource(key, stream);
					} else {
						resourceWriter.AddResource(key, enumerator.Value);
					}
				}
			}
		}
Beispiel #31
0
 /// <summary>
 /// Write resources to an XML or binary format resources file.
 /// </summary>
 /// <remarks>Closes writer automatically</remarks>
 /// <param name="writer">Appropriate IResourceWriter</param>
 private void WriteResources(ReaderInfo reader, IResourceWriter writer)
 {
     Exception capturedException = null;
     try
     {
         foreach (Entry entry in reader.resources)
         {
             string key = entry.name;
             object value = entry.value;
             writer.AddResource(key, value);
         }
     }
     catch (Exception e)
     {
         capturedException = e; // Rethrow this after catching exceptions thrown by Close().
     }
     finally
     {
         if (capturedException == null)
         {
             writer.Close(); // If this throws, exceptions will be caught upstream.
         }
         else
         {
             // It doesn't hurt to call Close() twice. In the event of a full disk, we *need* to call Close() twice.
             // In that case, the first time we catch an exception indicating that the XML written to disk is malformed,
             // specifically an InvalidOperationException: "Token EndElement in state Error would result in an invalid XML document."
             try { writer.Close(); }
             catch (Exception) { } // We agressively catch all exception types since we already have one we will throw.
             // The second time we catch the out of disk space exception.
             try { writer.Close(); }
             catch (Exception) { } // We agressively catch all exception types since we already have one we will throw.
             throw capturedException; // In the event of a full disk, this is an out of disk space IOException.
         }
     }
 }
        private static void GenerateResourceStream(
                LocBamlOptions options,                     // options from the command line
                string resourceName,                        // the name of the .resources file
                IResourceReader reader,                     // the reader for the .resources
                IResourceWriter writer,                     // the writer for the output .resources
                TranslationDictionariesReader dictionaries  // the translations
            )
        {
            options.WriteLine(StringLoader.Get("GenerateResource", resourceName));
            // enumerate through each resource and generate it
            foreach(DictionaryEntry entry in reader)
            {
                string name = entry.Key as string;
                object resourceValue = null;

                // See if it looks like a Baml resource
                if (BamlStream.IsResourceEntryBamlStream(name, entry.Value))
                {
            Stream targetStream = null;
                    options.Write("    ");
                    options.Write(StringLoader.Get("GenerateBaml", name));

                    // grab the localizations available for this Baml
                    string bamlName = BamlStream.CombineBamlStreamName(resourceName, name);
                    BamlLocalizationDictionary localizations = dictionaries[bamlName];
                    if (localizations != null)
                    {
                        targetStream = new MemoryStream();

                        // generate into a new Baml stream
                        GenerateBamlStream(
                            (Stream) entry.Value,
                            targetStream,
                            localizations,
                            options
                        );
                    }
                    options.WriteLine(StringLoader.Get("Done"));

            // sets the generated object to be the generated baml stream
            resourceValue = targetStream;
                }

            if (resourceValue == null)
                {
                    //
                    // The stream is not localized as Baml yet, so we will make a copy of this item into
                    // the localized resources
                    //

            // We will add the value as is if it is serializable. Otherwise, make a copy
            resourceValue = entry.Value;

                    object[] serializableAttributes = resourceValue.GetType().GetCustomAttributes(typeof(SerializableAttribute), true);
                    if (serializableAttributes.Length == 0)
                    {
                        // The item returned from resource reader is not serializable
                        // If it is Stream, we can wrap all the values in a MemoryStream and
                        // add to the resource. Otherwise, we had to skip this resource.
            Stream resourceStream = resourceValue as Stream;
                        if (resourceStream != null)
                        {
                Stream targetStream = new MemoryStream();
                            byte[] buffer = new byte[resourceStream.Length];
                            resourceStream.Read(buffer, 0, buffer.Length);
                            targetStream = new MemoryStream(buffer);
                resourceValue = targetStream;
                        }
                    }
                }

            if (resourceValue != null)
                {
            writer.AddResource(name, resourceValue);
                }
            }
        }
 // closes writer automatically
 private static void WriteResources(IResourceWriter writer) {
     foreach (Entry entry in resources) {
         string key = entry.name;
         object value = entry.value;
         writer.AddResource(key, value);
     }
     Console.Write(SR.GetString(SR.BeginWriting));
     writer.Close();
     Console.WriteLine(SR.GetString(SR.DoneDot));
 }
Beispiel #34
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage();
            }
            string path         = null;
            string locale       = null;
            string assemblyPath = null;
            string methodPath   = null;

            for (var i = 0; i < args.Length; ++i)
            {
                var arg = args[i];
                if (arg.StartsWith("-"))
                {
                    switch (arg)
                    {
                    case "-c":
                        if (++i < args.Length)
                        {
                            locale = args[i];
                        }
                        break;

                    case "-g":
                        if (++i < args.Length)
                        {
                            assemblyPath = Path.GetFullPath(args[i]);
                        }
                        if (++i < args.Length)
                        {
                            methodPath = args[i];
                        }
                        break;

                    default:
                        Usage();
                        break;
                    }
                }
                else
                {
                    path = arg;
                }
            }

            if (assemblyPath != null)
            {
                var assembly    = Assembly.LoadFrom(assemblyPath);
                var methodParts = methodPath.Split('.');
                var methodName  = methodParts.Last();
                var className   = string.Join(".", methodParts.Take(methodParts.Count() - 1));
                var classType   = assembly.GetType(className);
                var method      = classType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy);
                var methodArgs  = new object[method.GetParameters().Length];
                var form        = method.Invoke(null, methodArgs);
                var formPath    = className + ".resx";
                using (var stream = new FileStream(formPath, FileMode.Create))
                    using (var writer = new ResXResourceWriter(stream))
                    {
                        form.GetType().InvokeMember("SaveResources",
                                                    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy,
                                                    null, form, new object[] { writer });
                    }
                Console.WriteLine($"Generated {formPath} by calling {methodPath} in {assemblyPath}.");
            }
            else
            {
                var             isResX    = Path.GetExtension(path) == ".resx";
                IResourceWriter writer    = null;
                FileStream      outStream = null;
                if (locale != null)
                {
                    var outPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "-" + locale + Path.GetExtension(path));
                    Console.Write($"Copying to {outPath}");
                    Console.WriteLine();
                    outStream = new FileStream(outPath, FileMode.Create);
                    writer    = isResX ? (IResourceWriter) new ResXResourceWriter(outStream) : (IResourceWriter) new ResourceWriter(outStream);
                }
                using (var stream = new FileStream(path, FileMode.Open))
                    using (var reader = isResX ? (IResourceReader) new ResXResourceReader(stream) : (IResourceReader) new ResourceReader(stream))
                        using (outStream)
                            using (writer)
                            {
                                int values    = 0;
                                int lists     = 0;
                                int templates = 0;
                                foreach (DictionaryEntry entry in reader)
                                {
                                    var fullKey    = (string)entry.Key;
                                    var value      = (string)entry.Value;
                                    var typeAndKey = fullKey.Split(SEPERATOR);
                                    var type       = typeAndKey.Last();
                                    if (writer == null)
                                    {
                                        Console.WriteLine($"{fullKey}: {value}");
                                    }
                                    else
                                    {
                                        if (type == "LIST" || type == "TEMPLATE")
                                        {
                                            writer.AddResource(fullKey, MakeList(from elt in SplitList(value) select "<" + elt + ">"));
                                        }
                                        else
                                        {
                                            writer.AddResource(fullKey, "<" + value + ">");
                                        }
                                    }
                                    switch (type)
                                    {
                                    case "VALUE": ++values; break;

                                    case "LIST": ++lists; break;

                                    case "TEMPLATE": ++templates; break;
                                    }
                                }
                                Console.WriteLine($"Found {values} values, {lists} lists and {templates} templates");
                            }
            }
        }
 private void WriteResources(IResourceWriter writer)
 {
     try
     {
         foreach (Entry entry in this.resources)
         {
             string name = entry.name;
             object obj2 = entry.value;
             writer.AddResource(name, obj2);
         }
     }
     finally
     {
         writer.Close();
     }
 }
Beispiel #36
0
 public void WriteImage(string aName, Image aImage)
 {
     writer.AddResource(aName, aImage);
 }
		/// <summary>
		/// Save changes done to the resource content to disk.
		/// </summary>
		/// <param name="writer">The <see cref="IResourceWriter" /> to be used to save the resource content.</param>
		protected virtual void SaveContent(IResourceWriter writer)
		{
			foreach (KeyValuePair<string, object> entry in this.data) {
				writer.AddResource(entry.Key, entry.Value);
			}
		}
Beispiel #38
0
        public void Save(IResourceWriter writer)
        {
            foreach (var entry in _translations)
            {
                writer.AddResource(entry.Key + SEPARATOR + "VALUE", entry.Value);
            }

            foreach (var entry in _arrayTranslations)
            {
                writer.AddResource(entry.Key + SEPARATOR + "LIST", MakeList(entry.Value));
            }

            // Switch from field;usage -> patterns
            // to usage;pattern* -> [fields]
            var byPattern = new Dictionary<string, List<string>>();
            foreach (var entry in _templateTranslations)
            {
                var names = entry.Key.SplitList().ToArray();
                var field = names[0];
                var usage = names[1];
                var key = MakeList(AddPrefix(usage, entry.Value));
                List<string> fields;
                if (byPattern.TryGetValue(key, out fields))
                {
                    fields.Add(field);
                }
                else
                {
                    byPattern.Add(key, new List<string> { field });
                }
            }

            // Write out TEMPLATE;usage;field* -> pattern*
            foreach (var entry in byPattern)
            {
                var elements = entry.Key.SplitList().ToArray();
                var usage = elements[0];
                var patterns = elements.Skip(1);
                var key = usage + SEPARATOR + MakeList(entry.Value) + SEPARATOR + "TEMPLATE";
                writer.AddResource(key, MakeList(patterns));
            }
        }
Beispiel #39
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage();
            }
            var    path   = args[0];
            var    isResX = Path.GetExtension(path) == ".resx";
            string locale = null;
            string prefix = null;

            for (var i = 1; i < args.Length; ++i)
            {
                var arg = args[i];
                switch (arg)
                {
                case "-c":
                    if (++i < args.Length)
                    {
                        locale = args[i];
                    }
                    break;

                case "-p":
                    if (++i < args.Length)
                    {
                        prefix = args[i];
                    }
                    break;

                default:
                    Usage();
                    break;
                }
            }

            IResourceWriter writer    = null;
            FileStream      outStream = null;

            if (locale != null)
            {
                var outPath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "-" + locale + Path.GetExtension(path));
                Console.Write($"Copying to {outPath}");
                if (prefix != null)
                {
                    Console.Write($" with prefix {prefix}");
                }
                Console.WriteLine();
                outStream = new FileStream(outPath, FileMode.Create);
                writer    = isResX ? (IResourceWriter) new ResXResourceWriter(outStream) : (IResourceWriter) new ResourceWriter(outStream);
            }
            using (var stream = new FileStream(path, FileMode.Open))
                using (var reader = isResX ? (IResourceReader) new ResXResourceReader(stream) : (IResourceReader) new ResourceReader(stream))
                    using (outStream)
                        using (writer)
                        {
                            int values    = 0;
                            int lists     = 0;
                            int templates = 0;
                            foreach (DictionaryEntry entry in reader)
                            {
                                var fullKey    = (string)entry.Key;
                                var value      = (string)entry.Value;
                                var typeAndKey = fullKey.Split(SEPERATOR);
                                var type       = typeAndKey[0];
                                if (writer == null)
                                {
                                    Console.WriteLine($"{fullKey}: {value}");
                                }
                                else
                                {
                                    if (type == "LIST" || type == "TEMPLATE")
                                    {
                                        writer.AddResource(fullKey, MakeList(from elt in SplitList(value) select prefix + elt));
                                    }
                                    else if (type == "CULTURE")
                                    {
                                        writer.AddResource("CULTURE" + SSEPERATOR, locale);
                                    }
                                    else
                                    {
                                        writer.AddResource(fullKey, prefix + value);
                                    }
                                }
                                switch (type)
                                {
                                case "VALUE": ++values; break;

                                case "LIST": ++lists; break;

                                case "TEMPLATE": ++templates; break;
                                }
                            }
                            Console.WriteLine($"Found {values} values, {lists} lists and {templates} templates");
                        }
        }