Пример #1
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));
            }
        }
Пример #2
0
        List <ResXDataNode> ReadResourceEntries(DecompileContext ctx)
        {
            var list = new List <ResXDataNode>();

            try {
                using (var reader = new ResourceReader(embeddedResource.GetResourceStream())) {
                    var iter = reader.GetEnumerator();
                    while (iter.MoveNext())
                    {
                        ctx.CancellationToken.ThrowIfCancellationRequested();
                        string key = null;
                        try {
                            key = iter.Key as string;
                            if (key == null)
                            {
                                continue;
                            }
                            //TODO: Some resources, like images, should be saved as separate files. Use ResXFileRef.
                            //		Don't do it if it's a satellite assembly.
                            list.Add(new ResXDataNode(key, iter.Value, TypeNameConverter));
                        }
                        catch (Exception ex) {
                            ctx.Logger.Error(string.Format("Could not add resource '{0}', Message: {1}", key, ex.Message));
                        }
                    }
                }
            }
            catch (Exception ex) {
                ctx.Logger.Error(string.Format("Could not read resources from {0}, Message: {1}", embeddedResource.Name, ex.Message));
            }
            return(list);
        }
Пример #3
0
        public static ImageList GetimageListAll(int size)
        {
            ImageList imageList = imagelistall;

            if (imagelistall.Images.Count == 0)
            {
                imageList.ImageSize  = new System.Drawing.Size(size, size);
                imageList.ColorDepth = ColorDepth.Depth32Bit;
                Stream stream = GetFileStream("Itop.Client.Resources.Properties.Resources.resources");

                ResourceReader        read = new ResourceReader(stream);
                IDictionaryEnumerator ie   = read.GetEnumerator();
                while (ie.MoveNext())
                {
                    object obj = ie.Value;
                    try {
                        if (obj is Icon)
                        {
                            imageList.Images.Add(ie.Key as string, (Icon)obj);
                        }
                        else
                        {
                            Bitmap tempbit = (Bitmap)obj;
                            tempbit.Tag = ie.Key as string;
                            imageList.Images.Add(ie.Key as string, tempbit);
                        }
                    } catch { }
                }
            }
            return(imageList);
        }
Пример #4
0
        /// <summary>
        /// Find an image resource from local resource files
        /// </summary>
        /// <param name="imageResourceName">Resource name for the image</param>
        /// <param name="localResources">Local resource</param>
        /// <returns></returns>
        private bool FetchImageResource(string imageResourceName, string localResources)
        {
            if (!File.Exists(localResources))
            {
                return(false);
            }

            try
            {
                IResourceReader       basic  = new ResourceReader(localResources);
                IDictionaryEnumerator basicx = basic.GetEnumerator();
                while (basicx.MoveNext())
                {
                    if (basicx.Key.ToString() == imageResourceName)
                    {
                        pbImage.Image = (Image)basicx.Value;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionHandler.LogException(ex, true);
            }
            return(false);
        }
    public static void Main()
    {
        ResourceReader        rdr  = new ResourceReader(@".\ContactResources.resources");
        IDictionaryEnumerator dict = rdr.GetEnumerator();

        while (dict.MoveNext())
        {
            Console.WriteLine("Resource Name: {0}", dict.Key);
            try {
                Console.WriteLine("   Value: {0}", dict.Value);
            }
            catch (FileNotFoundException) {
                Console.WriteLine("   Exception: A file cannot be found.");
                DisplayResourceInfo(rdr, (string)dict.Key, false);
            }
            catch (FormatException) {
                Console.WriteLine("   Exception: Corrupted data.");
                DisplayResourceInfo(rdr, (string)dict.Key, true);
            }
            catch (TypeLoadException) {
                Console.WriteLine("   Exception: Cannot load the data type.");
                DisplayResourceInfo(rdr, (string)dict.Key, false);
            }
        }
    }
Пример #6
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);
                    }
                }
            }
        }
Пример #7
0
        [Test]         // AddResource (string, byte [])
        public void AddResource0()
        {
            byte [] value = new byte [] { 5, 7 };

            MemoryStream   ms     = new MemoryStream();
            ResourceWriter writer = new ResourceWriter(ms);

            writer.AddResource("Name", value);
            writer.Generate();

            try {
                writer.AddResource("Address", new byte [] { 8, 12 });
                Assert.Fail("#A1");
            } catch (InvalidOperationException ex) {
                // The resource writer has already been closed
                // and cannot be edited
                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType(), "#A2");
                Assert.IsNull(ex.InnerException, "#A3");
                Assert.IsNotNull(ex.Message, "#A4");
            }

            ms.Position = 0;
            ResourceReader        rr         = new ResourceReader(ms);
            IDictionaryEnumerator enumerator = rr.GetEnumerator();

            Assert.IsTrue(enumerator.MoveNext(), "#B1");
            Assert.AreEqual("Name", enumerator.Key, "#B3");
            Assert.AreEqual(value, enumerator.Value, "#B4");
            Assert.IsFalse(enumerator.MoveNext(), "#B5");

            writer.Close();
        }
