Click here to Skip to main content
15,891,248 members
Articles / Desktop Programming / WPF

StringsResourceGenerator, Custom Task + Add-in for managing strings in ResourceDictionary from code

Rate me:
Please Sign up or sign in to vote.
4.05/5 (8 votes)
27 May 2008CPOL4 min read 28.4K   291   10  
Creates a XAML file for your strings and generates a class to simplify use from code.
��using System;

using Extensibility;

using EnvDTE;

using EnvDTE80;

using Microsoft.VisualStudio.CommandBars;

using System.Resources;

using System.Reflection;

using System.Globalization;

using System.Windows.Forms;

using System.IO;

using System.Xml;



namespace StringsResourceGeneratorAddin

{

	/// <summary>The object for implementing an Add-in.</summary>

	/// <seealso class='IDTExtensibility2' />

	public class Connect : IDTExtensibility2, IDTCommandTarget

    {

        #region Data Members



        private DTE2 _applicationObject;

        private AddIn _addInInstance;



        Command _command = null;



        #endregion



        #region Constructors



        /// <summary>Implements the constructor for the Add-in object. Place your initialization code within this method.</summary>

		public Connect()

		{

        }



        #endregion



        #region Public Functions



        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>

		/// <param term='application'>Root object of the host application.</param>

		/// <param term='connectMode'>Describes how the Add-in is being loaded.</param>

		/// <param term='addInInst'>Object representing this Add-in.</param>

		/// <seealso class='IDTExtensibility2' />

		public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)

