コード例 #1
0
        public void GetStringSafe()
        {
            var path = Combine(Files.GetExecutingPath(), "Resources", "TestResourceResX.resx");
            var rs   = new ResXResourceSet(path, null)
            {
                SafeMode = true
            };

            // when getting an object, result is always a ResXDataNode regardless of the object is a string
            Assert.IsInstanceOf <ResXDataNode>(rs.GetObject("TestString"));
            Assert.IsInstanceOf <ResXDataNode>(rs.GetObject("TestBytes"));

            // for a string, the string value is returned
            Assert.AreEqual("String invariant ResX", rs.GetString("TestString"));

            // for a non-string, the non-deserialized raw string value is returned
            Assert.AreEqual("576, 17", rs.GetString("TestPoint"));

            // for a file reference, the reference value is returned...
            Assert.IsTrue(rs.GetString("TestBinFile").StartsWith("TestBinFile.bin;System.Byte[], mscorlib", StringComparison.Ordinal));

            // ...even if it refers to a string...
            Assert.IsTrue(rs.GetString("TestTextFile").StartsWith("TestTextFile.txt;System.String, mscorlib", StringComparison.Ordinal));

            rs.SafeMode = false;
            Assert.IsNotNull(rs.GetString("TestTextFile"));
            Assert.IsNotNull(rs.GetObject("TestBinFile"));
            rs.SafeMode = true;

            // ...unless the string value is already obtained and cached
            Assert.IsFalse(rs.GetString("TestTextFile").StartsWith("TestTextFile.txt;System.String, mscorlib", StringComparison.Ordinal));

            // but a non-string file reference will still return the file reference even if the result is cached (with AutoCleanup, this time with full path)
            Assert.IsTrue(rs.GetString("TestBinFile").Contains("TestBinFile.bin;System.Byte[], mscorlib"));
        }
コード例 #2
0
ファイル: retrieve1.cs プロジェクト: zhimaqiao51/docs
   public CarDisplayApp()
   {
      // Instantiate controls.
      PictureBox pictureBox = new PictureBox();
      pictureBox.Location = new Point(10, 10);
      this.Controls.Add(pictureBox);
      DataGridView grid = new DataGridView();
      grid.Location = new Point(10, 60);
      this.Controls.Add(grid);
      
      // Get resources from .resx file.
      using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
      {
         // Retrieve the string resource for the title.
         this.Text = resxSet.GetString("Title");
         // Retrieve the image.
         Icon image = (Icon) resxSet.GetObject("Information", true);
         if (image != null)
            pictureBox.Image = image.ToBitmap();

         // Retrieve Automobile objects.  
         List<Automobile> carList = new List<Automobile>();
         string resName = "EarlyAuto";
         Automobile auto; 
         int ctr = 1;
         do {
            auto = (Automobile) resxSet.GetObject(resName + ctr.ToString());
            ctr++;
            if (auto != null) 
               carList.Add(auto);
         } while (auto != null);
         cars = carList.ToArray();
         grid.DataSource = cars;
      }
   }
コード例 #3
0
        public void CleanupAndRegenerate()
        {
            string path = Combine(Files.GetExecutingPath(), "Resources", "TestResourceResX.resx");
            var    rs   = new ResXResourceSet(path, null);

            // in safe mode, raw value is expected
            rs.SafeMode = true;
            Assert.AreEqual("576, 17", rs.GetString("TestPoint"));

            // in non-safe mode, raw value is cleared once an object is generated
            rs.SafeMode = false;
            Assert.AreEqual(new Point(576, 17), rs.GetObject("TestPoint"));

            // when safe mode is turned on again, raw value is re-generated
            rs.SafeMode = true;
            Assert.AreEqual("576, 17", rs.GetString("TestPoint"));

            // for fileref, in safe mode, path/type is expected
            Assert.IsTrue(rs.GetString("TestBinFile").StartsWith("TestBinFile.bin;System.Byte[], mscorlib", StringComparison.Ordinal));

            // in non-safe mode, raw value is cleared once an object is generated
            rs.SafeMode = false;
            Assert.AreEqual(typeof(byte[]), rs.GetObject("TestBinFile").GetType());

            // when safe mode is turned on again, raw value is re-generated from fileRef
            rs.SafeMode = true;
            Assert.IsTrue(rs.GetString("TestBinFile").StartsWith("TestBinFile.bin;System.Byte[], mscorlib", StringComparison.Ordinal));
        }