Пример #8
0
        public static bool Phase2()
        {
            var resName = PhaseParam;

            var resReader = new ResourceReader(AsmDef.FindResource(res => res.Name == "app.resources").GetResourceStream());
            var en        = resReader.GetEnumerator();

            byte[] resData = null;

            while (en.MoveNext())
            {
                if (en.Key.ToString() == resName)
                {
                    resData = en.Value as byte[];
                }
            }

            if (resData == null)
            {
                PhaseError = new PhaseError
                {
                    Level   = PhaseError.ErrorLevel.Critical,
                    Message = "Could not read resource data!"
                };
            }

            PhaseParam = resData;
            return(true);
        }
Пример #9
0
        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="filepath">资源文件路径</param>
        public ResourceHelper(string filepath)
        {
            this.m_FilePath  = filepath;
            this.m_Hashtable = new Hashtable();

            //如果存在
            if (File.Exists(filepath))
            {
                string tempFile = HConst.TemplatePath + "\\decryptFile.resx";

                //解密文件
                //System.Net.Security tSecurity = new Security();
                //tSecurity.DecryptDES(filepath, tempFile);
                File.Copy(filepath, tempFile);

                using (ResourceReader ResReader = new ResourceReader(tempFile))
                {
                    IDictionaryEnumerator tDictEnum = ResReader.GetEnumerator();
                    while (tDictEnum.MoveNext())
                    {
                        this.m_Hashtable.Add(tDictEnum.Key, tDictEnum.Value);
                    }

                    ResReader.Close();
                }

                //删除临时文件
                File.Delete(tempFile);
            }
        }
Пример #10
0
        private Hashtable Get(string planguage)
        {
            if (planguage.Contains("fr"))
            {
                planguage = Constants.en_US; // fr_FR -> lock englis translate
            }
            else  /*when this device language doesn't found --> default language is English*/
            {
                planguage = Constants.en_US;
            }

            var      table            = new Hashtable();
            Assembly resourceAssembly = Assembly.GetExecutingAssembly();

            try
            {
                using (ResourceReader reader = new ResourceReader(resourceAssembly.GetManifestResourceStream($"Kola.Infrastructure.Localization.{planguage}.resources")))
                {
                    IDictionaryEnumerator dic = reader.GetEnumerator();
                    while (dic.MoveNext())
                    {
                        table.Add(dic.Key as string, dic.Value as string);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write($"TranslateManager: Error occured to load a language {planguage} resources ==> {ex.Message}");
            }
            return(table);
        }
        private static IReadOnlyDictionary <string, string> CreateFlagNameResourceMap()
        {
            var assembly = typeof(LanguageSelector).Assembly;
            var names    = assembly.GetManifestResourceNames();
            var match    = names.Single(x => x.EndsWith(".g.resources", StringComparison.Ordinal));

            Debug.Assert(match != null, "match != null");
            using var stream = assembly.GetManifestResourceStream(match);
            if (stream is null)
            {
                throw new InvalidOperationException($"GetManifestResourceStream({match}) returned null");
            }

            using var reader = new ResourceReader(stream);
            var flags      = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            var enumerator = reader.GetEnumerator();

            while (enumerator.MoveNext())
            {
                var flagName = (string)enumerator.Key;
                Debug.Assert(flagName != null, "flag == null");
                var name = System.IO.Path.GetFileNameWithoutExtension(flagName);
                if (Culture.AllRegions.Any(x => string.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase) ||
                                           string.Equals(x.TwoLetterISORegionName, name, StringComparison.OrdinalIgnoreCase)))
                {
                    flags.Add(name, $"pack://application:,,,/Gu.Wpf.Localization;component/Flags/{name}.png");
                }
            }

            return(flags);
        }
Пример #12
0
        public AccountForm()
        {
            InitializeComponent();

            IResourceReader             reader         = null;
            Dictionary <string, string> loginResources = new Dictionary <string, string>();

            try
            {
                reader = new ResourceReader("Account.resources");
                IDictionaryEnumerator dict = reader.GetEnumerator();
                gridAccounts.Rows.Clear();
                while (dict.MoveNext())
                {
                    string   key         = dict.Key.ToString();
                    string   valueString = dict.Value.ToString();
                    string[] values      = valueString.Split(',');
                    gridAccounts.Rows.Add(key, values[0], values[1], values[2]);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
Пример #13
0
 /// <summary>
 /// 加载指定的资源
 /// </summary>
 /// <param name="resName"></param>
 /// <param name="culture"></param>
 private void LoadResource(string resName, string culture)
 {
     using (IResourceReader rr = new ResourceReader(resName))
     {
         var iter = rr.GetEnumerator();
         while (iter.MoveNext())
         {
             // 获取字典集合
             OrderedDictionary resources = null;
             if (!resourcesByCulture.Contains(culture))
             {
                 resources = new OrderedDictionary();
                 resourcesByCulture.Add(culture, resources);
             }
             else
             {
                 resources = resourcesByCulture[culture] as OrderedDictionary;
             }
             if (resources != null)
             {
                 // 添加信息
                 resources.Add(iter.Key, iter.Value);
             }
         }
     }
 }
Пример #14
0
        /*
         * Load
         */

        public static Program Load(String fileName)
        {
            Program program = null;

            using (ResourceReader resourceReader = new ResourceReader(fileName))
            {
                IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();

                while (enumerator.MoveNext())
                {
                    switch (Convert.ToString(enumerator.Key))
                    {
                    case "Program":
                    {
                        program = (Program)enumerator.Key;
                        break;
                    }

                    case "ProgramNode":
                    {
                        program = ((ProgramNode)enumerator.Value).SubProgram;
                        break;
                    }
                    }
                }
            }

            return(program);
        }
Пример #15
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Assembly thisAssembly = Assembly.GetExecutingAssembly();

            string[] test = Assembly.GetExecutingAssembly().GetManifestResourceNames();

            foreach (string file in test)
            {
                Stream rgbxml = thisAssembly.GetManifestResourceStream(
                    file);
                try
                {
                    ResourceReader        res  = new ResourceReader(rgbxml);
                    IDictionaryEnumerator dict = res.GetEnumerator();
                    while (dict.MoveNext())
                    {
                        Console.WriteLine("   {0}: '{1}' (Type {2})",
                                          dict.Key, dict.Value, dict.Value.GetType().Name);

                        if (dict.Key.ToString().EndsWith(".ToolTip") || dict.Key.ToString().EndsWith(".Text") || dict.Key.ToString().EndsWith("HeaderText") || dict.Key.ToString().EndsWith("ToolTipText"))
                        {
                            dataGridView1.Rows.Add();

                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colFile.Index].Value      = System.IO.Path.GetFileName(file);
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colInternal.Index].Value  = dict.Key.ToString();
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colEnglish.Index].Value   = dict.Value.ToString();
                            dataGridView1.Rows[dataGridView1.RowCount - 1].Cells[colOtherLang.Index].Value = dict.Value.ToString();
                        }
                    }
                } catch {}
            }
        }
