private void AddDataRow(string elementName, string name, object value)
 {
     if (value is string)
     {
         this.AddDataRow(elementName, name, (string)value);
     }
     else if (value is byte[])
     {
         this.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(this.BasePath);
         }
         DataNodeInfo dataNodeInfo = node.GetDataNodeInfo();
         this.AddDataRow(elementName, dataNodeInfo.Name, dataNodeInfo.ValueData, dataNodeInfo.TypeName, dataNodeInfo.MimeType, dataNodeInfo.Comment);
     }
     else
     {
         DataNodeInfo info2 = new ResXDataNode(name, value, this.typeNameConverter).GetDataNodeInfo();
         this.AddDataRow(elementName, info2.Name, info2.ValueData, info2.TypeName, info2.MimeType, info2.Comment);
     }
 }
Beispiel #2
0
        private void ParseDataNode(bool meta)
        {
            Hashtable hashtable = ((meta && !useResXDataNodes) ? hashtm : hasht);
            Point_    pos       = new Point_(((IXmlLineInfo)xmlReader).LineNumber, ((IXmlLineInfo)xmlReader).LinePosition);
            string    name      = GetAttribute("name");
            string    type_name = GetAttribute("type");
            string    mime_type = GetAttribute("mimetype");


            string comment = null;
            string value   = GetDataValue(meta, out comment);

            ResXDataNode node = new ResXDataNode(name, mime_type, type_name, value, comment, pos, BasePath);

            if (useResXDataNodes)
            {
                hashtable [name] = node;
                return;
            }

            if (name == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          "Could not find a name for a resource. The resource value was '{0}'.",
                                                          node.GetValue((AssemblyName [])null).ToString()));
            }

            // useResXDataNodes is false, add to dictionary of values
            if (assemblyNames != null)
            {
                try {
                    hashtable [name] = node.GetValue(assemblyNames);
                } catch (TypeLoadException ex) {
                    // different error messages depending on type of resource, hacky solution
                    if (node.handler is TypeConverterFromResXHandler)
                    {
                        hashtable [name] = null;
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            else                 // there is a typeresolver or its null
            {
                try {
                    hashtable [name] = node.GetValue(typeresolver);
                } catch (TypeLoadException ex) {
                    if (node.handler is TypeConverterFromResXHandler)
                    {
                        hashtable [name] = null;
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
        /// <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);
            switch (value)
            {
            case string str:
                AddDataRow(elementName, name, str);
                break;

            case byte[] bytes:
                AddDataRow(elementName, name, bytes);
                break;

            case ResXFileRef fileRef:
            {
                ResXDataNode node = new ResXDataNode(name, fileRef, this.typeNameConverter);
                DataNodeInfo info = node.GetDataNodeInfo();
                AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment);
                break;
            }

            default:
            {
                ResXDataNode node = new ResXDataNode(name, value, this.typeNameConverter);
                DataNodeInfo info = node.GetDataNodeInfo();
                AddDataRow(elementName, info.Name, info.ValueData, info.TypeName, info.MimeType, info.Comment);
                break;
            }
            }
        }
 /// <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);
     }
 }
        /// <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);
        }
        public void AddResource(ResXDataNode node)
        {
            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            if (writer == null)
            {
                InitWriter();
            }

            if (node.IsWritable)
            {
                WriteWritableNode(node);
            }
            else if (node.FileRef != null)
            {
                AddResource(node.Name, node.FileRef, node.Comment);
            }
            else
            {
                AddResource(node.Name, node.GetValue((AssemblyName [])null), node.Comment);
            }
        }
		public void Update(ResxTranslatorTableRow row, ResXDataNode entry, bool isSource = true)
		{
			try
			{
				if (null == row) return;

				if (isSource)
				{
					// ソース
					row.SourceValue = entry.GetValue((ITypeResolutionService)null).ToString();
				}
				else
				{
					// ターゲット
					row.TargetValue = entry.GetValue((ITypeResolutionService)null).ToString();
				}

				// コメント
				if (string.IsNullOrWhiteSpace(row.Comment))
				{
					row.Comment = entry.Comment;
				}
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
			}
		}
		public void Add(ResXDataNode entry, bool isSource = true)
		{
			try
			{
				if (isSource)
				{
					// ソース
					this.ResxTranslatorTable.AddResxTranslatorTableRow(
						entry.Name,
						entry.GetValue((ITypeResolutionService)null).ToString(),
						string.Empty,
						entry.Comment
					);
				}
				else
				{
					// ターゲット
					this.ResxTranslatorTable.AddResxTranslatorTableRow(
						entry.Name,
						string.Empty,
						entry.GetValue((ITypeResolutionService)null).ToString(),
						entry.Comment
					);
				}
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
			}
		}
		public void ITRSNotUsedWhenNodeCreatedNew ()
		{
			ResXDataNode node;
			node = new ResXDataNode ("along", 34L);

			string returnedType = node.GetValueTypeName (new ReturnIntITRS ());
			Assert.AreEqual ((typeof (long)).AssemblyQualifiedName, returnedType, "#A1");
		}
		public void ITRSNotUsedWhenCreatedNew ()
		{
			ResXDataNode node;
			node = new ResXDataNode ("along", 34L);

			object obj = node.GetValue (new ReturnIntITRS ());
			Assert.IsInstanceOfType (typeof (long), obj, "#A1");
		}
		public void ITRSUsedWithNodeFromReader ()
		{
			ResXDataNode returnedNode, originalNode;
			originalNode = new ResXDataNode ("aNumber", 23L);
			returnedNode = GetNodeFromResXReader (originalNode);

			Assert.IsNotNull (returnedNode, "#A1");
			string returnedType = returnedNode.GetValueTypeName (new ReturnIntITRS ());
			Assert.AreEqual ((typeof (Int32)).AssemblyQualifiedName, returnedType, "#A2");
		}
Beispiel #12
0
 /// <summary>
 /// May return null.
 /// </summary>
 public virtual ResXDataNode ToResXDataNode()
 {
     ResXDataNode result = null;
     
     if (!String.IsNullOrEmpty(_name)) {
         result = new ResXDataNode(_name, _value);
         if (!String.IsNullOrEmpty(Metadata_Comment)) result.Comment = Metadata_Comment;
     }
     return result;
 }
		public void ITRSUsedEachTimeWhenNodeFromReader ()
		{
			ResXDataNode returnedNode, originalNode;
			originalNode = new ResXDataNode ("aNumber", 23L);
			returnedNode = GetNodeFromResXReader (originalNode);

			Assert.IsNotNull (returnedNode, "#A1");
			string newType = returnedNode.GetValueTypeName (new ReturnIntITRS ());
			Assert.AreEqual (typeof (int).AssemblyQualifiedName, newType, "#A2");
			string origType = returnedNode.GetValueTypeName ((ITypeResolutionService) null);
			Assert.AreEqual (typeof (long).AssemblyQualifiedName, origType, "#A3");				
		}
 public void BuildResX(string outputPath)
 {
     using (ResXResourceWriter w2 = new ResXResourceWriter(outputPath))
     {
         foreach (Item item in _items)
         {
             ResXDataNode node = new ResXDataNode(item.Name, item.Value);
             node.Comment = item.Comment;
             w2.AddResource(item.Name, node);
         }
     }
 }
		public void ResXNullRef_WriteBack ()
		{
			ResXDataNode node = new ResXDataNode ("NullRef", (object) null);
			node.Comment = "acomment";
			ResXDataNode returnedNode = GetNodeFromResXReader (node);
			Assert.IsNotNull (returnedNode, "#A1");
			Assert.IsNull (returnedNode.GetValue ((AssemblyName []) null), "#A2");
			Assert.AreEqual ("acomment", returnedNode.Comment,"#A3");
			ResXDataNode finalNode = GetNodeFromResXReader (returnedNode);
			Assert.IsNotNull (finalNode, "#A4");
			Assert.IsNull (finalNode.GetValue ((AssemblyName []) null), "#A5");
			Assert.AreEqual ("acomment", finalNode.Comment,"#A6");
		}
        public StringEntry(ResourceCatalog _owner, ResXDataNode _node, bool isMeta)
        {
            if (_node == null)
                throw new ArgumentNullException ("node");
            if (!_node.GetValueTypeName ((AssemblyName []) null).StartsWith ("System.String, mscorlib"))
                throw new ArgumentException ("node","Should be string resource");
            if (_node.FileRef != null)
                throw new ArgumentException ("node", "FileRef should not be set");
            if (_owner == null)
                throw new ArgumentNullException ("owner");

            IsMeta = isMeta;
            Owner = _owner;
            node = _node;
            SetRelativePos ();
        }
        public IconEntry(ResourceCatalog _owner, ResXDataNode _node, bool isMeta)
        {
            if (_node == null)
                throw new ArgumentNullException ("node");

            string nodeTypeName = _node.GetValueTypeName ((AssemblyName []) null);
            if (!nodeTypeName.StartsWith ("System.Drawing.Icon, System.Drawing"))
                throw new ArgumentException ("node","Invalid resource type");

            if (_owner == null)
                throw new ArgumentNullException ("owner");
            IsMeta = isMeta;
            Owner = _owner;
            node = _node;
            SetRelativePos ();
        }
Beispiel #18
0
        // <devdoc>
        // this is a deep clone
        //</devdoc>
        internal ResXDataNode DeepClone()
        {
            ResXDataNode result = new ResXDataNode();

            result.nodeInfo = (this.nodeInfo != null) ? this.nodeInfo.Clone() : null; // nodeinfo is just made up of immutable objects, we don't need to clone it
            result.name     = this.name;
            result.comment  = this.comment;

            result.typeName            = this.typeName;
            result.fileRefFullPath     = this.fileRefFullPath;
            result.fileRefType         = this.fileRefType;
            result.fileRefTextEncoding = this.fileRefTextEncoding;
            result.value             = this.value; // we don't clone the value, because we don't know how
            result.fileRef           = (this.fileRef != null) ? this.fileRef.Clone() : null;
            result.typeNameConverter = this.typeNameConverter;
            return(result);
        }
 public OtherEmbeddedEntry(ResourceCatalog _owner, string _name, object _value, bool isMeta)
 {
     if (_name == null)
         throw new ArgumentNullException ("name");
     if (_name == String.Empty)
         throw new ArgumentException ("name", "Name should not be empty");
     if (_value == null)
         throw new ArgumentNullException ("value");
     if (_value is string || _value is Icon || _value is Bitmap || _value is MemoryStream)
         throw new ArgumentException ("value", "Invalid type");
     if (_owner == null)
         throw new ArgumentNullException ("owner");
     IsMeta = isMeta;
     Owner = _owner;
     node = new ResXDataNode (_name,_value);
     SetRelativePos ();
 }
Beispiel #20
0
		protected ResXDataNode GetNodeFromResXReader (ResXDataNode node)
		{
			StringWriter sw = new StringWriter ();
			using (ResXResourceWriter writer = new ResXResourceWriter (sw)) {
				writer.AddResource (node);
			}

			StringReader sr = new StringReader (sw.GetStringBuilder ().ToString ());

			using (ResXResourceReader reader = new ResXResourceReader (sr)) {
				reader.UseResXDataNodes = true;
				IDictionaryEnumerator enumerator = reader.GetEnumerator ();
				enumerator.MoveNext ();

				return ((DictionaryEntry) enumerator.Current).Value as ResXDataNode;
			}
		}
        public StringEntry(ResourceCatalog _owner, string _name, string _value, string _comment, bool isMeta)
        {
            if (_name == null)
                throw new ArgumentNullException ("name");
            if (_name == String.Empty)
                throw new ArgumentException ("name","Should not be empty");
            if (_value == null)
                throw new ArgumentNullException ("value");
            if (!(_value is String))
                throw new ArgumentException ("value", "Should be string resource");
            if (_owner == null)
                throw new ArgumentNullException ("owner");

            IsMeta = isMeta;
            Owner = _owner;
            node = new ResXDataNode (_name, _value); //FIXME: perhaps shouldn't create node yet
            node.Comment = _comment;
            SetRelativePos ();
        }
        public BinaryOrStringEntry(ResourceCatalog _owner, ResXDataNode _node, bool isMeta)
        {
            if (_node == null)
                throw new ArgumentNullException ("node");
            if (_node.FileRef == null)
                throw new ArgumentNullException ("node","FileRef should be set");

            string nodeTypeName = _node.GetValueTypeName ((AssemblyName []) null);
            if (!nodeTypeName.StartsWith ("System.String, mscorlib") &&
                !nodeTypeName.StartsWith ("System.Byte[], mscorlib"))
                throw new ArgumentException ("node","Only string or byte[] TypeName allowed");

            if (_owner == null)
                throw new ArgumentNullException ("owner");
            IsMeta = isMeta;
            Owner = _owner;
            node = _node;
            SetRelativePos ();
        }
        public IconEntry(ResourceCatalog _owner, string _name, 
		                       string _fileName, bool isMeta)
        {
            if (_name == null)
                throw new ArgumentNullException ("name");
            if (_name == String.Empty)
                throw new ArgumentException ("name", "should not be empty");
            if (_fileName == null)
                throw new ArgumentNullException ("fileName");
            if (!(_fileName.EndsWith (".ico")))
                throw new ArgumentException ("fileName", "must point to a .ico file");
            if (_owner == null)
                throw new ArgumentNullException ("owner");

            IsMeta = isMeta;
            Owner = _owner;

            node = new ResXDataNode (_name, new ResXFileRef (_fileName, typeof (Icon).AssemblyQualifiedName)); // same ver as MD
            SetRelativePos ();
        }
        public OtherFileEntry(ResourceCatalog _owner, ResXDataNode _node, bool isMeta)
        {
            if (_node == null)
                throw new ArgumentNullException ("node");
            if (_node.FileRef == null)
                throw new ArgumentNullException ("node","FileRef should be set");

            string nodeTypeName = _node.GetValueTypeName ((AssemblyName []) null);
            if (nodeTypeName.StartsWith ("System.String, mscorlib") ||
                nodeTypeName.StartsWith ("System.Drawing.Bitmap, System.Drawing") ||
                nodeTypeName.StartsWith ("System.Drawing.Icon, System.Drawing") ||
                nodeTypeName.StartsWith ("System.IO.MemoryStream, mscorlib"))
                throw new ArgumentException ("node","Invalid resource type");

            if (_owner == null)
                throw new ArgumentNullException ("owner");
            IsMeta = isMeta;
            Owner = _owner;
            node = _node;
            SetRelativePos ();
        }
        public void AddResource(ResXDataNode node)
        {
            ResXDataNode node2    = node.DeepClone();
            ResXFileRef  fileRef  = node2.FileRef;
            string       basePath = this.BasePath;

            if (!string.IsNullOrEmpty(basePath))
            {
                if (!basePath.EndsWith(@"\"))
                {
                    basePath = basePath + @"\";
                }
                if (fileRef != null)
                {
                    fileRef.MakeFilePathRelative(basePath);
                }
            }
            DataNodeInfo dataNodeInfo = node2.GetDataNodeInfo();

            this.AddDataRow("data", dataNodeInfo.Name, dataNodeInfo.ValueData, dataNodeInfo.TypeName, dataNodeInfo.MimeType, dataNodeInfo.Comment);
        }
        /*
         * //adapted from MonoDevelop.Core
         * unsafe static string AbsoluteToRelativePath (string baseDirectoryPath, string absPath)
         *      {
         *              if (string.IsNullOrEmpty (baseDirectoryPath))
         *                      return absPath;
         *
         *              baseDirectoryPath = baseDirectoryPath.TrimEnd (Path.DirectorySeparatorChar);
         *
         *              fixed (char* bPtr = baseDirectoryPath, aPtr = absPath) {
         *                      var bEnd = bPtr + baseDirectoryPath.Length;
         *                      var aEnd = aPtr + absPath.Length;
         *                      char* lastStartA = aEnd;
         *                      char* lastStartB = bEnd;
         *
         *                      int indx = 0;
         *                      // search common base path
         *                      var a = aPtr;
         *                      var b = bPtr;
         *                      while (a < aEnd) {
         *                              if (*a != *b)
         *                                      break;
         *                              if (IsSeparator (*a)) {
         *                                      indx++;
         *                                      lastStartA = a + 1;
         *                                      lastStartB = b;
         *                              }
         *                              a++;
         *                              b++;
         *                              if (b >= bEnd) {
         *                                      if (a >= aEnd || IsSeparator (*a)) {
         *                                              indx++;
         *                                              lastStartA = a + 1;
         *                                              lastStartB = b;
         *                                      }
         *                                      break;
         *                              }
         *                      }
         *                      if (indx == 0)
         *                              return absPath;
         *
         *                      if (lastStartA >= aEnd)
         *                              return ".";
         *
         *                      // handle case a: some/path b: some/path/deeper...
         *                      if (a >= aEnd) {
         *                              if (IsSeparator (*b)) {
         *                                      lastStartA = a + 1;
         *                                      lastStartB = b;
         *                              }
         *                      }
         *
         *                      // look how many levels to go up into the base path
         *                      int goUpCount = 0;
         *                      while (lastStartB < bEnd) {
         *                              if (IsSeparator (*lastStartB))
         *                                      goUpCount++;
         *                              lastStartB++;
         *                      }
         *                      var size = goUpCount * 2 + goUpCount + aEnd - lastStartA;
         *                      var result = new char [size];
         *                      fixed (char* rPtr = result) {
         *                              // go paths up
         *                              var r = rPtr;
         *                              for (int i = 0; i < goUpCount; i++) {
         *(r++) = '.';
         *(r++) = '.';
         *(r++) = Path.DirectorySeparatorChar;
         *                              }
         *                              // copy the remaining absulute path
         *                              while (lastStartA < aEnd)
         *(r++) = *(lastStartA++);
         *                      }
         *                      return new string (result);
         *              }
         *      }
         */

        // avoids instantiating objects
        void WriteWritableNode(ResXDataNode node)
        {
            writer.WriteStartElement("data");
            writer.WriteAttributeString("name", node.Name);
            if (!(node.Type == null || node.Type.Equals(String.Empty)))
            {
                writer.WriteAttributeString("type", node.Type);
            }
            if (!(node.MimeType == null || node.MimeType.Equals(String.Empty)))
            {
                writer.WriteAttributeString("mimetype", node.MimeType);
            }
            writer.WriteStartElement("value");
            writer.WriteString(node.DataString);
            writer.WriteEndElement();
            if (!(node.Comment == null || node.Comment.Equals(String.Empty)))
            {
                writer.WriteStartElement("comment");
                writer.WriteString(node.Comment);
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
            writer.WriteWhitespace("\n  ");
        }
Beispiel #27
0
		public void ConstructorEx3 ()
		{
			ResXDataNode d = new ResXDataNode ("", (object) null);
		}
Beispiel #28
0
		public void ConstructorEx2B ()
		{
			ResXDataNode d = new ResXDataNode ("aname", (ResXFileRef) null);
		}
Beispiel #29
0
		string GetResXFileWithNode (ResXDataNode node, string filename)
		{
			string fullfileName;

			_tempDirectory = Path.Combine (Path.GetTempPath (), "ResXDataNodeTest");
			_otherTempDirectory = Path.Combine (_tempDirectory, "in");
			if (!Directory.Exists (_otherTempDirectory)) {
				Directory.CreateDirectory (_otherTempDirectory);
			}

			fullfileName = Path.Combine (_tempDirectory, filename);

			using (ResXResourceWriter writer = new ResXResourceWriter (fullfileName)) {
				writer.AddResource (node);
			}

			return fullfileName;
		}
Beispiel #30
0
		public void BasePathSetOnResXResourceReaderDoesAffectResXDataNode ()
		{
			ResXFileRef fileRef = new ResXFileRef ("file.name", "type.name");
			ResXDataNode node = new ResXDataNode("anode", fileRef);
			string resXFile = GetResXFileWithNode (node, "afilename.xxx");

			using (ResXResourceReader rr = new ResXResourceReader (resXFile)) {
				rr.BasePath = "basePath";
				rr.UseResXDataNodes = true;
				IDictionaryEnumerator en = rr.GetEnumerator ();
				en.MoveNext ();

				ResXDataNode returnedNode = ((DictionaryEntry) en.Current).Value as ResXDataNode;

				Assert.IsNotNull (node, "#A1");
				Assert.AreEqual (Path.Combine ("basePath", "file.name"), returnedNode.FileRef.FileName, "#A2");
			}
		}
Beispiel #31
0
		public void ITRSPassedToResourceReaderDoesNotAffectResXDataNode_Serializable ()
		{
			serializable ser = new serializable ("aaaaa", "bbbbb");
			ResXDataNode dn = new ResXDataNode ("test", ser);
			
			string resXFile = GetResXFileWithNode (dn,"resx.resx");

			ResXResourceReader rr = new ResXResourceReader (resXFile, new ReturnSerializableSubClassITRS ());
			rr.UseResXDataNodes = true;
			IDictionaryEnumerator en = rr.GetEnumerator ();
			en.MoveNext ();

			ResXDataNode node = ((DictionaryEntry) en.Current).Value as ResXDataNode;

			Assert.IsNotNull (node, "#A1");

			object o = node.GetValue ((AssemblyName []) null);

			Assert.IsNotInstanceOfType (typeof (serializableSubClass), o, "#A2");
			Assert.IsInstanceOfType (typeof (serializable), o, "#A3");
			rr.Close ();
		}
Beispiel #32
0
		public void ITRSPassedToResourceReaderDoesNotAffectResXDataNode_TypeConverter ()
		{
			ResXDataNode dn = new ResXDataNode ("test", 34L);
			
			string resXFile = GetResXFileWithNode (dn,"resx.resx");

			ResXResourceReader rr = new ResXResourceReader (resXFile, new ReturnIntITRS ());
			rr.UseResXDataNodes = true;
			IDictionaryEnumerator en = rr.GetEnumerator ();
			en.MoveNext ();

			ResXDataNode node = ((DictionaryEntry) en.Current).Value as ResXDataNode;
			
			Assert.IsNotNull (node, "#A1");

			object o = node.GetValue ((AssemblyName []) null);

			Assert.IsInstanceOfType (typeof (long), o, "#A2");
			Assert.AreEqual (34L, o, "#A3");

			rr.Close ();
		}
        private void ParseDataNode(XmlTextReader reader, bool isMetaData)
        {
            DataNodeInfo nodeInfo = new DataNodeInfo
            {
                Name = reader[ResXResourceWriter.NameStr]
            };

            string typeName = reader[ResXResourceWriter.TypeStr];

            string       alias        = null;
            AssemblyName assemblyName = null;

            if (!string.IsNullOrEmpty(typeName))
            {
                alias = GetAliasFromTypeName(typeName);
            }

            if (!string.IsNullOrEmpty(alias))
            {
                assemblyName = _aliasResolver.ResolveAlias(alias);
            }

            if (assemblyName != null)
            {
                nodeInfo.TypeName = GetTypeFromTypeName(typeName) + ", " + assemblyName.FullName;
            }
            else
            {
                nodeInfo.TypeName = reader[ResXResourceWriter.TypeStr];
            }

            nodeInfo.MimeType = reader[ResXResourceWriter.MimeTypeStr];

            bool finishedReadingDataNode = false;

            nodeInfo.ReaderPosition = GetPosition(reader);
            while (!finishedReadingDataNode && reader.Read())
            {
                if (reader.NodeType == XmlNodeType.EndElement && (reader.LocalName.Equals(ResXResourceWriter.DataStr) || reader.LocalName.Equals(ResXResourceWriter.MetadataStr)))
                {
                    // we just found </data>, quit or </metadata>
                    finishedReadingDataNode = true;
                }
                else
                {
                    // could be a <value> or a <comment>
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name.Equals(ResXResourceWriter.ValueStr))
                        {
                            WhitespaceHandling oldValue = reader.WhitespaceHandling;
                            try
                            {
                                // based on the documentation at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemxmlxmltextreaderclasswhitespacehandlingtopic.asp
                                // this is ok because:
                                // "Because the XmlTextReader does not have DTD information available to it,
                                // SignificantWhitepsace nodes are only returned within the an xml:space='preserve' scope."
                                // the xml:space would not be present for anything else than string and char (see ResXResourceWriter)
                                // so this would not cause any breaking change while reading data from Everett (we never outputed
                                // xml:space then) or from whidbey that is not specifically either a string or a char.
                                // However please note that manually editing a resx file in Everett and in Whidbey because of the addition
                                // of xml:space=preserve might have different consequences...
                                reader.WhitespaceHandling = WhitespaceHandling.Significant;
                                nodeInfo.ValueData        = reader.ReadString();
                            }
                            finally
                            {
                                reader.WhitespaceHandling = oldValue;
                            }
                        }
                        else if (reader.Name.Equals(ResXResourceWriter.CommentStr))
                        {
                            nodeInfo.Comment = reader.ReadString();
                        }
                    }
                    else
                    {
                        // weird, no <xxxx> tag, just the inside of <data> as text
                        nodeInfo.ValueData = reader.Value.Trim();
                    }
                }
            }

            if (nodeInfo.Name == null)
            {
                throw new ArgumentException(string.Format(SR.InvalidResXResourceNoName, nodeInfo.ValueData));
            }

            ResXDataNode dataNode = new ResXDataNode(nodeInfo, BasePath);

            if (UseResXDataNodes)
            {
                _resData[nodeInfo.Name] = dataNode;
            }
            else
            {
                IDictionary data = (isMetaData ? _resMetadata : _resData);
                if (_assemblyNames == null)
                {
                    data[nodeInfo.Name] = dataNode.GetValue(_typeResolver);
                }
                else
                {
                    data[nodeInfo.Name] = dataNode.GetValue(_assemblyNames);
                }
            }
        }
Beispiel #34
0
		public void ConstructorEx6 ()
		{
			ResXDataNode d = new ResXDataNode ("name", new notserializable ());
		}
Beispiel #35
0
		public void ConstructorEx4 ()
		{
			ResXDataNode d = new ResXDataNode ("", (ResXFileRef) null);
		}
        private void ParseDataNode(XmlTextReader reader, bool isMetaData)
        {
            DataNodeInfo nodeInfo = new DataNodeInfo {
                Name = reader["name"]
            };
            string       str = reader["type"];
            string       aliasFromTypeName = null;
            AssemblyName name = null;

            if (!string.IsNullOrEmpty(str))
            {
                aliasFromTypeName = this.GetAliasFromTypeName(str);
            }
            if (!string.IsNullOrEmpty(aliasFromTypeName))
            {
                name = this.aliasResolver.ResolveAlias(aliasFromTypeName);
            }
            if (name != null)
            {
                nodeInfo.TypeName = this.GetTypeFromTypeName(str) + ", " + name.FullName;
            }
            else
            {
                nodeInfo.TypeName = reader["type"];
            }
            nodeInfo.MimeType = reader["mimetype"];
            bool flag = false;

            nodeInfo.ReaderPosition = this.GetPosition(reader);
            while (!flag && reader.Read())
            {
                if ((reader.NodeType == XmlNodeType.EndElement) && (reader.LocalName.Equals("data") || reader.LocalName.Equals("metadata")))
                {
                    flag = true;
                }
                else
                {
                    if (reader.NodeType == XmlNodeType.Element)
                    {
                        if (reader.Name.Equals("value"))
                        {
                            WhitespaceHandling whitespaceHandling = reader.WhitespaceHandling;
                            try
                            {
                                reader.WhitespaceHandling = WhitespaceHandling.Significant;
                                nodeInfo.ValueData        = reader.ReadString();
                                continue;
                            }
                            finally
                            {
                                reader.WhitespaceHandling = whitespaceHandling;
                            }
                        }
                        if (reader.Name.Equals("comment"))
                        {
                            nodeInfo.Comment = reader.ReadString();
                        }
                        continue;
                    }
                    nodeInfo.ValueData = reader.Value.Trim();
                }
            }
            if (nodeInfo.Name == null)
            {
                throw new ArgumentException(System.Windows.Forms.SR.GetString("InvalidResXResourceNoName", new object[] { nodeInfo.ValueData }));
            }
            ResXDataNode node = new ResXDataNode(nodeInfo, this.BasePath);

            if (this.UseResXDataNodes)
            {
                this.resData[nodeInfo.Name] = node;
            }
            else
            {
                IDictionary dictionary = isMetaData ? this.resMetadata : this.resData;
                if (this.assemblyNames == null)
                {
                    dictionary[nodeInfo.Name] = node.GetValue(this.typeResolver);
                }
                else
                {
                    dictionary[nodeInfo.Name] = node.GetValue(this.assemblyNames);
                }
            }
        }
Beispiel #37
0
 public void AddResource(ResXDataNode node)
 {
     throw null;
 }
Beispiel #38
0
        private void ParseDataNode(bool meta)
        {
            Hashtable hashtable = ((meta && !useResXDataNodes) ? hashtm : hasht);
            Point     pos       = new Point(xmlReader.LineNumber, xmlReader.LinePosition);
            string    name      = GetAttribute("name");
            string    type_name = GetAttribute("type");
            string    mime_type = GetAttribute("mimetype");

            Type type = type_name == null ? null : ResolveType(type_name);

            if (type_name != null && type == null)
            {
                throw new ArgumentException(String.Format(
                                                "The type '{0}' of the element '{1}' could not be resolved.", type_name, name));
            }

            if (type == typeof(ResXNullRef))
            {
                if (useResXDataNodes)
                {
                    hashtable [name] = new ResXDataNode(name, null, pos);
                }
                else
                {
                    hashtable [name] = null;
                }
                return;
            }

            string comment = null;
            string value   = GetDataValue(meta, out comment);
            object obj     = null;

            if (mime_type != null && mime_type.Length > 0)
            {
                if (mime_type == ResXResourceWriter.BinSerializedObjectMimeType)
                {
                    byte []         data = Convert.FromBase64String(value);
                    BinaryFormatter f    = new BinaryFormatter();
                    using (MemoryStream s = new MemoryStream(data)) {
                        obj = f.Deserialize(s);
                    }
                }
                else if (mime_type == ResXResourceWriter.ByteArraySerializedObjectMimeType)
                {
                    if (type != null)
                    {
                        TypeConverter c = TypeDescriptor.GetConverter(type);
                        if (c.CanConvertFrom(typeof(byte [])))
                        {
                            obj = c.ConvertFrom(Convert.FromBase64String(value));
                        }
                    }
                }
            }
            else if (type != null)
            {
                if (type == typeof(byte []))
                {
                    obj = Convert.FromBase64String(value);
                }
                else
                {
                    TypeConverter c = TypeDescriptor.GetConverter(type);
                    if (c.CanConvertFrom(typeof(string)))
                    {
                        if (BasePath != null && type == typeof(ResXFileRef))
                        {
                            string [] parts = ResXFileRef.Parse(value);
                            parts [0] = Path.Combine(BasePath, parts [0]);
                            obj       = c.ConvertFromInvariantString(string.Join(";", parts));
                        }
                        else
                        {
                            obj = c.ConvertFromInvariantString(value);
                        }
                    }
                }
            }
            else
            {
                obj = value;
            }

            if (name == null)
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
                                                          "Could not find a name for a resource. The resource value "
                                                          + "was '{0}'.", obj));
            }
            if (useResXDataNodes)
            {
                ResXDataNode dataNode = new ResXDataNode(name, obj, pos);
                dataNode.Comment = comment;
                hashtable [name] = dataNode;
            }
            else
            {
                hashtable [name] = obj;
            }
        }
