コード例 #1
0
        public void Comment()
        {
            ResXDataNode node = new ResXDataNode("name", (object)null);

            node.Comment = "acomment";
            Assert.AreEqual("acomment", node.Comment, "#A1");
        }
コード例 #2
0
        public void CommentNullToStringEmpty()
        {
            ResXDataNode node = new ResXDataNode("name", (object)null);

            node.Comment = null;
            Assert.AreEqual(String.Empty, node.Comment, "#A1");
        }
コード例 #3
0
ファイル: basepathex1.cs プロジェクト: zhimaqiao51/docs
    private static void CreateXMLResourceFile()
    {
        // Define an array of ResXFileRef objects for images.
        String typeName = String.Format("{0}, {1}", typeof(Bitmap).FullName,
                                        typeof(Bitmap).Assembly.FullName);

        ResXFileRef[] imageRefs =
        { new ResXFileRef(@"images\Akita.jpg",          typeName),
          new ResXFileRef(@"images\Dalmatian.jpg",     typeName),
          new ResXFileRef(@"images\Husky.jpg",         typeName),
          new ResXFileRef(@"images\GreatPyrenees.jpg", typeName),
          new ResXFileRef(@"images\Malamute.jpg",      typeName),
          new ResXFileRef(@"images\newfoundland.jpg",  typeName),
          new ResXFileRef(@"images\Rottweiler.jpg",    typeName) };

        using (ResXResourceWriter resx = new ResXResourceWriter(@".\DogBreeds.resx")) {
            // Add each ResXFileRef object to the resource file.
            foreach (var imageRef in imageRefs)
            {
                // Form resource name from name of image.
                String name = imageRef.FileName;
                name = name.Substring(name.IndexOf(@"\") + 1);
                name = name.Substring(0, name.IndexOf("."));
                ResXDataNode node = new ResXDataNode(name, imageRef);
                resx.AddResource(node);
            }
            resx.AddResource("CreatedBy", typeof(Example).Assembly.FullName);
        }
    }
コード例 #4
0
        public void FileRef()
        {
            ResXFileRef  fileRef = new ResXFileRef("fileName", "Type.Name");
            ResXDataNode node    = new ResXDataNode("name", fileRef);

            Assert.AreEqual(fileRef, node.FileRef, "#A1");
        }
コード例 #5
0
ファイル: basepathex1.cs プロジェクト: zhimaqiao51/docs
    public static void Main()
    {
        CreateXMLResourceFile();

        // Read the resources in the XML resource file.
        ResXResourceReader resx = new ResXResourceReader("DogBreeds.resx");

        Console.WriteLine("Default Base Path: '{0}'", resx.BasePath);
        resx.BasePath = @"C:\Data\";
        Console.WriteLine("Current Base Path: '{0}'\n", resx.BasePath);
        resx.UseResXDataNodes = true;

        IDictionaryEnumerator dict = resx.GetEnumerator();

        AssemblyName[] assemblyNames = { new AssemblyName(typeof(Bitmap).Assembly.FullName) };
        while (dict.MoveNext())
        {
            ResXDataNode node = (ResXDataNode)dict.Value;
            if (node.FileRef != null)
            {
                object image = node.GetValue(assemblyNames);
                Console.WriteLine("{0}: {1} from {2}", dict.Key,
                                  image.GetType().Name, node.FileRef.FileName);
            }
            else
            {
                Console.WriteLine("{0}: {1}", node.Name, node.GetValue((ITypeResolutionService)null));
            }
        }
    }
コード例 #6
0
        void AddButtonEventHandler(object sender, EventArgs e)
        {
            if (scrolledWindow.Children[0] == stringTreeView)
            {
                ResponseType response = (ResponseType)stringDialog.Run();
                stringDialog.Hide();

                if (response == ResponseType.Ok && !string.IsNullOrWhiteSpace(stringDialog.NodeName))
                {
                    var note = new ResXDataNode(stringDialog.NodeName, stringDialog.NodeText)
                    {
                        Comment = stringDialog.NodeComment
                    };
                    this.AddItem(note);
                    editorView.IsDirty = true;
                }

                stringDialog.NodeText    = "";
                stringDialog.NodeName    = "";
                stringDialog.NodeComment = "";

                return;
            }
            else
            {
                //add existing item
                if (openDialog.Run())
                {
                    AddFileAsItem(openDialog.SelectedFile);
                    return;
                }
            }
        }
コード例 #7
0
        public void SetResource(string resourceName, string resourceValue, string resourceComment)
        {
            var item = new ResXDataNode(resourceName, resourceValue);

            item.Comment            = resourceComment;
            Resources[resourceName] = item;
        }
コード例 #8
0
        public void WriteRead1()
        {
            serializable ser = new serializable("aaaaa", "bbbbb");
            ResXDataNode dn  = new ResXDataNode("test", ser);

            dn.Comment = "comment";

            string resXFile = GetResXFileWithNode(dn, "resx.resx");

            bool found            = false;
            ResXResourceReader rr = new ResXResourceReader(resXFile);

            rr.UseResXDataNodes = true;
            IDictionaryEnumerator en = rr.GetEnumerator();

            while (en.MoveNext())
            {
                ResXDataNode node = ((DictionaryEntry)en.Current).Value as ResXDataNode;
                if (node == null)
                {
                    break;
                }
                serializable o = node.GetValue((AssemblyName [])null) as serializable;
                if (o != null)
                {
                    found = true;
                    Assert.AreEqual(ser, o, "#A1");
                    Assert.AreEqual("comment", node.Comment, "#A3");
                }
            }
            rr.Close();

            Assert.IsTrue(found, "#A2 - Serialized object not found on resx");
        }
        public static CodeCompileUnit Create(string resxFile, string baseName, string generatedCodeNamespace, string resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out string[] unmatchable)
        {
            if (resxFile == null)
            {
                throw new ArgumentNullException("resxFile");
            }
            Dictionary <string, ResourceData> resourceList = new Dictionary <string, ResourceData>(StringComparer.InvariantCultureIgnoreCase);

            using (ResXResourceReader reader = new ResXResourceReader(resxFile))
            {
                reader.UseResXDataNodes = true;
                foreach (DictionaryEntry entry in reader)
                {
                    ResXDataNode node = (ResXDataNode)entry.Value;
                    Type         type = Type.GetType(node.GetValueTypeName((AssemblyName[])null));
                    string       valueIfItWasAString = null;
                    if (type == typeof(string))
                    {
                        valueIfItWasAString = (string)node.GetValue((AssemblyName[])null);
                    }
                    ResourceData data = new ResourceData(type, valueIfItWasAString);
                    resourceList.Add((string)entry.Key, data);
                }
            }
            return(InternalCreate(resourceList, baseName, generatedCodeNamespace, resourcesNamespace, codeProvider, internalClass, out unmatchable));
        }
コード例 #10
0
ファイル: frmResXDifferences.cs プロジェクト: alfeg/resxmerge
        private void btnSave_Click(object sender, EventArgs e)
        {
            EnableControls(false);
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                if (FilesToDiff?.Length > 0)
                {
                    sfd.InitialDirectory = Path.GetDirectoryName(FilesToDiff[0]);
                }

                sfd.Filter = "Resource files|*.resx|All files|*.*";
                sfd.ShowDialog();

                if (sfd.FileName != "")
                {
                    String savePath = sfd.FileName;
                    dgv.Cursor = Cursors.WaitCursor;

                    try
                    {
                        if (dgv.IsCurrentCellDirty | dgv.IsCurrentRowDirty)
                        {
                            dgv.EndEdit();
                        }

                        dgv.Sort(colKey, ListSortDirection.Ascending);

                        ResXResourceWriter resX = new ResXResourceWriter(Path.Combine(Directory.GetCurrentDirectory(), savePath));

                        for (int i = 0; i <= dgv.RowCount - 1; i++)
                        {
                            if (dgv.Rows[i].IsNewRow)
                            {
                                continue;
                            }
                            if (chkAutoRemoveBaseOnly.Checked && ((ResXSourceType)dgv.Rows[i].Cells[colSourceVal.Index].Value) == ResXSourceType.BASE)
                            {
                                continue;
                            }

                            ResXDataNode n = new ResXDataNode(Convert.ToString(dgv[colKey.Index, i].Value), dgv[colValue.Index, i].Value)
                            {
                                Comment = Convert.ToString(dgv[colComment.Index, i].Value)
                            };
                            resX.AddResource(n);
                        }
                        resX.Generate();
                        resX.Close();

                        Properties.Settings.Default.AutoRemoveBaseOnly = chkAutoRemoveBaseOnly.Checked;
                        Properties.Settings.Default.Save();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"The ResX file '{savePath}' failed to save properly: " + ex.Message);
                    }
                }
            }
            EnableControls(true);
        }
