public TablesContextMenu(DatabaseMenuCommandParameters menuCommandParameters, ExplorerToolWindow parent)
        {
            var dcmd = new DatabaseMenuCommandsHandler(parent);

            var createTableCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.BuildTable);
            var createTableMenuItem = new MenuItem
            {
                Header = "Build Table (beta)...",
                Icon = ImageHelper.GetImageFromResource("../resources/AddTable_5632.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = menuCommandParameters
            };
            createTableMenuItem.CommandBindings.Add(createTableCommandBinding);
            Items.Add(createTableMenuItem);
            
            Items.Add(new Separator());

            var refreshCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.RefreshTables);
            var refreshMenuItem = new MenuItem
            {
                Header = "Refresh",
                Icon = ImageHelper.GetImageFromResource("../resources/refresh.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = menuCommandParameters
            };
            refreshMenuItem.CommandBindings.Add(refreshCommandBinding);
            Items.Add(refreshMenuItem);
        }
 private static void AddRowVersionColumns(DatabaseMenuCommandParameters databaseInfo)
 {
     using (IRepository repository = RepoHelper.CreateRepository(databaseInfo.Connectionstring))
     {
         var list       = repository.GetAllTableNames();
         var allColumns = repository.GetAllColumns();
         foreach (var table in list)
         {
             if (!table.StartsWith("__"))
             {
                 var rowVersionCol = allColumns.Where(c => c.TableName == table && c.DataType == "rowversion").SingleOrDefault();
                 if (rowVersionCol == null)
                 {
                     repository.ExecuteSql(string.Format("ALTER TABLE {0} ADD COLUMN VersionColumn rowversion NOT NULL;{1}GO", table, Environment.NewLine));
                 }
             }
         }
     }
 }
Exemple #3
0
        private static int SyncFxGetObjectsForSync(SyncFxDialog sfd, DatabaseMenuCommandParameters databaseInfo)
        {
            int totalCount;

            using (var repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo))
            {
                sfd.Tables =
                    repository.GetAllTableNames().Where(
                        t => !t.EndsWith("scope_info") && !t.EndsWith("scope_config") && !t.EndsWith("schema_info") && !t.EndsWith("_tracking")).ToList();
                sfd.Columns =
                    repository.GetAllColumns().Where(
                        t =>
                        !t.TableName.EndsWith("scope_info") && !t.TableName.EndsWith("scope_config") && !t.TableName.EndsWith("schema_info") &&
                        !t.TableName.EndsWith("_tracking")).ToList();
                sfd.PrimaryKeyColumns =
                    repository.GetAllPrimaryKeys().Where(
                        t =>
                        !t.TableName.EndsWith("scope_info") && !t.TableName.EndsWith("scope_config") && !t.TableName.EndsWith("schema_info") &&
                        !t.TableName.EndsWith("_tracking")).ToList();
                totalCount = sfd.Tables.Count;
            }
            return(totalCount);
        }
