public void GenerateWPDataContext(IRepository repository, string connectionString, string dcPath) { if (dcPath.ToUpperInvariant().EndsWith(".CS") || dcPath.ToUpperInvariant().EndsWith(".VB")) { } else { throw new Exception("DataContext file name must end with either .cs or .vb"); } 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)) { throw new Exception("Could not find SQLMetal location in registry"); } } sqlMetalPath = Path.Combine(sqlMetalPath, "sqlmetal.exe"); if (!File.Exists(sqlMetalPath)) { throw new Exception("Could not find SqlMetal in the expected location: " + sqlMetalPath); } string model = Path.GetFileNameWithoutExtension(dcPath).Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); model = model + "Context"; string parameters = " /provider:SQLCompact /code:\"" + dcPath + "\""; parameters += " /conn:\"" + connectionString + "\""; parameters += " /context:" + model; parameters += " /pluralize"; //parameters += " /serialization:Unidirectional"; string sqlmetalResult = RunSqlMetal(sqlMetalPath, parameters); if (!File.Exists(dcPath)) { throw new Exception("Error during SQL Metal run: " + sqlmetalResult); } string sdfFileName = string.Empty; List<KeyValuePair<string, string>> dbInfo = repository.GetDatabaseInfo(); foreach (var kvp in dbInfo) { if (kvp.Key == "Database") { sdfFileName = kvp.Value; break; } } sdfFileName = Path.GetFileName(sdfFileName); if (dcPath.ToUpperInvariant().EndsWith(".VB")) { FixDataContextVB(dcPath, model, null, sdfFileName, repository); } else { FixDataContextCS(dcPath, model, null, sdfFileName, repository); } }
public void GenerateWPDataContext(IRepository repository, string connectionString, string dcPath) { if (dcPath.ToUpperInvariant().EndsWith(".CS") || dcPath.ToUpperInvariant().EndsWith(".VB")) { } else { throw new Exception("DataContext file name must end with either .cs or .vb"); } string sqlMetalPath = (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A\WinSDK-NetFx40Tools", "InstallationFolder", null); if (sqlMetalPath == null) { throw new Exception("Could not find SQLMetal location in registry"); } sqlMetalPath = Path.Combine(sqlMetalPath, "sqlmetal.exe"); if (!File.Exists(sqlMetalPath)) { throw new Exception("Could not find SqlMetal in the expected location: " + sqlMetalPath); } string model = Path.GetFileNameWithoutExtension(dcPath).Replace(" ", string.Empty).Replace("#", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty); model = model + "Context"; string parameters = " /provider:SQLCompact /code:\"" + dcPath + "\""; parameters += " /conn:\"" + connectionString + "\""; parameters += " /context:" + model; parameters += " /pluralize"; string sqlmetalResult = RunSqlMetal(sqlMetalPath, parameters); if (!File.Exists(dcPath)) { throw new Exception("Error during SQL Metal run: " + sqlmetalResult); } string sdfFileName = string.Empty; List <KeyValuePair <string, string> > dbInfo = repository.GetDatabaseInfo(); foreach (var kvp in dbInfo) { if (kvp.Key == "Database") { sdfFileName = kvp.Value; break; } } sdfFileName = Path.GetFileName(sdfFileName); if (dcPath.ToUpperInvariant().EndsWith(".VB")) { FixDataContextVB(dcPath, model, null, sdfFileName, repository); } else { FixDataContextCS(dcPath, model, null, sdfFileName, repository); } }
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)); } }
private void Init(IRepository repository, string outFile) { _outFile = outFile; _repository = repository; _sbScript = new StringBuilder(10485760); _tableNames = _repository.GetAllTableNames(); _allColumns = _repository.GetColumnsFromTable(); _allForeignKeys = repository.GetAllForeignKeys(); _allPrimaryKeys = repository.GetAllPrimaryKeys(); if (_repository.IsServer()) { // Check if datatypes are supported when exporting from server // Either they can be converted, are supported, or an exception is thrown (if not supported) // Currently only sql_variant is not supported foreach (Column col in _allColumns) { col.CharacterMaxLength = Helper.CheckDateColumnLength(col.DataType, col); col.DateFormat = Helper.CheckDateFormat(col.DataType); // Check if the current column points to a unique identity column, // as the two columns' datatypes must match bool refToIdentity = false; Dictionary<string, Constraint> columnForeignKeys = new Dictionary<string, Constraint>(); // Fix for multiple constraints with same columns var _tableKeys = _allForeignKeys.Where(c => c.ConstraintTableName == col.TableName); foreach (var constraint in _tableKeys) { if (!columnForeignKeys.ContainsKey(constraint.Columns.ToString())) { columnForeignKeys.Add(constraint.Columns.ToString(), constraint); } } if (columnForeignKeys.ContainsKey(string.Format("[{0}]", col.ColumnName))) { var refCol = _allColumns.Where(c => c.TableName == columnForeignKeys[string.Format("[{0}]", col.ColumnName)].UniqueConstraintTableName && string.Format("[{0}]", c.ColumnName) == columnForeignKeys[string.Format("[{0}]", col.ColumnName)].UniqueColumnName).Single(); if (refCol != null && refCol.AutoIncrementBy > 0) { refToIdentity = true; } } // This modifies the datatype to be SQL Compact compatible col.DataType = Helper.CheckDataType(col.DataType, col, refToIdentity); } _sbScript.AppendFormat("-- Script Date: {0} {1} - Generated by Export2SqlCe version {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); } else { _sbScript.AppendFormat("-- Script Date: {0} {1} - Generated by ExportSqlCe version {2}", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Version); } _sbScript.AppendLine(); if (!string.IsNullOrEmpty(_outFile) && !_repository.IsServer()) { _sbScript.Append("-- Database information:"); _sbScript.AppendLine(); foreach (var kv in _repository.GetDatabaseInfo()) { _sbScript.Append("-- "); _sbScript.Append(kv.Key); _sbScript.Append(": "); _sbScript.Append(kv.Value); _sbScript.AppendLine(); } _sbScript.AppendLine(); // Populate all tablenames _sbScript.Append("-- User Table information:"); _sbScript.AppendLine(); _sbScript.Append("-- "); _sbScript.Append("Number of tables: "); _sbScript.Append(_tableNames.Count); _sbScript.AppendLine(); foreach (string tableName in _tableNames) { Int64 rowCount = _repository.GetRowCount(tableName); _sbScript.Append("-- "); _sbScript.Append(tableName); _sbScript.Append(": "); _sbScript.Append(rowCount); _sbScript.Append(" row(s)"); _sbScript.AppendLine(); } _sbScript.AppendLine(); } }