コード例 #11
0
        private Dictionary <string, Value> Read(string file)
        {
            Dictionary <string, Value> list = new Dictionary <string, Value>();

            using (ResXResourceReader reader = new ResXResourceReader(file)) {
                reader.UseResXDataNodes = true;
                foreach (DictionaryEntry item in reader)
                {
                    ResXDataNode node = (ResXDataNode)item.Value;
                    string       name = node.Name;
                    object       obj  = node.GetValue((ITypeResolutionService)null);
                    if (obj is string text)
                    {
                        Value value = new Value(name, text, node.Comment);
                        list.Add(value.Name, value);
                    }
                    else
                    {
                        Program.Log("File {0} contains unsupported resource {1}", file, name);
                        return(null);
                    }
                }
            }
            return(list);
        }
コード例 #12
0
        bool ProcessItem(ResxGenItem item, ref ResXDataNode node, List <ResXDataNode> allNodes)
        {
            if (NextMessageId < 0)
            {
                return(false);
            }

            if (node.FileRef != null)
            {
                return(false);
            }
            try
            {
                if (typeof(String) != Type.GetType(node.GetValueTypeName(new System.Reflection.AssemblyName[0])))
                {
                    return(false);
                }
            }
            catch { return(false); }

            string hr;

            if (!item.TryGetOption("MessageId", out hr))
            {
                bool hasOptions = node.Comment.IndexOf('#') >= 0;
                node.Comment = String.Format("{0}{1}MessageId={2}", node.Comment, !hasOptions ? " #" : ", ", NextMessageId++).Trim();
                return(true);
            }

            return(false);
        }
コード例 #13
0
        public void CantLoadTypeFromThisAssemblyWithOnlyFullName()
        {
            ResXDataNode node = GetNodeFromResXReader(thisAssemblyConvertableResXWithoutAssemblyName);

            Assert.IsNotNull(node, "#A1");
            object obj = node.GetValue((AssemblyName [])null);
        }
コード例 #14
0
        public void InvalidTypeReturnedFromReader_Exceptions()
        {
            ResXDataNode node = GetNodeFromResXReader(typeconResXInvalidType);

            Assert.IsNotNull(node, "#A1");
            object obj = node.GetValue((AssemblyName [])null);
        }
コード例 #15
0
        public void ErrorWhenAssemblyMissing()
        {
            ResXDataNode node = GetNodeFromResXReader(missingSerializableFromMissingAssembly);

            Assert.IsNotNull(node, "#A1");
            object val = node.GetValue((AssemblyName [])null);
        }
コード例 #16
0
        internal static CodeCompileUnit Create(String resxFile, String baseName, String generatedCodeNamespace, String resourcesNamespace, CodeDomProvider codeProvider, bool internalClass, out String[] unmatchable)
        {
            if (resxFile == null)
            {
                throw new ArgumentNullException("resxFile");
            }

            // Read the resources from a ResX file into a dictionary - name & type name
            Dictionary <String, ResourceData> resourceList = new Dictionary <String, ResourceData>(StringComparer.InvariantCultureIgnoreCase);

            using (ResXResourceReader rr = new ResXResourceReader(resxFile)) {
                rr.UseResXDataNodes = true;
                foreach (DictionaryEntry de in rr)
                {
                    ResXDataNode node          = (ResXDataNode)de.Value;
                    String       typeName      = node.GetValueTypeName((AssemblyName[])null);
                    Type         type          = Type.GetType(typeName);
                    String       valueAsString = node.GetValue((AssemblyName[])null).ToString();
                    ResourceData data          = new ResourceData(type, valueAsString);
                    resourceList.Add((String)de.Key, data);
                }
            }

            // Note we still need to verify the resource names are valid language
            // keywords, etc.  So there's no point to duplicating the code above.

            return(InternalCreate(resourceList, baseName, generatedCodeNamespace, resourcesNamespace, codeProvider, internalClass, out unmatchable));
        }
