예제 #1
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);
                    }
                }
            }
        }
예제 #2
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);
     }
 }
예제 #3
0
        /// <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");
    }
        public void WriteToStream(Stream stream)
        {
            IResourceWriter writer = null;

            if (_file.FilePath.Extension == ".resx")
            {
                writer = new ResXResourceWriter(stream);
            }
            else if (_file.FilePath.Extension == ".resources")
            {
                writer = new ResourceWriter(stream);
            }
            else
            {
                throw new NotSupportedException();
            }

            foreach (var item in resourcesListView.Items.Cast <EditorListViewItem>())
            {
                item.ResourceEntry.AddToWriter(writer);
            }

            writer.Generate();

            // no closing/disposing needed. caller will close stream.
        }
예제 #6
0
 private static void WriteResourceFile(IResourceWriter resources, Dictionary <string, Image> images)
 {
     foreach (var kvp in images)
     {
         resources.AddResource(kvp.Key, kvp.Value);
     }
 }
예제 #7
0
파일: respack.cs 프로젝트: ya1gaurav/moon
    public static int Pack(List <string> files)
    {
        IResourceWriter output = null;

        try {
            if (files [0].EndsWith(".resx"))
            {
                output = new ResXResourceWriter(files [0]);
            }
            else
            {
                output = new ResourceWriter(files [0]);
            }
        } catch {
            Console.WriteLine("Error creating {0} file", files [0]);
        }


        int i = 1;

        while (i < files.Count)
        {
            string f = files [i++];
            string key;
            string file = f;

            if (f.StartsWith("@"))
            {
                files.AddRange(System.IO.File.ReadAllLines(f.Substring(1)));
                continue;
            }

            int comma = file.IndexOf(',');
            if (comma != -1)
            {
                key  = file.Substring(comma + 1);
                file = file.Substring(0, comma);
            }
            else
            {
                key = Path.GetFileName(file);
            }


            using (FileStream source = File.OpenRead(file)){
                byte [] buffer = new byte [source.Length];
                source.Read(buffer, 0, (int)source.Length);

                // Sadly, we cant just pass byte arrays to resourcewriter, we need
                // to wrap this on a MemoryStream

                MemoryStream value = new MemoryStream(buffer);

                output.AddResource(Uri.EscapeUriString(key).ToLowerInvariant(), value);
            }
        }

        output.Generate();
        return(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 override void SaveContent(IResourceWriter writer)
		{
			base.SaveContent(writer);
			ResXResourceWriter w = (ResXResourceWriter)writer;
			foreach (KeyValuePair<string, object> entry in this.metadata) {
				w.AddMetadata(entry.Key, entry.Value);
			}
		}
예제 #9
0
파일: ImagesFolder.cs 프로젝트: rsdn/janus
		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();
        }
예제 #11
0
 /// <summary>
 /// Save changes done to the resource content to disk.
 /// </summary>
 protected virtual void SaveContent()
 {
     using (IResourceWriter writer = this.GetResourceWriter()) {
         if (writer != null)
         {
             this.SaveContent(writer);
             writer.Close();
         }
     }
 }
        // ********************************************************************************************************************************

        /// <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 override void SaveContent(IResourceWriter writer)
        {
            base.SaveContent(writer);
            ResXResourceWriter w = (ResXResourceWriter)writer;

            foreach (KeyValuePair <string, object> entry in this.metadata)
            {
                w.AddMetadata(entry.Key, entry.Value);
            }
        }
예제 #13
0
 public void AddTo(IResourceWriter writer)
 {
     if (writer is PreserializedResourceWriter preserializedResourceWriter)
     {
         preserializedResourceWriter.AddTypeConverterResource(Name, Bytes, TypeName);
     }
     else
     {
         ErrorUtilities.ThrowInternalError($"{nameof(TypeConverterByteArrayResource)} was asked to serialize to a {writer.GetType().ToString()}");
     }
 }
예제 #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);
        }
 public void Dispose()
 {
     if (this.stream != null)
     {
         this.writer.Dispose();
         this.stream.Dispose();
         this.writer = null;
         this.stream = null;
     }
     this.buffer = null;
 }
예제 #16
0
 public void AddTo(IResourceWriter writer)
 {
     if (writer is PreserializedResourceWriter preserializedResourceWriter)
     {
         preserializedResourceWriter.AddTypeConverterResource(Name, Bytes, TypeAssemblyQualifiedName);
     }
     else
     {
         throw new PreserializedResourceWriterRequiredException();
     }
 }
 public void AddTo(IResourceWriter writer)
 {
     if (writer is PreserializedResourceWriter preserializedResourceWriter)
     {
         preserializedResourceWriter.AddBinaryFormattedResource(Name, Bytes);
     }
     else
     {
         throw new PreserializedResourceWriterRequiredException();
     }
 }
 public void AddTo(IResourceWriter writer)
 {
     if (writer is PreserializedResourceWriter preserializedResourceWriter)
     {
         preserializedResourceWriter.AddResource(Name, StringRepresentation, TypeAssemblyQualifiedName);
     }
     else
     {
         throw new PreserializedResourceWriterRequiredException();
     }
 }
예제 #19
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));
            }
        }
예제 #20
0
        static void ProcessDirectory(DirectoryInfo dir, IResourceWriter writer, String localeName, String prefix)
        {
            foreach (FileInfo name in dir.GetFiles("*_" + localeName + ".properties"))
            {
                ProcessFile(name, writer, prefix + name.Name.Split(new char[] { '_' })[0] + ".");
            }

            foreach (DirectoryInfo name in dir.GetDirectories())
            {
                ProcessDirectory(name, writer, localeName, prefix + name + ".");
            }
        }
예제 #21
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);
         }
     }
 }
예제 #22
0
 public override void SaveResources(IResourceWriter writer)
 {
     _resources = new Localizer()
     {
         Culture = CultureInfo.CurrentUICulture
     };
     foreach (var step in _steps)
     {
         step.SaveResources();
     }
     _resources.Save(writer);
 }
 /// <summary>
 /// Writes the byte array containing the most recent version of the resource
 /// represented by this instance into the private field "buffer", if a
 /// resource writer has previously been requested for this resource.
 /// </summary>
 public void WriteResourcesToBuffer()
 {
     if (this.stream != null)
     {
         this.writer.Close();
         this.writer.Dispose();
         this.buffer = this.stream.ToArray();
         this.writer = null;
         this.stream.Dispose();
         this.stream = null;
     }
 }
예제 #24
0
파일: resgen.cs 프로젝트: ydunk/masters
 // 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));
 }
예제 #25
0
        public void AddTo(IResourceWriter writer)
        {
            if (writer is PreserializedResourceWriter preserializedResourceWriter)
            {
                FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);

                preserializedResourceWriter.AddActivatorResource(Name, fileStream, TypeName, closeAfterWrite: true);
            }
            else
            {
                throw new PreserializedResourceWriterRequiredException();
            }
        }
예제 #26
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;
        }
예제 #27
0
        public void AddTo(IResourceWriter writer)
        {
            if (writer is PreserializedResourceWriter preserializedResourceWriter)
            {
                FileStream fileStream = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);

                preserializedResourceWriter.AddActivatorResource(Name, fileStream, TypeName, closeAfterWrite: true);
            }
            else
            {
                ErrorUtilities.ThrowInternalError($"{nameof(FileStreamResource)} was asked to serialize to a {writer.GetType().ToString()}");
            }
        }
예제 #28
0
        public Resource(string name, IResourceReader reader, IResourceWriter writer)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Resource name is not set", nameof(name));
            }

            _name      = name;
            _reader    = reader ?? throw new ArgumentNullException(nameof(reader));
            _writer    = writer ?? throw new ArgumentNullException(nameof(writer));
            _formatter = new CompositeResourceFormatter(
                new JsonResourceFormatter(),
                new XmlResourceFormatter());
        }
