Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

VS.NET CodeDOM-Based Custom Tool for String Resource Management

, 22 Jun 2004
A VS.NET custom tool, created with the help of CodeDOM and EnvDTE, used to facilitate management of resource strings via IntelliSense and error checking in VS.NET environment.
resourceclassgenerator.zip
ResourceClassGenerator
redist
ResourceClassGenerator.dll
ResourceClassGenerator.csproj.user
TestCSharp
App.ico
bin
Debug
de
en
Release
de
TestCSharp.resources.dll
en
TestCSharp.resources.dll
TestCSharp.exe
Resources
TestCSharp.csproj.user
TestVB
bin
de
TestVB.resources.dll
en
TestVB.resources.dll
TestVB.exe
Resources
TestVB.vbproj.user
resourceclassgenerator_10.zip
ResourceClassGenerator.dll
ResourceClassGenerator.csproj.user
App.ico
TestCSharp.resources.dll
TestCSharp.resources.dll
TestCSharp.exe
TestCSharp.csproj.user
TestVB.resources.dll
TestVB.resources.dll
TestVB.exe
TestVB.vbproj.user
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.CodeDom;
using System.CodeDom.Compiler;
using CustomToolGenerator; // vs.net\Common7\IDE\Microsoft.VSDesigner.dll
using System.Windows.Forms;
using System.Resources;
using System.IO;
using System.Collections;
using EnvDTE;
using System.Text.RegularExpressions;

namespace CustomTools
{

	/// <summary>
	/// Summary description for ResourceKeysGenerator
	/// </summary>
	[Guid("8442788C-A1A7-4475-A0C6-C2B83BD4221F")]
	public class ResourceClassGenerator : BaseCodeGeneratorWithSite
	{
		protected override byte[] GenerateCode(string fileName, string fileContents)
		{
			ProjectItem projItem = (ProjectItem)GetService(typeof(ProjectItem));
			Project proj = projItem.ContainingProject;

			string baseName;
			//If resource file resides in the project root, then the file's namespace is identical to the project's DefaultNamespace
			if(Path.GetDirectoryName(proj.FileName)==Path.GetDirectoryName(fileName))
			{
				baseName = (string)proj.Properties.Item("DefaultNamespace").Value;
			}
			//If not, then find the file's parent folder and get its DefaultNamespace
			else
			{
				//The parent folder can't be reached directly through some property.
				//Instead, it's necessary to go down through the whole hierarchy from the project root.
				//The hierarchy is fetched from the resource file's full filename
				string[] arrTemp = Path.GetDirectoryName(fileName).Replace(Path.GetDirectoryName(proj.FileName) + "\\","").Split(new char[] {'\\'});
				ProjectItems projItems = proj.ProjectItems;
				for (int i = 0; i < arrTemp.Length; i++)
				{
					projItems = projItems.Item(arrTemp[i]).ProjectItems;
				}
				baseName = (string)((ProjectItem)projItems.Parent).Properties.Item("DefaultNamespace").Value;
			}
			//BaseName equals [resource file's default namespace].[the base filename(without extension)]
			baseName = baseName + "." + Helper.GetBaseFileName(Path.GetFileName(fileName));

			//Compare all different-language resource files and raise an error in case of inconsistencies with the base resource file
			string ParameterMatchExpression = @"(\{[^\}\{]+\})";
            string path = Path.GetDirectoryName(fileName);
			DirectoryInfo folder = new DirectoryInfo(path);
			//Create a sorted list of string resources from the base resource file
			//Sorted list is used to perform validation in alphabetical order
			ResXResourceReader reader = new ResXResourceReader(fileName);
			IDictionaryEnumerator enumerator = reader.GetEnumerator();
			SortedList baseList = new SortedList();
			while (enumerator.MoveNext())
			{
				MatchCollection mc = Regex.Matches(enumerator.Value.ToString(), ParameterMatchExpression);
				//The resource name is the key argument and the number of String.Format arguments is the value argument
				baseList.Add(enumerator.Key, mc.Count);
			}
			reader.Close();

			//Get all other .resx files in the same folder
			foreach(FileInfo file in folder.GetFiles("*.resx"))
			{
				//Consider only files with the same name (for instance - Strings.de.resx has the same name as Strings.en.resx)
				if ((file.FullName!=fileName) && (Helper.GetBaseFileName(file.Name)==Helper.GetBaseFileName(Path.GetFileNameWithoutExtension(fileName))))
				{
					//Create a sorted list of string resources from the found resource file
					reader = new ResXResourceReader(file.FullName);
					enumerator = reader.GetEnumerator();
					SortedList list = new SortedList();
					while (enumerator.MoveNext())
					{
						MatchCollection mc = Regex.Matches(enumerator.Value.ToString(), ParameterMatchExpression);
						list.Add(enumerator.Key, mc.Count);
					}
					reader.Close();

					enumerator = baseList.GetEnumerator();
					try
					{					
						//iterate through the sorted list created from a base resource file and
						//compare its key and value with the ones from the sorted list created from the other file
						while (enumerator.MoveNext())
						{
							if (list.ContainsKey(enumerator.Key)==false)
							{
								throw new Exception("Resource " + enumerator.Key.ToString() + " is missing in the file " + file.Name);
							}
							if (!list[enumerator.Key].Equals(enumerator.Value))
							{
								throw new Exception("Resource " + enumerator.Key.ToString() + " in the file " + file.Name + " has incorrect number of arguments.");
							}
						}
					}
					catch (Exception ex)
					{
						//The exception will be thrown in the VS.NET environment
						throw (ex);
					}
				}
			}
			
			CodeDomProvider provider = null;
			switch(proj.CodeModel.Language)
			{
				case CodeModelLanguageConstants.vsCMLanguageCSharp:
					provider = new Microsoft.CSharp.CSharpCodeProvider();
					break;
				case CodeModelLanguageConstants.vsCMLanguageVB:
					provider = new Microsoft.VisualBasic.VBCodeProvider();
					break;
			}
			
			//This is the value of the .resx file "Custom Tool Namespace" property
			string classNameSpace = FileNameSpace != String.Empty ? FileNameSpace : Assembly.GetExecutingAssembly().GetName().Name;
			
			return CodeDomResourceClassGenerator.GenerateCode(
						provider,
						fileName,
						fileContents,
						baseName,
						classNameSpace
			);
		}

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Jasmin Muharemovic
Software Developer Mono Ltd
Croatia Croatia
No Biography provided

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 23 Jun 2004
Article Copyright 2004 by Jasmin Muharemovic
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid