PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/VSXTra/Samples/Package/VSXtraCommands/VSXtraCommands_IntegrationTestProject/IntegrationTest Library/Utils.cs

#
C# | 401 lines | 245 code | 50 blank | 106 comment | 22 complexity | b38c8a5d68dc081db2787344b7946478 MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Reflection;
  5. using System.Diagnostics;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.ComponentModel.Design;
  9. using System.Runtime.InteropServices;
  10. using Microsoft.VisualStudio.Shell.Interop;
  11. using Microsoft.VisualStudio.Shell;
  12. using EnvDTE;
  13. using EnvDTE80;
  14. using Microsoft.Win32;
  15. using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
  16. using Microsoft.VisualStudio.TestTools.UnitTesting;
  17. using Microsoft.VSSDK.Tools.VsIdeTesting;
  18. using Microsoft.VisualStudio;
  19. namespace Microsoft.VsSDK.IntegrationTestLibrary
  20. {
  21. /// <summary>
  22. /// </summary>
  23. public class TestUtils
  24. {
  25. #region Methods: Handling embedded resources
  26. /// <summary>
  27. /// Gets the embedded file identified by the resource name, and converts the
  28. /// file into a string.
  29. /// </summary>
  30. /// <param name="resourceName">In VS, is DefaultNamespace.FileName?</param>
  31. /// <returns></returns>
  32. public static string GetEmbeddedStringResource(Assembly assembly, string resourceName)
  33. {
  34. string result = null;
  35. // Use the .NET procedure for loading a file embedded in the assembly
  36. Stream stream = assembly.GetManifestResourceStream(resourceName);
  37. if (stream != null)
  38. {
  39. // Convert bytes to string
  40. byte[] fileContentsAsBytes = new byte[stream.Length];
  41. stream.Read(fileContentsAsBytes, 0, (int)stream.Length);
  42. result = Encoding.Default.GetString(fileContentsAsBytes);
  43. }
  44. else
  45. {
  46. // Embedded resource not found - list available resources
  47. Debug.WriteLine("Unable to find the embedded resource file '" + resourceName + "'.");
  48. Debug.WriteLine(" Available resources:");
  49. foreach (string aResourceName in assembly.GetManifestResourceNames())
  50. {
  51. Debug.WriteLine(" " + aResourceName);
  52. }
  53. }
  54. return result;
  55. }
  56. /// <summary>
  57. ///
  58. /// </summary>
  59. /// <param name="embeddedResourceName"></param>
  60. /// <param name="baseFileName"></param>
  61. /// <param name="fileExtension"></param>
  62. /// <returns></returns>
  63. public static void WriteEmbeddedResourceToFile(Assembly assembly, string embeddedResourceName, string fileName)
  64. {
  65. // Get file contents
  66. string fileContents = GetEmbeddedStringResource(assembly, embeddedResourceName);
  67. if (fileContents == null)
  68. throw new ApplicationException("Failed to get embedded resource '" + embeddedResourceName + "' from assembly '" + assembly.FullName);
  69. // Write to file
  70. StreamWriter sw = new StreamWriter(fileName);
  71. sw.Write(fileContents);
  72. sw.Close();
  73. }
  74. /// <summary>
  75. /// Writes an embedded resource to a file.
  76. /// </summary>
  77. /// <param name="assembly">The name of the assembly that the embedded resource is defined.</param>
  78. /// <param name="embeddedResourceName">The name of the embedded resource.</param>
  79. /// <param name="fileName">The file to write the embedded resource's content.</param>
  80. public static void WriteEmbeddedResourceToBinaryFile(Assembly assembly, string embeddedResourceName, string fileName)
  81. {
  82. // Get file contents
  83. Stream stream = assembly.GetManifestResourceStream(embeddedResourceName);
  84. if (stream == null)
  85. throw new InvalidOperationException("Failed to get embedded resource '" + embeddedResourceName + "' from assembly '" + assembly.FullName);
  86. // Write to file
  87. BinaryWriter sw = null;
  88. FileStream fs = null;
  89. try
  90. {
  91. byte[] fileContentsAsBytes = new byte[stream.Length];
  92. stream.Read(fileContentsAsBytes, 0, (int)stream.Length);
  93. FileMode mode = FileMode.CreateNew;
  94. if (File.Exists(fileName))
  95. {
  96. mode = FileMode.Truncate;
  97. }
  98. fs = new FileStream(fileName, mode);
  99. sw = new BinaryWriter(fs);
  100. sw.Write(fileContentsAsBytes);
  101. }
  102. finally
  103. {
  104. if (fs != null)
  105. {
  106. fs.Close();
  107. }
  108. if (sw != null)
  109. {
  110. sw.Close();
  111. }
  112. }
  113. }
  114. #endregion
  115. #region Methods: Handling temporary files and directories
  116. /// <summary>
  117. /// Returns the first available file name on the form
  118. /// [baseFileName]i.[extension]
  119. /// where [i] starts at 1 and increases until there is an available file name
  120. /// in the given directory. Also creates an empty file with that name to mark
  121. /// that file as occupied.
  122. /// </summary>
  123. /// <param name="directory">Directory that the file should live in.</param>
  124. /// <param name="baseFileName"></param>
  125. /// <param name="extension">may be null, in which case the .[extension] part
  126. /// is not added.</param>
  127. /// <returns>Full file name.</returns>
  128. public static string GetNewFileName(string directory, string baseFileName, string extension)
  129. {
  130. // Get the new file name
  131. string fileName = GetNewFileOrDirectoryNameWithoutCreatingAnything(directory, baseFileName, extension);
  132. // Create an empty file to mark it as taken
  133. StreamWriter sw = new StreamWriter(fileName);
  134. sw.Write("");
  135. sw.Close();
  136. return fileName;
  137. }
  138. /// <summary>
  139. /// Returns the first available directory name on the form
  140. /// [baseDirectoryName]i
  141. /// where [i] starts at 1 and increases until there is an available directory name
  142. /// in the given directory. Also creates the directory to mark it as occupied.
  143. /// </summary>
  144. /// <param name="directory">Directory that the file should live in.</param>
  145. /// <param name="baseDirectoryName"></param>
  146. /// <returns>Full directory name.</returns>
  147. public static string GetNewDirectoryName(string directory, string baseDirectoryName)
  148. {
  149. // Get the new file name
  150. string directoryName = GetNewFileOrDirectoryNameWithoutCreatingAnything(directory, baseDirectoryName, null);
  151. // Create an empty directory to make it as occupied
  152. Directory.CreateDirectory(directoryName);
  153. return directoryName;
  154. }
  155. /// <summary>
  156. ///
  157. /// </summary>
  158. /// <param name="directory"></param>
  159. /// <param name="baseFileName"></param>
  160. /// <param name="extension"></param>
  161. /// <returns></returns>
  162. private static string GetNewFileOrDirectoryNameWithoutCreatingAnything(string directory, string baseFileName, string extension)
  163. {
  164. // - get a file name that we can use
  165. string fileName;
  166. int i = 1;
  167. string fullFileName = null;
  168. while (true)
  169. {
  170. // construct next file name
  171. fileName = baseFileName + i;
  172. if (extension != null)
  173. fileName += '.' + extension;
  174. // check if that file exists in the directory
  175. fullFileName = Path.Combine(directory, fileName);
  176. if (!File.Exists(fullFileName) && !Directory.Exists(fullFileName))
  177. break;
  178. else
  179. i++;
  180. }
  181. return fullFileName;
  182. }
  183. #endregion
  184. #region Methods: Handling solutions
  185. /// <summary>
  186. /// Closes the currently open solution (if any), and creates a new solution with the given name.
  187. /// </summary>
  188. /// <param name="solutionName">Name of new solution.</param>
  189. public void CreateEmptySolution(string directory, string solutionName)
  190. {
  191. CloseCurrentSolution(__VSSLNSAVEOPTIONS.SLNSAVEOPT_NoSave);
  192. string solutionDirectory = GetNewDirectoryName(directory, solutionName);
  193. // Create and force save solution
  194. IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
  195. solutionService.CreateSolution(solutionDirectory, solutionName, (uint)__VSCREATESOLUTIONFLAGS.CSF_SILENT);
  196. solutionService.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, null, 0);
  197. DTE dte = VsIdeTestHostContext.Dte;
  198. Assert.AreEqual(solutionName + ".sln", Path.GetFileName(dte.Solution.FileName), "Newly created solution has wrong Filename");
  199. }
  200. public void CloseCurrentSolution(__VSSLNSAVEOPTIONS saveoptions)
  201. {
  202. // Get solution service
  203. IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
  204. // Close already open solution
  205. solutionService.CloseSolutionElement((uint)saveoptions, null, 0);
  206. }
  207. public void ForceSaveSolution()
  208. {
  209. // Get solution service
  210. IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
  211. // Force-save the solution
  212. solutionService.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, null, 0);
  213. }
  214. /// <summary>
  215. /// Get current number of open project in solution
  216. /// </summary>
  217. /// <returns></returns>
  218. public int ProjectCount()
  219. {
  220. // Get solution service
  221. IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
  222. object projectCount;
  223. solutionService.GetProperty((int)__VSPROPID.VSPROPID_ProjectCount, out projectCount);
  224. return (int)projectCount;
  225. }
  226. #endregion
  227. #region Methods: Handling projects
  228. /// <summary>
  229. /// Creates a project.
  230. /// </summary>
  231. /// <param name="projectName">Name of new project.</param>
  232. /// <param name="templateName">Name of project template to use</param>
  233. /// <param name="language">language</param>
  234. /// <returns>New project.</returns>
  235. public void CreateProjectFromTemplate(string projectName, string templateName, string language, bool exclusive)
  236. {
  237. DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
  238. Solution2 sol = dte.Solution as Solution2;
  239. string projectTemplate = sol.GetProjectTemplate(templateName, language);
  240. // - project name and directory
  241. string solutionDirectory = Directory.GetParent(dte.Solution.FullName).FullName;
  242. string projectDirectory = GetNewDirectoryName(solutionDirectory, projectName);
  243. dte.Solution.AddFromTemplate(projectTemplate, projectDirectory, projectName, false);
  244. }
  245. #endregion
  246. #region Methods: Handling project items
  247. /// <summary>
  248. /// Create a new item in the project
  249. /// </summary>
  250. /// <param name="parent">the parent collection for the new item</param>
  251. /// <param name="templateName"></param>
  252. /// <param name="language"></param>
  253. /// <param name="name"></param>
  254. /// <returns></returns>
  255. public ProjectItem AddNewItemFromVsTemplate(ProjectItems parent, string templateName, string language, string name)
  256. {
  257. if (parent == null)
  258. throw new ArgumentException("project");
  259. if (name == null)
  260. throw new ArgumentException("name");
  261. DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
  262. Solution2 sol = dte.Solution as Solution2;
  263. string filename = sol.GetProjectItemTemplate(templateName, language);
  264. parent.AddFromTemplate(filename, name);
  265. return parent.Item(name);
  266. }
  267. /// <summary>
  268. /// Save an open document.
  269. /// </summary>
  270. /// <param name="documentMoniker">for filebased documents this is the full path to the document</param>
  271. public void SaveDocument(string documentMoniker)
  272. {
  273. // Get document cookie and hierarchy for the file
  274. IVsRunningDocumentTable runningDocumentTableService = (IVsRunningDocumentTable)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsRunningDocumentTable));
  275. uint docCookie;
  276. IntPtr docData;
  277. IVsHierarchy hierarchy;
  278. uint itemId;
  279. runningDocumentTableService.FindAndLockDocument(
  280. (uint)Microsoft.VisualStudio.Shell.Interop._VSRDTFLAGS.RDT_NoLock,
  281. documentMoniker,
  282. out hierarchy,
  283. out itemId,
  284. out docData,
  285. out docCookie);
  286. // Save the document
  287. IVsSolution solutionService = (IVsSolution)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution));
  288. solutionService.SaveSolutionElement((uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_ForceSave, hierarchy, docCookie);
  289. }
  290. public void CloseInEditorWithoutSaving(string fullFileName)
  291. {
  292. // Get the RDT service
  293. IVsRunningDocumentTable runningDocumentTableService = (IVsRunningDocumentTable)VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsRunningDocumentTable));
  294. Assert.IsNotNull(runningDocumentTableService, "Failed to get the Running Document Table Service");
  295. // Get our document cookie and hierarchy for the file
  296. uint docCookie;
  297. IntPtr docData;
  298. IVsHierarchy hierarchy;
  299. uint itemId;
  300. runningDocumentTableService.FindAndLockDocument(
  301. (uint)Microsoft.VisualStudio.Shell.Interop._VSRDTFLAGS.RDT_NoLock,
  302. fullFileName,
  303. out hierarchy,
  304. out itemId,
  305. out docData,
  306. out docCookie);
  307. // Get the SolutionService
  308. IVsSolution solutionService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(IVsSolution)) as IVsSolution;
  309. Assert.IsNotNull(solutionService, "Failed to get IVsSolution service");
  310. // Close the document
  311. solutionService.CloseSolutionElement(
  312. (uint)__VSSLNSAVEOPTIONS.SLNSAVEOPT_NoSave,
  313. hierarchy,
  314. docCookie);
  315. }
  316. #endregion
  317. #region Methods: Handling Toolwindows
  318. public bool CanFindToolwindow(Guid persistenceGuid)
  319. {
  320. IVsUIShell uiShellService = VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;
  321. Assert.IsNotNull(uiShellService);
  322. IVsWindowFrame windowFrame;
  323. int hr = uiShellService.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFindFirst, ref persistenceGuid, out windowFrame);
  324. Assert.IsTrue(hr == VSConstants.S_OK);
  325. return (windowFrame != null);
  326. }
  327. #endregion
  328. #region Methods: Loading packages
  329. public IVsPackage LoadPackage(Guid packageGuid)
  330. {
  331. IVsShell shellService = (IVsShell)VsIdeTestHostContext.ServiceProvider.GetService(typeof(SVsShell));
  332. IVsPackage package;
  333. shellService.LoadPackage(ref packageGuid, out package);
  334. Assert.IsNotNull(package, "Failed to load package");
  335. return package;
  336. }
  337. #endregion
  338. /// <summary>
  339. /// Executes a Command (menu item) in the given context
  340. /// </summary>
  341. public void ExecuteCommand(CommandID cmd)
  342. {
  343. object Customin = null;
  344. object Customout = null;
  345. string guidString = cmd.Guid.ToString("B").ToUpper();
  346. int cmdId = cmd.ID;
  347. DTE dte = VsIdeTestHostContext.Dte;
  348. dte.Commands.Raise(guidString, cmdId, ref Customin, ref Customout);
  349. }
  350. }
  351. }