Exemple #1
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            IComponentModel       componentModel = (IComponentModel)(await GetServiceAsync(typeof(SComponentModel)));
            RunningDocTableEvents runningDocTableEventListener = new RunningDocTableEvents();

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            IVsRunningDocumentTable iVsRunningDocumentTable =
                (IVsRunningDocumentTable)GetGlobalService(typeof(SVsRunningDocumentTable));

            iVsRunningDocumentTable.AdviseRunningDocTableEvents(runningDocTableEventListener, out uint mRdtCookie);

            DocumentService documentService =
                new DocumentService(iVsRunningDocumentTable, runningDocTableEventListener, componentModel.GetService <VisualStudioWorkspace>());

            OutputWindowHelper.LogWriteLine("XAMLator initialized.");

            VisualStudioIDE visualStudioIDE = new VisualStudioIDE(documentService);

            XAMLatorMonitor.Init(visualStudioIDE);
            XAMLatorMonitor.Instance.StartMonitoring();

            OutputWindowHelper.LogWriteLine("XAMLator Start monitoring...");
        }
        /// <summary>
        /// Toggles all solution folders open temporarily to workaround searches not working inside
        /// solution folders that have never been expanded.
        /// </summary>
        /// <param name="parentItem">The parent item to inspect.</param>
        private void ToggleSolutionFoldersOpenTemporarily(UIHierarchyItem parentItem)
        {
            if (parentItem == null)
            {
                throw new ArgumentNullException(nameof(parentItem));
            }

            const string solutionFolderGuid = "{66A26720-8FB5-11D2-AA7E-00C04F688DDE}";

            var  project = parentItem.Object as Project;
            bool isCollapsedSolutionFolder = project != null && project.Kind == solutionFolderGuid && !parentItem.UIHierarchyItems.Expanded;

            // Expand the solution folder temporarily.
            if (isCollapsedSolutionFolder)
            {
                OutputWindowHelper.DiagnosticWriteLine($"FindInSolutionExplorerCommand.ToggleSolutionFoldersOpenTemporarily expanding '{parentItem.Name}'");

                parentItem.Select(vsUISelectionType.vsUISelectionTypeSelect);
                Package.IDE.ToolWindows.SolutionExplorer.DoDefaultAction();
            }

            // Run recursively to children as well for nested solution folders.
            foreach (UIHierarchyItem childItem in parentItem.UIHierarchyItems)
            {
                ToggleSolutionFoldersOpenTemporarily(childItem);
            }

            // Collapse the solution folder.
            if (isCollapsedSolutionFolder)
            {
                OutputWindowHelper.DiagnosticWriteLine($"FindInSolutionExplorerCommand.ToggleSolutionFoldersOpenTemporarily collapsing '{parentItem.Name}'");

                parentItem.Select(vsUISelectionType.vsUISelectionTypeSelect);
                Package.IDE.ToolWindows.SolutionExplorer.DoDefaultAction();
            }
        }
        /// <summary>
        /// Finds a code cleanup method appropriate for the specified document, otherwise null.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>The code cleanup method, otherwise null.</returns>
        private Action <Document> FindCodeCleanupMethod(Document document)
        {
            switch (document.Language)
            {
            case "CSharp":
                return(RunCodeCleanupCSharp);

            case "C/C++":
            case "CSS":
            case "JavaScript":
            case "JScript":
            case "JSON":
            case "LESS":
            case "Node.js":
            case "PHP":
            case "PowerShell":
            case "SCSS":
            case "TypeScript":
                return(RunCodeCleanupC);

            case "HTML":
            case "HTMLX":
            case "XAML":
            case "XML":
                return(RunCodeCleanupMarkup);

            case "Basic":
            case "F#":
                return(RunCodeCleanupGeneric);

            default:
                OutputWindowHelper.WarningWriteLine(
                    string.Format("FindCodeCleanupMethod does not recognize document language '{0}'", document.Language));
                return(null);
            }
        }