Beispiel #39
0
		public void ConstructorEx5 ()
		{
			ResXDataNode d = new ResXDataNode ("", new ResXFileRef ("filename", "typename"));
		}
Beispiel #40
0
 public void AddResource(ResXDataNode node)
 {
     AddResource(node.Name, node.Value, node.Comment);
 }
Beispiel #41
0
		public void Name ()
		{
			ResXDataNode node = new ResXDataNode ("startname", (object) null);
			Assert.AreEqual ("startname", node.Name, "#A1");
			node.Name = "newname";
			Assert.AreEqual ("newname", node.Name, "#A2");
		}
Beispiel #42
0
		public void NullObjectReturnedFromResXGetValueTypeNameReturnsObject ()
		{
			ResXDataNode node = new ResXDataNode ("aname", (object) null);
			ResXDataNode returnedNode = GetNodeFromResXReader (node);
			Assert.IsNotNull (returnedNode, "#A1");
			Assert.IsNull (returnedNode.GetValue ((AssemblyName []) null), "#A2");
			string type = returnedNode.GetValueTypeName ((AssemblyName []) null);
			Assert.AreEqual (typeof (object).AssemblyQualifiedName, type, "#A3");
		}
		public void AddResource (ResXDataNode node)
		{
			AddResource (node.Name, node.Value, node.Comment);
		}
Beispiel #44
0
		public void DoesNotRequireResXFileToBeOpen_Serializable ()
		{
			serializable ser = new serializable ("aaaaa", "bbbbb");
			ResXDataNode dn = new ResXDataNode ("test", ser);
			
			string resXFile = GetResXFileWithNode (dn,"resx.resx");

			ResXResourceReader rr = new ResXResourceReader (resXFile);
			rr.UseResXDataNodes = true;
			IDictionaryEnumerator en = rr.GetEnumerator ();
			en.MoveNext (); 

			ResXDataNode node = ((DictionaryEntry) en.Current).Value as ResXDataNode;
			rr.Close ();

			File.Delete ("resx.resx");
			Assert.IsNotNull (node,"#A1");

			serializable o = node.GetValue ((AssemblyName []) null) as serializable;
			Assert.IsNotNull (o, "#A2");
		}