public void GenerateDataContextInProject(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) return; var isDesktop = (bool)((MenuItem)sender).Tag; if (package == null) return; var dte = package.GetServiceHelper(typeof(EnvDTE.DTE)) as EnvDTE.DTE; if (dte == null) return; if (dte.Mode == vsIDEMode.vsIDEModeDebug) { EnvDTEHelper.ShowError("Cannot generate code while debugging"); return; } var helper = DataConnectionHelper.CreateEngineHelper(databaseInfo.DatabaseInfo.DatabaseType); if (!helper.IsV35DbProviderInstalled()) { EnvDTEHelper.ShowError("This feature requires the SQL Server Compact 3.5 SP2 DbProvider to be properly installed"); return; } var dteH = new Helpers.EnvDTEHelper(); var project = dteH.GetProject(dte); if (project == null) { EnvDTEHelper.ShowError("Please select a project in Solution Explorer, where you want the DataContext to be placed"); return; } if (!isDesktop && !dteH.AllowedWPProjectKinds.Contains(new Guid(project.Kind))) { EnvDTEHelper.ShowError("The selected project type does not support Windows Phone (please let me know if I am wrong)"); return; } if (isDesktop && !dteH.AllowedProjectKinds.Contains(new Guid(project.Kind))) { EnvDTEHelper.ShowError("The selected project type does not support LINQ to SQL (please let me know if I am wrong)"); return; } if (project.Properties.Item("TargetFrameworkMoniker") == null) { EnvDTEHelper.ShowError("The selected project type does not support Windows Phone - missing TargetFrameworkMoniker"); return; } if (!isDesktop) { if (project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "Silverlight,Version=v4.0,Profile=WindowsPhone71" || project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.0" || project.Properties.Item("TargetFrameworkMoniker").Value.ToString() == "WindowsPhone,Version=v8.1" ) { } else { EnvDTEHelper.ShowError("The selected project type does not support Windows Phone 7.1/8.0 - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value.ToString()); return; } } if (isDesktop && !project.Properties.Item("TargetFrameworkMoniker").Value.ToString().Contains(".NETFramework")) { EnvDTEHelper.ShowError("The selected project type does not support .NET Desktop - wrong TargetFrameworkMoniker: " + project.Properties.Item("TargetFrameworkMoniker").Value.ToString()); return; } if (!isDesktop && databaseInfo.DatabaseInfo.DatabaseType != DatabaseType.SQLCE35) { EnvDTEHelper.ShowError("Sorry, only version 3.5 databases are supported for now"); return; } string sqlMetalPath = string.Empty; var sqlMetalPaths = ProbeSqlMetalRegPaths(); if (sqlMetalPaths.Count == 0) { EnvDTEHelper.ShowError("Could not find SQLMetal location in registry"); return; } foreach (var path in sqlMetalPaths) { if (File.Exists(path)) { sqlMetalPath = path; break; } } if (string.IsNullOrEmpty(sqlMetalPath)) { EnvDTEHelper.ShowError("Could not find SQLMetal file location"); return; } var sdfFileName = string.Empty; try { using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var tables = repository.GetAllTableNames(); var pks = repository.GetAllPrimaryKeys(); string checkedTables = string.Empty; foreach (string tableName in tables) { var pk = pks.Where(k => k.TableName == tableName).FirstOrDefault(); if (pk.TableName == null) { checkedTables += tableName + Environment.NewLine; } } if (!string.IsNullOrEmpty(checkedTables)) { string message = string.Format("The tables below do not have Primary Keys defined,{0}and will not be generated properly:{1}{2}", Environment.NewLine, Environment.NewLine, checkedTables); EnvDTEHelper.ShowError(message); } List<KeyValuePair<string, string>> dbInfo = repository.GetDatabaseInfo(); foreach (var kvp in dbInfo) { if (kvp.Key == "Database") { sdfFileName = kvp.Value; break; } } sdfFileName = Path.GetFileName(sdfFileName); } string model = Path.GetFileNameWithoutExtension(databaseInfo.DatabaseInfo.Caption).Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); model = model + "Context"; DataContextDialog dcDialog = new DataContextDialog(); dcDialog.ModelName = model; dcDialog.IsDesktop = isDesktop; dcDialog.ProjectName = project.Name; dcDialog.NameSpace = project.Properties.Item("DefaultNamespace").Value.ToString(); if (EnvDTEHelper.VBProject == new Guid(project.Kind)) { dcDialog.CodeLanguage = "VB"; } else { dcDialog.CodeLanguage = "C#"; } bool? result = dcDialog.ShowModal(); if (result.HasValue && result.Value == true && (!string.IsNullOrWhiteSpace(dcDialog.ModelName))) { if (dcDialog.AddRowversionColumns) { AddRowVersionColumns(databaseInfo); } string sdfPath = databaseInfo.DatabaseInfo.ConnectionString; //If version 4.0, create a 3.5 schema sdf, and use that as connection string if (isDesktop && databaseInfo.DatabaseInfo.DatabaseType == DatabaseType.SQLCE40) { var tempFile = Path.GetTempFileName(); using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var generator = Helpers.DataConnectionHelper.CreateGenerator(repository, tempFile, databaseInfo.DatabaseInfo.DatabaseType); generator.ScriptDatabaseToFile(Scope.Schema); } sdfPath = Path.Combine(Path.GetTempPath(), sdfFileName); using (Stream stream = new MemoryStream(Resources.SqlCe35AddinStore)) { // Create a FileStream object to write a stream to a file using (FileStream fileStream = File.Create(sdfPath, (int)stream.Length)) { // Fill the bytes[] array with the stream data byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } DatabaseInfo info = new DatabaseInfo(); info.ConnectionString = "Data Source=" + sdfPath; info.DatabaseType = DatabaseType.SQLCE35; using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(info)) { string script = File.ReadAllText(tempFile); repository.ExecuteSql(script); } sdfPath = info.ConnectionString; } int versionNumber = GetVersionTableNumber(databaseInfo.DatabaseInfo, isDesktop); model = dcDialog.ModelName; string dcPath = Path.Combine(Path.GetTempPath(), model + ".cs"); if (dcDialog.CodeLanguage == "VB") { dcPath = Path.Combine(Path.GetTempPath(), model + ".vb"); } string parameters = " /provider:SQLCompact /code:\"" + dcPath + "\""; parameters += " /conn:\"" + sdfPath + "\""; parameters += " /context:" + model; if (dcDialog.Pluralize) { parameters += " /pluralize"; } if (!string.IsNullOrWhiteSpace(dcDialog.NameSpace)) { parameters += " /namespace:" + dcDialog.NameSpace; } var dcH = new ErikEJ.SqlCeScripting.DataContextHelper(); string sqlmetalResult = dcH.RunSqlMetal(sqlMetalPath, parameters); if (!File.Exists(dcPath)) { EnvDTEHelper.ShowError("Error during SQL Metal run: " + sqlmetalResult); return; } if (!isDesktop) { using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo)) { if (dcDialog.CodeLanguage == "VB") { DataContextHelper.FixDataContextVB(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } else { DataContextHelper.FixDataContextCS(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } } } if (dcDialog.MultipleFiles) { Dictionary<string, string> classes = DataContextHelper.SplitIntoMultipleFiles(dcPath, dcDialog.NameSpace, model); string 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); ProjectItem classItem = dteH.GetProjectDataContextClass(project, fileName); if (classItem != null) { classItem.Delete(); } project.ProjectItems.AddFromFile(fileName); } } else { string extension = ".cs"; if (dcDialog.CodeLanguage == "VB") extension = ".vb"; ProjectItem dcItem = dteH.GetProjectDC(project, model, extension); if (dcItem == null) { project.ProjectItems.AddFromFileCopy(dcPath); } else { if (EnvDTEHelper.ShowMessageBox("The Data Context class already exists in the project, do you wish to replace it?", OLEMSGBUTTON.OLEMSGBUTTON_YESNO, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_SECOND, OLEMSGICON.OLEMSGICON_QUERY) == System.Windows.Forms.DialogResult.Yes) { dcItem.Delete(); project.ProjectItems.AddFromFileCopy(dcPath); } } } EnvDTEHelper.AddReference(project, "System.Data.Linq"); if (dcDialog.AddConnectionStringBuilder) { string projectPath = project.Properties.Item("FullPath").Value.ToString(); string fileName = "LocalDatabaseConnectionStringBuilder.cs"; string filePath = Path.Combine(projectPath, fileName); if (File.Exists(filePath)) { File.Delete(filePath); } using (Stream stream = new MemoryStream(Resources.LocalDatabaseConnectionStringBuilder)) { // Create a FileStream object to write a stream to a file using (FileStream fileStream = File.Create(filePath, (int)stream.Length)) { // Fill the bytes[] array with the stream data byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); // Use FileStream object to write to the specified file fileStream.Write(bytesInStream, 0, bytesInStream.Length); } } project.ProjectItems.AddFromFile(filePath); } // Creates __Version table and adds one row if desired if (dcDialog.AddVersionTable) { using (IRepository repository = Helpers.DataConnectionHelper.CreateRepository(databaseInfo.DatabaseInfo)) { var list = repository.GetAllTableNames(); if (!list.Contains("__VERSION")) { repository.ExecuteSql(string.Format(@" CREATE TABLE [__VERSION] ( [SchemaVersion] int NOT NULL , [DateUpdated] datetime NOT NULL DEFAULT (GETDATE()) ); GO CREATE INDEX [IX_SchemaVersion] ON [__VERSION] ([SchemaVersion] DESC); GO INSERT INTO [__VERSION] ([SchemaVersion]) VALUES ({0}); GO", versionNumber)); } } } Helpers.DataConnectionHelper.LogUsage("DatabaseCreateDC"); } } catch (Exception ex) { Helpers.DataConnectionHelper.SendError(ex, databaseInfo.DatabaseInfo.DatabaseType, false); } }
public void GenerateDataContext(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } bool isDesktop = false; if ((bool)((MenuItem)sender).Tag == true) { isDesktop = true; } SqlCeHelper helper = new SqlCeHelper(); if (!helper.IsV35DbProviderInstalled()) { MessageBox.Show("This feature requires the SQL Server Compact 3.5 SP2 runtime & DbProvider to be installed"); return; } string sqlMetalPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools", "InstallationFolder", null); if (string.IsNullOrEmpty(sqlMetalPath)) { sqlMetalPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A", "InstallationFolder", string.Empty) + "bin\\NETFX 4.0 Tools\\"; if (string.IsNullOrEmpty(sqlMetalPath)) { MessageBox.Show("Could not find SQLMetal location in registry"); return; } } sqlMetalPath = Path.Combine(sqlMetalPath, "sqlmetal.exe"); if (!File.Exists(sqlMetalPath)) { MessageBox.Show("Could not find SqlMetal in the expected location: " + sqlMetalPath); return; } string sdfFileName = string.Empty; string fileName = string.Empty; SaveFileDialog fd = new SaveFileDialog(); fd.Title = "Save Data Context as"; fd.Filter = "C# code (*.cs)|*.cs|VB code|*.vb"; fd.OverwritePrompt = true; fd.ValidateNames = true; bool?fdresult = fd.ShowDialog(); if (fdresult.HasValue && fdresult.Value == true) { fileName = fd.FileName; } if (string.IsNullOrEmpty(fileName)) { return; } try { using (IRepository repository = RepoHelper.CreateRepository(databaseInfo.Connectionstring)) { var tables = repository.GetAllTableNames(); var pks = repository.GetAllPrimaryKeys(); string checkedTables = string.Empty; foreach (string tableName in tables) { var pk = pks.Where(k => k.TableName == tableName).FirstOrDefault(); if (pk.TableName == null) { checkedTables += tableName + Environment.NewLine; } } if (!string.IsNullOrEmpty(checkedTables)) { string message = string.Format("The tables below do not have Primary Keys defined,{0}and will not be generated properly:{1}{2}", Environment.NewLine, Environment.NewLine, checkedTables); MessageBox.Show(message); } List <KeyValuePair <string, string> > dbInfo = repository.GetDatabaseInfo(); foreach (var kvp in dbInfo) { if (kvp.Key == "Database") { sdfFileName = kvp.Value; break; } } sdfFileName = Path.GetFileName(sdfFileName); } string model = Path.GetFileNameWithoutExtension(databaseInfo.Caption).Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); model = model + "Context"; DataContextDialog dcDialog = new DataContextDialog(); dcDialog.ModelName = model; dcDialog.IsDesktop = isDesktop; dcDialog.NameSpace = string.Empty; dcDialog.CodeLanguage = "C#"; bool?result = dcDialog.ShowDialog(); if (result.HasValue && result.Value == true && (!string.IsNullOrWhiteSpace(dcDialog.ModelName))) { if (dcDialog.AddRowversionColumns) { AddRowVersionColumns(databaseInfo); } string sdfPath = databaseInfo.Connectionstring; #if V35 #else //If version 4.0, create a 3.5 schema sdf, and use that as connection string if (isDesktop) { var tempFile = Path.GetTempFileName(); using (IRepository repository = RepoHelper.CreateRepository(databaseInfo.Connectionstring)) { var generator = RepoHelper.CreateGenerator(repository, tempFile); generator.ScriptDatabaseToFile(Scope.Schema); } sdfPath = Path.Combine(Path.GetTempPath(), sdfFileName); if (File.Exists(sdfPath)) { File.Delete(sdfPath); } sdfPath = "Data Source=" + sdfPath; helper.CreateDatabase(sdfPath); using (IRepository repository = new DBRepository(sdfPath)) { string script = File.ReadAllText(tempFile); repository.ExecuteSql(script); } } #endif int versionNumber = GetVersionTableNumber(databaseInfo.Connectionstring, isDesktop); model = dcDialog.ModelName; string dcPath = fileName; string parameters = " /provider:SQLCompact /code:\"" + dcPath + "\""; parameters += " /conn:\"" + sdfPath + "\""; parameters += " /context:" + model; if (dcDialog.Pluralize) { parameters += " /pluralize"; } if (!string.IsNullOrWhiteSpace(dcDialog.NameSpace)) { parameters += " /namespace:" + dcDialog.NameSpace; } var dcH = new ErikEJ.SqlCeScripting.DataContextHelper(); string sqlmetalResult = dcH.RunSqlMetal(sqlMetalPath, parameters); if (!File.Exists(dcPath)) { MessageBox.Show("Error during SQL Metal run: " + sqlmetalResult); return; } if (!isDesktop) { using (IRepository repository = RepoHelper.CreateRepository(databaseInfo.Connectionstring)) { if (dcDialog.CodeLanguage == "VB") { DataContextHelper.FixDataContextVB(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } else { DataContextHelper.FixDataContextCS(dcPath, model, dcDialog.NameSpace, sdfFileName, repository); } } } // Creates __Version table and adds one row if desired if (!isDesktop && dcDialog.AddVersionTable) { using (IRepository repository = RepoHelper.CreateRepository(databaseInfo.Connectionstring)) { var list = repository.GetAllTableNames(); if (!list.Contains("__VERSION")) { repository.ExecuteSql(string.Format(@" CREATE TABLE [__VERSION] ( [SchemaVersion] int NOT NULL , [DateUpdated] datetime NOT NULL DEFAULT (GETDATE()) ); GO CREATE INDEX [IX_SchemaVersion] ON [__VERSION] ([SchemaVersion] DESC); GO INSERT INTO [__VERSION] ([SchemaVersion]) VALUES ({0}); GO", versionNumber)); } } } MessageBox.Show("DataContext class successfully created"); } } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } }
static int Main(string[] args) { if (args.Length < 2 || args.Length > 6) { PrintUsageGuide(); return 2; } else { try { string connectionString = args[0]; string outputFileLocation = args[1]; bool includeData = true; bool includeSchema = true; bool saveImageFiles = false; bool sqlAzure = false; System.Collections.Generic.List<string> exclusions = new System.Collections.Generic.List<string>(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); if (args[0].Equals("diff", StringComparison.OrdinalIgnoreCase)) { #if V31 PrintUsageGuide(); return 2; #else if (args.Length == 4) { using (var source = Helper.CreateRepository(args[1])) { using (var target = Helper.CreateRepository(args[2])) { var generator = Helper.CreateGenerator(source); SqlCeDiff.CreateDiffScript(source, target, generator, false); System.IO.File.WriteAllText(args[3], generator.GeneratedScript); return 0; } } } else { PrintUsageGuide(); return 2; } #endif } else if (args[0].Equals("dgml", StringComparison.OrdinalIgnoreCase)) { #if V31 PrintUsageGuide(); return 2; #endif if (args.Length == 3) { using (var source = Helper.CreateRepository(args[1])) { var generator = Helper.CreateGenerator(source, args[2]); generator.GenerateSchemaGraph(args[1]); } return 0; } else { PrintUsageGuide(); return 2; } } else if (args[0].Equals("wpdc", StringComparison.OrdinalIgnoreCase)) { #if V31 PrintUsageGuide(); return 2; #endif #if V40 PrintUsageGuide(); return 2; #else if (args.Length == 3) { using (var repo = Helper.CreateRepository(args[1])) { var dch = new DataContextHelper(); dch.GenerateWPDataContext(repo, args[1], args[2]); } return 0; } else { PrintUsageGuide(); return 2; } #endif } else { for (int i = 2; i < args.Length; i++) { if (args[i].Contains("dataonly")) { includeData = true; includeSchema = false; } if (args[i].Contains("schemaonly")) { includeData = false; includeSchema = true; } if (args[i].Contains("saveimages")) saveImageFiles = true; if (args[i].Contains("sqlazure")) sqlAzure = true; if (args[i].StartsWith("exclude:")) ParseExclusions(exclusions, args[i]); } using (IRepository repository = Helper.CreateRepository(connectionString)) { Helper.FinalFiles = outputFileLocation; #if V40 var generator = new Generator4(repository, outputFileLocation, sqlAzure); #else var generator = new Generator(repository, outputFileLocation, sqlAzure); #endif generator.ExcludeTables(exclusions); Console.WriteLine("Generating the tables...."); #if V31 generator.GenerateTable(false); #else generator.GenerateTable(includeData); #endif if (sqlAzure && includeSchema) { Console.WriteLine("Generating the primary keys (SQL Azure)...."); generator.GeneratePrimaryKeys(); } if (includeData) { Console.WriteLine("Generating the data...."); generator.GenerateTableContent(saveImageFiles); } if (!sqlAzure && includeSchema) { Console.WriteLine("Generating the primary keys...."); generator.GeneratePrimaryKeys(); } if (includeSchema) { Console.WriteLine("Generating the indexes...."); generator.GenerateIndex(); Console.WriteLine("Generating the foreign keys...."); generator.GenerateForeignKeys(); } Helper.WriteIntoFile(generator.GeneratedScript, outputFileLocation, generator.FileCounter); } Console.WriteLine("Sent script to output file(s) : {0} in {1} ms", Helper.FinalFiles, (sw.ElapsedMilliseconds).ToString()); return 0; } } catch (System.Data.SqlServerCe.SqlCeException e) { Console.WriteLine(Helper.ShowErrors(e)); return 1; } catch (System.Data.SqlClient.SqlException es) { Console.WriteLine(Helper.ShowErrors(es)); return 1; } catch (Exception ex) { Console.WriteLine("Error: " + ex); return 1; } } }