예제 #29
0
 public void WriteResource(string aUriTail, uint aIpAddress, List<string> aLanguageList, IResourceWriter aWriter)
 {
     if (iUiDir == null)
     {
         // UI is disabled.
         return;
     }
     if (IsNodeJsPath(aUriTail))
     {
         WriteNodeJs(aWriter);
         return;
     }
     string tail = (aUriTail.Length == 0 ? "index.html" : aUriTail);
     string fullPath = Path.Combine(iUiDir, tail);
     if (Path.GetDirectoryName(fullPath).EndsWith(kResourcesDir))
     {
         string resDir = Path.Combine(iUiDir, kResourcesDir);
         string fileName = Path.GetFileName(aUriTail);
         foreach (string lang in aLanguageList)
         {
             string language = lang.ToLower();
             if (language.Contains('-'))
             {
                 if (TryWriteFile(resDir, language, fileName, aWriter))
                 {
                     return;
                 }
             }
             else
             {
                 string[] paths = Directory.GetDirectories(resDir);
                 foreach (string path in paths)
                 {
                     int index = path.LastIndexOf(Path.DirectorySeparatorChar);
                     string dir = path.Substring(index + 1);
                     if (dir.StartsWith(language))
                     {
                         if (TryWriteFile(resDir, dir, fileName, aWriter))
                         {
                             return;
                         }
                     }
                 }
             }
         }
     }
     TryWriteFile(fullPath, aWriter);
 }
예제 #30
0
        /// <summary>
        /// Constructeur.
        /// </summary>
        /// <param name="dataSourceName">Nom de la source de données.</param>
        /// <param name="resourceLoader">Service de chargement des ressources.</param>
        /// <param name="resourceWriter">Service d'écriture des ressources.</param>
        public ReferenceBroker(string dataSourceName, IResourceLoader resourceLoader, IResourceWriter resourceWriter)
            : base(dataSourceName)
        {
            if (resourceLoader == null)
            {
                throw new ArgumentNullException("resourceLoader");
            }

            if (resourceWriter == null)
            {
                throw new ArgumentNullException("resourceWriter");
            }

            _resourceLoader = resourceLoader;
            _resourceWriter = resourceWriter;
        }
예제 #31
0
        /// <summary>
        /// Embeds a single resource into the assembly.
        /// </summary>
        void AddResource(ModuleBuilder moduleBuilder, ResourceFile resourceFile)
        {
            string fileName  = resourceFile.FileName;
            string extension = Path.GetExtension(fileName).ToLowerInvariant();

            if (extension == ".resources")
            {
                string          fullFileName   = Path.GetFileName(fileName);
                IResourceWriter resourceWriter = moduleBuilder.DefineResource(fullFileName, resourceFile.Name, ResourceAttributes.Public);
                AddResources(resourceWriter, fileName);
            }
            else
            {
                moduleBuilder.DefineManifestResource(resourceFile.Name, new FileStream(fileName, FileMode.Open), ResourceAttributes.Public);
            }
        }
// <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();
     }
 }
예제 #34
0
 void WriteNodeJs(IResourceWriter aWriter)
 {
     MemoryStream memStream = new MemoryStream();
     StreamWriter writer = new StreamWriter(memStream);
     writer.Write("var nodeUdn = \"" + iUdn + "\";\n");
     writer.Write("var webSocketPort = " + iWebSocketPort + ";\n");
     writer.Write("var isRemote = false;\n");
     writer.Flush();
     aWriter.WriteResourceBegin((int)memStream.Length, "application/javascript");
     aWriter.WriteResource(memStream.GetBuffer(), (int)memStream.Length);
     aWriter.WriteResourceEnd();
     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;
     }
 }
예제 #36
0
 public ResourceBuilder(IResourceWriter resourceWriter)
 {
     _resourceWriter = resourceWriter;
 }
예제 #37
0
        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);
                }
            }
        }
예제 #38
0
			/// <summary>
			/// Returns a new resource writer for this resource.
			/// According to the SDK documentation of IResourceService.GetResourceWriter,
			/// a new writer needs to be returned every time one is requested, discarding any
			/// data written by previously returned writers.
			/// </summary>
			public IResourceWriter GetWriter()
			{
				this.stream = new MemoryStream();
				this.writer = CreateResourceWriter(this.stream, GetResourceType(OpenedFile.FileName));
				return this.writer;
			}