コード例 #17
0
        private void SetImagesDir(string name, DirectoryInfo dirInfo)
        {
            //Console.WriteLine("----> Dirrectory:" + name);
            ResXResourceWriter writer = GetResourceWriter(name);

            foreach (FileInfo file in dirInfo.GetFiles("*.png"))
            {
                Console.WriteLine("Image file: {0}", file.FullName);
                string       nameRes = "image." + Path.GetFileNameWithoutExtension(file.Name);
                ResXDataNode node    = new ResXDataNode(nameRes, new ResXFileRef(file.FullName,
                                                                                 "System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));
                writer.AddResource(node);
                Console.WriteLine(nameRes);
            }
            foreach (FileInfo file in dirInfo.GetFiles("*.ico"))
            {
                Console.WriteLine("Icon file: {0}", file.FullName);
                string       nameRes = "icon." + Path.GetFileNameWithoutExtension(file.Name);
                ResXDataNode node    = new ResXDataNode(nameRes, new ResXFileRef(file.FullName,
                                                                                 "System.Drawing.Icon, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"));
                writer.AddResource(node);
                Console.WriteLine(nameRes);
            }
            foreach (FileInfo file in dirInfo.GetFiles("*.cur"))
            {
                Console.WriteLine("Cursor file: {0}", file.FullName);
                string       nameRes = "cur." + Path.GetFileNameWithoutExtension(file.Name);
                ResXDataNode node    = new ResXDataNode(nameRes, new ResXFileRef(file.FullName,
                                                                                 "System.Byte[], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"));
                writer.AddResource(node);
                Console.WriteLine(nameRes);
            }
        }
コード例 #18
0
        public static void AddOrUpdateResource(string resourceFilepath, string newKey, string newValue)
        {
            string resourcesFile = resourceFilepath + @"\Resources.resx";
            var    reader        = new ResXResourceReader(resourcesFile); //same fileName

            reader.BasePath = resourceFilepath;                           // this is very important
            var node = reader.GetEnumerator();

            var writer = new ResXResourceWriter(resourcesFile);//same fileName(not new)

            while (node.MoveNext())
            {
                string nodeKey   = node.Key.ToString();
                string nodeValue = node.Value.ToString();
                if (nodeKey == "alter")
                {
                    nodeValue += "\r\n" + newKey;//add new script name
                }
                writer.AddResource(nodeKey, nodeValue);
            }
            var newNode = new ResXDataNode(newKey, newValue);

            writer.AddResource(newNode);
            writer.Generate();
            writer.Close();
        }
コード例 #19
0
        private void translateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string fileName = Path.Combine(Path.GetDirectoryName(openFileDialog1.FileName),
                                               String.Format("{0}.es{1}", Path.GetFileNameWithoutExtension(openFileDialog1.FileName), Path.GetExtension(openFileDialog1.FileName)));
                using (ResXResourceWriter resxWriter = new ResXResourceWriter(fileName))
                {
                    var q = from line in this._srcDictionary.AsQueryable()
                            select line;

                    foreach (var entry in q.ToList())
                    {
                        if (this._dictionary.ContainsKey(entry.Value.ToString()))
                        {
                            var translation = this._dictionary.FirstOrDefault(x => x.Key.ToString().Equals(entry.Value.ToString()));
                            resxWriter.AddResource(entry.Key.ToString(), translation.Value.ToString());
                        }
                        else // translation not found
                        {
                            var node = new ResXDataNode(entry.Key.ToString(), entry.Value.ToString());
                            node.Comment = "to be translated";
                            resxWriter.AddResource(node);
                        }
                    }
                }
                toolStripStatusLabel4.Text = "Done";
            }
            catch (Exception ex)
            {
                toolStripStatusLabel4.Text = ex.Message;
            }
        }