Exemple #4
0
        public void SyncFxGenerateLocalDatabaseCacheCode(object sender, ExecutedRoutedEventArgs e)
        {
            // http://www.mztools.com/articles/2007/MZ2007011.aspx
            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }

            Scope scope = (Scope)menuItem.Tag;

            var dte = package.GetServiceHelper(typeof(EnvDTE.DTE)) as EnvDTE.DTE;

            var dteH = new Helpers.EnvDTEHelper();

            var project = dteH.GetProject(dte);

            if (project == null)
            {
                EnvDTEHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed");
                return;
            }
            if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDTEHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)");
                return;
            }
            if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                EnvDTEHelper.ShowError("Unsupported code language, only C# is currently supported");
                return;
            }
            if (project.Properties.Item("TargetFrameworkMoniker") == null)
            {
                EnvDTEHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker");
                return;
            }
            if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework"))
            {
                EnvDTEHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value.ToString());
                return;
            }

            try
            {
                string serverConnectionString = DataConnectionHelper.PromptForConnectionString(package);
                if (!string.IsNullOrEmpty(serverConnectionString))
                {
                    string clientConnectionString = string.Empty;

                    //grab target SQL CE Database
                    var dialog = new ConnectionDialog();
                    dialog.DbType = DatabaseType.SQLCE35;
                    bool?result = dialog.ShowModal();
                    if (result.HasValue && result.Value == true && !string.IsNullOrWhiteSpace(dialog.ConnectionString))
                    {
                        clientConnectionString = dialog.ConnectionString;
                    }
                    else
                    {
                        return;
                    }

                    string       model        = string.Empty;
                    SyncFxDialog sfd          = new SyncFxDialog();
                    int          totalCount   = 0;
                    var          databaseInfo = new DatabaseMenuCommandParameters
                    {
                        DatabaseInfo = new DatabaseInfo
                        {
                            ConnectionString = serverConnectionString,
                            DatabaseType     = DatabaseType.SQLServer
                        }
                    };
                    totalCount    = SyncFxGetObjectsForSync(sfd, databaseInfo);
                    sfd.ModelName = model;

                    bool?res = sfd.ShowModal();
                    if (res.HasValue && res.Value == true && (sfd.Tables.Count > 0) && !string.IsNullOrWhiteSpace(sfd.ModelName))
                    {
                        model = sfd.ModelName;
                        var defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();

                        var columns     = sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList();
                        var classes     = new SyncFxHelper().GenerateCodeForScope(serverConnectionString, clientConnectionString, "SQL", model, columns, defaultNamespace);
                        var projectPath = project.Properties.Item("FullPath").Value.ToString();

                        foreach (var item in classes)
                        {
                            string fileName = Path.Combine(projectPath, item.Key + ".cs");
                            if (File.Exists(fileName))
                            {
                                File.Delete(fileName);
                            }
                            File.WriteAllText(fileName, item.Value);
                            project.ProjectItems.AddFromFile(fileName);
                        }
                        //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx
                        EnvDTEHelper.AddReference(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.ShowMessage("Scope: " + model + " code generated.");
                        Helpers.DataConnectionHelper.LogUsage("DatabasesSyncAddLocalDBCache");
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
Exemple #5
0
        private void ExportServerDatabaseToEmbedded(DatabaseType databaseType, DatabaseMenuCommandParameters parameters)
        {
            string filter = DataConnectionHelper.GetSqlCeFileFilter();
            Scope  scope  = Scope.SchemaData;

            if (databaseType == DatabaseType.SQLite)
            {
                filter = DataConnectionHelper.GetSqliteFileFilter();
                scope  = Scope.SchemaDataSQLite;
            }
            Debug.Assert(databaseType == DatabaseType.SQLite || databaseType == DatabaseType.SQLCE40, "Unexpected database type");
            try
            {
                string connectionString = parameters.DatabaseInfo != null
                    ? parameters.DatabaseInfo.ConnectionString :
                                          DataConnectionHelper.PromptForConnectionString(package);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    PickTablesDialog ptd = new PickTablesDialog();
                    int totalCount       = 0;
                    using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(new DatabaseInfo
                    {
                        ConnectionString = connectionString, DatabaseType = DatabaseType.SQLServer
                    }))
                    {
                        ptd.Tables = repository.GetAllTableNamesForExclusion();
                        totalCount = ptd.Tables.Count;
                    }

                    bool?res = ptd.ShowModal();
                    if (res.HasValue && res.Value == true && (ptd.Tables.Count < totalCount))
                    {
                        string         dbName;
                        string         dbConnectionString = null;
                        SaveFileDialog fd = new SaveFileDialog();
                        fd.Title           = "Export as";
                        fd.Filter          = filter;
                        fd.OverwritePrompt = true;
                        fd.ValidateNames   = true;
                        bool?result = fd.ShowDialog();
                        if (result.HasValue && result.Value == true)
                        {
                            dbName = fd.FileName;
                            try
                            {
                                if (databaseType == DatabaseType.SQLCE40)
                                {
                                    package.SetStatus("Creating SQL Server Compact database...");
                                    SqlCeScripting.SqlCeHelper4 helper = new SqlCeScripting.SqlCeHelper4();
                                    dbConnectionString = string.Format("Data Source={0};Max Database Size=4091", dbName);
                                    if (System.IO.File.Exists(dbName))
                                    {
                                        File.Delete(dbName);
                                    }
                                    helper.CreateDatabase(dbConnectionString);
                                }
                                if (databaseType == DatabaseType.SQLite)
                                {
                                    package.SetStatus("Creating SQLite database...");
                                    var helper = new SqliteHelper();
                                    dbConnectionString = string.Format("Data Source={0};", dbName);
                                    if (System.IO.File.Exists(dbName))
                                    {
                                        File.Delete(dbName);
                                    }
                                    helper.CreateDatabase(dbConnectionString);
                                }

                                BackgroundWorker bw = new BackgroundWorker();
                                List <object>    workerParameters = new List <object>();
                                workerParameters.Add(dbConnectionString);
                                workerParameters.Add(connectionString);
                                workerParameters.Add(ptd.Tables);
                                workerParameters.Add(databaseType.ToString());
                                workerParameters.Add(scope.ToString());

                                bw.DoWork             += new DoWorkEventHandler(bw_DoWork);
                                bw.RunWorkerCompleted += (s, ea) =>
                                {
                                    try
                                    {
                                        if (ea.Error != null)
                                        {
                                            Helpers.DataConnectionHelper.SendError(ea.Error, databaseType, false);
                                        }
                                        Helpers.DataConnectionHelper.LogUsage("DatabasesExportFromServer");
                                    }
                                    finally
                                    {
                                        bw.Dispose();
                                    }
                                };
                                bw.RunWorkerAsync(workerParameters);
                            }
                            catch (Exception ex)
                            {
                                Helpers.DataConnectionHelper.SendError(ex, databaseType, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
        public DatabasesContextMenu(DatabaseMenuCommandParameters databaseMenuCommandParameters, ExplorerToolWindow parent)
        {
            var dcmd = new DatabasesMenuCommandsHandler(parent);

            // Add 4.0 database menu
            bool ver40IsInstalled = DataConnectionHelper.IsV40Installed();
            bool ver35IsInstalled = DataConnectionHelper.IsV35Installed();
            
            var addCe4DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.AddPrivateCe40Database);
            var addCeDatabaseMenuItem = new MenuItem
            {
                Header = "Add SQL Server Compact 4.0 Connection...",
                Icon = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            var pkg = parent.Package as SqlCeToolboxPackage;
            if (pkg.VSSupportsDDEX40())
            {
                var addCe40DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.AddCe40Database);
                addCeDatabaseMenuItem.CommandBindings.Add(addCe40DatabaseCommandBinding);
                addCeDatabaseMenuItem.IsEnabled = ver40IsInstalled;
                Items.Add(addCeDatabaseMenuItem);                
            }
            else
            {
                addCeDatabaseMenuItem.CommandBindings.Add(addCe4DatabaseCommandBinding);
                addCeDatabaseMenuItem.IsEnabled = ver40IsInstalled;
                Items.Add(addCeDatabaseMenuItem);
            }

            // Add 3.5 database menu
            var addCe35DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.AddCe35Database);
            var addCe35DatabaseMenuItem = new MenuItem
            {
                Header = "Add SQL Server Compact 3.5 Connection...",
                Icon = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            if (pkg.VSSupportsDDEX35())
            {
                addCe35DatabaseMenuItem.CommandBindings.Add(addCe35DatabaseCommandBinding);
                addCe35DatabaseMenuItem.IsEnabled = ver35IsInstalled;
                Items.Add(addCe35DatabaseMenuItem);
            }
            else
            {
                var addCe3511DatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.AddPrivateCe35Database);
                addCe35DatabaseMenuItem.CommandBindings.Add(addCe3511DatabaseCommandBinding);
                addCe35DatabaseMenuItem.IsEnabled = ver35IsInstalled;
                Items.Add(addCe35DatabaseMenuItem);
            }

            // Add SQLite database menu
            var addSQLiteDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.AddSQLiteDatabase);
            var addSQLiteDatabaseMenuItem = new MenuItem
            {
                Header = "Add SQLite Connection...",
                Icon = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            addSQLiteDatabaseMenuItem.CommandBindings.Add(addSQLiteDatabaseCommandBinding);
            Items.Add(addSQLiteDatabaseMenuItem);
            
            // Add from solution
            var addFromSolutionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.ScanConnections);

            var addFromSolutionMenuItem = new MenuItem
            {
                Header = "Add Connections from Solution",
                Icon = ImageHelper.GetImageFromResource("../resources/AddConnection_477.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                ToolTip = "Scan current Solution for SQL Compact and SQLite files",
                CommandParameter = databaseMenuCommandParameters,
            };
            addFromSolutionMenuItem.CommandBindings.Add(addFromSolutionCommandBinding);
            addFromSolutionMenuItem.IsEnabled = ver40IsInstalled || ver35IsInstalled;
            Items.Add(addFromSolutionMenuItem);

            // Fix connections
            var fixConnectionsCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.FixConnections);

            var fixConnectionsMenuItem = new MenuItem
            {
                Header = "Remove broken connections",
                Icon = ImageHelper.GetImageFromResource("../resources/action_Cancel_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                ToolTip = "Remove invalid connections",
                CommandParameter = databaseMenuCommandParameters,
            };
            fixConnectionsMenuItem.CommandBindings.Add(fixConnectionsCommandBinding);
            Items.Add(fixConnectionsMenuItem);

            Items.Add(new Separator());

            var scriptGraphCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateServerDgmlFiles);
            var scriptDatabaseGraphMenuItem = new MenuItem
            {
                Header = "Create SQL Server Database Graph (DGML)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Diagram_16XLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseGraphMenuItem.CommandBindings.Add(scriptGraphCommandBinding);
            Items.Add(scriptDatabaseGraphMenuItem);

            var designDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.DesignDatabase);
            var designDatabaseMenuItem = new MenuItem
            {
                Header = "Database designer (alpha)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            designDatabaseMenuItem.CommandBindings.Add(designDatabaseCommandBinding);
            Items.Add(designDatabaseMenuItem);
            Items.Add(new Separator());

            var scriptDatabaseRootMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
            };

            var toolTip = new ToolTip();
            toolTip.Content = "Generate a SQL Server Compact compatible database script from SQL Server 2005+";

            var scriptDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ScriptServerDatabase);

            var scriptDatabaseSchemaMenuItem = new MenuItem
                                             {
                                                 Header = "Script SQL Server Database Schema...",
                                                 Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                                                 ToolTip = toolTip,
                                                 Command = DatabaseMenuCommands.DatabaseCommand,
                                                 CommandParameter = databaseMenuCommandParameters,
                                                 Tag = SqlCeScripting.Scope.Schema
                                             };
            scriptDatabaseSchemaMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaMenuItem);

            var scriptDatabaseDataMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnly
            };
            scriptDatabaseDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDataMenuItem);

            var scriptDatabaseSchemaDataMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaData 
            };
            scriptDatabaseSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataMenuItem);

            var scriptDatabaseSchemaDataSQLiteMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data for SQLite...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataSQLite
            };
            scriptDatabaseSchemaDataSQLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataSQLiteMenuItem);

            var scriptDatabaseSchemaSQLiteMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema for SQLite...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaSQLite
            };
            scriptDatabaseSchemaSQLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaSQLiteMenuItem);

            var scriptDatabaseSchemaDataBLOBMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data with BLOBs...",
                ToolTip = toolTip,
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs 
            };
            scriptDatabaseSchemaDataBLOBMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataBLOBMenuItem);



            Items.Add(scriptDatabaseRootMenuItem);

            Items.Add(new Separator());

            var exportServerCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ExportServerDatabaseTo40);
            var exportServerMenuItem = new MenuItem
            {
                Header = "Export SQL Server to SQL Server Compact 4.0...",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            exportServerMenuItem.CommandBindings.Add(exportServerCommandBinding);
            exportServerMenuItem.IsEnabled = (ver40IsInstalled);
            Items.Add(exportServerMenuItem);

            var exportServerToLiteCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                               dcmd.ExportServerDatabaseToSqlite);
            var exportServerToLiteMenuItem = new MenuItem
            {
                Header = "Export SQL Server to SQLite... (beta)",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            exportServerToLiteMenuItem.CommandBindings.Add(exportServerToLiteCommandBinding);
            Items.Add(exportServerToLiteMenuItem);

            Items.Add(new Separator());

            var localDatabaseCacheCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.SyncFxGenerateLocalDatabaseCacheCode);
            var localDatabaseCacheMenuItem = new MenuItem
            {
                Header = "Generate Local Database Cache code...",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs
            };
            localDatabaseCacheMenuItem.CommandBindings.Add(localDatabaseCacheCommandBinding);
            localDatabaseCacheMenuItem.IsEnabled = (ver35IsInstalled && DataConnectionHelper.IsSyncFx21Installed());
            Items.Add(localDatabaseCacheMenuItem);

            Items.Add(new Separator());
            var detectDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.CheckCeVersion);

            var versionDetectMenuItem = new MenuItem
            {
                Header = "Detect SQL Server Compact file version...",
                Icon = ImageHelper.GetImageFromResource("../resources/Find_5650.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            versionDetectMenuItem.CommandBindings.Add(detectDatabaseCommandBinding);
            Items.Add(versionDetectMenuItem);

        }
        public DatabaseContextMenu(DatabaseMenuCommandParameters databaseMenuCommandParameters, ExplorerToolWindow parent)
        {
            var isSqlCe = databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35
                || databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40;

            var dcmd = new DatabaseMenuCommandsHandler(parent);

            var showSqlEditorCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.SpawnSqlEditorWindow);
            var showSqlEditorMenuItem = new MenuItem
            {
                Header = "New Query",
                Icon = ImageHelper.GetImageFromResource("../resources/NewQuery.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            showSqlEditorMenuItem.CommandBindings.Add(showSqlEditorCommandBinding);
            Items.Add(showSqlEditorMenuItem);

            var createTableCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.BuildTable);
            var createTableMenuItem = new MenuItem
            {
                Header = "Build Table (beta)...",
                Icon = ImageHelper.GetImageFromResource("../resources/AddTable_5632.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            createTableMenuItem.CommandBindings.Add(createTableCommandBinding);
            Items.Add(createTableMenuItem);
            Items.Add(new Separator());

            var scriptDatabaseRootMenuItem = new MenuItem
            {
                Header = "Script Database",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
            };

            // Database scripting items
            var scriptDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.ScriptDatabase);

            var scriptDatabaseSchemaMenuItem = new MenuItem
            {
                Header = "Script Database Schema...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.Schema
            };
            scriptDatabaseSchemaMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaMenuItem);


            var scriptDatabaseSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaData
            };
            scriptDatabaseSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataMenuItem);

            var scriptAzureSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data for SQL Azure...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataAzure
            };
            scriptAzureSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            if (isSqlCe)
                scriptDatabaseRootMenuItem.Items.Add(scriptAzureSchemaDataMenuItem);

            var scriptSqliteSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data for SQLite...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataSQLite
            };
            scriptSqliteSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            if (isSqlCe)
                scriptDatabaseRootMenuItem.Items.Add(scriptSqliteSchemaDataMenuItem);

            var scriptDatabaseSchemaDataBLOBMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data with BLOBs...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs
            };
            scriptDatabaseSchemaDataBLOBMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            if (isSqlCe)
                scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataBLOBMenuItem);

            var scriptDatabaseDataMenuItem = new MenuItem
            {
                Header = "Script Database Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnly
            };
            scriptDatabaseDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDataMenuItem);

            var scriptDatabaseDataForServerMenuItem = new MenuItem
            {
                Header = "Script Database Data for SQL Server...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnlyForSqlServer
            };
            scriptDatabaseDataForServerMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            if (isSqlCe)
                scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDataForServerMenuItem);

            var scriptDiffCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateDiffScript);

            var scriptDatabaseDiffMenuItem = new MenuItem
            {
                Header = "Script Database Diff...",
                Icon = ImageHelper.GetImageFromResource("../resources/DataCompare_9880.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseDiffMenuItem.CommandBindings.Add(scriptDiffCommandBinding);
            scriptDatabaseDiffMenuItem.ToolTip = "Script all tables, columns and constraints in this database\r\nthat are missing/different in the target database.";
            if (isSqlCe)
                scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDiffMenuItem);

            //End Database scripting options
            Items.Add(scriptDatabaseRootMenuItem);
            Items.Add(new Separator());

            var maintenanceMenuItem = new MenuItem
            {
                Header = "Maintenance",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
            };

            var setPwdCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.SetPassword);
            var pwdMenuItem = new MenuItem
            {
                Header = "Set Password",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Set the database password"
            };
            pwdMenuItem.CommandBindings.Add(setPwdCommandBinding);
            maintenanceMenuItem.Items.Add(pwdMenuItem);

            var shrinkCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.ShrinkDatabase);
            var shrinkMenuItem = new MenuItem
            {
                Header = "Shrink",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Shrink database by deleting free pages"
            };
            shrinkMenuItem.CommandBindings.Add(shrinkCommandBinding);
            maintenanceMenuItem.Items.Add(shrinkMenuItem);

            var compactCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.CompactDatabase);
            var compactMenuItem = new MenuItem
            {
                Header = "Compact",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Perform full database compaction"
            };
            compactMenuItem.CommandBindings.Add(compactCommandBinding);
            maintenanceMenuItem.Items.Add(compactMenuItem);

            var verifyCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.VerifyDatabase);
            var verifyMenuItem = new MenuItem
            {
                Header = "Verify",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Verify the integrity of the database (enhanced)"
            };
            verifyMenuItem.CommandBindings.Add(verifyCommandBinding);
            maintenanceMenuItem.Items.Add(verifyMenuItem);

            var repairDeleteCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseDeleteCorruptedRows);
            var repairDeleteMenuItem = new MenuItem
            {
                Header = "Repair (delete corrupted rows)",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairDeleteMenuItem.CommandBindings.Add(repairDeleteCommandBinding);
            maintenanceMenuItem.Items.Add(repairDeleteMenuItem);

            var repairRecoverAllCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseRecoverAllOrFail);
            var repairRecoverAllMenuItem = new MenuItem
            {
                Header = "Repair (recover all or fail)",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairRecoverAllMenuItem.CommandBindings.Add(repairRecoverAllCommandBinding);
            maintenanceMenuItem.Items.Add(repairRecoverAllMenuItem);

            var repairRecoverPossibleCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseRecoverAllPossibleRows);
            var repairRecoverPossibleMenuItem = new MenuItem
            {
                Header = "Repair (recover all possible)",
                Icon = ImageHelper.GetImageFromResource("../resources/Hammer_Builder_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairRecoverPossibleMenuItem.CommandBindings.Add(repairRecoverPossibleCommandBinding);
            maintenanceMenuItem.Items.Add(repairRecoverPossibleMenuItem);

            if (isSqlCe)
            {
                Items.Add(maintenanceMenuItem);
                Items.Add(new Separator());
            }

            var scriptExportCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.ExportToServer);

            var scriptDatabaseExportMenuItem = new MenuItem
            {
                Header = "Migrate to SQL Server (incl. LocalDB/Express)...",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseExportMenuItem.CommandBindings.Add(scriptExportCommandBinding);
            scriptDatabaseExportMenuItem.ToolTip = "Migrate entire database to a SQL Server database";
            Items.Add(scriptDatabaseExportMenuItem);

            var scriptUpgradeCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.UpgradeTo40);

            var scriptUpgradeMenuItem = new MenuItem
            {
                Header = "Upgrade to version 4.0...",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptUpgradeMenuItem.CommandBindings.Add(scriptUpgradeCommandBinding);
            scriptUpgradeMenuItem.ToolTip = "Create a copy of this database in 4.0 format";

            if (databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 
                && Helpers.DataConnectionHelper.IsV40Installed())
            {
                Items.Add(scriptUpgradeMenuItem);
            }

            Items.Add(new Separator());

            var scriptGraphCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.GenerateCeDgmlFiles);

            var scriptDatabaseGraphMenuItem = new MenuItem
            {
                Header = "Create Database Graph (DGML)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Diagram_16XLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseGraphMenuItem.CommandBindings.Add(scriptGraphCommandBinding);
            Items.Add(scriptDatabaseGraphMenuItem);

            // Documentation menu item

            var docDbCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.GenerateDocFiles);
            var docDatabaseMenuItem = new MenuItem
            {
                Header = "Create Database Documentation...",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            docDatabaseMenuItem.CommandBindings.Add(docDbCommandBinding);
            Items.Add(docDatabaseMenuItem);

            Items.Add(new Separator());
            var generateCodeRootMenuItem = new MenuItem
            {
                Header = "Generate Code (EF/LINQ to SQL/SyncFX)",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
            };

            var scriptEdmxCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.GenerateEdmxInProject);

            var scriptEdmxMenuItem = new MenuItem
            {
                Header = "Add Entity Data Model (EDMX) to current Project...",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptEdmxMenuItem.CommandBindings.Add(scriptEdmxCommandBinding);
            generateCodeRootMenuItem.Items.Add(scriptEdmxMenuItem);

            var scriptDCCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateDataContextInProject);

            var scriptDCMenuItem = new MenuItem
            {
                Header = "Add LINQ to SQL DataContext to current Project (needs 3.5)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = true
            };
            scriptDCMenuItem.CommandBindings.Add(scriptDCCommandBinding);
            scriptDCMenuItem.IsEnabled = DataConnectionHelper.IsV35Installed() && DataConnectionHelper.IsV35DbProviderInstalled();
            generateCodeRootMenuItem.Items.Add(scriptDCMenuItem);

            var scriptWPDCMenuItem = new MenuItem
            {
                Header = "Add Windows Phone DataContext to current Project (needs 3.5)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = false
            };
            scriptWPDCMenuItem.CommandBindings.Add(scriptDCCommandBinding);
            scriptWPDCMenuItem.IsEnabled = DataConnectionHelper.IsV35Installed() && DataConnectionHelper.IsV35DbProviderInstalled();
            if (databaseMenuCommandParameters.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35)
            {
                scriptWPDCMenuItem.IsEnabled = false;
            }            
            generateCodeRootMenuItem.Items.Add(scriptWPDCMenuItem);
            generateCodeRootMenuItem.Items.Add(new Separator());

            var syncFXRootMenuItem = new MenuItem
            {
                Header = "Sync Framework Tools",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
            };

            var syncFxProvisionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.SyncFxProvisionScope);

            var syncFxProvisionMenuItem = new MenuItem
            {
                Header = "Provision Sync Framework Scope...",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            syncFxProvisionMenuItem.CommandBindings.Add(syncFxProvisionCommandBinding);
            syncFxProvisionMenuItem.IsEnabled = databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 
                && Helpers.DataConnectionHelper.IsSyncFx21Installed();
            
            syncFXRootMenuItem.Items.Add(syncFxProvisionMenuItem);

            var syncFxDeprovisionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.SyncFxDeprovisionDatabase);

            var syncFxDeprovisionMenuItem = new MenuItem
            {
                Header = "Deprovision Sync Framework Objects from Database",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            syncFxDeprovisionMenuItem.CommandBindings.Add(syncFxDeprovisionCommandBinding);

            syncFxDeprovisionMenuItem.IsEnabled = databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 
                && Helpers.DataConnectionHelper.IsSyncFx21Installed();

            syncFXRootMenuItem.Items.Add(syncFxDeprovisionMenuItem);

            var syncFxGenerateSnapshotCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.SyncFxGenerateSnapshot);

            var syncFxGenerateSnapshotMenuItem = new MenuItem
            {
                Header = "Generate snapshot database to initialize other clients...",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            syncFxGenerateSnapshotMenuItem.CommandBindings.Add(syncFxGenerateSnapshotCommandBinding);

            syncFxGenerateSnapshotMenuItem.IsEnabled = databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35
                && Helpers.DataConnectionHelper.IsSyncFx21Installed();

            syncFXRootMenuItem.Items.Add(syncFxGenerateSnapshotMenuItem);

            var syncFxCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.SyncFxGenerateSyncCodeInProject);

            var syncFxMenuItem = new MenuItem
            {
                Header = "Add Sync Framework Class to current Project...",
                Icon = ImageHelper.GetImageFromResource("../resources/Synchronize_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            syncFxMenuItem.CommandBindings.Add(syncFxCommandBinding);

            syncFxMenuItem.IsEnabled = databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLCE35 
                && Helpers.DataConnectionHelper.IsSyncFx21Installed();

            generateCodeRootMenuItem.Items.Add(syncFxMenuItem);
            generateCodeRootMenuItem.Items.Add(syncFXRootMenuItem);

            if (isSqlCe)
            {
                Items.Add(generateCodeRootMenuItem);
            }
            else if (databaseMenuCommandParameters.DatabaseInfo.DatabaseType == DatabaseType.SQLite)
            {
                var scriptModelCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateModelCodeInProject);

                var scriptModelMenuItem = new MenuItem
                {
                    Header = "Add sqlite-net DataAccess.cs to current Project...",
                    Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                    Command = DatabaseMenuCommands.DatabaseCommand,
                    CommandParameter = databaseMenuCommandParameters,
                };
                scriptModelMenuItem.CommandBindings.Add(scriptModelCommandBinding);
                Items.Add(scriptModelMenuItem);

                //var scriptSqliteEdmxCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                //            dcmd.GenerateEdmxInProject);

                //var scriptSqliteEdmxMenuItem = new MenuItem
                //{
                //    Header = "Add Entity Data Model (EDMX) to current Project...",
                //    Icon = ImageHelper.GetImageFromResource("../resources/Schema_16xLG.png"),
                //    Command = DatabaseMenuCommands.DatabaseCommand,
                //    CommandParameter = databaseMenuCommandParameters,
                //};
                //scriptSqliteEdmxMenuItem.CommandBindings.Add(scriptSqliteEdmxCommandBinding);
                //Items.Add(scriptSqliteEdmxMenuItem);
            }
            Items.Add(new Separator());

            var addDescriptionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.AddDescription);
            var addDescriptionMenuItem = new MenuItem
            {
                Header = "Edit description...",
                Icon = ImageHelper.GetImageFromResource("../resources/properties_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            addDescriptionMenuItem.CommandBindings.Add(addDescriptionCommandBinding);
            if (isSqlCe)
            {
                Items.Add(addDescriptionMenuItem);
            }

            var generateInfoCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.GenerateDatabaseInfo);
            var generateInfoMenuItem = new MenuItem
            {
                Header = "Database Information",
                Icon = ImageHelper.GetImageFromResource("../resources/properties_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            generateInfoMenuItem.CommandBindings.Add(generateInfoCommandBinding);
            Items.Add(generateInfoMenuItem);
            
            Items.Add(new Separator());

            var copyCeConnectionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.CopyCeDatabase);
            var copyCeConnectionMenuItem = new MenuItem
            {
                InputGestureText = "Ctrl+C",
                Header = "Copy Database File",
                Icon = ImageHelper.GetImageFromResource("../resources/Copy_6524.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            copyCeConnectionMenuItem.CommandBindings.Add(copyCeConnectionCommandBinding);
            Items.Add(copyCeConnectionMenuItem);

            var renameConnectionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                   dcmd.RenameConnection);
            var renameConnectionMenuItem = new MenuItem
            {
                Header = "Rename Connection... (beta)",
                Icon = ImageHelper.GetImageFromResource("../resources/Rename_6779.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            renameConnectionMenuItem.CommandBindings.Add(renameConnectionCommandBinding);
            if (!databaseMenuCommandParameters.DatabaseInfo.FromServerExplorer)
            {
                Items.Add(renameConnectionMenuItem);
            }

            var removeCeConnectionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.RemoveCeDatabase);
            var removeCeConnectionMenuItem = new MenuItem
            {
                Header = "Remove Connection",
                Icon = ImageHelper.GetImageFromResource("../resources/action_Cancel_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            removeCeConnectionMenuItem.CommandBindings.Add(removeCeConnectionCommandBinding);
            Items.Add(removeCeConnectionMenuItem);
        }
        private void ExportServerDatabaseToEmbedded(DatabaseType databaseType, DatabaseMenuCommandParameters parameters)
        {
            var filter = DataConnectionHelper.GetSqlCeFileFilter();
            var scope  = Scope.SchemaData;

            if (databaseType == DatabaseType.SQLite)
            {
                filter = DataConnectionHelper.GetSqliteFileFilter();
                scope  = Scope.SchemaDataSQLite;
            }
            Debug.Assert(databaseType == DatabaseType.SQLite || databaseType == DatabaseType.SQLCE40, "Unexpected database type");
            try
            {
                var connectionString = parameters.DatabaseInfo != null
                    ? parameters.DatabaseInfo.ConnectionString :
                                       DataConnectionHelper.PromptForConnectionString(_package);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    var ptd = new PickTablesDialog();
                    int totalCount;
                    using (var repository = DataConnectionHelper.CreateRepository(new DatabaseInfo
                    {
                        ConnectionString = connectionString, DatabaseType = DatabaseType.SQLServer
                    }))
                    {
                        ptd.Tables = repository.GetAllTableNamesForExclusion();
                        totalCount = ptd.Tables.Count;
                    }

                    var res = ptd.ShowModal();
                    if (!res.HasValue || res.Value != true || (ptd.Tables.Count >= totalCount))
                    {
                        return;
                    }
                    string dbConnectionString = null;
                    var    fd = new SaveFileDialog
                    {
                        Title           = "Export as",
                        Filter          = filter,
                        OverwritePrompt = true,
                        ValidateNames   = true
                    };
                    var result = fd.ShowDialog();
                    if (!result.HasValue || result.Value != true)
                    {
                        return;
                    }
                    var dbName = fd.FileName;
                    try
                    {
                        if (databaseType == DatabaseType.SQLCE40)
                        {
                            _package.SetStatus("Creating SQL Server Compact database...");
                            var helper = new SqlCeHelper4();
                            dbConnectionString = string.Format("Data Source={0};Max Database Size=4091", dbName);
                            if (File.Exists(dbName))
                            {
                                File.Delete(dbName);
                            }
                            helper.CreateDatabase(dbConnectionString);
                        }
                        if (databaseType == DatabaseType.SQLite)
                        {
                            _package.SetStatus("Creating SQLite database...");
                            var helper = new SqliteHelper();
                            dbConnectionString = string.Format("Data Source={0};", dbName);
                            if (File.Exists(dbName))
                            {
                                File.Delete(dbName);
                            }
                            helper.CreateDatabase(dbConnectionString);
                        }

                        var bw = new BackgroundWorker();
                        var workerParameters = new List <object>
                        {
                            dbConnectionString,
                            connectionString,
                            ptd.Tables,
                            databaseType.ToString(),
                            scope.ToString()
                        };

                        bw.DoWork             += bw_DoWork;
                        bw.RunWorkerCompleted += (s, ea) =>
                        {
                            try
                            {
                                if (ea.Error != null)
                                {
                                    DataConnectionHelper.SendError(ea.Error, databaseType, false);
                                }
                                DataConnectionHelper.LogUsage("DatabasesExportFromServer");
                            }
                            finally
                            {
                                bw.Dispose();
                            }
                        };
                        bw.RunWorkerAsync(workerParameters);
                    }
                    catch (Exception ex)
                    {
                        DataConnectionHelper.SendError(ex, databaseType, false);
                    }
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
        public async void SyncFxGenerateLocalDatabaseCacheCode(object sender, ExecutedRoutedEventArgs e)
        {
            // http://www.mztools.com/articles/2007/MZ2007011.aspx
            var menuItem = sender as MenuItem;

            if (menuItem == null)
            {
                return;
            }
            var dteH    = new EnvDteHelper();
            var project = dteH.GetProject();

            if (project == null)
            {
                EnvDteHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed");
                return;
            }
            if (!dteH.ContainsAllowed(project))
            {
                EnvDteHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)");
                return;
            }

            var tfm = ThreadHelper.JoinableTaskFactory.Run(() => project.GetAttributeAsync("TargetFrameworkMoniker"));

            if (string.IsNullOrEmpty(tfm))
            {
                EnvDteHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker");
                return;
            }
            if (!tfm.Contains(".NETFramework"))
            {
                EnvDteHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + tfm);
                return;
            }

            try
            {
                var serverConnectionString = DataConnectionHelper.PromptForConnectionString(_package);
                if (string.IsNullOrEmpty(serverConnectionString))
                {
                    return;
                }
                string clientConnectionString;

                //grab target SQL CE Database
                var dialog = new ConnectionDialog();
                dialog.DbType = DatabaseType.SQLCE35;
                var result = dialog.ShowModal();
                if (result.HasValue && result.Value && !string.IsNullOrWhiteSpace(dialog.ConnectionString))
                {
                    clientConnectionString = dialog.ConnectionString;
                }
                else
                {
                    return;
                }

                var model        = string.Empty;
                var sfd          = new SyncFxDialog();
                var databaseInfo = new DatabaseMenuCommandParameters
                {
                    DatabaseInfo = new DatabaseInfo
                    {
                        ConnectionString = serverConnectionString,
                        DatabaseType     = DatabaseType.SQLServer
                    }
                };
                SyncFxGetObjectsForSync(sfd, databaseInfo);
                sfd.ModelName = model;

                var res = sfd.ShowModal();
                if (res.HasValue && res.Value && (sfd.Tables.Count > 0) && !string.IsNullOrWhiteSpace(sfd.ModelName))
                {
                    model = sfd.ModelName;
                    var defaultNamespace = ThreadHelper.JoinableTaskFactory.Run(() => project.GetAttributeAsync("DefaultNamespace"));

                    var columns     = sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList();
                    var classes     = new SyncFxHelper().GenerateCodeForScope(serverConnectionString, clientConnectionString, "SQL", model, columns, defaultNamespace);
                    var projectPath = Path.GetDirectoryName(project.FullPath);

                    foreach (var item in classes)
                    {
                        var fileName = Path.Combine(projectPath, item.Key + ".cs");
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                        File.WriteAllText(fileName, item.Value);
                        ThreadHelper.JoinableTaskFactory.Run(() => project.AddExistingFilesAsync(fileName));
                    }
                    //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx
                    await EnvDteHelper.AddReferenceAsync(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    await EnvDteHelper.AddReferenceAsync(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                    EnvDteHelper.ShowMessage("Scope: " + model + " code generated.");
                    DataConnectionHelper.LogUsage("DatabasesSyncAddLocalDBCache");
                }
            }
            catch (Exception ex)
            {
                DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
        private void ExportServerDatabaseToEmbedded(DatabaseType databaseType, DatabaseMenuCommandParameters parameters)
        {
            string filter = DataConnectionHelper.GetSqlCeFileFilter();
            Scope scope = Scope.SchemaData;
            if (databaseType == DatabaseType.SQLite)
            {
                filter = DataConnectionHelper.GetSqliteFileFilter();
                scope = Scope.SchemaDataSQLite;
            }
            Debug.Assert(databaseType == DatabaseType.SQLite || databaseType == DatabaseType.SQLCE40, "Unexpected database type");
            try
            {
                string connectionString = parameters.DatabaseInfo != null
                    ? parameters.DatabaseInfo.ConnectionString :
                    DataConnectionHelper.PromptForConnectionString(package);
                if (!string.IsNullOrEmpty(connectionString))
                {
                    PickTablesDialog ptd = new PickTablesDialog();
                    int totalCount = 0;
                    using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(new DatabaseInfo
                        { ConnectionString = connectionString, DatabaseType = DatabaseType.SQLServer }))
                    {
                        ptd.Tables = repository.GetAllTableNamesForExclusion();
                        totalCount = ptd.Tables.Count;
                    }

                    bool? res = ptd.ShowModal();
                    if (res.HasValue && res.Value == true && (ptd.Tables.Count < totalCount))
                    {
                        string dbName;
                        string dbConnectionString = null;
                        SaveFileDialog fd = new SaveFileDialog();
                        fd.Title = "Export as";
                        fd.Filter = filter;
                        fd.OverwritePrompt = true;
                        fd.ValidateNames = true;
                        bool? result = fd.ShowDialog();
                        if (result.HasValue && result.Value == true)
                        {
                            dbName = fd.FileName;
                            try
                            {
                                if (databaseType == DatabaseType.SQLCE40)
                                {
                                    package.SetStatus("Creating SQL Server Compact database...");
                                    SqlCeScripting.SqlCeHelper4 helper = new SqlCeScripting.SqlCeHelper4();
                                    dbConnectionString = string.Format("Data Source={0};Max Database Size=4091", dbName);
                                    if (System.IO.File.Exists(dbName))
                                        File.Delete(dbName);
                                    helper.CreateDatabase(dbConnectionString);
                                }
                                if (databaseType == DatabaseType.SQLite)
                                {
                                    package.SetStatus("Creating SQLite database...");
                                    var helper = new SqliteHelper();
                                    dbConnectionString = string.Format("Data Source={0};", dbName);
                                    if (System.IO.File.Exists(dbName))
                                        File.Delete(dbName);
                                    helper.CreateDatabase(dbConnectionString);
                                }

                                BackgroundWorker bw = new BackgroundWorker();
                                List<object> workerParameters = new List<object>();
                                workerParameters.Add(dbConnectionString);
                                workerParameters.Add(connectionString);
                                workerParameters.Add(ptd.Tables);
                                workerParameters.Add(databaseType.ToString());
                                workerParameters.Add(scope.ToString());

                                bw.DoWork += new DoWorkEventHandler(bw_DoWork);
                                bw.RunWorkerCompleted += (s, ea) =>
                                {
                                    try
                                    {
                                        if (ea.Error != null)
                                        {
                                            Helpers.DataConnectionHelper.SendError(ea.Error, databaseType, false);
                                        }
                                        Helpers.DataConnectionHelper.LogUsage("DatabasesExportFromServer");
                                    }
                                    finally
                                    {
                                        bw.Dispose();
                                    }
                                };
                                bw.RunWorkerAsync(workerParameters);

                            }
                            catch (Exception ex)
                            {
                                Helpers.DataConnectionHelper.SendError(ex, databaseType, false);
                            }
                        }
                   }
                }
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
 private static int SyncFxGetObjectsForSync(SyncFxDialog sfd, DatabaseMenuCommandParameters databaseInfo)
 {
     int totalCount;
     using (var repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo))
     {
         sfd.Tables =
             repository.GetAllTableNames().Where(
                 t => !t.EndsWith("scope_info") && !t.EndsWith("scope_config") && !t.EndsWith("schema_info") && !t.EndsWith("_tracking")).ToList();
         sfd.Columns =
             repository.GetAllColumns().Where(
                 t =>
                 !t.TableName.EndsWith("scope_info") && !t.TableName.EndsWith("scope_config") && !t.TableName.EndsWith("schema_info") &&
                 !t.TableName.EndsWith("_tracking")).ToList();
         sfd.PrimaryKeyColumns =
             repository.GetAllPrimaryKeys().Where(
                 t =>
                 !t.TableName.EndsWith("scope_info") && !t.TableName.EndsWith("scope_config") && !t.TableName.EndsWith("schema_info") &&
                 !t.TableName.EndsWith("_tracking")).ToList();
         totalCount = sfd.Tables.Count;
     }
     return totalCount;
 }
        public void SyncFxGenerateLocalDatabaseCacheCode(object sender, ExecutedRoutedEventArgs e)
        {
            // http://www.mztools.com/articles/2007/MZ2007011.aspx
            var menuItem = sender as MenuItem;
            if (menuItem == null) return;

            Scope scope = (Scope)menuItem.Tag;

            var dte = package.GetServiceHelper(typeof(EnvDTE.DTE)) as EnvDTE.DTE;

            var dteH = new Helpers.EnvDTEHelper();

            var project = dteH.GetProject(dte);
            if (project == null)
            {
                EnvDTEHelper.ShowError("Please select a project in Solution Explorer, where you want the SyncFx classes to be placed");
                return;
            }
            if (!dteH.AllowedProjectKinds.Contains(new Guid(project.Kind)))
            {
                EnvDTEHelper.ShowError("The selected project type does not support Sync Framework (please let me know if I am wrong)");
                return;
            }
            if (project.CodeModel.Language != CodeModelLanguageConstants.vsCMLanguageCSharp)
            {
                EnvDTEHelper.ShowError("Unsupported code language, only C# is currently supported");
                return;
            }
            if (project.Properties.Item("TargetFrameworkMoniker") == null)
            {
                EnvDTEHelper.ShowError("The selected project type does not support Sync Framework - missing TargetFrameworkMoniker");
                return;
            }
            if (!project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework"))
            {
                EnvDTEHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value.ToString());
                return;
            }

            try
            {
                string serverConnectionString = DataConnectionHelper.PromptForConnectionString(package);
                if (!string.IsNullOrEmpty(serverConnectionString))
                {
                    string clientConnectionString = string.Empty;

                    //grab target SQL CE Database
                    var dialog = new ConnectionDialog();
                    dialog.DbType = DatabaseType.SQLCE35;
                    bool? result = dialog.ShowModal();
                    if (result.HasValue && result.Value == true && !string.IsNullOrWhiteSpace(dialog.ConnectionString))
                    {
                        clientConnectionString = dialog.ConnectionString;
                    }
                    else
                    {
                        return;
                    }

                    string model = string.Empty;
                    SyncFxDialog sfd = new SyncFxDialog();
                    int totalCount = 0;
                    var databaseInfo = new DatabaseMenuCommandParameters
                    {
                        DatabaseInfo = new DatabaseInfo
                        {
                            ConnectionString = serverConnectionString,
                            DatabaseType = DatabaseType.SQLServer
                        }
                    };
                    totalCount = SyncFxGetObjectsForSync(sfd, databaseInfo);
                    sfd.ModelName = model;

                    bool? res = sfd.ShowModal();
                    if (res.HasValue && res.Value == true && (sfd.Tables.Count > 0) && !string.IsNullOrWhiteSpace(sfd.ModelName))
                    {
                        model = sfd.ModelName;
                        var defaultNamespace = project.Properties.Item("DefaultNamespace").Value.ToString();

                        var columns = sfd.Columns.Where(c => sfd.Tables.Contains(c.TableName)).ToList();
                        var classes = new SyncFxHelper().GenerateCodeForScope(serverConnectionString, clientConnectionString, "SQL", model, columns, defaultNamespace);
                        var projectPath = project.Properties.Item("FullPath").Value.ToString();

                        foreach (var item in classes)
                        {
                            string fileName = Path.Combine(projectPath, item.Key + ".cs");
                            if (File.Exists(fileName))
                            {
                                File.Delete(fileName);
                            }
                            File.WriteAllText(fileName, item.Value);
                            project.ProjectItems.AddFromFile(fileName);
                        }
                        //Adding references - http://blogs.msdn.com/b/murat/archive/2008/07/30/envdte-adding-a-refernce-to-a-project.aspx
                        EnvDTEHelper.AddReference(project, "System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");

                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization, Version=2.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServer, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.AddReference(project, "Microsoft.Synchronization.Data.SqlServerCe, Version=3.1.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");
                        EnvDTEHelper.ShowMessage("Scope: " + model + " code generated.");
                        Helpers.DataConnectionHelper.LogUsage("DatabasesSyncAddLocalDBCache");
                    }
                }
            }
            catch (Exception ex)
            {
                Helpers.DataConnectionHelper.SendError(ex, DatabaseType.SQLServer);
            }
        }
 private static void AddRowVersionColumns(DatabaseMenuCommandParameters databaseInfo)
 {
     using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo))
     {
         var list = repository.GetAllTableNames();
         var allColumns = repository.GetAllColumns();
         foreach (var table in list)
         {
             if (!table.StartsWith("__"))
             {
                 var rowVersionCol = allColumns.SingleOrDefault(c => c.TableName == table && c.DataType == "rowversion");
                 if (rowVersionCol == null)
                 {
                     repository.ExecuteSql(string.Format("ALTER TABLE {0} ADD COLUMN VersionColumn rowversion NOT NULL;{1}GO", table, Environment.NewLine));
                 }
             }
         }
     }
 }
        public SqlServerDatabaseContextMenu(DatabaseMenuCommandParameters databaseMenuCommandParameters, ExplorerToolWindow parent)
        {
            var dcmd = new DatabasesMenuCommandsHandler(parent);
            bool isSqlCe40Installed = DataConnectionHelper.IsV40Installed();
            
            var scriptGraphCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateServerDgmlFiles);
            var scriptDatabaseGraphMenuItem = new MenuItem
            {
                Header = "Create SQL Server Database Graph (DGML)...",
                Icon = ImageHelper.GetImageFromResource("../resources/Diagram_16XLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseGraphMenuItem.CommandBindings.Add(scriptGraphCommandBinding);
            Items.Add(scriptDatabaseGraphMenuItem);

            Items.Add(new Separator());

            var scriptDatabaseRootMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
            };

            var toolTip = new ToolTip();
            toolTip.Content = "Generate a SQL Server Compact compatible database script from SQL Server 2005+";

            var scriptDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ScriptServerDatabase);

            var scriptDatabaseSchemaMenuItem = new MenuItem
                                             {
                                                 Header = "Script SQL Server Database Schema...",
                                                 Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                                                 ToolTip = toolTip,
                                                 Command = DatabaseMenuCommands.DatabaseCommand,
                                                 CommandParameter = databaseMenuCommandParameters,
                                                 Tag = SqlCeScripting.Scope.Schema
                                             };
            scriptDatabaseSchemaMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaMenuItem);

            var scriptDatabaseDataMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnly
            };
            scriptDatabaseDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseDataMenuItem);

            var scriptDatabaseSchemaDataMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaData 
            };
            scriptDatabaseSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataMenuItem);

            var scriptDatabaseSchemaDataSQLiteMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data for SQLite...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataSQLite
            };
            scriptDatabaseSchemaDataSQLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataSQLiteMenuItem);

            var scriptDatabaseSchemaSQLiteMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema for SQLite...",
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                ToolTip = toolTip,
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaSQLite
            };
            scriptDatabaseSchemaSQLiteMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaSQLiteMenuItem);

            var scriptDatabaseSchemaDataBLOBMenuItem = new MenuItem
            {
                Header = "Script SQL Server Database Schema and Data with BLOBs...",
                ToolTip = toolTip,
                Icon = ImageHelper.GetImageFromResource("../resources/script_16xLG.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs 
            };
            scriptDatabaseSchemaDataBLOBMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptDatabaseRootMenuItem.Items.Add(scriptDatabaseSchemaDataBLOBMenuItem);
            Items.Add(scriptDatabaseRootMenuItem);
            Items.Add(new Separator());

            var exportServerCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ExportServerDatabaseTo40);
            var exportServerMenuItem = new MenuItem
            {
                Header = "Export SQL Server to SQL Server Compact 4.0...",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            exportServerMenuItem.CommandBindings.Add(exportServerCommandBinding);
            exportServerMenuItem.IsEnabled = (isSqlCe40Installed);
            Items.Add(exportServerMenuItem);

            var exportServerToLiteCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                               dcmd.ExportServerDatabaseToSqlite);
            var exportServerToLiteMenuItem = new MenuItem
            {
                Header = "Export SQL Server to SQLite... (beta)",
                Icon = ImageHelper.GetImageFromResource("../resources/ExportReportData_10565.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            exportServerToLiteMenuItem.CommandBindings.Add(exportServerToLiteCommandBinding);
            Items.Add(exportServerToLiteMenuItem);
        }
        public DatabaseContextMenu(DatabaseMenuCommandParameters databaseMenuCommandParameters, ExplorerControl parent)
        {
            var dcmd = new DatabaseMenuCommandsHandler(parent);

            var showSqlEditorCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.SpawnSqlEditorWindow);
            var showSqlEditorMenuItem = new MenuItem
            {
                Header = "Open SQL Editor",
                Icon = ImageHelper.GetImageFromResource("../resources/sqlEditor.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            showSqlEditorMenuItem.CommandBindings.Add(showSqlEditorCommandBinding);
            Items.Add(showSqlEditorMenuItem);

            var createTableCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.BuildTable);
            var createTableMenuItem = new MenuItem
            {
                Header = "Build Table (alpha)...",
                Icon = ImageHelper.GetImageFromResource("../resources/sqlEditor.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            createTableMenuItem.CommandBindings.Add(createTableCommandBinding);
            Items.Add(createTableMenuItem);

            Items.Add(new Separator());

            var scriptMenuItem = new MenuItem
            {
                Header = "Script",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png")
            };

            var scriptDatabaseCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                                dcmd.ScriptDatabase);
            var scriptDatabaseSchemaMenuItem = new MenuItem
            {
                Header = "Script Database Schema...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.Schema
            };
            scriptDatabaseSchemaMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptDatabaseSchemaMenuItem);

            var scriptDatabaseSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaData
            };
            scriptDatabaseSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptDatabaseSchemaDataMenuItem);

            var scriptAzureSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data for SQL Azure...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataAzure
            };
            scriptAzureSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptAzureSchemaDataMenuItem);

            var scriptSqliteSchemaDataMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data for SQLite (beta)...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataSQLite
            };
            scriptSqliteSchemaDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptSqliteSchemaDataMenuItem);

            var scriptDatabaseSchemaDataBLOBMenuItem = new MenuItem
            {
                Header = "Script Database Schema and Data with BLOBs...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.SchemaDataBlobs
            };
            scriptDatabaseSchemaDataBLOBMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptDatabaseSchemaDataBLOBMenuItem);

            var scriptDatabaseDataMenuItem = new MenuItem
            {
                Header = "Script Database Data...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnly
            };
            scriptDatabaseDataMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptDatabaseDataMenuItem);

            var scriptDatabaseDataForServerMenuItem = new MenuItem
            {
                Header = "Script Database Data for SQL Server...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = SqlCeScripting.Scope.DataOnlyForSqlServer
            };
            scriptDatabaseDataForServerMenuItem.CommandBindings.Add(scriptDatabaseCommandBinding);
            scriptMenuItem.Items.Add(scriptDatabaseDataForServerMenuItem);

            Items.Add(scriptMenuItem);

            Items.Add(new Separator());

            var scriptDiffCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateDiffScript);

            var scriptDatabaseDiffMenuItem = new MenuItem
            {
                Header = "Script Database Diff...",
                Icon = ImageHelper.GetImageFromResource("../resources/database.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseDiffMenuItem.CommandBindings.Add(scriptDiffCommandBinding);
            scriptDatabaseDiffMenuItem.ToolTip = "Script all tables, columns and constraints in this database\r\nthat are missing/different in the target database.";
            Items.Add(scriptDatabaseDiffMenuItem);

            Items.Add(new Separator());

            var scriptGraphCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.GenerateCeDgmlFiles);

            var scriptDatabaseGraphMenuItem = new MenuItem
            {
                Header = "Create Database Graph (DGML)...",
                Icon = ImageHelper.GetImageFromResource("../resources/RelationshipsHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            scriptDatabaseGraphMenuItem.CommandBindings.Add(scriptGraphCommandBinding);
            Items.Add(scriptDatabaseGraphMenuItem);

            // Documentation menu item

            var docDbCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.GenerateDocFiles);
            var docDatabaseMenuItem = new MenuItem
            {
                Header = "Create Database Documentation...",
                Icon = ImageHelper.GetImageFromResource("../resources/RelationshipsHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
            };
            docDatabaseMenuItem.CommandBindings.Add(docDbCommandBinding);
            Items.Add(docDatabaseMenuItem);

            Items.Add(new Separator());

            var scriptDCCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.GenerateDataContext);

            // Desktop Data Context
            var scriptDCMenuItem = new MenuItem
            {
                Header = "Create LINQ to SQL DataContext class...",
                Icon = ImageHelper.GetImageFromResource("../resources/RelationshipsHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = true
            };
            scriptDCMenuItem.CommandBindings.Add(scriptDCCommandBinding);
            Items.Add(scriptDCMenuItem);

            //Windows Phone Data Context
            var scriptWPDCMenuItem = new MenuItem
            {
                Header = "Create Windows Phone DataContext class...",
                Icon = ImageHelper.GetImageFromResource("../resources/Phone.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                Tag = false
            };
            scriptWPDCMenuItem.CommandBindings.Add(scriptDCCommandBinding);            
#if V35
            scriptWPDCMenuItem.IsEnabled = true;
#else
            scriptWPDCMenuItem.IsEnabled = false;
#endif
            Items.Add(scriptWPDCMenuItem);
            Items.Add(new Separator());

            var maintenanceMenuItem = new MenuItem
            {
                Header = "Maintenance",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
            };

            var shrinkCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.ShrinkDatabase);
            var shrinkMenuItem = new MenuItem
            {
                Header = "Shrink",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Shrink database by deleting free pages"
            };
            shrinkMenuItem.CommandBindings.Add(shrinkCommandBinding);
            maintenanceMenuItem.Items.Add(shrinkMenuItem);

            var compactCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.CompactDatabase);
            var compactMenuItem = new MenuItem
            {
                Header = "Compact",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Perform full database compaction"
            };
            compactMenuItem.CommandBindings.Add(compactCommandBinding);
            maintenanceMenuItem.Items.Add(compactMenuItem);

            var verifyCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                dcmd.VerifyDatabase);
            var verifyMenuItem = new MenuItem
            {
                Header = "Verify",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Verify the integrity of the database (enhanced)"
            };
            verifyMenuItem.CommandBindings.Add(verifyCommandBinding);
            maintenanceMenuItem.Items.Add(verifyMenuItem);

            var repairDeleteCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseDeleteCorruptedRows);
            var repairDeleteMenuItem = new MenuItem
            {
                Header = "Repair (delete corrupted rows)",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairDeleteMenuItem.CommandBindings.Add(repairDeleteCommandBinding);
            maintenanceMenuItem.Items.Add(repairDeleteMenuItem);

            var repairRecoverAllCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseRecoverAllOrFail);
            var repairRecoverAllMenuItem = new MenuItem
            {
                Header = "Repair (recover all or fail)",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairRecoverAllMenuItem.CommandBindings.Add(repairRecoverAllCommandBinding);
            maintenanceMenuItem.Items.Add(repairRecoverAllMenuItem);

            var repairRecoverPossibleCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                            dcmd.RepairDatabaseRecoverAllPossibleRows);
            var repairRecoverPossibleMenuItem = new MenuItem
            {
                Header = "Repair (recover all possible)",
                Icon = ImageHelper.GetImageFromResource("../resources/SplitSubdocumentHS.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters,
                ToolTip = "Repairs a corrupted database"
            };
            repairRecoverPossibleMenuItem.CommandBindings.Add(repairRecoverPossibleCommandBinding);
            maintenanceMenuItem.Items.Add(repairRecoverPossibleMenuItem);

            Items.Add(maintenanceMenuItem);

            Items.Add(new Separator());

            var addDescriptionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                        dcmd.AddDescription);
            var addDescriptionMenuItem = new MenuItem
            {
                Header = "Edit description",
                Icon = ImageHelper.GetImageFromResource("../resources/propes.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            addDescriptionMenuItem.CommandBindings.Add(addDescriptionCommandBinding);
            Items.Add(addDescriptionMenuItem);

            Items.Add(new Separator());

            var removeCeConnectionCommandBinding = new CommandBinding(DatabaseMenuCommands.DatabaseCommand,
                                                    dcmd.RemoveCeDatabase);
            var removeCeConnectionMenuItem = new MenuItem
            {
                Header = "Remove Connection",
                Icon = ImageHelper.GetImageFromResource("../resources/delete.png"),
                Command = DatabaseMenuCommands.DatabaseCommand,
                CommandParameter = databaseMenuCommandParameters
            };
            removeCeConnectionMenuItem.CommandBindings.Add(removeCeConnectionCommandBinding);
            Items.Add(removeCeConnectionMenuItem);

        }