/// <summary>
 /// Runs custom wizard logic at the beginning of a template wizard run.
 /// </summary>
 /// <param name="automationObject">The automation object being used by the template wizard.</param>
 /// <param name="replacementsDictionary">The list of standard parameters to be replaced.</param>
 /// <param name="runKind">A <see cref="T:Microsoft.VisualStudio.TemplateWizard.WizardRunKind" /> indicating the type of wizard run.</param>
 /// <param name="customParams">The custom parameters with which to perform parameter replacement in the project.</param>
 public void RunStarted(Object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, Object[] customParams)
 {
     try
     {
         dte = automationObject as DTE;
         Array   activeProjects = (Array)dte.ActiveSolutionProjects;
         Project activeProj     = (Project)activeProjects.GetValue(0);
         _projectPath          = System.IO.Path.GetDirectoryName(activeProj.FullName);
         _projectNamespace     = activeProj.Properties.Item("DefaultNamespace").Value.ToString();
         _NetFxVersion         = replacementsDictionary["$targetframeworkversion$"];
         _itemTemplateTempPath = customParams[0].ToString().Substring(0, customParams[0].ToString().LastIndexOf("\\"));
         ItemTemplatesWebWizard form = new ItemTemplatesWebWizard(_language, dte, _projectType);
         form.StartPosition = FormStartPosition.CenterScreen;
         DialogResult result = form.ShowDialog();
         if (result == DialogResult.OK)
         {
             GetFormValues(form);
             string providerConnectionString = ItemTemplateUtilities.GetProviderConnectionString(_selectedModel, dte, false);
             if (!string.IsNullOrEmpty(providerConnectionString))
             {
                 _connectionString = providerConnectionString;
                 _connectionName   = ItemTemplateUtilities.GetConnectionStringName(_selectedModel, dte, false);
                 _connection       = new MySqlConnection(_connectionString);
             }
         }
     }
     catch (WizardCancelledException wce)
     {
         throw wce;
     }
     catch (Exception e)
     {
         SendToGeneralOutputWindow(string.Format("An error occurred: {0}\n\n {1}", e.Message, e.StackTrace));
     }
 }
        /// <summary>
        /// Runs custom wizard logic when the wizard has completed all tasks.
        /// </summary>
        public void RunFinished()
        {
            string    frmName        = string.Empty;
            Array     activeProjects = (Array)dte.ActiveSolutionProjects;
            Project   project        = null;
            VSProject vsProj         = null;

            project = (Project)activeProjects.GetValue(0);

            if (project == null)
            {
                return;
            }

            vsProj = project.Object as VSProject;
            var tables = new List <string>();

            Settings.Default.MVCWizardConnection = _connectionString;
            Settings.Default.Save();
            if (_generalPane != null)
            {
                _generalPane.Activate();
            }

            SendToGeneralOutputWindow("Starting project generation...");
            if (_selectedTables != null && _dataAccessTechnology != DataAccessTechnology.None)
            {
                _selectedTables.ForEach(t => tables.Add(t.Name));
                SendToGeneralOutputWindow("Generating Entity Framework model...");
                if (tables.Count > 0)
                {
                    if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5)
                    {
                        _currentEntityFrameworkVersion = ENTITY_FRAMEWORK_VERSION_5;
                    }
                    else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework6)
                    {
                        _currentEntityFrameworkVersion = ENTITY_FRAMEWORK_VERSION_6;
                    }

                    if (string.IsNullOrEmpty(_projectPath))
                    {
                        _projectPath = System.IO.Path.GetDirectoryName(project.FullName);
                    }

                    string modelPath = Path.Combine(_projectPath, "Models");
                    ItemTemplateUtilities.GenerateEntityFrameworkModel(project, vsProj, new MySqlConnection(_connectionString), _selectedModel, tables,
                                                                       modelPath, "1", _language, ColumnMappings, ref TablesIncludedInModel);
                    GenerateMVCItems(vsProj);
                }
            }

            SendToGeneralOutputWindow("Finished MVC item generation.");
        }
        /// <summary>
        /// Adds the bindings.
        /// </summary>
        /// <param name="vsProj">The vs proj.</param>
        /// <param name="Strategy">The strategy.</param>
        /// <param name="frmName">Name of the form.</param>
        /// <param name="frmDesignerName">The name of the Form designer.</param>
        private void AddBindings(VSProject vsProj, WindowsFormsCodeGeneratorStrategy Strategy, string frmName, string frmDesignerName)
        {
            string ext = Strategy.GetExtension();

            SendToGeneralOutputWindow(string.Format("Customizing Form {0} Code...", frmName));
            // Get Form.cs
            ProjectItem item = ItemTemplateUtilities.FindProjectItem(vsProj.Project.ProjectItems, frmName + ext);
            // Get Form.Designer.cs
            ProjectItem itemDesigner = ItemTemplateUtilities.FindProjectItem(item.ProjectItems, frmDesignerName + ext);

            AddBindings((string)(item.Properties.Item("FullPath").Value), Strategy);
            AddBindings((string)(itemDesigner.Properties.Item("FullPath").Value), Strategy);
        }
        /// <summary>
        /// Generates the detail tables definition based on the master-detail data of the model, getting the detail foreign keys as well.
        /// </summary>
        private void GenerateDetailModelsForItemTemplates()
        {
            if (DetailForeignKeys != null)
            {
                DetailForeignKeys.Clear();
            }

            _detailTable = _detailEntity;
            if (string.IsNullOrEmpty(_detailTable))
            {
                return;
            }

            _detailColumns = BaseWizard <BaseWizardForm, WindowsFormsCodeGeneratorStrategy> .GetColumnsFromTable(_detailTable, _connection);

            ItemTemplateUtilities.RetrieveAllFkInfo(_connection, _detailTable, out DetailForeignKeys);
            _colValidationsDetail = ValidationsGrid.GetColumnValidationList(_detailTable, _detailColumns, DetailForeignKeys);
        }
        /// <summary>
        /// Initializes the column mappings.
        /// </summary>
        /// <param name="fks">The FKS.</param>
        internal void InitializeColumnMappings(Dictionary <string, MySql.Data.VisualStudio.Wizards.ForeignKeyColumnInfo> fks)
        {
            foreach (KeyValuePair <string, MySql.Data.VisualStudio.Wizards.ForeignKeyColumnInfo> kvp in fks)
            {
                string fkTableName = kvp.Value.ReferencedTableName;
                if (string.IsNullOrEmpty(fkTableName))
                {
                    continue;
                }

                if (ColumnMappings.ContainsKey(fkTableName))
                {
                    continue;
                }

                Dictionary <string, Column> dicCols          = ItemTemplateUtilities.GetColumnsFromTable(fkTableName, _connection);
                List <ColumnValidation>     myColValidations = ValidationsGrid.GetColumnValidationList(fkTableName, dicCols, null);
                ColumnMappings.Add(fkTableName, myColValidations.ToDictionary(p => { return(p.Name); }));
            }
        }
        /// <summary>
        /// Generates the tables and columns based on the model information. Also, it gets the foreign keys data.
        /// </summary>
        private void GenerateModelsForItemTemplates()
        {
            if (_columns == null || _columns.Count == 0)
            {
                if (ForeignKeys != null)
                {
                    ForeignKeys.Clear();
                }

                _table   = _selectedEntity;
                _columns = BaseWizard <BaseWizardForm, WindowsFormsCodeGeneratorStrategy> .GetColumnsFromTable(_table, _connection);

                ItemTemplateUtilities.RetrieveAllFkInfo(_connection, _table, out ForeignKeys);
                _colValidations = ValidationsGrid.GetColumnValidationList(_table, _columns, ForeignKeys);
            }

            if ((_GuiType == Wizards.GuiType.MasterDetail) && ((_detailColumns == null) || (_detailColumns.Count == 0)))
            {
                GenerateDetailModelsForItemTemplates();
            }
        }
