public void ScriptAsData(object sender, ExecutedRoutedEventArgs e) { try { var menuInfo = ValidateMenuInfo(sender); if (menuInfo != null) { using (IRepository repository = RepoHelper.CreateRepository(menuInfo.Connectionstring)) { var generator = RepoHelper.CreateGenerator(repository); generator.GenerateTableContent(menuInfo.Name, false, Properties.Settings.Default.IgnoreIdentityInInsertScript); OpenSqlEditorToolWindow(menuInfo, generator.GeneratedScript); } } } catch (Exception ex) { MessageBox.Show(DataConnectionHelper.ShowErrors(ex)); } }
public void ScriptAsCreate(object sender, ExecutedRoutedEventArgs e) { try { var menuInfo = ValidateMenuInfo(sender); if (menuInfo != null) { using (IRepository repository = RepoHelper.CreateRepository(menuInfo.Connectionstring)) { var generator = RepoHelper.CreateGenerator(repository); generator.GenerateTableScript(menuInfo.Name); OpenSqlEditorToolWindow(menuInfo, generator.GeneratedScript); } } } catch (Exception ex) { MessageBox.Show(DataConnectionHelper.ShowErrors(ex)); } }
private void ExecuteSqlScriptInEditor() { Debug.Assert(!string.IsNullOrEmpty(Database), "Database property of this control has not been set by parent window or control"); using (var repository = RepoHelper.CreateRepository(Database)) { try { var sql = GetSqlFromSqlEditorTextBox(); if (string.IsNullOrWhiteSpace(sql)) { return; } sql = sql.Replace("\r", " \r"); sql = sql.Replace("GO \r", "GO\r"); sql = sql.Replace("GO \r", "GO\r"); Stopwatch sw = new Stopwatch(); sw.Start(); var dataset = repository.ExecuteSql(sql); sw.Stop(); FormatTime(sw); if (dataset != null) { ParseDataSetResultsToResultsBox(dataset); } } catch (SqlCeException sqlException) { ParseSqlErrorToResultsBox(sqlException); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
public void SpawnReportViewerWindow(object sender, ExecutedRoutedEventArgs e) { try { var menuItem = sender as MenuItem; if (menuItem == null) { return; } var menuInfo = menuItem.CommandParameter as MenuCommandParameters; if (menuInfo == null) { return; } WindowsFormsHost wh = new WindowsFormsHost(); ReportGrid rg = new ReportGrid(); DataSet ds; using (IRepository repository = RepoHelper.CreateRepository(menuInfo.Connectionstring)) { var generator = RepoHelper.CreateGenerator(repository); generator.GenerateTableSelect(menuInfo.Name); var sqlText = generator.GeneratedScript; ds = repository.ExecuteSql(sqlText); } rg.DataSet = ds; rg.TableName = menuInfo.Name; wh.Child = rg; string tabTitle = System.IO.Path.GetFileNameWithoutExtension(menuInfo.Caption) + "-" + menuInfo.Name + "-Report"; bool alreadyThere = false; int i = -1; foreach (var item in _parent.FabTab.Items) { i++; if (item is FabTabItem) { FabTabItem ftItem = (FabTabItem)item; if (ftItem.Header.ToString() == tabTitle) { alreadyThere = true; } } } if (alreadyThere) { _parent.FabTab.SelectedIndex = i; _parent.FabTab.Focus(); } else { FabTabItem tab = new FabTabItem(); tab.Content = wh; tab.Header = tabTitle; _parent.FabTab.Items.Add(tab); _parent.FabTab.SelectedIndex = _parent.FabTab.Items.Count - 1; rg.Focus(); } } catch (System.IO.FileNotFoundException) { MessageBox.Show("Microsoft Report Viewer 2010 not installed, please download and install to use this feature http://www.microsoft.com/en-us/download/details.aspx?id=6442"); } catch (Exception ex) { MessageBox.Show(DataConnectionHelper.ShowErrors(ex)); } }
public void SpawnDataEditorWindow(object sender, ExecutedRoutedEventArgs e) { try { var menuItem = sender as MenuItem; if (menuItem == null) { return; } var menuInfo = menuItem.CommandParameter as MenuCommandParameters; if (menuInfo == null) { return; } WindowsFormsHost wh = new WindowsFormsHost(); ResultsetGrid rg = new ResultsetGrid(); List <int> readOnlyColumns = new List <int>(); using (IRepository repository = RepoHelper.CreateRepository(menuInfo.Connectionstring)) { var tpks = repository.GetAllPrimaryKeys().Where(pk => pk.TableName == menuInfo.Name).ToList(); if (tpks.Count == 0) { rg.ReadOnly = true; } List <Column> cols = repository.GetAllColumns(); cols = cols.Where(c => c.TableName == menuInfo.Name).ToList(); int x = 0; foreach (Column col in cols) { if (col.AutoIncrementBy > 0 || col.RowGuidCol) { readOnlyColumns.Add(x); } x++; } } var sqlText = string.Format(Environment.NewLine + "SELECT TOP({0}) * FROM [{1}]", Properties.Settings.Default.MaxRowsToEdit, menuInfo.Name); rg.TableName = sqlText; rg.ConnectionString = menuInfo.Connectionstring; rg.Tag = wh; rg.ReadOnlyColumns = readOnlyColumns; wh.Child = rg; string tabTitle = System.IO.Path.GetFileNameWithoutExtension(menuInfo.Caption) + "-" + menuInfo.Name + "-Edit"; if (rg.ReadOnly) { tabTitle = System.IO.Path.GetFileNameWithoutExtension(menuInfo.Caption) + "-" + menuInfo.Name + "-ReadOnly"; } bool alreadyThere = false; int i = -1; foreach (var item in _parent.FabTab.Items) { i++; if (item is FabTabItem) { FabTabItem ftItem = (FabTabItem)item; if (ftItem.Header.ToString() == tabTitle) { alreadyThere = true; } } } if (alreadyThere) { _parent.FabTab.SelectedIndex = i; _parent.FabTab.Focus(); } else { FabTabItem tab = new FabTabItem(); tab.Content = wh; tab.Header = tabTitle; _parent.FabTab.Items.Add(tab); _parent.FabTab.SelectedIndex = _parent.FabTab.Items.Count - 1; rg.Focus(); } } catch (Exception ex) { MessageBox.Show(DataConnectionHelper.ShowErrors(ex)); } }
/// <summary> /// The entry point. /// </summary> /// <param name="parameters"></param> private static void RunMain(CommandLineArguments parameters) { InitialRun(parameters); if (!parameters.DoNotClone) { CheckFreeSpace(parameters.Repo, parameters.Out); } string clonedRepoPath = Path.Combine(parameters.Out, ".git"); if (!parameters.DoNotClone) { clonedRepoPath = CloneRepository(parameters.Repo, parameters.Out); } string enClonedRepoPath = null; if (!String.IsNullOrEmpty(parameters.EnOut)) { enClonedRepoPath = Path.Combine(parameters.EnOut, ".git"); if (!String.IsNullOrEmpty(parameters.EnRepo)) { enClonedRepoPath = CloneRepository(parameters.EnRepo, parameters.EnOut); } } if (!RepoHelper.TryToCheckClonedRepo(parameters.Out, parameters.Json, out string pathToDocFxJson)) { Logger.LogError($"{Error}: File {pathToDocFxJson} does not exist"); Exit(ExitCodeEnum.InvalidRepo); } string pathToEnDocFxJson = null; if (enClonedRepoPath != null && !RepoHelper.TryToCheckClonedRepo(parameters.EnOut, parameters.Json, out pathToEnDocFxJson)) { Logger.LogError($"{Error}: File {pathToEnDocFxJson} does not exist in en-US repository"); Exit(ExitCodeEnum.InvalidRepo); } string repoLocalRoot = Path.GetDirectoryName(pathToDocFxJson); string repoEnUsLocalRoot = Path.GetDirectoryName(pathToEnDocFxJson); if (!DocFxJsonHelper.IsDocFxJsonCorrect(pathToDocFxJson)) { Logger.LogError(DocFxJsonIncorrect); Exit(ExitCodeEnum.InvalidRepo); } FilesCollector filesCollector = new FilesCollector(Logger); Logger.LogInfo("Collecting files, it may take awhile..."); string[] files = filesCollector.FindAllFiles(repoLocalRoot, "*.md|*.yml", (fname, count) => { Console.SetCursorPosition(0, Console.CursorTop); Console.CursorVisible = false; string file = Path.GetFileName(fname); if (file != null && file.Length > 30) { file = file.Substring(file.Length - 30, 30); } Console.Write($@"Found {count} files: {file}"); }); Console.SetCursorPosition(0, Console.CursorTop); Console.Write(new char[80]); Console.SetCursorPosition(0, Console.CursorTop); Logger.LogInfo($"Found {files.Length} files."); Console.WriteLine(@"Normalizing files..."); foreach (string f in files) { string content = File.ReadAllText(f); content = Regex.Replace(content, "ms.contentlocale:.*", "ms.contentlocale: " + parameters.Lng); File.WriteAllText(f, content); } string externalText = parameters.ExternalText; if (!String.IsNullOrEmpty(externalText)) { externalText = " " + externalText; } if (!parameters.ReplaceUrl.EndsWith("/")) { parameters.ReplaceUrl = $"{parameters.ReplaceUrl}/"; } string baseEnUsUrl = parameters.ReplaceUrl; string baseWoExtUrl = null; if (Uri.TryCreate(parameters.ReplaceUrl, UriKind.Absolute, out var uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps)) { baseWoExtUrl = $"{uriResult.Scheme}://{uriResult.Host}"; } foreach (string f in files) { string content = File.ReadAllText(f); StringBuilder newContent = new StringBuilder(); LinkProcessorBase proc = new ConceptualLinkProcessor(Logger, repoLocalRoot, parameters.ReplaceUrl, baseEnUsUrl, baseWoExtUrl, externalText, repoLocalRoot != null ? f.Replace(repoLocalRoot, "").TrimStart('\\') : "", repoEnUsLocalRoot, content, newContent); bool hasModified = proc.ProcessContentLinks(); if (hasModified) { File.WriteAllText(f, newContent.ToString()); } AppendTextLog(LogType.NotExistingFiles, proc.GetLogContent(LogType.NotExistingFiles)); AppendTextLog(LogType.NormalFiles, proc.GetLogContent(LogType.NormalFiles)); AppendTextLog(LogType.CopiedFiles, proc.GetLogContent(LogType.CopiedFiles)); AppendTextLog(LogType.ReplacedLinks, proc.GetLogContent(LogType.ReplacedLinks)); AppendTextLog(LogType.ReplacedEnUsLinks, proc.GetLogContent(LogType.ReplacedEnUsLinks)); AppendRemovedFiles(proc.GetFilesToRemove()); AppendIgnoredFiles(proc.GetFilesToIgnore()); if (proc.GetCopiedFiles().Length > 0) { ProcessCopiedFiles(repoLocalRoot, parameters.ReplaceUrl, baseEnUsUrl, baseWoExtUrl, externalText, repoEnUsLocalRoot, proc.GetCopiedFiles()); } } LogFiles logFiles = new LogFiles(parameters.LogsDir); StringBuilder sb = new StringBuilder(); foreach (string file in LRemovedFiles) { if (!LIgnoredFiles.Contains(file)) { sb.AppendLine(file); string path = Path.Combine(repoLocalRoot, file); if (File.Exists(path)) { File.Delete(path); } } } WriteLog(sb.ToString(), logFiles.RemovedFilesLog, "The files which have been removed"); StringBuilder sbIgnored = new StringBuilder(); foreach (string file in LIgnoredFiles) { sbIgnored.AppendLine(file); } WriteLog(SbNormalFiles.ToString(), logFiles.NormalFilesLog, "The normal files"); WriteLog(SbNotExistingFiles.ToString(), logFiles.NotExistentFilesLog, "Not Existing Link;Source File"); WriteLog(SbCopiedFiles.ToString(), logFiles.CopiedFilesLog, "The files which have been copied from en-US repository"); WriteLog(SbReplacedLinks.ToString(), logFiles.ReplacedLinksLog, "Source file,Link,Title,New Link,New Title"); WriteLog(SbReplacedEnUsLinks.ToString(), logFiles.ReplacedLanguageLinksLog, "Source file,Link,Title,New Link,New Title"); //WriteLog(sbIgnored.ToString(), "logs\\ignored files.txt", "The ignored files"); string tempDocFxZipFile = SaveToTempFile(Properties.Resources.docfx, DocFxZip); string tempDocFxDir = ExtractZip(tempDocFxZipFile, DocFxZip); CopyCustomPlugin(pathToDocFxJson); string pathToTemplateZip = SaveToTempFile(Properties.Resources.mstemplate, MsTemplateZip); string templateTempDir = ExtractZip(pathToTemplateZip, MsTemplateZip); UtilityHelper.CopyDirectory(templateTempDir, Path.GetDirectoryName(pathToDocFxJson)); if (String.IsNullOrEmpty(parameters.Lng)) { parameters.Lng = "en-us"; } Logger.LogInfo($"Setting language {parameters.Lng} for template...", false); SetLanguage(parameters.Lng, Path.GetDirectoryName(pathToDocFxJson)); Logger.LogInfo(Completed); DocFxJsonHelper.ModifyDocfxJson(pathToDocFxJson, CustomPluginName, parameters.Rtl); string docfxexe = Path.Combine(tempDocFxDir, DocFxExe); int exitCodeDocFx = RunDocFx(docfxexe, pathToDocFxJson); ExitCodeEnum exitCode = ExitCodeEnum.Success; if (exitCodeDocFx != 0) { exitCode = ExitCodeEnum.DocFxError; Logger.LogError($"{Error}: exit code {exitCode}"); } DocFxJsonHelper.RevertDocfxJson(pathToDocFxJson, CustomPluginName); RepoHelper.CleanRepo(parameters.RemoveGitFolder ? clonedRepoPath : null, pathToDocFxJson); string docfxDir = Path.GetDirectoryName(pathToDocFxJson); RemoveTemp(new[] { tempDocFxDir, tempDocFxZipFile, pathToTemplateZip, templateTempDir, (docfxDir != null ? Path.Combine(docfxDir, CustomPluginName) : null) }); string consoleOutput = Logger.GetLogContent(); File.WriteAllText(logFiles.ConsoleLog, consoleOutput); Exit(exitCode); }
public void ExportServerDatabaseTo40(object sender, ExecutedRoutedEventArgs e) { var menuItem = sender as MenuItem; if (menuItem == null) { return; } var databaseInfo = menuItem.CommandParameter as DatabasesMenuCommandParameters; if (databaseInfo == null) { return; } var treeViewItem = databaseInfo.DatabasesTreeViewItem; try { DataSource sqlDataSource = new DataSource("MicrosoftSqlServer", "Microsoft SQL Server"); sqlDataSource.Providers.Add(DataProvider.SqlDataProvider); DataConnectionDialog dcd = new DataConnectionDialog(); dcd.DataSources.Add(sqlDataSource); dcd.SelectedDataProvider = DataProvider.SqlDataProvider; dcd.SelectedDataSource = sqlDataSource; if (DataConnectionDialog.Show(dcd) == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(dcd.ConnectionString)) { PickTablesDialog ptd = new PickTablesDialog(); int totalCount = 0; using (IRepository repository = RepoHelper.CreateServerRepository(dcd.ConnectionString)) { ptd.Tables = repository.GetAllTableNamesForExclusion(); totalCount = ptd.Tables.Count; } ptd.Owner = Application.Current.MainWindow; bool?res = ptd.ShowDialog(); if (res.HasValue && res.Value == true && (ptd.Tables.Count < totalCount)) { string sdfName; SaveFileDialog fd = new SaveFileDialog(); fd.Title = "Export as"; fd.Filter = "SQL Server Compact Database (*.sdf)|*.sdf|All Files(*.*)|*.*"; fd.OverwritePrompt = true; fd.ValidateNames = true; bool?result = fd.ShowDialog(); if (result.HasValue && result.Value == true) { sdfName = fd.FileName; using (IRepository repository = RepoHelper.CreateServerRepository(dcd.ConnectionString)) { try { string scriptRoot = System.IO.Path.GetTempFileName(); string tempScript = scriptRoot + ".sqlce"; var generator = RepoHelper.CreateGenerator(repository, tempScript); generator.ExcludeTables(ptd.Tables); SetStatus("Scripting server database..."); generator.ScriptDatabaseToFile(Scope.SchemaData); SetStatus("Creating SQL Server Compact database..."); ISqlCeHelper helper = RepoHelper.CreateHelper(); string sdfConnectionString = string.Format("Data Source={0};Max Database Size=4091", sdfName); if (System.IO.File.Exists(sdfName)) { File.Delete(sdfName); } helper.CreateDatabase(sdfConnectionString); BackgroundWorker bw = new BackgroundWorker(); List <string> parameters = new List <string>(); parameters.Add(sdfConnectionString); parameters.Add(tempScript); parameters.Add(scriptRoot); bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerCompleted += (s, ea) => { try { if (ea.Error != null) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ea.Error)); } else { MessageBox.Show("Database successfully exported"); } } finally { bw.Dispose(); } }; bw.RunWorkerAsync(parameters); } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } } } } dcd.Dispose(); } } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } }
private void BackfillCommitDates( IEnumerable <CodeLinkMap.FileData> files, Repository repo, RepoHelper helper) { // This is currently a very inefficient algorithm. // In theory, we just want information about the last commit to touch each file. //var filesMap = new Dictionary<string, CodeLinkMap.FileData>(files.Count()); //foreach (var file in files) { filesMap[file.RelFilePath] = file; } var filesMap = files.ToDictionary(f => f.RelFilePath, f => f, CodeLinkMap.FileData.PathComparer); var todo = filesMap.Count; Status.WriteLine(Severity.Information, $"Looking for commit information for {todo} files in repo."); Status.ScrollToCaret(); // Ignore merge commits (with 2 parents). foreach (var commit in repo.Commits.Where(c => c.Parents.Count() is 1)) { // Search each change in each commit for the files we're interested in. var diff = repo.Diff.Compare <TreeChanges>(commit.Parents.First().Tree, commit.Tree); foreach (var change in diff.Where(i => i.Status != ChangeKind.Unmodified)) { // Not sure why `filesMap.ContainsKey(change.Path)` was having issues with string casing. var key = filesMap.Keys.FirstOrDefault( k => string.Equals(change.Path, k, StringComparison.InvariantCultureIgnoreCase)); if (key != null) { // If we've found a match, fill in the commit information. var fileEntry = filesMap[key]; fileEntry.CommitSha = commit.Id.Sha; fileEntry.Author = commit.Author.Name; fileEntry.LastCommitDate = commit.Author.When; fileEntry.LastChangeStatus = change.Status.ToString(); // Remove this file from the list of files to search for. // Use the key that was used to create the dictionary, not the path used to find the entry. if (filesMap.Remove(key)) { todo--; } else { Status.WriteLine(Severity.Error, $"Failed to remove {change.Path} from the temporary collection."); } if (todo is 0) { break; } } } if (todo is 0) { break; } } if (filesMap.Count > 0) { Status.WriteLine(Severity.Warning, $"Failed to get commit data for {filesMap.Count} files."); foreach (var fileEntry in filesMap.Values) { fileEntry.CommitSha = "unknown"; fileEntry.Author = "unknown"; fileEntry.LastChangeStatus = "unknown"; } } }
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)); } }
public void GenerateServerDgmlFiles(object sender, ExecutedRoutedEventArgs e) { // http://www.mztools.com/articles/2007/MZ2007011.aspx var menuItem = sender as MenuItem; if (menuItem == null) { return; } var databaseInfo = menuItem.CommandParameter as DatabasesMenuCommandParameters; if (databaseInfo == null) { return; } var treeViewItem = databaseInfo.DatabasesTreeViewItem; bool originalValue = Properties.Settings.Default.KeepServerSchemaNames; try { DataSource sqlDataSource = new DataSource("MicrosoftSqlServer", "Microsoft SQL Server"); sqlDataSource.Providers.Add(DataProvider.SqlDataProvider); DataConnectionDialog dcd = new DataConnectionDialog(); dcd.DataSources.Add(sqlDataSource); dcd.SelectedDataProvider = DataProvider.SqlDataProvider; dcd.SelectedDataSource = sqlDataSource; if (DataConnectionDialog.Show(dcd) == System.Windows.Forms.DialogResult.OK) { string connectionString = dcd.ConnectionString; string fileName; PickTablesDialog ptd = new PickTablesDialog(); int totalCount = 0; using (IRepository repository = RepoHelper.CreateServerRepository(dcd.ConnectionString)) { ptd.Tables = repository.GetAllTableNamesForExclusion(); totalCount = ptd.Tables.Count; } ptd.Owner = Application.Current.MainWindow; bool?res = ptd.ShowDialog(); if (res.HasValue && res.Value == true && (ptd.Tables.Count < totalCount)) { SaveFileDialog fd = new SaveFileDialog(); fd.Title = "Save generated DGML file as"; fd.Filter = "DGML (*.dgml)|*.dgml"; fd.OverwritePrompt = true; fd.ValidateNames = true; bool?result = fd.ShowDialog(); if (result.HasValue && result.Value == true) { Properties.Settings.Default.KeepServerSchemaNames = true; fileName = fd.FileName; #if V35 using (IRepository repository = new ServerDBRepository(connectionString, Properties.Settings.Default.KeepServerSchemaNames)) #else using (IRepository repository = new ServerDBRepository4(connectionString, Properties.Settings.Default.KeepServerSchemaNames)) #endif { var generator = RepoHelper.CreateGenerator(repository, fileName); generator.GenerateSchemaGraph(connectionString, ptd.Tables); MessageBox.Show(string.Format("Saved {0}", fileName)); } } } dcd.Dispose(); } } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } finally { Properties.Settings.Default.KeepServerSchemaNames = originalValue; } }
public void GenerateDiffScript(object sender, ExecutedRoutedEventArgs e) { var databaseInfo = ValidateMenuInfo(sender); if (databaseInfo == null) { return; } try { SortedDictionary <string, string> databaseList = Helpers.DataConnectionHelper.GetDataConnections(); foreach (KeyValuePair <string, string> info in databaseList) { if (!databaseList.ContainsKey(info.Key)) { databaseList.Add(info.Key, info.Value); } } CompareDialog cd = new CompareDialog(databaseInfo.Caption, databaseList); bool?result = cd.ShowDialog(); if (result.HasValue && result.Value == true && (cd.TargetDatabase.Key != null)) { var target = cd.TargetDatabase.Value; var source = databaseInfo.Connectionstring; var editorTarget = target; using (IRepository sourceRepository = RepoHelper.CreateRepository(source)) { var generator = RepoHelper.CreateGenerator(sourceRepository); using (IRepository targetRepository = RepoHelper.CreateRepository(target)) { try { SqlCeDiff.CreateDiffScript(sourceRepository, targetRepository, generator, Properties.Settings.Default.DropTargetTables); string explain = @"-- This database diff script contains the following objects: -- - Tables: Any that are not in the destination -- - (tables that are only in the destination are not dropped) -- - Columns: Any added, deleted, changed columns for existing tables -- - Indexes: Any added, deleted indexes for existing tables -- - Foreign keys: Any added, deleted foreign keys for existing tables -- ** Make sure to test against a production version of the destination database! ** " + Environment.NewLine + Environment.NewLine; databaseInfo.Connectionstring = cd.TargetDatabase.Value; databaseInfo.Caption = cd.TargetDatabase.Key; OpenSqlEditorToolWindow(databaseInfo, explain + generator.GeneratedScript); } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } } } } } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } }
public IEnumerable <OffenderExit> GetAllOffenderExits() { var offenderExitRecords = RepoHelper.GetRecords(_filepath); return(offenderExitRecords.Select(constructOffenderExitEntity)); }
private void GetTableColumns(object sender, RoutedEventArgs args, List <Column> columns, KeyValuePair <string, string> database) { var viewItem = sender as DatabaseTreeViewItem; // Prevent loading again and again if (viewItem != null && (viewItem.Items.Count > 0 && viewItem.Items[0].ToString() == "Loading...")) { var tableName = viewItem.MetaData; viewItem.Items.Clear(); using (var _repository = RepoHelper.CreateRepository(database.Value)) { // If the node is being refreshed by the user, make sure to reload the columns instead of using the cached ones from the // previous load of the entire database tree if (viewItem.IsRefreshing) { columns = _repository.GetAllColumns().Where(x => x.TableName == tableName).ToList(); } var pkList = _repository.GetAllPrimaryKeys().Where(p => p.TableName == tableName); var pks = (from pk in pkList select pk.ColumnName).ToList <string>(); var fkList = _repository.GetAllForeignKeys().Where(fk => fk.ConstraintTableName == tableName).ToList(); foreach (var column in columns) { var display = column.ShortType; var image = "../Resources/column.png"; var constraints = (from fk in fkList where fk.Columns.Contains(column.ColumnName) select fk); if (constraints.Count() > 0) { display = "FK, " + display; image = "../Resources/fk.png"; } if (pks.Contains(column.ColumnName)) { display = "PK, " + display; image = "../Resources/key.png"; } string nullable = " not null)"; if (column.IsNullable == YesNoOption.YES) { nullable = " null)"; } display = column.ColumnName + " (" + display + nullable; var i = TreeViewHelper.CreateTreeViewItemWithImage(display, image, false); i.ContextMenu = new ColumnContextMenu(new MenuCommandParameters { Description = tableName, Connectionstring = database.Value, Name = column.ColumnName, MenuItemType = MenuCommandParameters.MenuType.Table }, this); i.ToolTip = column.ColumnName; if (DescriptionCache != null) { var desc = DescriptionCache.Where(dc => dc.Parent == tableName && dc.Object == column.ColumnName).Select(dc => dc.Description).SingleOrDefault(); if (!string.IsNullOrWhiteSpace(desc)) { i.ToolTip = desc; } } viewItem.Items.Add(i); } var indexesItem = TreeViewHelper.CreateTreeViewItemWithImage("Indexes", "../Resources/folder.png", true); indexesItem.Items.Clear(); string oldName = string.Empty; foreach (var primaryKey in pkList) { if (oldName != primaryKey.KeyName) { var display = primaryKey.KeyName + " (Primary Key)"; var indexItem = TreeViewHelper.CreateTreeViewItemWithImage(display, "../Resources/index.png", false); indexItem.ContextMenu = new IndexContextMenu(new MenuCommandParameters { Connectionstring = database.Value, Name = viewItem.MetaData, MenuItemType = MenuCommandParameters.MenuType.Table, Caption = primaryKey.KeyName }, this); indexItem.ToolTip = primaryKey.KeyName; indexesItem.Items.Add(indexItem); oldName = primaryKey.KeyName; } } oldName = string.Empty; var indexes = _repository.GetIndexesFromTable(viewItem.MetaData); foreach (var index in indexes) { if (oldName != index.IndexName) { var display = string.Empty; if (index.Unique) { display = index.IndexName + " (Unique)"; } else { display = index.IndexName + " (Non-Unique)"; } var indexItem = TreeViewHelper.CreateTreeViewItemWithImage(display, "../Resources/index.png", false); indexItem.ContextMenu = new IndexContextMenu(new MenuCommandParameters { Connectionstring = database.Value, Name = viewItem.MetaData, MenuItemType = MenuCommandParameters.MenuType.Table, Caption = index.IndexName }, this); indexItem.ToolTip = index.IndexName; indexesItem.Items.Add(indexItem); oldName = index.IndexName; } } viewItem.Items.Add(indexesItem); } } args.Handled = true; }
// To simplify things, the initial report uses constants. // TODO Add command line args to allow the user to change things, or set this up with some sort of GUI. // TODO Refactor so this isn't a monolithic method. public static async Task Main(string[] args) { Console.WriteLine(Strings.About); if (args.Any(p => p.Equals("clear", StringComparison.InvariantCultureIgnoreCase))) { SecretsManager.Clear(); } // Check for and collect credentials. if (!TryGetCredentials(out var userName, out var userToken)) { return; } // Check for and create the output directory. var outputPath = TryCreateOutputDirectory(GitHubConstants.DefaultOutputRoot); if (outputPath is null) { return; } // Test the credentials. var nameToGet = "bot-docs"; var repo = GitHubConstants.KnownRepos.FirstOrDefault( r => r.Name.Equals(nameToGet, StringComparison.InvariantCultureIgnoreCase)); if (repo is null) { Console.WriteLine($"Sorry, The '{nameToGet}' repo is not defined in the constants file; exiting."); return; } Console.WriteLine("Testing your user token..."); try { var data = await GitHubQlService.ExecuteGraphQLRequest(Requests.GetUserInfo(userName)); //await GitHubGraphQlService.Queries // .GetUser(userName).ConfigureAwait(false); Console.WriteLine(data.User.ForConsole()); } catch (Exception ex) { Console.WriteLine($"{ex.GetType().Name} encountered: {ex.Message}...exiting."); return; } Console.WriteLine(); // Generate a simple bot-docs report summarizing the contents of the repo. var summaryHelper = new RepoHelper(Now); var query = Requests.GetRepository(repo); var rData = await GitHubQlService.ExecuteGraphQLRequest(query); var repoReport = Path.Combine(outputPath, "Repository.csv"); Console.Write($"Writing general information about the repository to '{repoReport}'..."); using (TextWriter writer = new StreamWriter(repoReport, false)) { writer.WriteLine(string.Join(',', summaryHelper.DefaultFormatter.Keys)); writer.WriteLine(string.Join(',', summaryHelper.DefaultFormatter.Values.Select(func => func(rData.Repository)?.CsvEscape() ?? string.Empty))); } Console.WriteLine("done."); Console.WriteLine(); // Generate an issues report against the bot-docs repo. var issueHelper = new IssueHelper(Now); await GetDocRepoIssues(repo, outputPath, issueHelper.DefaultFormatter); // Generate report for open doc issues in the code repos. var filePath = Path.Combine(outputPath, "CodeRepoIssues.csv"); var repos = GitHubConstants.KnownRepos.Where(r => RepoIsOfType(r, GitHubConstants.RepoTypes.Code)); var stateFilter = new IssueState[] { IssueState.OPEN }; var labelFilter = new string[] { "documentation", "Docs", "DCR" }; await GenerateIssuesReport(repos, issueHelper.DefaultFormatter, filePath, stateFilter, labelFilter); // Generate an issues report against the botframework-solutions repo. filePath = Path.Combine(outputPath, "SlaIssuesReport.csv"); repos = GitHubConstants.KnownRepos.Where(r => r.Name.Equals("botframework-solutions", StringComparison.CurrentCultureIgnoreCase)); await GenerateIssuesReport(repos, issueHelper.DefaultFormatter, filePath, null, null); //filePath = Path.Combine(outputPath, "DocRepoIssues.csv"); //repos = GitHubConstants.KnownRepos.Where(r => RepoIsOfType(r, GitHubConstants.RepoTypes.Docs | GitHubConstants.RepoTypes.Private)); //await GenerateIssuesReport(repos, issueFormatter, filePath); //var taClient = new TextAnalyticsService("westus2"); //// The "documents" to analyze. These mat need to be batched. Review //// [Text Analytics Overview > Data limits](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview#data-limits). //var input = issues.Select(i => new MultiLanguageInput("en", i.Number.ToString(), i.BodyText)).ToList(); //// Once we're done, this will be the aggregated output from analysis. //var output = new List<SentimentBatchResultItem>(); //// TODO track what we've already analyzed, so that: //// 1. We don't reanalyze the same issue twice. //// 1. We can sanely add to the existing data set. //var docData = new CognitiveServicesDocData //{ // Docs = issues.Select(i => new CognitiveServicesDoc // { // Language = "en", // Id = i.Number.ToString(), // Text = i.Body, // }).ToList(), //}; //// TODO Make the call(s) to the Text Analytics service, aggregate results, generate a report. //Console.WriteLine(); // Other reports that might be useful: // - Issues in other repos that have the "Docs" label applied. // - PRs in the main code repos that are labeled as "DCR". // - Merge activity in the samples repo. // - An orphaned or stale branch report for bot-docs-pr. // Any reports that crawl the file content may be better suited to the other tool: // - Topics that need review, such as their ms.date attribute is getting old, the author // or manager is no longer on the team, or any other metadata maintenance we might need to do. }
public IEnumerable <OffenderReception> GetAllOffenderReceptions() { var offenderRecptionRecords = RepoHelper.GetRecords(_filepath); return(offenderRecptionRecords.Select(constructOffenderReceptionEntity)); }
public void ScriptServerDatabase(object sender, ExecutedRoutedEventArgs e) { var menuItem = sender as MenuItem; if (menuItem == null) { return; } Scope scope = (Scope)menuItem.Tag; var databaseInfo = menuItem.CommandParameter as DatabasesMenuCommandParameters; if (databaseInfo == null) { return; } var treeViewItem = databaseInfo.DatabasesTreeViewItem; try { DataSource sqlDataSource = new DataSource("MicrosoftSqlServer", "Microsoft SQL Server"); sqlDataSource.Providers.Add(DataProvider.SqlDataProvider); DataConnectionDialog dcd = new DataConnectionDialog(); dcd.DataSources.Add(sqlDataSource); dcd.SelectedDataProvider = DataProvider.SqlDataProvider; dcd.SelectedDataSource = sqlDataSource; if (DataConnectionDialog.Show(dcd) == System.Windows.Forms.DialogResult.OK) { string connectionString = dcd.ConnectionString; string fileName; PickTablesDialog ptd = new PickTablesDialog(); int totalCount = 0; using (IRepository repository = RepoHelper.CreateServerRepository(dcd.ConnectionString)) { ptd.Tables = repository.GetAllTableNamesForExclusion(); totalCount = ptd.Tables.Count; } ptd.Owner = Application.Current.MainWindow; bool?res = ptd.ShowDialog(); if (res.HasValue && res.Value == true && (ptd.Tables.Count < totalCount)) { SaveFileDialog fd = new SaveFileDialog(); fd.Title = "Save generated database script as"; fd.Filter = "SQL Server Compact Script (*.sqlce)|*.sqlce|SQL Server Script (*.sql)|*.sql|All Files(*.*)|*.*"; fd.OverwritePrompt = true; fd.ValidateNames = true; bool?result = fd.ShowDialog(); if (result.HasValue && result.Value == true) { fileName = fd.FileName; using (IRepository repository = RepoHelper.CreateServerRepository(connectionString)) { var generator = RepoHelper.CreateGenerator(repository, fd.FileName); generator.ExcludeTables(ptd.Tables); System.Windows.Forms.MessageBox.Show(generator.ScriptDatabaseToFile(scope)); } } } } dcd.Dispose(); } catch (Exception ex) { MessageBox.Show(Helpers.DataConnectionHelper.ShowErrors(ex)); } }
public TaskRepo(ApplicationDbContext context, RepoHelper <AllowanceTask> helper) { _context = context; _helper = helper; _dbSet = context.AllowanceTasks; }