		{

			_applicationObject = (DTE2)application;

			_addInInstance = (AddIn)addInInst;

			if(connectMode == ext_ConnectMode.ext_cm_UISetup)

			{

				object []contextGUIDS = new object[] { };

				Commands2 commands = (Commands2)_applicationObject.Commands;

				string toolsMenuName;



				try

				{

					//If you would like to move the command to a different menu, change the word "Tools" to the 

					//  English version of the menu. This code will take the culture, append on the name of the menu

					//  then add the command to that menu. You can find a list of all the top-level menus in the file

					//  CommandBar.resx.

					string resourceName;

					ResourceManager resourceManager = new ResourceManager("StringsResourceGeneratorAddin.CommandBar", Assembly.GetExecutingAssembly());

					CultureInfo cultureInfo = new CultureInfo(_applicationObject.LocaleID);

					

					if(cultureInfo.TwoLetterISOLanguageName == "zh")

					{

						System.Globalization.CultureInfo parentCultureInfo = cultureInfo.Parent;

						resourceName = String.Concat(parentCultureInfo.Name, "Tools");

					}

					else

					{

						resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");

					}

					toolsMenuName = resourceManager.GetString(resourceName);

				}

				catch

				{

					//We tried to find a localized version of the word Tools, but one was not found.

					//  Default to the en-US word, which may work for the current culture.

					toolsMenuName = "Tools";

				}



				//Place the command on the tools menu.

				//Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:

				Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"];



				//Find the Tools command bar on the MenuBar command bar:

				CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName];

				CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;



				//This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,

				//  just make sure you also update the QueryStatus/Exec method to include the new command names.

				try

				{

					//Add a command to the Commands collection:

					_command = commands.AddNamedCommand2(_addInInstance, "StringsResourceGeneratorAddin", "StringsResourceGenerator...", "Executes the command for StringsResourceGeneratorAddin", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);



					//Add a control for the command to the tools menu:

					if((_command != null) && (toolsPopup != null))

					{

						_command.AddControl(toolsPopup.CommandBar, 1);

					}

				}

				catch(System.ArgumentException)

				{

					//If we are here, then the exception is probably because a command with that name

					//  already exists. If so there is no need to recreate the command and we can 

                    //  safely ignore the exception.

				}

            }

        }



		/// <summary>Implements the OnDisconnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being unloaded.</summary>

		/// <param term='disconnectMode'>Describes how the Add-in is being unloaded.</param>

		/// <param term='custom'>Array of parameters that are host application specific.</param>

		/// <seealso class='IDTExtensibility2' />

		public void OnDisconnection(ext_DisconnectMode disconnectMode, ref Array custom)

		{

            //if (_command != null)

            //    _command.Delete();

		}



		/// <summary>Implements the OnAddInsUpdate method of the IDTExtensibility2 interface. Receives notification when the collection of Add-ins has changed.</summary>

		/// <param term='custom'>Array of parameters that are host application specific.</param>

		/// <seealso class='IDTExtensibility2' />		

		public void OnAddInsUpdate(ref Array custom)

		{

		}



		/// <summary>Implements the OnStartupComplete method of the IDTExtensibility2 interface. Receives notification that the host application has completed loading.</summary>

		/// <param term='custom'>Array of parameters that are host application specific.</param>

		/// <seealso class='IDTExtensibility2' />

		public void OnStartupComplete(ref Array custom)

		{

		}



		/// <summary>Implements the OnBeginShutdown method of the IDTExtensibility2 interface. Receives notification that the host application is being unloaded.</summary>

		/// <param term='custom'>Array of parameters that are host application specific.</param>

		/// <seealso class='IDTExtensibility2' />

		public void OnBeginShutdown(ref Array custom)

		{

		}

		

		/// <summary>Implements the QueryStatus method of the IDTCommandTarget interface. This is called when the command's availability is updated</summary>

		/// <param term='commandName'>The name of the command to determine state for.</param>

		/// <param term='neededText'>Text that is needed for the command.</param>

		/// <param term='status'>The state of the command in the user interface.</param>

		/// <param term='commandText'>Text requested by the neededText parameter.</param>

		/// <seealso class='Exec' />

		public void QueryStatus(string commandName, vsCommandStatusTextWanted neededText, ref vsCommandStatus status, ref object commandText)

		{

			if(neededText == vsCommandStatusTextWanted.vsCommandStatusTextWantedNone)

			{

				if(commandName == "StringsResourceGeneratorAddin.Connect.StringsResourceGeneratorAddin")

				{

					status = (vsCommandStatus)vsCommandStatus.vsCommandStatusSupported|vsCommandStatus.vsCommandStatusEnabled;

					return;

				}

			}

		}



		/// <summary>Implements the Exec method of the IDTCommandTarget interface. This is called when the command is invoked.</summary>

		/// <param term='commandName'>The name of the command to execute.</param>

		/// <param term='executeOption'>Describes how the command should be run.</param>

		/// <param term='varIn'>Parameters passed from the caller to the command handler.</param>

		/// <param term='varOut'>Parameters passed from the command handler to the caller.</param>

		/// <param term='handled'>Informs the caller if the command was handled or not.</param>

		/// <seealso class='Exec' />

		public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)

		{

			handled = false;

			if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)

			{

				if(commandName == "StringsResourceGeneratorAddin.Connect.StringsResourceGeneratorAddin")

				{

					handled = true;



                    ProjectInformation projectInformation = GetProjectInformation();

                    if (projectInformation == null)

                    {

                        MessageBox.Show("Cannot retrieve project information!");

                        return;

                    }



                    StringsResourceGeneratorSettings settings = new StringsResourceGeneratorSettings(projectInformation);

                    if (settings.ShowDialog() == DialogResult.OK)

                        UpdateProject(projectInformation);



					return;

				}

			}

        }



        #endregion



        #region Private Fucntions



        private ProjectInformation GetProjectInformation()

        {

            if (_applicationObject.Solution == null || _applicationObject.Solution.Projects.Count == 0)

            {

                MessageBox.Show("No project to update!");

                return null;

            }



            if (_applicationObject.SelectedItems == null || _applicationObject.SelectedItems.Count == 0)

            {

                MessageBox.Show("The active document is invalid!");

                return null;

            }



            if (_applicationObject.SelectedItems.Count > 1)

            {

                MessageBox.Show("Select only an item in the project!");

                return null;

            }



            Project project = null;



            try

            {

                project = _applicationObject.SelectedItems.Item(1).Project;

                ProjectItem projectItem = _applicationObject.SelectedItems.Item(1).ProjectItem;

                if (project == null)

                    project = projectItem.ContainingProject;

            }

            catch (Exception e)

            {

                string message = "A problem occurs in the selected item on current project!";

                message += System.Environment.NewLine;

                message += "Exception:";

                message += System.Environment.NewLine;

                message += e.Message;

                MessageBox.Show(message);

                return null;

            }

            

            string projectName = Path.GetFileNameWithoutExtension(project.Name);

            string defaultNamespace = project.Properties.Item("DefaultNamespace").Value as string;

            defaultNamespace += GetRelativeNamespace();

            string assemblyName = project.Properties.Item("AssemblyName").Value as string;



            return new ProjectInformation() { StringsResourceFileName = "Strings", Namespace = defaultNamespace, AssemblyName = assemblyName, ClassName = "Strings" };

        }



        private void UpdateProject(ProjectInformation projectInformation)

        {

            try

            {

                UpdateProjectTree(projectInformation);

                UpdateProjectTask(projectInformation);

            }

            catch (Exception e)

            {

                string message = "A problem occurs during project updating!";

                message += System.Environment.NewLine;

                message += "Exception:";

                message += System.Environment.NewLine;

                message += e.Message;

                MessageBox.Show(message);

            }

        }



        private void UpdateProjectTree(ProjectInformation projectInformation)

        {

            Solution2 solution = _applicationObject.Solution as Solution2;

            string templateFullFileName = solution.GetProjectItemTemplate("LocalizableStringsResource.zip", "CSharp");



            ProjectItem projectItem = _applicationObject.SelectedItems.Item(1).ProjectItem;

            ProjectItem newProjectItem = projectItem.ProjectItems.AddFromTemplate(templateFullFileName, projectInformation.StringsResourceFileName);



            projectItem.ContainingProject.Save(projectItem.ContainingProject.FullName);

        }



        private void UpdateProjectTask(ProjectInformation projectInformation)

        {

            string targetTemplate = StringsResourceGeneratorAddin.Templates.ProjectTargetTemplate;

            targetTemplate = targetTemplate.Replace("$(NAMESPACE)", projectInformation.Namespace);

            targetTemplate = targetTemplate.Replace("$(ASSEMBLY)", projectInformation.AssemblyName);

            targetTemplate = targetTemplate.Replace("$(STRINGSRESOURCE)", Path.Combine(GetRelativeFolderPath(), projectInformation.StringsResourceFileName));

            targetTemplate = targetTemplate.Replace("$(CLASSNAME)", projectInformation.ClassName);



            XmlDocument document = new XmlDocument();

            document.Load(_applicationObject.ActiveDocument.ProjectItem.ContainingProject.FullName);



            XmlDocument taskDocument = new XmlDocument();

            taskDocument.LoadXml(Templates.ProjectTaskTemplate);

            XmlNode taskNode = document.ImportNode(taskDocument.DocumentElement, true);

            document.DocumentElement.AppendChild(taskNode);



            XmlDocument targetDocument = new XmlDocument();

            targetDocument.LoadXml(targetTemplate);

            XmlNode targetNode = document.ImportNode(targetDocument.DocumentElement, true);

            document.DocumentElement.AppendChild(targetNode);



            document.InnerXml = document.InnerXml.Replace("xmlns=\"\"", string.Empty);



            document.Save(_applicationObject.ActiveDocument.ProjectItem.ContainingProject.FullName);

        }



        string[] GetDecomposedRelativePath()

        {

            ProjectItem projectItem = _applicationObject.SelectedItems.Item(1).ProjectItem;

            string projectItemFileName = projectItem.Properties.Item("FullPath").Value as string;



            string projectFolder = Path.GetDirectoryName(projectItem.ContainingProject.FullName);

            projectItemFileName = projectItemFileName.Replace(projectFolder, string.Empty);



            string[] allDecomposedRelativePath = projectItemFileName.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries);

            string[] decomposedRelativePath = null;

            if (projectItem.Kind == Constants.vsProjectItemKindPhysicalFile)

            {

                decomposedRelativePath = new string[allDecomposedRelativePath.Length - 1];

                for (int i = 0; i < allDecomposedRelativePath.Length - 1; i++)

                    decomposedRelativePath[i] = allDecomposedRelativePath[i];

            }

            else

                decomposedRelativePath = allDecomposedRelativePath;



            return decomposedRelativePath;

        }



        string GetRelativeFolderPath()

        {

            string[] folders = GetDecomposedRelativePath();



            string relativeFolder = string.Empty;



            for (int i = 0; i < folders.Length; i++)

                relativeFolder = Path.Combine(relativeFolder, folders[i]);



            return relativeFolder;

        }



        string GetRelativeNamespace()

        {

            string[] namespaces = GetDecomposedRelativePath();



            string relativeNamespace = string.Empty;



            for (int i = 0; i < namespaces.Length; i++)

                relativeNamespace += "." + namespaces[i];



            return relativeNamespace;

        }



        #endregion

    }

}

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Italy Italy
I am a biomedical engineer. I work in Genoa as software developer. I developed MFC ActiveX controls for industrial automation for 2 years and packages for Visual Studio 2005 for 1 year. Currently I'm working in .NET 3.5 in biomedical area.

Comments and Discussions