コード例 #4
0
 public static void CargarConfiguracion()
 {
     if (File.Exists("config.cfg"))
     {
         try
         {
             cargador            = new ResXResourceSet("config.cfg");
             Language            = cargador.GetString("Language");
             LastOpenedDirectory = cargador.GetString("LastOpenedDirectory");
             LinkedWithSpotify   = (bool)cargador.GetObject("LinkedWithSpotify");
             Clipboard           = cargador.GetString("Clipboard");
             History             = cargador.GetString("History");
             HistoryEnabled      = (bool)cargador.GetObject("HistoryEnabled");
             StreamString        = cargador.GetString("StreamString");
             StreamEnabled       = (bool)cargador.GetObject("StreamEnabled");
             //Load the colors
             ColorLongSong = Color.FromArgb(int.Parse(cargador.GetString("ColorLongSong"), NumberStyles.HexNumber));
             ColorBonus    = Color.FromArgb(int.Parse(cargador.GetString("ColorBonus"), NumberStyles.HexNumber));
             //Load fonts
             string[] FontViewString   = cargador.GetString("FontView").Split(',');
             string[] FontLyricsString = cargador.GetString("FontLyrics").Split(',');
             FontView            = new Font(FontViewString[0], (float)Convert.ToInt32(FontViewString[1]));
             FontLyrics          = new Font(FontLyricsString[0], (float)Convert.ToInt32(FontLyricsString[1]));
             MainFormSize        = (Size)cargador.GetObject("MainFormSize");
             MainFormViewSidebar = (bool)cargador.GetObject("MainFormViewSidebar");
         }
         catch (NullReferenceException)
         {
             //Load defaults
             MainFormViewSidebar = true;
         }
     }
     else
     {
         Language            = "es";
         LinkedWithSpotify   = false;
         LastOpenedDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
         Clipboard           = "%artist% - %title% (%year%)";
         History             = "#%track_num%. %artist% - %title%";
         StreamString        = "#%track_num%. %artist% - %title%";
         StreamEnabled       = false;
         HistoryEnabled      = true;
         ColorLongSong       = Color.Salmon;
         ColorBonus          = Color.SkyBlue;
         FontLyrics          = new Font("Segoe UI", 10);
         FontView            = new Font("Segoe UI", 10);
         //MainFormSize -> designer
         MainFormViewSidebar = true;
     }
     guardador = new ResXResourceWriter("config.cfg");
 }