예제 #39
0
파일: App.cs 프로젝트: weeble/ohos
 public void WriteResource(string aUriTail, uint aIpAddress, List<string> aLanguageList, IResourceWriter aWriter)
 {
     iResourceManager.WriteResource(aUriTail, aIpAddress, aLanguageList, aWriter);
 }
예제 #40
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(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();
            }
        }
예제 #41
0
			public void Dispose()
			{
				if (this.stream != null) {
					this.writer.Dispose();
					this.stream.Dispose();
					this.writer = null;
					this.stream = null;
				}
				this.buffer = null;
			}
예제 #42
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="ResourceOutput" /> class.
 /// </summary>
 /// <param name="name">The output file name.</param>
 /// <param name="type">The resource type.</param>
 public ResourceOutput(string name, ResourceOutputType type)
 {
     OutputFileName = ChangeExtension(name, type);
     resourceWriter = GetResourceWriter(OutputFileName, type);
 }
			/// <summary>
			/// Returns a new resource writer for this resource.
			/// According to the SDK documentation of IResourceService.GetResourceWriter,
			/// a new writer needs to be returned every time one is requested, discarding any
			/// data written by previously returned writers.
			/// </summary>
			public IResourceWriter GetWriter()
			{
				this.stream = new MemoryStream();
				this.writer = CreateResourceWriter(this.stream);
				return this.writer;
			}
		/// <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);
			}
		}
예제 #45
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);
					}
				}
			}
		}
예제 #46
0
 public ResourceRegistryRenderer(RegisteredResources resources, IResourceWriter resourceWriter, Func<string,string> urlResolver)
 {
     _resources = resources;
     _resourceWriter = resourceWriter;
     _urlResolver = urlResolver;
 }
 public void AddToWriter(IResourceWriter writer)
 {
     writer.AddResource(Name, Value);
 }
			/// <summary>
			/// Writes the byte array containing the most recent version of the resource
			/// represented by this instance into the private field "buffer" and returns it.
			/// Returns null, if this resource has not been written to yet.
			/// </summary>
			byte[] GetBuffer()
			{
				if (this.stream != null) {
					byte[] buffer = this.stream.ToArray();
					if (buffer.Length > 0) {
						this.writer.Close();
						this.writer.Dispose();
						this.buffer = this.stream.ToArray();
						this.writer = null;
						this.stream.Dispose();
						this.stream = null;
					}
				}
				return this.buffer;
			}
 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();
     }
 }
		public void SetResourceWriter(IResourceWriter writer)
		{
			resourceWriter = writer;
		}
예제 #51
0
			/// <summary>
			/// Writes the byte array containing the most recent version of the resource
			/// represented by this instance into the private field "buffer", if a
			/// resource writer has previously been requested for this resource.
			/// </summary>
			public void WriteResourcesToBuffer()
			{
				if (this.stream != null) {
					this.writer.Close();
					this.writer.Dispose();
					this.buffer = this.stream.ToArray();
					this.writer = null;
					this.stream.Dispose();
					this.stream = null;
				}
			}
예제 #52
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));
            }
        }
 /// <summary>
 /// ChessResourseWriterconstructor
 /// </summary>
 public ChessResourseWriter()
 {
     writer = new ResourceWriter("Chess.resources"); // Chess Pieces
 }
예제 #54
0
 private static bool TryWriteFile(string aResDir, string aLangDir, string aFileName, IResourceWriter aWriter)
 {
     string fullPath = Path.Combine(Path.Combine(aResDir, aLangDir), aFileName);
     return TryWriteFile(fullPath, aWriter);
 }
예제 #55
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));
 }
예제 #56
0
 private static bool TryWriteFile(string aFullName, IResourceWriter aWriter)
 {
     if (!File.Exists(aFullName))
         return false;
     string mime = MimeFromFileName(aFullName);
     byte[] data = File.ReadAllBytes(aFullName);
     aWriter.WriteResourceBegin(data.Length, mime);
     aWriter.WriteResource(data, data.Length);
     aWriter.WriteResourceEnd();
     return true;
 }
예제 #57
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.
         }
     }
 }
예제 #58
0
		public void SetResourceWriter(IResourceWriter writer)
		{
			this.writer = writer;
		}