Пример #16
0
        private void ParseResource(EmbeddedResource resource)
        {
            ResourceReader reader;

            try
            {
                reader = new ResourceReader(resource.CreateReader().AsStream());
            }
            catch (ArgumentException)
            {
                Console.WriteLine("This resource can not be parsed.");
                //throw;
                return;
            }

            var e = reader.GetEnumerator();

            while (e.MoveNext())
            {
                if (e.Key.ToString().ToLower().EndsWith(".baml"))
                {
                    reader.GetResourceData(e.Key.ToString(), out _, out var contents);

                    //MARK:AF 3E 00 00
                    contents = contents.Skip(4).ToArray(); //MARK:the first 4 bytes = length
                    using (var ms = new MemoryStream(contents))
                    {
                        BamlDocument b = BamlReader.ReadDocument(ms);
                        BamlFiles.TryAdd(e.Key.ToString(), b);
                    }
                }
            }
        }
Пример #17
0
        private static Dictionary <string, object> TryLoadEmbededDictionary(Stream resourceStream)
        {
            if (resourceStream == null)
            {
                throw new ArgumentNullException(nameof(resourceStream));
            }

            try
            {
                var loadedDictionary = new Dictionary <string, object>(StringComparer.InvariantCultureIgnoreCase);

                using (var resourceReader = new ResourceReader(resourceStream))
                {
                    var enumerator = resourceReader.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        if (!loadedDictionary.ContainsKey(enumerator.Key.ToString()))
                        {
                            loadedDictionary.Add(enumerator.Key.ToString(), enumerator.Value);
                        }
                    }
                }

                return(loadedDictionary);
            }
            catch
            {
                return(null);
            }
        }
Пример #18
0
        private void ProcessResources()
        {
            resources = new ResourcesData();

            if (verbose)
            {
                Console.WriteLine("Processing resource files");
            }

            foreach (var resFile in resFiles)
            {
                if (verbose)
                {
                    Console.WriteLine(" Processing resource file {0}", resFile);
                }

                var resource = new ResourceData(Path.GetFileNameWithoutExtension(resFile));
                using (var reader = new ResourceReader(resFile))
                {
                    IDictionaryEnumerator en = reader.GetEnumerator();
                    while (en.MoveNext())
                    {
                        resource.Data.Add(en.Key.ToString(), en.Value.ToString());
                    }
                }

                resources.AddResource(resource);
            }

            if (resources.GetResourceNames().Length == 0)
            {
                throw new ApplicationException("No resources found");
            }
        }
Пример #19
0
        static LanguageSelector()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(LanguageSelector), new FrameworkPropertyMetadata(typeof(LanguageSelector)));
            var assembly = typeof(LanguageSelector).Assembly;
            var names    = assembly.GetManifestResourceNames();
            var match    = names.Single(x => x.EndsWith(".g.resources"));

            Debug.Assert(match != null, "match != null");

            // ReSharper disable once AssignNullToNotNullAttribute
            using (var reader = new ResourceReader(assembly.GetManifestResourceStream(match)))
            {
                var flags      = new Dictionary <CultureInfo, string>(CultureInfoComparer.ByName);
                var enumerator = reader.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var flagName = (string)enumerator.Key;
                    Debug.Assert(flagName != null, "flag == null");
                    var name = System.IO.Path.GetFileNameWithoutExtension(flagName);
                    if (Culture.TryGet(name, out CultureInfo culture))
                    {
                        flags.Add(culture, flagName);
                    }
                }

                FlagNameResourceMap = flags;
            }
        }
