Exemplo n.º 1
0
        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);
                }
            }
        }