コード例 #5
0
ファイル: MainWindow.xaml.cs プロジェクト: tomual/peopledex
        // Set currently visible profile
        public void SetProfile(Profile profile)
        {
            WelcomeOverlay.Visibility = Visibility.Hidden;
            if (File.Exists("profileImages.resx"))
            {
                using (ResXResourceSet resxSet = new ResXResourceSet("profileImages.resx"))
                {
                    Console.WriteLine(resxSet.GetObject(profile.Id.ToString(), true));
                    System.Drawing.Image img = (System.Drawing.Image)resxSet.GetObject(profile.Id.ToString(), true);
                    if (img != null)
                    {
                        using (MemoryStream memory = new MemoryStream())
                        {
                            img.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
                            memory.Position = 0;
                            BitmapImage bitmapimage = new BitmapImage();
                            bitmapimage.BeginInit();
                            bitmapimage.StreamSource = memory;
                            bitmapimage.CacheOption  = BitmapCacheOption.OnLoad;
                            bitmapimage.EndInit();

                            ProfileImage.Source = bitmapimage;
                        }
                    }
                    else
                    {
                        ProfileImage.Source = new BitmapImage(new Uri(@"pack://*****:*****@"pack://application:,,,/Resources/default.jpg"));
            }
            ProfileNumber.Text  = "#" + profile.Id.ToString("D3");
            ProfileName.Text    = profile.Name;
            ProfileSubtext.Text = profile.Location;
            if (!string.IsNullOrEmpty(profile.Email))
            {
                ProfileSubtext.Text += "  ·  " + profile.Email;
            }
            ProfileOccupation.Text  = profile.Occupation;
            ProfileBirthday.Text    = profile.Birthday;
            ProfileLikes.Text       = profile.Likes;
            ProfileDescription.Text = profile.Description;

            currentProfile = profile;
            RefreshProfileEventsListing();
        }
コード例 #6
0
ファイル: PlotObserver.cs プロジェクト: radtek/WarzoneConnect
        private static bool Load(ResXResourceSet resxSet)
        {
            try
            {
                // StopObserve();
                if (_currentNode != null)
                {
                    foreach (var node in _currentNode)
                    {
                        MailServer.Trigger -= node.TriggerPlay;
                    }
                }

                _currentNode = (List <ObjectiveNode>)resxSet.GetObject("Objectives");

                HalfwayObserve();
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                AutoSave();
            }
        }
コード例 #7
0
        private void linkLabel7_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Program.LoadStart();

            CompanyInfo cmpInfo = new CompanyInfo();

            cmpInfo.ShowDialog();

            adresa.Text   = Properties.Settings.Default.CmpAddress;
            oib.Text      = Properties.Settings.Default.CmpVAT;
            www.Text      = Properties.Settings.Default.CmpWWW;
            tel.Text      = Properties.Settings.Default.CmpPhone;
            infomail.Text = Properties.Settings.Default.CmpEmail;

            try
            {
                using (ResXResourceSet resxLoad = new ResXResourceSet(@".\Logo.resx"))
                {
                    pictureBox3.Image = (Image)resxLoad.GetObject("LogoPicture", true);
                }
            }
            catch (Exception e1)
            {
                Program.LoadStop();
                this.Focus();

                new LogWriter(e1);
            }
        }
コード例 #8
0
ファイル: MapEdit.cs プロジェクト: lep3714/Order-of-the-Paw
        //Creates the tile map from a file.
        private void CreateTileBox(BinaryReader bi)
        {
            ResXResourceSet resSet = new ResXResourceSet(resX); //Holds all the images to paint with.

            try
            {
                for (int row = 0; row < SaveBox.GetLength(0); row++)
                {
                    for (int col = 0; col < SaveBox.GetLength(1); col++)
                    {
                        SaveBox[row, col].Size = new Size(TILE_SIZE / (SaveBox.GetLength(1) / 2), TILE_SIZE / (SaveBox.GetLength(1) / 2));
                        if (SaveBox[row, col].Size.Width > 80)
                        {
                            SaveBox[row, col].Size = new Size(50, 50);
                        }
                        SaveBox[row, col].Location = new Point(279 + (SaveBox[row, col].Size.Width * col), 9 + (SaveBox[row, col].Size.Height * row));
                        string temp = bi.ReadString();
                        SaveBox[row, col].Image    = (System.Drawing.Image)resSet.GetObject(temp);
                        SaveBox[row, col].SizeMode = PictureBoxSizeMode.StretchImage;
                        Controls.Add(SaveBox[row, col]);
                        SaveBox[row, col].Tag = temp;


                        SaveBox[row, col].MouseDown  += delegate(object sender, MouseEventArgs e) { MapEdit_MouseClick(sender, e); };
                        SaveBox[row, col].MouseEnter += delegate(object sender, EventArgs e) { MapEdit_MouseDrag(sender, e); };
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
コード例 #9
0
        public void FromNodeInfo()
        {
            var path = Combine(Files.GetExecutingPath(), "Resources", "TestRes.resx");
            var rs   = new ResXResourceSet(path, null)
            {
                SafeMode = true
            };
            var node = (ResXDataNode)rs.GetObject("string");

            Assert.IsNotNull(node.ValueData);
            node.GetValue(cleanupRawData: true);
            Assert.IsNull(node.ValueData);
        }
コード例 #10
0
        public void NonSerializableObject()
        {
            var rs = new ResXResourceSet();

            rs.SetObject("x", new NonSerializableClass {
                Prop = 1
            });

            var sb = new StringBuilder();

            rs.Save(new StringWriter(sb), true);

            var rsCheck = new ResXResourceSet(new StringReader(sb.ToString()));

            Assert.AreEqual(rs.GetObject("x"), rsCheck.GetObject("x"));

            sb = new StringBuilder();
            rs.Save(new StringWriter(sb), false);

            rsCheck = new ResXResourceSet(new StringReader(sb.ToString()));
            Assert.AreEqual(rs.GetObject("x"), rsCheck.GetObject("x"));
        }
コード例 #11
0
ファイル: MapEdit.cs プロジェクト: lep3714/Order-of-the-Paw
 //Handles changing the file by the name in the list box
 private void PictureList_SelectedIndexChanged(object sender, EventArgs e)
 {
     try
     {
         ResXResourceSet resSet = new ResXResourceSet(resX);
         ListBox         temp   = (ListBox)sender;
         string          temp2  = (string)temp.SelectedItem;
         holder           = (System.Drawing.Image)resSet.GetObject(temp2);
         currentImg.Image = holder;
         imgLoc           = temp2;
     }
     catch (Exception exc)
     {
         MessageBox.Show(exc.Message);
     }
 }
コード例 #12
0
ファイル: MapEdit.cs プロジェクト: lep3714/Order-of-the-Paw
 //Logic for clicking and dragging to paint.
 private void MapEdit_MouseDrag(object sender, EventArgs e)
 {
     if (MouseButtons == MouseButtons.Left)
     {
         PictureBox orig = (PictureBox)sender;
         orig.Image = holder;
         orig.Tag   = imgLoc;
     }
     else if (MouseButtons == MouseButtons.Right)
     {
         PictureBox      orig   = (PictureBox)sender;
         ResXResourceSet resSet = new ResXResourceSet(resX);
         orig.Image = (System.Drawing.Image)resSet.GetObject("blackpaint");
         orig.Tag   = imgLoc;
     }
 }
コード例 #13
0
        public MainWindow()
        {
            InitializeComponent();
            NotifyIcon notifyIcon = new NotifyIcon();

            using (ResXResourceSet resourceSet = new ResXResourceSet(@"..\..\Properties\Resources.resx")) {
                notifyIcon.Icon = (System.Drawing.Icon)resourceSet.GetObject("Icon", true);
            }
            notifyIcon.Visible = true;
            System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
            System.Windows.Forms.MenuItem    exitItem    = new System.Windows.Forms.MenuItem();
            exitItem.Index  = 0;
            exitItem.Text   = "Wyjdź";
            exitItem.Click += ContextMenuExit;
            contextMenu.MenuItems.Add(exitItem);
            notifyIcon.ContextMenu = contextMenu;
        }
コード例 #14
0
ファイル: MapEdit.cs プロジェクト: lep3714/Order-of-the-Paw
 private void MapEdit_MouseClick(object sender, MouseEventArgs e)
 {
     //"Erase" tiles with right click.
     if (MouseButtons == MouseButtons.Right)
     {
         PictureBox orig = (PictureBox)sender;
         orig.Tag     = "blackpaint";
         orig.Capture = false;
         ResXResourceSet resSet = new ResXResourceSet(resX);
         orig.Image = (System.Drawing.Image)resSet.GetObject("blackpaint");
     }
     else if (MouseButtons == MouseButtons.Left)
     {
         PictureBox orig = (PictureBox)sender;
         orig.Tag     = imgLoc;
         orig.Capture = false;
         orig.Image   = holder;
     }
 }
コード例 #15
0
 public void ReadResxImages(string resxPath)
 {
     using (ResXResourceSet resxSet = new ResXResourceSet(resxPath))
     {
         foreach (string grid in Grids.Keys)
         {
             foreach (ResourceImage image in grids[grid].Images.Values)
             {
                 image.ImageData = (System.Drawing.Image)resxSet.GetObject(image.Name);
             }
             if (!grids[grid].Images.ContainsKey($"{grid}.Images"))
             {
                 ResourceImage asterisk = new ResourceImage();
                 asterisk.Name      = $"{grid}.Images";
                 asterisk.ImageData = Resources.image_asterisk;
                 grids[grid].Images.Add(asterisk.Name, asterisk);
             }
         }
     }
 }
コード例 #16
0
    public static void Main()
    {
        CreateResXFile();

        ResXResourceSet       resSet = new ResXResourceSet(@".\StoreResources.resx");
        IDictionaryEnumerator dict   = resSet.GetEnumerator();

        while (dict.MoveNext())
        {
            string key = (string)dict.Key;
            // Retrieve resource by name.
            if (dict.Value is string)
            {
                Console.WriteLine("{0}: {1}", key, resSet.GetString(key));
            }
            else
            {
                Console.WriteLine("{0}: {1}", key, resSet.GetObject(key));
            }
        }
    }
コード例 #17
0
ファイル: Form1.cs プロジェクト: Jakub-Syrek/BitmapComparer
        private async void button10_Click(object sender, EventArgs e)
        {
            try
            {
                ResXResourceSet resX     = new ResXResourceSet(Resources.ResourceManager.BaseName);
                byte[]          _byteArr = (byte[])resX.GetObject("resource1");
                if (!(_byteArr.Equals(null)))
                {
                    Bitmap bitmap = await ByteToImageAsync(_byteArr);

                    pictureBox1.Image = bitmap;
                    textBox1.AppendText($"res added to picBox{Environment.NewLine}");
                }
                resX.Close();
                resX.Dispose();
                resX = null;
            }
            catch (Exception exc)
            {
                textBox1.AppendText($"res not added to pic => {exc.ToString()}{Environment.NewLine}");
            }
        }
コード例 #18
0
        public Image GetImage()
        {
            try
            {
                using (ResXResourceSet resxLoad = new ResXResourceSet(@".\Logo.resx"))
                {
                    img = (Image)resxLoad.GetObject("LogoPicture", true);

                    if (img == null)
                    {
                        img = (Image)rm.GetObject("DefaultLogoPOT");
                    }
                }
            }
            catch (Exception e1)
            {
                new LogWriter(e1);
                img = (Image)rm.GetObject("DefaultLogoPOT");
            }

            return(img);
        }
コード例 #19
0
        private void ShowWorldMap(Dictionary <KeyValuePair <int, int>, Terrain> terrainDictionary)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                worldMap = new WorldMap(128, 10, 10, terrainDictionary);

                int    maxindex = size - 1;
                string resxFile = "Resources.resx";

                using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
                {
                    for (int i = 0; i < maxindex; i++)
                    {
                        for (int j = 0; j < maxindex; j++)
                        {
                            KeyValuePair <int, int> keyValuePair = new KeyValuePair <int, int>(i, j);
                            Terrain terrain = terrainDictionary[keyValuePair];

                            Image image = (Image)resxSet.GetObject(terrain.Picture, true);
                            if (image != null)
                            {
                                terrain.Image = image;
                            }

                            worldMap.FillCell(i, j, terrain);
                        }
                    }
                }

                Application.Run(worldMap);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #20
0
ファイル: MapEdit.cs プロジェクト: lep3714/Order-of-the-Paw
        //

        #region methods
        //Draws the array of pictureboxes in the desired place
        private void CreateTileBox(PictureBox[,] pb)
        {
            ResXResourceSet resSet = new ResXResourceSet(resX);

            for (int row = 0; row < SaveBox.GetLength(0); row++)
            {
                for (int col = 0; col < SaveBox.GetLength(1); col++)
                {
                    SaveBox[row, col].Size = new Size(TILE_SIZE / (SaveBox.GetLength(1) / 2), TILE_SIZE / (SaveBox.GetLength(1) / 2));
                    if (SaveBox[row, col].Size.Width > 80)
                    {
                        SaveBox[row, col].Size = new Size(50, 50);
                    }
                    SaveBox[row, col].Location = new Point(279 + (SaveBox[row, col].Size.Width * col), 9 + (SaveBox[row, col].Size.Height * row));
                    SaveBox[row, col].Image    = (System.Drawing.Image)resSet.GetObject("blackpaint");//makes the beginning canvas black
                    SaveBox[row, col].Tag      = "blackpaint";
                    SaveBox[row, col].SizeMode = PictureBoxSizeMode.StretchImage;
                    Controls.Add(SaveBox[row, col]);

                    SaveBox[row, col].MouseDown  += delegate(object sender, MouseEventArgs e){ MapEdit_MouseClick(sender, e); };
                    SaveBox[row, col].MouseEnter += delegate(object sender, EventArgs e) { MapEdit_MouseDrag(sender, e); };
                }
            }
        }
コード例 #21
0
        private static Dictionary <string, string> GetResourceKeyValueList(string resourceFilePath)
        {
            Dictionary <string, string> resourceKeyValues = new Dictionary <string, string>();

            ResXResourceSet resSet = new ResXResourceSet(resourceFilePath);

            IDictionaryEnumerator dict = resSet.GetEnumerator();

            while (dict.MoveNext())
            {
                string key = (string)dict.Key;

                if (dict.Value is string)
                {
                    resourceKeyValues.Add(key, resSet.GetString(key));
                }
                else
                {
                    resourceKeyValues.Add(key, resSet.GetObject(key).ToString());
                }
            }

            return(resourceKeyValues);
        }
コード例 #22
0
        public void CloneValuesTest()
        {
            string key  = "TestBinFile";
            var    path = Combine(Files.GetExecutingPath(), "Resources", "TestResourceResX.resx");
            var    rs   = new ResXResourceSet(path);

            Assert.IsFalse(rs.CloneValues);
            Assert.IsTrue(rs.AutoFreeXmlData);

            // if not cloning values, references are the same for subsequent calls
            Assert.AreSame(rs.GetObject(key), rs.GetObject(key));

            // if cloning values, references are different
            rs.CloneValues = true;
            Assert.AreNotSame(rs.GetObject(key), rs.GetObject(key));

            // but strings are always the same reference
            key = "TestString";
            Assert.AreSame(rs.GetObject(key), rs.GetObject(key));
            Assert.AreSame(rs.GetString(key), rs.GetString(key));
        }
コード例 #23
0
        public void SetRemoveObject()
        {
            var path = Combine(Files.GetExecutingPath(), "Resources", "TestResourceResX.resx");
            var rs   = new ResXResourceSet(path, null);

            // replace
            Assert.IsTrue(rs.GetObject("TestString") is string);
            rs.SetObject("TestString", 1);
            Assert.AreEqual(1, rs.GetObject("TestString"));

            // add new
            Assert.IsNull(rs.GetObject("NotExist"));
            rs.SetObject("NotExist", 2);
            Assert.IsNotNull(rs.GetObject("NotExist"));

            // delete
            rs.RemoveObject("TestString");
            Assert.IsNull(rs.GetObject("TestString"));
            Assert.IsFalse(rs.GetEnumerator().GetKeysEnumerator().Any(e => e == "TestString"));

            // nullifying
            rs.SetObject("NotExist", null);
            Assert.IsNull(rs.GetObject("TestString"));
            Assert.IsTrue(rs.GetEnumerator().GetKeysEnumerator().Any(e => e == "NotExist"));


            // save and reload
            StringBuilder sb = new StringBuilder();

#if NETCOREAPP2_0 || NETCOREAPP3_0
            RemoveUnsupportedItems(rs);
#endif
            rs.Save(new StringWriter(sb));
            var rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()), Path.GetDirectoryName(path));
            AssertItemsEqual(rs, rsReloaded);
        }
コード例 #24
0
        private void btnGo_Click(object sender, EventArgs e)
        {
            foreach (string mainFile in lbMainFile.Items)
            {
                string path, fileName;
                if (!ValidMainFile(mainFile, out path, out fileName))
                {
                    lblResults.Text += "File doesn't exist!" + Environment.NewLine;
                    continue;
                }
                string[] extraLanguages = GetValidLanguageEntries();


                foreach (var lang in extraLanguages)
                {
                    string fullLangPath = Path.Combine(path, LanguifyFileName(fileName, lang));
                    string tempName     = Path.GetTempFileName();
                    using (ResXResourceReader mainReader = new ResXResourceReader(mainFile))
                    {
                        using (ResXResourceWriter writer = new ResXResourceWriter(tempName))
                        {
                            if (File.Exists(fullLangPath))
                            {
                                using (ResXResourceSet langReader = new ResXResourceSet(fullLangPath))
                                {
                                    foreach (DictionaryEntry de in mainReader)
                                    {
                                        object o = langReader.GetObject((string)de.Key);
                                        if (o is String && !string.IsNullOrEmpty((string)o))
                                        {
                                            writer.AddResource((string)de.Key, (string)o);
                                        }
                                        else
                                        {
                                            writer.AddResource((string)de.Key, "-");
                                        }
                                    }
                                }
                            }
                            else
                            {
                                foreach (DictionaryEntry de in mainReader)
                                {
                                    writer.AddResource((string)de.Key, "-");
                                }
                            }
                        }
                    }
                    string newTempFile = "";
                    if (File.Exists(fullLangPath))
                    {
                        newTempFile = Path.GetTempFileName();
                        File.Delete(newTempFile);
                        File.Move(fullLangPath, newTempFile);
                    }
                    try { File.Move(tempName, fullLangPath); }
                    catch { if (newTempFile.Length > 0)
                            {
                                File.Move(newTempFile, fullLangPath);
                            }
                    }
                    if (File.Exists(newTempFile))
                    {
                        File.Delete(newTempFile);
                    }
                }
            }
        }
コード例 #25
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                throw new ArgumentNullException("Source");
            }

            if (!File.Exists(args[0]))
            {
                throw new FileNotFoundException($"Source file not found: {args[0]}");
            }

            string sourceFilename = args[0];

            if (args.Length == 1)
            {
                throw new ArgumentNullException("Target");
            }

            if (!File.Exists(args[1]))
            {
                throw new FileNotFoundException($"Target file not found: {args[1]}");
            }

            string targetFilename = args[1];

            var missingFilename = Path.GetFileNameWithoutExtension(targetFilename)
                                  + "-missing"
                                  + Path.GetExtension(targetFilename);

            var missingCount = 0;
            var foundCount   = 0;

            using (var sourceReader = new ResXResourceReader(sourceFilename)
            {
                UseResXDataNodes = true
            })
            {
                using (var targetSet = new ResXResourceSet(targetFilename))
                {
                    using (var missingWriter = new ResXResourceWriter(missingFilename))
                    {
                        foreach (DictionaryEntry sourceEntry in sourceReader)
                        {
                            var targetEntry = targetSet.GetObject(sourceEntry.Key.ToString());
                            if (targetEntry == null)
                            {
                                missingCount++;
                                Console.WriteLine($"Missing key: '{sourceEntry.Key}'");
                                missingWriter.AddResource((ResXDataNode)sourceEntry.Value);
                            }
                            else
                            {
                                foundCount++;
                            }
                        }
                    }
                }
            }
            Console.WriteLine($"Found {foundCount}, missing {missingCount} out of {foundCount + missingCount} total keys.");
            if (missingCount == 0)
            {
                File.Delete(missingFilename);
            }
            else
            {
                Console.WriteLine($"File '{missingFilename}' generated with the missing keys.");
            }
#if DEBUG
            Console.WriteLine("Hit any key to continue...");
            Console.ReadKey();
#endif
        }
コード例 #26
0
        public void GetObject()
        {
            var path = Combine(Files.GetExecutingPath(), "Resources", "TestResourceResX.resx");
            var rs   = new ResXResourceSet(path, null);

            // string
            Assert.IsInstanceOf <string>(rs.GetObject("TestString"));
            Assert.IsInstanceOf <string>(rs.GetMetaObject("TestString"));
            Assert.AreNotEqual(rs.GetObject("TestString"), rs.GetMetaObject("TestString"));
            Assert.IsTrue(rs.GetString("MultilineString").Contains(Environment.NewLine), "MultilineString should contain the NewLine string");

            // WinForms.FileRef/string
            Assert.IsInstanceOf <string>(rs.GetObject("TestTextFile"));

            // byte array without mime
            Assert.IsInstanceOf <byte[]>(rs.GetObject("TestBytes"));

            // null stored in the compatible way
            Assert.IsNull(rs.GetObject("TestNull"));

            // no mime, parsed from string by type converter
            Assert.IsInstanceOf <Point>(rs.GetObject("TestPoint"));

#if NETFRAMEWORK
            // mime, deserialized by BinaryFormatter
            Assert.IsInstanceOf <ImageListStreamer>(rs.GetObject("TestObjectEmbedded"));
#endif

#if !NETCOREAPP2_0
            // mime, converted from byte array by type converter
            Assert.IsInstanceOf <Bitmap>(rs.GetObject("TestImageEmbedded"));
#endif

            // WinForms.FileRef/byte[]
            Assert.IsInstanceOf <byte[]>(rs.GetObject("TestBinFile"));

            // WinForms.FileRef/MemoryStream
            Assert.IsInstanceOf <MemoryStream>(rs.GetObject("TestSound"));

#if !NETCOREAPP2_0
            // WinForms.FileRef/object created from stream
            Assert.IsInstanceOf <Bitmap>(rs.GetObject("TestImage"));
#endif
        }
コード例 #27
0
        public void Save()
        {
            var path = Path.GetTempPath();
            var rs   = new ResXResourceSet(basePath: path)
            {
                SafeMode = true
            };
            var newFile = Path.GetTempFileName();

            rs.SetObject("fileref", new ResXFileRef(newFile, typeof(string)));
            var filerefRef = ((ResXDataNode)rs.GetObject("fileref")).FileRef;

            Assert.IsTrue(Path.IsPathRooted(filerefRef.FileName));

            var sb = new StringBuilder();

            rs.Save(new StringWriter(sb));

            // path does not change in original resource set after saving
            Assert.IsTrue(Path.IsPathRooted(filerefRef.FileName));

            // if BasePath was specified, the path turns relative on saving
            var rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()), path)
            {
                SafeMode = true
            };
            var filerefCheck = ((ResXDataNode)rsReloaded.GetObject("fileref")).FileRef;

            Assert.IsFalse(Path.IsPathRooted(filerefCheck.FileName));

            // fileref paths are adjusted if BasePath is changed, even the original relative paths
            sb = new StringBuilder();
            string newPath = Path.Combine(path, "subdir");

            rsReloaded.Save(new StringWriter(sb), newBasePath: newPath);
            rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()))
            {
                SafeMode = true
            };
            var filerefCheck2 = ((ResXDataNode)rsReloaded.GetObject("fileref")).FileRef;

            Assert.AreNotEqual(filerefCheck.FileName, filerefCheck2.FileName);

            // on forced embedding the fileRefs are gone
            sb = new StringBuilder();
            rs.Save(new StringWriter(sb), forceEmbeddedResources: true);
            rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()))
            {
                SafeMode = true
            };
            Assert.IsNull(((ResXDataNode)rsReloaded.GetObject("fileref")).FileRef);

            // creating without basePath...
            rs = new ResXResourceSet {
                SafeMode = true
            };
            rs.SetObject("filerefFull", new ResXFileRef(newFile, typeof(string)));
            rs.SetObject("filerefRelative", new ResXFileRef(Path.GetFileName(newFile), typeof(string)));

            // neither original, nor new basePath: all paths remain as it is
            sb = new StringBuilder();
            rs.Save(new StringWriter(sb));
            rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()))
            {
                SafeMode = true
            };
            Assert.AreEqual(((ResXDataNode)rs.GetObject("filerefFull")).FileRef.FileName, ((ResXDataNode)rsReloaded.GetObject("filerefFull")).FileRef.FileName);
            Assert.AreEqual(((ResXDataNode)rs.GetObject("filerefRelative")).FileRef.FileName, ((ResXDataNode)rsReloaded.GetObject("filerefRelative")).FileRef.FileName);

            // no original basePath just a new one: the relative paths are not changed, full paths become relative
            sb = new StringBuilder();
            rs.Save(new StringWriter(sb), newBasePath: path);
            rsReloaded = new ResXResourceSet(new StringReader(sb.ToString()))
            {
                SafeMode = true
            };
            Assert.AreNotEqual(((ResXDataNode)rs.GetObject("filerefFull")).FileRef.FileName, ((ResXDataNode)rsReloaded.GetObject("filerefFull")).FileRef.FileName);
            Assert.IsFalse(Path.IsPathRooted(((ResXDataNode)rsReloaded.GetObject("filerefFull")).FileRef.FileName));
            Assert.AreEqual(((ResXDataNode)rs.GetObject("filerefRelative")).FileRef.FileName, ((ResXDataNode)rsReloaded.GetObject("filerefRelative")).FileRef.FileName);

            File.Delete(newFile);
        }
