/// <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>
        /// Adds the bindings.
        /// </summary>
        /// <param name="FormPath">The form path.</param>
        /// <param name="Strategy">The strategy.</param>
        private void AddBindings(string FormPath, WindowsFormsCodeGeneratorStrategy Strategy)
        {
            string     originalContents = File.ReadAllText(FormPath);
            FileStream fs = new FileStream(FormPath, FileMode.Truncate, FileAccess.Write, FileShare.Read, 16284);

            using (StringReader sr = new StringReader(originalContents))
            {
                using (sw = new IdentedStreamWriter(fs))
                {
                    Strategy.Writer = sw;
                    string line = null;

                    while ((line = sr.ReadLine()) != null)
                    {
                        Strategy.Execute(line);
                    }
                }
            }
        }
        /// <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);
            }
        }