Exemple #4
0
        /// <summary>
        /// Finds a code cleanup method appropriate for the specified document, otherwise null.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <returns>The code cleanup method, otherwise null.</returns>
        private Action <Document> FindCodeCleanupMethod(Document document)
        {
            switch (document.GetCodeLanguage())
            {
            case CodeLanguage.CSharp:
                return(RunCodeCleanupCSharp);

            case CodeLanguage.VisualBasic:
                return(RunCodeCleanupVB);

            case CodeLanguage.CPlusPlus:
            case CodeLanguage.CSS:
            case CodeLanguage.JavaScript:
            case CodeLanguage.JSON:
            case CodeLanguage.LESS:
            case CodeLanguage.PHP:
            case CodeLanguage.PowerShell:
            case CodeLanguage.R:
            case CodeLanguage.SCSS:
            case CodeLanguage.TypeScript:
                return(RunCodeCleanupC);

            case CodeLanguage.HTML:
            case CodeLanguage.XAML:
            case CodeLanguage.XML:
                return(RunCodeCleanupMarkup);

            case CodeLanguage.FSharp:
            case CodeLanguage.Unknown:
                return(RunCodeCleanupGeneric);

            default:
                OutputWindowHelper.WarningWriteLine($"FindCodeCleanupMethod does not recognize document language '{document.Language}'");
                return(null);
            }
        }
Exemple #5
0
        /// <summary>
        /// An event handler for a line being changed.
        /// </summary>
        /// <param name="startPoint">The starting point of the change.</param>
        /// <param name="endPoint">The ending point of the change.</param>
        /// <param name="hint">A hint as to the type of change that has occurred.</param>
        private void TextEditorEvents_LineChanged(TextPoint startPoint, TextPoint endPoint, int hint)
        {
            if (startPoint == null)
            {
                return;
            }
            var textDocument = startPoint.Parent;

            if (textDocument == null)
            {
                return;
            }

            var document = startPoint.Parent.Parent;

            var onLineChanged = OnLineChanged;

            if (onLineChanged != null && document != null)
            {
                OutputWindowHelper.DiagnosticWriteLine(string.Format("TextEditorEventListener.OnLineChanged raised for '{0}'", document.FullName));

                onLineChanged(document);
            }
        }
        private static Task <string> RunAsync(string eslintPath, string arguments, CancellationToken token)
        {
            return(Task.Run(() =>
            {
                var startInfo = new ProcessStartInfo(eslintPath, arguments)
                {
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true,
                    StandardErrorEncoding = Encoding.UTF8,
                    StandardOutputEncoding = Encoding.UTF8
                };

                var process = new Process {
                    StartInfo = startInfo
                };

                string error = null;
                string output = null;

                process.ErrorDataReceived += ErrorHandler;
                process.OutputDataReceived += OutputHandler;

                void ErrorHandler(object sender, DataReceivedEventArgs e)
                {
                    if (null != e.Data)
                    {
                        error += e.Data;
                    }
                }

                void OutputHandler(object sender, DataReceivedEventArgs e)
                {
                    if (null != e.Data)
                    {
                        output += e.Data;
                    }
                }

                try
                {
                    //token.ThrowIfCancellationRequested();

                    if (false == process.Start())
                    {
                        throw new Exception("exception: unable to start eslint process");
                    }

                    process.BeginErrorReadLine();
                    process.BeginOutputReadLine();

                    process.WaitForExit();

                    if (false == string.IsNullOrEmpty(error))
                    {
                        throw new Exception(error);
                    }
                }
                catch (OperationCanceledException)
                { }
                catch (Exception e)
                {
                    OutputWindowHelper.WriteLine(e.Message);
                }
                finally
                {
                    process.Close();
                }

                return output;
            }, token));
        }
Exemple #7
0
        public async Task LintAsync(ILinterProvider provider, string filePath, CancellationToken token)
        {
            try
            {
                await _mutex.WaitAsync(token).ConfigureAwait(false);

                try
                {
                    token.ThrowIfCancellationRequested();

                    var relativePath = Path.GetDirectoryName(filePath) ??
                                       throw new Exception($"exception: could not get directory for file {filePath}");

                    var executable = EslintHelper.GetExecutableInfo(relativePath);
                    var config     = EslintHelper.GetConfigInfo(relativePath);
                    var ignore     = EslintHelper.GetIgnoreInfo(relativePath);

                    var arguments = GetArguments(filePath, config?.FullName, ignore?.FullName);

                    var output = await RunAsync(config?.DirectoryName, executable.FullName, arguments, token)
                                 .ConfigureAwait(false);

                    token.ThrowIfCancellationRequested();

                    if (string.IsNullOrEmpty(output))
                    {
                        throw new Exception("linter returned empty result~ please read output for detailed information ^");
                    }

                    IEnumerable <EslintResult> results = new List <EslintResult>();

                    try
                    {
                        results = JsonConvert.DeserializeObject <IEnumerable <EslintResult> >(output);
                    }
                    catch (Exception e)
                    {
                        OutputWindowHelper.WriteLine(
                            "exception: error trying to deserialize output:" +
                            Environment.NewLine +
                            output);

                        OutputWindowHelper.WriteLine(e.Message);
                    }

                    var messages = ProcessResults(results);

                    token.ThrowIfCancellationRequested();

                    provider.Accept(filePath, messages);
                }
                catch (OperationCanceledException)
                { }
                catch (Exception e)
                {
                    OutputWindowHelper.WriteLine(e.Message);
                }
                finally
                {
                    _mutex.Release();
                }
            }
            catch (OperationCanceledException)
            { }
            catch (Exception e)
            {
                OutputWindowHelper.WriteLine(e.Message);
            }
        }