Пример #20
0
        SkillReplayConfig()
        {
            var asm  = Assembly.GetExecutingAssembly();
            var name = Assembly.GetExecutingAssembly().GetName().Name;

            using (var stream = asm.GetManifestResourceStream($"{name}.g.resources"))
            {
                if (stream != null)
                {
                    using (var rr = new ResourceReader(stream))
                    {
                        var dict = rr.GetEnumerator();
                        while (dict.MoveNext())
                        {
                            var m = Regex.Match((string)dict.Key, "resources/strings\\.(.*)\\.xaml");
                            if (m.Success)
                            {
                                var         culturee = m.Groups[1].Value.ToLower();
                                CultureInfo info     = new CultureInfo(culturee);
                                LanguageList.Add(culturee, info.NativeName);
                            }
                        }
                    }
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Pobiera tekst z zasobu.
        /// </summary>
        /// <param name="assembly">Assembly.</param>
        /// <param name="embeddedResourceName">Ścieżka do zasobu.</param>
        /// <param name="name">Nazwa klucza.</param>
        public static string GetManifestResourceStream(Assembly assembly, string embeddedResourceName, string name)
        {
            try
            {
                using (Stream str = assembly.GetManifestResourceStream(embeddedResourceName))
                {
                    ResourceReader        reader     = new ResourceReader(str);
                    IDictionaryEnumerator enumerator = reader.GetEnumerator();

                    while (enumerator.MoveNext())
                    {
                        if (enumerator.Key.ToString() == name)
                        {
                            return(enumerator.Value.ToString());
                        }
                    }
                }
            }
            #region Blok catch i finally.
            catch
            {
                throw;
            }
            #endregion

            return("");
        }
Пример #22
0
        static void Main(string[] args)
        {
            ResourceReader        res  = new ResourceReader("Resources.resources");//该文件放到bin
            IDictionaryEnumerator dics = res.GetEnumerator();

            while (dics.MoveNext())
            {
                Stream s           = (Stream)dics.Value;
                int    fileSize    = (int)s.Length;
                byte[] fileContent = new byte[fileSize];
                s.Read(fileContent, 0, fileSize);
                FileStream fs;
                string     filepath = dics.Key.ToString();
                filepath = Path.Combine("C://", filepath); //保存到指定目录
                filepath = Path.GetFullPath(filepath);
                var p = Path.GetDirectoryName(filepath);   //要创建的目录
                if (!Directory.Exists(p))
                {
                    Directory.CreateDirectory(p);
                }

                FileInfo fi = new System.IO.FileInfo(filepath);
                fs = fi.OpenWrite();
                fs.Write(fileContent, 0, fileSize);
                fs.Close();
            }

            res.Close();
        }
Пример #23
0
        private static Bitmap ExtractBitmapResource(ResourceReader resourceReader, string bitmapName)
        {
            var dictEnum = resourceReader.GetEnumerator();

            Bitmap bitmap = null;

            while (dictEnum.MoveNext())
            {
                if (Equals(dictEnum.Key, bitmapName))
                {
                    bitmap = dictEnum.Value as Bitmap;

                    if (bitmap != null)
                    {
                        var pixel = bitmap.GetPixel(bitmap.Width - 1, 0);

                        bitmap.MakeTransparent(pixel);
                    }

                    break;
                }
            }

            return(bitmap);
        }
        public static ImageResourceCache DoLoad(string ImageType)
        {
            ImageResourceCache cache = GetChannelManager();

            cache.resources.Clear(); cache.resourcesByFileName.Clear();
            using (ResourceReader reader = DoLoadResourceReader())
            {
                IDictionaryEnumerator e = reader.GetEnumerator();
                string[] parts; string key, category;
                while (e.MoveNext())
                {
                    key   = e.Key as string;
                    parts = Split(key);
                    if (parts[0] == ImageType.ToLower())
                    {
                        cache.resources.Add(key, (Stream)e.Value);
                        category = parts[1];
                        key      = parts[0] + @"\" + parts[parts.Length - 1];
                        if (!cache.resourcesByFileName.ContainsKey(key))
                        {
                            cache.resourcesByFileName.Add(key, (Stream)e.Value);
                        }

                        continue;
                    }
                }
            }
            return(cache);
        }
Пример #25
0
        protected SqlStatementsBase(Assembly assembly, string resourcePath)
        {
            Ensure.That(assembly, "assembly").IsNotNull();
            Ensure.That(resourcePath, "resourcePath").IsNotNullOrWhiteSpace();

            if (!resourcePath.EndsWith(".resources"))
            {
                resourcePath = string.Concat(resourcePath, ".resources");
            }

            resourcePath = string.Concat(assembly.GetName().Name, ".", resourcePath);

            _sqlStrings = new Dictionary <string, string>();

            using (var resourceStream = assembly.GetManifestResourceStream(resourcePath))
            {
                using (var reader = new ResourceReader(resourceStream))
                {
                    var e = reader.GetEnumerator();
                    while (e.MoveNext())
                    {
                        _sqlStrings.Add(e.Key.ToString(), e.Value.ToString());
                    }
                }

                if (resourceStream != null)
                {
                    resourceStream.Close();
                }
            }
        }
Пример #26
0
        public XamlSnippetProvider(Assembly assembly, string resourceIdString)
        {
            var resourceIds = new[] { resourceIdString };

            foreach (var resourceId in resourceIds)
            {
                try
                {
                    using (var reader = new ResourceReader(assembly.GetManifestResourceStream(resourceId)))
                    {
                        var enumerator = reader.GetEnumerator();
                        while (enumerator.MoveNext())
                        {
                            var name = enumerator.Key as string;
                            var xaml = enumerator.Value as string;
                            if (name != null && xaml != null)
                            {
                                snippets.Add(new Snippet(name, xaml));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Debug.WriteLine($"Cannot load snippets. Exception: {e}");
                }
            }
        }
        /// <summary>
        /// Loads the resources.
        /// </summary>
        /// <param name="resourceName">Name of the resource.</param>
        /// <param name="ci">The ci.</param>
        public static void LoadResources(string resourceName, System.Globalization.CultureInfo ci)
        {
            string resFileName = System.Web.HttpRuntime.BinDirectory + resourceName + "." + ci.ToString() + ".resources";

            if (System.IO.File.Exists(resFileName))
            {
                lock (stringResources)
                {
                    if (!stringResources.ContainsKey(ci.ToString()))
                    {
                        stringResources.Add(ci.ToString(), new Hashtable());

                        try
                        {
                            ResourceReader        reader = new ResourceReader(resFileName);
                            IDictionaryEnumerator en     = reader.GetEnumerator();
                            while (en.MoveNext())
                            {
                                stringResources[ci.ToString()].Add(en.Key, en.Value);
                            }
                            reader.Close();
                        }
                        catch
                        {
                        }
                    }
                }
            }
        }
Пример #28
0
 private bool ReadSoftInforResources(string resourcesFileName)
 {
     try
     {
         using (ResourceReader resourceReader = new ResourceReader(resourcesFileName))
         {
             IDictionaryEnumerator enumerator = resourceReader.GetEnumerator();
             foreach (FieldInfo fieldInfo in SoftInfor.singleton.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
             {
                 while (enumerator.MoveNext())
                 {
                     if (enumerator.Key.ToString().Equals(fieldInfo.Name.ToLower()))
                     {
                         fieldInfo.SetValue((object)SoftInfor.singleton, enumerator.Value);
                         break;
                     }
                 }
                 enumerator.Reset();
             }
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Пример #29
0
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string ci = "";

            CultureInfo[] temp = System.Globalization.CultureInfo.GetCultures(CultureTypes.AllCultures);

            foreach (CultureInfo cul in temp)
            {
                if ((cul.DisplayName + " " + cul.Name) == comboBox1.Text)
                {
                    Console.WriteLine(cul.Name);
                    ci = cul.Name;
                }
            }

            Assembly thisAssembly;

            try
            {
                thisAssembly = Assembly.LoadFile(Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + ci + Path.DirectorySeparatorChar + "ArdupilotMegaPlanner.resources.dll");
            }
            catch { return; }

            string[] test = thisAssembly.GetManifestResourceNames();

            Encoding unicode = Encoding.Unicode;

            foreach (string file in test)
            {
                Stream rgbxml = thisAssembly.GetManifestResourceStream(
                    file);
                try
                {
                    ResourceReader        res  = new ResourceReader(rgbxml);
                    IDictionaryEnumerator dict = res.GetEnumerator();
                    while (dict.MoveNext())
                    {
                        Console.WriteLine("   {0}: '{1}' (Type {2})",
                                          dict.Key, dict.Value, dict.Value.GetType().Name);

                        string thing = (string)dict.Value;

//                            dataGridView1.Rows[0].Cells[colOtherLang.Index].Value = dict.Value.ToString();
                        foreach (DataGridViewRow row in dataGridView1.Rows)
                        {
                            string t2 = file.Replace(ci + ".", "");

                            if (row.Cells[0].Value.ToString() == t2 && row.Cells[1].Value.ToString() == dict.Key.ToString())
                            {
                                row.Cells[3].Value = thing;
                            }
                        }
                    }
                }
                catch { }
            }

            CustomMessageBox.Show("Loaded Existing");
        }
Пример #30
0
        /// <summary>
        /// Gets the icon set for the given index, using the given list for missing icons.
        /// </summary>
        /// <param name="defaultResourcesPath">The default resources path.</param>
        /// <param name="groupResourcesPath">The group resources path.</param>
        /// <returns></returns>
        private static ImageList GetCustomIconSet(string defaultResourcesPath, string groupResourcesPath)
        {
            ImageList customIconSet;
            ImageList tempImageList = null;

            try
            {
                tempImageList = new ImageList();
                IDictionaryEnumerator basicx;
                IResourceReader       defaultGroupReader = null;
                tempImageList.ColorDepth = ColorDepth.Depth32Bit;
                try
                {
                    defaultGroupReader = new ResourceReader(defaultResourcesPath);

                    basicx = defaultGroupReader.GetEnumerator();

                    while (basicx.MoveNext())
                    {
                        tempImageList.Images.Add(basicx.Key.ToString(), (Icon)basicx.Value);
                    }
                }
                finally
                {
                    defaultGroupReader?.Close();
                }

                IResourceReader groupReader = null;
                try
                {
                    groupReader = new ResourceReader(groupResourcesPath);

                    basicx = groupReader.GetEnumerator();

                    while (basicx.MoveNext())
                    {
                        if (tempImageList.Images.ContainsKey(basicx.Key.ToString()))
                        {
                            tempImageList.Images.RemoveByKey(basicx.Key.ToString());
                        }

                        tempImageList.Images.Add(basicx.Key.ToString(), (Icon)basicx.Value);
                    }
                }
                finally
                {
                    groupReader?.Close();
                }

                customIconSet = tempImageList;
                tempImageList = null;
            }
            finally
            {
                tempImageList?.Dispose();
            }

            return(customIconSet);
        }
Пример #31
0
        public static void Exception_Enumerator_Value()
        {
            Assert.Throws<InvalidOperationException>(() =>
            {
                using (var ms2 = new MemoryStream())
                {
                    using (var rw = GenerateResourceStream(s_dict, ms2))
                    {
                        ms2.Seek(0L, SeekOrigin.Begin);
                        var rr1 = new ResourceReader(ms2);

                        IDictionaryEnumerator enumarator = rr1.GetEnumerator();
                        rr1.Dispose();
                        var shouldnotgethere = enumarator.Value;


                    }
                }
            });
        }
Пример #32
0
        public static void Exception_Corrupted_resources1()
        {
            byte[] _RefBuffer12 = new byte[] { 206, 202, 239, 190, 1, 0, 0, 0, 145, 0, 0, 0, 108, 83, 121, 115, 116, 101, 109, 46, 82, 101, 115, 111, 117, 114, 99, 101, 115, 46, 82, 101, 115, 111, 117, 114, 99, 101, 82, 101, 97, 100, 101, 114, 44, 32, 109, 115, 99, 111, 114, 108, 105, 98, 44, 32, 86, 101, 114, 115, 105, 111, 110, 61, 52, 46, 48, 46, 48, 46, 48, 44, 32, 67, 117, 108, 116, 117, 114, 101, 61, 110, 101, 117, 116, 114, 97, 108, 44, 32, 80, 117, 98, 108, 105, 99, 75, 101, 121, 84, 111, 107, 101, 110, 61, 98, 55, 55, 97, 53, 99, 53, 54, 49, 57, 51, 52, 101, 48, 56, 57, 35, 83, 121, 115, 116, 101, 109, 46, 82, 101, 115, 111, 117, 114, 99, 101, 115, 46, 82, 117, 110, 116, 105, 109, 101, 82, 101, 115, 111, 117, 114, 99, 101, 83, 101, 116, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 80, 65, 68, 80, 65, 68, 80, 208, 41, 193, 10, 209, 41, 193, 10, 211, 41, 193, 10, 15, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 249, 0, 0, 0, 10, 110, 0, 97, 0, 109, 0, 101, 0, 49, 0, 0, 0, 0, 0, 10, 110, 0, 97, 0, 109, 0, 101, 0, 50, 0, 8, 0, 0, 0, 10, 110, 0, 97, 0, 109, 0, 101, 0, 51, 0, 16, 0, 0, 0, 1, 6, 118, 97, 108, 117, 101, 49, 1, 6, 118, 97, 108, 117, 101, 50, 1};
            using (var ms2 = new MemoryStream(_RefBuffer12))
            {
                using (var reader = new ResourceReader(ms2))
                {
                    var s_found_list = new List<DictionaryEntry>();
                    Assert.Throws<BadImageFormatException>(() =>
                    {
                        var enume = reader.GetEnumerator();

                        while (enume.MoveNext())
                        {
                            s_found_list.Add(enume.Entry);
                        }

                    });
                }
            }
        }
Пример #33
0
	public static int Unpack (string assembly, string pattern)
	{
		Assembly asm = null;
		try {
			asm = Assembly.LoadFile (assembly);
		} catch (Exception e) {
			Console.Error.WriteLine ("Unable to load assembly: {0}.", assembly);
			Console.Error.WriteLine (e);
			return 1;
		}

		string [] resources = asm.GetManifestResourceNames ();
	
		foreach (string resource in resources) {
			if (verbose)
				Console.WriteLine ("decompressing '{0}'", resource);

			ResourceReader reader = null;

			try {
				using (reader = new ResourceReader (asm.GetManifestResourceStream (resource))) {
				
					IDictionaryEnumerator id = reader.GetEnumerator (); 

					while (id.MoveNext ()) {
						string key = (string) id.Key;
						if (!Regex.IsMatch (key, pattern))
							continue;

						if (verbose)
							Console.WriteLine ("  stream: {0}", key);

						MemoryStream stream = id.Value as MemoryStream;
						if (stream == null) {
							Console.Error.WriteLine ("Item not stored as a MemoryStream. {0}", key);
							continue;
						}

						byte [] data = new byte [stream.Length];
						stream.Read (data, 0, data.Length);

						string dir = Path.GetDirectoryName (key);
						if (!String.IsNullOrEmpty (dir))
							Directory.CreateDirectory (dir);

						using (FileStream fs = File.OpenWrite (key)) {
							fs.Write (data, 0, data.Length);
						}
									      
					}
				}
			} catch (Exception e) {
				Console.WriteLine ("failed to decompress {0}, exception '{1}'.. skipping", resource, e.Message);
			}
		}

		return 0;
	}
Пример #34
0
        public static void ReadResource1()
        {

            using (var ms2 = new MemoryStream())
            {
                using (var rw = GenerateResourceStream(s_dict, ms2))
                {
                    //Rewind to begining of stream

                    ms2.Seek(0L, SeekOrigin.Begin);

                    var reader = new ResourceReader(ms2);

                    var s_found_key = new List<string>();
                    var s_found_value = new List<string>();
                    var enume = reader.GetEnumerator();

                    while (enume.MoveNext())
                    {
                        s_found_key.Add((string)enume.Key);
                        s_found_value.Add((string)enume.Value);
                    }
                    enume.Reset();
                    int i = 0;
                    while (enume.MoveNext())
                    {
                        string key = s_found_key[i];
                        string found_key = (string)enume.Key;

                        string value = s_found_key[i];
                        string found_value = (string)enume.Key;
                        i++;
                        Assert.True(string.Compare(key, found_key) == 0, "expected: " + key + ", but got : " + found_key);
                        Assert.True(string.Compare(value, found_value) == 0, "expected: " + value + ", but got : " + found_value);
                    }


                    Assert.True(s_found_key.Count == s_dict.Count);
                }
            }

        }
Пример #35
0
 public Boolean runTest()
   {
   Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   String strValue = String.Empty;
   Co5209AddResource_str_ubArr cc = new Co5209AddResource_str_ubArr();
   IDictionaryEnumerator idic;
   try {
   do
     {
     ResourceWriter resWriter;
     ResourceReader resReader;
     int statusBits = 0;
     int resultBits = 0;
     Byte[] ubArr = null;
     if(File.Exists(Environment.CurrentDirectory+"\\Co5209.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5209.resources");
     strLoc = "Loc_204gh";
     resWriter = new ResourceWriter("Co5209.resources");
     strLoc = "Loc_209tj";
     try
       {
       iCountTestcases++;
       resWriter.AddResource(null, ubArr);
       iCountErrors++;
       printerr("Error_20fhs! Expected Exception not thrown");
       }
     catch (ArgumentException) {}
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_2t0jg! Unexpected exception exc=="+exc.ToString());
       }
     strLoc = "Loc_t4j80";
     ubArr = null;
     iCountTestcases++;
     try
       {
       resWriter.AddResource("key with null value", ubArr);
       }
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_59ufd! Unexpected exc=="+exc.ToString());
       }
     Byte[] ubArr1 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'1',};
     Byte[] ubArr2 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'2',};
     Byte[] ubArr3 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'3',};
     Byte[] ubArr4 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'4',};
     Byte[] ubArr5 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'5',};
     Byte[] ubArr6 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'6',};
     strLoc = "Loc_59ugd";
     resWriter.AddResource("key 1", ubArr1);
     resWriter.AddResource("key 2", ubArr2);
     resWriter.AddResource("key 3", ubArr3);
     resWriter.AddResource("key 4", ubArr4);
     resWriter.AddResource("key 5", ubArr5);
     resWriter.AddResource("key 6", ubArr6);
     strLoc = "Loc_230rj";
     iCountTestcases++;
     try
       {
       resWriter.AddResource("key 1", ubArr6);
       iCountErrors++;
       printerr("Error_2th8e! Names are not unique");
       }
     catch (ArgumentException) {}
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_298hg! Unexpected exception=="+exc.ToString());
       }
     resWriter.Generate();
     iCountTestcases++;
     if(!File.Exists(Environment.CurrentDirectory+"\\Co5209.resources"))
       {
       iCountErrors++;
       printerr("Error_23094! Expected file was not created");
       }
     resWriter.Close();
     strLoc = "Loc_30tud";
     resReader = new ResourceReader(Environment.CurrentDirectory+"\\Co5209.resources");
     strLoc = "Loc_0576cd";
     byte[] btTemp;
     Boolean fNotEqual;
     IDictionaryEnumerator resEnumerator = resReader.GetEnumerator();
     idic = resReader.GetEnumerator();
     while(idic.MoveNext())
       {
       if(idic.Key.Equals("key 1")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr1[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x1;
       } else if(idic.Key.Equals("key 2")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr2[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x2;
       } else if(idic.Key.Equals("key 3")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr3[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x4;
       } else if(idic.Key.Equals("key 4")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr4[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x8;
       } else if(idic.Key.Equals("key 5")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr5[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x10;
       } else if(idic.Key.Equals("key 6")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr6[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x20;
       }
       }
     resultBits = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20;
     iCountTestcases++;
     if(statusBits != resultBits)
       {
       iCountErrors++;
       printerr("Error_238fh! The names are incorrect, StatusBits=="+statusBits);
       }
     strLoc = "Loc_t0dds";
     iCountTestcases++;
     if(idic.MoveNext())
       {
       iCountErrors++;
       printerr("Error_2398r! , There shouldn't have been more elementes : GetValue=="+idic.Value);
       }
     resReader.Close();
     strLoc = "Loc_957fd";
     } while (false);
   } catch (Exception exc_general ) {
   ++iCountErrors;
   Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general);
   }
   if ( iCountErrors == 0 )
     {
     Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
     return true;
     }
   else
     {
     Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
 public bool runTest()
   {
   Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   String strValue = String.Empty;
   IDictionaryEnumerator idic;
   try
     {
     ResourceWriter resWriter;
     ResourceReader resReader;
     Stream stream = null;
     MemoryStream ms;
     FileStream fs;
     if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5445.resources");
     strLoc = "Loc_20xcy";
     stream = null;
     iCountTestcases++;
     try {
     resWriter = new ResourceWriter(stream);
     iCountErrors++;
     printerr( "Error_29vc8! ArgumentNullException expected");
     } catch ( ArgumentNullException aExc) {
     } catch ( Exception exc) {
     iCountErrors++;
     printerr( "Error_10s9x! ArgumentNullException expected , got exc=="+exc.ToString());
     }
     strLoc = "Loc_3f98d";
     new FileStream("Co5445.resources", FileMode.Create).Close();
     fs = new FileStream("Co5445.resources", FileMode.Open, FileAccess.Read, FileShare.None);
     iCountTestcases++;
     try {
     resWriter = new ResourceWriter(fs);
     iCountErrors++;
     printerr( "Error_2c88s! ArgumentException expected");
     } catch (ArgumentException aExc) {
     } catch ( Exception exc) {
     iCountErrors++;
     printerr( "Error_2x0zu! ArgumentException expected, got exc=="+exc.ToString());
     }
     strLoc = "Loc_f0843";
     ms = new MemoryStream();
     resWriter = new ResourceWriter(ms);
     resWriter.AddResource("Harrison", "Ford");
     resWriter.AddResource("Mark", "Hamill");
     resWriter.Generate();
     ms.Position = 0;
     resReader = new ResourceReader(ms);
     idic = resReader.GetEnumerator();
     idic.MoveNext();
     iCountTestcases++;
     if(!idic.Value.Equals("Ford"))
       {
       iCountErrors++;
       printerr( "Error_2d0s9 Expected==Ford, value=="+idic.Value.ToString());
       }
     idic.MoveNext();
     iCountTestcases++;
     if(!idic.Value.Equals("Hamill"))
       {
       iCountErrors++;
       printerr( "Error_2ce80 Expected==Hamill, value=="+idic.Value.ToString());
       }
     strLoc = "Loc_20984";
     iCountTestcases++;
     if(idic.MoveNext())
       {
       iCountErrors++;
       printerr( "Error_f4094! Should have hit the end of the stream already");
       }
     fs.Close();
     strLoc = "Loc_04853fd";
     if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5445.resources");
     } catch (Exception exc_general ) {
     ++iCountErrors;
     Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
     }
   if ( iCountErrors == 0 )
     {
     Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
     return true;
     }
   else
     {
     Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
    private static bool ValidateResourceFile(string resFile, string outputDir, string sourceHash, int viewCount)
    {
        IDictionary<int, KeyValuePair<string, string>> resourceDictionary =
            new Dictionary<int, KeyValuePair<string, string>>();
        using (var resourceReader = new ResourceReader(Path.Combine(outputDir, resFile)))
        {
            // Create an IDictionaryEnumerator to iterate through the resources.
            IDictionaryEnumerator IDEnumerator = resourceReader.GetEnumerator();

            // Iterate through the resources and store it in dictionary
            foreach (DictionaryEntry d in resourceReader)
            {
                //The KeyValuePair to be Inserted into the dictionary, NEEDS TO BE CASTED!
                var valueToInsert = (KeyValuePair<string, string>)d.Value;

                //Populating Dictionary, Item, the key in the dictionary is turn into an integer
                resourceDictionary.Add(Int32.Parse(d.Key.ToString()), valueToInsert);
            }
            resourceReader.Close();
        }

        /*
         * This is commented out in the public file because this class is an internal MS class that EF uses to create it's hash.
         * I reflected on it, made it a public class, and included it in our internal process to validate that the views were
         * created correctly and the view hash matched the original EF hash.
         * I will not distribute MS source code so the simplest approach is to comment this section out.
         *
         * This code being commented out does not affect the output file, it's just a validation step.
         * */

        //var resourceHaser = new CompressingHashBuilder(new SHA256CryptoServiceProvider());
        //for (int i = 0; i < viewCount; i++)
        //{
        //   KeyValuePair<string, string> resourceValue = resourceDictionary[i];
        //   resourceHaser.AppendLine(resourceValue.Key);
        //   resourceHaser.AppendLine(resourceValue.Value);
        //}
        //string fileHash = resourceHaser.ComputeHash();
        //return sourceHash == fileHash;
        return true;
    }