コード例 #28
0
        public static void prepararImagens()
        {
            ResXResourceSet resxSet = new ResXResourceSet(@"C:\Users\migue\Desktop\SIGOPEA\TCC\View\RecupDados.resx");

            senhaOculta  = (Bitmap)resxSet.GetObject("passwd_20x20", true);
            senhaVisivel = (Bitmap)resxSet.GetObject("passwd_2_20x20", true);
            email        = (Bitmap)resxSet.GetObject("email_32x32", true);
            obs          = (Bitmap)resxSet.GetObject("note_48x48", true);
            agend        = (Bitmap)resxSet.GetObject("appointment_32x32", true);
            foto         = (Bitmap)resxSet.GetObject("camera_48x48", true);
            trab         = (Bitmap)resxSet.GetObject("worker_24x24", true);
            forn         = (Bitmap)resxSet.GetObject("provider_24x24", true);
            salvar       = (Bitmap)resxSet.GetObject("save_24x24", true);
            alterar      = (Bitmap)resxSet.GetObject("edit_24x24", true);
            reg          = (Bitmap)resxSet.GetObject("reg_32x32", true);
        }
コード例 #29
0
        internal static void Load()
        {
            Console.CursorVisible = false;
            if (File.Exists(@".\Save.resx"))
            {
                try
                {
                    using var resxSet       = new ResXResourceSet(@".\Save.resx");
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(GameController_TextResource.Load_Option, resxSet.GetObject("time"));
                    Console.ForegroundColor = ConsoleColor.Black;
                    Console.BackgroundColor = ConsoleColor.Gray;
                    Console.Write(GameController_TextResource.Yes);
                    Console.ResetColor();
                    Console.Write('\t' + GameController_TextResource.No);
                    var        isYes = true;
                    ConsoleKey key;
                    do
                    {
                        key = Console.ReadKey().Key;
                        // ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
                        switch (key)
                        {
                        case ConsoleKey.RightArrow:
                        {
                            if (isYes)
                            {
                                isYes = false;
                                Console.CursorLeft = 0;
                                Console.Write(GameController_TextResource.Yes + '\t');
                                Console.ForegroundColor = ConsoleColor.Black;
                                Console.BackgroundColor = ConsoleColor.Gray;
                                Console.Write(GameController_TextResource.No);
                                Console.ResetColor();
                            }

                            break;
                        }

                        case ConsoleKey.LeftArrow:
                        {
                            if (!isYes)
                            {
                                isYes = true;
                                Console.CursorLeft      = 0;
                                Console.ForegroundColor = ConsoleColor.Black;
                                Console.BackgroundColor = ConsoleColor.Gray;
                                Console.Write(GameController_TextResource.Yes);
                                Console.ResetColor();
                                Console.Write('\t' + GameController_TextResource.No);
                            }

                            break;
                        }
                        }
                    } while (key != ConsoleKey.Enter);

                    if (isYes)
                    {
                        HostList     = (List <Host>)resxSet.GetObject("hosts");
                        SaveLoadList = (List <SaveLoadActions>)resxSet.GetObject("slList");
                        if ((SaveLoadList ?? throw new BrokenSaveException()).Any(sla => !sla.Load(resxSet)))
                        {
                            throw new BrokenSaveException();
                        }
                        Console.Clear();
                        Console.WriteLine(GameController_TextResource.Load);
                        new Terminal(HostList?[0].Sh).Open();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    File.Delete(@".\Save.resx");
                }
            }
            else
            {
                Console.WriteLine(GameController_TextResource.SaveNotExist);
            }

            Console.CursorVisible = true;
        }
コード例 #30
0
        internal static void Initialize()
        {
            if (File.Exists(@".\Save.resx"))
            {
                try
                {
                    using (var resxSet = new ResXResourceSet(@".\Save.resx"))
                    {
                        try
                        {
                            if (resxSet.GetObject("RootKit") != null)
                            {
                                BigFirework.YouDied();
                                return;
                            }
                        }
                        catch
                        {
                            // 忽略掉
                        }

                        HostList     = (List <Host>)resxSet.GetObject("hosts");
                        SaveLoadList = (List <SaveLoadActions>)resxSet.GetObject("slList");
                        if ((SaveLoadList ?? throw new BrokenSaveException()).Any(sla => !sla.Load(resxSet)))
                        {
                            throw new BrokenSaveException();
                        }
                    }

                    if (HostList == null)
                    {
                        throw new BrokenSaveException();
                    }
                }
                catch
                {
                    File.Delete(@".\Save.resx");
                    Initialize();
                }
            }
            else
            {
                var initTask = new Task(() =>
                {
                    HostList = HostStorage.InitializeHost();
                    var rm   = GlobalConfig.ResourceManager;
                    LinkStorage.ReLink(rm);
                    WafServer.FirewallInstall(rm);
                    MailServer.RebuildMails();
                    AutoSploitServer.AddExploit(rm);
                });
                //HostList = HostStorage.InitializeHost();

                //var rm = GlobalConfig.ResourceManager;

                //LinkStorage.ReLink(rm);
                //WafServer.FirewallInstall(rm);
                //MailServer.RebuildMails();
                //AutoSploitServer.AddExploit(rm);

                initTask.Start();

                foreach (var s in GameController_TextResource.BootUp.Replace("\r\n", "\n").Split('\n'))
                {
                    if (s.Trim() == string.Empty)
                    {
                        Thread.Sleep(1000);
                    }

                    Console.WriteLine(s);
                    Thread.Sleep(50);
                }
                initTask.Wait();
                PlotObserver.InitializePlot();
                PlotObserver.StartObserve();
                Console.Clear();
                Thread.Sleep(2000);
            }

            WafServer.FirewallBootUp();
            MediaPlayer.RegisterMediaFile();
            AutoSploit.RegisterExpFile();

            new Terminal(HostList?[0].Sh).Open();
        }