Exemple #8
0
        private void ExecuteCommand(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        if (match.Success)
                        {
                            try
                            {
                                TryOpenFile(match.Value);
                            }
                            catch (Exception ex)
                            {
                                OutputWindowHelper.ExceptionWriteLine(string.Format("Can't Open {0},Exception:{1}", match.Value, ex.Message), ex);
                            }
                        }
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                {
                    try
                    {
                        using (var git = new GitAnalysis(GetActiveFilePath()))
                        {
                            if (!git.IsDiscoveredGitRepository)
                            {
                                return;
                            }
                            var selectionLineRange = GetSelectionLineRange();
                            var type     = ToGiteaUrlType(command.CommandID.ID);
                            var GiteaUrl = git.BuildGiteaUrl(type, selectionLineRange);
                            System.Diagnostics.Process.Start(GiteaUrl);         // open browser
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.ExceptionWriteLine(string.Format("ExecuteCommand {0}", command.CommandID.ID, ex.Message), ex);
                    }
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.ToString());
            }
        }
Exemple #9
0
 private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     OutputWindowHelper.ExceptionWriteLine("Diagnostics mode caught and marked as handled the following DispatcherUnhandledException raised in Visual Studio", e.Exception);
     e.Handled = true;
 }
Exemple #10
0
        /// <summary>
        /// OnDragDrop is used to create classes corresponding to the selection dragged
        /// from the Server Explorer
        /// </summary>
        private void OnDragDrop(object sender, DragEventArgs e)
        {
            // Check if the data present is in the DSRef format
            if (e.Data.GetDataPresent(DSRefNavigator.DataSourceReferenceFormat))
            {
                try
                {
                    // Create a navigator for the DSRef Consumer (and dispose it when finished)
                    using (DSRefNavigator navigator = new DSRefNavigator(e.Data.GetData(
                                                                             DSRefNavigator.DataSourceReferenceFormat)
                                                                         as Stream))
                    {
                        _output = new OutputWindowHelper(DTEHelper.GetDTE(this.Store));

                        // Get connection info of the connection of selected tables
                        string        providerType = null;
                        IDbConnection connection   = ServerExplorerHelper.GetConnection(navigator, out providerType);

                        IDbHelper helper;

                        switch (providerType)
                        {
                        case "System.Data.SqlClient.SqlConnection":
                            helper = new SqlHelper(connection);
                            break;

                        case "System.Data.OracleClient.OracleConnection":
                        case "Oracle.DataAccess.Client.OracleConnection":
                            Log("Selecting Oracle Helper for provider " + providerType);
                            helper = new OracleHelper(connection);
                            break;

                        case "MySql.Data.MySqlClient.MySqlConnection":
                            helper = new MySqlHelper(connection);
                            break;

                        default:
                            // TODO: Support other databases with native providers.
                            Log(
                                string.Format(
                                    @"Failed: ActiveWriter does not support model generation through {0}. Supported providers: System.Data.SqlClient.SqlConnection, System.Data.OracleClient.OracleConnection, Oracle.DataAccess.Client.OracleConnection, MySql.Data.MySqlClient.MySqlConnection. You can help us improve this functionality, though. See http://www.castleproject.org/others/contrib/index.html to access ActiveWriter source code under the contrib repository, and check Dsl\ServerExplorerSupport\IDbHelper.cs for the start.",
                                    providerType));
                            return;
                        }

                        // Get the root element where we'll add the classes
                        Model model = Helper.GetModel(this.Store);
                        if (model == null)
                        {
                            Log("Failed: Cannot get the model for the store.");
                            return;
                        }

                        _manager = new DiagramManager(this.Store, model);
                        _manager.OutputWindow = _output;

                        // Create a transaction to add the clases.
                        using (Transaction txAdd =
                                   model.Store.TransactionManager.BeginTransaction("Add classes"))
                        {
                            List <DSRefNode> tableList = new List <DSRefNode>();
                            // Get the tables from the Server Explorer selection
                            // We'll iterate this list twice to use nodes' list to
                            // determine if we have to generate relations for each
                            // table or not.
                            foreach (DSRefNode node in navigator.ChildTableNodes)
                            {
                                tableList.Add(node);
                            }

                            _manager.Tables = tableList;

                            _relations = new List <Relation>();

                            foreach (DSRefNode node in tableList)
                            {
                                // Create the table and add it to the model
                                ModelClass cls = _manager.NewClass(node.Owner, node.Name);
                                PopulateClass(cls, connection, helper);
                                _manager.AssignModel(cls);
                            }

                            // Create relations
                            if (_relations != null && _relations.Count > 0)
                            {
                                HandleRelations();
                            }

                            // Commit the transaction and add tables to the model
                            txAdd.Commit();
                        }

                        // TODO: Auto layout doesn't work well. Will check with future versions of DSL tools.
                        // this.AutoLayoutShapeElements(this.NestedChildShapes);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
                finally
                {
                    _manager   = null;
                    _relations = null;
                    _output    = null;
                }
            }
        }
Exemple #11
0
 /// <summary>
 /// Called to execute the package.
 /// </summary>
 public virtual void OnExecute()
 {
     OutputWindowHelper.DiagnosticWriteLine($"Other Package: {GetType().Name}.OnExecute invoked");
 }
		/// <summary>
		/// OnDragDrop is used to create classes corresponding to the selection dragged
		/// from the Server Explorer
		/// </summary>
		private void OnDragDrop(object sender, DragEventArgs e)
		{
			// Check if the data present is in the DSRef format
			if (e.Data.GetDataPresent(DSRefNavigator.DataSourceReferenceFormat))
			{
				try
				{
					// Create a navigator for the DSRef Consumer (and dispose it when finished)
					using(DSRefNavigator navigator = new DSRefNavigator(e.Data.GetData(
					                                                    	DSRefNavigator.DataSourceReferenceFormat)
					                                                    as Stream))
					{
						_output = new OutputWindowHelper(DTEHelper.GetDTE(Store));

						// Get connection info of the connection of selected tables
						string providerType = null;
						IDbConnection connection = ServerExplorerHelper.GetConnection(navigator, out providerType);

						IDbHelper helper;

						switch(providerType)
						{
							case "System.Data.SqlClient.SqlConnection":
								helper = new SqlHelper(connection);
								break;
                            case "System.Data.OracleClient.OracleConnection":
                            case "Oracle.DataAccess.Client.OracleConnection":
                                Log("Selecting Oracle Helper for provider " + providerType);
                                helper = new OracleHelper(connection);
                                break;
                            case "MySql.Data.MySqlClient.MySqlConnection":
								helper = new MySqlHelper(connection);
								break;
							default:
								// TODO: Support other databases with native providers.
								Log(
									string.Format(
                                        @"Failed: ActiveWriter does not support model generation through {0}. Supported providers: System.Data.SqlClient.SqlConnection, System.Data.OracleClient.OracleConnection, Oracle.DataAccess.Client.OracleConnection, MySql.Data.MySqlClient.MySqlConnection. You can help us improve this functionality, though. See http://www.castleproject.org/others/contrib/index.html to access ActiveWriter source code under the contrib repository, and check Dsl\ServerExplorerSupport\IDbHelper.cs for the start.",
										providerType));
								return;
						}

						// Get the root element where we'll add the classes
						Model model = Helper.GetModel(Store);
						if (model == null)
						{
							Log("Failed: Cannot get the model for the store.");
							return;
						}

						_manager = new DiagramManager(Store, model);
						_manager.OutputWindow = _output;

						// Create a transaction to add the clases.
						using(Transaction txAdd =
							model.Store.TransactionManager.BeginTransaction("Add classes"))
						{
							List<DSRefNode> tableList = new List<DSRefNode>();
							// Get the tables from the Server Explorer selection
							// We'll iterate this list twice to use nodes' list to
							// determine if we have to generate relations for each
							// table or not.
							foreach(DSRefNode node in navigator.ChildTableNodes)
							{
								tableList.Add(node);
							}

							_manager.Tables = tableList;

							_relations = new List<Relation>();

							foreach(DSRefNode node in tableList)
							{
								// Create the table and add it to the model
								ModelClass cls = _manager.NewClass(node.Owner, node.Name);
								PopulateClass(cls, connection, helper);
								_manager.AssignModel(cls);
							}

							// Create relations
							if (_relations != null && _relations.Count > 0)
							{
								HandleRelations();
							}

							// Commit the transaction and add tables to the model
							txAdd.Commit();
						}

						// TODO: Auto layout doesn't work well. Will check with future versions of DSL tools.
						// this.AutoLayoutShapeElements(this.NestedChildShapes);
					}
				}
				catch(Exception ex)
				{
					Debug.WriteLine(ex.Message);
				}
				finally
				{
					_manager = null;
					_relations = null;
					_output = null;
				}
			}
		}
Exemple #13
0
 public void ShowError(string error, Exception ex = null)
 {
     OutputWindowHelper.ExceptionWriteLine(error, ex);
 }
Exemple #14
0
 public void MonitorEditorChanges()
 {
     OutputWindowHelper.LogWriteLine("Monitor editor changes.");
 }
Exemple #15
0
        private void ExecuteCommand(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenCreateSnippet:
                    var selection = DTE.ActiveDocument.Selection as TextSelection;
                    if (selection != null)
                    {
                        var dialog = _viewFactory.GetView <Dialog>(ViewTypes.CreateSnippet);
                        var cs     = (CreateSnippet)dialog;
                        var csm    = cs.DataContext as CreateSnippetViewModel;
                        csm.Code     = selection.Text;
                        csm.FileName = new System.IO.FileInfo(DTE.ActiveDocument.FullName).Name;
                        _shell.ShowDialog(Strings.OpenOnGitLabPackage_CreateSnippet, dialog);
                    }
                    else
                    {
                        OutputWindowHelper.DiagnosticWriteLine(GitLab.VisualStudio.Shared.Strings.PleaseCodes);
                    }
                    break;

                case PackageIds.OpenFromUrl:

                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        if (match.Success)
                        {
                            try
                            {
                                TryOpenFile(match.Value);
                            }
                            catch (Exception ex)
                            {
                                OutputWindowHelper.ExceptionWriteLine(string.Format(GitLab.VisualStudio.Shared.Strings.Canotopenurl, match.Value, ex.Message), ex);
                            }
                        }
                    }
                    break;

                default:
                    using (var git = new GitAnalysis(GetActiveFilePath()))
                    {
                        if (!git.IsDiscoveredGitRepository)
                        {
                            return;
                        }
                        var selectionLineRange = GetSelectionLineRange();
                        var type      = ToGitLabUrlType(command.CommandID.ID);
                        var GitLabUrl = git.BuildGitLabUrl(type, selectionLineRange);
                        System.Diagnostics.Process.Start(GitLabUrl);     // open browser
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                OutputWindowHelper.ExceptionWriteLine($"Command:{command.Text},Message:{ex.Message}", ex);
            }
        }
Exemple #16
0
        public async Task LintAsync(ILinterProvider provider, string filePath, CancellationToken token)
        {
            try
            {
                await _mutex.WaitAsync(token).ConfigureAwait(false);

                try
                {
                    token.ThrowIfCancellationRequested();

                    var directoryPath = Path.GetDirectoryName(filePath) ??
                                        throw new Exception($"exception: could not get directory for file {filePath}");

                    var eslintPath = EslintHelper.GetEslintPath(directoryPath);
                    var arguments  = string.Join(" ", QuoteArgument(filePath), EslintHelper.GetArguments(directoryPath));

                    var output = await RunAsync(eslintPath, arguments, token)
                                 .ConfigureAwait(false);

                    token.ThrowIfCancellationRequested();

                    if (string.IsNullOrEmpty(output))
                    {
                        throw new Exception("exception: linter returned empty result");
                    }

                    IEnumerable <EslintResult> results = new List <EslintResult>();

                    try
                    {
                        results = JsonConvert.DeserializeObject <IEnumerable <EslintResult> >(output);
                    }
                    catch (Exception e)
                    {
                        OutputWindowHelper.WriteLine(
                            "exception: error trying to deserialize output:" +
                            Environment.NewLine +
                            output);

                        OutputWindowHelper.WriteLine(e.Message);
                    }

                    var messages = ProcessResults(results);

                    token.ThrowIfCancellationRequested();

                    provider.Accept(filePath, messages);
                }
                catch (OperationCanceledException)
                { }
                catch (Exception e)
                {
                    OutputWindowHelper.WriteLine(e.Message);
                }
                finally
                {
                    _mutex.Release();
                }
            }
            catch (OperationCanceledException)
            { }
            catch (Exception e)
            {
                OutputWindowHelper.WriteLine(e.Message);
            }
        }
        public CodeGenerationContext(Model model, string nameSpace, string processID, string modelFileFullName, ITextTemplatingEngineHost textTemplatingHost)
        {
            CompileUnit = new CodeCompileUnit();

            Model = model;
            if (string.IsNullOrEmpty(Model.Namespace))
                Namespace = nameSpace;
            else
                Namespace = Model.Namespace;

            DTE = DTEHelper.GetDTE(processID);

            TextTemplatingHost = textTemplatingHost;

            ModelFileName = modelFileFullName;

            ProjectItem = DTE.Solution.FindProjectItem(ModelFileName);
            AssemblyName = DTEHelper.GetAssemblyName(ProjectItem.ContainingProject);

            Language = DTEHelper.GetProjectLanguage(ProjectItem.ContainingProject);
            switch (Language)
            {
                case CodeLanguage.CSharp:
                    Provider = new CSharpCodeProvider();
                    break;
                case CodeLanguage.VB:
                    Provider = new VBCodeProvider();

                    // use VB default namespace if it was set
                    VSProject project = (VSProject)ProjectItem.ContainingProject.Object;
                    Property DefaultNamespaceProperty = project.Project.Properties.Item("DefaultNamespace");

                    DefaultNamespace = (string)DefaultNamespaceProperty.Value;

                    break;
                default:
                    throw new ArgumentException(
                        "Unsupported project type. ActiveWriter currently supports C# and Visual Basic.NET projects.");
            }

            Output = new OutputWindowHelper(DTE);
        }
 /// <summary>
 /// 数据执行操作
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void btn_Build_Click(object sender, EventArgs e)
 {
     try
     {
         List <string>   csFileList = new List <string>();
         var             template   = string.Empty;
         List <TreeNode> tNodeList  = new List <TreeNode>();
         if (tabControl1.SelectedTab != null && tabControl1.SelectedTab.Name == "tPage_SQL")
         {
             var sql  = txtSqls.Text.Trim();
             var link = DBInfo.DBInfoList.Where(w => w.DBName == tv_DBList.SelectedNode.Name).FirstOrDefault();
             if (link == null)
             {
                 OutPutMsg($"鼠标焦点不在库节点上,请重置焦点");
             }
             DataColumnCollection colums = null;
             if (link.Type == DBEnum.SqlServer)
             {
                 colums = SqlHelper.ExecuteDataTable(link?.DBLink, sql).Columns;
             }
             else
             {
                 colums = MySqlHelper.ExecuteDataTable(link?.DBLink, sql).Columns;
             }
             List <DBStructure> infos = new List <DBStructure>();
             template = File.ReadAllText(Path.Combine(BEContent.SelectedProject.ABEPath, "Templates", "ComboEntity.txt"));
             for (int i = 0; i < colums.Count; i++)
             {
                 DBStructure stru = new DBStructure();
                 stru.ColName = colums[i].ColumnName;
                 stru.ColType = colums[i].DataType.MapCsharpType();
                 infos.Add(stru);
             }
             var csFile = GetCSFile(tv_DBList.SelectedNode.Name, "NameReplace", template, infos, sql);
             csFileList.Add(csFile);
         }
         else
         {
             template = File.ReadAllText(Path.Combine(BEContent.SelectedProject.ABEPath, "Templates", "Entity.txt"));
             foreach (TreeNode tnode in this.tv_DBList.Nodes)
             {
                 foreach (TreeNode node in tnode.Nodes)
                 {
                     if (node.Checked)
                     {
                         tNodeList.Add(node);
                         var csFile = GetCSFile(node.Parent.Name, node.Name, template);
                         csFileList.Add(csFile);
                     }
                 }
             }
         }
         BEContent.SelectedProject.ProjectDte.AddFilesToProject(csFileList);
         tNodeList.ForEach(f => f.Checked = false);
         txtSqls.Clear();
         OutPutMsg($"数据执行操作成功,共生成{csFileList.Count}文件");
     }
     catch (Exception ex)
     {
         OutputWindowHelper.OutPutMessage($"数据执行操作出现异常 \r\n 信息:{ex.Message} \r\n 堆栈:{ex.StackTrace}");
         OutPutMsg($"数据执行操作出现异常 \r\n 信息:{ex.Message}");
     }
 }
 /// <summary>
 /// Called when a DispatcherUnhandledException is raised by Visual Studio.
 /// </summary>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="DispatcherUnhandledExceptionEventArgs" /> instance containing the event data.</param>
 private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
 {
     OutputWindowHelper.WriteLine("EditorConfig's diagnostics mode caught the following unhandled exception in Visual Studio--" + Environment.NewLine + e.Exception);
     e.Handled = true;
 }
Exemple #20
0
        private void MenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    try
                    {
                        command.Enabled = false;
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        if (match.Success)
                        {
                            Uri uri = new Uri(match.Value);
                            if (uri.Host.ToLower() == "gitee.com")
                            {
                                command.Enabled = true;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                case PackageIds.OpenWebIDE:
                {
                    try
                    {
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        var git = GitAnalysis.GetBy(GetActiveFilePath());
                        if (!git.IsDiscoveredGitRepository)
                        {
                            command.Enabled = false;
                            return;
                        }
                        var type       = ToGiteaUrlType(command.CommandID.ID);
                        var targetPath = git.GetGiteaTargetPath(type);
                        if (type == GiteeUrlType.CurrentBranch && targetPath == "master")
                        {
                            command.Visible = false;
                        }
                        else
                        {
                            command.Text    = git.GetGiteaTargetDescription(type);
                            command.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                }
                break;

                case PackageIds.OpenCreateSnippet:
                    var selectionLineRange = GetSelectionLineRange();
                    command.Enabled = selectionLineRange != null && selectionLineRange.Item1 < selectionLineRange.Item2;
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                var exstr = ex.ToString();
                Debug.Write(exstr);
                command.Text    = "error:" + ex.GetType().Name;
                command.Enabled = false;
                OutputWindowHelper.WarningWriteLine(ex.Message);
            }
        }
Exemple #21
0
 /// <summary>
 /// Called to execute the command.
 /// </summary>
 protected virtual void OnExecute()
 {
     OutputWindowHelper.DiagnosticWriteLine($"{GetType().Name}.OnExecute invoked");
 }
Exemple #22
0
        private void ExecuteCommand(object sender, EventArgs e)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    if (Clipboard.ContainsText(TextDataFormat.Text))
                    {
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        if (match.Success)
                        {
                            try
                            {
                                TryOpenFile(match.Value);
                            }
                            catch (Exception ex)
                            {
                                OutputWindowHelper.ExceptionWriteLine(string.Format("Can't Open {0},Exception:{1}", match.Value, ex.Message), ex);
                            }
                        }
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                case PackageIds.OpenWebIDE:
                {
                    try
                    {
                        using (var git = new GitAnalysis(GetActiveFilePath()))
                        {
                            if (!git.IsDiscoveredGitRepository)
                            {
                                return;
                            }
                            var selectionLineRange = GetSelectionLineRange();
                            var type     = ToGiteaUrlType(command.CommandID.ID);
                            var GiteaUrl = git.BuildGiteaUrl(type, selectionLineRange);
                            System.Diagnostics.Process.Start(GiteaUrl);         // open browser
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.ExceptionWriteLine(string.Format("ExecuteCommand {0}", command.CommandID.ID, ex.Message), ex);
                    }
                }
                break;

                case PackageIds.OpenCreateSnippet:
                    var selection = DTE.ActiveDocument.Selection as TextSelection;
                    if (selection != null)
                    {
                        var dialog = _viewFactory.GetView <Dialog>(ViewTypes.CreateSnippet);
                        var cs     = (CreateSnippet)dialog;
                        var csm    = cs.DataContext as CreateSnippetViewModel;
                        csm.Code     = selection.Text;
                        csm.FileName = new FileInfo(DTE.ActiveDocument.FullName).Name;
                        csm.Desc     = csm.FileName;
                        _shell.ShowDialog(Strings.CreateSnippet, dialog);
                    }
                    else
                    {
                        OutputWindowHelper.DiagnosticWriteLine(Strings.PleaseSelectCode);
                    }
                    break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                Debug.Write(ex.ToString());
            }
        }
Exemple #23
0
        private void MenuItem_BeforeQueryStatus(object sender, EventArgs e)
        {
            var command = (OleMenuCommand)sender;

            try
            {
                switch ((uint)command.CommandID.ID)
                {
                case PackageIds.OpenFromUrl:
                    try
                    {
                        var match = Regex.Match(Clipboard.GetText(TextDataFormat.Text), "[a-zA-z]+://[^\\s]*");
                        command.Enabled = match.Success;
                        if (command.Enabled)
                        {
                            Uri uri = new Uri(match.Value);
                            command.Text = string.Format(Strings.OpenFrom0, uri.Host);
                        }
                        else
                        {
                            command.Text = Strings.OpenFromURL;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                    break;

                case PackageIds.OpenBlame:
                case PackageIds.OpenBranch:
                case PackageIds.OpenCommits:
                case PackageIds.OpenMaster:
                case PackageIds.OpenRevision:
                case PackageIds.OpenRevisionFull:
                {
                    try
                    {
                        var git = GitAnalysis.GetBy(GetActiveFilePath());
                        if (!git.IsDiscoveredGitRepository)
                        {
                            command.Enabled = false;
                            return;
                        }
                        var type       = ToGiteaUrlType(command.CommandID.ID);
                        var targetPath = git.GetGiteaTargetPath(type);
                        if (type == GiteaUrlType.CurrentBranch && targetPath == "master")
                        {
                            command.Visible = false;
                        }
                        else
                        {
                            command.Text    = git.GetGiteaTargetDescription(type);
                            command.Enabled = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        OutputWindowHelper.WarningWriteLine($"QueryStatus:{command.CommandID.ID},{ex.Message}");
                    }
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception ex)
            {
                var exstr = ex.ToString();
                Debug.Write(exstr);
                command.Text    = "error:" + ex.GetType().Name;
                command.Enabled = false;
                OutputWindowHelper.WarningWriteLine(ex.Message);
            }
        }
Exemple #24
0
 /// <summary>
 /// Called to execute the command.
 /// </summary>
 protected virtual void OnExecute()
 {
     OutputWindowHelper.DiagnosticWriteLine(
         string.Format("{0}.OnExecute invoked", GetType().Name));
 }
        public CodeGenerationHelper(Hashtable propertyBag)
        {
            _propertyBag = propertyBag;
            _model = (Model)propertyBag["Generic.Model"];
            if (string.IsNullOrEmpty(_model.Namespace))
                _namespace = propertyBag["Generic.Namespace"].ToString();
            else
                _namespace = _model.Namespace;


            _dte = DTEHelper.GetDTE(_propertyBag["Generic.ProcessID"].ToString());
            _propertyBag.Add("Generic.DTE", _dte);

            _modelFileName = (string)_propertyBag["Generic.ModelFileFullName"];
            _modelFilePath = Path.GetDirectoryName(_modelFileName);
            _projectItem = _dte.Solution.FindProjectItem(_modelFileName);

            _language = DTEHelper.GetProjectLanguage(_projectItem.ContainingProject);
            switch (_language)
            {
                case CodeLanguage.CSharp:
                    _provider = new CSharpCodeProvider();
                    _propertyBag.Add("Generic.Language", CodeLanguage.CSharp);
                    break;
                case CodeLanguage.VB:
                    _provider = new VBCodeProvider();
                    _propertyBag.Add("Generic.Language", CodeLanguage.VB);

                    // use VB default namespace if it was set
                    VSProject project = (VSProject)_projectItem.ContainingProject.Object;
                    Property DefaultNamespaceProperty = project.Project.Properties.Item("DefaultNamespace");

                    _defaultNamespace = (string)DefaultNamespaceProperty.Value;

                    break;
                default:
                    throw new ArgumentException(
                        "Unsupported project type. ActiveWriter currently supports C# and Visual Basic.NET projects.");
            }

            _output = new OutputWindowHelper(_dte);
        }
Exemple #26
0
        protected override void Initialize()
        {
            base.Initialize();

            var context = ((ITeamFoundationContextManager)GetService(typeof(ITeamFoundationContextManager))).CurrentContext;

            _model       = new TimelineModel(new TimelineService(context, (message) => OutputWindowHelper.OutputString(this, message)));
            base.Content = new TimelineWrapper(_model,
                                               (message) => OutputWindowHelper.OutputString(this, message),
                                               (id) => {
                var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE));
                SourceControlHelper.ShowChangeset(dte, id);
            });
        }