Ejemplo n.º 7
0
        internal void FillComboModels()
        {
            try
            {
                LockUI();
                Array   activeProjects = (Array)Dte.ActiveSolutionProjects;
                Project project        = (Project)activeProjects.GetValue(0);
                models = new List <string>();
                models = ItemTemplateUtilities.GetModels(project.ProjectItems, ref models);

                foreach (var model in models)
                {
                    comboModelsList.Items.Add(model);
                }

                SetModelsAutoCompleteCollection();
            }
            finally
            {
                UnlockUI();
            }
        }
        /// <summary>
        /// Runs custom wizard logic when the wizard has completed all tasks.
        /// </summary>
        public void RunFinished()
        {
            Array     activeProjects = (Array)dte.ActiveSolutionProjects;
            Project   project        = (Project)activeProjects.GetValue(0);
            VSProject vsProj         = null;

            if (wizardFinished)
            {
#if NET_40_OR_GREATER
                string             frmName = string.Empty;
                SortedSet <string> tables  = new SortedSet <string>();
                Dictionary <string, WindowsFormsCodeGeneratorStrategy> strategies = new Dictionary <string, WindowsFormsCodeGeneratorStrategy>();
                vsProj = project.Object as VSProject;
                ItemTemplateUtilities.CopyResourcesToProject(project, _itemTemplateTempPath);
                try
                {
                    // Ensure all model exists, even if user didn't went through validation pages, so metadata for table used in FKs is already loaded.
                    GenerateModelsForItemTemplates();
                    string detailTableName          = _detailEntity;
                    string _canonicalTableName      = ItemTemplateUtilities.GetCanonicalIdentifier(_selectedEntity);
                    string canonicalDetailTableName = ItemTemplateUtilities.GetCanonicalIdentifier(detailTableName);
                    // Gather all the tables
                    tables.Add(_selectedEntity);
                    if (!string.IsNullOrEmpty(detailTableName))
                    {
                        tables.Add(detailTableName);
                    }

                    foreach (KeyValuePair <string, MySql.Data.VisualStudio.Wizards.ForeignKeyColumnInfo> kvp2 in ForeignKeys)
                    {
                        tables.Add(kvp2.Value.ReferencedTableName);
                    }

                    foreach (KeyValuePair <string, MySql.Data.VisualStudio.Wizards.ForeignKeyColumnInfo> kvp2 in DetailForeignKeys)
                    {
                        tables.Add(kvp2.Value.ReferencedTableName);
                    }

                    AddColumnMappings(_canonicalTableName, _colValidations);
                    if (!string.IsNullOrEmpty(detailTableName))
                    {
                        AddColumnMappings(canonicalDetailTableName, _colValidationsDetail);
                    }

                    InitializeColumnMappings(ForeignKeys);
                    InitializeColumnMappings(DetailForeignKeys);
                    // Generate the model using the proper technology
                    ItemTemplateUtilities.GenerateEntityFrameworkModel(project, vsProj, _connection, _selectedModel, tables.ToList(), _projectPath,
                                                                       _currentEntityFrameworkVersion, _language, ColumnMappings, ref TablesIncludedInModel);

                    // Generate screens for the selected table.
                    _hasDataGridDateColumn = false;
                    Dictionary <string, Column> Columns       = _columns;
                    Dictionary <string, Column> DetailColumns = _detailColumns;
                    _canonicalTableName      = ItemTemplateUtilities.GetCanonicalIdentifier(_selectedEntity);
                    detailTableName          = _detailEntity;
                    canonicalDetailTableName = ItemTemplateUtilities.GetCanonicalIdentifier(detailTableName);
                    if (!TablesIncludedInModel.ContainsKey(_selectedEntity))
                    {
                        SendToGeneralOutputWindow(string.Format("Skipping generation of screen for table '{0}' because it does not have primary key.", _selectedEntity));
                        return;
                    }

                    if ((_GuiType == GuiType.MasterDetail) && !TablesIncludedInModel.ContainsKey(_detailEntity))
                    {
                        // If Detail table does not have PK, then you cannot edit details, "degrade" layout from Master Detail to Individual Controls.
                        _GuiType = GuiType.IndividualControls;
                        SendToGeneralOutputWindow(string.Format("Degrading layout for table '{0}' from master detail to single controls (because detail table '{1}' does not have primary key).",
                                                                _selectedEntity, _detailEntity));
                    }

                    // Create the strategy
                    StrategyConfig config = new StrategyConfig(sw, _canonicalTableName, Columns, DetailColumns, _dataAccessTechnology, _GuiType, _language,
                                                               _colValidations != null, _colValidations, DetailValidationColumns, ItemTemplateUtilities.ConnectionStringWithIncludedPassword(_connection),
                                                               _connectionString, _selectedEntity, _detailEntity, _constraintName, ForeignKeys, DetailForeignKeys);
                    WindowsFormsCodeGeneratorStrategy Strategy = WindowsFormsCodeGeneratorStrategy.GetInstance(config);
                    strategies.Add(_selectedEntity, Strategy);
                    if (!_hasDataGridDateColumn)
                    {
                        ItemTemplateUtilities.EnsureCodeForDateTimeGridColumn(vsProj, Columns, DetailColumns, _language, _projectPath, _projectNamespace);
                    }

                    // Add new form to project.
                    frmName = string.Format("frm{0}", _canonicalTableName);
                    string frmDesignerName = string.Format("frm{0}.designer", _canonicalTableName);
                    ItemTemplateUtilities.AddNewForm(project, frmName, _projectPath, _projectNamespace, _language);

                    // Now generated the bindings & custom code
                    List <string> formNames  = new List <string>();
                    List <string> tableNames = new List <string>();
                    if (!TablesIncludedInModel.ContainsKey(_selectedEntity))
                    {
                        return;
                    }

                    _canonicalTableName = ItemTemplateUtilities.GetCanonicalIdentifier(_selectedEntity);
                    if (TablesIncludedInModel.ContainsKey(_selectedEntity))
                    {
                        frmName = string.Format("frm{0}", _canonicalTableName);
                        formNames.Add(frmName);
                        tableNames.Add(_selectedEntity);
                        frmDesignerName = string.Format("frm{0}.designer", _canonicalTableName);
                        WindowsFormsCodeGeneratorStrategy strategy = strategies[_selectedEntity];
                        AddBindings(vsProj, strategy, frmName, frmDesignerName);
                    }

                    // This line is a hack to avoid "Project Unavailable" exceptions.
                    project = (Project)((Array)(dte.ActiveSolutionProjects)).GetValue(0);
                    vsProj  = project.Object as VSProject;
                    ItemTemplateUtilities.RemoveTemplateForm(vsProj, _projectPath, _language);
                    ItemTemplateUtilities.FixNamespaces(_language, _projectPath, _projectNamespace, _dataAccessTechnology);
                    // Update the model name with the Conn string name
                    ItemTemplateUtilities.UpdateModelName(project, frmName, _projectPath, _projectNamespace, _connectionName, _language);
                    if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5)
                    {
                        string formFile = Path.Combine(_projectPath, _language == LanguageGenerator.CSharp ? string.Format("{0}.cs", frmName) : string.Format("{0}.vb", frmName));
                        if (File.Exists(formFile))
                        {
                            string contents = "";
                            contents = File.ReadAllText(formFile);
                            string strToReplace   = string.Format("ObjectResult<{0}> _entities = ctx.{0}.Execute(MergeOption.AppendOnly);", _selectedEntity);
                            string strReplaceWith = string.Format("var _entities = ctx.{0}.ToList<{0}>();", _selectedEntity);
                            contents = contents.Replace(strToReplace, strReplaceWith);
                            File.WriteAllText(formFile, contents);
                        }
                    }

                    SendToGeneralOutputWindow("Building Solution...");
                    project.DTE.Solution.SolutionBuild.Build(true);
                    Settings.Default.WinFormsWizardConnection = _connectionName;
                    Settings.Default.Save();
                    SendToGeneralOutputWindow("Finished item generation.");
                }
                catch (WizardException e)
                {
                    SendToGeneralOutputWindow(string.Format("An error ocurred: {0}\n\n{1}", e.Message, e.StackTrace));
                }
#else
                throw new NotImplementedException();
#endif
            }
            else
            {
                vsProj = project.Object as VSProject;
                ItemTemplateUtilities.RemoveTemplateForm(vsProj, _projectPath, _language);
            }
        }