コード例 #20
0
        public void TestConvertToAndFromResXDataNode()
        {
            List <ResXDataNode> nodes;

            using (var reader = new ResXResourceReader(resxFile)
            {
                UseResXDataNodes = true,
            })
            {
                nodes = reader.Cast <DictionaryEntry>().Select(x => (ResXDataNode)x.Value).ToList();
            }
            foreach (var node in nodes)
            {
                ResXNode     icon  = node;
                ResXDataNode node2 = icon;

                var resolution = default(System.ComponentModel.Design.ITypeResolutionService);
                Assert.AreEqual(node.GetValueTypeName(resolution), node2.GetValueTypeName(resolution));
                Assert.AreEqual(node.Name, node2.Name);
                Assert.AreEqual(node.Comment, node2.Comment);
                Assert.AreEqual(node.FileRef, node2.FileRef);

                if (node.FileRef == null)
                {
                    AreEqual(node.GetValue(resolution), node2.GetValue(resolution));
                }
            }
        }
コード例 #21
0
        public ResXDataNode GetNodeFileRefToIcon()
        {
            ResXFileRef  fileRef = new ResXFileRef(TestResourceHelper.GetFullPathOfResource("Test/resources/32x32.ico"), typeof(Icon).AssemblyQualifiedName);
            ResXDataNode node    = new ResXDataNode("test", fileRef);

            return(node);
        }
コード例 #22
0
        public ResXDataNode GetNodeEmdeddedIcon()
        {
            Icon         ico  = new Icon(TestResourceHelper.GetStreamOfResource("Test/resources/32x32.ico"));
            ResXDataNode node = new ResXDataNode("test", ico);

            return(node);
        }
コード例 #23
0
        public void AddResource_WithComment()
        {
            ResXResourceWriter w    = new ResXResourceWriter(fileName);
            ResXDataNode       node = new ResXDataNode("key", "value");

            node.Comment = "comment is preserved";
            w.AddResource(node);
            w.Generate();
            w.Close();

            ResXResourceReader     r       = new ResXResourceReader(fileName);
            ITypeResolutionService typeres = null;

            r.UseResXDataNodes = true;

            int count = 0;

            foreach (DictionaryEntry o in r)
            {
                string key = o.Key.ToString();
                node = (ResXDataNode)o.Value;
                string value   = node.GetValue(typeres).ToString();
                string comment = node.Comment;

                Assert.AreEqual("key", key, "key");
                Assert.AreEqual("value", value, "value");
                Assert.AreEqual("comment is preserved", comment, "comment");
                Assert.AreEqual(0, count, "too many nodes");
                count++;
            }
            r.Close();

            File.Delete(fileName);
        }
コード例 #24
0
        public ResXDataNode GetNodeEmdeddedBytes1To10()
        {
            byte []      someBytes = new byte [] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            ResXDataNode node      = new ResXDataNode("test", someBytes);

            return(node);
        }
コード例 #25
0
        /// <summary>
        /// Saves given node's content into random file in specified directory and returns the file path
        /// </summary>
        protected override string SaveIntoTmpFile(ResXDataNode node, string name, string directory)
        {
            MemoryStream ms       = node.GetValue <MemoryStream>();
            string       filename = name + ".wav";
            string       path     = Path.Combine(directory, filename);

            FileStream fs = null;

            try {
                fs = new FileStream(path, FileMode.Create);

                byte[] buffer = new byte[8192];
                int    read   = 0;
                while ((read = ms.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, read);
                }
            } finally {
                if (fs != null)
                {
                    fs.Close();
                }
                ms.Close();
            }

            return(path);
        }
コード例 #26
0
        public ResXDataNode GetNodeEmdeddedSerializable()
        {
            serializable ser  = new serializable("testName", "testValue");
            ResXDataNode node = new ResXDataNode("test", ser);

            return(node);
        }
コード例 #27
0
        /// <include file='doc\ResXResourceWriter.uex' path='docs/doc[@for="ResXResourceWriter.AddResource3"]/*' />
        /// <devdoc>
        ///     Adds a string resource to the resources.
        /// </devdoc>
        public void AddResource(ResXDataNode node)
        {
            // we're modifying the node as we're adding it to the resxwriter
            // this is BAD, so we clone it. adding it to a writer doesnt change it
            // we're messing with a copy
            ResXDataNode nodeClone = node.DeepClone();

            ResXFileRef fileRef          = nodeClone.FileRef;
            string      modifiedBasePath = BasePath;

            if (!String.IsNullOrEmpty(modifiedBasePath))
            {
                if (!(modifiedBasePath.EndsWith("\\")))
                {
                    modifiedBasePath += "\\";
                }
                if (fileRef != null)
                {
                    fileRef.MakeFilePathRelative(modifiedBasePath);
                }
            }
            DataNodeInfo info = nodeClone.GetDataNodeInfo();

            AddDataRow(DataStr, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment);
        }
コード例 #28
0
        public void DeserializationError()
        {
            ResXDataNode node = GetNodeFromResXReader(serializedResXCorruped);

            Assert.IsNotNull(node, "#A1");
            object val = node.GetValue((AssemblyName [])null);
        }
コード例 #29
0
 /// <devdoc>
 ///     Adds a resource to the resources. If the resource is a string,
 ///     it will be saved that way, otherwise it will be serialized
 ///     and stored as in binary.
 /// </devdoc>
 private void AddDataRow(string elementName, string name, object value)
 {
     Debug.WriteLineIf(ResValueProviderSwitch.TraceVerbose, "  resx: adding resource " + name);
     if (value is string)
     {
         AddDataRow(elementName, name, (string)value);
     }
     else if (value is byte[])
     {
         AddDataRow(elementName, name, (byte[])value);
     }
     else if (value is ResXFileRef)
     {
         ResXFileRef  fileRef = (ResXFileRef)value;
         ResXDataNode node    = new ResXDataNode(name, fileRef, this.typeNameConverter);
         if (fileRef != null)
         {
             fileRef.MakeFilePathRelative(BasePath);
         }
         DataNodeInfo info = node.GetDataNodeInfo();
         AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment);
     }
     else
     {
         ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter);
         DataNodeInfo info = node.GetDataNodeInfo();
         AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment);
     }
 }
コード例 #30
0
        public void CantAccessValueWereOnlyFullNameAndAliasInResXForEmbedded()
        {
            ResXDataNode node = GetNodeFromResXReader(convertableResXAlias);

            Assert.IsNotNull(node, "#A1");
            object obj = node.GetValue((AssemblyName [])null);
        }
コード例 #31
0
 public void AddResource(ResXDataNode node)
 {
 }