PageRenderTime 68ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/SolutionFramework/Microsoft.VisualStudio.ServiceModel.DomainServices.Tools.10.0/Microsoft/VisualStudio/ServiceModel/DomainServices/Tools/DomainServiceClassWizard.cs

#
C# | 556 lines | 525 code | 31 blank | 0 comment | 150 complexity | 2ab26add04aa05de0ebd28686450d6b5 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0
  1. namespace Microsoft.VisualStudio.ServiceModel.DomainServices.Tools
  2. {
  3. using EnvDTE;
  4. using EnvDTE80;
  5. using Microsoft.ServiceModel.DomainServices.Tools;
  6. using Microsoft.VisualStudio.ManagedInterfaces9;
  7. using Microsoft.VisualStudio.OLE.Interop;
  8. using Microsoft.VisualStudio.Shell;
  9. using Microsoft.VisualStudio.Shell.Design;
  10. using Microsoft.VisualStudio.Shell.Interop;
  11. using Microsoft.VisualStudio.TemplateWizard;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.ComponentModel.Design;
  15. using System.Configuration;
  16. using System.Data.Linq;
  17. using System.Data.Objects;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Reflection;
  22. using System.Threading;
  23. using System.Windows.Forms;
  24. using System.Windows.Forms.Design;
  25. using System.Windows.Interop;
  26. using VSLangProj;
  27. internal class DomainServiceClassWizard : IWizard
  28. {
  29. private GeneratedCode _businessLogicCode;
  30. private BusinessLogicClassDialog _dialog;
  31. private EnvDTE80.DTE2 _dte2;
  32. private bool _generateMetadataFile;
  33. private bool _isClientAccessEnabled;
  34. private bool _isODataEndpointEnabled;
  35. private GeneratedCode _metadataCode;
  36. private Project _project;
  37. private InternalTestHook _testHook;
  38. private void AddReferences(IEnumerable<string> references)
  39. {
  40. if (references.Any<string>())
  41. {
  42. VSProject project2 = this.ActiveProject.Object as VSProject;
  43. if (project2 != null)
  44. {
  45. foreach (string str in references)
  46. {
  47. Reference reference = project2.References.Add(str);
  48. if (ShouldCopyLocal(str))
  49. {
  50. reference.CopyLocal = true;
  51. }
  52. }
  53. }
  54. }
  55. }
  56. public void BeforeOpeningFile(ProjectItem projectItem)
  57. {
  58. }
  59. private string ComputeNamespace()
  60. {
  61. ProjectItems projItems = null;
  62. if (this._dte2.SelectedItems.Count == 1)
  63. {
  64. SelectedItem item = this._dte2.SelectedItems.Item(1);
  65. if (item.ProjectItem != null)
  66. {
  67. projItems = item.ProjectItem.ProjectItems;
  68. if ((projItems != null) && (projItems.Kind != "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}"))
  69. {
  70. projItems = null;
  71. }
  72. }
  73. }
  74. if (projItems == null)
  75. {
  76. projItems = this.ActiveProject.ProjectItems;
  77. }
  78. return FindNSOfItem(projItems);
  79. }
  80. private static string FindNSOfItem(ProjectItems projItems)
  81. {
  82. string extension = Path.GetExtension(projItems.ContainingProject.FileName);
  83. if (!string.Equals(extension, ".csproj", StringComparison.OrdinalIgnoreCase) && !string.Equals(extension, ".vjsproj", StringComparison.OrdinalIgnoreCase))
  84. {
  85. if (projItems.ContainingProject.Object is VSProject)
  86. {
  87. return projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString();
  88. }
  89. return MakeNameCompliant(Path.GetFileNameWithoutExtension(projItems.ContainingProject.FileName));
  90. }
  91. if (projItems is Project)
  92. {
  93. return projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString();
  94. }
  95. string str2 = string.Empty;
  96. while (projItems.Kind == "{6BB5F8EF-4483-11D3-8BCF-00C04F8EC28C}")
  97. {
  98. if (projItems.Parent is Project)
  99. {
  100. if (str2.Length == 0)
  101. {
  102. return projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString();
  103. }
  104. return (projItems.ContainingProject.Properties.Item("RootNamespace").Value.ToString() + "." + str2);
  105. }
  106. if (str2.Length == 0)
  107. {
  108. str2 = MakeNameCompliant(((ProjectItem) projItems.Parent).Name);
  109. }
  110. else
  111. {
  112. str2 = MakeNameCompliant(((ProjectItem) projItems.Parent).Name) + "." + str2;
  113. }
  114. projItems = ((ProjectItem) projItems.Parent).Collection;
  115. }
  116. return str2;
  117. }
  118. private IEnumerable<System.Type> GetCandidateTypes(ITypeDiscoveryService typeDiscoveryService)
  119. {
  120. List<System.Type> list = new List<System.Type>();
  121. VSProject vsProject = this.ActiveProject.Object as VSProject;
  122. if ((vsProject != null) && (typeDiscoveryService != null))
  123. {
  124. List<Reference> projectReferences = new List<Reference>();
  125. foreach (Reference reference in vsProject.References)
  126. {
  127. if (((reference != null) && !string.IsNullOrEmpty(reference.Name)) && (reference.Type == prjReferenceType.prjReferenceTypeAssembly))
  128. {
  129. projectReferences.Add(reference);
  130. }
  131. }
  132. bool enableDataContextTypes = LinqToSqlContext.EnableDataContextTypes;
  133. foreach (System.Type type in typeDiscoveryService.GetTypes(typeof(object), true))
  134. {
  135. if (IsContextType(type, enableDataContextTypes) && IsVisibleInCurrentProject(type, vsProject, projectReferences))
  136. {
  137. list.Add(type);
  138. }
  139. }
  140. }
  141. return list;
  142. }
  143. private object GetService(System.Type serviceType)
  144. {
  145. Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = this.DTE2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
  146. if (sp == null)
  147. {
  148. return null;
  149. }
  150. using (ServiceProvider provider2 = new ServiceProvider(sp))
  151. {
  152. return provider2.GetService(serviceType);
  153. }
  154. }
  155. private ITypeDiscoveryService GetTypeDiscoveryService(Project project)
  156. {
  157. DynamicTypeService service = this.GetService(typeof(DynamicTypeService)) as DynamicTypeService;
  158. if (service == null)
  159. {
  160. return null;
  161. }
  162. IVsHierarchy vsHierarchy = this.GetVsHierarchy(project);
  163. return service.GetTypeDiscoveryService(vsHierarchy);
  164. }
  165. private IVsHierarchy GetVsHierarchy(Project project)
  166. {
  167. IVsSolution service = this.GetService(typeof(SVsSolution)) as IVsSolution;
  168. if (service == null)
  169. {
  170. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_Hierarchy);
  171. }
  172. IVsHierarchy ppHierarchy = null;
  173. if ((service.GetProjectOfUniqueName(project.UniqueName, out ppHierarchy) != 0) || (ppHierarchy == null))
  174. {
  175. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_Hierarchy);
  176. }
  177. return ppHierarchy;
  178. }
  179. private static bool IsAssociatedMetadataFile(string fileName)
  180. {
  181. return (fileName.IndexOf(".metadata.", StringComparison.OrdinalIgnoreCase) >= 0);
  182. }
  183. internal static bool IsContextType(System.Type t, bool dataContextEnabled)
  184. {
  185. if ((t.IsValueType || t.IsInterface) || ((!typeof(ObjectContext).IsAssignableFrom(t) && !t.IsDbContext()) && (!dataContextEnabled || !typeof(DataContext).IsAssignableFrom(t))))
  186. {
  187. return false;
  188. }
  189. return true;
  190. }
  191. private static bool IsVisibleInCurrentProject(System.Type t, VSProject vsProject, IEnumerable<Reference> projectReferences)
  192. {
  193. if (((t == null) || (vsProject == null)) || (projectReferences == null))
  194. {
  195. return true;
  196. }
  197. Assembly assembly = t.Assembly;
  198. string name = assembly.GetName().Name;
  199. Project project = vsProject.Project;
  200. string str2 = (string) project.Properties.Item("AssemblyName").Value;
  201. if (name.Equals(str2, StringComparison.Ordinal))
  202. {
  203. return true;
  204. }
  205. string str3 = project.ConfigurationManager.ActiveConfiguration.Properties.Item("IntermediatePath").Value as string;
  206. string str4 = Path.Combine(Path.GetDirectoryName(project.FullName), str3);
  207. if (assembly.Location.StartsWith(str4, StringComparison.OrdinalIgnoreCase))
  208. {
  209. return true;
  210. }
  211. foreach (Reference reference in projectReferences)
  212. {
  213. string identity = reference.Identity;
  214. if (identity.EndsWith(char.ToString('\0'), StringComparison.Ordinal))
  215. {
  216. identity = identity.Substring(0, identity.Length - 1);
  217. }
  218. if (identity.Equals(name, StringComparison.OrdinalIgnoreCase))
  219. {
  220. return true;
  221. }
  222. }
  223. return false;
  224. }
  225. private static string MakeNameCompliant(string name)
  226. {
  227. if (string.IsNullOrEmpty(name))
  228. {
  229. return string.Empty;
  230. }
  231. if (char.IsDigit(name[0]))
  232. {
  233. name = "_" + name;
  234. }
  235. for (int i = 0; i < name.Length; i++)
  236. {
  237. UnicodeCategory unicodeCategory = char.GetUnicodeCategory(name[i]);
  238. if (((((unicodeCategory != UnicodeCategory.UppercaseLetter) && (unicodeCategory != UnicodeCategory.LowercaseLetter)) && ((unicodeCategory != UnicodeCategory.OtherLetter) && (unicodeCategory != UnicodeCategory.ConnectorPunctuation))) && (((unicodeCategory != UnicodeCategory.ModifierLetter) && (unicodeCategory != UnicodeCategory.NonSpacingMark)) && ((unicodeCategory != UnicodeCategory.SpacingCombiningMark) && (unicodeCategory != UnicodeCategory.TitlecaseLetter)))) && ((((unicodeCategory != UnicodeCategory.Format) && (unicodeCategory != UnicodeCategory.LetterNumber)) && ((unicodeCategory != UnicodeCategory.DecimalDigitNumber) && (name[i] != '.'))) && (name[i] != '_')))
  239. {
  240. name = name.Replace(name[i], '_');
  241. }
  242. }
  243. return name;
  244. }
  245. public void ProjectFinishedGenerating(Project project)
  246. {
  247. }
  248. public void ProjectItemFinishedGenerating(ProjectItem projectItem)
  249. {
  250. }
  251. public void RunFinished()
  252. {
  253. this.UpdateConfiguration();
  254. }
  255. public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
  256. {
  257. Action<Exception> action = null;
  258. this._project = null;
  259. this._dte2 = automationObject as EnvDTE80.DTE2;
  260. if (this._dte2 == null)
  261. {
  262. this.TerminateWizard(Resources.WizardError_No_DTE);
  263. }
  264. Project activeProject = this.ActiveProject;
  265. ITypeDiscoveryService typeDiscoveryService = this.GetTypeDiscoveryService(activeProject);
  266. if (typeDiscoveryService == null)
  267. {
  268. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_TypeDiscoveryService);
  269. }
  270. IEnumerable<System.Type> candidateTypes = this.GetCandidateTypes(typeDiscoveryService);
  271. string str = replacementsDictionary["$rootname$"];
  272. str = str.Trim();
  273. if (string.IsNullOrEmpty(str))
  274. {
  275. this.TerminateWizard(Resources.WizardError_Empty_Filename);
  276. }
  277. string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(str);
  278. if (string.IsNullOrEmpty(fileNameWithoutExtension))
  279. {
  280. this.TerminateWizard(Resources.WizardError_Empty_Filename);
  281. }
  282. bool flag = Path.GetExtension(str).EndsWith("vb", StringComparison.OrdinalIgnoreCase);
  283. string language = flag ? "VB" : "C#";
  284. Property property = activeProject.Properties.Item("RootNamespace");
  285. string str5 = (property == null) ? null : ((string) property.Value);
  286. if (string.IsNullOrEmpty(str5))
  287. {
  288. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_RootNamespace);
  289. }
  290. string rootNamespace = flag ? str5 : string.Empty;
  291. Property property2 = activeProject.Properties.Item("AssemblyName");
  292. string str7 = (property2 == null) ? null : ((string) property2.Value);
  293. if (string.IsNullOrEmpty(str7))
  294. {
  295. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_AssemblyName);
  296. }
  297. IEnumerable<System.Type> contextTypes = from t in candidateTypes
  298. where CodeGenUtilities.IsValidGenericTypeParam(t)
  299. select t;
  300. string fullName = activeProject.FullName;
  301. if (string.IsNullOrEmpty(fullName))
  302. {
  303. this.TerminateWizard(Resources.BusinessLogicClass_No_Project_Path);
  304. }
  305. string directoryName = Path.GetDirectoryName(fullName);
  306. try
  307. {
  308. IVsHelp service = this.GetService(typeof(IVsHelp)) as IVsHelp;
  309. using (BusinessLogicViewModel model = new BusinessLogicViewModel(directoryName, fileNameWithoutExtension, language, rootNamespace, str7, contextTypes, service))
  310. {
  311. if (action == null)
  312. {
  313. action = delegate (Exception ex) {
  314. this.ShowError(ex.Message);
  315. throw ex;
  316. };
  317. }
  318. model.ExceptionHandler = action;
  319. this._dialog = new BusinessLogicClassDialog();
  320. this._dialog.Model = model;
  321. IVsUIShell shell = this.GetService(typeof(IVsUIShell)) as IVsUIShell;
  322. IntPtr phwnd = new IntPtr();
  323. if ((shell.GetDialogOwnerHwnd(out phwnd) == 0) && (phwnd != new IntPtr()))
  324. {
  325. WindowInteropHelper helper = new WindowInteropHelper(this._dialog) {
  326. Owner = phwnd
  327. };
  328. }
  329. this._dialog.ShowInTaskbar = false;
  330. this._dialog.ShowDialog();
  331. bool flag2 = !this._dialog.DialogResult.HasValue ? false : this._dialog.DialogResult.Value;
  332. this._dialog.Model = null;
  333. if (!flag2)
  334. {
  335. throw new WizardCancelledException();
  336. }
  337. ContextViewModel currentContextViewModel = model.CurrentContextViewModel;
  338. this._isClientAccessEnabled = (currentContextViewModel != null) && currentContextViewModel.IsClientAccessEnabled;
  339. this._isODataEndpointEnabled = (currentContextViewModel != null) && currentContextViewModel.IsODataEndpointEnabled;
  340. str5 = this.ComputeNamespace();
  341. GeneratedCode code = model.GenerateBusinessLogicClass(str5);
  342. replacementsDictionary.Add("$generatedcode$", code.SourceCode);
  343. this.AddReferences(code.References);
  344. this._businessLogicCode = code;
  345. if (model.IsMetadataClassGenerationRequested)
  346. {
  347. GeneratedCode code2 = model.GenerateMetadataClasses(null);
  348. replacementsDictionary.Add("$generatedmetadatacode$", code2.SourceCode);
  349. this.AddReferences(code2.References);
  350. this._generateMetadataFile = code2.SourceCode.Length > 0;
  351. this._metadataCode = code2;
  352. }
  353. else
  354. {
  355. this._generateMetadataFile = false;
  356. }
  357. }
  358. }
  359. finally
  360. {
  361. this._dialog = null;
  362. }
  363. }
  364. public bool ShouldAddProjectItem(string filePath)
  365. {
  366. return (!IsAssociatedMetadataFile(Path.GetFileName(filePath)) || this._generateMetadataFile);
  367. }
  368. private static bool ShouldCopyLocal(string assemblyReference)
  369. {
  370. return (File.Exists(assemblyReference) && assemblyReference.ToUpperInvariant().Contains(BusinessLogicClassConstants.LinqToSqlDomainServiceAssemblyName.ToUpperInvariant()));
  371. }
  372. public void ShowError(string errorMessage)
  373. {
  374. IUIService service = (IUIService) this.GetService(typeof(IUIService));
  375. if (service != null)
  376. {
  377. MessageBoxOptions options = 0;
  378. System.Windows.Forms.IWin32Window dialogOwnerWindow = service.GetDialogOwnerWindow();
  379. if (System.Threading.Thread.CurrentThread.CurrentUICulture.TextInfo.IsRightToLeft)
  380. {
  381. options |= MessageBoxOptions.RightAlign;
  382. options |= MessageBoxOptions.RtlReading;
  383. }
  384. MessageBox.Show(dialogOwnerWindow, errorMessage, Resources.WizardError_Caption, MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1, options);
  385. }
  386. }
  387. private void TerminateWizard(string errorMessage)
  388. {
  389. if (!string.IsNullOrEmpty(errorMessage))
  390. {
  391. this.ShowError(errorMessage);
  392. throw new WizardCancelledException(errorMessage);
  393. }
  394. throw new WizardCancelledException();
  395. }
  396. private void UpdateConfiguration()
  397. {
  398. if (this._isClientAccessEnabled || this._isODataEndpointEnabled)
  399. {
  400. Project activeProject = this.ActiveProject;
  401. IVsHierarchy vsHierarchy = this.GetVsHierarchy(activeProject);
  402. IVsApplicationConfigurationManager service = this.GetService(typeof(IVsApplicationConfigurationManager)) as IVsApplicationConfigurationManager;
  403. if (service == null)
  404. {
  405. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_ConfigurationManager);
  406. }
  407. using (IVsApplicationConfiguration configuration = service.GetApplicationConfiguration(vsHierarchy, 0xfffffffe))
  408. {
  409. if ((configuration != null) && configuration.FileExists())
  410. {
  411. System.Configuration.Configuration configuration2 = configuration.LoadConfiguration();
  412. if (configuration2 != null)
  413. {
  414. WebConfigUtil util = new WebConfigUtil(configuration2);
  415. bool flag = util.DoWeNeedToAddHttpModule();
  416. bool flag2 = util.DoWeNeedToAddModuleToWebServer();
  417. bool flag3 = !util.IsAspNetCompatibilityEnabled();
  418. bool flag4 = !util.IsMultipleSiteBindingsEnabled();
  419. bool flag5 = util.DoWeNeedToValidateIntegratedModeToWebServer();
  420. bool flag6 = this._isODataEndpointEnabled && !util.IsEndpointDeclared(BusinessLogicClassConstants.ODataEndpointName);
  421. if (((flag || flag2) || (flag3 || flag4)) || (flag5 || flag6))
  422. {
  423. string domainServiceModuleTypeName = WebConfigUtil.GetDomainServiceModuleTypeName();
  424. configuration.QueryEditConfiguration();
  425. if (flag)
  426. {
  427. util.AddHttpModule(domainServiceModuleTypeName);
  428. }
  429. if (flag2)
  430. {
  431. util.AddModuleToWebServer(domainServiceModuleTypeName);
  432. }
  433. if (flag3)
  434. {
  435. util.SetAspNetCompatibilityEnabled(true);
  436. }
  437. if (flag4)
  438. {
  439. util.SetMultipleSiteBindingsEnabled(true);
  440. }
  441. if (flag5)
  442. {
  443. util.AddValidateIntegratedModeToWebServer();
  444. }
  445. if (flag6)
  446. {
  447. string oDataEndpointFactoryTypeName = WebConfigUtil.GetODataEndpointFactoryTypeName();
  448. util.AddEndpointDeclaration(BusinessLogicClassConstants.ODataEndpointName, oDataEndpointFactoryTypeName);
  449. }
  450. configuration2.Save();
  451. }
  452. }
  453. }
  454. }
  455. }
  456. }
  457. private Project ActiveProject
  458. {
  459. get
  460. {
  461. if (this._project == null)
  462. {
  463. Array activeSolutionProjects = (Array) this.DTE2.ActiveSolutionProjects;
  464. this._project = activeSolutionProjects.OfType<Project>().FirstOrDefault<Project>();
  465. if (this._project == null)
  466. {
  467. this.TerminateWizard(Resources.BusinessLogicClass_Error_No_Project);
  468. }
  469. }
  470. return this._project;
  471. }
  472. }
  473. private EnvDTE80.DTE2 DTE2
  474. {
  475. get
  476. {
  477. if (this._dte2 == null)
  478. {
  479. this.TerminateWizard(Resources.WizardError_No_DTE);
  480. }
  481. return this._dte2;
  482. }
  483. }
  484. internal InternalTestHook TestHook
  485. {
  486. get
  487. {
  488. if (this._testHook == null)
  489. {
  490. this._testHook = new InternalTestHook(this);
  491. }
  492. return this._testHook;
  493. }
  494. }
  495. internal class InternalTestHook
  496. {
  497. private DomainServiceClassWizard _wizard;
  498. internal InternalTestHook(DomainServiceClassWizard wizard)
  499. {
  500. this._wizard = wizard;
  501. }
  502. internal Microsoft.VisualStudio.ServiceModel.DomainServices.Tools.BusinessLogicClassDialog BusinessLogicClassDialog
  503. {
  504. get
  505. {
  506. return this._wizard._dialog;
  507. }
  508. }
  509. internal string GeneratedBusinessLogicCode
  510. {
  511. get
  512. {
  513. return this._wizard._businessLogicCode.SourceCode;
  514. }
  515. }
  516. internal string GeneratedMetadataCode
  517. {
  518. get
  519. {
  520. return this._wizard._metadataCode.SourceCode;
  521. }
  522. }
  523. }
  524. }
  525. }