Ejemplo n.º 9
0
        internal void FillTables(string modelName, DTE dte, bool checkForAppConfig)
        {
            string edmxFileName             = string.Format("{0}.edmx", modelName);
            string providerConnectionString = ItemTemplateUtilities.GetProviderConnectionString(edmxFileName, dte, checkForAppConfig);

            if (string.IsNullOrEmpty(providerConnectionString))
            {
                return;
            }

            this.ConnectionString = providerConnectionString;
            this.ConnectionName   = ItemTemplateUtilities.GetConnectionStringName(edmxFileName, dte, checkForAppConfig);
            LockUI();

            try
            {
                DoWorkEventHandler doWorker = (worker, doWorkerArgs) =>
                {
                    Application.DoEvents();
                    var cnn = new MySqlConnection(providerConnectionString);
                    cnn.Open();
                    var dtTables = cnn.GetSchema("Tables", new string[] { null, cnn.Database });
                    cnn.Close();
                    _tables = new BindingList <DbTables>();

                    this.Invoke((Action)(() =>
                    {
                        ComboEntities.Items.Clear();

                        for (int i = 0; i < dtTables.Rows.Count; i++)
                        {
                            _tables.Add(new DbTables(false, dtTables.Rows[i][2].ToString()));
                        }

                        _sourceTables.DataSource = _tables;

                        foreach (string table in _tables.Select(t => t.Name))
                        {
                            ComboEntities.Items.Add(table);
                        }

                        SetEntitiesAutoCompleteCollection();
                    }));
                };

                if (Worker != null)
                {
                    Worker.DoWork             -= doWorker;
                    Worker.RunWorkerCompleted -= _worker_RunWorkerCompleted;
                    Worker.Dispose();
                }

                Worker = new BackgroundWorker();
                Worker.WorkerSupportsCancellation = true;
                Worker.DoWork             += doWorker;
                Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);
                Worker.RunWorkerAsync();
            }
            finally
            {
                UnlockUI();
            }
        }
        /// <summary>
        /// Creates the MVC item and add it to the MVC project.
        /// </summary>
        /// <param name="vsProj">The Visual Studio project.</param>
        private void GenerateMVCItems(VSProject vsProj)
        {
            if (string.IsNullOrEmpty(_connectionString))
            {
                return;
            }

            if (_selectedTables == null || _selectedTables.Count == 0)
            {
                return;
            }

#if CLR4 || NET_40_OR_GREATER
            IServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte);
            Microsoft.VisualStudio.TextTemplating.VSHost.ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
            ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;
            var     controllerClassPath            = string.Empty;
            var     IndexFilePath  = string.Empty;
            var     fileExtension  = string.Empty;
            Version productVersion = Assembly.GetExecutingAssembly().GetName().Version;
            var     version        = String.Format("{0}.{1}.{2}", productVersion.Major, productVersion.Minor, productVersion.Build);
            double  visualStudioVersion;
            double.TryParse(ItemTemplateUtilities.GetVisualStudioVersion(dte), out visualStudioVersion);
            if (_language == LanguageGenerator.CSharp)
            {
                controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpControllerClass_FileName));
                IndexFilePath       = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpIndexFile_FileName));
                fileExtension       = "cs";
            }
            else
            {
                controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbControllerClass_FileName));
                IndexFilePath       = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbIndexFile_FileName));
                fileExtension       = "vb";
            }

            StringBuilder catalogs = new StringBuilder();
            catalogs = new StringBuilder("<h3> Catalog list</h3>");
            catalogs.AppendLine();

            foreach (var table in TablesIncludedInModel)
            {
                catalogs.AppendLine(string.Format(@"<div> @Html.ActionLink(""{0}"",""Index"", ""{0}"")</div>",
                                                  table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1)));
            }

            try
            {
                foreach (var table in TablesIncludedInModel)
                {
                    // creating controller file
                    sessionHost.Session = sessionHost.CreateSession();
                    sessionHost.Session["namespaceParameter"]            = string.Format("{0}.Controllers", _projectNamespace);
                    sessionHost.Session["applicationNamespaceParameter"] = string.Format("{0}.Models", _projectNamespace);
                    sessionHost.Session["controllerClassParameter"]      = string.Format("{0}Controller", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1));
                    if ((_dataAccessTechnology == DataAccessTechnology.EntityFramework6 && _language == LanguageGenerator.VBNET) ||
                        _language == LanguageGenerator.CSharp)
                    {
                        sessionHost.Session["modelNameParameter"] = _connectionName;
                    }
                    else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5 && _language == LanguageGenerator.VBNET)
                    {
                        sessionHost.Session["modelNameParameter"] = string.Format("{1}.{0}", _connectionName, _projectNamespace);
                    }

                    sessionHost.Session["classNameParameter"]       = table.Key;
                    sessionHost.Session["entityNameParameter"]      = table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1);
                    sessionHost.Session["entityClassNameParameter"] = table.Key;
                    if ((visualStudioVersion < 12.0 && _language == LanguageGenerator.VBNET) ||
                        _language == LanguageGenerator.CSharp)
                    {
                        sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", _projectNamespace, table.Key);
                    }
                    else if (_language == LanguageGenerator.VBNET && visualStudioVersion >= 12.0)
                    {
                        if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5)
                        {
                            sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{0}.{1}", _projectNamespace, table.Key);
                        }
                        else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework6)
                        {
                            sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", _projectNamespace, table.Key);
                        }
                    }

                    T4Callback    cb = new T4Callback();
                    StringBuilder resultControllerFile = new StringBuilder(t4.ProcessTemplate(controllerClassPath, File.ReadAllText(controllerClassPath), cb));
                    string        controllerFilePath   = string.Format(@"{0}\Controllers\{1}Controller.{2}", _projectPath,
                                                                       table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1), fileExtension);
                    File.WriteAllText(controllerFilePath, resultControllerFile.ToString());
                    if (cb.errorMessages.Count > 0)
                    {
                        File.AppendAllLines(controllerFilePath, cb.errorMessages);
                    }

                    vsProj.Project.ProjectItems.AddFromFile(controllerFilePath);
                    var viewPath = Path.GetFullPath(_projectPath + string.Format(@"\Views\{0}", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1)));
                    Directory.CreateDirectory(viewPath);
                    string resultViewFile = t4.ProcessTemplate(IndexFilePath, File.ReadAllText(IndexFilePath), cb);
                    File.WriteAllText(string.Format(viewPath + @"\Index.{0}html", fileExtension), resultViewFile);
                    if (cb.errorMessages.Count > 0)
                    {
                        File.AppendAllLines(controllerFilePath, cb.errorMessages);
                    }

                    vsProj.Project.ProjectItems.AddFromFile(string.Format(viewPath + @"\Index.{0}html", fileExtension));
                }
            }
            catch (Exception ex)
            {
                SendToGeneralOutputWindow(string.Format("An error occurred: {0}\n\n {1}", ex.Message, ex.StackTrace));
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.ItemTemplatesBaseWebWizard_GenerateMvcItemsError));
            }
#endif
        }