public void GenerateModelCodeInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } if (package == null) { return; } var dte = package.GetServiceHelper(typeof(DTE)) as DTE; var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the DataAccess.cs to be placed"); return; } if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError(string.Format("The selected project type {0} does not support sqlite-net (please let me know if I am wrong)", project.Kind)); return; } if (project.CodeModel != null && project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp) { EnvDteHelper.ShowError("Unsupported code language, only C# is currently supported"); return; } if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLite) { EnvDteHelper.ShowError("Sorry, only SQLite databases are supported"); return; } try { var defaultNamespace = "Model"; if (project.Properties.Item("DefaultNamespace") != null) { defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString(); } var projectPath = project.Properties.Item("FullPath").Value.ToString(); using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var generator = DataConnectionHelper.CreateGenerator(repository, databaseInfo.DatabaseInfo.DatabaseType); generator.GenerateSqliteNetModel(defaultNamespace); var fileName = Path.Combine(projectPath, "DataAccess.cs"); if (File.Exists(fileName)) { File.Delete(fileName); } var warning = @"//This code was generated by a tool. //Changes to this file will be lost if the code is regenerated." + Environment.NewLine + "// See the blog post here for help on using the generated code: http://erikej.blogspot.dk/2014/10/database-first-with-sqlite-in-universal.html" + Environment.NewLine; File.WriteAllText(fileName, warning + generator.GeneratedScript); project.ProjectItems.AddFromFile(fileName); EnvDteHelper.ShowMessage("DataAccess.cs generated."); DataConnectionHelper.LogUsage("DatabaseSqliteNetCodegen"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType); } }
public void GenerateEfPocoInProject(object sender, ExecutedRoutedEventArgs e) { EnvDteHelper.LaunchUrl("https://github.com/ErikEJ/SqlCeToolbox/wiki/EntityFramework-Reverse-POCO-Code-First-Generator"); var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } var isEf6 = SqlCeToolboxPackage.VsSupportsEf6(); try { if (package == null) { return; } var dte = package.GetServiceHelper(typeof(DTE)) as DTE; if (dte == null) { return; } if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the code to be placed"); return; } if (dte.Solution.SolutionBuild.BuildState == vsBuildState.vsBuildStateNotStarted) { EnvDteHelper.ShowError("Please build the project before proceeding"); return; } if (isEf6) { if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40 && !dteH.ContainsEfSqlCeReference(project)) { EnvDteHelper.ShowError("Please add the EntityFramework.SqlServerCompact NuGet package to the project"); return; } if (databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 && !dteH.ContainsEfSqlCeLegacyReference(project)) { EnvDteHelper.ShowError("Please add the EntityFramework.SqlServerCompact.Legacy NuGet package to the project"); return; } if (!File.Exists(Path.Combine(dteH.GetVisualStudioInstallationDir(SqlCeToolboxPackage.VisualStudioVersion), "ItemTemplates\\CSharp\\Data\\1033\\DbCtxCSEF6\\CSharpDbContext.Context.tt"))) { EnvDteHelper.ShowError("Please install the Entity Framework 6 Tools in order to proceed"); return; } } if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support Entity Framework (please let me know if I am wrong)"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type does not have a TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } var dte2 = (DTE2)package.GetServiceHelper(typeof(DTE)); // ReSharper disable once SuspiciousTypeConversion.Global var solution2 = dte2.Solution as Solution2; if (solution2 != null) { var projectItemTemplate = solution2.GetProjectItemTemplate("EntityFramework Reverse POCO Code First Generator", "CSharp"); if (!string.IsNullOrEmpty(projectItemTemplate)) { project.ProjectItems.AddFromTemplate(projectItemTemplate, "Database.tt"); } } DataConnectionHelper.LogUsage("DatabaseCreateEFPOCO"); } // EDM end catch (Exception ex) { if (ex.GetType() == typeof(FileNotFoundException)) { EnvDteHelper.ShowMessage("Unable to find the EF Reverse POCO Template, is it installed?"); } else { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } } }
public async void GenerateEfCoreModelInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } var dbType = databaseInfo.DatabaseInfo.DatabaseType; var dte = package?.GetServiceHelper(typeof(DTE)) as DTE; if (dte == null) { return; } if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the EF Core Model to be placed"); return; } try { var ptd = new PickTablesDialog { IncludeTables = true }; using (var repository = Helpers.RepositoryHelper.CreateRepository(new DatabaseInfo { ConnectionString = databaseInfo.DatabaseInfo.ConnectionString, DatabaseType = databaseInfo.DatabaseInfo.DatabaseType })) { ptd.Tables = repository.GetAllTableNamesForExclusion(); } var res = ptd.ShowModal(); if (!res.HasValue || !res.Value) { return; } var revEng = new EfCoreReverseEngineer(); var classBasis = Helpers.RepositoryHelper.GetClassBasis(databaseInfo.DatabaseInfo.ConnectionString, dbType); var model = revEng.GenerateClassName(classBasis) + "Context"; var packageResult = dteH.ContainsEfCoreReference(project, dbType); var modelDialog = new EfCoreModelDialog { InstallNuGetPackage = !packageResult.Item1, ModelName = model, ProjectName = project.Name, NameSpace = project.Properties.Item("DefaultNamespace").Value.ToString() }; var result = modelDialog.ShowModal(); if (!result.HasValue || result.Value != true) { return; } var projectPath = project.Properties.Item("FullPath").Value.ToString(); var options = new ReverseEngineerOptions { UseFluentApiOnly = !modelDialog.UseDataAnnotations, ConnectionString = databaseInfo.DatabaseInfo.ConnectionString, ContextClassName = modelDialog.ModelName, DatabaseType = (EFCoreReverseEngineer.DatabaseType)dbType, ProjectPath = projectPath, OutputPath = modelDialog.OutputPath, ProjectRootNamespace = modelDialog.NameSpace, Tables = ptd.Tables }; var revEngResult = revEng.GenerateFiles(options); if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 2) { foreach (var filePath in revEngResult.EntityTypeFilePaths) { project.ProjectItems.AddFromFile(filePath); } } if (modelDialog.SelectedTobeGenerated == 0 || modelDialog.SelectedTobeGenerated == 1) { project.ProjectItems.AddFromFile(revEngResult.ContextFilePath); dte.ItemOperations.OpenFile(revEngResult.ContextFilePath); } packageResult = dteH.ContainsEfCoreReference(project, dbType); var missingProviderPackage = packageResult.Item1 ? null : packageResult.Item2; if (modelDialog.InstallNuGetPackage) { missingProviderPackage = null; } ReportRevEngErrors(revEngResult, missingProviderPackage); if (modelDialog.InstallNuGetPackage) { package.SetStatus("Installing EF Core provider package"); var nuGetHelper = new NuGetHelper(); await nuGetHelper.InstallPackageAsync(packageResult.Item2, project); } DataConnectionHelper.LogUsage("DatabaseCreateEfCoreModel"); } catch (Exception ex) { package.SetStatus(null); DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }
public void SyncFxGenerateSyncCodeInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } if (package == null) { return; } var dte = package.GetServiceHelper(typeof(DTE)) as DTE; var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed"); return; } if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)"); return; } if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp) { EnvDteHelper.ShowError("Unsupported code language, only C# is currently supported"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35) { EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now"); return; } try { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption); if (fileNameWithoutExtension != null) { var model = fileNameWithoutExtension.Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); var sfd = new SyncFxDialog { ModelName = model }; var res = sfd.ShowModal(); if (!res.HasValue || res.Value != true || (sfd.Tables.Count <= 0)) { return; } model = sfd.ModelName; var defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString(); var classes = new SyncFxHelper().GenerateCodeForScope(string.Empty, databaseInfo.DatabaseInfo.ConnectionString, "SQLCE", model, sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList(), defaultNamespace); var projectPath = project.Properties.Item("FullPath").Value.ToString(); foreach (var item in classes) { var fileName = Path.Combine(projectPath, item.Key + ".cs"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, item.Value); project.ProjectItems.AddFromFile(fileName); } //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx EnvDteHelper.AddReference(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.ShowMessage("Scope: " + model + " code generated."); DataConnectionHelper.LogUsage("DatabaseSyncCodegen"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }
public void SyncFxGenerateLocalDatabaseCacheCode(object sender, ExecutedRoutedEventArgs e) { // http://www.mztools.com/articles/2007/MZ2007011.aspx var menuItem = sender as MenuItem; if (menuItem == null) { return; } var dte = _package.GetServiceHelper(typeof(DTE)) as DTE; var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed"); return; } if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)"); return; } if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp) { EnvDteHelper.ShowError("Unsupported code language, only C# is currently supported"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } try { var serverConnectionString = DataConnectionHelper.PromptForConnectionString(_package); if (string.IsNullOrEmpty(serverConnectionString)) { return; } string clientConnectionString; //grab target SQL CE Database var dialog = new ConnectionDialog(); dialog.DbType = DatabaseType.SQLCE35; var result = dialog.ShowModal(); if (result.HasValue && result.Value && !string.IsNullOrWhiteSpace(dialog.ConnectionString)) { clientConnectionString = dialog.ConnectionString; } else { return; } var model = string.Empty; var sfd = new SyncFxDialog(); var databaseInfo = new DatabaseMenuCommandParameters { DatabaseInfo = new DatabaseInfo { ConnectionString = serverConnectionString, DatabaseType = DatabaseType.SQLServer } }; SyncFxGetObjectsForSync(sfd, databaseInfo); sfd.ModelName = model; var res = sfd.ShowModal(); if (res.HasValue && res.Value && (sfd.Tables.Count > 0) && !string.IsNullOrWhiteSpace(sfd.ModelName)) { model = sfd.ModelName; var defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString(); var columns = sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList(); var classes = new SyncFxHelper().GenerateCodeForScope(serverConnectionString, clientConnectionString, "SQL", model, columns, defaultNamespace); var projectPath = project.Properties.Item("FullPath").Value.ToString(); foreach (var item in classes) { var fileName = Path.Combine(projectPath, item.Key + ".cs"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, item.Value); project.ProjectItems.AddFromFile(fileName); } //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx EnvDteHelper.AddReference(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.ShowMessage("Scope: " + model + " code generated."); DataConnectionHelper.LogUsage("DatabasesSyncAddLocalDBCache"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, DatabaseType.SQLServer); } }
public void GenerateDataContextInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } var isDesktop = (bool)((MenuItem)sender).Tag; if (package == null) { return; } var dte = package.GetServiceHelper(typeof(DTE)) as DTE; if (dte == null) { return; } if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var helper = Helpers.RepositoryHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType); if (!helper.IsV35DbProviderInstalled()) { EnvDteHelper.ShowError("This feature requires the SQL Server Compact 3.5 SP2 DbProvider to be properly installed"); return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the DataContext to be placed"); return; } if (!isDesktop && !dteH.AllowedWpProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support Windows Phone (please let me know if I am wrong)"); return; } if (isDesktop && !dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support LINQ to SQL (please let me know if I am wrong)"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type does not support Windows Phone - missing TargetFrameworkMoniker"); return; } if (!isDesktop) { if (project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "Silverlight,Version=v4.0,Profile=WindowsPhone71" || project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.0" || project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.1" ) { } else { EnvDteHelper.ShowError("The selected project type does not support Windows Phone 7.1/8.0 - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } } if (isDesktop && !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } if (!isDesktop && databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35) { EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now"); return; } var sqlMetalPath = ProbeSqlMetalRegPaths(); if (string.IsNullOrEmpty(sqlMetalPath)) { EnvDteHelper.ShowError("Could not find SQLMetal file location"); return; } var sdfFileName = string.Empty; try { using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var tables = repository.GetAllTableNames(); var pks = repository.GetAllPrimaryKeys(); var checkedTables = string.Empty; foreach (var tableName in tables) { var pk = pks.Where(k => k.TableName == tableName).FirstOrDefault(); if (pk.TableName == null) { checkedTables += tableName + Environment.NewLine; } } if (!string.IsNullOrEmpty(checkedTables)) { var message = string.Format("The tables below do not have Primary Keys defined,{0}and will not be generated properly:{1}{2}", Environment.NewLine, Environment.NewLine, checkedTables); EnvDteHelper.ShowError(message); } var dbInfo = repository.GetDatabaseInfo(); foreach (var kvp in dbInfo) { if (kvp.Key == "Database") { sdfFileName = kvp.Value; break; } } sdfFileName = Path.GetFileName(sdfFileName); } var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption); if (fileNameWithoutExtension != null) { var model = fileNameWithoutExtension.Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); model = model + "Context"; var dcDialog = new DataContextDialog(); dcDialog.ModelName = model; dcDialog.IsDesktop = isDesktop; dcDialog.ProjectName = project.Name; dcDialog.NameSpace = project.Properties.Item("DefaultNamespace").Value.ToString(); if (EnvDteHelper.VbProject == new Guid(project.Kind)) { dcDialog.CodeLanguage = "VB"; } else { dcDialog.CodeLanguage = "C#"; } var result = dcDialog.ShowModal(); if (!result.HasValue || result.Value != true || string.IsNullOrWhiteSpace(dcDialog.ModelName)) { return; } if (dcDialog.AddRowversionColumns) { AddRowVersionColumns(databaseInfo); } var sdfPath = databaseInfo.DatabaseInfo.ConnectionString; //If version 4.0, create a 3.5 schema sdf, and use that as connection string if (isDesktop && databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40) { var tempFile = Path.GetTempFileName(); using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var generator = DataConnectionHelper.CreateGenerator(repository, tempFile, databaseInfo.DatabaseInfo.DatabaseType); generator.ScriptDatabaseToFile(Scope.Schema); } if (sdfFileName != null) { sdfPath = Path.Combine(Path.GetTempPath(), sdfFileName); } using (Stream stream = new MemoryStream(Resources.SqlCe35AddinStore)) { // Create a FileStream object to write a stream to a file using (var fileStream = File.Create(sdfPath, (int)stream.Length)) { // Fill the bytes[] array with the stream data var bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } var info = new DatabaseInfo { ConnectionString = "Data Source=" + sdfPath, DatabaseType = DatabaseType.SQLCE35 }; using (var repository = Helpers.RepositoryHelper.CreateRepository(info)) { var script = File.ReadAllText(tempFile); repository.ExecuteSql(script); } sdfPath = info.ConnectionString; } var versionNumber = GetVersionTableNumber(databaseInfo.DatabaseInfo, isDesktop); model = dcDialog.ModelName; var dcPath = Path.Combine(Path.GetTempPath(), model + ".cs"); if (dcDialog.CodeLanguage == "VB") { dcPath = Path.Combine(Path.GetTempPath(), model + ".vb"); } var parameters = " /provider:SQLCompact /code:\"" + dcPath + "\""; parameters += " /conn:\"" + sdfPath + "\""; parameters += " /context:" + model; if (dcDialog.Pluralize) { parameters += " /pluralize"; } if (!string.IsNullOrWhiteSpace(dcDialog.NameSpace)) { parameters += " /namespace:" + dcDialog.NameSpace; } var dcH = new DataContextHelper(); var sqlmetalResult = dcH.RunSqlMetal(sqlMetalPath, parameters); if (!File.Exists(dcPath)) { EnvDteHelper.ShowError("Error during SQL Metal run: " + sqlmetalResult); return; } if (!isDesktop) { using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { if (dcDialog.CodeLanguage == "VB") { DataContextHelper.FixDataContextVB(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } else { DataContextHelper.FixDataContextCS(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } } } if (dcDialog.MultipleFiles) { var classes = DataContextHelper.SplitIntoMultipleFiles(dcPath, dcDialog.NameSpace, model); var projectPath = project.Properties.Item("FullPath").Value.ToString(); foreach (var item in classes) { var fileName = Path.Combine(projectPath, item.Key + ".cs"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, item.Value); var classItem = dteH.GetProjectDataContextClass(project, fileName); if (classItem != null) { classItem.Delete(); } project.ProjectItems.AddFromFile(fileName); } } else { var extension = ".cs"; if (dcDialog.CodeLanguage == "VB") { extension = ".vb"; } var dcItem = dteH.GetProjectDc(project, model, extension); if (dcItem == null) { project.ProjectItems.AddFromFileCopy(dcPath); } else { if (EnvDteHelper.ShowMessageBox("The Data Context class already exists in the project, do you wish to replace it?", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, OLEMSGICON.OLEMSGICON_QUERY) == System.Windows.Forms.DialogResult.Yes) { dcItem.Delete(); project.ProjectItems.AddFromFileCopy(dcPath); } } } EnvDteHelper.AddReference(project, "System.Data.Linq"); if (dcDialog.AddConnectionStringBuilder) { var projectPath = project.Properties.Item("FullPath").Value.ToString(); var fileName = "LocalDatabaseConnectionStringBuilder.cs"; var filePath = Path.Combine(projectPath, fileName); if (File.Exists(filePath)) { File.Delete(filePath); } using (Stream stream = new MemoryStream(Resources.LocalDatabaseConnectionStringBuilder)) { // Create a FileStream object to write a stream to a file using (var fileStream = File.Create(filePath, (int)stream.Length)) { // Fill the bytes[] array with the stream data var bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } project.ProjectItems.AddFromFile(filePath); } // Creates __Version table and adds one row if desired if (dcDialog.AddVersionTable) { using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var list = repository.GetAllTableNames(); if (!list.Contains("__VERSION")) { repository.ExecuteSql(string.Format(@" CREATE TABLE [__VERSION] ( [SchemaVersion] int NOT NULL , [DateUpdated] datetime NOT NULL DEFAULT (GETDATE()) ); GO CREATE INDEX [IX_SchemaVersion] ON [__VERSION] ([SchemaVersion] DESC); GO INSERT INTO [__VERSION] ([SchemaVersion]) VALUES ({0}); GO", versionNumber)); } } } DataConnectionHelper.LogUsage("DatabaseCreateDC"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }
public void GenerateModelCodeInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } if (package == null) { return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the DataAccess.cs to be placed"); return; } if (!dteH.ContainsAllowed(project)) { EnvDteHelper.ShowError("The selected project type does not support sqlite-net (please let me know if I am wrong)"); return; } if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLite) { EnvDteHelper.ShowError("Sorry, only SQLite databases are supported"); return; } try { var defaultNamespace = "Model"; var projectNamespace = ThreadHelper.JoinableTaskFactory.Run(() => project.GetAttributeAsync("DefaultNamespace")); if (projectNamespace != null) { defaultNamespace = projectNamespace; } var projectPath = Path.GetDirectoryName(project.FullPath); using (var repository = Helpers.RepositoryHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var generator = DataConnectionHelper.CreateGenerator(repository, databaseInfo.DatabaseInfo.DatabaseType); generator.GenerateSqliteNetModel(defaultNamespace); var fileName = Path.Combine(projectPath, "DataAccess.cs"); if (File.Exists(fileName)) { File.Delete(fileName); } var warning = @"//This code was generated by a tool. //Changes to this file will be lost if the code is regenerated." + Environment.NewLine + "// See the blog post here for help on using the generated code: http://erikej.blogspot.dk/2014/10/database-first-with-sqlite-in-universal.html" + Environment.NewLine; File.WriteAllText(fileName, warning + generator.GeneratedScript); ThreadHelper.JoinableTaskFactory.Run(() => project.AddExistingFilesAsync(fileName)); EnvDteHelper.ShowMessage("DataAccess.cs generated."); DataConnectionHelper.LogUsage("DatabaseSqliteNetCodegen"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType); } }
public async void GenerateEfPocoFromDacPacInProject(object sender, ExecutedRoutedEventArgs e) { EnvDteHelper.LaunchUrl("https://github.com/sjh37/EntityFramework-Reverse-POCO-Code-First-Generator"); var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } var isEf6 = SqlCeToolboxPackage.VsSupportsEf6(); try { var dte = _package?.GetServiceHelper(typeof(DTE)) as DTE; if (dte == null) { return; } if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the generated code to be placed"); return; } if (dte.Solution.SolutionBuild.BuildState == vsBuildState.vsBuildStateNotStarted) { EnvDteHelper.ShowError("Please build the project before proceeding"); return; } if (isEf6) { if (!dteH.ContainsEf6Reference(project)) { EnvDteHelper.ShowError("Please add the EntityFramework 6.x NuGet package to the project"); return; } } if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDteHelper.ShowError("The selected project type does not support Entity Framework (please let me know if I am wrong)"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDteHelper.ShowError("The selected project type does not have a TargetFrameworkMoniker"); return; } if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value); return; } var ofd = new OpenFileDialog { Filter = "Dacpac (*.dacpac)|*.dacpac|All Files(*.*)|*.*", CheckFileExists = true, Multiselect = false, ValidateNames = true }; if (ofd.ShowDialog() != true) { return; } var dacPacFileName = ofd.FileName; var connectionStringBuilder = new SqlConnectionStringBuilder { DataSource = @"(localdb)\mssqllocaldb", InitialCatalog = Path.GetFileNameWithoutExtension(dacPacFileName), IntegratedSecurity = true }; var dacFxHelper = new DacFxHelper(_package); await dacFxHelper.RunDacPackageAsync(connectionStringBuilder, dacPacFileName); var prefix = "App"; var configPath = Path.Combine(Path.GetTempPath(), prefix + ".config"); var item = dteH.GetProjectConfig(project); if (item == null) { //Add app.config file to project var cfgSb = new StringBuilder(); cfgSb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); cfgSb.AppendLine("<configuration>"); cfgSb.AppendLine("</configuration>"); File.WriteAllText(configPath, cfgSb.ToString(), Encoding.UTF8); item = project.ProjectItems.AddFromFileCopy(configPath); } if (item != null) { AppConfigHelper.WriteConnectionStringToAppConfig("MyDbContext", connectionStringBuilder.ConnectionString, project.FullName, "System.Data.SqlClient", prefix, item.Name); } var dte2 = (DTE2)_package.GetServiceHelper(typeof(DTE)); // ReSharper disable once SuspiciousTypeConversion.Global var solution2 = dte2.Solution as Solution2; var projectItemTemplate = solution2?.GetProjectItemTemplate("EntityFramework Reverse POCO Code First Generator", "CSharp"); if (!string.IsNullOrEmpty(projectItemTemplate)) { var projectItem = dteH.GetProjectDataContextClass(project, "Database.tt".ToLowerInvariant()); if (projectItem == null) { project.ProjectItems.AddFromTemplate(projectItemTemplate, "Database.tt"); EnvDteHelper.ShowMessage("Please run Custom Tool with the Database.tt file"); } else { EnvDteHelper.ShowMessage("Database.tt already exists, please run Custom Tool with existing Database.tt file"); } } DataConnectionHelper.LogUsage("DatabaseCreateEFPOCODacpac"); } catch (Exception ex) { if (ex.GetType() == typeof(FileNotFoundException)) { EnvDteHelper.ShowMessage("Unable to find the EF Reverse POCO Template, is it installed?"); } else { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } } }
public void GenerateEfCoreModelInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } var dbType = databaseInfo.DatabaseInfo.DatabaseType; var dte = package?.GetServiceHelper(typeof(DTE)) as DTE; if (dte == null) { return; } if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDteHelper.ShowError("Cannot generate code while debugging"); return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the EF Core Model to be placed"); return; } try { var ptd = new PickTablesDialog { IncludeTables = true }; using (var repository = DataConnectionHelper.CreateRepository(new DatabaseInfo { ConnectionString = databaseInfo.DatabaseInfo.ConnectionString, DatabaseType = databaseInfo.DatabaseInfo.DatabaseType })) { ptd.Tables = repository.GetAllTableNamesForExclusion(); } var res = ptd.ShowModal(); if (!res.HasValue || !res.Value) { return; } var revEng = new EFCoreReverseEngineer.EfCoreReverseEngineer(); var classBasis = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption); if (dbType == DatabaseType.SQLServer) { classBasis = new SqlConnectionStringBuilder(databaseInfo.DatabaseInfo.ConnectionString).InitialCatalog; } var model = revEng.GenerateClassName(classBasis) + "Context"; var modelDialog = new EfCoreModelDialog { ModelName = model, ProjectName = project.Name, NameSpace = project.Properties.Item("DefaultNamespace").Value.ToString() }; var result = modelDialog.ShowModal(); if (!result.HasValue || result.Value != true) { return; } var projectPath = project.Properties.Item("FullPath").Value.ToString(); var options = new ReverseEngineerOptions { UseFluentApiOnly = !modelDialog.UseDataAnnotations, ConnectionString = databaseInfo.DatabaseInfo.ConnectionString, ContextClassName = modelDialog.ModelName, DatabaseType = (EFCoreReverseEngineer.DatabaseType)dbType, ProjectPath = projectPath, OutputPath = modelDialog.OutputPath, ProjectRootNamespace = modelDialog.NameSpace, Tables = ptd.Tables }; var revEngResult = revEng.GenerateFiles(options); foreach (var filePath in revEngResult.FilePaths) { project.ProjectItems.AddFromFile(filePath); } if (revEngResult.FilePaths.Count > 0) { dte.ItemOperations.OpenFile(revEngResult.FilePaths.Last()); } ReportRevEngErrors(revEngResult, dteH.ContainsEfCoreReference(project, dbType)); DataConnectionHelper.LogUsage("DatabaseCreateEfCoreModel"); } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }
public async void SyncFxGenerateSyncCodeInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } if (package == null) { return; } var dteH = new EnvDteHelper(); var project = dteH.GetProject(); if (project == null) { EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed"); return; } if (!dteH.ContainsAllowed(project)) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)"); return; } var tfm = ThreadHelper.JoinableTaskFactory.Run(() => project.GetAttributeAsync("TargetFrameworkMoniker")); if (string.IsNullOrEmpty(tfm)) { EnvDteHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker"); return; } if (!tfm.Contains(".NETFramework")) { EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + tfm); return; } if (databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35) { EnvDteHelper.ShowError("Sorry, only version 3.5 databases are supported for now"); return; } try { var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption); if (fileNameWithoutExtension != null) { var model = fileNameWithoutExtension.Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); var sfd = new SyncFxDialog { ModelName = model }; var res = sfd.ShowModal(); if (!res.HasValue || res.Value != true || (sfd.Tables.Count <= 0)) { return; } model = sfd.ModelName; var defaultNamespace = ThreadHelper.JoinableTaskFactory.Run(() => project.GetAttributeAsync("DefaultNamespace")); var classes = new SyncFxHelper().GenerateCodeForScope(string.Empty, databaseInfo.DatabaseInfo.ConnectionString, "SQLCE", model, sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList(), defaultNamespace); var projectPath = Path.GetDirectoryName(project.FullPath); foreach (var item in classes) { var fileName = Path.Combine(projectPath, item.Key + ".cs"); if (File.Exists(fileName)) { File.Delete(fileName); } File.WriteAllText(fileName, item.Value); ThreadHelper.JoinableTaskFactory.Run(() => project.AddExistingFilesAsync(fileName)); } //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx await EnvDteHelper.AddReferenceAsync(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"); EnvDteHelper.ShowMessage("Scope: " + model + " code generated."); DataConnectionHelper.LogUsage("DatabaseSyncCodegen"); } } catch (Exception ex) { DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }