Exemple #1
0
 private void ShowPlanButton_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(SqlText))
     {
         return;
     }
     DataConnectionHelper.LogUsage("EditorShowPlan");
     try
     {
         using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
         {
             string sql      = GetSqlFromSqlEditorTextBox();
             string showPlan = repository.ParseSql(sql);
             try
             {
                 TryLaunchSqlplan(showPlan, true);
             }
             catch (Exception ex)
             {
                 DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35);
             }
         }
     }
     catch (Exception sqlException)
     {
         ParseSqlErrorToResultsBox(DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(sqlException));
     }
 }
        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            var item = TreeView1.SelectedItem as DatabaseTreeViewItem;

            if (item == null)
            {
                return;
            }
            try
            {
                if (e.Key == Key.C && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
                {
                    var databaseInfo = item.Tag as DatabaseInfo;
                    if (databaseInfo != null)
                    {
                        var helper = DataConnectionHelper.CreateEngineHelper(databaseInfo.DatabaseType);
                        Clipboard.Clear();
                        Clipboard.SetData(DataFormats.FileDrop, new[] { helper.PathFromConnectionString(databaseInfo.ConnectionString) });
                    }
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
Exemple #3
0
 private void ParseButton_Click(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(SqlText))
     {
         return;
     }
     DataConnectionHelper.LogUsage("EditorParse");
     try
     {
         using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
         {
             var textBox = new TextBox();
             textBox.FontFamily = _fontFamiliy;
             textBox.FontSize   = _fontSize;
             string sql = GetSqlFromSqlEditorTextBox();
             repository.ParseSql(sql);
             textBox.Text = "Statement(s) in script parsed and seems OK!";
             ClearResults();
             Resultspanel.Children.Add(textBox);
             tab2.Focus();
         }
     }
     catch (Exception ex)
     {
         ParseSqlErrorToResultsBox(DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(ex));
     }
 }
        public void SetPassword(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }
            try
            {
                var dbInfo = databaseInfo.DatabaseInfo;
                var pwd    = new PasswordDialog();
                pwd.ShowModal();
                if (!pwd.DialogResult.HasValue || !pwd.DialogResult.Value)
                {
                    return;
                }
                var helper = DataConnectionHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType);
                var newConnectionString = helper.ChangeDatabasePassword(databaseInfo.DatabaseInfo.ConnectionString, pwd.Password);
                if (dbInfo.FromServerExplorer)
                {
                    var providerId = Resources.SqlCompact35Provider;
                    if (dbInfo.DatabaseType == DatabaseType.SQLCE40)
                    {
                        providerId = Resources.SqlCompact40Provider;
                    }
                    DataConnectionHelper.RemoveDataConnection(package, dbInfo.ConnectionString, new Guid(providerId));
                }
                else
                {
                    DataConnectionHelper.RemoveDataConnection(databaseInfo.DatabaseInfo.ConnectionString);
                }

                if (!string.IsNullOrEmpty(newConnectionString))
                {
                    DataConnectionHelper.SaveDataConnection(newConnectionString, dbInfo.DatabaseType, package);
                    EnvDteHelper.ShowMessage("Password was set, and connection updated");
                }
                else
                {
                    EnvDteHelper.ShowMessage("Password was set, but could not update connection, please reconnect the database");
                }

                var control = _parentWindow.Content as ExplorerControl;
                if (control != null)
                {
                    control.BuildDatabaseTree();
                }
                DataConnectionHelper.LogUsage("DatabaseMaintainSetPassword");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
Exemple #5
0
        private async void ExecuteSqlScriptInEditor()
        {
            try
            {
                StartQuerying();
                using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
                {
                    var sql           = GetSqlFromSqlEditorTextBox();
                    var schemaChanged = false;
                    if (sql.Length == 0)
                    {
                        return;
                    }

                    var sbSql = new StringBuilder(sql);
                    sbSql = sbSql.Replace("\r", " \r");
                    sbSql = sbSql.Replace("GO  \r", "GO\r");
                    sql   = sbSql.Replace("GO \r", "GO\r").ToString();

                    var sw = new Stopwatch();
                    sw.Start();

                    var dataset = await Task.Run(()
                                                 // ReSharper disable once AccessToDisposedClosure
                                                 => repository.ExecuteSql(sql, out schemaChanged, _ignoreDdlErrors));

                    sw.Stop();
                    FormatTime(sw);
                    if (dataset == null)
                    {
                        return;
                    }
                    ParseDataSetResultsToResultsBox(dataset);
                    if (!schemaChanged)
                    {
                        return;
                    }
                    ExplorerControl?.RefreshTables(DatabaseInfo);
                }
            }
            catch (Exception sqlException)
            {
                ParseSqlErrorToResultsBox(
                    DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(sqlException));
            }
            finally
            {
                StopQuerying();
            }
        }
Exemple #6
0
        private async void ExecuteWithPlanButton_Click(object sender, RoutedEventArgs e)
        {
            DataConnectionHelper.LogUsage("EditorExecuteWithPlan");
            if (string.IsNullOrWhiteSpace(SqlText))
            {
                return;
            }
            try
            {
                StartQuerying();
                using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
                {
                    var       sql      = GetSqlFromSqlEditorTextBox();
                    string    showPlan = string.Empty;
                    Stopwatch sw       = new Stopwatch();
                    sw.Start();
                    var dataset = await Task.Run(()
                                                 // ReSharper disable once AccessToDisposedClosure
                                                 => repository.ExecuteSql(sql, out showPlan));

                    sw.Stop();
                    FormatTime(sw);
                    if (dataset != null)
                    {
                        ParseDataSetResultsToResultsBox(dataset);
                    }
                    try
                    {
                        TryLaunchSqlplan(showPlan, false);
                    }
                    catch (Exception ex)
                    {
                        DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35);
                    }
                }
            }
            catch (Exception ex)
            {
                ParseSqlErrorToResultsBox(
                    DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(ex));
            }
            finally
            {
                StopQuerying();
            }
        }
Exemple #7
0
        public void CheckCeVersion(object sender, ExecutedRoutedEventArgs e)
        {
            var helper = DataConnectionHelper.CreateEngineHelper(DatabaseType.SQLCE40);
            var ofd    = new OpenFileDialog();

            ofd.Filter          = DataConnectionHelper.GetSqlCeFileFilter();
            ofd.CheckFileExists = true;
            ofd.Multiselect     = false;
            ofd.ValidateNames   = true;
            if (ofd.ShowDialog() == true)
            {
                try
                {
                    var    sdfVersion = helper.DetermineVersion(ofd.FileName);
                    string found;
                    switch (sdfVersion)
                    {
                    case SQLCEVersion.SQLCE20:
                        found = "2.0";
                        break;

                    case SQLCEVersion.SQLCE30:
                        found = "3.0/3.1";
                        break;

                    case SQLCEVersion.SQLCE35:
                        found = "3.5";
                        break;

                    case SQLCEVersion.SQLCE40:
                        found = "4.0";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    EnvDteHelper.ShowMessage(string.Format("{0} is SQL Server Compact version {1}", Path.GetFileName(ofd.FileName), found));
                    DataConnectionHelper.LogUsage("DatabaseVersionDetect");
                }
                catch (Exception ex)
                {
                    EnvDteHelper.ShowError(ex.Message);
                }
            }
        }
        public void CompactDatabase(object sender, ExecutedRoutedEventArgs e)
        {
            var databaseInfo = ValidateMenuInfo(sender);

            if (databaseInfo == null)
            {
                return;
            }
            try
            {
                var helper = DataConnectionHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType);
                helper.CompactDatabase(databaseInfo.DatabaseInfo.ConnectionString);
                package.SetStatus("Compact Database completed");
                DataConnectionHelper.LogUsage("DatabaseMaintainCompact");
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false);
            }
        }
Exemple #9
0
 private void ExecuteSqlScriptInEditor()
 {
     try
     {
         using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
         {
             var  sql = GetSqlFromSqlEditorTextBox();
             bool schemaChanged;
             if (sql.Length == 0)
             {
                 return;
             }
             var sbSql = new StringBuilder(sql);
             sbSql = sbSql.Replace("\r", " \r");
             sbSql = sbSql.Replace("GO  \r", "GO\r");
             sql   = sbSql.Replace("GO \r", "GO\r").ToString();
             var sw = new Stopwatch();
             sw.Start();
             var dataset = repository.ExecuteSql(sql, out schemaChanged, _ignoreDdlErrors);
             sw.Stop();
             FormatTime(sw);
             if (dataset == null)
             {
                 return;
             }
             ParseDataSetResultsToResultsBox(dataset);
             if (!schemaChanged)
             {
                 return;
             }
             if (ExplorerControl != null)
             {
                 ExplorerControl.RefreshTables(DatabaseInfo);
             }
         }
     }
     catch (Exception sqlException)
     {
         ParseSqlErrorToResultsBox(DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(sqlException));
     }
 }
Exemple #10
0
 private void ExecuteWithPlanButton_Click(object sender, RoutedEventArgs e)
 {
     DataConnectionHelper.LogUsage("EditorExecuteWithPlan");
     if (string.IsNullOrWhiteSpace(SqlText))
     {
         return;
     }
     try
     {
         using (var repository = DataConnectionHelper.CreateRepository(DatabaseInfo))
         {
             var       sql = GetSqlFromSqlEditorTextBox();
             string    showPlan;
             Stopwatch sw = new Stopwatch();
             sw.Start();
             var dataset = repository.ExecuteSql(sql, out showPlan);
             sw.Stop();
             FormatTime(sw);
             if (dataset != null)
             {
                 ParseDataSetResultsToResultsBox(dataset);
             }
             try
             {
                 TryLaunchSqlplan(showPlan, false);
             }
             catch (Exception ex)
             {
                 DataConnectionHelper.SendError(ex, DatabaseType.SQLCE35);
             }
         }
     }
     catch (Exception ex)
     {
         ParseSqlErrorToResultsBox(DataConnectionHelper.CreateEngineHelper(DatabaseInfo.DatabaseType).FormatError(ex));
     }
 }
Exemple #11
0
        private void TestConnection(bool showMessage)
        {
            if (string.IsNullOrWhiteSpace(_builder.DataSource))
            {
                return;
            }
            try
            {
                if (_createDb)
                {
                    if (!System.IO.File.Exists(_builder.DataSource))
                    {
                        var engineHelper = DataConnectionHelper.CreateEngineHelper(DatabaseType.SQLite);
                        engineHelper.CreateDatabase(_builder.ConnectionString);
                    }
                }

                using (var conn = new SQLiteConnection(_builder.ConnectionString))
                {
                    conn.Open();
                    ConnectionString = _builder.ConnectionString;
                    if (showMessage)
                    {
                        EnvDteHelper.ShowMessage("Test succeeded!");
                    }
                    else
                    {
                        DialogResult = true;
                    }
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLite, false);
            }
        }
 private bool TestConnection(bool showMessage)
 {
     try
     {
         if (_createDb)
         {
             if (!System.IO.File.Exists(dataSourceTextBox.Text))
             {
                 var engineHelper = DataConnectionHelper.CreateEngineHelper(DbType);
                 engineHelper.CreateDatabase(_connectionString);
             }
         }
         using (DataConnectionHelper.CreateRepository(new DatabaseInfo {
             ConnectionString = _connectionString, DatabaseType = DbType
         }))
         {
             if (showMessage)
             {
                 EnvDTEHelper.ShowMessage("Connection OK!");
             }
             else
             {
                 DialogResult = true;
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         if (ex.Message.Contains("Please upgrade using SqlCeEngine.Upgrade() method") && DbType == DatabaseType.SQLCE40)
         {
             if (EnvDTEHelper.ShowMessageBox("This database file is from an earlier version,\n\rwould you like to Upgrade it?\n\r(A copy of the original file will be named .bak)"
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                             , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
             {
                 var bakFile = dataSourceTextBox.Text + ".bak";
                 var go      = true;
                 try
                 {
                     if (System.IO.File.Exists(bakFile))
                     {
                         if (EnvDTEHelper.ShowMessageBox(string.Format("{0} already exists, do you wish to overwrite it?", bakFile)
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGBUTTON.OLEMSGBUTTON_YESNO
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND
                                                         , Microsoft.VisualStudio.Shell.Interop.OLEMSGICON.OLEMSGICON_WARNING) == System.Windows.Forms.DialogResult.Yes)
                         {
                             System.IO.File.Delete(bakFile);
                         }
                         else
                         {
                             go = false;
                         }
                     }
                     if (go)
                     {
                         System.IO.File.Copy(dataSourceTextBox.Text, dataSourceTextBox.Text + ".bak");
                         var helper = new SqlCeScripting.SqlCeHelper4();
                         helper.UpgradeTo40(_connectionString);
                         DialogResult = true;
                     }
                 }
                 catch (Exception ex2)
                 {
                     DataConnectionHelper.SendError(ex2, DbType, false);
                     return(false);
                 }
             }
         }
         else
         {
             DataConnectionHelper.SendError(ex, DbType, false);
             return(false);
         }
     }
     return(true);
 }
Exemple #13
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (SqlCeToolboxPackage.VisualStudioVersion < new Version(11, 0))
            {
                DDEXButton.Visibility = Visibility.Collapsed;
            }
            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork             += bw_DoWork;
            bw.RunWorkerCompleted += (s, ea) =>
            {
                Version.Text = "Version " + Assembly.GetExecutingAssembly().GetName().Version + " " + ea.Result.ToString();
            };
            bw.RunWorkerAsync();

            Background   = VsThemes.GetWindowBackground();
            Version.Text = "Version " + Assembly.GetExecutingAssembly().GetName().Version;

            txtStatus.Text = "SQL Server Compact 4.0 in GAC - ";
            try
            {
                Assembly        asm4    = Assembly.Load("System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                FileVersionInfo fvi     = FileVersionInfo.GetVersionInfo(asm4.Location);
                string          version = fvi.FileVersion;
                txtStatus.Text += string.Format("Yes - {0}\n", version);
            }
            catch (FileNotFoundException)
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "SQL Server Compact 4.0 DbProvider - ";
            try
            {
                System.Data.Common.DbProviderFactories.GetFactory(SqlCeToolbox.Resources.SqlCompact40InvariantName);
                txtStatus.Text += "Yes\n";
            }
            catch (System.Configuration.ConfigurationException)
            {
                txtStatus.Text += "No\n";
            }
            catch (ArgumentException)
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "\nSQL Server Compact 4.0 DDEX provider - ";
            try
            {
                if (DataConnectionHelper.DdexProviderIsInstalled(new Guid(SqlCeToolbox.Resources.SqlCompact40Provider)))
                {
                    txtStatus.Text += "Yes\n";
                }
                else
                {
                    txtStatus.Text += "No\n";
                }
            }
            catch
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "SQL Server Compact 4.0 Simple DDEX provider - ";
            try
            {
                if (DataConnectionHelper.DdexProviderIsInstalled(new Guid(SqlCeToolbox.Resources.SqlCompact40PrivateProvider)))
                {
                    txtStatus.Text += "Yes\n";
                }
                else
                {
                    txtStatus.Text += "No\n";
                }
            }
            catch
            {
                txtStatus.Text += "No\n";
            }

            var tempFile40 = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            var tempFile35 = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

            try
            {
                var helper = DataConnectionHelper.CreateEngineHelper(DatabaseType.SQLCE40);
                var conn40 = string.Format("Data Source={0}", tempFile40);
                helper.CreateDatabase(conn40);
                txtStatus.Text += "SQL Server Compact 4.0 Engine test: PASS!\n";
            }
            catch
            {
                txtStatus.Text += "SQL Server Compact 4.0 Engine test: FAIL!\n";
            }

            txtStatus.Text += "\n\nSQL Server Compact 3.5 in GAC - ";
            var sqlce35Ver = new Version(0, 0, 0);

            try
            {
                var asm35 = Assembly.Load("System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                var fvi   = FileVersionInfo.GetVersionInfo(asm35.Location);
                sqlce35Ver      = new Version(fvi.FileVersion);
                txtStatus.Text += string.Format("Yes - {0}\n", sqlce35Ver);
            }
            catch (FileNotFoundException)
            {
                txtStatus.Text += "No\n";
            }
            if (sqlce35Ver > new Version(0, 0, 0) && sqlce35Ver < new Version(3, 5, 8080))
            {
                txtStatus.Text += "(Too old version installed, update to 3.5 SP2)\n";
            }

            txtStatus.Text += "SQL Server Compact 3.5 DbProvider - ";
            try
            {
                System.Data.Common.DbProviderFactories.GetFactory(SqlCeToolbox.Resources.SqlCompact35InvariantName);
                txtStatus.Text += "Yes\n";
            }
            catch (System.Configuration.ConfigurationException)
            {
                txtStatus.Text += "No\n";
            }
            catch (ArgumentException)
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "\nSQL Server Compact 3.5 DDEX provider - ";
            try
            {
                if (DataConnectionHelper.DdexProviderIsInstalled(new Guid(SqlCeToolbox.Resources.SqlCompact35Provider)))
                {
                    txtStatus.Text += "Yes\n";
                }
                else
                {
                    txtStatus.Text += "No\n";
                }
            }
            catch
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "SQL Server Compact 3.5 Simple DDEX provider - ";
            try
            {
                if (DataConnectionHelper.DdexProviderIsInstalled(new Guid(SqlCeToolbox.Resources.SqlCompact35PrivateProvider)))
                {
                    txtStatus.Text += "Yes\n";
                }
                else
                {
                    txtStatus.Text += "No\n";
                }
            }
            catch
            {
                txtStatus.Text += "No\n";
            }
            try
            {
                var helper = DataConnectionHelper.CreateEngineHelper(DatabaseType.SQLCE35);
                var conn35 = string.Format("Data Source={0}", tempFile35);
                helper.CreateDatabase(conn35);
                txtStatus.Text += "SQL Server Compact 3.5 Engine test: PASS!\n";
            }
            catch
            {
                txtStatus.Text += "SQL Server Compact 3.5Engine test: FAIL!\n";
            }

            txtStatus.Text += "\n\nSync Framework 2.1 SqlCe 3.5 provider - ";
            if (DataConnectionHelper.IsSyncFx21Installed())
            {
                txtStatus.Text += "Yes\n";
            }
            else
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "\n\nSQLite ADO.NET Provider included: ";
            try
            {
                Assembly asm = Assembly.Load("System.Data.SQLite");
                txtStatus.Text += string.Format("{0}\n", asm.GetName().Version);
            }
            catch (FileNotFoundException)
            {
                txtStatus.Text += "No\n";
            }

            txtStatus.Text += "SQLite EF6 DbProvider in GAC - ";
            try
            {
                if (DataConnectionHelper.IsSqLiteDbProviderInstalled())
                {
                    txtStatus.Text += "Yes\n";
                }
                else
                {
                    txtStatus.Text += "No\n";
                }
            }
            catch
            {
                txtStatus.Text += "No\n";
            }

            try
            {
                if (File.Exists(tempFile40))
                {
                    File.Delete(tempFile40);
                }
                if (File.Exists(tempFile35))
                {
                    File.Delete(tempFile35);
                }
            }
            catch
            {
                // ignored
            }
        }
        private void FillTableItems(KeyValuePair <string, DatabaseInfo> database, DatabaseTreeViewItem parentItem, Exception ex, RoutedEventArgs args)
        {
            if (ex != null)
            {
                var error = DataConnectionHelper.CreateEngineHelper(database.Value.DatabaseType).FormatError(ex);
                if (error.Contains("Minor Err.: 25028"))
                {
                    var pwd = new PasswordDialog();
                    pwd.ShowModal();
                    if (pwd.DialogResult.HasValue && pwd.DialogResult.Value && !string.IsNullOrWhiteSpace(pwd.Password))
                    {
                        database.Value.ConnectionString = database.Value.ConnectionString + ";Password="******"locale identifier")
                                {
                                    dbInfo.LCID = int.Parse(values.Value);
                                }
                                if (values.Key.ToLowerInvariant() == "encryption mode")
                                {
                                    dbInfo.EncryptionMode = values.Value;
                                }
                                if (string.IsNullOrWhiteSpace(dbInfo.EncryptionMode))
                                {
                                    dbInfo.EncryptionMode = "None";
                                }
                                if (values.Key.ToLowerInvariant() == "case sensitive")
                                {
                                    dbInfo.CaseSensitive = bool.Parse(values.Value);
                                }
                                if (values.Key == "DatabaseSize")
                                {
                                    dbInfo.Size = values.Value;
                                }
                                if (values.Key == "SpaceAvailable")
                                {
                                    dbInfo.SpaceAvailable = values.Value;
                                }
                                if (values.Key == "Created")
                                {
                                    dbInfo.Created = values.Value;
                                }
                                if (values.Key == "ServerVersion")
                                {
                                    dbInfo.ServerVersion = values.Value;
                                }
                            }
                            TrackSelection(dbInfo);
                        }
                    }
                    var tables      = repository.GetAllTableNames();
                    var columns     = repository.GetAllColumns();
                    var primaryKeys = repository.GetAllPrimaryKeys();
                    var foreignKeys = repository.GetAllForeignKeys();
                    var indexes     = repository.GetAllIndexes();
                    var triggers    = repository.GetAllTriggers();

                    foreach (var table in tables)
                    {
                        if (!Properties.Settings.Default.DisplayDescriptionTable && table.Equals("__ExtendedProperties"))
                        {
                            continue;
                        }
                        var item = TreeViewHelper.CreateTreeViewItemWithImage(table, "../Resources/table_16xLG.png", true);
                        item.ContextMenu = new TableContextMenu(new MenuCommandParameters {
                            DatabaseInfo = database.Value, Name = table, MenuItemType = MenuType.Table
                        }, _parentWindow);
                        item.ToolTip = table;
                        item.Tag     = new TableInfo {
                            Name = table, RowCount = repository.GetRowCount(table)
                        };
                        if (DescriptionCache != null)
                        {
                            var desc = DescriptionCache.Where(dc => dc.Parent == null && dc.Object == table).Select(dc => dc.Description).SingleOrDefault();
                            if (!string.IsNullOrWhiteSpace(desc))
                            {
                                item.ToolTip = desc;
                            }
                        }

                        var tableColumns     = (from col in columns where col.TableName == table select col).ToList();
                        var tablePrimaryKeys = primaryKeys.Where(pk => pk.TableName == table).ToList();
                        var tableForeignKeys = foreignKeys.Where(fk => fk.ConstraintTableName == table).ToList();
                        var tableIndexes     = indexes.Where(i => i.TableName == table).ToList();
                        var tableTriggers    = triggers.Where(t => t.TableName == table).ToList();
                        parentItem.Items.Add(item);
                        item.Expanded += (s, e) => GetTableColumns(s, e, tableColumns, tableForeignKeys, tablePrimaryKeys, tableIndexes, tableTriggers, database);
                    }
                }
            }
            catch (Exception ex2)
            {
                DataConnectionHelper.SendError(ex2, database.Value.DatabaseType, false);
            }
        }
        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 = DataConnectionHelper.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 = DataConnectionHelper.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 = DataConnectionHelper.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 = DataConnectionHelper.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 = DataConnectionHelper.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 = DataConnectionHelper.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);
            }
        }